Entropy Visualizer — JavaScript 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 JavaScript implementation — the same logic the interactive tool runs, in a shareable, citable form.
/**
* entropy-visualizer — pure byte-level randomness analysis. No dependencies.
*
* Language: JavaScript (ES module; runs in browsers, Node >= 16, Bun, Deno).
* 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.
* Only Math.* is used, so no WebCrypto substitution is needed; the Lanczos
* approximation of ln Γ(x) rides along because the χ² p-value needs it.
*
* display source — part of CosmoDev's polyglot tool pages.
*/
/** Bytes per heatmap block. */
export const BLOCK_SIZE = 16;
/** Degrees of freedom for the byte-frequency χ² test (256 bins − 1 constraint). */
export const CHI_SQUARED_DF = 255;
/** Count occurrences of each byte value 0-255. */
export function countBytes(data) {
const freq = new Array(256).fill(0);
for (let i = 0; i < data.length; i++) freq[data[i]]++;
return freq;
}
/** Shannon entropy H = −Σ p·log₂p in bits/byte (zero-count bins contribute nothing). */
export function shannonBitsPerByte(frequencies, total) {
if (total <= 0) return 0;
let h = 0;
for (const count of frequencies) {
if (count === 0) continue;
h -= (count / total) * Math.log2(count / total);
}
return h;
}
/** Pearson χ² against the uniform expectation E = total/256 per bin. */
export function chiSquaredStatistic(frequencies, total) {
if (total <= 0) throw new Error('chi-squared needs a positive sample size');
const expected = total / 256;
let chi2 = 0;
for (const observed of frequencies) {
const diff = observed - expected;
chi2 += (diff * diff) / expected;
}
return chi2;
}
// Lanczos approximation (g=7, 9 coefficients) of ln Γ(x); reflection below x<0.5.
function lnGamma(x) {
const 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 Math.log(Math.PI / Math.sin(Math.PI * x)) - lnGamma(1 - x);
x -= 1;
let a = g[0];
const t = x + 7.5;
for (let i = 1; i < 9; i++) a += g[i] / (x + i);
return 0.5 * Math.log(2 * Math.PI) + (x + 0.5) * Math.log(t) - t + Math.log(a);
}
/** Regularized upper incomplete gamma Q(a,x): power series below a+1, Lentz fraction above (NR §6.2). */
export function gammaQ(a, x) {
if (a <= 0 || x < 0) return NaN;
if (x === 0) return 1;
const prefix = Math.exp(-x + a * Math.log(x) - lnGamma(a));
if (x < a + 1) {
// Series for P(a,x); Q = 1 − P.
let ap = a, sum = 1 / a, del = sum;
for (let n = 0; n < 1000; n++) {
del *= x / ++ap;
sum += del;
if (Math.abs(del) < Math.abs(sum) * 1e-15) break;
}
return Math.min(1, Math.max(0, 1 - sum * prefix));
}
// Continued fraction (modified Lentz) for Q(a,x).
const FPMIN = 1e-300;
let b = x + 1 - a, c = 1 / FPMIN, d = 1 / b, h = d;
for (let i = 1; i <= 1000; i++) {
const an = -i * (i - a);
d = an * d + (b += 2);
if (Math.abs(d) < FPMIN) d = FPMIN;
c = b + an / c;
if (Math.abs(c) < FPMIN) c = FPMIN;
h *= (d = 1 / d) * c;
if (Math.abs(d * c - 1) < 1e-15) break;
}
return Math.min(1, Math.max(0, prefix * h));
}
/** Upper-tail p-value for a χ² statistic with `df` degrees of freedom. */
export function chiSquaredP(chi2, df = CHI_SQUARED_DF) {
if (chi2 < 0 || df <= 0) return NaN;
return gammaQ(df / 2, chi2 / 2);
}
/** Circular serial correlation of consecutive bytes (`ent` metric; 0 for n<2 or constant input). */
export function serialCorrelationCoefficient(data) {
const n = data.length;
if (n < 2) return 0;
let sum = 0, sumSq = 0, sumXY = 0;
for (let i = 0; i < n; i++) {
const x = data[i];
const y = data[(i + 1) % n];
sum += x;
sumSq += x * x;
sumXY += x * y;
}
const meanSq = (sum * sum) / n;
const denom = sumSq - meanSq;
return denom === 0 ? 0 : (sumXY - meanSq) / denom;
}
/** Monte Carlo π estimate: byte pairs as points in a 256×256 square, circle radius 128. */
export function monteCarloPiEstimate(data) {
const pairs = Math.floor(data.length / 2);
if (pairs === 0) return 0;
let inside = 0;
for (let i = 0; i < pairs; i++) {
const dx = data[2 * i] - 127.5;
const dy = 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). */
export function blockEntropies(data, blockSize = BLOCK_SIZE) {
if (blockSize < 1) throw new Error('blockSize must be at least 1');
const blocks = [];
for (let off = 0; off < data.length; off += blockSize) {
const counts = new Array(256).fill(0);
let n = 0;
const end = Math.min(off + blockSize, data.length);
for (let i = off; i < end; i++) { counts[data[i]]++; n++; }
blocks.push(shannonBitsPerByte(counts, n));
}
return blocks;
}
/** Map a Shannon entropy (bits/byte) to the verdict scale. */
export function verdictFromShannon(bitsPerByte) {
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; throws on empty input. */
export function analyzeEntropy(data) {
if (data.length === 0) throw new Error('Nothing to analyze - provide at least 1 byte of data.');
const total = data.length;
const freq = countBytes(data);
const shannon = shannonBitsPerByte(freq, total);
const chi2 = chiSquaredStatistic(freq, total);
return {
shannonEntropy: shannon,
chiSquared: chi2,
chiSquaredPValue: chiSquaredP(chi2),
serialCorrelation: serialCorrelationCoefficient(data),
monteCarloPi: monteCarloPiEstimate(data),
byteFrequencies: freq,
blockEntropies: blockEntropies(data),
verdict: verdictFromShannon(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 →