"""STAT-21: 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/'stats21-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




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

U=read(COMMON/'churn.csv');note(COMMON/'churn.csv','actual retained3150 telecom records');archive=raw/'churn.zip'
if archive.is_file():
    note(archive,'original UCI Customer Churn.csv',True)
    with zipfile.ZipFile(archive) as z:source=list(csv.DictReader(io.StringIO(z.read('Customer Churn.csv').decode('utf-8-sig'))))
    assert len(U)==len(source)==3150
    for i,(r,o) in enumerate(zip(U,source),1):
        assert int(r['row_id'])==i
        for k,v in o.items():same(Q(v),r[k.strip().lower().replace(' ','_')])

def avg(v):return sum(v,Q(0))/len(v)
# Independent scalar normal equations and residual-weighted covariance sums.
x=[Q(o['gdp_pc'])/10000 for o in countries];y=[Q(o['life_expectancy']) for o in countries];n=len(x);sx=sum(x,Q(0));sxx=sum((v*v for v in x),Q(0));sy=sum(y,Q(0));sxy=sum((a*b for a,b in zip(x,y)),Q(0));det=n*sxx-sx*sx;P=[[sxx/det,-sx/det],[-sx/det,Q(n)/det]];beta=[P[j][0]*sy+P[j][1]*sxy for j in range(2)];e=[yy-beta[0]-beta[1]*xx for xx,yy in zip(x,y)];assert sum(e,Q(0))==sum((xx*r for xx,r in zip(x,e)),Q(0))==0;sse=sum((r*r for r in e),Q(0));A=[[Q(1),sx/n],[sx/n,sxx/n]];Ai=[[v*n for v in row] for row in P];B=[[sum((r*r*(1 if j==0 else xx)*(1 if k==0 else xx) for xx,r in zip(x,e)),Q(0))/n for k in range(2)] for j in range(2)];HC0=[[sum(((P[j][0]+P[j][1]*xx)*(P[k][0]+P[k][1]*xx)*r*r for xx,r in zip(x,e)),Q(0)) for k in range(2)] for j in range(2)];HC1=[[v*n/(n-2) for v in row] for row in HC0];classical=[[v*sse/(n-2) for v in row] for row in P]
path=DATA/'actual16-country-design-residuals-scores-and-distinct-influences.csv';S=read(path);note(path,'actual two indicators, exact OLS scores and two different sensitivity definitions');assert len(S)==n
for i,(o,r) in enumerate(zip(countries,S)):
 assert o['country']==r['country'];same(Q(o['gdp_pc']),r['actual2024_GDPpc']);same(Q(o['life_expectancy']),r['actual2024_period_life_expectancy']);vals=dict(chosen_x_GDPpc_divide10000_exact=x[i],observed_OLS_fit_exact=y[i]-e[i],observed_OLS_residual_exact=e[i],estimating_score_intercept_exact=e[i],estimating_score_slope_exact=x[i]*e[i],empirical_reference_IF_intercept_exact=n*(P[0][0]+P[0][1]*x[i])*e[i],empirical_reference_IF_slope_exact=n*(P[1][0]+P[1][1]*x[i])*e[i],fixed_design_y_perturbation_derivative_intercept_exact=P[0][0]+P[0][1]*x[i],fixed_design_y_perturbation_derivative_slope_exact=P[1][0]+P[1][1]*x[i])
 for key,v in vals.items():same(v,r[key]);add('country_'+o['country']+'_'+key,v)
path=DATA/'exact-OLS-mean-score-and-sandwich-matrices.csv';S=read(path);note(path,'all six normalized-score/covariance matrices independently reconstructed');matrices=dict(A_mean_design_outer=A,B_mean_score_outer=B,inverse_A=Ai,HC0_covariance=HC0,HC1_covariance=HC1,classical_homoskedastic_covariance=classical);coords=['intercept','GDP_10000USD_slope']
for name,M in matrices.items():
 for j,k in itertools.product(range(2),repeat=2):
  r=next(r for r in S if r['matrix']==name and r['row_coordinate']==coords[j] and r['column_coordinate']==coords[k]);same(M[j][k],r['value_exact']);add('country_'+name+'_'+str(j)+str(k),M[j][k])
path=DATA/'actual-country-linear-projection-and-variance-rules.csv';S=read(path);note(path,'same coefficients and explicit distinct variance rules');vals=dict(actual_selected_countries=n,OLS_intercept_exact=beta[0],OLS_slope_per10000USD_exact=beta[1],SSE_exact=sse,HC0_slope_variance_exact=HC0[1][1],HC1_slope_variance_exact=HC1[1][1],classical_slope_variance_exact=classical[1][1],HC1_over_HC0_variance_exact=Q(n,n-2))
for key,v in vals.items():same(Q(v),S[0][key]);add('country_'+key,v)
path=DATA/'actual3613-person-source-logs-with-missingness.csv';S=read(path);note(path,'original person rows,1976 source logs and603 unavailable values retained')
for i,(o,r) in enumerate(zip(people,S),1):
 same(Q(i),r['sourceRow']);same(o['person'],r['person_code'])
 if o['log_wage'] is None:assert r['source_trimmed1976_log_hourly_wage_cents']==''
 else:same(o['log_wage'],r['source_trimmed1976_log_hourly_wage_cents'])
X=[o['log_wage'] for o in people if o['log_wage'] is not None];N=len(X);cutoff=Q(1,2);mu=avg(X)
def clipped(v,c):return min(c,max(-c,v))
def independent_root(values,weights,c):
 # Locate the interval numerically, then solve and certify the score exactly.
 # This differs from the case author's exact breakpoint-sweep algorithm.
 lo=float(min(values)-c);hi=float(max(values)+c);xx=list(map(float,values));ww=list(map(float,weights));cc=float(c)
 for iteration in range(100):
  m=(lo+hi)/2;f=sum(w*max(-cc,min(cc,x-m)) for x,w in zip(xx,ww))
  if f>0:lo=m
  else:hi=m
 query=Q(str((lo+hi)/2));inside=[i for i,x in enumerate(values) if abs(x-query)<c];A=sum((weights[i] for i in inside),Q(0));assert A>0;C=sum((weights[i]*values[i] for i in inside),Q(0))+c*(sum((w for x,w in zip(values,weights) if x-query>=c),Q(0))-sum((w for x,w in zip(values,weights) if x-query<=-c),Q(0)));root=C/A;assert sum((w*clipped(x-root,c) for x,w in zip(values,weights)),Q(0))==0
 return root
theta=independent_root(X,[Q(1,N)]*N,cutoff);scores=[clipped(x-theta,cutoff) for x in X];inside=sum(abs(x-theta)<cutoff for x in X);boundary=sum(abs(x-theta)==cutoff for x in X);AH=Q(inside,N);BH=sum((v*v for v in scores),Q(0))/N;VH=BH/(N*AH*AH);VM=sum(((x-mu)**2 for x in X),Q(0))/(N*N);assert sum(scores,Q(0))==0 and boundary==0
path=DATA/'actual-log-mean-fixed-cutoff-Huber-and-empirical-sandwich.csv';S=read(path);note(path,'independent certified active-set Huber root, empirical A/B and fixed-c influence');vals=dict(all_original_people=len(people),available_source_logs=N,unavailable_source_logs=len(people)-N,chosen_fixed_cutoff_log_units_exact=cutoff,observed_arithmetic_log_mean_exact=mu,observed_fixed_cutoff_Huber_location_exact=theta,observations_strictly_inside_cutoff=inside,observations_at_nondifferentiable_score_knots=boundary,empirical_A_mean_psi_derivative_exact=AH,empirical_B_mean_psi_squared_exact=BH,working_HC0_Huber_location_variance_exact=VH,working_HC0_log_mean_variance_exact=VM,Huber_reference_IF_absolute_bound_exact=cutoff/AH)
for key,v in vals.items():same(Q(v),S[0][key]);add('person_'+key,v)
path=DATA/'chosen-contamination-query-influence-curves.csv';S=read(path);note(path,'explicit hypothetical points and different target influence curves')
for i,z in enumerate([Q(j,2) for j in range(6,21)]):
 mif=z-mu;hif=clipped(z-theta,cutoff)/AH;same(z,S[i]['queried_contamination_log_value_exact']);same(mif,S[i]['reference_mean_IF_exact']);same(hif,S[i]['reference_Huber_IF_exact']);add('person_IFquery'+str(i)+'_mean',mif);add('person_IFquery'+str(i)+'_Huber',hif)
path=DATA/'explicit-assumed-contamination-recomputed-and-first-order-location.csv';S=read(path);note(path,'twelve assumed mixtures independently solved without changing actual values')
for i,(eps,z) in enumerate(itertools.product([Q(1,1000),Q(1,100)],[Q(4),Q(5),Q(6),Q(8),Q(10),Q(100)])):
 new=independent_root(X+[z],[Q(1,N)*(1-eps)]*N+[eps],cutoff);first=theta+eps*clipped(z-theta,cutoff)/AH;newmean=mu+eps*(z-mu);vals=dict(assumed_contamination_mass_exact=eps,assumed_point_log_value_exact=z,recomputed_Huber_location_under_assumed_mixture_exact=new,first_order_IF_Huber_location_approximation_exact=first,actual_minus_first_order_remainder_exact=new-first,mean_under_same_assumed_mixture_exact=newmean)
 for key,v in vals.items():same(v,S[i][key]);add('person_contamination'+str(i)+'_'+key,v)
path=DATA/'actual3150-customer-records-all-source-fields.csv';S=read(path);note(path,'all3150 actual source records and14 fields preserved')
for o,r in zip(U,S):
 for key,v in o.items():same(Q(v),r[key])
NC=len(U);events=sum(int(Q(o['churn'])) for o in U);p=Q(events,NC);AC=p*(1-p);BC=sum(((Q(o['churn'])-p)**2 for o in U),Q(0))/NC;assert AC==BC;eta=(D(p.numerator)/D(p.denominator)/(1-D(p.numerator)/D(p.denominator))).ln();path=DATA/'actual-pooled-binary-score-logit-and-sandwich.csv';S=read(path);note(path,'binary-score empirical identity, not a test of actual iid or equal risks');vals=dict(actual_customers=NC,actual_churn=events,observed_p_exact=p,intercept_logit_MLE_decimal_approx=eta,empirical_A_negative_mean_score_derivative_exact=AC,empirical_B_mean_score_squared_exact=BC,working_HC0_logit_sandwich_variance_exact=BC/(NC*AC*AC),working_model_based_logit_variance_exact=1/(NC*AC))
for key,v in vals.items():near(v,S[0][key]);add('company_'+key,v if isinstance(v,(int,Q)) else float(v))
path=DATA/'two-actual-outcomes-score-and-reference-influence.csv';S=read(path);note(path,'score and influence depend on parameterization')
for label,r in zip([0,1],S):
 count=events if label else NC-events;score=Q(label)-p;vals=dict(actual_binary_outcome=label,actual_frequency=count,observed_empirical_mass_exact=Q(count,NC),logit_estimating_score_exact=score,reference_logit_influence_exact=score/AC,reference_probability_influence_exact=score)
 for key,v in vals.items():same(Q(v),r[key]);add('company_label'+str(label)+'_'+key,v)

rpath=ROOT/'stat21-r-results.csv'
if rpath.is_file():
 R={r['metric']:float(r['value']) for r in read(rpath)};assert set(R)==set(METRICS)
 for key,value in METRICS.items():
  near(value,R[key])
  if 0<abs(value)<1e-9:assert abs(R[key]/value-1)<=1e-8,(key,R[key],value)
 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)
CHECKS['caseJSONOrPreviousMetricsUsedAsNumericInputs']=False
(ROOT/'stat21-results.json').write_text(json.dumps(dict(chapter='STAT-21',metrics=METRICS,exactFractions=EXACT,numericalApproximationMetrics=APPROX,inputAudit=AUDIT,checks=CHECKS,interpretation='Original public observations are numeric inputs. M-estimation targets, score conventions, mean normalization and estimator covariance scaling are explicit. Fixed-c Huber is a different functional from arithmetic mean and is not jointly scaled. Hypothetical contamination never edits actual data. Binary empirical A=B is an algebraic identity, not an independence/homogeneity diagnostic. No actual iid, representativeness or causal guarantee is certified. Python active-set root certification differs from author knot sweep; R uses uniroot and lm/matrix algebra independently.'),ensure_ascii=False,indent=2,allow_nan=False)+'\n',encoding='utf-8')
print('STAT-21:',len(METRICS),'actual-source metrics; R comparisons',CHECKS['RmetricComparisons'])
