"""NIST SP 800-90B continuous health tests (section 4.4) as a Python reference model. * rct_cutoff, apt_cutoff: the cutoff formulas of sections 4.4.1 and 4.4.2 * rct_failures, apt_failures: the tests, sample by sample, as written in the standard * biased_bits, stuck_bits, periodic_bits: seeded test sources This model is the reference that cocotb_health.py compares health_tests.sv against. It tests a recorded or simulated bit stream; it cannot tell you how much entropy a real noise source has. Run: /Volumes/M2-Dev/conda/envs/toptech/bin/python sp80090b_health.py """ from __future__ import annotations import math import numpy as np from scipy.stats import binom ALPHA = 2.0 ** -20 # false-positive probability used throughout SP 800-90B section 4.4 def rct_cutoff(h: float, alpha: float = ALPHA) -> int: """Repetition Count Test cutoff: C = 1 + ceil(-log2(alpha) / H).""" return 1 + math.ceil(-math.log2(alpha) / h) def apt_cutoff(h: float, window: int, alpha: float = ALPHA) -> int: """Adaptive Proportion Test cutoff: C = 1 + CRITBINOM(W, 2^-H, 1 - alpha). CRITBINOM(n, p, a) is the smallest k with P(X <= k) >= a for X ~ Binomial(n, p), which is scipy's binom.ppf. """ return 1 + int(binom.ppf(1.0 - alpha, window, 2.0 ** -h)) def rct_failures(samples: np.ndarray, c: int) -> list[int]: """Indices of the samples at which the Repetition Count Test signals a failure.""" fails: list[int] = [] a, b = int(samples[0]), 1 for i in range(1, len(samples)): x = int(samples[i]) if x == a: b += 1 if b >= c: fails.append(i) else: a, b = x, 1 return fails def apt_failures(samples: np.ndarray, c: int, window: int) -> list[int]: """Indices of the samples at which the Adaptive Proportion Test signals a failure. Windows are back to back: the sample after a full window becomes the next reference. """ fails: list[int] = [] i = 0 n = len(samples) while i < n: a, b = int(samples[i]), 1 for j in range(i + 1, min(i + window, n)): if int(samples[j]) == a: b += 1 if b >= c: fails.append(j) i += window return fails def biased_bits(p_one: float, n: int, seed: int) -> np.ndarray: """Independent bits with P(1) = p_one.""" return (np.random.default_rng(seed).random(n) < p_one).astype(np.int64) def stuck_bits(value: int, n: int) -> np.ndarray: return np.full(n, value, dtype=np.int64) def periodic_bits(pattern: list[int], n: int) -> np.ndarray: return np.resize(np.array(pattern, dtype=np.int64), n) def min_entropy_iid_binary(p_one: float) -> float: """Min-entropy per bit of an IID binary source: -log2(max(p, 1 - p)).""" return -math.log2(max(p_one, 1.0 - p_one)) def main() -> None: print("Cutoffs for alpha = 2^-20") print(" H RCT C APT C (W=1024) APT C (W=512)") for h in (0.2, 0.5, 0.8, 1.0, 2.0, 4.0, 8.0): apt_bin = apt_cutoff(h, 1024) if h <= 1.0 else None apt_nb = apt_cutoff(h, 512) print(f"{h:4.1f} {rct_cutoff(h):6d} {str(apt_bin) if apt_bin else '-':>12} {apt_nb:12d}") c_rct, c_apt = rct_cutoff(1.0), apt_cutoff(1.0, 1024) n = 1 << 16 print(f"\nBinary source assessed at H = 1: RCT C = {c_rct}, APT C = {c_apt}, {n} samples") sources = { "fair, p = 0.50": biased_bits(0.50, n, 1), "biased, p = 0.60": biased_bits(0.60, n, 2), "biased, p = 0.75": biased_bits(0.75, n, 3), "stuck at 1": stuck_bits(1, n), "alternating 0101": periodic_bits([0, 1], n), } for name, s in sources.items(): r, a = rct_failures(s, c_rct), apt_failures(s, c_apt, 1024) first = lambda f: str(f[0]) if f else "-" # noqa: E731 print(f"{name:18s} RCT fails {len(r):6d} (first at {first(r):>5s}) " f"APT fails {len(a):6d} (first at {first(a):>5s})") if __name__ == "__main__": main()