"""
Tajwells Theoretical Research Lab (Non-Commercial)
Reproducible Benchmark: Balanced Ternary {-1, 0, +1} Sparse Zero-Skipping

Measures software operation-count reduction when skipping Polarity::ZERO (0)
nodes versus dense multiply-accumulate evaluation across controlled sparsity levels.
Note: Reports algorithmic operation counts and Python loop timing only; does not
imply physical silicon fabrication performance.
"""

import random
import time


def generate_trinary_vector(length: int, zero_prob: float, seed: int) -> list[int]:
    """Generate a reproducible balanced ternary vector in {-1, 0, +1}."""
    rng = random.Random(seed)
    vec = []
    for _ in range(length):
        if rng.random() < zero_prob:
            vec.append(0)
        else:
            vec.append(-1 if rng.random() < 0.5 else 1)
    return vec


def dense_trinary_dot(a: list[int], b: list[int]) -> tuple[int, int]:
    """Evaluate all N elements unconditionally."""
    acc = 0
    ops = 0
    for x, y in zip(a, b):
        acc += x * y
        ops += 1
    return acc, ops


def sparse_trinary_dot(a_nonzero: list[tuple[int, int]], b: list[int]) -> tuple[int, int]:
    """Evaluate only non-zero entries of `a`, skipping Polarity::ZERO states."""
    acc = 0
    ops = 0
    for idx, x in a_nonzero:
        y = b[idx]
        if y == 0:
            continue
        acc += x * y
        ops += 1
    return acc, ops


def main() -> None:
    length = 100_000
    seed = 42
    b = generate_trinary_vector(length, zero_prob=0.5, seed=seed + 1)

    print(f"Balanced Ternary Sparse Dot-Product Benchmark (N={length:,}, seed={seed})")
    print("-" * 78)
    print(f"{'Target Zero %':>13} | {'Actual A Zero %':>15} | {'Dense Ops':>10} | {'Sparse Ops':>10} | {'Op Reduction':>12} | {'Match':>5}")
    print("-" * 78)

    for z in (0.0, 0.5, 0.7, 0.8, 0.9):
        a = generate_trinary_vector(length, zero_prob=z, seed=seed + int(z * 100))
        a_nz = [(i, v) for i, v in enumerate(a) if v != 0]

        t0 = time.perf_counter()
        d_acc, d_ops = dense_trinary_dot(a, b)
        t1 = time.perf_counter()
        s_acc, s_ops = sparse_trinary_dot(a_nz, b)
        t2 = time.perf_counter()

        actual_zero_pct = (1.0 - (len(a_nz) / length)) * 100.0
        reduction_pct = (1.0 - (s_ops / d_ops)) * 100.0
        match = d_acc == s_acc
        _ = (t1 - t0, t2 - t1)

        print(
            f"{z*100:12.1f}% | {actual_zero_pct:14.2f}% | {d_ops:10,d} | {s_ops:10,d} | {reduction_pct:11.2f}% | {str(match):>5}"
        )


if __name__ == "__main__":
    main()
