Entropy Visualizer — PHP 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 PHP implementation — the same logic the interactive tool runs, in a shareable, citable form.
<?php
/**
* entropy-visualizer — pure byte-level randomness analysis. No dependencies.
*
* Language: PHP 7.4+ (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 a binary string (PHP strings are byte buffers, so each offset is a
* byte). PHP's stdlib has no lgamma, so the Lanczos approximation of ln Γ(x)
* is ported verbatim for the χ² p-value.
*
* display source — part of CosmoDev's polyglot tool pages.
*/
declare(strict_types=1);
const EV_BLOCK_SIZE = 16; // Bytes per heatmap block.
const EV_CHI_SQUARED_DF = 255.0; // Degrees of freedom (256 bins - 1 constraint).
/** Count occurrences of each byte value 0-255 (index => count). */
function ev_count_bytes(string $data): array
{
$freq = array_fill(0, 256, 0);
$len = strlen($data);
for ($i = 0; $i < $len; $i++) {
$freq[ord($data[$i])]++;
}
return $freq;
}
/** Shannon entropy H = -Σ p·log₂p in bits/byte; zero-count bins contribute nothing. */
function ev_shannon_bits_per_byte(array $frequencies, int $total): float
{
if ($total <= 0) {
return 0.0;
}
$h = 0.0;
foreach ($frequencies as $count) {
if ($count === 0) {
continue;
}
$p = $count / $total;
$h -= $p * log($p, 2);
}
return $h;
}
/** Pearson χ² against the uniform expectation E = total/256 per bin. */
function ev_chi_squared_statistic(array $frequencies, int $total): float
{
if ($total <= 0) {
throw new InvalidArgumentException('chi-squared needs a positive sample size');
}
$expected = $total / 256;
$chi2 = 0.0;
foreach ($frequencies as $observed) {
$diff = $observed - $expected;
$chi2 += ($diff * $diff) / $expected;
}
return $chi2;
}
/** Lanczos approximation (g=7, 9 coefficients) of ln Γ(x); reflection below x<0.5. */
function ev_ln_gamma(float $x): float
{
static $g = [
0.99999999999980993, 676.5203681218851, -1259.1392167224028,
771.32342877765313, -176.61502916214059, 12.507343278686905,
-0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7,
];
if ($x < 0.5) {
return log(M_PI / sin(M_PI * $x)) - ev_ln_gamma(1 - $x);
}
$x -= 1;
$a = $g[0];
$t = $x + 7.5;
for ($i = 1; $i < 9; $i++) {
$a += $g[$i] / ($x + $i);
}
return 0.5 * log(2 * M_PI) + ($x + 0.5) * log($t) - $t + log($a);
}
/** Regularized upper incomplete gamma Q(a,x): series below a+1, Lentz fraction above. */
function ev_gamma_q(float $a, float $x): float
{
if ($a <= 0 || $x < 0) {
return NAN;
}
if ($x == 0) {
return 1.0;
}
$prefix = exp(-$x + $a * log($x) - ev_ln_gamma($a));
if ($x < $a + 1) {
// Series for P(a,x); Q = 1 - P.
$ap = $a;
$sum = 1 / $a;
$del = $sum;
for ($n = 0; $n < 1000; $n++) {
$ap += 1;
$del *= $x / $ap;
$sum += $del;
if (abs($del) < abs($sum) * 1e-15) {
break;
}
}
return min(1.0, max(0.0, 1 - $sum * $prefix));
}
// Continued fraction (modified Lentz) for Q(a,x).
$fpmin = 1e-300;
$b = $x + 1 - $a;
$c = 1 / $fpmin;
$d = 1 / $b;
$h = $d;
for ($i = 1; $i <= 1000; $i++) {
$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 / $d;
$del = $d * $c;
$h *= $del;
if (abs($del - 1) < 1e-15) {
break;
}
}
return min(1.0, max(0.0, $prefix * $h));
}
/** Upper-tail p-value for a χ² statistic with $df degrees of freedom. */
function ev_chi_squared_p(float $chi2, float $df = EV_CHI_SQUARED_DF): float
{
if ($chi2 < 0 || $df <= 0) {
return NAN;
}
return ev_gamma_q($df / 2, $chi2 / 2);
}
/** Circular serial correlation of consecutive bytes (`ent` metric); 0 for n<2 or constant input. */
function ev_serial_correlation_coefficient(string $data): float
{
$n = strlen($data);
if ($n < 2) {
return 0.0;
}
$sum = 0;
$sumSq = 0;
$sumXY = 0;
for ($i = 0; $i < $n; $i++) {
$x = ord($data[$i]);
$y = ord($data[($i + 1) % $n]);
$sum += $x;
$sumSq += $x * $x;
$sumXY += $x * $y;
}
$meanSq = ($sum * $sum) / $n;
$denom = $sumSq - $meanSq;
if ($denom == 0) {
return 0.0;
}
return ($sumXY - $meanSq) / $denom;
}
/** Monte Carlo π estimate: byte pairs as points in a 256×256 square, circle radius 128. */
function ev_monte_carlo_pi_estimate(string $data): float
{
$pairs = intdiv(strlen($data), 2);
if ($pairs === 0) {
return 0.0;
}
$inside = 0;
for ($i = 0; $i < $pairs; $i++) {
$dx = ord($data[2 * $i]) - 127.5;
$dy = ord($data[2 * $i + 1]) - 127.5;
if ($dx * $dx + $dy * $dy <= 128 * 128) {
$inside++;
}
}
return (4 * $inside) / $pairs;
}
/** Shannon entropy (bits/byte) of each consecutive $blockSize-byte block (heatmap data). */
function ev_block_entropies(string $data, int $blockSize = EV_BLOCK_SIZE): array
{
if ($blockSize < 1) {
throw new InvalidArgumentException('blockSize must be at least 1');
}
$blocks = [];
foreach (str_split($data, $blockSize) as $chunk) {
$blocks[] = ev_shannon_bits_per_byte(ev_count_bytes($chunk), strlen($chunk));
}
return $blocks;
}
/** Map a Shannon entropy (bits/byte) to the verdict scale. */
function ev_verdict_from_shannon(float $bitsPerByte): string
{
if ($bitsPerByte > 7.5) {
return 'excellent';
}
if ($bitsPerByte > 6.0) {
return 'good';
}
if ($bitsPerByte > 4.0) {
return 'suspicious';
}
return 'low';
}
/**
* Full analysis of a byte sequence.
*
* @return array{shannon_entropy: float, chi_squared: float, chi_squared_p_value: float,
* serial_correlation: float, monte_carlo_pi: float, byte_frequencies: int[],
* block_entropies: float[], verdict: string}
*
* @throws InvalidArgumentException on empty input.
*/
function ev_analyze_entropy(string $data): array
{
if ($data === '') {
throw new InvalidArgumentException('Nothing to analyze - provide at least 1 byte of data.');
}
$total = strlen($data);
$freq = ev_count_bytes($data);
$shannon = ev_shannon_bits_per_byte($freq, $total);
$chi2 = ev_chi_squared_statistic($freq, $total);
return [
'shannon_entropy' => $shannon,
'chi_squared' => $chi2,
'chi_squared_p_value' => ev_chi_squared_p($chi2),
'serial_correlation' => ev_serial_correlation_coefficient($data),
'monte_carlo_pi' => ev_monte_carlo_pi_estimate($data),
'byte_frequencies' => $freq,
'block_entropies' => ev_block_entropies($data),
'verdict' => ev_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 →