"""STAT-15: actual finite-law moments and conditional decomposition.
Actual data are read again; case JSON and prior results are not numeric inputs.
Python standard library only; no original data or recorded mass is overwritten.
"""
from pathlib import Path
from fractions import Fraction as Q
from decimal import Decimal as D,getcontext
from collections import Counter
from html.parser import HTMLParser
import csv,hashlib,json,re,io,zipfile,math,itertools
import xml.etree.ElementTree as ET
getcontext().prec=110
ROOT=Path(__file__).resolve().parent;WORKSPACE=ROOT.parents[1]
COMMON=ROOT/'\uc2e4\uc81c\ub370\uc774\ud130';DATA=ROOT/'stats15-sources'
METRICS={};EXACT={};AUDIT=[];CHECKS={'selectedValuesCompared':0}
def read(path):
    with path.open(encoding='utf-8-sig',newline='') as stream:return list(csv.DictReader(stream))
def note(path,purpose,original=False):AUDIT.append({'file':str(path.relative_to(ROOT)) if path.is_relative_to(ROOT) else str(path.relative_to(WORKSPACE)),'sha256':hashlib.sha256(path.read_bytes()).hexdigest(),'purpose':purpose,'archivedOriginalUsed':original})
APPROX=[]
def add(key,value):
    METRICS[key]=float(value)
    if isinstance(value,(Q,int)):EXACT[key]=str(Q(value))
    else:APPROX.append(key)
def near(a,b):assert abs(float(a)-float(Q(b)))<=1e-10*max(1,abs(float(a))),(a,b)
def same(value,stored):assert value==Q(stored),(value,stored);CHECKS['selectedValuesCompared']+=1



"""Stdlib numerical Student-t probabilities; not a data or case-result input.

Decimal Stirling normalization avoids large-df lgamma subtraction. A transformed,
scaled density integral computes survival probabilities directly, avoiding 1-CDF
cancellation. Published lesson values remain labeled numerical approximations.
"""
import math
from decimal import Decimal,localcontext
from functools import lru_cache
from statistics import NormalDist

def adaptive_integral(f,a,b,tolerance=2e-13,max_depth=28):
    fa,fb=f(a),f(b);mid=(a+b)/2;fm=f(mid);whole=(b-a)*(fa+4*fm+fb)/6
    def step(a,b,fa,fm,fb,whole,tol,depth):
        mid=(a+b)/2;leftmid=(a+mid)/2;rightmid=(mid+b)/2
        fl,fr=f(leftmid),f(rightmid)
        left=(mid-a)*(fa+4*fl+fm)/6;right=(b-mid)*(fm+4*fr+fb)/6
        delta=left+right-whole
        if abs(delta)<=15*tol:return left+right+delta/15
        if depth<=0:raise ArithmeticError('Adaptive integration did not converge')
        return step(a,mid,fa,fl,fm,left,tol/2,depth-1)+step(mid,b,fm,fr,fb,right,tol/2,depth-1)
    return step(a,b,fa,fm,fb,whole,tolerance,max_depth)

def _loggamma_without_constant(value):
    """logGamma minus .5*log(2*pi), with arguments shifted to at least64."""
    with localcontext() as ctx:
        ctx.prec=80;x=Decimal(str(value));correction=Decimal(0)
        while x<64:correction+=x.ln();x+=1
        pairs=[(1,6),(-1,30),(1,42),(-1,30),(5,66),(-691,2730),(7,6),(-3617,510),(43867,798),(-174611,330)]
        series=sum((Decimal(a)/b/(2*k*(2*k-1)*x**(2*k-1)) for k,(a,b) in enumerate(pairs,1)),Decimal(0))
        return (x-Decimal('.5'))*x.ln()-x+series-correction

@lru_cache(maxsize=256)
def student_log_normalizer(df):
    if not df>0:raise ValueError('Positive degrees of freedom required')
    with localcontext() as ctx:
        ctx.prec=80;nu=Decimal(str(df))
        ratio=_loggamma_without_constant((nu+1)/2)-_loggamma_without_constant(nu/2)
    return float(ratio)-.5*math.log(float(df)*math.pi)

def student_sf(t,df):
    """Upper-tail probability with direct scaled density integration."""
    t=float(t);df=float(df)
    if df<=0:raise ValueError('Positive degrees of freedom required')
    if t<0:return 1-student_sf(-t,df)
    if t==0:return .5
    if math.isinf(t):return 0.
    if df==1:return math.atan(1/t)/math.pi
    if df<=1:raise ValueError('This direct integral is used only for df>=1')
    base=math.log1p(t*t/df);logpdf=student_log_normalizer(df)-(df+1)*base/2
    def integrand(u):
        if u==1:return 0.
        x=t+u/(1-u)
        logratio=-(df+1)*(math.log1p(x*x/df)-base)/2-2*math.log1p(-u)
        return math.exp(logratio)
    tail=math.exp(logpdf)*adaptive_integral(integrand,0.,1.)
    if not 0<=tail<=.5+1e-12:raise ArithmeticError('Invalid Student-t upper tail')
    return min(.5,max(0.,tail))

@lru_cache(maxsize=256)
def student_quantile(probability,df):
    if not 0<probability<1:raise ValueError('Quantile probability must be inside(0,1)')
    if probability==.5:return 0.
    if probability<.5:return -student_quantile(1-probability,df)
    target=1-probability;left=0.;right=2.
    while student_sf(right,df)>target:right*=2
    for _ in range(56):
        mid=(left+right)/2
        if student_sf(mid,df)>target:left=mid
        else:right=mid
    return (left+right)/2

def normal_quantile(probability):return NormalDist().inv_cdf(probability)


def field(line,a,b):
    s=line[a-1:b].strip();return None if s in ['','.'] else Q(s)
raw=WORKSPACE/'work/textbooks-2026/raw';W=read(COMMON/'worldbank.csv');note(COMMON/'worldbank.csv','actual retained country-year observations');originalfile=raw/'worldbank-panel.json'
if originalfile.is_file():
    note(originalfile,'original World Bank API response',True);original=json.loads(originalfile.read_text(encoding='utf-8'),parse_float=D)[1];lookup={(r['countryiso3code'],r['date'],r['indicator']['id']):r['value'] for r in original};assert len(original)==6480
    for r in W:
        for key,code in [('gdp_pc','NY.GDP.PCAP.KD'),('life_expectancy','SP.DYN.LE00.IN')]:
            v=lookup[(r['country'],r['year'],code)]
            if v is None:assert r[key]==''
            else:same(Q(v),r[key])
countries=sorted([r for r in W if r['year']=='2024'],key=lambda r:r['country']);assert len(countries)==16
C=read(COMMON/'college-proximity.csv');note(COMMON/'college-proximity.csv','retained actual people with missingness');archive=raw/'proximity.zip';spec=[('person',1,5),('nearc4',10,10),('education',18,19),('age',24,25),('log_wage',86,97),('metro',116,116),('south',120,120)]
if archive.is_file():
    note(archive,'original Card fixed-width person observations',True)
    with zipfile.ZipFile(archive) as z:lines=z.read('nls.dat').decode('ascii').splitlines()
    assert len(lines)==len(C)==3613;people=[{k:field(line,a,b) for k,a,b in spec} for line in lines]
    for o,r in zip(people,C):
        for k,a,b in spec:
            if o[k] is None:assert r[k]==''
            else:same(o[k],r[k])
else:people=[{k:Q(r[k]) if r[k] else None for k,a,b in spec} for r in C]
w=[r['log_wage'] for r in people if r['log_wage'] is not None];assert len(w)==3010

wine=read(COMMON/'wine.csv');note(COMMON/'wine.csv','actual retained red-wine laboratory records');archive=raw/'wine-quality.zip'
if archive.is_file():
    note(archive,'original UCI red-wine measurements and codebook',True)
    with zipfile.ZipFile(archive) as z:original=list(csv.DictReader(io.StringIO(z.read('winequality-red.csv').decode('utf-8-sig')),delimiter=';'));book=z.read('winequality.names').decode('latin1')
    assert len(original)==len(wine)==1599 and 'median of at least 3 evaluations' in book
    for r,o in zip(wine,original):
        for k,v in o.items():same(Q(v),r[k.replace(' ','_')])
else:original=[{k:v for k,v in r.items() if k!='row_id'} for r in wine]
signatures=[tuple(Q(v) for k,v in o.items()) for o in original];frequencies=Counter(signatures)

vectors={'country':([Q(r['gdp_pc'])/10000 for r in countries],[Q(r['life_expectancy']) for r in countries],[r['country'] for r in countries]),'person':([o['education'] for o in people if o['log_wage'] is not None],[o['log_wage'] for o in people if o['log_wage'] is not None],[str(o['person']) for o in people if o['log_wage'] is not None]),'company':([Q(r['alcohol']) for r in wine],[Q(r['quality']) for r in wine],[r['row_id'] for r in wine])}
S=read(DATA/'actual16-country2024-GDPpc-and-period-life-expectancy.csv');note(DATA/'actual16-country2024-GDPpc-and-period-life-expectancy.csv','actual country measurements and GDP unit conversion')
for o,r in zip(countries,S):assert o['country']==r['country'];same(Q(o['gdp_pc']),r['reported_GDPpc_constant2015USD_per_person']);same(Q(o['gdp_pc'])/10000,r['chosen_GDPpc_10000USD_per_person_exact']);same(Q(o['life_expectancy']),r['reported_period_life_expectancy_years'])
S=read(DATA/'actual3613-person-schooling-and-preserved-missing-log-wages.csv');note(DATA/'actual3613-person-schooling-and-preserved-missing-log-wages.csv','actual people retain603 missing source logs');assert len(S)==3613
for o,r in zip(people,S):
    same(o['person'],r['source_person_ID']);same(o['education'],r['reported_education_years'])
    if o['log_wage'] is None:assert r['source_trimmed_log_wage']==''
    else:same(o['log_wage'],r['source_trimmed_log_wage'])
S=read(DATA/'actual1599-red-wine-laboratory-and-quality-records.csv');note(DATA/'actual1599-red-wine-laboratory-and-quality-records.csv','actual laboratory records preserve identical numeric rows');assert len(S)==1599
for o,sig,r in zip(wine,signatures,S):same(Q(o['alcohol']),r['reported_alcohol_percent_volume']);same(Q(o['quality']),r['reported_ordinal_expert_quality_score']);assert int(r['same_full_numeric_row_frequency'])==frequencies[sig]
SS=read(DATA/'actual-three-linear-projection-summaries.csv');note(DATA/'actual-three-linear-projection-summaries.csv','three projections independently recomputed by exact normal equations');summary={}
for case,srow in zip(['country','person','company'],SS):
    x,y,ids=vectors[case];n=len(x);sx=sum(x,Q(0));sy=sum(y,Q(0));sxxraw=sum((v*v for v in x),Q(0));sxyraw=sum((a*b for a,b in zip(x,y)),Q(0));slope=(n*sxyraw-sx*sy)/(n*sxxraw-sx*sx);intercept=(sy-slope*sx)/n;mx=sx/n;my=sy/n;sxx=sxxraw-sx*sx/n;sxy=sxyraw-sx*sy/n;fit=[intercept+slope*v for v in x];e=[b-f for b,f in zip(y,fit)];sse=sum((v*v for v in e),Q(0));sst=sum(((v-my)**2 for v in y),Q(0));s2=sse/(n-2);vc=s2/sxx;vr=Q(n,n-2)*sum(((v-mx)**2*r*r for v,r in zip(x,e)),Q(0))/sxx**2;sec=math.sqrt(float(vc));ser=math.sqrt(float(vr));t=float(slope)/sec;crit=student_quantile(.975,n-2);assert sum(e,Q(0))==sum((a*r for a,r in zip(x,e)),Q(0))==0
    vals=dict(n=n,df=n-2,x_mean_exact=mx,y_mean_exact=my,Sxx_exact=sxx,Sxy_exact=sxy,intercept_exact=intercept,slope_exact=slope,SSE_exact=sse,SST_exact=sst,R_squared_exact=1-sse/sst,working_residual_variance_exact=s2,classical_slope_variance_exact=vc,classical_slope_SE_approx=sec,HC1_slope_variance_exact=vr,HC1_slope_SE_approx=ser,classical_slope_t_approx=t,classical_slope_two_sided_p_approx=2*student_sf(abs(t),n-2),classical_slope_CI95_lower_approx=float(slope)-crit*sec,classical_slope_CI95_upper_approx=float(slope)+crit*sec);summary[case]=vals
    for key,v in vals.items():near(v,srow[key]);add(case+'_'+key,v)
    path=DATA/('actual-'+case+'-OLS-fits-residuals-leverage-and-influence.csv');S=read(path);note(path,'all original-record fits/residuals/leverage/influence recalculated');assert len(S)==n;hvals=[];cvals=[]
    for r,key,xx,yy,ff,ee in zip(S,ids,x,y,fit,e):
        assert r['source_ID']==str(key) or Q(r['source_ID'])==Q(key);hh=Q(1,n)+(xx-mx)**2/sxx;cc=ee**2/(2*s2)*hh/(1-hh)**2;hvals.append(hh);cvals.append(cc)
        for field,v in dict(actual_x_exact=xx,actual_y_exact=yy,observed_OLS_fit_exact=ff,within_fit_residual_exact=ee,residual_squared_exact=ee*ee,hat_diagonal_exact=hh,Cooks_distance_exact=cc).items():same(v,r[field])
    assert sum(hvals,Q(0))==2;add(case+'_hat_trace',sum(hvals,Q(0)));add(case+'_maximum_leverage',max(hvals));add(case+'_maximum_Cooks_distance',max(cvals))
    if case!='country':
        path=DATA/('actual-'+case+'-conditional-sample-means-and-OLS-values.csv');S=read(path);note(path,'empirical conditional means retain original count weights');xxs=sorted(set(x));assert len(S)==len(xxs)
        for i,(xx,r) in enumerate(zip(xxs,S)):
            ys=[b for a,b in zip(x,y) if a==xx];mu=sum(ys,Q(0))/len(ys);ff=intercept+slope*xx;same(mu,r['observed_conditional_sample_mean_exact']);same(ff,r['OLS_value_at_x_exact']);same(mu-ff,r['observed_conditional_mean_minus_OLS_exact']);same(Q(len(ys)),r['actual_records_at_x']);add(case+'_same_x_group'+str(i)+'_n',len(ys));add(case+'_same_x_group'+str(i)+'_observed_mean',mu)
path=DATA/'chosen-in-range-queries-and-classical-working-intervals.csv';S=read(path);note(path,'nine in-range working mean/new-value intervals independently checked');assert len(S)==9
for r in S:
    case=r['case'];s=summary[case];xx=Q(r['chosen_x_exact']);n=s['n'];f=s['intercept_exact']+s['slope_exact']*xx;h=Q(1,n)+(xx-s['x_mean_exact'])**2/s['Sxx_exact'];vm=s['working_residual_variance_exact']*h;vp=s['working_residual_variance_exact']*(1+h);cr=student_quantile(.975,n-2);mh=cr*math.sqrt(float(vm));ph=cr*math.sqrt(float(vp));vals=dict(chosen_x_exact=xx,fitted_OLS_y_exact=f,mean_variance_under_classical_working_model_exact=vm,new_value_variance_under_classical_working_model_exact=vp,working_mean_CI95_lower_approx=float(f)-mh,working_mean_CI95_upper_approx=float(f)+mh,working_new_value_PI95_lower_approx=float(f)-ph,working_new_value_PI95_upper_approx=float(f)+ph)
    for k,v in vals.items():near(v,r[k]);add(case+'_'+r['chosen_query']+'_'+k,v)
add('person_all_source_rows',len(people));add('person_missing_source_log_wages',len(people)-len(w));add('wine_distinct_full_numeric_rows',len(frequencies));add('wine_additional_identical_numeric_rows',sum(n-1 for n in frequencies.values()))

rpath=ROOT/'stat15-r-results.csv'
if rpath.is_file():
    R={r['metric']:float(r['value']) for r in read(rpath)};assert set(R)==set(METRICS),(set(R)-set(METRICS),set(METRICS)-set(R))
    for k,v in METRICS.items():
        near(v,R[k])
        if 0<abs(v)<1e-9:assert abs(R[k]/v-1)<=1e-8,(k,R[k],v)
    CHECKS['RmetricComparisons']=len(METRICS)
else:CHECKS['RmetricComparisons']=0
for item in AUDIT:
    path=ROOT/item['file']
    if not path.is_file():path=WORKSPACE/item['file']
    assert hashlib.sha256(path.read_bytes()).hexdigest()==item['sha256']
CHECKS['inputHashesPreserved']=len(AUDIT)
(ROOT/'stat15-results.json').write_text(json.dumps({'chapter':'STAT-15','metrics':METRICS,'exactFractions':EXACT,'numericalApproximationMetrics':APPROX,'inputAudit':AUDIT,'checks':CHECKS,'interpretation':'Actual source records are numeric inputs. Independent univariate OLS normal-equation calculations are compared with R lm. Full actual records/missingness/identical wine rows are preserved; classical/HC1 variance and mean/new-value intervals are explicit working formulas. Population conditional means, random sampling, causality and future prediction are not certified. Numeric squared loss on ordinal wine scores is a chosen model, not a verified measurement scale.'},ensure_ascii=False,indent=2,allow_nan=False)+'\n',encoding='utf-8');print('STAT-15:',len(METRICS),'independent actual-source metrics; R comparisons',CHECKS['RmetricComparisons'])
