Entropy Visualizer — Python source
Visualize the randomness quality of any data. See Shannon entropy, byte frequency distribution, chi-squared score, and a visual entropy heatmap.
This is the Python implementation — the same logic the interactive tool runs, in a shareable, citable form.
"""entropy-visualizer — pure byte-level randomness analysis. No dependencies.
Language: Python 3 (standard library only).
CosmoDev polyglot showcase port of the `entropy-visualizer` tool, ported from
src/lib/entropy-visualizer.ts (the canonical TypeScript implementation).
Everything is deterministic: the same bytes always produce the same numbers.
Input is any bytes-like object. The χ² p-value uses ``math.lgamma`` in place
of the TypeScript lib's hand-rolled Lanczos approximation of ln Γ(x) — same
function, stdlib precision.
display source — part of CosmoDev's polyglot tool pages.
"""
from __future__ import annotations
import math
from dataclasses import dataclass
from typing import Iterable
# Bytes per heatmap block.
BLOCK_SIZE = 16
# Degrees of freedom for the byte-frequency χ² test (256 bins - 1 constraint).
CHI_SQUARED_DF = 255
@dataclass
class EntropyAnalysis:
"""Result bundle for :func:`analyze_entropy` (mirrors the TS interface)."""
shannon_entropy: float
chi_squared: float
chi_squared_p_value: float
serial_correlation: float
monte_carlo_pi: float
byte_frequencies: list[int]
block_entropies: list[float]
verdict: str
def count_bytes(data: bytes) -> list[int]:
"""Count occurrences of each byte value 0-255."""
freq = [0] * 256
for byte in data:
freq[byte] += 1
return freq
def shannon_bits_per_byte(frequencies: Iterable[int], total: int) -> float:
"""Shannon entropy H = -Σ p·log₂p in bits/byte; zero-count bins contribute nothing."""
if total <= 0:
return 0.0
h = 0.0
for count in frequencies:
if count == 0:
continue
p = count / total
h -= p * math.log2(p)
return h
def chi_squared_statistic(frequencies: Iterable[int], total: int) -> float:
"""Pearson χ² against the uniform expectation E = total/256 per bin."""
if total <= 0:
raise ValueError("chi-squared needs a positive sample size")
expected = total / 256
chi2 = 0.0
for observed in frequencies:
diff = observed - expected
chi2 += (diff * diff) / expected
return chi2
def gamma_q(a: float, x: float) -> float:
"""Regularized upper incomplete gamma Q(a,x): series below a+1, Lentz fraction above."""
if a <= 0 or x < 0:
return math.nan
if x == 0:
return 1.0
prefix = math.exp(-x + a * math.log(x) - math.lgamma(a))
if x < a + 1:
# Series for P(a,x); Q = 1 - P.
ap, total_sum, dele = a, 1.0 / a, 1.0 / a
for _ in range(1000):
ap += 1
dele *= x / ap
total_sum += dele
if abs(dele) < abs(total_sum) * 1e-15:
break
return min(1.0, max(0.0, 1.0 - total_sum * prefix))
# Continued fraction (modified Lentz) for Q(a,x).
fpmin = 1e-300
b = x + 1 - a
c = 1.0 / fpmin
d = 1.0 / b
h = d
for i in range(1, 1001):
an = -i * (i - a)
b += 2
d = an * d + b
if abs(d) < fpmin:
d = fpmin
c = b + an / c
if abs(c) < fpmin:
c = fpmin
d = 1.0 / d
dele = d * c
h *= dele
if abs(dele - 1) < 1e-15:
break
return min(1.0, max(0.0, prefix * h))
def chi_squared_p(chi2: float, df: int = CHI_SQUARED_DF) -> float:
"""Upper-tail p-value for a χ² statistic with ``df`` degrees of freedom."""
if chi2 < 0 or df <= 0:
return math.nan
return gamma_q(df / 2, chi2 / 2)
def serial_correlation_coefficient(data: bytes) -> float:
"""Circular serial correlation of consecutive bytes (`ent` metric); 0 for n<2 or constant input."""
n = len(data)
if n < 2:
return 0.0
total = sum(data)
sum_sq = sum(b * b for b in data)
sum_xy = sum(data[i] * data[(i + 1) % n] for i in range(n))
mean_sq = (total * total) / n
denom = sum_sq - mean_sq
if denom == 0:
return 0.0
return (sum_xy - mean_sq) / denom
def monte_carlo_pi_estimate(data: bytes) -> float:
"""Monte Carlo π estimate: byte pairs as points in a 256×256 square, circle radius 128."""
pairs = len(data) // 2
if pairs == 0:
return 0.0
inside = 0
for i in range(pairs):
dx = data[2 * i] - 127.5
dy = data[2 * i + 1] - 127.5
if dx * dx + dy * dy <= 128 * 128:
inside += 1
return (4.0 * inside) / pairs
def block_entropies(data: bytes, block_size: int = BLOCK_SIZE) -> list[float]:
"""Shannon entropy (bits/byte) of each consecutive ``block_size``-byte block (heatmap data)."""
if block_size < 1:
raise ValueError("blockSize must be at least 1")
blocks = []
for off in range(0, len(data), block_size):
chunk = data[off : off + block_size]
blocks.append(shannon_bits_per_byte(count_bytes(chunk), len(chunk)))
return blocks
def verdict_from_shannon(bits_per_byte: float) -> str:
"""Map a Shannon entropy (bits/byte) to the verdict scale."""
if bits_per_byte > 7.5:
return "excellent"
if bits_per_byte > 6.0:
return "good"
if bits_per_byte > 4.0:
return "suspicious"
return "low"
def analyze_entropy(data: bytes) -> EntropyAnalysis:
"""Full analysis of a byte sequence; raises on empty input."""
if len(data) == 0:
raise ValueError("Nothing to analyze - provide at least 1 byte of data.")
total = len(data)
freq = count_bytes(data)
shannon = shannon_bits_per_byte(freq, total)
chi2 = chi_squared_statistic(freq, total)
return EntropyAnalysis(
shannon_entropy=shannon,
chi_squared=chi2,
chi_squared_p_value=chi_squared_p(chi2),
serial_correlation=serial_correlation_coefficient(data),
monte_carlo_pi=monte_carlo_pi_estimate(data),
byte_frequencies=freq,
block_entropies=block_entropies(data),
verdict=verdict_from_shannon(shannon),
)
Also available in 13 other languages
Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →