"""MATH-23. Independent raw-data L1, SVD/projection and projected-GD reproduction.
Original observations remain unchanged; penalties and constraints are teaching choices.
"""
from pathlib import Path
from fractions import Fraction as Q
from decimal import Decimal,localcontext
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 dec(v):return Decimal(v.numerator)/Decimal(v.denominator)if isinstance(v,Q)else Decimal(v)
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];a=sum(y)/len(y);b=sum(v*w for v,w in zip(u,y))/sum(v*v for v in u);s=b/100;h=Q(1,10);Fstar=sum((a+b*v-w)**2 for v,w in zip(u,y))/(2*len(y)*1000000)
cert=[]
for r in rows('math23-sources/korea-L1-threshold-path-and-exact-dual-certificates.csv'):
 tau=Q(r['tau_exact_fraction']);v=max(s-tau/h,0);dualU=h*(s-v);P=Fstar+h*(v-s)**2/2+tau*v;D=Fstar+s*dualU-dualU**2/(2*h);assert P==D
 with localcontext()as ctx:
    ctx.prec=110;assert abs(dec(v)-Decimal(r['fitted_dimensionless_slope_v_NOT_observed']))<Decimal('1e-75');assert abs(dec(P)-Decimal(r['primal_normalized_penalized_objective']))<Decimal('1e-75')
 cert.append(dict(case='country',parameter=str(tau),primal=float(P),dual=float(D),gap=float(P-D),exact_gap=str(P-D)))
tau=Q(1,2);v=max(s-tau/h,0);P=Fstar+h*(v-s)**2/2+tau*v
results=dict(country_intercept=a,country_slope=b,country_threshold=h*s,country_tauHalf_slope=100*v,country_tauHalf_objective=P)
power=rows('math10-sources/power-2006-12-17.csv');actual=[[Q(r[k])for k in ['Sub_metering_1','Sub_metering_2']]for r in power];N=len(actual);mu=[sum(p[i]for p in actual)/N for i in range(2)];cov=[[sum((p[i]-mu[i])*(p[j]-mu[j])for p in actual)/N for j in range(2)]for i in range(2)];stored=rows('math23-sources/household-actual-SVD-derived-and-orthant-projected.csv')
with localcontext()as ctx:
 ctx.prec=110;aD,bD,dD=dec(cov[0][0]),dec(cov[0][1]),dec(cov[1][1]);lam=(aD+dD+((aD-dD)**2+4*bD*bD).sqrt())/2;norm=(bD*bD+(lam-aD)**2).sqrt();axis=[bD/norm,(lam-aD)/norm];mean=list(map(dec,mu));before=after=movement=Decimal(0);negative=0;derivedCells=0
 for obs,row in zip(actual,stored):
    obsD=list(map(dec,obs));score=sum(axis[i]*(obsD[i]-mean[i])for i in range(2));z=[mean[i]+axis[i]*score for i in range(2)];p=[max(v,0)for v in z]
    for i,key in enumerate(['stored_SVD_approx_kitchen_Wh_NOT_observed','stored_SVD_approx_laundry_Wh_NOT_observed']):assert abs(z[i]-Decimal(row[key]))<Decimal('1e-75');derivedCells+=1
    negative+=any(v<0 for v in z);before+=sum((z[i]-obsD[i])**2 for i in range(2));after+=sum((p[i]-obsD[i])**2 for i in range(2));movement+=sum((p[i]-z[i])**2 for i in range(2))
 results.update(household_n=N,household_negative_records=negative,household_before_squared_error=before,household_after_squared_error=after,household_projection_movement_squared=movement,household_derived_cells_verified=derivedCells)
Arows=rows('math16-sources/apple-sales-two-year-gram-input.csv');x=[Q(r['reported_FY2023_net_sales_million_USD'])/100000 for r in Arows];z=[Q(r['reported_FY2024_net_sales_million_USD'])/100000 for r in Arows];A=sum(v*v for v in x)/5;B=sum(v*w for v,w in zip(x,z))/5;C0=sum(v*v for v in z)/10;alpha0=B/A;lower=Q(95,100);upper=Q(101,100);eta=Q(1,5);alpha=Q(1);first=None
for k in range(11):
 g=A*alpha-B;nextAlpha=min(upper,max(lower,alpha-eta*g));nuU=-g;P=A*alpha**2/2-B*alpha+C0;D=C0-(B-nuU)**2/(2*A)-nuU*upper;assert P-D>=0
 if alpha==upper and first is None:first=k
 cert.append(dict(case='company',parameter=str(k),primal=float(P),dual=float(D),gap=float(P-D),exact_gap=str(P-D)));alpha=nextAlpha
assert first==4 and negative==756
results.update(company_A=A,company_B=B,company_C0=C0,company_alpha0=alpha0,company_constrained_alpha=upper,company_gradient_at_optimum=A*upper-B,company_nu_upper=B-A*upper,company_first_boundary=first,company_optimal_objective=A*upper**2/2-B*upper+C0)
with(root/'math23-independent-certificates.csv').open('w',encoding='utf-8',newline='')as f:
 w=csv.DictWriter(f,fieldnames=list(cert[0]));w.writeheader();w.writerows(cert)
(root/'math23-results.json').write_text(json.dumps({k:float(v)for k,v in results.items()},indent=2)+'\n',encoding='utf-8')
print('MATH-23: 22 exact L1 dual certificates, 2880 raw-data SVD cells and 11 projected-GD dual certificates passed.')
