Source code for dit.algorithms.distribution_optimizers

"""
A variety of distribution optimizers using scipy.optimize's methods.
"""

from collections import namedtuple
from itertools import combinations

import numpy as np
from debtcollector import removals
from scipy.optimize import linprog

from ..distconst import product_distribution
from ..distribution import Distribution
from ..multivariate import coinformation as I
from ..utils import flatten
from .ipf import ipf_dist
from .maxentropy import marginal_constraints_generic
from .optimization import BaseConvexOptimizer, BaseNonConvexOptimizer, BaseOptimizer
from .optutil import _as_full_rank, prepare_dist
from .pid_broja import extra_constraints as broja_extra_constraints
from .pid_broja import prepare_dist as broja_prepare_dist

__all__ = (
    "maxent_dist",
    "marginal_maxent_dists",
)


def infer_free_values(A, b):
    """
    Infer the indices of fixed values in an optimization vector.

    Parameters
    ----------
    A : np.ndarray
        The constraint matrix.
    b : np.ndarray
        The constraint values.

    Returns
    -------
    fixed : list
        The list of fixed indices.
    """
    # find locations of b == 0, since pmf values are non-negative, this means they are identically zero.
    free = [i for i, n in enumerate(A[b == 0, :].sum(axis=0)) if n == 0]
    while True:
        # now find rows of A with only a single free value in them. those values must also be fixed.
        fixed = A[:, free].sum(axis=1) == 1
        new_fixed = [[i for i, n in enumerate(row) if n and (i in free)][0] for i, row in enumerate(A) if fixed[i]]
        free = sorted(set(free) - set(new_fixed))
        if not new_fixed:
            break
    return free


class BaseDistOptimizer(BaseOptimizer):
    """
    Calculate an optimized distribution consistent with the given marginal constraints.
    """

    construct_initial = BaseOptimizer.construct_uniform_initial

    def __init__(self, dist, marginals):
        """
        Initialize the optimizer.

        Parameters
        ----------
        dist : Distribution
            The distribution from which the corresponding optimal distribution
            will be calculated.
        marginals : list, None
            The list of sets of variables whose marginals will be constrained to
            match the given distribution.
        """
        super().__init__(dist, dist.rvs, crvs=[])

        # TODO: actually make this class support crvs?
        self._all_vars = self._rvs

        self.dist = prepare_dist(dist)
        self._vpmf = self.dist.pmf.copy()
        self._A, self._b = marginal_constraints_generic(self.dist, marginals)
        self._shape = [len(alpha) for alpha in self.dist.alphabet]
        self._free = infer_free_values(self._A, self._b)
        self.constraints = [
            {
                "type": "eq",
                "fun": self.constraint_match_marginals,
                "jac": self.constraint_match_marginals_jac,
            },
        ]
        self._optvec_size = len(self._free)
        self._default_hops = 50

        self._additional_options = {
            "options": {
                "maxiter": 1000,
                "ftol": 1e-7,
                "eps": 1.4901161193847656e-08,
            }
        }

    def optimize(self, x0=None, niter=None, maxiter=None, polish=1e-8, callback=False, rng=None):
        """
        Optimize this distribution w.r.t. the objective.

        Parameters
        ----------
        x0 : np.ndarray
            An initial optimization vector.
        niter : int
            The number of optimization iterations to perform.
        maxiter : int
            The number of steps for an optimization subroutine to perform.
        polish : float
            The threshold for valid optimization elements. If 0, no polishing is
            performed.
        callback : bool
            Whether to use a callback to track the performance of the optimization.
            Generally, this should be False as it adds some significant time to the
            optimization.
        rng : np.random.Generator, None
            An optional random number generator for RNG isolation. When None
            (default), the global ``np.random`` state is used.

        Returns
        -------
        result : OptimizeResult, None
            Return the optimization result, or None if no optimization was needed.
        """
        if len(self._free) == 0:
            self._optima = self._vpmf
        else:
            if x0 is not None and len(x0) == len(self._vpmf):
                # if a full pmf vector was passed in, restrict it to the free
                # indices:
                x0 = x0[self._free]
            result = super().optimize(x0=x0, niter=niter, maxiter=maxiter, polish=polish, callback=callback, rng=rng)
            return result

    def construct_vector(self, x):
        """
        Expand the `x` argument to the full pmf.

        Parameters
        ----------
        x : np.ndarray
            An optimization vector.

        Returns
        -------
        vpmf : np.array
            The full pmf as a vector.
        """
        if self._free:
            self._vpmf[self._free] = x
        return self._vpmf

    def construct_joint(self, x):
        """
        Construct the joint distribution.

        Parameters
        ----------
        x : np.ndarray
            An optimization vector.

        Returns
        -------
        pmf : np.ndarray
            The joint distribution.
        """
        vec = self.construct_vector(x)
        pmf = vec.reshape(self._shape)
        return pmf

    def _marginal_system(self):
        """
        The marginal constraints on the free entries, as a linear system of full row rank.

        The marginals overlap (they all sum to the same total), so the system on the
        whole pmf is rank deficient, which SLSQP cannot handle. It is reduced again
        whenever a subclass changes the free entries.

        Returns
        -------
        A : np.ndarray
            The constraint matrix, with one column per free entry.
        b : np.ndarray
            The right-hand side.
        """
        key = tuple(self._free)
        if getattr(self, "_marginal_key", None) != key:
            fixed = np.setdiff1d(np.arange(len(self._vpmf)), self._free)
            rhs = self._b - self._A[:, fixed] @ self._vpmf[fixed]
            A, b, _ = _as_full_rank(self._A[:, list(self._free)], rhs)
            self._marginal_key, self._marginal_A, self._marginal_b = key, A, b
        return self._marginal_A, self._marginal_b

    def constraint_match_marginals(self, x):
        """
        Ensure that the joint distribution represented by the optimization
        vector matches that of the distribution.

        The constraints are linear, but SLSQP stops once their violation is below its
        tolerance, so its optima can miss them by about 1e-7. A single squared deviation,
        as used before, counts as satisfied once it is below SLSQP's tolerance of 1e-7,
        which leaves deviations of about 3e-4.

        Parameters
        ----------
        x : np.ndarray
            An optimization vector.

        Returns
        -------
        d : np.ndarray
            The residuals of the marginal constraints, reduced to full rank.
        """
        A, b = self._marginal_system()
        return A @ np.asarray(x, dtype=float) - b

    def constraint_match_marginals_jac(self, x):
        """
        Jacobian of :meth:`constraint_match_marginals` w.r.t. the free
        optimization variables: the constant matrix of the reduced system.

        Parameters
        ----------
        x : np.ndarray
            An optimization vector.

        Returns
        -------
        jac : np.ndarray
            The jacobian, with one row per constraint and one column per free entry.
        """
        return self._marginal_system()[0]

    def _jacobian(self, x):
        """
        Exact gradient of the objective w.r.t. the free optimization variables.

        The parametrization is linear (the free entries of the pmf *are* ``x``),
        so the objective gradient is just the measure's pmf-gradient (supplied
        by :meth:`_objective_gradient`) restricted to the free indices. Wired
        into SciPy only when the subclass defines ``_objective_gradient``;
        otherwise the optimizer falls back to finite differences.

        Parameters
        ----------
        x : np.ndarray
            An optimization vector.

        Returns
        -------
        jac : np.ndarray
            The gradient, of length ``len(x)``.
        """
        grad = self._objective_gradient()(self.construct_joint(x))
        return grad.ravel()[self._free]

    def construct_dist(self, x=None, cutoff=1e-6, sparse=True):
        """
        Construct the optimal distribution.

        Parameters
        ----------
        x : np.ndarray
            An optimization vector.
        cutoff : float
            A probability cutoff. Any joint event with probability below
            this will be set to zero.
        sparse : bool
            Whether to make the distribution sparse or not. Defaults to True.

        Returns
        -------
        d : distribution
            The optimized distribution.
        """
        if x is None:
            x = self._optima.copy()

        pmf = self.construct_vector(x)

        pmf[pmf < cutoff] = 0
        pmf /= pmf.sum()

        new_dist = self.dist.copy()
        new_dist.pmf = pmf.ravel()
        if sparse:
            new_dist.make_sparse()

        names = self.dist.get_rv_names()
        if names is not None:
            new_dist.set_rv_names(names)

        return new_dist


class MaxEntOptimizer(BaseDistOptimizer, BaseConvexOptimizer):
    """
    Compute maximum entropy distributions.
    """

    def __init__(self, dist, marginals):
        super().__init__(dist, marginals)
        self._objective_bound = -np.log2(np.prod(self._shape))

    def _objective_gradient(self):
        """Gradient of the ``-H`` objective w.r.t. the pmf."""
        entropy_grad = self._entropy_grad(self._rvs)
        return lambda pmf: -entropy_grad(pmf)

    def _objective(self):
        """
        Compute the negative entropy.

        Returns
        -------
        objective : func
            The objective function.
        """
        entropy = self._entropy(self._rvs)

        def objective(self, x):
            """
            Compute -H[rvs]

            Parameters
            ----------
            x : np.ndarray
                An optimization vector.

            Returns
            -------
            obj : float
                The value of the objective.
            """
            pmf = self.construct_joint(x)
            return -entropy(pmf)

        return objective


class MinEntOptimizer(BaseDistOptimizer, BaseNonConvexOptimizer):
    """
    Compute minimum entropy distributions.

    Entropy is concave, so its minimum over the polytope of distributions
    matching the marginals is attained at a vertex. The search is seeded with
    vertices from linear programs with random costs and, for a coupling of disjoint
    groups of variables, with the greedy coupling of :cite:`kocaoglu2017entropic`,
    whose entropy is within one bit of the minimum :cite:`cicalese2019minimum`.
    """

    _n_vertex_seeds = 50

    def __init__(self, dist, marginals):
        super().__init__(dist, marginals)
        self._objective_bound = 0.0
        self._marginals = [sorted(set(flatten(m))) for m in marginals]

    def _greedy_coupling(self):
        """
        Greedy minimum-entropy coupling, when the marginals are disjoint groups
        of variables that together cover every variable.

        Returns
        -------
        pmf : np.ndarray, None
            The coupling as a full pmf vector, or None if not applicable.
        """
        groups = self._marginals
        n = len(self._shape)
        flat = [v for g in groups for v in g]
        if len(groups) < 2 or len(flat) != n or set(flat) != set(range(n)):
            return None
        pmf = self.dist.pmf.reshape(self._shape)
        margs = [pmf.sum(axis=tuple(v for v in range(n) if v not in g)).ravel() for g in groups]
        joint = np.zeros([len(m) for m in margs])
        while min(m.sum() for m in margs) > 1e-12:
            idx = tuple(int(m.argmax()) for m in margs)
            mass = min(m[i] for m, i in zip(margs, idx, strict=True))
            joint[idx] += mass
            for m, i in zip(margs, idx, strict=True):
                m[i] -= mass
        joint = joint.reshape([self._shape[v] for v in flat]).transpose(np.argsort(flat))
        return joint.ravel()

    def _seed_pmfs(self, rng=None):
        """
        Vertices of the marginal polytope, plus the greedy coupling if applicable.

        Returns
        -------
        seeds : list of np.ndarray
            Full pmf vectors.
        """
        rng = np.random.default_rng(rng)
        seeds = []
        greedy = self._greedy_coupling()
        if greedy is not None:
            seeds.append(greedy)
        for _ in range(self._n_vertex_seeds):
            res = linprog(rng.random(len(self._vpmf)), A_eq=self._A, b_eq=self._b, bounds=(0, None), method="highs-ds")
            if res.x is not None:
                seeds.append(np.clip(res.x, 0, None))
        return seeds

    def optimize(self, *args, **kwargs):
        """
        Optimize, then keep the best of the result and the vertex seeds, each projected
        exactly onto the marginal constraints.

        Parameters
        ----------
        args, kwargs
            Passed to :meth:`BaseDistOptimizer.optimize`.

        Returns
        -------
        result : OptimizeResult, None
            The result of the local search.
        """
        result = super().optimize(*args, **kwargs)
        if self._free:
            candidates = [self._optima] + [seed[self._free] for seed in self._seed_pmfs(kwargs.get("rng"))]
            candidates = [self._project_onto_marginals(x) for x in candidates]
            self._optima = min(candidates, key=self.objective).copy()
        return result

    def _project_onto_marginals(self, x):
        """
        Satisfy the marginal constraints exactly, changing only the positive entries.

        SLSQP stops once the constraint violations are below its tolerance, so a local
        optimum can miss the marginals by about 1e-7. A vector short of mass has a lower
        computed entropy, which is enough to beat the exact vertex it approximates. The
        least-squares correction on the support keeps zeros at zero, and is exact when
        the support contains that of a vertex, as it does near one. A vector with a
        non-finite entry is returned unchanged, since no correction could repair it.

        Parameters
        ----------
        x : np.ndarray
            An optimization vector.

        Returns
        -------
        x : np.ndarray
            The corrected optimization vector.
        """
        A, b = self._marginal_system()
        x = np.clip(np.asarray(x, dtype=float), 0, None)
        if not np.isfinite(x).all():
            return x
        while True:  # each retry zeroes an entry, and zeros stay zero
            support = x > 0
            x[support] += np.linalg.lstsq(A[:, support], b - A @ x, rcond=None)[0]
            if (x >= 0).all():
                return x
            x = np.clip(x, 0, None)

    def _objective_gradient(self):
        """Gradient of the ``+H`` objective w.r.t. the pmf."""
        return self._entropy_grad(self._rvs)

    def _objective(self):
        """
        Compute the entropy.

        Returns
        -------
        objective : func
            The objective function.
        """
        entropy = self._entropy(self._rvs)

        def objective(self, x):
            """
            Compute H[rvs]

            Parameters
            ----------
            x : np.ndarray
                An optimization vector.

            Returns
            -------
            obj : float
                The value of the objective.
            """
            pmf = self.construct_joint(x)
            return entropy(pmf)

        return objective


class MaxCoInfoOptimizer(BaseDistOptimizer, BaseNonConvexOptimizer):
    """
    Compute maximum co-information distributions.
    """

    def _objective_gradient(self):
        """Gradient of the ``-I`` objective w.r.t. the pmf."""
        coinformation_grad = self._coinformation_grad(self._rvs)
        return lambda pmf: -coinformation_grad(pmf)

    def _objective(self):
        """
        Compute the negative co-information.

        Returns
        -------
        objective : func
            The objective function.
        """
        coinformation = self._coinformation(self._rvs)

        def objective(self, x):
            """
            Compute :math:`-I[rvs]`.

            Parameters
            ----------
            x : np.ndarray
                An optimization vector.

            Returns
            -------
            obj : float
                The value of the objective.
            """
            pmf = self.construct_joint(x)
            return -coinformation(pmf)

        return objective


class MinCoInfoOptimizer(BaseDistOptimizer, BaseNonConvexOptimizer):
    """
    Compute minimum co-information distributions.
    """

    def _objective_gradient(self):
        """Gradient of the ``+I`` objective w.r.t. the pmf."""
        return self._coinformation_grad(self._rvs)

    def _objective(self):
        """
        Compute the co-information.

        Returns
        -------
        objective : func
            The objective function.
        """
        coinformation = self._coinformation(self._rvs)

        def objective(self, x):
            """
            Compute :math:`I[rvs]`.

            Parameters
            ----------
            x : np.ndarray
                An optimization vector.

            Returns
            -------
            obj : float
                The value of the objective.
            """
            pmf = self.construct_joint(x)
            return coinformation(pmf)

        return objective


class MaxDualTotalCorrelationOptimizer(BaseDistOptimizer, BaseNonConvexOptimizer):
    """
    Compute maximum dual total correlation distributions.
    """

    def _objective_gradient(self):
        """Gradient of the ``-B`` objective w.r.t. the pmf."""
        dtc_grad = self._dual_total_correlation_grad(self._rvs)
        return lambda pmf: -dtc_grad(pmf)

    def _objective(self):
        """
        Compute the negative dual total correlation.

        Returns
        -------
        objective : func
            The objective function.
        """
        dual_total_correlation = self._dual_total_correlation(self._rvs)

        def objective(self, x):
            """
            Compute :math:`-B[rvs]`

            Parameters
            ----------
            x : np.ndarray
                An optimization vector.

            Returns
            -------
            obj : float
                The value of the objective.
            """
            pmf = self.construct_joint(x)
            return -dual_total_correlation(pmf)

        return objective


class MinDualTotalCorrelationOptimizer(BaseDistOptimizer, BaseNonConvexOptimizer):
    """
    Compute minimum dual total correlation distributions.
    """

    def _objective_gradient(self):
        """Gradient of the ``+B`` objective w.r.t. the pmf."""
        return self._dual_total_correlation_grad(self._rvs)

    def _objective(self):
        """
        Compute the dual total correlation.

        Returns
        -------
        objective : func
            The objective function.
        """
        dual_total_correlation = self._dual_total_correlation(self._rvs)

        def objective(self, x):
            """
            Compute B[rvs]

            Parameters
            ----------
            x : np.ndarray
                An optimization vector.

            Returns
            -------
            obj : float
                The value of the objective.
            """
            pmf = self.construct_joint(x)
            return dual_total_correlation(pmf)

        return objective


class MinResidualEntropyOptimizer(BaseDistOptimizer, BaseNonConvexOptimizer):
    """
    Compute minimum residual entropy distributions.
    """

    def _objective_gradient(self):
        """Gradient of the ``+R`` objective w.r.t. the pmf."""
        return self._residual_entropy_grad(self._rvs)

    def _objective(self):
        """
        Compute the residual entropy.

        Returns
        -------
        objective : func
            The objective function.
        """
        residual_entropy = self._residual_entropy(self._rvs)

        def objective(self, x):
            """
            Compute :math:`R[rvs]`

            Parameters
            ----------
            x : np.ndarray
                An optimization vector.

            Returns
            -------
            obj : float
                The value of the objective.
            """
            pmf = self.construct_joint(x)
            return residual_entropy(pmf)

        return objective


class MaxCAEKLMutualInformationOptimizer(BaseDistOptimizer, BaseNonConvexOptimizer):
    """
    Compute maximum CAEKL mutual information distributions.
    """

    def _objective_gradient(self):
        """Gradient of the ``-J`` objective w.r.t. the pmf."""
        caekl_grad = self._caekl_mutual_information_grad(self._rvs)
        return lambda pmf: -caekl_grad(pmf)

    def _objective(self):
        """
        Compute the negative CAEKL mutual information.

        Returns
        -------
        objective : func
            The objective function.
        """
        caekl_mutual_information = self._caekl_mutual_information(self._rvs)

        def objective(self, x):
            """
            Compute :math:`-J[rvs]`

            Parameters
            ----------
            x : np.ndarray
                An optimization vector.

            Returns
            -------
            obj : float
                The value of the objective.
            """
            pmf = self.construct_joint(x)
            return -caekl_mutual_information(pmf)

        return objective


class BROJABivariateOptimizer(MaxCoInfoOptimizer):
    """
    An optimizer for constructing the maximum co-information distribution
    consistent with (source, target) marginals of the given distribution.

    Notes
    -----
    Though maximizing co-information is generically a non-convex optimization,
    with the specific constraints involved in this calculation the problem is
    convex.
    """

    def __init__(self, dist, sources, target):
        """
        Initialize the optimizer.

        Parameters
        ----------
        dist : Distribution
            The distribution from which the corresponding optimal distribution
            will be calculated.
        sources : list, len = 2
            List of two source sets of variables.
        target : list
            The target variables.
        """
        dist = broja_prepare_dist(dist, sources, target)
        super().__init__(dist, [[0, 2], [1, 2]])

        extra_free = broja_extra_constraints(self.dist, 2).free
        self._free = sorted(set(self._free) & set(extra_free))
        self._optvec_size = len(self._free)


class BROJAAdmUIOptimizer(BROJABivariateOptimizer):
    """
    BROJA bivariate optimizer via admUI (Banerjee et al., arXiv:1709.07487).
    """

    def __init__(self, dist, sources, target, maxiter=1000, eps=1e-7, ip_method="IS"):
        self._broja_sources = list(sources)
        self._broja_target = list(target)
        self._broja_orig = dist
        self._admui_maxiter = maxiter
        self._admui_eps = eps
        self._admui_ip_method = ip_method
        self._admui_meta = {}
        super().__init__(dist, sources, target)

    def optimize(self, x0=None, niter=None, maxiter=None, polish=1e-8, callback=False, rng=None):
        from .admui import admui_dist

        q_dist, self._admui_meta = admui_dist(
            self._broja_orig,
            self._broja_sources,
            self._broja_target,
            eps=self._admui_eps,
            maxiter=self._admui_maxiter if maxiter is None else maxiter,
            ip_method=self._admui_ip_method,
        )
        self.dist = q_dist
        self._vpmf = self.dist.pmf.copy()
        self._optima = self._vpmf[self._free].copy() if self._free else self._vpmf.copy()
        return None


class BROJAConEOptimizer(BROJABivariateOptimizer):
    """
    BROJA bivariate optimizer via exponential cone programming (Makkeh et al., arXiv:1802.02485).
    """

    def __init__(self, dist, sources, target, **ecos_kwargs):
        self._broja_sources = list(sources)
        self._broja_target = list(target)
        self._broja_orig = dist
        self._ecos_kwargs = ecos_kwargs
        self._cone_meta = {}
        super().__init__(dist, sources, target)

    def optimize(self, x0=None, niter=None, maxiter=None, polish=1e-8, callback=False, rng=None):
        from .broja_cone import broja_cone_solve

        q_dist, self._cone_meta = broja_cone_solve(
            self._broja_orig,
            self._broja_sources,
            self._broja_target,
            **self._ecos_kwargs,
        )
        self.dist = q_dist
        self._vpmf = self.dist.pmf.copy()
        self._optima = self._vpmf[self._free].copy() if self._free else self._vpmf.copy()
        return None


[docs] def maxent_dist(dist, rvs, x0=None, maxiter=1000, sparse=True, method="ipf"): """ Return the maximum entropy distribution consistent with the marginals from `dist` specified in `rvs`. Parameters ---------- dist : Distribution The distributions whose marginals should be matched. rvs : list of lists The marginals from `dist` to constrain. x0 : np.ndarray Initial condition for the scipy optimizer. Ignored when `method` is 'ipf', which always starts from the uniform distribution. maxiter : int The number of optimization iterations to perform. Used only by the scipy optimizer; IPF uses its own convergence tolerance. sparse : bool Whether the returned distribution should be sparse or dense. method : str The algorithm used to compute the maximum entropy distribution. 'ipf' (the default) uses Iterative Proportional Fitting, which is typically far faster than the convex optimizer. IPF converges only linearly on cyclic structures with induced structural zeros, so when it fails to converge within its iteration budget this falls back to the scipy optimizer to preserve accuracy. 'scipy' (also accepts 'slsqp') forces the scipy convex optimizer. Returns ------- me : Distribution The maximum entropy distribution. """ dist = dist.copy() if method == "ipf": # Easy structures (acyclic, or well-conditioned cyclic) converge well # within this budget; structures that stall here converge only linearly # and are handled exactly by the scipy fallback below, so there is no # point spending IPF's full default budget on them. Run IPF densely so a # stalled iterate can be reused as a warm start for the fallback. me, converged = ipf_dist(dist, rvs, maxiter=1000, sparse=False, return_status=True) if converged: if sparse: me.make_sparse() return me # IPF stalled (typically a cyclic structure with induced structural # zeros); warm-start the convex optimizer from IPF's near-converged # iterate (a full pmf vector, which the optimizer restricts to its free # indices) for an exact answer in fewer steps. x0 = me.pmf method = "scipy" if method in ("scipy", "slsqp"): meo = MaxEntOptimizer(dist, rvs) meo.optimize(x0=x0, maxiter=maxiter) return meo.construct_dist(sparse=sparse) msg = f"Unknown method {method!r}; expected 'ipf', 'scipy', or 'slsqp'." raise ValueError(msg)
[docs] def marginal_maxent_dists(dist, k_max=None): """ Return the marginal-constrained maximum entropy distributions. Parameters ---------- dist : distribution The distribution used to constrain the maxent distributions. k_max : int The maximum order to calculate. Returns ------- dists : list A list of distributions, where the `i`th element is the maxent distribution with the `i`-size marginals fixed. """ dist = prepare_dist(dist) n_variables = dist.outcome_length() if k_max is None: k_max = n_variables outcomes = list(dist._sample_space) # Optimization for the k=0 and k=1 cases are slow since you have to optimize # the full space. We also know the answer in these cases. # This is safe since the distribution must be dense. k0 = Distribution(outcomes, [1] * len(outcomes), base="linear", validate=False) k0.normalize() k1 = product_distribution(dist) dists = [k0, k1] for k in range(k_max + 1): if k in [0, 1, n_variables]: continue variables = dist.get_rv_names() rvs = list(combinations(variables, k)) if variables is not None else list(combinations(range(n_variables), k)) dists.append(maxent_dist(dist, rvs)) # To match the all-way marginal is to match itself. Again, this is a time # savings decision, even though the optimization should be fast. if k_max == n_variables: dists.append(dist) return dists
PID = namedtuple("PID", ["R", "U0", "U1", "S"]) @removals.remove(message="Please see dit.pid.PID_BROJA.", version="1.0.0.dev8") def pid_broja(dist, sources, target, niter=10, return_opt=False): """ Compute the BROJA partial information decomposition. Parameters ---------- dist : Distribution The distribution to compute the partial information decomposition of. sources : iterable The source variables of the distribution. target : iterable The target variable of the distribution. niter : int The number of optimization steps to perform. return_opt : bool If True, return the distribution resulting from the optimization. Defaults to False. Returns ------- pid : PID namedtuple The partial information decomposition. opt_dist : Distribution The distribution resulting from the optimization. Note that var [0] is sources[0], [1] is sources[1] and [2] is target. """ broja = BROJABivariateOptimizer(dist, sources, target) broja.optimize(niter=niter) opt_dist = broja.construct_dist() r = -broja.objective(broja._optima) # in opt_dist, source[0] is [0], sources[1] is [1], and target is [2] # see broja_prepare_dist() for details u0 = I(opt_dist, [[0], [2]], [1]) u1 = I(opt_dist, [[1], [2]], [0]) # r = 0.0 if close(r, 0, rtol=1e-6, atol=1e-6) else r # u0 = 0.0 if close(u0, 0, rtol=1e-6, atol=1e-6) else u0 # u1 = 0.0 if close(u1, 0, rtol=1e-6, atol=1e-6) else u1 s = I(dist, [list(flatten(sources)), target]) - r - u0 - u1 pid = PID(R=r, U0=u0, U1=u1, S=s) if return_opt: return pid, opt_dist else: return pid