#!/usr/bin/env python3
"""static_mod_v2.py — combinatorial fractal static experiment.

Model: x[n] = m[n] * w[n]
  w: fresh zero-mean white Gaussian carrier
  m: atom selected from a finite Cantor/Thue-Morse/Weierstrass library

Tests ensemble and single-realization PSD flatness, cross-band comodulation,
normalized energy-envelope pursuit, atom ambiguity, independent-carrier
spectral reconstruction floor, and an unmodulated-white negative control.

Dependencies: Python 3.10+, NumPy only.

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

import argparse
import math
from dataclasses import dataclass

import numpy as np

PHI = (1.0 + math.sqrt(5.0)) / 2.0
EDGES = np.array([500, 707, 1000, 1414, 2000, 2828, 3900], dtype=float)


@dataclass
class Config:
    fs: int
    duration: float
    trials: int
    seed: int
    envelope_window: int
    envelope_hop: int
    equivalence_threshold: float
    ambiguity_threshold: float


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):
    x = (t / period) % 1.0
    keep = np.ones(len(t), dtype=bool)
    for _ in range(depth):
        x *= 3.0
        digit = np.floor(x).astype(int)
        keep &= digit != 1
        x -= digit
    return keep.astype(float)


def thue_morse_gate(t, period):
    index = (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):
    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, 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, 0.10),
        "TM.20": thue_morse_gate(t, 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 or (gate_name, am_name) == ("none", "none"):
                library[(gate_name, am_name)] = atom
    return library, gates, ams


# ----------------------------------------------------------------------
# Energy envelopes and normalized templates
# ----------------------------------------------------------------------

def frame_energy(x, window, hop):
    if len(x) < window:
        raise ValueError("Signal is shorter than the 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-15):
    """Normalize temporal variation; a constant atom has no signature."""
    x = np.asarray(x, dtype=float)
    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):
    raw = {k: frame_energy(v, window, hop) for k, v in library.items()}
    normalized = {k: normalize_template(v) for k, v in raw.items()}
    return raw, normalized


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 envelope-template similarity graph."""
    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, rb = find(a), 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):
        groups.setdefault(find(i), []).append(key)
    return list(groups.values())


def pursuit(x, library, raw_templates, normalized_templates, keys,
            window, hop, ambiguity_threshold):
    observed = frame_energy(x, window, hop)
    observed_normalized = normalize_template(observed)
    scores = np.array([normalized_templates[k] @ observed_normalized 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 = raw_templates[best_key]
    gain = float(np.dot(template, observed) / (np.dot(template, template) + 1e-30))
    residual = observed - gain * template

    # R2 is improvement over a constant-mean energy-envelope predictor.
    baseline_error = np.sum((observed - observed.mean()) ** 2) + 1e-30
    r2 = 1.0 - np.sum(residual ** 2) / baseline_error
    second_score = float(scores[second_i])
    ambiguous = second_score >= ambiguity_threshold

    return best_key, gain, float(r2), second_score, bool(ambiguous), scores


# ----------------------------------------------------------------------
# Spectral measurements
# ----------------------------------------------------------------------

def periodogram(x):
    # Rectangular window: ensemble expectation is flat for independent
    # white samples even when their deterministic variances vary in time.
    return np.abs(np.fft.rfft(x)) ** 2 / len(x)


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


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


def spectral_lsd(atom_a, atom_b, rng, trials):
    """LSD between ensemble PSD estimates, not between waveforms."""
    pa = ensemble_spectrum(atom_a, rng, trials)
    pb = ensemble_spectrum(atom_b, rng, trials)
    eps = 1e-12 * max(float(pa.max()), float(pb.max()), 1.0)
    # Ignore DC; retain the same frequency bins for both spectra.
    da = 10.0 * np.log10(pa[1:] + eps)
    db = 10.0 * np.log10(pb[1:] + eps)
    return float(np.sqrt(np.mean((db - da) ** 2)))


# ----------------------------------------------------------------------
# Cross-band energy and comodulation
# ----------------------------------------------------------------------

def band_envelopes(x, fs, fft_size=256, hop=128):
    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)

    masks = [band_index == b for b in range(len(EDGES) - 1)]
    for frame_i, start in enumerate(starts):
        segment = x[start:start + fft_size] * window
        power = np.abs(np.fft.rfft(segment)) ** 2
        for band_i, mask in enumerate(masks):
            output[band_i, frame_i] = np.sum(power[mask])
    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 = corr[np.triu_indices(len(envelopes), k=1)]
    return float(np.nanmean(upper))


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))


# ----------------------------------------------------------------------
# Experiment
# ----------------------------------------------------------------------

def main():
    args = parse_args()
    if args.fs <= 0 or args.duration <= 0:
        raise SystemExit("--fs and --duration must be positive")
    if args.trials < 2:
        raise SystemExit("--trials must be at least 2")
    if args.stages < 1:
        raise SystemExit("--stages must be at least 1")
    if args.window < 2 or args.hop < 1:
        raise SystemExit("--window must be >= 2 and --hop must be >= 1")

    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)
    if n < max(cfg.envelope_window, 256):
        raise SystemExit("Duration is too short for the selected analysis windows")

    t = np.arange(n) / cfg.fs
    rng = np.random.default_rng(cfg.seed)
    library, gates, ams = build_library(t, args.stages)
    keys = list(library)
    raw_templates, normalized_templates = build_envelope_templates(
        library, cfg.envelope_window, cfg.envelope_hop
    )
    similarity = similarity_matrix(normalized_templates, keys)
    classes = build_equivalence_classes(similarity, keys, cfg.equivalence_threshold)
    class_lookup = {key: ci for ci, group in enumerate(classes) for key in group}

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

    print("\n" + "=" * 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}\n")

    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}\n")

    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

    am_name = next(k for k in ams if k.startswith("W a0.5"))
    selected_key = ("C1.0", am_name)
    selected_atom = library[selected_key]
    single_x = 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(single_x)):8.3f} dB")
    print(f"  Modulated ensemble SFM:  {spectral_flatness_db(modulated_power):8.3f} dB\n")

    print("[2] COMODULATION — six 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_band = band_split(rng.standard_normal(n), cfg.fs, lo, hi)
        atom_key = keys[int(rng.integers(len(keys)))]
        independent += carrier_band * library[atom_key]

    f = np.fft.rfftfreq(n, d=1.0 / cfg.fs)
    pink_scale = 1.0 / np.sqrt(np.maximum(f, 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),
    ):
        env = band_envelopes(signal, cfg.fs)
        print(f"  {name:34s} comodulation={comodulation_index(env): .4f}")
    print()

    print("[3] ENVELOPE PURSUIT — fresh carrier per observation")
    exact_count = class_count = ambiguous_count = 0
    r2_values, best_scores, second_scores, gains = [], [], [], []
    records = []

    for _ in range(cfg.trials):
        true_key = keys[int(rng.integers(len(keys)))]
        x = rng.standard_normal(n) * library[true_key]
        predicted, gain, r2, second, ambiguous, scores = pursuit(
            x, library, raw_templates, normalized_templates, keys,
            cfg.envelope_window, cfg.envelope_hop, cfg.ambiguity_threshold,
        )
        exact = predicted == true_key
        same_class = class_lookup[predicted] == class_lookup[true_key]
        exact_count += int(exact)
        class_count += int(same_class)
        ambiguous_count += int(ambiguous)
        r2_values.append(r2)
        best_scores.append(float(np.max(scores)))
        second_scores.append(second)
        gains.append(gain)
        records.append((true_key, predicted, exact, same_class, ambiguous))

    print(f"  Exact atom recovery:     {exact_count}/{cfg.trials} ({100*exact_count/cfg.trials:.1f}%)")
    print(f"  Class recovery:          {class_count}/{cfg.trials} ({100*class_count/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(gains):.4f}\n")

    print("[4] IDENTIFIABILITY — ten most similar atom pairs")
    pair_i, pair_j = np.triu_indices(len(keys), k=1)
    pair_scores = similarity[pair_i, pair_j]
    top = np.argsort(pair_scores)[::-1][:min(10, len(pair_scores))]
    for idx in top:
        i, j = pair_i[idx], pair_j[idx]
        print(f"  {pair_scores[idx]:.5f}  {keys[i]}  <->  {keys[j]}")
    print()

    print("[5] ENSEMBLE PSD INDISTINGUISHABILITY — independent carriers")
    oracle_lsd, decoded_lsd = [], []
    lsd_trials = max(2, min(8, cfg.trials))
    for true_key, predicted, *_ in records:
        true_atom = library[true_key]
        predicted_atom = library[predicted]
        oracle_lsd.append(spectral_lsd(true_atom, true_atom, rng, lsd_trials))
        decoded_lsd.append(spectral_lsd(true_atom, predicted_atom, rng, lsd_trials))
    print(f"  Oracle same-atom LSD:    {np.mean(oracle_lsd):.4f} dB")
    print(f"  Decoded-atom LSD:        {np.mean(decoded_lsd):.4f} dB\n")

    print("[6] PLAIN WHITE NEGATIVE CONTROL")
    negative_r2, negative_scores = [], []
    for _ in range(min(30, cfg.trials)):
        x = rng.standard_normal(n)
        _, _, r2, _, _, scores = pursuit(
            x, library, raw_templates, normalized_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}\n")

    print("[7] INFORMATION ACCOUNTING")
    print(f"  Nominal library bits:    {nominal_bits:.3f}")
    print(f"  Effective class bits:    {effective_bits:.3f}")
    print(f"  Nominal rate:            {nominal_bits/cfg.duration:.3f} bits/s")
    print(f"  Class rate:              {effective_bits/cfg.duration:.3f} bits/s")
    print(f"  Exact recovery rate:     {exact_count/cfg.trials:.4f}")
    print(f"  Class recovery rate:     {class_count/cfg.trials:.4f}\n")

    print("=" * 72)
    print("END OF EXPERIMENT")
    print("=" * 72)
    print("Interpretation:")
    print("  1. Ensemble PSD tests spectral flatness in expectation.")
    print("  2. Single-record PSD shows finite-realization spectral variation.")
    print("  3. Comodulation measures shared band-energy fluctuations.")
    print("  4. Exact recovery tests atom identity; class recovery handles aliases.")
    print("  5. LSD compares ensemble spectra, not stochastic waveforms; similar")
    print("     LSD across different atoms is expected if modulation is PSD-invisible.")
    print("  6. Effective bits count threshold-defined template classes, not channel capacity.")


if __name__ == "__main__":
    main()
