"""Entropy over coded values. Shannon entropy needs counts, and counting needs an ordering. This module gets that ordering from the same bit-scan comparator the shaders use, so a histogram can be built from hypervectors without decoding them: bucket(v) = number of bucket edges e with v >= e Each of those tests is ``ShaderFabric.compare``, which is exact. The result is an ordinary integer count vector, from which entropy in bits follows. Why this matters for shading ---------------------------- Entropy is the natural weight for "how much is happening here": a flat region has all its values in one bucket (0 bits), an edge or a noisy patch spreads across buckets (up to log2(buckets) bits). ``entropic_octave`` turns that into a power-of-two attenuation, which the shader applies with ``shift`` — so an entropy-weighted shader is still exact arithmetic, not a float multiply. The one decoded step is :func:`local_entropy`, which is a *measurement* of an already-decoded grid; it is used for reporting and for computing the attenuation table, never inside the pixel path. """ from __future__ import annotations import math from typing import Sequence from .shader import ShaderFabric def coded_histogram( vectors: Sequence[int], buckets: int = 8, lo: int = 0, hi: int = 255, fabric: ShaderFabric | None = None, ) -> list[int]: """Count *coded* values into ``buckets`` bins using only the comparator. ``vectors`` must be hypervectors from ``fabric.level``; passing raw integers is a silent error, since a small integer is also a valid vector word. Use :func:`level_histogram` for raw levels. """ if buckets < 1: raise ValueError("buckets must be positive") fabric = fabric or ShaderFabric() span = (hi - lo) / buckets edges = [fabric.level(lo + int(round(span * (i + 1)))) for i in range(buckets - 1)] counts = [0] * buckets for vector in vectors: idx = 0 for edge in edges: if fabric.compare(vector, edge) >= 0: idx += 1 else: break counts[idx] += 1 return counts def level_histogram( levels: Sequence[int], buckets: int = 8, lo: int = 0, hi: int = 255, fabric: ShaderFabric | None = None, ) -> list[int]: """Encode raw levels, then histogram them.""" fabric = fabric or ShaderFabric() return coded_histogram([fabric.level(v) for v in levels], buckets, lo, hi, fabric) def shannon(counts: Sequence[int]) -> float: """Shannon entropy of a count vector, in bits.""" total = sum(counts) if total <= 0: return 0.0 bits = 0.0 for count in counts: if count: p = count / total bits -= p * math.log2(p) return bits def entropy_bits( levels: Sequence[int], buckets: int = 8, lo: int = 0, hi: int = 255, fabric: ShaderFabric | None = None, ) -> tuple[float, list[int]]: """Entropy of a set of raw levels, plus the histogram it came from.""" counts = level_histogram(levels, buckets, lo, hi, fabric) return shannon(counts), counts def local_entropy( levels: Sequence[Sequence[int]], radius: int = 1, buckets: int = 8, hi: int = 255 ) -> list[list[float]]: """Per-pixel entropy of a decoded grid inside a (2r+1) window. A measurement of an already-decoded grid — used for reporting and for choosing attenuation, not inside the exact pixel path. """ height = len(levels) width = len(levels[0]) if height else 0 out = [[0.0] * width for _ in range(height)] span = hi / buckets for y in range(height): for x in range(width): counts = [0] * buckets for dy in range(-radius, radius + 1): for dx in range(-radius, radius + 1): ny, nx = y + dy, x + dx if 0 <= ny < height and 0 <= nx < width: idx = min(buckets - 1, int(levels[ny][nx] / span)) counts[idx] += 1 out[y][x] = shannon(counts) return out def entropic_octave(bits: float, max_bits: float, octaves: int = 4) -> int: """Map entropy in bits to an attenuation exponent. Low entropy means a flat region, which is dimmed most; high entropy keeps the value. The mapping is deliberately coarse: it lands on an integer shift, which is what makes entropy-weighted shading exact. """ if max_bits <= 0: return octaves ratio = max(0.0, min(1.0, bits / max_bits)) return max(0, min(octaves, int(round((1.0 - ratio) * octaves)))) def max_bits(buckets: int = 8) -> float: """Entropy ceiling for a histogram with ``buckets`` bins.""" return math.log2(max(1, buckets))