"""MATH-18: exact recorded-decimal gradients, Hessians and Taylor identities. Standard library."""
from pathlib import Path
from fractions import Fraction as Q
import csv,json
root=Path(__file__).resolve().parent
def read(name):
    with(root/name).open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))
country=read('math15-sources/korea-2014-2024-gdp-linear-projection.csv')
Xc=[[Q(1),Q(r['centered_year_u'])]for r in country];yc=[Q(r['reported_GDPpc_constant2015USD_per_person'])for r in country]
house=read('math16-sources/household-2006-12-17-two-submeter-observations.csv')
Yh=[[Q(r['reported_kitchen_energy_Wh']),Q(r['reported_laundry_energy_Wh'])]for r in house]
company=read('math16-sources/apple-sales-two-year-gram-input.csv')
Xe=[[Q(r['reported_FY2023_net_sales_million_USD']),Q(int(i==4))]for i,r in enumerate(company)];ye=[Q(r['reported_FY2024_net_sales_million_USD'])for r in company]
def dot(a,b):return sum(x*y for x,y in zip(a,b))
def fitting(X,y,p):
    n=len(y);res=[dot(r,p)-v for r,v in zip(X,y)]
    H=[[sum(r[i]*r[j]for r in X)/n for j in range(2)]for i in range(2)]
    return dot(res,res)/(2*n),[sum(r[j]*e for r,e in zip(X,res))/n for j in range(2)],H
def household(p):
    n=len(Yh);res=[[p[i]-r[i]for i in range(2)]for r in Yh]
    return sum(dot(r,r)for r in res)/(2*n),[sum(r[i]for r in res)/n for i in range(2)],[[Q(1),Q(0)],[Q(0),Q(1)]]
hm=[sum(r[i]for r in Yh)/len(Yh)for i in range(2)]
specs=[('country',lambda p:fitting(Xc,yc,p),[Q(33000),Q(700)],[Q(50),Q(10)]),('person',household,hm,[Q(1,10),Q(1,5)]),('company',lambda p:fitting(Xe,ye,p),[Q(1),Q(0)],[Q(1,1000),Q(100)])]
results={};profiles=[]
for kind,evaluate,p,h in specs:
    loss,g,H=evaluate(p);after=[p[i]+h[i]for i in range(2)];new,_,_=evaluate(after);term=dot(h,[dot(r,h)for r in H])/2
    assert new==loss+dot(g,h)+term
    det=H[0][0]*H[1][1]-H[0][1]*H[1][0];opt=[p[0]-(H[1][1]*g[0]-H[0][1]*g[1])/det,p[1]-(-H[1][0]*g[0]+H[0][0]*g[1])/det];optloss,optg,_=evaluate(opt)
    assert optg==[0,0]and det>0 and H[0][0]>0
    vals=dict(loss=loss,g1=g[0],g2=g[1],h11=H[0][0],h12=H[0][1],h22=H[1][1],next_loss=new,quadratic_term=term,opt1=opt[0],opt2=opt[1],opt_loss=optloss)
    results.update({kind+'_'+k:float(v)for k,v in vals.items()})
    for i in range(11):
        t=Q(i,10);z=[p[j]+t*h[j]for j in range(2)];actual,_,_=evaluate(z);first=loss+t*dot(g,h);second=first+t*t*term;assert actual==second
        profiles.append(dict(dataset=kind,t=str(t),p1=str(z[0]),p2=str(z[1]),loss=float(actual),loss_exact_fraction=str(actual),linear=float(first),taylor2=float(second),difference_exact_fraction=str(actual-second)))
results.update(base_f=4,base_fx=3,base_fy=5,chain_value=8,chain_ds=16,chain_dt=11)
with(root/'math18-loss-paths.csv').open('w',encoding='utf-8',newline='')as f:
    w=csv.DictWriter(f,fieldnames=list(profiles[0]));w.writeheader();w.writerows(profiles)
(root/'math18-results.json').write_text(json.dumps(results,ensure_ascii=False,indent=2)+'\n',encoding='utf-8')
print('MATH-18: exact source objectives, gradients, Hessians, joint optima and 33 path identities checked.')
