"""MATH-12: explicit algorithms and actual recorded-decimal power sums. Standard library."""
from pathlib import Path
from decimal import Decimal,localcontext,ROUND_HALF_UP
from fractions import Fraction
import csv,json,math
root=Path(__file__).resolve().parent
def read(name):
    with (root/name).open(encoding='utf-8-sig',newline='') as f:return list(csv.DictReader(f))
def sequential(values):
    s=0.0
    for v in values:s+=v
    return s
def kahan(values):
    s=c=0.0
    for v in values:
        y=v-c;t=s+y;c=(t-s)-y;s=t
    return s
def neumaier(values):
    s=c=0.0
    for v in values:
        t=s+v;c+=(s-t)+v if abs(s)>=abs(v) else (v-t)+s;s=t
    return s+c
results={}
for power in [2,4]:
    f=lambda x:x**power
    for n in [2,4,10,100]:
        h=Fraction(1,n);nodes=[Fraction(i,n) for i in range(n+1)]
        trap=h*(sum(f(x) for x in nodes[1:-1])+(f(nodes[0])+f(nodes[-1]))/2)
        simp=h*(f(nodes[0])+f(nodes[-1])+sum((4 if i%2 else 2)*f(nodes[i]) for i in range(1,n)))/3
        for name,value in [('trapezoid',trap),('simpson',simp)]:results[f'x{power}_{name}_{n}']=float(value)
perms=[[1e16,1,-1e16],[1e16,-1e16,1],[1,1e16,-1e16],[1,-1e16,1e16],[-1e16,1e16,1],[-1e16,1,1e16]]
for i,v in enumerate(perms):
    for name,fn in [('sequential',sequential),('kahan',kahan),('neumaier',neumaier)]:results[f'sum_{i}_{name}']=fn(v)
for label,file in [('complete','power-2006-12-17.csv'),('missing','power-2007-04-28.csv')]:
    rows=read('math10-sources/'+file);values=[Decimal(r['Global_active_power']) for r in rows if r['Global_active_power'] not in ('','?','NA')]
    watts=[int(v*1000) for v in values];results[label+'_known']=len(watts);results[label+'_missing']=len(rows)-len(watts)
    results[label+'_integer_w_sum']=sum(watts);results[label+'_reference_kwh']=float(Fraction(sum(watts),60000))
    for d in range(4):
        step=10**(3-d);rounded=sum(((2*w+step)//(2*step))*step for w in watts)
        results[f'{label}_round{d}_kwh']=float(Fraction(rounded,60000))
    if label=='complete':
        hour_sums=[sum(watts[i:i+60]) for i in range(0,1440,60)]
        results['rounded_hour_groups_kwh']=sum((v+300)//600 for v in hour_sums)/100
        results['first3_energy_kwh']=float(Fraction(sum(watts[:3]),60000))
for x in [.01,.1,1.0]:
    results[f'exp_forward_h{x:g}']=(math.exp(1+x)-math.e)/x
    results[f'exp_central_h{x:g}']=(math.exp(1+x)-math.exp(1-x))/(2*x)
rows=[]
with localcontext() as ctx:
    ctx.prec=70
    for k in range(1,19):
        x=Decimal(10)**(-k);reference=1/((1+x).sqrt()+1);xf=float(x);direct=(math.sqrt(1+xf)-1)/xf;stable=1/(math.sqrt(1+xf)+1)
        rows.append(dict(k=k,x=str(x),decimal_reference=str(reference),binary_direct=direct,binary_stable=stable,direct_error=float(Decimal.from_float(direct)-reference),stable_error=float(Decimal.from_float(stable)-reference)))
with (root/'math12-cancellation.csv').open('w',encoding='utf-8',newline='') as f:
    w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows)
(root/'math12-results.json').write_text(json.dumps(results,indent=2)+'\n',encoding='utf-8')
print('MATH-12:',len(results),'quantities; 18 high-precision cancellation references')
