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