#!/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.')



def bisect_crossing(fn,a,b):
    fa,fb=fn(a),fn(b)
    if fa*fb>0: return None
    for _ in range(65):
        mid=(a+b)/2;fm=fn(mid)
        if fa*fm<=0:b,fb=mid,fm
        else:a,fa=mid,fm
    return (a+b)/2

def uncertainty_results():
    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]
    result=main();best=result['nominal_demo'];dhat=best['total_end_correction_m'];vhat=best['speed_with_end_correction_m_s'];minimum=best['nll_with_end_correction']
    threshold=1.920729410347062
    def profile_d(delta):return nll(rows,golden(lambda v:nll(rows,v,delta),250,450),delta)
    def profile_v(v):return nll(rows,v,golden(lambda d:nll(rows,v,d),-0.05,0.05))
    delta_ci=[bisect_crossing(lambda d:profile_d(d)-minimum-threshold,-0.05,dhat),bisect_crossing(lambda d:profile_d(d)-minimum-threshold,dhat,0.05)]
    speed_ci=[bisect_crossing(lambda v:profile_v(v)-minimum-threshold,250,vhat),bisect_crossing(lambda v:profile_v(v)-minimum-threshold,vhat,450)]
    assert all(x is not None for x in delta_ci+speed_ci)
    grid=[dhat-0.001+i*0.000025 for i in range(81)]
    result['profile_uncertainty']={'total_end_correction_m':delta_ci,'speed_m_s':speed_ci,
        'nominal_level':0.95,'nll_increase_threshold':threshold,
        'method':'Separate one-parameter profile likelihood intervals; nuisance parameter reoptimized; asymptotic chi-square(1), not joint 95% coverage.',
        'limitations':'Conditional on supplied independent Gaussian errors and linearized length uncertainty; 12 synthetic rows. No empirical coverage validation or shared calibration/systematic-error budget. Negative fitted correction is a diagnostic of noise, not a negative physical opening length.',
        'offset_profile':[{'offset_m':d,'delta_nll':profile_d(d)-minimum} for d in grid]}
    return result

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