
#!/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()
