#!/usr/bin/env python3
"""End-correction sensitivity using a small-error Gaussian likelihood; stdlib.
This is not York's full correlated errors-in-variables method.
"""
import csv,json,math
from pathlib import Path

def golden(f,a,b):
    g=(math.sqrt(5)-1)/2;c=b-g*(b-a);d=a+g*(b-a);fc=f(c);fd=f(d)
    for _ in range(90):
        if fc<fd:b,d,fd=d,c,fc;c=b-g*(b-a);fc=f(c)
        else:a,c,fc=c,d,fd;d=a+g*(b-a);fd=f(d)
    return (a+b)/2

def nll(rows,speed,offset):
    total=0.0
    for L,n,f,sf,sl in rows:
        pred=n*speed/(2*(L+offset))
        variance=sf**2+(pred*sl/(L+offset))**2
        total+=0.5*(math.log(2*math.pi*variance)+(f-pred)**2/variance)
    return total

def fit(rows):
    speed=343.2;offset=0.0
    # Profile speed for each offset, then optimize the one-dimensional profile.
    def profile(delta):
        v=golden(lambda v:nll(rows,v,delta),250,450)
        return nll(rows,v,delta)
    offset=golden(profile,-0.05,0.05)
    speed=golden(lambda v:nll(rows,v,offset),250,450)
    fixed=golden(lambda v:nll(rows,v,0),250,450)
    return dict(speed_with_end_correction_m_s=speed,total_end_correction_m=offset,
        zero_correction_speed_m_s=fixed,nll_with_end_correction=nll(rows,speed,offset),nll_zero_correction=nll(rows,fixed,0),
        bounds=dict(speed_m_s=[250,450],end_correction_m=[-0.05,0.05]))

def main():
    with (Path(__file__).parent/'synthetic-demo.csv').open() as f: raw=list(csv.DictReader(f))
    rows=[tuple(float(r[k]) for k in ['length_m','mode','frequency_hz','sigma_frequency_hz','sigma_length_m']) for r in raw]
    control=[(L,1,343.2/(2*(L+0.008)),0.35,0.0) for L in [0.15,0.18,0.22,0.26,0.31,0.37,0.44,0.53,0.64,0.76,0.9,1.05]]
    positive=fit(control)
    assert abs(positive['total_end_correction_m']-0.008)<1e-6
    assert abs(positive['speed_with_end_correction_m_s']-343.2)<0.002
    return dict(status='Synthetic software checks only',boundary='Open-open acoustic cavity; ideal closed-closed has the same frequency formula. Closed-open requires (2n-1)*v/(4L).',
        model='f=n*v/[2*(L+Delta)]; Delta is the total end correction',
        likelihood='Independent Gaussian frequency errors with small length errors propagated to frequency; includes log variance. No correlated calibration, exact latent-length likelihood, humidity or temperature model.',
        nominal_demo=fit(rows),noiseless_8mm_positive_control=positive,
        note='A frequency-axis intercept is not an end-correction parameter. A transformed plot n/(2f) versus L has slope 1/v and intercept Delta/v, with errors on both axes. Reference v is illustrative near room temperature, not a calibrated universal constant.')

if __name__=='__main__':print(json.dumps(main(),indent=2,allow_nan=False))
