Skip to content

Entropy Visualizer — Go 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 Go implementation — the same logic the interactive tool runs, in a shareable, citable form.

// Package entropyvisualizer ports src/lib/entropy-visualizer.ts (dual source:
// the web lib is TypeScript, the CLI lib is Go — kept in lock-step). Pure
// byte-level randomness analysis: Shannon entropy, χ² uniformity, circular
// serial correlation, Monte Carlo π, per-block entropy. Deterministic and
// stdlib-only; never panics — invalid input returns an error. The
// table-driven tests in entropy_visualizer_test.go share vectors with
// src/lib/entropy-visualizer.test.ts so the two implementations are held to
// the same contract.
package entropyvisualizer

import (
	"errors"
	"math"
)

// EntropyVerdict is the qualitative rating mapped from Shannon entropy.
type EntropyVerdict string

// Verdict scale, mirroring the EntropyVerdict union of the TS lib.
const (
	VerdictExcellent  EntropyVerdict = "excellent"
	VerdictGood       EntropyVerdict = "good"
	VerdictSuspicious EntropyVerdict = "suspicious"
	VerdictLow        EntropyVerdict = "low"
)

// BlockSize is the bytes-per-heatmap-block default of the TS lib's
// blockEntropies (pass it to BlockEntropies).
const BlockSize = 16

// ChiSquaredDF is the degrees of freedom for the byte-frequency χ² test
// (256 bins - 1 constraint). Pass it to ChiSquaredP.
const ChiSquaredDF = 255

// EntropyAnalysis is the full analysis of a byte sequence, mirroring the
// EntropyAnalysis interface of the TS lib.
type EntropyAnalysis struct {
	// ShannonEntropy is Shannon entropy in bits per byte
	// (0 = one repeating byte, 8 = perfectly uniform).
	ShannonEntropy float64
	// ChiSquared is the χ² statistic against the uniform 256-bin expectation.
	ChiSquared float64
	// ChiSquaredPValue is the upper-tail p-value for χ² with 255 degrees of
	// freedom (1 = perfectly plausible).
	ChiSquaredPValue float64
	// SerialCorrelation is the circular serial correlation between
	// consecutive bytes (-1 … +1, 0 = uncorrelated).
	SerialCorrelation float64
	// MonteCarloPi is the Monte Carlo π estimate from consecutive byte pairs
	// (≈3.14159 for random data).
	MonteCarloPi float64
	// ByteFrequencies is the occurrence count per byte value 0-255.
	ByteFrequencies [256]int
	// BlockEntropies holds the Shannon entropy (bits/byte) of each
	// BlockSize-byte block, for the heatmap.
	BlockEntropies []float64
	Verdict        EntropyVerdict
}

// CountBytes counts occurrences of each byte value 0-255. The [256]int array
// type enforces the TS lib's "always 256 bins" invariant.
func CountBytes(data []byte) [256]int {
	var freq [256]int
	for _, b := range data {
		freq[b]++
	}
	return freq
}

// ShannonBitsPerByte returns Shannon entropy H = -Σ p(x)·log2(p(x)) in bits
// per byte, computed from a frequency histogram. Zero-count bins contribute
// nothing. total must be the sum of frequencies.
func ShannonBitsPerByte(frequencies [256]int, total int) float64 {
	if total <= 0 {
		return 0
	}
	h := 0.0
	for _, count := range frequencies {
		if count == 0 {
			continue
		}
		p := float64(count) / float64(total)
		h -= p * math.Log2(p)
	}
	return h
}

// ChiSquaredStatistic returns the Pearson χ² comparing observed byte counts
// against a uniform expectation E = total/256 per bin. It errors on a
// non-positive sample size (the TS lib throws).
func ChiSquaredStatistic(frequencies [256]int, total int) (float64, error) {
	if total <= 0 {
		return 0, errors.New("chi-squared needs a positive sample size")
	}
	expected := float64(total) / 256
	chi2 := 0.0
	for _, observed := range frequencies {
		diff := float64(observed) - expected
		chi2 += (diff * diff) / expected
	}
	return chi2, nil
}

// lanczos holds the g=7, 9-coefficient Lanczos terms shared with lnGamma in
// the TS lib — identical literals, identical results.
var lanczos = [9]float64{
	0.99999999999980993, 676.5203681218851, -1259.1392167224028,
	771.32342877765313, -176.61502916214059, 12.507343278686905,
	-0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7,
}

// lnGamma is the Lanczos approximation (g=7, 9 coefficients) of ln Γ(x).
func lnGamma(x float64) float64 {
	if x < 0.5 {
		// Reflection formula: Γ(x)·Γ(1-x) = π / sin(πx)
		return math.Log(math.Pi/math.Sin(math.Pi*x)) - lnGamma(1-x)
	}
	x -= 1
	a := lanczos[0]
	t := x + 7.5
	for i := 1; i < 9; i++ {
		a += lanczos[i] / (x + float64(i))
	}
	return 0.5*math.Log(2*math.Pi) + (x+0.5)*math.Log(t) - t + math.Log(a)
}

// GammaQ is the regularized upper incomplete gamma function Q(a, x) =
// Γ(a,x)/Γ(a), via the power series (x < a+1) or the Lentz continued
// fraction (otherwise). Numerical Recipes §6.2. Invalid input yields NaN,
// mirroring the TS lib.
func GammaQ(a, x float64) float64 {
	if a <= 0 || x < 0 {
		return math.NaN()
	}
	if x == 0 {
		return 1
	}
	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 math.Abs(del) < math.Abs(sum)*1e-15 {
				break
			}
		}
		return math.Min(1, math.Max(0, 1-sum*math.Exp(-x+a*math.Log(x)-lnGamma(a))))
	}
	// Continued fraction for Q(a,x)
	const fpmin = 1e-300
	b := x + 1 - a
	c := 1 / fpmin
	d := 1 / b
	h := d
	for i := 1; i <= 1000; i++ {
		an := -float64(i) * (float64(i) - a)
		b += 2
		d = an*d + b
		if math.Abs(d) < fpmin {
			d = fpmin
		}
		c = b + an/c
		if math.Abs(c) < fpmin {
			c = fpmin
		}
		d = 1 / d
		del := d * c
		h *= del
		if math.Abs(del-1) < 1e-15 {
			break
		}
	}
	return math.Min(1, math.Max(0, math.Exp(-x+a*math.Log(x)-lnGamma(a))*h))
}

// ChiSquaredP returns the upper-tail p-value for a χ² statistic with df
// degrees of freedom. Go has no default parameters: pass ChiSquaredDF (255)
// for the byte-histogram default of the TS lib. Negative chi2 or non-positive
// df yields NaN, mirroring the TS lib.
func ChiSquaredP(chi2, df float64) float64 {
	if chi2 < 0 || df <= 0 {
		return math.NaN()
	}
	return GammaQ(df/2, chi2/2)
}

// SerialCorrelationCoefficient returns the circular serial correlation
// between consecutive bytes (the `ent` tool's metric):
// scc = (Σxy - (Σx)²/n) / (Σx² - (Σx)²/n) over the pair sequence
// (x₀,x₁), (x₁,x₂), …, (xₙ₋₁,x₀). 0 = uncorrelated, ±1 = perfectly
// (anti)correlated. Constant input has a zero denominator → reported as 0
// (nothing to correlate); inputs shorter than 2 bytes are also 0.
func SerialCorrelationCoefficient(data []byte) float64 {
	n := len(data)
	if n < 2 {
		return 0
	}
	sum := 0.0
	sumSq := 0.0
	sumXY := 0.0
	for i := 0; i < n; i++ {
		x := float64(data[i])
		y := float64(data[(i+1)%n])
		sum += x
		sumSq += x * x
		sumXY += x * y
	}
	meanSq := (sum * sum) / float64(n)
	denom := sumSq - meanSq
	if denom == 0 {
		return 0
	}
	return (sumXY - meanSq) / denom
}

// MonteCarloPiEstimate returns the Monte Carlo π estimate: consecutive byte
// pairs are (x, y) points in a 256×256 square; the fraction inside the
// inscribed circle (center 127.5, radius 128) times 4 estimates π. Inputs
// with fewer than 2 bytes → 0.
func MonteCarloPiEstimate(data []byte) float64 {
	pairs := len(data) / 2
	if pairs == 0 {
		return 0
	}
	inside := 0
	for i := 0; i < pairs; i++ {
		dx := float64(data[2*i]) - 127.5
		dy := float64(data[2*i+1]) - 127.5
		if dx*dx+dy*dy <= 128*128 {
			inside++
		}
	}
	return (4 * float64(inside)) / float64(pairs)
}

// BlockEntropies returns the Shannon entropy (bits/byte) of each consecutive
// blockSize-byte block (the final partial block included). Go has no default
// parameters: pass BlockSize (16) for the heatmap default of the TS lib. A
// blockSize below 1 errors (the TS lib throws).
func BlockEntropies(data []byte, blockSize int) ([]float64, error) {
	if blockSize < 1 {
		return nil, errors.New("blockSize must be at least 1")
	}
	var blocks []float64
	for off := 0; off < len(data); off += blockSize {
		var counts [256]int
		n := 0
		end := off + blockSize
		if end > len(data) {
			end = len(data)
		}
		for i := off; i < end; i++ {
			counts[data[i]]++
			n++
		}
		blocks = append(blocks, ShannonBitsPerByte(counts, n))
	}
	return blocks, nil
}

// VerdictFromShannon maps a Shannon entropy (bits/byte) to the verdict scale:
// >7.5 excellent, >6 good, >4 suspicious, else low.
func VerdictFromShannon(bitsPerByte float64) EntropyVerdict {
	switch {
	case bitsPerByte > 7.5:
		return VerdictExcellent
	case bitsPerByte > 6.0:
		return VerdictGood
	case bitsPerByte > 4.0:
		return VerdictSuspicious
	default:
		return VerdictLow
	}
}

// AnalyzeEntropy runs the full analysis of a byte sequence. It returns an
// error on empty input — there is nothing to measure and every metric would
// be undefined (the TS lib throws).
func AnalyzeEntropy(data []byte) (EntropyAnalysis, error) {
	if len(data) == 0 {
		return EntropyAnalysis{}, errors.New("Nothing to analyze - provide at least 1 byte of data.")
	}
	total := len(data)
	freq := CountBytes(data)
	shannon := ShannonBitsPerByte(freq, total)
	chi2, err := ChiSquaredStatistic(freq, total)
	if err != nil {
		return EntropyAnalysis{}, err
	}
	blocks, err := BlockEntropies(data, BlockSize)
	if err != nil {
		return EntropyAnalysis{}, err
	}
	return EntropyAnalysis{
		ShannonEntropy:    shannon,
		ChiSquared:        chi2,
		ChiSquaredPValue:  ChiSquaredP(chi2, ChiSquaredDF),
		SerialCorrelation: SerialCorrelationCoefficient(data),
		MonteCarloPi:      MonteCarloPiEstimate(data),
		ByteFrequencies:   freq,
		BlockEntropies:    blocks,
		Verdict:           VerdictFromShannon(shannon),
	}, nil
}

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 →