"""Independent error-coordinate PLL integration with SciPy DOP853. MIT license.
Run: python3 fm_pll_reference.py  (requires numpy and scipy).
The error ODE is a reference calculation, not a receiver with access to true FM.
"""
import json
import math
import numpy as np
from scipy.integrate import solve_ivp

TAU = 2*math.pi

def reference(natural_hz=2, message_hz=1, offset_hz=0, deviation=2, phase=80*math.pi/180):
    wn = TAU*natural_hz
    kp, ki = math.sqrt(2)*wn, wn*wn
    def rhs(t, state):
        error, integrator = state
        detector = math.sin(error)
        return [TAU*(offset_hz+deviation*math.cos(TAU*message_hz*t))-integrator-kp*detector, ki*detector]
    times = [0, .05, .1, .25, .5, 1, 2, 4, 6, 6.125, 6.5, 7.75, 8]
    result = solve_ivp(rhs, [0, 8], [phase, 0], method='DOP853', t_eval=times, rtol=2e-11, atol=2e-12, max_step=.01)
    if not result.success:
        raise RuntimeError(result.message)
    rows = []
    for t, error, integrator in zip(result.t, result.y[0], result.y[1]):
        estimate = (integrator+kp*math.sin(error))/TAU
        rows.append(dict(t=float(t), error=float(error), integrator=float(integrator), estimateHz=float(estimate)))
    return dict(naturalHz=natural_hz, messageHz=message_hz, offsetHz=offset_hz, rows=rows)

if __name__ == '__main__':
    print(json.dumps([reference(n, m, o) for n in [.5, 2, 8] for m in [1, 4] for o in [0, 4, 12]], indent=2))
