White Noise (Stealth) Transmission Using Fractal Library

Introduction

You know, radio towers & the grid sort of brute force nature with a hammer. For this reason, though not limited thereby, it is perhaps natural that they felt the need to regulate the crowded bands, or it is perhaps more nefarious that nobody’s allowed to tune the now-empty analog airwaves in this way. That’s right, it’s all digital now, and for which you (allegedly) need a license, though a firm understanding of the Constitution in the context of both repugnancy and intrastate (as distinct from interstate) communications calls into question these bandwagon/appeal to tradition/appeal to authority/straw man/etc. narratives.

https://www.fcc.gov/general/digital-television-0

That’s ok, we might not need to ask, we can whisper, instead of bang, when we pluck those sweet-sweet airwave strings. That is to say, you turn on your tv to a static channel, and what do you see? Pure, beautiful chaos. White noise, they call it. We don’t hit the white noise with a hammer, that’s cavemen. Oh no, we caress mother nature, we gently ask her to to talk. And so, we modulate not by hitting her with a hammer, nobody likes to get hit by hammers, rather, we gently influence or modulate the existing white noise. The white noise remains white noise… to all appearances.

With our library, we are very much heard by anyone else with the same library. But with respect to mother nature’s white noise channels, we are only whispering. Not bothering anybody, as well, we are not heard by those pesky eavesdroppers, so much, per se.

It’s just noise to everybody else, but to our libraries and scripts, it is the song of the universe. God bless.

I built this Fractal Library over here -

https://josefkulovany.com/demo/12.1.26%20-%20Fractals/3sat%20library/

Using primarily this script - discover_rc.py

#!/usr/bin/env python3
"""
discover_rc.py

Iterative exact-structure discovery for rc_ladder_exact.py.

Search dimensions:
    n       ladder depth
    rho     geometric resistance ratio
    gamma   geometric capacitance ratio

R0=C0=1 to remove trivial dimensional scaling.

Identity:
    Exact equality of reduced rational transfer functions over Q(s).

No floating point. Standard library only.

Usage:
    py discover_rc.py --height 5 --max-n 12
    py discover_rc.py --height 7 --max-n 16
    py discover_rc.py --height 9 --max-n 24

Each run continues from discover_rc_state.json.
"""

from __future__ import annotations

import argparse
import hashlib
import json
from fractions import Fraction
from pathlib import Path

from rc_ladder_exact import (
    make_geometric_ladder,
    ladder_transfer,
    polynomial_json,
)


STATE_FILE = "discover_rc_state.json"
DISCOVERY_FILE = "discoveries.jsonl"
CANDIDATE_FILE = "candidate_history.jsonl"


def rational_height(x: Fraction) -> int:
    """Integer complexity of a reduced positive rational."""
    return max(x.numerator, x.denominator)


def rational_layer(height: int) -> list[Fraction]:
    """All positive reduced rationals whose height is <= height."""
    values = {
        Fraction(p, q)
        for p in range(1, height + 1)
        for q in range(1, height + 1)
    }
    return sorted(values, key=lambda x: (
        rational_height(x), x.numerator, x.denominator
    ))


def canonical_transfer(num, den):
    """
    Exact canonical identity.

    ladder_transfer() already reduces the rational function and normalizes
    the denominator leading coefficient to +1.
    """
    return {
        "numerator": polynomial_json(num),
        "denominator": polynomial_json(den),
    }


def signature_id(signature) -> str:
    payload = json.dumps(
        signature, sort_keys=True, separators=(",", ":")
    ).encode("utf-8")
    return hashlib.sha256(payload).hexdigest()


def parameter_id(n, rho, gamma) -> str:
    return f"{n}|{rho.numerator}/{rho.denominator}|{gamma.numerator}/{gamma.denominator}"


def load_state(path: Path):
    if not path.exists():
        return {
            "version": 1,
            "seen_parameters": [],
            "structures": {},
            "completed_height": 0,
            "completed_max_n": 0,
        }

    with path.open("r", encoding="utf-8") as f:
        state = json.load(f)

    state.setdefault("seen_parameters", [])
    state.setdefault("structures", {})
    state.setdefault("completed_height", 0)
    state.setdefault("completed_max_n", 0)
    return state


def save_state(path: Path, state):
    temporary = path.with_suffix(path.suffix + ".tmp")
    with temporary.open("w", encoding="utf-8") as f:
        json.dump(state, f, indent=2, sort_keys=True)
        f.write("\n")
    temporary.replace(path)


def append_jsonl(path: Path, record):
    with path.open("a", encoding="utf-8") as f:
        f.write(json.dumps(record, sort_keys=True) + "\n")


def discover(height_limit: int, max_n: int, state_path: Path,
             discovery_path: Path, history_path: Path):

    state = load_state(state_path)

    seen_parameters = set(state["seen_parameters"])
    structures = state["structures"]

    total_new_parameters = 0
    total_new_structures = 0
    total_known_structures = 0

    previous_height = int(state["completed_height"])

    if height_limit < previous_height:
        raise ValueError(
            f"Requested height {height_limit} is below saved height "
            f"{previous_height}. Increase the limit or use a new state file."
        )

    print("EXACT RC DISCOVERY")
    print("Search law: geometric series-R / geometric shunt-C")
    print("R0=C0=1")
    print("Identity: exact reduced transfer function")
    print(f"Previous height: {previous_height}")
    print(f"Target height:   {height_limit}")
    print(f"Target depth:    {max_n}")
    print()

    for height in range(1, height_limit + 1):
        if height <= previous_height:
            # A higher max_n can still introduce new parameter/depth pairs.
            pass

        ratios = rational_layer(height)

        # Only pairs containing at least one ratio from this new layer.
        # This makes the search incremental in rational complexity.
        pairs = [
            (rho, gamma)
            for rho in ratios
            for gamma in ratios
            if max(rational_height(rho), rational_height(gamma)) == height
        ]

        layer_new = 0
        layer_structures = 0

        for rho, gamma in pairs:
            for n in range(1, max_n + 1):
                pid = parameter_id(n, rho, gamma)

                if pid in seen_parameters:
                    continue

                R, C = make_geometric_ladder(
                    n, 1, 1, rho, gamma
                )

                num, den = ladder_transfer(R, C)

                signature = canonical_transfer(num, den)
                sid = signature_id(signature)

                candidate = {
                    "parameter_id": pid,
                    "n": n,
                    "R0": "1/1",
                    "C0": "1/1",
                    "rho": f"{rho.numerator}/{rho.denominator}",
                    "gamma": f"{gamma.numerator}/{gamma.denominator}",
                    "degree_numerator": len(num) - 1,
                    "degree_denominator": len(den) - 1,
                    "structure_id": sid,
                }

                seen_parameters.add(pid)
                total_new_parameters += 1
                layer_new += 1

                if sid not in structures:
                    structures[sid] = {
                        "structure_id": sid,
                        "signature": signature,
                        "representative": candidate,
                        "members": [candidate],
                        "member_count": 1,
                    }

                    total_new_structures += 1
                    layer_structures += 1

                    append_jsonl(discovery_path, {
                        "discovery_number": len(structures),
                        **candidate,
                        "transfer_function": signature,
                    })

                    status = "NEW STRUCTURE"

                else:
                    entry = structures[sid]

                    # SHA-256 is an index, not the mathematical
                    # equivalence criterion. Verify the full signature.
                    if entry["signature"] != signature:
                        raise RuntimeError(
                            "Signature hash collision; search halted."
                        )

                    entry["members"].append(candidate)
                    entry["member_count"] += 1
                    total_known_structures += 1
                    status = "known structure"

                append_jsonl(history_path, {
                    **candidate,
                    "status": status,
                })

        state["seen_parameters"] = sorted(seen_parameters)
        state["structures"] = structures
        state["completed_height"] = max(
            height, int(state["completed_height"])
        )
        state["completed_max_n"] = max(
            max_n, int(state["completed_max_n"])
        )

        save_state(state_path, state)

        print(
            f"height={height:3d} "
            f"ratios={len(ratios):4d} "
            f"pairs={len(pairs):6d} "
            f"new_parameters={layer_new:7d} "
            f"new_structures={layer_structures:6d} "
            f"total_structures={len(structures):7d}"
        )

    print()
    print("SEARCH COMPLETE")
    print(f"New parameterizations: {total_new_parameters}")
    print(f"New exact structures:  {total_new_structures}")
    print(f"Known-structure hits:  {total_known_structures}")
    print(f"Total exact structures: {len(structures)}")
    print(f"Total parameterizations: {len(seen_parameters)}")
    print()
    print(f"State:       {state_path}")
    print(f"Discoveries: {discovery_path}")
    print(f"History:     {history_path}")


def main():
    parser = argparse.ArgumentParser(
        description="Iterative exact RC fractal-structure discovery"
    )

    parser.add_argument(
        "--height", type=int, default=5,
        help="Maximum numerator/denominator complexity of rho and gamma"
    )
    parser.add_argument(
        "--max-n", type=int, default=12,
        help="Maximum ladder depth"
    )
    parser.add_argument(
        "--state", default=STATE_FILE
    )
    parser.add_argument(
        "--discoveries", default=DISCOVERY_FILE
    )
    parser.add_argument(
        "--history", default=CANDIDATE_FILE
    )

    args = parser.parse_args()

    if args.height < 1 or args.max_n < 1:
        parser.error("--height and --max-n must be positive")

    discover(
        args.height,
        args.max_n,
        Path(args.state),
        Path(args.discoveries),
        Path(args.history),
    )


if __name__ == "__main__":
    main()

Incidentally, I used a modification of my 3-sat technique to discover many new fractals (pat on the back, pat pat pat). The included script can help you to explore more ad infinitum, and you can, provided you provide the correct and prominent attribution, of course, and negotiate my reasonable fee by contacting me before your own claim to fame. Mouths to feed, you understand..

White Noise from Library Scripts

And this script got me started..

#!/usr/bin/env python3
"""static_mod.py - test: 'static is white unless modulated by the combinatorial fractal library'.
Model: x(t) = m(t) * w(t),  w = white carrier (zero bits, any seed), m = library atom (gate x slow Weierstrass AM).
Facts tested: (1) PSD stays flat (modulation invisible in the spectrum); (2) comodulation index across bands separates
modulated from plain / per-band-independent noise; (3) pursuit identifies m from the energy envelope; (4) bits; (5) LSD vs 2-realisation floor."""
import math, itertools, numpy as np
fs=8000; T=2.0; N=int(fs*T); t=np.arange(N)/fs; PHI=(1+5**.5)/2
def cantor(Tp,depth=3):
    x=(t/Tp)%1.0; ok=np.ones(N,bool)
    for _ in range(depth): x*=3; d=np.floor(x).astype(int); ok&=d!=1; x-=d
    return ok.astype(float)
def tm(L): return np.array([bin(i).count('1')%2 for i in (np.arange(N)/ (fs*L)).astype(int)],float)
def am(a,b,f0,M=3):
    y=sum(a**n*np.cos(2*np.pi*f0*b**n*t) for n in range(M)); return 1+0.8*y/np.abs(y).max()
GATES={'none':np.ones(N),'C2.0':cantor(2.0),'C1.0':cantor(1.0),'TM.10':tm(.10),'TM.20':tm(.20)}
AMS={'none':np.ones(N)}
for a in (.5,.7):
    for b in (PHI,2.):
        for f0 in (1.,2.,3.): AMS[f'W a{a} b{b:.2f} f{f0:g}']=am(a,b,f0)
LIB={(g,h):(GATES[g]*AMS[h]).clip(0)**1 for g in GATES for h in AMS}
LIB={k:v for k,v in LIB.items() if v.std()>1e-9 or k==('none','none')}
W_,H_=128,64; nT=(N-W_)//H_+1
def env(x): return np.array([np.mean(x[i*H_:i*H_+W_]**2) for i in range(nT)])
ATOM_E={k:env(v) for k,v in LIB.items()}      # frame-mean m^2 : note m enters x as amplitude, energy = m^2
LIBA={k:v for k,v in LIB.items()}
ATOM_E={k:env(v*np.ones(N)) for k,v in LIB.items()}   # env of m (as if carrier unit-variance): need m^2
ATOM_E={k:np.array([np.mean(v[i*H_:i*H_+W_]**2) for i in range(nT)]) for k,v in LIB.items()}
EDG=np.array([500,707,1000,1414,2000,2828,3900.]); FR=256;HOP=128
def bandenv(x):
    fb=np.fft.rfftfreq(FR,1/fs); band=np.digitize(fb,EDG)-1; w=np.hanning(FR); Tn=(len(x)-FR)//HOP+1
    S=np.array([np.abs(np.fft.rfft(w*x[i*HOP:i*HOP+FR]))**2 for i in range(Tn)])
    return np.array([S[:,band==b].sum(1) for b in range(len(EDG)-1)])
def comod(x):
    E=bandenv(x); E=E/E.mean(1,keepdims=True); C=np.corrcoef(E); return float(C[np.triu_indices(len(C),1)].mean())
def sfm(x):
    P=np.abs(np.fft.rfft(x))**2; P=P[5:]; return 10*np.log10(np.exp(np.mean(np.log(P+1e-30)))/P.mean())
def pursuit(x):
    s=env(x); best=(1e30,None)
    for k,a in ATOM_E.items():
        g=(a@s)/(a@a+1e-30); r=np.sum((s-g*a)**2)
        if r<best[0]: best=(r,k,g)
    return best[1],best[2],1-best[0]/np.sum((s-s.mean())**2+1e-30)
def lsd(x,y):
    fbn=np.fft.rfftfreq(FR,1/fs); 
    A=bandenv(x);B=bandenv(y); e=1e-5*A.max(); return float(np.sqrt(np.mean((10*np.log10((B+e)/(A+e)))**2)))
if __name__=="__main__":
    rng=np.random.default_rng(11); keys=list(LIB)
    print(f"modulator library: {len(keys)} atoms = gates({len(GATES)}) x slow-Weierstrass AM({len(AMS)}); {math.log2(len(keys)):.1f} bits/id")
    print("\n[1,2] flatness (SFM, 0 dB = white) and comodulation index over 6 bands >=500 Hz")
    w=rng.standard_normal(N); x_mod=w*LIB[('C1.0','W a0.5 b1.62 f2')]
    per=sum(rng.standard_normal(N)*0 for _ in range(1))
    # per-band independent modulation: filter bands separately with independent modulators
    def bandsplit(sig,lo,hi):
        X=np.fft.rfft(sig); f=np.fft.rfftfreq(len(sig),1/fs); X[(f<lo)|(f>=hi)]=0; return np.fft.irfft(X,len(sig))
    indep=sum(bandsplit(rng.standard_normal(N),lo,hi)*LIB[keys[rng.integers(len(keys))]] for lo,hi in zip(EDG[:-1],EDG[1:]))
    pink=np.fft.irfft((rng.standard_normal(N//2+1)+1j*rng.standard_normal(N//2+1))/np.sqrt(np.maximum(np.fft.rfftfreq(N,1/fs),20)),N)
    for nm,x in (("plain white",w),("white x library modulator",x_mod),("per-band INDEPENDENT modulators",indep),("pink, unmodulated",pink)):
        print(f"  {nm:34} SFM {sfm(x):6.2f} dB   comodulation {comod(x):5.2f}")
    print("\n[3,4,5] identify modulator from the energy envelope (30 random library atoms, fresh carrier each time)")
    ok=0;R2=[];Lf=[];Lo=[]
    for _ in range(30):
        k=keys[rng.integers(len(keys))]; x=rng.standard_normal(N)*LIB[k]
        kh,g,r2=pursuit(x); ok+=(kh==k); R2.append(r2)
        y=rng.standard_normal(N)*LIB[kh]; y2=rng.standard_normal(N)*LIB[k]
        Lf.append(lsd(x,y)); Lo.append(lsd(x,y2))
    bits=math.log2(len(keys))+6
    print(f"  exact atom identified {ok}/30 | envelope R^2 mean {np.mean(R2):.2f} | decoded-vs-original LSD {np.mean(Lf):.2f} dB vs oracle (true atom, new carrier) {np.mean(Lo):.2f} dB")
    print(f"  cost: {bits:.0f} bits per {T:.0f} s ({bits/T:.0f} b/s) vs direct 125-fps x 3-bit envelope = {125*3} b/s; waveform SNR is ~0 dB by design (carrier not coded)")
    print("\n[negative control] plain white fed to the pursuit: best atom, gain, R^2 (chance-level R^2 expected small)")
    for _ in range(3): print("  ",pursuit(rng.standard_normal(N)))

For which I upgraded to this script:

static_mod_v2.py


#!/usr/bin/env python3
"""
static_mod_v2.py

Combinatorial Fractal Static — multi-realization experiment.

Hypothesis:
    x[n] = m[n] * w[n]

    w[n] = independent zero-mean white Gaussian carrier
    m[n] = atom selected from a finite combinatorial fractal library

Tests:
    1. Ensemble PSD flatness.
    2. Single-realization PSD flatness.
    3. Shared modulation comodulation across frequency bands.
    4. Independent per-band modulation negative control.
    5. Energy-envelope atom identification.
    6. Atom ambiguity and equivalence classes.
    7. Independent-carrier reconstruction floor.
    8. Empirical distinguishable-library size.
    9. Plain white-noise negative control.

Dependencies:
    Python 3.10+
    NumPy

No SciPy, sklearn, or external datasets.

Usage:
    py static_mod_v2.py
    py static_mod_v2.py --trials 100
    py static_mod_v2.py --trials 100 --stages 4
    py static_mod_v2.py --seed 42 --trials 60
    py static_mod_v2.py --duration 4 --trials 100

Interpretation:
    Nominal bits = log2(number of library atoms).
    Effective bits = log2(number of distinguishable envelope classes).

    Effective bits are a codebook property, not a demonstrated
    error-free communication capacity.
"""

import argparse
import math
from dataclasses import dataclass

import numpy as np


# ------------------------------------------------------------
# Configuration
# ------------------------------------------------------------

@dataclass
class Config:
    fs: int = 8000
    duration: float = 2.0
    trials: int = 60
    seed: int = 11

    envelope_window: int = 128
    envelope_hop: int = 64

    fft_size: int = 256
    band_hop: int = 128

    equivalence_threshold: float = 0.999
    ambiguity_threshold: float = 0.995

    noise_floor: float = 1e-12


PHI = (1.0 + math.sqrt(5.0)) / 2.0

EDGES = np.array(
    [500, 707, 1000, 1414, 2000, 2828, 3900],
    dtype=float
)


# ------------------------------------------------------------
# Argument parsing
# ------------------------------------------------------------

def parse_args():
    p = argparse.ArgumentParser(
        description="Combinatorial fractal static experiment"
    )

    p.add_argument("--fs", type=int, default=8000)
    p.add_argument("--duration", type=float, default=2.0)
    p.add_argument("--trials", type=int, default=60)
    p.add_argument("--seed", type=int, default=11)

    p.add_argument("--stages", type=int, default=3)
    p.add_argument("--window", type=int, default=128)
    p.add_argument("--hop", type=int, default=64)

    p.add_argument("--equivalence", type=float, default=0.999)
    p.add_argument("--ambiguity", type=float, default=0.995)

    return p.parse_args()


# ------------------------------------------------------------
# Fractal library
# ------------------------------------------------------------

def cantor_gate(t, period, depth=3):
    """
    Ternary Cantor gate.

    Returns a binary mask.
    """
    x = (t / period) % 1.0
    ok = np.ones(len(t), dtype=bool)

    for _ in range(depth):
        x *= 3.0
        digit = np.floor(x).astype(int)

        ok &= digit != 1
        x -= digit

    return ok.astype(float)


def thue_morse_gate(t, fs, period):
    """
    Time-domain Thue-Morse parity gate.
    """
    index = (t / period).astype(np.int64)
    parity = np.fromiter(
        (i.bit_count() & 1 for i in index),
        dtype=np.int8,
        count=len(index)
    )

    return parity.astype(float)


def weierstrass_am(t, a, b, f0, stages=3):
    """
    Slow Weierstrass amplitude modulation.

    Normalized to remain nonnegative.
    """
    y = np.zeros_like(t)

    for n in range(stages):
        y += a**n * np.cos(
            2.0 * np.pi * f0 * b**n * t
        )

    peak = np.max(np.abs(y))

    if peak < 1e-15:
        return np.ones_like(t)

    return 1.0 + 0.8 * y / peak


def build_library(t, fs, stages):
    gates = {
        "none": np.ones_like(t),
        "C2.0": cantor_gate(t, 2.0),
        "C1.0": cantor_gate(t, 1.0),
        "TM.10": thue_morse_gate(t, fs, 0.10),
        "TM.20": thue_morse_gate(t, fs, 0.20),
    }

    ams = {
        "none": np.ones_like(t)
    }

    for a in (0.5, 0.7):
        for b in (PHI, 2.0):
            for f0 in (1.0, 2.0, 3.0):
                name = f"W a{a} b{b:.3f} f{f0:g}"

                ams[name] = weierstrass_am(
                    t, a, b, f0, stages
                )

    library = {}

    for gate_name, gate in gates.items():
        for am_name, am in ams.items():

            atom = gate * am

            if atom.std() > 1e-9:
                library[(gate_name, am_name)] = atom

            elif gate_name == "none" and am_name == "none":
                library[(gate_name, am_name)] = atom

    return library, gates, ams


# ------------------------------------------------------------
# Envelope extraction
# ------------------------------------------------------------

def frame_energy(x, window, hop):
    """
    Mean-square energy in overlapping frames.
    """
    if len(x) < window:
        raise ValueError("Signal shorter than envelope window")

    starts = np.arange(
        0,
        len(x) - window + 1,
        hop
    )

    frames = np.stack([
        x[i:i + window] for i in starts
    ])

    return np.mean(frames * frames, axis=1)


def normalize_template(x, floor=1e-12):
    """
    Remove absolute gain and center the template.

    This makes identification independent of carrier amplitude.
    """
    x = np.asarray(x, dtype=float)

    x = x / max(np.mean(x), floor)
    x = x - np.mean(x)

    norm = np.linalg.norm(x)

    if norm < floor:
        return np.zeros_like(x)

    return x / norm


def build_envelope_templates(
    library,
    window,
    hop
):
    templates = {}

    for key, atom in library.items():
        e = frame_energy(atom, window, hop)
        templates[key] = normalize_template(e)

    return templates


# ------------------------------------------------------------
# Atom similarity and equivalence
# ------------------------------------------------------------

def similarity_matrix(templates, keys):
    matrix = np.stack([
        templates[k] for k in keys
    ])

    return matrix @ matrix.T


def build_equivalence_classes(
    similarity,
    keys,
    threshold
):
    """
    Connected components of the similarity graph.

    If A resembles B and B resembles C, they belong
    to the same equivalence class.
    """
    n = len(keys)
    parent = list(range(n))

    def find(x):
        while parent[x] != x:
            parent[x] = parent[parent[x]]
            x = parent[x]
        return x

    def union(a, b):
        ra = find(a)
        rb = find(b)

        if ra != rb:
            parent[rb] = ra

    for i in range(n):
        for j in range(i + 1, n):
            if similarity[i, j] >= threshold:
                union(i, j)

    groups = {}

    for i, key in enumerate(keys):
        root = find(i)
        groups.setdefault(root, []).append(key)

    return list(groups.values())


# ------------------------------------------------------------
# Envelope pursuit
# ------------------------------------------------------------

def pursuit(
    x,
    templates,
    keys,
    window,
    hop,
    ambiguity_threshold
):
    """
    Normalized energy-envelope correlation pursuit.

    Returns:
        best atom
        gain
        envelope R2
        second-best score
        ambiguity flag
        complete score vector
    """
    observed = frame_energy(x, window, hop)

    y = normalize_template(observed)

    scores = np.array([
        templates[k] @ y
        for k in keys
    ])

    order = np.argsort(scores)[::-1]

    best_i = int(order[0])
    second_i = int(order[1]) if len(order) > 1 else best_i

    best_key = keys[best_i]

    atom_energy = frame_energy(
        np.asarray(x) * 0 + 1.0,
        window,
        hop
    )

    # Estimate gain against the original unnormalized template.
    # The gain is computed directly from the energy templates.
    template = frame_energy(
        LIBRARY[best_key],
        window,
        hop
    )

    gain = (
        np.dot(template, observed)
        / (np.dot(template, template) + 1e-30)
    )

    residual = observed - gain * template

    denominator = np.sum(
        (observed - observed.mean())**2
    ) + 1e-30

    r2 = 1.0 - np.sum(residual**2) / denominator

    ambiguous = (
        scores[second_i] >= ambiguity_threshold
    )

    return (
        best_key,
        float(gain),
        float(r2),
        float(scores[second_i]),
        bool(ambiguous),
        scores
    )


# ------------------------------------------------------------
# Frequency-domain measurements
# ------------------------------------------------------------

def periodogram(x):
    """
    Rectangular-window periodogram.

    Rectangular window is intentional: for independent
    white samples with deterministic time-varying variance,
    expected periodogram power is flat across Fourier bins.
    """
    return np.abs(np.fft.rfft(x))**2 / len(x)


def spectral_flatness_db(power):
    power = np.asarray(power)[1:]

    power = np.maximum(
        power,
        1e-30
    )

    return float(
        10.0 * np.log10(
            np.exp(np.mean(np.log(power)))
            / np.mean(power)
        )
    )


def ensemble_spectrum(
    atom,
    rng,
    trials
):
    """
    Average periodograms over independent carrier seeds.
    """
    result = None

    for _ in range(trials):
        x = atom * rng.standard_normal(len(atom))
        p = periodogram(x)

        if result is None:
            result = p
        else:
            result += p

    return result / trials


# ------------------------------------------------------------
# Band envelope and comodulation
# ------------------------------------------------------------

def band_envelopes(x, fs, fft_size, hop):
    """
    Short-time frequency-band energy.

    Returns:
        shape = (number_of_bands, number_of_frames)
    """
    frequencies = np.fft.rfftfreq(
        fft_size,
        d=1.0 / fs
    )

    band_index = np.digitize(
        frequencies,
        EDGES
    ) - 1

    window = np.hanning(fft_size)

    starts = np.arange(
        0,
        len(x) - fft_size + 1,
        hop
    )

    output = np.zeros(
        (len(EDGES) - 1, len(starts)),
        dtype=float
    )

    for frame_index, start in enumerate(starts):
        segment = (
            x[start:start + fft_size] * window
        )

        spectrum = np.abs(
            np.fft.rfft(segment)
        )**2

        for band in range(len(EDGES) - 1):
            output[band, frame_index] = np.sum(
                spectrum[band_index == band]
            )

    return output


def comodulation_index(envelopes):
    """
    Mean pairwise correlation between normalized
    frequency-band energy envelopes.
    """
    envelopes = np.asarray(envelopes)

    means = envelopes.mean(axis=1, keepdims=True)

    normalized = envelopes / np.maximum(
        means,
        1e-30
    )

    correlation = np.corrcoef(normalized)

    indices = np.triu_indices(
        len(envelopes),
        k=1
    )

    return float(np.nanmean(correlation[indices]))


def band_split(x, fs, lo, hi):
    """
    Isolate one frequency band using an FFT mask.
    """
    spectrum = np.fft.rfft(x)
    frequencies = np.fft.rfftfreq(
        len(x),
        1.0 / fs
    )

    spectrum[
        (frequencies < lo) |
        (frequencies >= hi)
    ] = 0

    return np.fft.irfft(
        spectrum,
        n=len(x)
    )


# ------------------------------------------------------------
# Spectral reconstruction comparison
# ------------------------------------------------------------

def spectral_lsd(
    atom_a,
    atom_b,
    rng,
    trials,
    floor=1e-12
):
    """
    Compare ensemble-averaged spectra.

    Independent carrier realizations are used for both
    atoms so the comparison measures spectral structure,
    not accidental waveform alignment.
    """
    pa = ensemble_spectrum(
        atom_a, rng, trials
    )

    pb = ensemble_spectrum(
        atom_b, rng, trials
    )

    eps = floor * max(
        np.max(pa),
        np.max(pb),
        1.0
    )

    return float(
        np.sqrt(
            np.mean(
                (
                    10.0 * np.log10(pb + eps)
                    - 10.0 * np.log10(pa + eps)
                )**2
            )
        )
    )


# ------------------------------------------------------------
# Main experiment
# ------------------------------------------------------------

def main():
    args = parse_args()

    if args.fs <= 0 or args.duration <= 0:
        raise ValueError("Sampling rate and duration must be positive")

    if args.trials < 2:
        raise ValueError("Use at least two trials")

    if args.stages < 1:
        raise ValueError("Stages must be at least one")

    cfg = Config(
        fs=args.fs,
        duration=args.duration,
        trials=args.trials,
        seed=args.seed,
        envelope_window=args.window,
        envelope_hop=args.hop,
        equivalence_threshold=args.equivalence,
        ambiguity_threshold=args.ambiguity
    )

    n = int(cfg.fs * cfg.duration)
    t = np.arange(n) / cfg.fs

    rng = np.random.default_rng(cfg.seed)

    global LIBRARY

    LIBRARY, gates, ams = build_library(
        t,
        cfg.fs,
        args.stages
    )

    keys = list(LIBRARY)

    templates = build_envelope_templates(
        LIBRARY,
        cfg.envelope_window,
        cfg.envelope_hop
    )

    similarity = similarity_matrix(
        templates,
        keys
    )

    classes = build_equivalence_classes(
        similarity,
        keys,
        cfg.equivalence_threshold
    )

    class_lookup = {}

    for class_index, group in enumerate(classes):
        for key in group:
            class_lookup[key] = class_index

    nominal_bits = math.log2(len(keys))
    effective_bits = math.log2(len(classes))

    print()
    print("=" * 72)
    print("STATIC MOD V2 — COMBINATORIAL FRACTAL STATIC")
    print("=" * 72)

    print(f"Sampling rate:             {cfg.fs} Hz")
    print(f"Duration:                  {cfg.duration:.2f} s")
    print(f"Samples:                   {n:,}")
    print(f"Carrier trials:            {cfg.trials}")
    print(f"Envelope window / hop:     {cfg.envelope_window} / {cfg.envelope_hop}")
    print(f"Weierstrass stages:        {args.stages}")
    print()

    print("[LIBRARY]")
    print(f"  Gates:                   {len(gates)}")
    print(f"  AM atoms:                {len(ams)}")
    print(f"  Valid combinations:     {len(keys)}")
    print(f"  Nominal bits / ID:       {nominal_bits:.3f}")
    print(f"  Envelope classes:       {len(classes)}")
    print(f"  Effective bits / ID:     {effective_bits:.3f}")
    print()

    print("[1] SPECTRAL FLATNESS")
    print("    Single realization versus ensemble average")

    white_power = np.zeros(n // 2 + 1)

    for _ in range(cfg.trials):
        w = rng.standard_normal(n)
        white_power += periodogram(w)

    white_power /= cfg.trials

    white_sfm = spectral_flatness_db(white_power)

    selected_key = ("C1.0", next(
        k for k in ams if k.startswith("W a0.5")
    ))

    selected_atom = LIBRARY[selected_key]

    one_carrier = (
        selected_atom * rng.standard_normal(n)
    )

    single_sfm = spectral_flatness_db(
        periodogram(one_carrier)
    )

    modulated_power = ensemble_spectrum(
        selected_atom,
        rng,
        cfg.trials
    )

    ensemble_sfm = spectral_flatness_db(
        modulated_power
    )

    print(f"  White ensemble SFM:      {white_sfm:8.3f} dB")
    print(f"  Modulated single SFM:    {single_sfm:8.3f} dB")
    print(f"  Modulated ensemble SFM:  {ensemble_sfm:8.3f} dB")
    print()

    print("[2] COMODULATION")
    print("    Six frequency bands, 500–3900 Hz")

    plain = rng.standard_normal(n)

    shared = (
        rng.standard_normal(n) * selected_atom
    )

    independent = np.zeros(n)

    for lo, hi in zip(EDGES[:-1], EDGES[1:]):
        carrier = rng.standard_normal(n)

        carrier_band = band_split(
            carrier,
            cfg.fs,
            lo,
            hi
        )

        atom_key = keys[
            rng.integers(len(keys))
        ]

        independent += (
            carrier_band * LIBRARY[atom_key]
        )

    pink_frequency = np.fft.rfftfreq(
        n,
        d=1.0 / cfg.fs
    )

    pink_scale = 1.0 / np.sqrt(
        np.maximum(pink_frequency, 20.0)
    )

    pink = np.fft.irfft(
        (
            rng.standard_normal(n // 2 + 1)
            + 1j * rng.standard_normal(n // 2 + 1)
        ) * pink_scale,
        n=n
    )

    for name, signal in (
        ("Plain white", plain),
        ("Shared library modulation", shared),
        ("Independent band modulation", independent),
        ("Unmodulated pink", pink),
    ):
        envelopes = band_envelopes(
            signal,
            cfg.fs,
            256,
            128
        )

        print(
            f"  {name:34s}"
            f" comodulation={comodulation_index(envelopes): .4f}"
        )

    print()

    print("[3] ENVELOPE PURSUIT")
    print("    Fresh carrier for every observation")

    correct = 0
    class_correct = 0
    ambiguous_count = 0

    r2_values = []
    best_scores = []
    second_scores = []
    gain_values = []

    confusion = {}

    trial_records = []

    for trial in range(cfg.trials):
        true_key = keys[
            rng.integers(len(keys))
        ]

        x = (
            rng.standard_normal(n)
            * LIBRARY[true_key]
        )

        (
            predicted,
            gain,
            r2,
            second_score,
            ambiguous,
            scores
        ) = pursuit(
            x,
            templates,
            keys,
            cfg.envelope_window,
            cfg.envelope_hop,
            cfg.ambiguity_threshold
        )

        exact = predicted == true_key

        same_class = (
            class_lookup[predicted]
            == class_lookup[true_key]
        )

        correct += int(exact)
        class_correct += int(same_class)
        ambiguous_count += int(ambiguous)

        r2_values.append(r2)
        best_scores.append(float(np.max(scores)))
        second_scores.append(second_score)
        gain_values.append(gain)

        confusion[(true_key, predicted)] = (
            confusion.get((true_key, predicted), 0) + 1
        )

        trial_records.append(
            (true_key, predicted, exact, same_class, ambiguous)
        )

    print(f"  Exact atom recovery:     {correct}/{cfg.trials} ({100*correct/cfg.trials:.1f}%)")
    print(f"  Class recovery:          {class_correct}/{cfg.trials} ({100*class_correct/cfg.trials:.1f}%)")
    print(f"  Ambiguous predictions:   {ambiguous_count}/{cfg.trials}")
    print(f"  Mean envelope R2:         {np.mean(r2_values):.4f}")
    print(f"  Mean best correlation:   {np.mean(best_scores):.4f}")
    print(f"  Mean second correlation: {np.mean(second_scores):.4f}")
    print(f"  Mean fitted gain:        {np.mean(gain_values):.4f}")
    print()

    print("[4] IDENTIFIABILITY")
    print("    Most similar atom pairs")

    pair_indices = np.triu_indices(
        len(keys),
        k=1
    )

    pair_scores = similarity[pair_indices]

    top = np.argsort(pair_scores)[::-1][:10]

    for index in top:
        i = pair_indices[0][index]
        j = pair_indices[1][index]

        print(
            f"  {pair_scores[index]:.5f}  "
            f"{keys[i]}  <->  {keys[j]}"
        )

    print()

    print("[5] RECONSTRUCTION FLOOR")
    print("    Different carrier seeds, same modulation")

    oracle_lsd = []
    decoded_lsd = []

    for true_key, predicted, exact, same_class, ambiguous in trial_records:

        true_atom = LIBRARY[true_key]
        predicted_atom = LIBRARY[predicted]

        oracle_lsd.append(
            spectral_lsd(
                true_atom,
                true_atom,
                rng,
                max(2, min(8, cfg.trials))
            )
        )

        decoded_lsd.append(
            spectral_lsd(
                true_atom,
                predicted_atom,
                rng,
                max(2, min(8, cfg.trials))
            )
        )

    print(f"  Oracle same-atom LSD:    {np.mean(oracle_lsd):.4f} dB")
    print(f"  Decoded-atom LSD:        {np.mean(decoded_lsd):.4f} dB")
    print()

    print("[6] PLAIN WHITE NEGATIVE CONTROL")
    print("    Library pursuit on unmodulated white noise")

    negative_r2 = []
    negative_scores = []

    for _ in range(min(30, cfg.trials)):
        x = rng.standard_normal(n)

        (
            predicted,
            gain,
            r2,
            second_score,
            ambiguous,
            scores
        ) = pursuit(
            x,
            templates,
            keys,
            cfg.envelope_window,
            cfg.envelope_hop,
            cfg.ambiguity_threshold
        )

        negative_r2.append(r2)
        negative_scores.append(float(np.max(scores)))

    print(f"  Mean negative-control R2: {np.mean(negative_r2):.4f}")
    print(f"  Mean best correlation:   {np.mean(negative_scores):.4f}")
    print()

    print("[7] INFORMATION ACCOUNTING")

    print(f"  Nominal library bits:    {nominal_bits:.3f}")
    print(f"  Effective class bits:    {effective_bits:.3f}")

    nominal_rate = nominal_bits / cfg.duration
    effective_rate = effective_bits / cfg.duration

    print(f"  Nominal rate:            {nominal_rate:.3f} bits/s")
    print(f"  Class rate:              {effective_rate:.3f} bits/s")

    print(
        f"  Exact recovery rate:     "
        f"{correct/cfg.trials:.4f}"
    )

    print(
        f"  Class recovery rate:     "
        f"{class_correct/cfg.trials:.4f}"
    )

    print()
    print("=" * 72)
    print("END OF EXPERIMENT")
    print("=" * 72)

    print()
    print("INTERPRETATION:")
    print("  1. Ensemble PSD tests spectral invisibility in expectation.")
    print("  2. Comodulation tests shared modulation across frequency bands.")
    print("  3. Exact recovery tests whether individual atoms are identifiable.")
    print("  4. Class recovery accounts for envelope-equivalent atoms.")
    print("  5. Oracle LSD measures finite-estimation spectral variation.")
    print("  6. Decoded LSD measures spectral reconstruction loss.")
    print("  7. Effective bits count distinguishable template classes,")
    print("     not guaranteed error-free communication capacity.")
    print()


if __name__ == "__main__":
    main()

v3

#!/usr/bin/env python3
"""
static_mod_v3.py — wideband combinatorial-fractal static experiment

Expands BOTH:
  • carrier bandwidth: default 192 kHz sampling, 0–90 kHz analysis
  • modulation bandwidth: fast Cantor/Thue-Morse gates and multiscale AM

The experiment still tests x[n] = m[n] * w[n], where w is an independent
white carrier and m is selected from a deterministic modulation library.

Dependencies: Python 3.10+, NumPy
No SciPy, sklearn, or external datasets.

Examples:
    py static_mod_v3.py
    py static_mod_v3.py --fs 192000 --duration 1 --trials 24
    py static_mod_v3.py --fs 96000 --max-frequency 44000
    py static_mod_v3.py --stages 5 --trials 40

Important:
  Sampling rate sets the available carrier bandwidth.
  The modulation atom sets the amplitude-envelope bandwidth.
  These are measured separately; neither is inferred from the other.
"""

import argparse
import math
from dataclasses import dataclass

import numpy as np


PHI = (1.0 + math.sqrt(5.0)) / 2.0


@dataclass
class Config:
    fs: int
    duration: float
    trials: int
    seed: int
    max_frequency: float
    bands: int
    fft_size: int
    band_hop: int
    envelope_window: int
    envelope_hop: int
    stages: int
    equivalence_threshold: float
    ambiguity_threshold: float


def parse_args():
    p = argparse.ArgumentParser(
        description="Wideband combinatorial-fractal static experiment"
    )
    p.add_argument("--fs", type=int, default=192000)
    p.add_argument("--duration", type=float, default=1.0)
    p.add_argument("--trials", type=int, default=24)
    p.add_argument("--seed", type=int, default=11)
    p.add_argument("--max-frequency", type=float, default=90000.0)
    p.add_argument("--bands", type=int, default=96)
    p.add_argument("--fft-size", type=int, default=4096)
    p.add_argument("--band-hop", type=int, default=1024)
    p.add_argument("--window", type=int, default=512)
    p.add_argument("--hop", type=int, default=128)
    p.add_argument("--stages", type=int, default=4)
    p.add_argument("--equivalence", type=float, default=0.999)
    p.add_argument("--ambiguity", type=float, default=0.995)
    return p.parse_args()


def cantor_gate(t, period, depth=3):
    x = (t / period) % 1.0
    ok = np.ones(len(t), dtype=bool)
    for _ in range(depth):
        x *= 3.0
        digit = np.floor(x).astype(np.int64)
        ok &= digit != 1
        x -= digit
    return ok.astype(float)


def thue_morse_gate(t, period):
    index = np.floor(t / period).astype(np.int64)
    parity = np.fromiter(
        (int(i).bit_count() & 1 for i in index),
        dtype=np.int8,
        count=len(index),
    )
    return parity.astype(float)


def weierstrass_am(t, a, b, f0, stages):
    """Nonnegative multiscale AM atom, normalized around unity."""
    y = np.zeros_like(t, dtype=np.float64)
    for level in range(stages):
        y += (a ** level) * np.cos(
            2.0 * np.pi * f0 * (b ** level) * t
        )
    peak = float(np.max(np.abs(y)))
    if peak < 1e-15:
        return np.ones_like(t)
    return 1.0 + 0.8 * y / peak


def build_library(t, stages):
    # Gate periods descend into the millisecond range at the default rate.
    gates = {"none": np.ones_like(t)}
    for period in (0.064, 0.016, 0.004, 0.001):
        gates[f"C{period:g}"] = cantor_gate(t, period)
    for period in (0.032, 0.008, 0.002, 0.0005):
        gates[f"TM{period:g}"] = thue_morse_gate(t, period)

    # Base frequencies span slow structure through fast envelope changes.
    ams = {"none": np.ones_like(t)}
    for a in (0.5, 0.7):
        for b in (PHI, 2.0):
            for f0 in (2.0, 8.0, 32.0, 128.0, 256.0):
                name = f"W_a{a:g}_b{b:.3f}_f{f0:g}"
                ams[name] = weierstrass_am(t, a, b, f0, stages)

    library = {}
    for gate_name, gate in gates.items():
        for am_name, am in ams.items():
            atom = gate * am
            if atom.std() > 1e-10 or (
                gate_name == "none" and am_name == "none"
            ):
                library[(gate_name, am_name)] = atom.astype(np.float64)

    return library, gates, ams


def frame_energy(x, window, hop):
    if len(x) < window:
        raise ValueError(
            f"Signal ({len(x)} samples) shorter than window ({window})"
        )
    starts = np.arange(0, len(x) - window + 1, hop)
    frames = np.stack([x[i:i + window] for i in starts])
    return np.mean(frames * frames, axis=1)


def normalize_template(x, floor=1e-12):
    x = np.asarray(x, dtype=np.float64)
    x = x / max(float(np.mean(x)), floor)
    x = x - np.mean(x)
    norm = float(np.linalg.norm(x))
    return x / norm if norm > floor else np.zeros_like(x)


def build_envelope_templates(library, window, hop):
    return {
        key: normalize_template(frame_energy(atom, window, hop))
        for key, atom in library.items()
    }


def similarity_matrix(templates, keys):
    matrix = np.stack([templates[k] for k in keys])
    return matrix @ matrix.T


def build_equivalence_classes(similarity, threshold):
    n = len(similarity)
    parent = list(range(n))

    def find(x):
        while parent[x] != x:
            parent[x] = parent[parent[x]]
            x = parent[x]
        return x

    for i in range(n):
        for j in range(i + 1, n):
            if similarity[i, j] >= threshold:
                a, b = find(i), find(j)
                if a != b:
                    parent[b] = a

    groups = {}
    for i in range(n):
        groups.setdefault(find(i), []).append(i)
    return list(groups.values())


def pursuit(x, library, templates, keys, window, hop, ambiguity_threshold):
    observed = frame_energy(x, window, hop)
    y = normalize_template(observed)
    scores = np.array([templates[k] @ y for k in keys])
    order = np.argsort(scores)[::-1]
    best_i = int(order[0])
    second_i = int(order[1]) if len(order) > 1 else best_i
    best_key = keys[best_i]

    template_energy = frame_energy(library[best_key], window, hop)
    gain = float(
        np.dot(template_energy, observed)
        / (np.dot(template_energy, template_energy) + 1e-30)
    )
    residual = observed - gain * template_energy
    denominator = np.sum((observed - observed.mean()) ** 2) + 1e-30
    r2 = 1.0 - np.sum(residual ** 2) / denominator

    return (
        best_key,
        gain,
        float(r2),
        float(scores[second_i]),
        bool(scores[second_i] >= ambiguity_threshold),
        scores,
    )


def periodogram(x):
    return np.abs(np.fft.rfft(x)) ** 2 / len(x)


def spectral_flatness_db(power):
    p = np.maximum(np.asarray(power)[1:], 1e-30)
    return float(10.0 * np.log10(np.exp(np.mean(np.log(p))) / np.mean(p)))


def ensemble_spectrum(atom, rng, trials):
    result = np.zeros(len(atom) // 2 + 1, dtype=np.float64)
    for _ in range(trials):
        result += periodogram(atom * rng.standard_normal(len(atom)))
    return result / trials


def band_envelopes(x, fs, edges, fft_size, hop):
    frequencies = np.fft.rfftfreq(fft_size, d=1.0 / fs)
    band_index = np.digitize(frequencies, edges) - 1
    window = np.hanning(fft_size)
    starts = np.arange(0, len(x) - fft_size + 1, hop)
    output = np.zeros((len(edges) - 1, len(starts)), dtype=np.float64)

    for frame_index, start in enumerate(starts):
        segment = x[start:start + fft_size] * window
        spectrum = np.abs(np.fft.rfft(segment)) ** 2
        for band in range(len(edges) - 1):
            bins = band_index == band
            output[band, frame_index] = (
                np.sum(spectrum[bins]) if np.any(bins) else 0.0
            )
    return output


def comodulation_index(envelopes):
    means = envelopes.mean(axis=1, keepdims=True)
    normalized = envelopes / np.maximum(means, 1e-30)
    corr = np.corrcoef(normalized)
    upper = np.triu_indices(len(envelopes), k=1)
    values = corr[upper]
    values = values[np.isfinite(values)]
    return float(np.mean(values)) if len(values) else float("nan")


def band_split(x, fs, lo, hi):
    spectrum = np.fft.rfft(x)
    frequencies = np.fft.rfftfreq(len(x), 1.0 / fs)
    spectrum[(frequencies < lo) | (frequencies >= hi)] = 0
    return np.fft.irfft(spectrum, n=len(x))


def spectral_lsd(atom_a, atom_b, rng, trials):
    pa = ensemble_spectrum(atom_a, rng, trials)
    pb = ensemble_spectrum(atom_b, rng, trials)
    eps = 1e-12 * max(float(np.max(pa)), float(np.max(pb)), 1.0)
    delta = 10.0 * np.log10(pb + eps) - 10.0 * np.log10(pa + eps)
    return float(np.sqrt(np.mean(delta * delta)))


def modulation_spectrum(atom, fs):
    """Return the highest frequency containing 99% of non-DC AM power."""
    centered = atom - np.mean(atom)
    power = np.abs(np.fft.rfft(centered)) ** 2
    frequencies = np.fft.rfftfreq(len(atom), 1.0 / fs)
    if len(power) <= 1 or np.sum(power[1:]) <= 1e-30:
        return 0.0
    cumulative = np.cumsum(power[1:])
    index = int(np.searchsorted(cumulative, 0.99 * cumulative[-1]))
    return float(frequencies[min(index + 1, len(frequencies) - 1)])


def main():
    args = parse_args()
    if args.fs <= 0 or args.duration <= 0 or args.trials < 2:
        raise ValueError("fs/duration must be positive and trials must be >= 2")
    if args.stages < 1 or args.bands < 2:
        raise ValueError("stages must be >= 1 and bands must be >= 2")
    if args.max_frequency <= 0 or args.max_frequency >= args.fs / 2:
        raise ValueError("--max-frequency must be below Nyquist")
    if args.fft_size < 16 or args.window < 8:
        raise ValueError("FFT and envelope windows are too small")

    cfg = Config(
        fs=args.fs,
        duration=args.duration,
        trials=args.trials,
        seed=args.seed,
        max_frequency=args.max_frequency,
        bands=args.bands,
        fft_size=args.fft_size,
        band_hop=args.band_hop,
        envelope_window=args.window,
        envelope_hop=args.hop,
        stages=args.stages,
        equivalence_threshold=args.equivalence,
        ambiguity_threshold=args.ambiguity,
    )

    n = int(cfg.fs * cfg.duration)
    t = np.arange(n, dtype=np.float64) / cfg.fs
    rng = np.random.default_rng(cfg.seed)
    library, gates, ams = build_library(t, cfg.stages)
    keys = list(library)

    templates = build_envelope_templates(
        library, cfg.envelope_window, cfg.envelope_hop
    )
    similarity = similarity_matrix(templates, keys)
    classes = build_equivalence_classes(
        similarity, cfg.equivalence_threshold
    )
    class_lookup = {}
    for class_index, group in enumerate(classes):
        for index in group:
            class_lookup[keys[index]] = class_index

    nominal_bits = math.log2(len(keys))
    effective_bits = math.log2(len(classes))
    selected_key = next(
        key for key in keys
        if key[0] == "C0.016" and key[1].startswith("W_a0.5_b1.618_f32")
    )
    selected_atom = library[selected_key]
    edges = np.linspace(0.0, cfg.max_frequency, cfg.bands + 1)

    print()
    print("=" * 76)
    print("STATIC MOD V3 — WIDEBAND COMBINATORIAL FRACTAL STATIC")
    print("=" * 76)
    print(f"Sampling rate:                 {cfg.fs:,} Hz")
    print(f"Nyquist limit:                 {cfg.fs / 2:,.1f} Hz")
    print(f"Analyzed carrier bandwidth:    0–{cfg.max_frequency:,.1f} Hz")
    print(f"Carrier bandwidth vs v2:       {cfg.max_frequency / 3900.0:.1f}x")
    print(f"Duration / samples:            {cfg.duration:.3f} s / {n:,}")
    print(f"Frequency bands:                {cfg.bands}")
    print(f"Band FFT / hop:                 {cfg.fft_size} / {cfg.band_hop}")
    print(f"Envelope window / hop:          {cfg.envelope_window} / {cfg.envelope_hop}")
    print(f"Envelope frame interval:        {cfg.envelope_hop / cfg.fs * 1000:.3f} ms")
    print(f"Weierstrass stages:             {cfg.stages}")
    print()

    print("[LIBRARY]")
    print(f"  Gate atoms:                   {len(gates)}")
    print(f"  AM atoms:                     {len(ams)}")
    print(f"  Valid combinations:           {len(keys)}")
    print(f"  Nominal bits / atom:           {nominal_bits:.3f}")
    print(f"  Envelope equivalence classes: {len(classes)}")
    print(f"  Effective bits / class:        {effective_bits:.3f}")
    print(f"  Selected atom 99% AM extent:   {modulation_spectrum(selected_atom, cfg.fs):,.1f} Hz")
    print()

    print("[1] SPECTRAL FLATNESS")
    white_power = np.zeros(n // 2 + 1)
    for _ in range(cfg.trials):
        white_power += periodogram(rng.standard_normal(n))
    white_power /= cfg.trials
    one_carrier = selected_atom * rng.standard_normal(n)
    modulated_power = ensemble_spectrum(selected_atom, rng, cfg.trials)
    print(f"  White ensemble SFM:            {spectral_flatness_db(white_power):8.3f} dB")
    print(f"  Modulated single SFM:          {spectral_flatness_db(periodogram(one_carrier)):8.3f} dB")
    print(f"  Modulated ensemble SFM:        {spectral_flatness_db(modulated_power):8.3f} dB")
    print()

    print("[2] WIDEBAND COMODULATION")
    plain = rng.standard_normal(n)
    shared = rng.standard_normal(n) * selected_atom
    independent = np.zeros(n)
    for lo, hi in zip(edges[:-1], edges[1:]):
        carrier_band = band_split(rng.standard_normal(n), cfg.fs, lo, hi)
        atom_key = keys[rng.integers(len(keys))]
        independent += carrier_band * library[atom_key]

    signals = (
        ("Plain white", plain),
        ("Shared library modulation", shared),
        ("Independent band modulation", independent),
    )
    for name, signal in signals:
        env = band_envelopes(
            signal, cfg.fs, edges, cfg.fft_size, cfg.band_hop
        )
        print(f"  {name:32s} comodulation={comodulation_index(env): .4f}")
    print()

    print("[3] ENVELOPE PURSUIT")
    correct = class_correct = ambiguous_count = 0
    r2_values, best_scores, second_scores = [], [], []
    records = []
    for _ in range(cfg.trials):
        true_key = keys[rng.integers(len(keys))]
        x = rng.standard_normal(n) * library[true_key]
        predicted, gain, r2, second, ambiguous, scores = pursuit(
            x, library, templates, keys,
            cfg.envelope_window, cfg.envelope_hop,
            cfg.ambiguity_threshold,
        )
        exact = predicted == true_key
        same_class = class_lookup[predicted] == class_lookup[true_key]
        correct += int(exact)
        class_correct += int(same_class)
        ambiguous_count += int(ambiguous)
        r2_values.append(r2)
        best_scores.append(float(np.max(scores)))
        second_scores.append(second)
        records.append((true_key, predicted))
    print(f"  Exact atom recovery:           {correct}/{cfg.trials} ({100*correct/cfg.trials:.1f}%)")
    print(f"  Class recovery:                 {class_correct}/{cfg.trials} ({100*class_correct/cfg.trials:.1f}%)")
    print(f"  Ambiguous predictions:          {ambiguous_count}/{cfg.trials}")
    print(f"  Mean envelope R2:               {np.mean(r2_values):.4f}")
    print(f"  Mean best correlation:          {np.mean(best_scores):.4f}")
    print(f"  Mean second correlation:        {np.mean(second_scores):.4f}")
    print()

    print("[4] IDENTIFIABILITY — CLOSEST PAIRS")
    pair_i, pair_j = np.triu_indices(len(keys), k=1)
    top = np.argsort(similarity[pair_i, pair_j])[::-1][:10]
    for index in top:
        i, j = pair_i[index], pair_j[index]
        print(f"  {similarity[i, j]:.5f}  {keys[i]} <-> {keys[j]}")
    print()

    print("[5] RECONSTRUCTION FLOOR")
    oracle_lsd, decoded_lsd = [], []
    for true_key, predicted in records:
        oracle_lsd.append(
            spectral_lsd(library[true_key], library[true_key], rng, 3)
        )
        decoded_lsd.append(
            spectral_lsd(library[true_key], library[predicted], rng, 3)
        )
    print(f"  Oracle same-atom LSD:           {np.mean(oracle_lsd):.4f} dB")
    print(f"  Decoded-atom LSD:               {np.mean(decoded_lsd):.4f} dB")
    print()

    print("[6] PLAIN WHITE NEGATIVE CONTROL")
    negative_r2, negative_scores = [], []
    for _ in range(min(20, cfg.trials)):
        result = pursuit(
            rng.standard_normal(n), library, templates, keys,
            cfg.envelope_window, cfg.envelope_hop,
            cfg.ambiguity_threshold,
        )
        negative_r2.append(result[2])
        negative_scores.append(float(np.max(result[5])))
    print(f"  Mean negative-control R2:       {np.mean(negative_r2):.4f}")
    print(f"  Mean best correlation:          {np.mean(negative_scores):.4f}")
    print()

    print("[7] INFORMATION ACCOUNTING")
    print(f"  Nominal library bits:           {nominal_bits:.3f}")
    print(f"  Effective class bits:           {effective_bits:.3f}")
    print(f"  Nominal codebook rate:          {nominal_bits/cfg.duration:.3f} bits/s")
    print(f"  Class codebook rate:             {effective_bits/cfg.duration:.3f} bits/s")
    print(f"  Exact recovery fraction:        {correct/cfg.trials:.4f}")
    print(f"  Class recovery fraction:        {class_correct/cfg.trials:.4f}")
    print()
    print("=" * 76)
    print("END OF EXPERIMENT")
    print("=" * 76)
    print("Interpretation:")
    print("  • Carrier bandwidth is set by fs and the analyzed frequency ceiling.")
    print("  • Modulation bandwidth is measured from the selected envelope atom.")
    print("  • Comodulation compares shared versus independently modulated bands.")
    print("  • Effective bits count envelope classes, not proven channel capacity.")
    print()


if __name__ == "__main__":
    main()

V4


#!/usr/bin/env python3
"""
STATIC MOD V4 — PARALLEL HIGH-RATE DATA

Parallel amplitude-modulated fractal-static data experiment.

Features:
    - Parallel independent baseband channels
    - Sylvester Hadamard codebook
    - Full alphabet support, including the final antipodal codeword
    - Gaussian carrier
    - Per-chip amplitude modulation
    - Energy-based decoding
    - Common carrier-scale normalization
    - Optional additive white Gaussian noise
    - Batch processing to bound RAM usage
    - BER, SER, and aggregate throughput reporting

Requirements:
    Python 3.9+
    NumPy

Example:
    py static_mod_v4.py

High-rate experiment:
    py static_mod_v4.py --fs 192000 --duration 2 \
        --channels 96 --alphabet 16 --chips 16 \
        --samples-per-chip 64 --gain 0.70

Higher bandwidth simulation:
    py static_mod_v4.py --fs 20000000 --duration 0.1 \
        --channels 16 --alphabet 16 --chips 16 \
        --samples-per-chip 64

Note:
    This is a simulated parallel baseband experiment.
    Channels are independent streams, not physically separated RF carriers.
"""

import argparse
import math
import numpy as np


# ============================================================
# ARGUMENTS
# ============================================================

def parse_args():
    p = argparse.ArgumentParser(
        description="Parallel high-rate fractal-static data experiment"
    )

    p.add_argument("--fs", type=int, default=192000)
    p.add_argument("--duration", type=float, default=2.0)
    p.add_argument("--channels", type=int, default=96)
    p.add_argument("--alphabet", type=int, default=16)
    p.add_argument("--chips", type=int, default=16)
    p.add_argument("--samples-per-chip", type=int, default=64)
    p.add_argument("--seed", type=int, default=17)

    p.add_argument(
        "--gain",
        type=float,
        default=0.70,
        help="Amplitude modulation depth, 0..0.95"
    )

    p.add_argument(
        "--noise",
        type=float,
        default=0.0,
        help="Additional additive white noise power ratio"
    )

    p.add_argument(
        "--report-every",
        type=int,
        default=0
    )

    p.add_argument(
        "--batch-size",
        type=int,
        default=16,
        help="Number of channels processed per batch"
    )

    return p.parse_args()


# ============================================================
# HADAMARD CONSTRUCTION
# ============================================================

def hadamard(n):
    """
    Sylvester Hadamard matrix.

    n must be a power of two.

    H @ H.T = n * I
    """

    if n < 1 or n & (n - 1):
        raise ValueError("Hadamard size must be a power of two")

    h = np.array([[1.0]], dtype=np.float64)

    while h.shape[0] < n:
        h = np.block([
            [h, h],
            [h, -h]
        ])

    return h


# ============================================================
# CODEBOOK
# ============================================================

def make_codebook(alphabet, chips):
    """
    Construct the amplitude modulation codebook.

    Uses non-DC Hadamard rows.

    For a full alphabet:
        chips - 1 orthogonal non-DC rows
        1 antipodal completion

    The antipodal completion is distinguishable but is not
    orthogonal to its corresponding original codeword.
    """

    if chips & (chips - 1):
        raise ValueError("--chips must be a power of two")

    if alphabet < 2 or alphabet > chips:
        raise ValueError(
            "--alphabet must be between 2 and --chips"
        )

    h = hadamard(chips)

    rows = [
        row.copy()
        for row in h[1:alphabet + 1]
    ]

    if len(rows) < alphabet:
        rows.append(-h[1].copy())

    codebook = np.asarray(
        rows[:alphabet],
        dtype=np.float64
    )

    if codebook.shape != (alphabet, chips):
        raise RuntimeError("Invalid codebook dimensions")

    if np.unique(codebook, axis=0).shape[0] != alphabet:
        raise RuntimeError("Duplicate codewords detected")

    return codebook


# ============================================================
# PAYLOAD GENERATION
# ============================================================

def make_payload(rng, channels, symbols, alphabet):
    """
    Generate independent random symbols for every channel.
    """

    return rng.integers(
        0,
        alphabet,
        size=(channels, symbols),
        dtype=np.uint16
    )


# ============================================================
# ENCODER
# ============================================================


def encode_channel(
    payload,
    codebook,
    samples_per_chip,
    gain,
    rng,
    noise
):
    """
    Encode independent parallel channels.

    Output shape:
        channels x total_samples

    Signal:
        x[n] = carrier[n] * modulation_envelope[n]
    """

    channels, symbols = payload.shape
    chips = codebook.shape[1]

    samples_per_symbol = chips * samples_per_chip
    n = symbols * samples_per_symbol

    # C x S x chips
    chip_codes = codebook[payload]

    # C x S x chips
    envelope = 1.0 + gain * chip_codes

    # C x S x chips x samples_per_chip
    envelope = np.repeat(
        envelope[..., None],
        samples_per_chip,
        axis=3
    )

    # C x (S * chips * samples_per_chip)
    envelope = envelope.reshape(channels, n)

    # Generate carrier.
    carrier = rng.standard_normal(
        (channels, n),
        dtype=np.float32
    )

    signal = carrier * envelope.astype(np.float32)

    # Optional additive noise.
    if noise > 0:
        signal += (
            rng.standard_normal(
                signal.shape,
                dtype=np.float32
            )
            * np.float32(math.sqrt(noise))
        )

    return signal



# ============================================================
# DECODER
# ============================================================

def decode_channel(
    signal,
    codebook,
    samples_per_chip,
    gain
):
    """
    Estimate chip energy.

    Processing:
        1. Divide signal into symbols.
        2. Calculate chip mean-square energy.
        3. Convert energy to logarithmic power.
        4. Remove common per-symbol carrier scale.
        5. Normalize chip profiles.
        6. Correlate against expected codeword templates.
        7. Select maximum-correlation symbol.

    Returns:
        decoded symbols
        correlation scores
    """

    channels, n = signal.shape
    chips = codebook.shape[1]

    samples_per_symbol = chips * samples_per_chip
    symbols = n // samples_per_symbol

    usable = signal[
        :,
        :symbols * samples_per_symbol
    ]

    blocks = usable.reshape(
        channels,
        symbols,
        chips,
        samples_per_chip
    )

    # Chip energy.
    energy = np.mean(
        blocks * blocks,
        axis=3
    )

    # Logarithmic power.
    log_energy = np.log(
        np.maximum(energy, 1e-20)
    )

    # Remove per-symbol carrier gain.
    log_energy -= np.mean(
        log_energy,
        axis=2,
        keepdims=True
    )

    # Normalize chip profile.
    norms = np.linalg.norm(
        log_energy,
        axis=2,
        keepdims=True
    )

    features = (
        log_energy /
        np.maximum(norms, 1e-20)
    )

    # Expected log-power templates.
    amp = 1.0 + gain * codebook

    templates = np.log(amp * amp)

    templates -= templates.mean(
        axis=1,
        keepdims=True
    )

    templates /= np.maximum(
        np.linalg.norm(
            templates,
            axis=1,
            keepdims=True
        ),
        1e-20
    )

    # Correlation scores:
    # channels x symbols x alphabet

    scores = np.einsum(
        "csk,ak->csa",
        features,
        templates,
        optimize=True
    )

    decoded = np.argmax(
        scores,
        axis=2
    )

    return decoded, scores


# ============================================================
# BIT CONVERSION
# ============================================================

def bits_per_symbol(alphabet):
    """
    Fixed-width binary payload representation.

    For non-power-of-two alphabets, unused binary patterns
    are not transmitted.
    """

    return int(math.floor(math.log2(alphabet)))


def payload_bits(payload, bits):
    """
    Convert symbols to fixed-width binary representation.

    Most-significant bit first.
    """

    shifts = np.arange(
        bits - 1,
        -1,
        -1,
        dtype=np.uint16
    )

    return (
        (payload[..., None] >> shifts) & 1
    ).astype(np.uint8)


# ============================================================
# PERFORMANCE SUMMARY
# ============================================================

def summarize(
    true_payload,
    decoded,
    fs,
    chips,
    samples_per_chip,
    alphabet
):
    bits = bits_per_symbol(alphabet)

    true_bits = payload_bits(
        true_payload,
        bits
    )

    decoded_bits = payload_bits(
        decoded,
        bits
    )

    bit_errors = int(
        np.count_nonzero(
            true_bits != decoded_bits
        )
    )

    total_bits = int(true_bits.size)

    symbol_errors = int(
        np.count_nonzero(
            true_payload != decoded
        )
    )

    total_symbols = int(true_payload.size)

    symbol_rate = (
        fs /
        (chips * samples_per_chip)
    )

    raw_rate = (
        symbol_rate *
        bits *
        true_payload.shape[0]
    )

    ber = bit_errors / max(total_bits, 1)

    ser = symbol_errors / max(total_symbols, 1)

    return {
        "bit_errors": bit_errors,
        "total_bits": total_bits,
        "ber": ber,

        "symbol_errors": symbol_errors,
        "total_symbols": total_symbols,
        "ser": ser,

        "symbol_rate": symbol_rate,
        "raw_rate": raw_rate,

        "delivered_rate": raw_rate * (1.0 - ber)
    }


# ============================================================
# VALIDATION
# ============================================================

def validate_args(a):

    if a.fs <= 0:
        raise ValueError("--fs must be positive")

    if a.duration <= 0:
        raise ValueError("--duration must be positive")

    if a.channels < 1:
        raise ValueError("--channels must be >= 1")

    if a.samples_per_chip < 2:
        raise ValueError("--samples-per-chip must be >= 2")

    if not 0.0 < a.gain < 1.0:
        raise ValueError("--gain must be between 0 and 1")

    if a.noise < 0:
        raise ValueError("--noise cannot be negative")

    if a.batch_size < 1:
        raise ValueError("--batch-size must be >= 1")

    if a.report_every < 0:
        raise ValueError("--report-every cannot be negative")


# ============================================================
# MAIN EXPERIMENT
# ============================================================

def main():

    a = parse_args()

    validate_args(a)

    rng = np.random.default_rng(a.seed)

    codebook = make_codebook(
        a.alphabet,
        a.chips
    )

    bits = bits_per_symbol(a.alphabet)

    samples_per_symbol = (
        a.chips *
        a.samples_per_chip
    )

    symbol_rate = (
        a.fs /
        samples_per_symbol
    )

    symbols = max(
        1,
        int(a.duration * symbol_rate)
    )

    actual_duration = (
        symbols /
        symbol_rate
    )

    payload = make_payload(
        rng,
        a.channels,
        symbols,
        a.alphabet
    )

    decoded = np.empty_like(payload)

    batch_size = min(
        a.channels,
        a.batch_size
    )

    # --------------------------------------------------------
    # ENCODE AND DECODE IN BATCHES
    # --------------------------------------------------------

    for first in range(
        0,
        a.channels,
        batch_size
    ):

        last = min(
            first + batch_size,
            a.channels
        )

        block_payload = payload[first:last]

        encoded = encode_channel(
            block_payload,
            codebook,
            a.samples_per_chip,
            a.gain,
            rng,
            a.noise
        )

        block_decoded, _ = decode_channel(
            encoded,
            codebook,
            a.samples_per_chip,
            a.gain
        )

        decoded[first:last] = block_decoded

        batch_index = first // batch_size

        if (
            a.report_every
            and batch_index % a.report_every == 0
        ):

            print(
                f"Processed channels "
                f"{first + 1}–{last}/{a.channels}"
            )

    # --------------------------------------------------------
    # SUMMARY
    # --------------------------------------------------------

    result = summarize(
        payload,
        decoded,
        a.fs,
        a.chips,
        a.samples_per_chip,
        a.alphabet
    )

    # --------------------------------------------------------
    # REPORT
    # --------------------------------------------------------

    print()

    print("=" * 72)
    print("STATIC MOD V4 — PARALLEL HIGH-RATE DATA")
    print("=" * 72)

    print(
        f"Sampling rate:                 "
        f"{a.fs:,} samples/s per channel"
    )

    print(
        f"Parallel channels:             "
        f"{a.channels}"
    )

    print(
        f"Code alphabet:                 "
        f"{a.alphabet} symbols"
    )

    print(
        f"Bits per symbol:               "
        f"{bits}"
    )

    print(
        f"Chips per symbol:              "
        f"{a.chips}"
    )

    print(
        f"Samples per chip:              "
        f"{a.samples_per_chip}"
    )

    print(
        f"Samples per symbol:            "
        f"{samples_per_symbol:,}"
    )

    print(
        f"Symbol rate per channel:       "
        f"{symbol_rate:,.2f} symbols/s"
    )

    print(
        f"Symbols transmitted/channel:   "
        f"{symbols:,}"
    )

    print(
        f"Payload duration:              "
        f"{actual_duration:.4f} s"
    )

    print()

    print("[DATA RATE]")

    print(
        f"Raw aggregate rate:            "
        f"{result['raw_rate']:,.0f} bit/s"
    )

    print(
        f"Raw aggregate rate:            "
        f"{result['raw_rate']/1e6:.4f} Mbit/s"
    )

    print(
        f"Measured delivered rate:       "
        f"{result['delivered_rate']:,.0f} bit/s"
    )

    print(
        f"Measured delivered rate:       "
        f"{result['delivered_rate']/1e6:.4f} Mbit/s"
    )

    print()

    print("[DECODE]")

    print(
        f"Symbol errors:                 "
        f"{result['symbol_errors']:,}/"
        f"{result['total_symbols']:,}"
    )

    print(
        f"Symbol error rate:             "
        f"{result['ser']:.6f}"
    )

    print(
        f"Bit errors:                    "
        f"{result['bit_errors']:,}/"
        f"{result['total_bits']:,}"
    )

    print(
        f"Bit error rate:                "
        f"{result['ber']:.8f}"
    )

    print()

    print("[MODEL]")

    print(
        f"AM depth:                      "
        f"{a.gain:.3f}"
    )

    print(
        f"Additional noise power ratio:  "
        f"{a.noise:.6g}"
    )

    print(
        f"Seed:                          "
        f"{a.seed}"
    )

    print()

    print("[CODEBOOK]")

    print(
        f"Codebook dimensions:           "
        f"{codebook.shape[0]} x {codebook.shape[1]}"
    )

    print(
        f"Unique codewords:              "
        f"{np.unique(codebook, axis=0).shape[0]}"
    )

    gram = codebook @ codebook.T

    off_diagonal = gram.copy()

    np.fill_diagonal(
        off_diagonal,
        0
    )

    print(
        f"Maximum absolute cross-product:"
        f" {np.max(np.abs(off_diagonal)):.0f}"
    )

    print()

    print("[INTERPRETATION]")

    print(
        "Rate is a simulated raw payload rate, "
        "not a measured RF link rate."
    )

    print(
        "The channels are independent parallel "
        "baseband streams in this test."
    )

    print(
        "The final full-alphabet codeword is antipodal "
        "to the first non-DC Hadamard row."
    )

    print(
        "A physical implementation still needs channel "
        "filters, synchronization, transmit/receive "
        "hardware, and an RF/link budget."
    )

    print("=" * 72)


# ============================================================
# ENTRY POINT
# ============================================================

if __name__ == "__main__":
    main()

v5


#!/usr/bin/env python3
"""
STATIC MOD V5
=============
Parallel wideband variance-modulation simulator.

Architecture:
    independent Gaussian carrier per frequency channel
        -> fractal-compatible variance modulation
        -> parallel channel aggregation
        -> multipath channel
        -> additive noise
        -> receiver channelization
        -> per-chip variance estimation
        -> codebook correlation decoder
        -> BER / SER / throughput analysis

Default configuration:
    Complex sample rate:       20 MHz
    Channels:                  8
    Channel spacing:           1 MHz
    Channel bandwidth:         800 kHz
    Chips per symbol:          32
    Samples per chip:          500
    Symbol duration:           800 us
    Alphabet:                  16
    Bits per symbol:           4
    Aggregate raw rate:        40 kbit/s

Dependencies:
    Python 3.10+
    NumPy

This is a communications-channel simulation, not a stealth
or regulatory-compliance assessment.
"""

import argparse
import math
import time

import numpy as np


VERSION = "STATIC-MOD-V5"
EPS = 1e-20


# ------------------------------------------------------------
# CONFIGURATION
# ------------------------------------------------------------

def arguments():

    p = argparse.ArgumentParser(
        description="STATIC MOD V5 wideband variance-modulation simulator"
    )

    p.add_argument("--fs", type=float, default=20_000_000)
    p.add_argument("--duration", type=float, default=0.064)

    p.add_argument("--channels", type=int, default=8)
    p.add_argument("--channel-spacing", type=float, default=1_000_000)
    p.add_argument("--channel-bandwidth", type=float, default=800_000)

    p.add_argument("--alphabet", type=int, default=16)
    p.add_argument("--chips", type=int, default=32)
    p.add_argument("--samples-per-chip", type=int, default=500)

    p.add_argument("--gain", type=float, default=0.65)
    p.add_argument("--snr-db", type=float, default=12.0)

    p.add_argument("--echo-delay-us", type=float, default=0.0)
    p.add_argument("--echo-gain", type=float, default=0.25)

    p.add_argument("--ramp-fraction", type=float, default=0.12)

    p.add_argument("--seed", type=int, default=23)

    return p.parse_args()


# ------------------------------------------------------------
# HADAMARD / SYMBOL LIBRARY
# ------------------------------------------------------------

def hadamard(n):

    if n < 1 or n & (n - 1):
        raise ValueError("Hadamard dimension must be a power of two")

    h = np.ones((1, 1), dtype=np.float32)

    while h.shape[0] < n:

        h = np.block([
            [h, h],
            [h, -h]
        ])

    return h


def make_codebook(alphabet, chips):

    if chips & (chips - 1):
        raise ValueError("chips must be a power of two")

    if alphabet < 2 or alphabet > chips - 1:
        raise ValueError(
            "alphabet must be between 2 and chips-1"
        )

    # Exclude the constant DC row.
    return hadamard(chips)[1:alphabet + 1]


def generate_payload(rng, channels, symbols, alphabet):

    return rng.integers(
        0,
        alphabet,
        size=(channels, symbols),
        dtype=np.uint16
    )


# ------------------------------------------------------------
# FRACTAL-COMPATIBLE VARIANCE ENCODING
# ------------------------------------------------------------

def make_envelope(
    payload,
    codebook,
    samples_per_chip,
    gain,
    ramp_fraction
):

    codes = codebook[payload].reshape(-1)

    levels = 1.0 + gain * codes

    envelope = np.repeat(
        levels,
        samples_per_chip
    ).astype(np.float32)

    # Smooth transitions to limit spectral spreading.
    ramp = max(
        2,
        int(samples_per_chip * ramp_fraction)
    )

    for j in range(1, len(levels)):

        boundary = j * samples_per_chip

        start = max(0, boundary - ramp)
        stop = min(len(envelope), boundary + ramp)

        envelope[start:stop] = np.linspace(
            levels[j - 1],
            levels[j],
            stop - start,
            endpoint=False,
            dtype=np.float32
        )

    return envelope, ramp


# ------------------------------------------------------------
# FREQUENCY CHANNEL GEOMETRY
# ------------------------------------------------------------

def channel_geometry(args):

    fs = args.fs
    k = args.channels
    spacing = args.channel_spacing
    bandwidth = args.channel_bandwidth

    if bandwidth <= 0 or spacing < bandwidth:
        raise ValueError(
            "Channel spacing must be >= channel bandwidth"
        )

    centers = (
        np.arange(k) - (k - 1) / 2
    ) * spacing

    total_span = (k - 1) * spacing + bandwidth

    if total_span >= fs * 0.8:
        raise ValueError(
            "Channel allocation exceeds the 80% sample-rate limit"
        )

    return centers, total_span


def frequency_mask(freq, center, bandwidth):

    return (
        (freq >= center - bandwidth / 2)
        &
        (freq < center + bandwidth / 2)
    )


# ------------------------------------------------------------
# BAND-LIMITED GAUSSIAN CARRIER
# ------------------------------------------------------------

def make_carrier(rng, n, freq, center, bandwidth):

    mask = frequency_mask(
        freq,
        center,
        bandwidth
    )

    spectrum = (
        rng.standard_normal(n)
        +
        1j * rng.standard_normal(n)
    )

    spectrum *= mask

    carrier = np.fft.ifft(spectrum).astype(
        np.complex64
    )

    power = np.mean(
        np.abs(carrier) ** 2
    )

    if power < EPS:
        raise RuntimeError("Carrier generation failed")

    carrier /= np.float32(math.sqrt(power))

    return carrier


# ------------------------------------------------------------
# TRANSMITTER
# ------------------------------------------------------------

def transmit(args, payload, codebook, rng):

    fs = args.fs

    chips = args.chips
    spc = args.samples_per_chip

    symbol_samples = chips * spc

    symbols = payload.shape[1]
    n = symbols * symbol_samples

    freq = np.fft.fftfreq(n, d=1.0 / fs)

    centers, total_span = channel_geometry(args)

    tx = np.zeros(n, dtype=np.complex64)

    envelopes = []

    for channel, center in enumerate(centers):

        envelope, ramp = make_envelope(
            payload[channel],
            codebook,
            spc,
            args.gain,
            args.ramp_fraction
        )

        carrier = make_carrier(
            rng,
            n,
            freq,
            center,
            args.channel_bandwidth
        )

        tx += carrier * envelope

        envelopes.append(envelope)

    return tx, centers, total_span, ramp


# ------------------------------------------------------------
# MULTIPATH CHANNEL
# ------------------------------------------------------------

def multipath(tx, args):

    delay_samples = int(
        round(args.echo_delay_us * 1e-6 * args.fs)
    )

    if args.echo_gain < 0:
        raise ValueError("Echo gain cannot be negative")

    if delay_samples == 0 or args.echo_gain == 0:

        return tx.copy(), delay_samples

    echo = np.roll(tx, delay_samples)

    rx = tx + np.float32(args.echo_gain) * echo

    return rx.astype(np.complex64), delay_samples


# ------------------------------------------------------------
# ADDITIVE WHITE GAUSSIAN NOISE
# ------------------------------------------------------------

def add_noise(signal, args, rng):

    # The SNR parameter is defined per isolated channel.
    snr_linear = 10.0 ** (args.snr_db / 10.0)

    noise_variance = (
        args.fs / args.channel_bandwidth
    ) / snr_linear

    sigma = math.sqrt(noise_variance / 2.0)

    noise = (
        rng.standard_normal(len(signal))
        +
        1j * rng.standard_normal(len(signal))
    ) * sigma

    return (
        signal + noise.astype(np.complex64)
    ).astype(np.complex64)


# ------------------------------------------------------------
# RECEIVER CHANNELIZATION
# ------------------------------------------------------------

def channelize(rx, args, centers):

    n = len(rx)

    freq = np.fft.fftfreq(
        n,
        d=1.0 / args.fs
    )

    spectrum = np.fft.fft(rx)

    output = []

    for center in centers:

        mask = frequency_mask(
            freq,
            center,
            args.channel_bandwidth
        )

        isolated = np.fft.ifft(
            spectrum * mask
        ).astype(np.complex64)

        output.append(isolated)

    return output


# ------------------------------------------------------------
# VARIANCE DECODER
# ------------------------------------------------------------

def make_templates(codebook, gain, noise_power):

    amplitude = 1.0 + gain * codebook

    # Expected measured power includes additive noise.
    templates = np.log(
        amplitude ** 2 + noise_power
    )

    templates -= templates.mean(
        axis=1,
        keepdims=True
    )

    norms = np.linalg.norm(
        templates,
        axis=1,
        keepdims=True
    )

    return templates / np.maximum(norms, EPS)


def decode_channel(
    signal,
    codebook,
    args,
    margin,
    templates
):

    chips = args.chips
    spc = args.samples_per_chip

    symbol_samples = chips * spc

    symbols = len(signal) // symbol_samples

    usable = signal[
        :symbols * symbol_samples
    ]

    blocks = usable.reshape(
        symbols,
        chips,
        spc
    )

    # Estimate power from the interior of each chip.
    interior = blocks[
        :,
        :,
        margin:spc - margin
    ]

    energy = np.mean(
        np.abs(interior) ** 2,
        axis=2
    )

    log_energy = np.log(
        np.maximum(energy, EPS)
    )

    # Remove common gain fluctuations within each symbol.
    log_energy -= log_energy.mean(
        axis=1,
        keepdims=True
    )

    norms = np.linalg.norm(
        log_energy,
        axis=1,
        keepdims=True
    )

    features = log_energy / np.maximum(
        norms,
        EPS
    )

    scores = features @ templates.T

    decoded = np.argmax(
        scores,
        axis=1
    )

    return decoded, energy, scores


# ------------------------------------------------------------
# BIT CONVERSION
# ------------------------------------------------------------

def to_bits(values, bits):

    shifts = np.arange(
        bits - 1,
        -1,
        -1,
        dtype=np.uint16
    )

    return (
        (values[..., None] >> shifts) & 1
    ).astype(np.uint8)


# ------------------------------------------------------------
# METRICS
# ------------------------------------------------------------

def calculate_metrics(
    original,
    decoded,
    args
):

    bits = int(
        math.log2(args.alphabet)
    )

    original_bits = to_bits(
        original,
        bits
    )

    decoded_bits = to_bits(
        decoded,
        bits
    )

    bit_errors = np.count_nonzero(
        original_bits != decoded_bits
    )

    total_bits = original_bits.size

    symbol_errors = np.count_nonzero(
        original != decoded
    )

    total_symbols = original.size

    symbol_duration = (
        args.chips *
        args.samples_per_chip /
        args.fs
    )

    symbol_rate = 1.0 / symbol_duration

    raw_rate = (
        args.channels *
        bits *
        symbol_rate
    )

    ber = bit_errors / total_bits
    ser = symbol_errors / total_symbols

    return {
        "bits": bits,
        "bit_errors": int(bit_errors),
        "total_bits": int(total_bits),
        "ber": float(ber),
        "symbol_errors": int(symbol_errors),
        "total_symbols": int(total_symbols),
        "ser": float(ser),
        "symbol_rate": symbol_rate,
        "raw_rate": raw_rate,
        "goodput": raw_rate * (1.0 - ber)
    }


def cross_channel_correlation(features):

    if len(features) < 2:
        return 0.0

    flattened = [
        f.reshape(-1)
        for f in features
    ]

    matrix = np.corrcoef(
        np.stack(flattened)
    )

    upper = np.triu_indices(
        len(features),
        k=1
    )

    values = matrix[upper]

    values = values[
        np.isfinite(values)
    ]

    if not len(values):
        return 0.0

    return float(
        np.mean(values)
    )


# ------------------------------------------------------------
# MAIN EXPERIMENT
# ------------------------------------------------------------

def main():

    args = arguments()

    if args.fs <= 0 or args.duration <= 0:
        raise ValueError("Invalid sampling rate or duration")

    if args.channels < 1:
        raise ValueError("At least one channel is required")

    if args.samples_per_chip <= 2:
        raise ValueError("Insufficient samples per chip")

    if not 0 < args.gain < 1:
        raise ValueError("Gain must be between 0 and 1")

    if not 0 < args.ramp_fraction < 0.4:
        raise ValueError("Invalid ramp fraction")

    if args.echo_gain < 0:
        raise ValueError("Echo gain cannot be negative")

    if args.echo_delay_us < 0:
        raise ValueError("Echo delay cannot be negative")

    if args.snr_db < -100 or args.snr_db > 100:
        raise ValueError("SNR outside supported simulation range")

    if args.alphabet & (args.alphabet - 1):
        raise ValueError("Alphabet must be a power of two")

    if args.chips & (args.chips - 1):
        raise ValueError("Chips must be a power of two")

    rng = np.random.default_rng(args.seed)

    codebook = make_codebook(
        args.alphabet,
        args.chips
    )

    bits = int(
        math.log2(args.alphabet)
    )

    symbol_samples = (
        args.chips * args.samples_per_chip
    )

    symbol_duration = (
        symbol_samples / args.fs
    )

    symbols = int(
        args.duration / symbol_duration
    )

    if symbols < 2:
        raise ValueError(
            "Duration must contain at least two symbols"
        )

    actual_duration = (
        symbols * symbol_duration
    )

    n = symbols * symbol_samples

    # Ensure the channel geometry is valid.
    centers, total_span = channel_geometry(args)

    if total_span >= args.fs:
        raise ValueError("Channel span exceeds sample rate")

    # --------------------------------------------------------
    # HEADER
    # --------------------------------------------------------

    print()
    print("=" * 76)
    print(VERSION)
    print("PARALLEL WIDEBAND VARIANCE-MODULATION EXPERIMENT")
    print("=" * 76)

    print(f"Complex sample rate:          {args.fs:,.0f} Hz")
    print(f"Nyquist frequency:             {args.fs / 2:,.0f} Hz")
    print(f"Channels:                       {args.channels}")
    print(f"Channel spacing:                {args.channel_spacing:,.0f} Hz")
    print(f"Channel bandwidth:              {args.channel_bandwidth:,.0f} Hz")
    print(f"Total channel span:             {total_span / 1e6:.3f} MHz")
    print(f"Alphabet:                       {args.alphabet}")
    print(f"Bits per symbol:                {bits}")
    print(f"Chips per symbol:               {args.chips}")
    print(f"Samples per chip:               {args.samples_per_chip:,}")
    print(f"Samples per symbol:             {symbol_samples:,}")
    print(f"Symbol duration:                {symbol_duration * 1e6:.3f} us")
    print(f"Symbol rate per channel:        {1 / symbol_duration:,.2f} baud")
    print(f"Symbols per channel:            {symbols:,}")
    print(f"Recording duration:             {actual_duration:.6f} s")
    print()

    # --------------------------------------------------------
    # TRANSMITTER
    # --------------------------------------------------------

    start_time = time.perf_counter()

    print("[1] TRANSMITTER")

    payload = generate_payload(
        rng,
        args.channels,
        symbols,
        args.alphabet
    )

    tx, centers, total_span, ramp = transmit(
        args,
        payload,
        codebook,
        rng
    )

    tx_power = float(
        np.mean(np.abs(tx) ** 2)
    )

    print(f"  Samples generated:             {n:,}")
    print(f"  Aggregate transmit power:      {tx_power:.6f}")
    print(f"  Envelope transition ramp:      {ramp} samples")
    print()

    # --------------------------------------------------------
    # CHANNEL
    # --------------------------------------------------------

    print("[2] CHANNEL")

    multipath_signal, delay_samples = multipath(
        tx,
        args
    )

    rx = add_noise(
        multipath_signal,
        args,
        rng
    )

    print(f"  Requested SNR/channel:         {args.snr_db:.2f} dB")
    print(f"  Echo delay:                    {args.echo_delay_us:.3f} us")
    print(f"  Echo delay samples:            {delay_samples}")
    print(f"  Echo amplitude:                {args.echo_gain:.3f}")
    print()

    # --------------------------------------------------------
    # RECEIVER
    # --------------------------------------------------------

    print("[3] RECEIVER CHANNELIZATION")

    received_channels = channelize(
        rx,
        args,
        centers
    )

    print(f"  Isolated channels:             {len(received_channels)}")
    print()

    # --------------------------------------------------------
    # DECODING
    # --------------------------------------------------------

    print("[4] VARIANCE DECODING")

    noise_power = (
        10.0 ** (-args.snr_db / 10.0)
    )

    templates = make_templates(
        codebook,
        args.gain,
        noise_power
    )

    delay_margin = delay_samples + 4

    margin = max(
        ramp,
        delay_margin
    )

    if margin >= args.samples_per_chip // 3:
        raise ValueError(
            "Echo delay/ramp too large relative to chip duration. "
            "Increase samples per chip or reduce echo delay."
        )

    decoded = np.empty_like(payload)

    channel_features = []

    for channel, signal in enumerate(received_channels):

        result, energy, scores = decode_channel(
            signal,
            codebook,
            args,
            margin,
            templates
        )

        decoded[channel] = result

        # Normalized chip log-energy for cross-channel analysis.
        feature = np.log(
            np.maximum(energy, EPS)
        )

        feature -= feature.mean(
            axis=1,
            keepdims=True
        )

        channel_features.append(feature)

        print(
            f"  Channel {channel + 1:02d}: "
            f"{len(result):,} symbols decoded"
        )

    print()

    # --------------------------------------------------------
    # PERFORMANCE
    # --------------------------------------------------------

    print("[5] DATA RATE AND ERROR ANALYSIS")

    metrics = calculate_metrics(
        payload,
        decoded,
        args
    )

    print(f"  Raw aggregate rate:             {metrics['raw_rate']:,.2f} bit/s")
    print(f"  Raw aggregate rate:             {metrics['raw_rate'] / 1e3:.4f} kbit/s")
    print(f"  Measured goodput:               {metrics['goodput']:,.2f} bit/s")
    print(f"  Measured goodput:               {metrics['goodput'] / 1e3:.4f} kbit/s")
    print()
    print(f"  Bit errors:                     {metrics['bit_errors']:,}")
    print(f"  Total bits:                     {metrics['total_bits']:,}")
    print(f"  BER:                            {metrics['ber']:.8f}")
    print()
    print(f"  Symbol errors:                  {metrics['symbol_errors']:,}")
    print(f"  Total symbols:                  {metrics['total_symbols']:,}")
    print(f"  SER:                            {metrics['ser']:.8f}")
    print()

    # --------------------------------------------------------
    # CROSS-CHANNEL ANALYSIS
    # --------------------------------------------------------

    print("[6] CROSS-CHANNEL ANALYSIS")

    correlation = cross_channel_correlation(
        channel_features
    )

    print(
        f"  Mean pairwise chip-energy correlation: "
        f"{correlation:.6f}"
    )

    print()

    # --------------------------------------------------------
    # PER-CHANNEL RESULTS
    # --------------------------------------------------------

    print("[7] PER-CHANNEL RESULTS")

    for channel in range(args.channels):

        errors = np.count_nonzero(
            payload[channel] != decoded[channel]
        )

        channel_ser = errors / symbols

        print(
            f"  Channel {channel + 1:02d}: "
            f"SER={channel_ser:.6f} "
            f"errors={errors}/{symbols} "
            f"center={centers[channel] / 1e6:+.3f} MHz"
        )

    print()

    # --------------------------------------------------------
    # INFORMATION ACCOUNTING
    # --------------------------------------------------------

    print("[8] INFORMATION ACCOUNTING")

    nominal_bits = (
        args.channels *
        symbols *
        bits
    )

    print(f"  Payload bits:                   {nominal_bits:,}")
    print(f"  Codebook symbols:               {args.alphabet}")
    print(f"  Codebook bits/symbol:           {bits}")
    print(f"  Channel count:                  {args.channels}")
    print(f"  Observation window:             {symbol_duration * 1e6:.3f} us")
    print(f"  Samples per observation:        {symbol_samples:,}")

    effective_observation = (
        args.samples_per_chip - 2 * margin
    )

    time_bandwidth = (
        args.channel_bandwidth *
        effective_observation /
        args.fs
    )

    print(
        f"  Approx. chip time-bandwidth:    "
        f"{time_bandwidth:.2f}"
    )

    print()

    # --------------------------------------------------------
    # EXECUTION TIME
    # --------------------------------------------------------

    elapsed = (
        time.perf_counter() - start_time
    )

    print("[9] EXECUTION")

    print(f"  Runtime:                        {elapsed:.3f} seconds")
    print(f"  Samples processed:              {n:,}")
    print(f"  Samples per second:             {n / max(elapsed, EPS):,.0f}")

    print()
    print("=" * 76)
    print("END STATIC MOD V5")
    print("=" * 76)

    print()
    print("INTERPRETATION")
    print("  Raw rate is the configured uncoded payload rate.")
    print("  Goodput discounts bit errors but does not include framing or FEC.")
    print("  BER and SER are measurements of this simulated realization.")
    print("  Cross-channel correlation measures decoded chip-energy patterns.")
    print("  The time-bandwidth product is an approximate observation metric.")
    print("  This model does not establish real-world RF performance.")
    print()


if __name__ == "__main__":
    main()