#!/usr/bin/env python3
"""Verify the rose-curve sideband identity used by piece 023."""
import math

N = 8192
TOL = 2e-12


def coeff(values, harmonic):
    return sum(v * complex(math.cos(-harmonic*t), math.sin(-harmonic*t))
               for v, t in values) / N


worst_identity = 0.0
worst_leak = 0.0
rows = []

for k in range(2, 13):
    xs, ys = [], []
    for j in range(N):
        t = 2 * math.pi * j / N
        r = math.cos(k*t)
        x = r * math.cos(t)
        y = r * math.sin(t)
        x_expected = .5 * (math.cos((k-1)*t) + math.cos((k+1)*t))
        y_expected = .5 * (math.sin((k+1)*t) - math.sin((k-1)*t))
        worst_identity = max(worst_identity, abs(x-x_expected), abs(y-y_expected))
        xs.append((x, t)); ys.append((y, t))

    allowed = {k-1, k+1}
    leak = max(abs(coeff(xs, h)) + abs(coeff(ys, h))
               for h in range(0, 20) if h not in allowed)
    worst_leak = max(worst_leak, leak)
    rows.append((k, k-1, k+1, leak))

print("rose r(t)=cos(k t): coordinate spectrum")
for k, lo, hi, leak in rows:
    print(f"k={k:2d} -> harmonics {lo:2d} and {hi:2d}; largest tested other bin {leak:.3e}")
print(f"worst pointwise identity error: {worst_identity:.3e}")
print(f"worst tested spectral leakage: {worst_leak:.3e}")
holds = worst_identity < TOL and worst_leak < TOL
print(f"claim holds: {holds}")
raise SystemExit(0 if holds else 1)
