Skip to content

cds2.infotheory

Entropy, divergence and dependence measures.

Information theory: entropy, divergence and dependence measures.

entropy(probabilities, base=2.0)

Shannon entropy of a discrete distribution in units of base.

Source code in src/cds2/infotheory.py
61
62
63
def entropy(probabilities: Sequence[float] | FloatArray, base: float = 2.0) -> float:
    """Shannon entropy of a discrete distribution in units of ``base``."""
    return _entropy(_as_probabilities(probabilities), _log_base(base))

joint_entropy(joint, base=2.0)

Entropy of a joint distribution given as a 2-D probability table.

Source code in src/cds2/infotheory.py
66
67
68
69
def joint_entropy(joint: Sequence[Sequence[float]] | FloatArray, base: float = 2.0) -> float:
    """Entropy of a joint distribution given as a 2-D probability table."""
    matrix = _as_joint_distribution(joint)
    return _entropy(matrix.ravel(), _log_base(base))

conditional_entropy(joint, marginal=None, base=2.0)

H(Y|X) from a joint P(X, Y) table (rows indexed by X).

Source code in src/cds2/infotheory.py
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
def conditional_entropy(
    joint: Sequence[Sequence[float]] | FloatArray,
    marginal: Sequence[float] | FloatArray | None = None,
    base: float = 2.0,
) -> float:
    """H(Y|X) from a joint P(X, Y) table (rows indexed by X)."""
    matrix = _as_joint_distribution(joint)
    logarithm = _log_base(base)
    row_sums = matrix.sum(axis=1)
    if marginal is not None:
        marginal_values = np.asarray(marginal, dtype=float)
        if marginal_values.shape != (matrix.shape[0],):
            msg = "marginal shape does not match the joint table rows"
            raise ValueError(msg)
        if not np.allclose(_as_probabilities(marginal_values), row_sums, rtol=1e-9, atol=1e-9):
            msg = "marginal probabilities must match the joint table row sums"
            raise ValueError(msg)
    total = float(row_sums.sum())
    return math.fsum(
        float(p_x) / total * _entropy(row / p_x, logarithm)
        for row, p_x in zip(matrix, row_sums, strict=True)
        if p_x > 0
    )

kl_divergence(p, q, base=2.0)

Kullback-Leibler divergence D_KL(P || Q), with zero terms where P is 0.

Source code in src/cds2/infotheory.py
108
109
110
111
112
113
114
115
116
117
118
def kl_divergence(
    p: Sequence[float] | FloatArray, q: Sequence[float] | FloatArray, base: float = 2.0
) -> float:
    """Kullback-Leibler divergence D_KL(P || Q), with zero terms where P is 0."""
    p_array, q_array = _as_probability_pair(p, q)
    logarithm = _log_base(base)
    support = p_array > 0
    if np.any(q_array[support] == 0):
        return math.inf / logarithm
    ratio_terms = p_array[support] * (np.log(p_array[support]) - np.log(q_array[support]))
    return float(ratio_terms.sum() / logarithm)

js_divergence(p, q, base=2.0)

Jensen-Shannon divergence between P and Q (symmetric, bounded).

Source code in src/cds2/infotheory.py
121
122
123
124
125
126
127
128
129
130
131
132
133
134
def js_divergence(
    p: Sequence[float] | FloatArray, q: Sequence[float] | FloatArray, base: float = 2.0
) -> float:
    """Jensen-Shannon divergence between P and Q (symmetric, bounded)."""
    p_array, q_array = _as_probability_pair(p, q)
    logarithm = _log_base(base)
    combined = p_array + q_array
    divergence = 0.0
    for probabilities in (p_array, q_array):
        support = probabilities > 0
        positive = probabilities[support]
        # Use 2P/(P+Q) to keep the smallest positive probabilities in support.
        divergence += float((positive * np.log(2.0 * positive / combined[support])).sum())
    return 0.5 * divergence / logarithm

cross_entropy(p, q, base=2.0)

Cross-entropy H(P, Q) = H(P) + D_KL(P || Q).

Source code in src/cds2/infotheory.py
137
138
139
140
141
142
143
144
145
146
147
def cross_entropy(
    p: Sequence[float] | FloatArray, q: Sequence[float] | FloatArray, base: float = 2.0
) -> float:
    """Cross-entropy H(P, Q) = H(P) + D_KL(P || Q)."""
    p_array, q_array = _as_probability_pair(p, q)
    logarithm = _log_base(base)
    support = p_array > 0
    if np.any(q_array[support] == 0):
        return math.inf / logarithm
    terms = -p_array[support] * np.log(q_array[support])
    return float(terms.sum() / logarithm)

mutual_information(joint, base=2.0)

Mutual information I(X; Y) from a joint P(X, Y) table.

Source code in src/cds2/infotheory.py
159
160
161
def mutual_information(joint: Sequence[Sequence[float]] | FloatArray, base: float = 2.0) -> float:
    """Mutual information I(X; Y) from a joint P(X, Y) table."""
    return _mutual_information(_as_joint_distribution(joint), _log_base(base))

normalized_mutual_information(joint, base=2.0)

I(X; Y) scaled into [0, 1] by the square-root entropy product.

Source code in src/cds2/infotheory.py
164
165
166
167
168
169
170
171
172
173
174
175
176
def normalized_mutual_information(
    joint: Sequence[Sequence[float]] | FloatArray, base: float = 2.0
) -> float:
    """I(X; Y) scaled into [0, 1] by the square-root entropy product."""
    matrix = _as_joint_distribution(joint)
    _log_base(base)
    # The logarithm base cancels in the normalized result.
    h_x = _entropy(matrix.sum(axis=1), 1.0)
    h_y = _entropy(matrix.sum(axis=0), 1.0)
    denominator = math.sqrt(abs(h_x)) * math.sqrt(abs(h_y))
    if denominator == 0:
        return 0.0
    return _mutual_information(matrix, 1.0) / denominator

permutation_entropy(signal, order=3, delay=1, base=2.0)

Bandt-Pompe permutation entropy of an ordinal-pattern histogram.

Source code in src/cds2/infotheory.py
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
def permutation_entropy(
    signal: Sequence[float] | FloatArray, order: int = 3, delay: int = 1, base: float = 2.0
) -> float:
    """Bandt-Pompe permutation entropy of an ordinal-pattern histogram."""
    series = np.asarray(signal, dtype=float)
    if series.ndim != 1 or not np.all(np.isfinite(series)):
        msg = "signal must be a finite 1-D sequence"
        raise ValueError(msg)
    if order < 2:
        msg = "order must be at least 2"
        raise ValueError(msg)
    if delay < 1:
        msg = "delay must be at least 1"
        raise ValueError(msg)
    needed = (order - 1) * delay + 1
    if series.size < needed:
        msg = f"signal needs at least {needed} samples for order={order}, delay={delay}"
        raise ValueError(msg)
    windows = np.lib.stride_tricks.sliding_window_view(series, needed)
    embedded = windows[:, ::delay]
    codes = np.argsort(embedded, axis=1, kind="stable")
    _, counts = np.unique(codes, axis=0, return_counts=True)
    probabilities = counts / counts.sum()
    return entropy(probabilities, base)