#!/usr/bin/env python3
"""MIT License. Original periodic FM/noise teaching reference; requires NumPy.
python3 fm_threshold_reference.py > results.json
Independent FFT noise synthesis, angle unwrap, and FFT output filtering.
No claim of a universal hardware threshold; full 8 s block is periodic.
"""
import json
import numpy as np

def coefficients(seed=7, modes=64):
    state = seed
    def uniform():
        nonlocal state
        state ^= (state << 13) & 0xffffffff
        state ^= state >> 17
        state ^= (state << 5) & 0xffffffff
        state &= 0xffffffff
        return (state + .5) / 4294967296
    ans = []
    for k in range(-modes, modes+1):
        radius = np.sqrt(-np.log(uniform()) / (2*modes+1))
        angle = 2*np.pi*uniform()
        ans.append((k, radius*np.exp(1j*angle)))
    return ans

def simulate(cnr_db, seed=7, samples=16384):
    duration, deviation = 8., 2.
    dt = duration / samples
    t = np.arange(samples)*dt
    bins = np.zeros(samples, dtype=complex)
    for k, c in coefficients(seed):
        bins[k % samples] = c * samples
    noise = np.fft.ifft(bins) * 10**(-cnr_db/20)
    phase = 2*np.sin(2*np.pi*t)
    received = np.exp(1j*phase)+noise
    # Unwrap entire measured phase including the periodic closing sample.
    unwrapped = np.unwrap(np.angle(np.r_[received, received[0]]))
    raw = np.diff(unwrapped)/(2*np.pi*dt*deviation)
    target = np.diff(np.r_[phase,phase[0]])/(2*np.pi*dt*deviation)
    qrot = np.imag(noise*np.exp(-1j*phase))
    linear = target + np.diff(np.r_[qrot,qrot[0]])/(2*np.pi*dt*deviation)
    def lowpass(x):
        spectrum = np.fft.fft(x)
        spectrum[np.abs(np.fft.fftfreq(samples,dt)) > 1.5] = 0
        return np.fft.ifft(spectrum).real
    y, yl = lowpass(raw), lowpass(linear)
    indices = [0,113,2048,8001,samples-1]
    return dict(seed=seed, cnrDb=cnr_db, samples=samples,
        rmse=float(np.sqrt(np.mean((y-target)**2))),
        linearRmse=float(np.sqrt(np.mean((yl-target)**2))),
        netWinding=int(round((unwrapped[-1]-unwrapped[0])/(2*np.pi))),
        mean=float(np.mean(y)), noisePower=float(np.mean(abs(noise)**2)),
        probes=[dict(index=j, output=float(y[j]),linearOutput=float(yl[j]),raw=float(raw[j])) for j in indices])

if __name__ == '__main__':
    print(json.dumps([simulate(cnr,seed) for seed in [7,19,41] for cnr in [24,12,8,4,0,-4]],indent=2))
