"""Exact rational gradient-descent trajectories from fixed public observations.
Iteration is computational, not future country/household/company observations.
"""
from pathlib import Path
from fractions import Fraction as Q
import csv,json
root=Path(__file__).resolve().parent
def rows(f):
    with(root/f).open(encoding='utf-8-sig',newline='')as h:return list(csv.DictReader(h))
def system(X,y,start):
    n=len(y);H=[[sum(row[i]*row[j]for row in X)/n for j in range(2)]for i in range(2)];b=[sum(row[i]*v for row,v in zip(X,y))/n for i in range(2)];det=H[0][0]*H[1][1]-H[0][1]**2
    star=[(b[0]*H[1][1]-b[1]*H[0][1])/det,(H[0][0]*b[1]-H[0][1]*b[0])/det];Fstar=sum((sum(x*t for x,t in zip(row,star))-v)**2 for row,v in zip(X,y))/(2*n)
    return dict(H=H,star=star,Fstar=Fstar,start=list(map(Q,start)))
C=rows('math15-sources/korea-2014-2024-gdp-linear-projection.csv');u=[Q(r['centered_year_u'])for r in C];y=[Q(r['reported_GDPpc_constant2015USD_per_person'])for r in C];country=system([[Q(1),v/10]for v in u],[v/1000 for v in y],[33,7])
P=rows('math10-sources/power-2006-12-17.csv');p1=[Q(r['Sub_metering_1'])for r in P];p2=[Q(r['Sub_metering_2'])for r in P];mu=[sum(p1)/len(p1),sum(p2)/len(p2)];person=dict(H=[[Q(1),Q(0)],[Q(0),Q(1)]],star=mu,Fstar=sum((v-mu[0])**2+(w-mu[1])**2 for v,w in zip(p1,p2))/(2*len(p1)),start=[Q(0),Q(0)])
A=rows('math16-sources/apple-sales-two-year-gram-input.csv');x=[Q(r['reported_FY2023_net_sales_million_USD'])for r in A];z=[Q(r['reported_FY2024_net_sales_million_USD'])for r in A];dummy=[Q(i==4)for i in range(5)];systems=dict(country=country,person=person)
for key,scale in [('companyUnit1',Q(1)),('companyScaled',Q(100000))]:systems[key]=system([[v/100000,d*scale/100000]for v,d in zip(x,dummy)],[v/100000 for v in z],[1,0])
settings=[('country','eta1',Q(1)),('country','eta20div11',Q(20,11)),('country','eta2',Q(2)),('country','eta2p1',Q(21,10)),('person','etaHalf',Q(1,2)),('person','eta1',Q(1)),('person','eta2',Q(2)),('person','eta2p1',Q(21,10)),('companyUnit1','unit1_eta1',Q(1)),('companyScaled','scaled_eta1',Q(1))]
results={};profiles=[]
for key,m in systems.items():
    for i in range(2):
        results[key+'_star'+str(i)]=float(m['star'][i])
        for j in range(2):results[key+'_H'+str(i)+str(j)]=float(m['H'][i][j])
    results[key+'_Fstar']=float(m['Fstar'])
for key,label,eta in settings:
    m=systems[key];theta=m['start'][:];H=m['H'];initial=None
    for k in range(21):
        e=[theta[i]-m['star'][i]for i in range(2)];g=[sum(H[i][j]*e[j]for j in range(2))for i in range(2)];gap=sum(e[i]*g[i]for i in range(2))/2
        if initial is None:initial=gap
        profiles.append(dict(system=key,step=label,k=k,theta1=float(theta[0]),theta2=float(theta[1]),gap=float(gap),relative_gap=float(gap/initial),gap_exact_fraction=str(gap)))
        if k==20:
            for i in range(2):results[key+'_'+label+'_theta'+str(i)]=float(theta[i])
            results[key+'_'+label+'_gap']=float(gap)
        theta=[theta[i]-eta*g[i]for i in range(2)]
with(root/'math21-independent-trajectories.csv').open('w',encoding='utf-8',newline='')as f:
    w=csv.DictWriter(f,fieldnames=list(profiles[0]));w.writeheader();w.writerows(profiles)
(root/'math21-results.json').write_text(json.dumps(results,indent=2)+'\n',encoding='utf-8')
print('MATH-21: 4 actual-data quadratic systems and 210 exact-rational GD trajectory rows reproduced.')
