"""
The extropy.
"""
import numpy as np
from ..math.ops import get_ops
__all__ = ("extropy",)
[docs]
def extropy(dist, rvs=None):
"""
Returns the extropy J[X] over the random variables in `rvs`.
If the distribution represents linear probabilities, then the extropy
is calculated with units of 'bits' (base-2).
Parameters
----------
dist : Distribution or float
The distribution from which the extropy is calculated. If a float,
then we calculate the binary extropy.
rvs : list, None
The indexes of the random variable used to calculate the extropy.
If None, then the extropy is calculated over all random variables.
This should remain `None` for scalar distributions.
Returns
-------
J : float
The extropy of the distribution.
"""
try:
# Handle binary extropy.
float(dist)
except TypeError:
pass
else:
# Assume linear probability for binary extropy.
import dit
dist = dit.Distribution([dist, 1 - dist])
rvs = None
d = dist.marginal(rvs) if rvs is not None else dist
pmf = d.pmf
if d.is_symbolic():
import sympy
terms = []
for p in pmf:
np_ = 1 - sympy.sympify(p)
if np_ == 0:
continue
terms.append(-np_ * sympy.log(np_, 2))
return sympy.Add(*terms)
if d.is_log():
base = d.get_base(numerical=True)
npmf = d.ops.log(1 - d.ops.exp(pmf))
terms = -(base**npmf) * npmf
else:
# Calculate entropy in bits.
log = get_ops(2).log
npmf = 1 - pmf
terms = -npmf * log(npmf)
J = np.nansum(terms)
return J