"""STAT-13: 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/'stats13-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 avg(v):return sum(v,Q(0))/len(v)
def sv(v):
    m=avg(v);return sum(((x-m)**2 for x in v),Q(0))/(len(v)-1)
def field(line,a,b):
    s=line[a-1:b].strip();return None if s in ['','.'] else Q(s)
def test(v,ref):
    n=len(v);mu=avg(v);s2=sv(v);sd=math.sqrt(float(s2));se=sd/math.sqrt(n);diff=mu-ref;t=float(diff)/se;p=2*student_sf(abs(t),n-1);crit=student_quantile(.975,n-1)
    return dict(n=n,df=n-1,mean_exact=mu,reference_exact=ref,difference_exact=diff,sample_variance_exact=s2,SD_approx=sd,SE_approx=se,t_approx=t,two_sided_p_approx=p,standardized_mean_difference_approx=float(diff)/sd,CI95_difference_lower_approx=float(diff)-crit*se,CI95_difference_upper_approx=float(diff)+crit*se)
raw=WORKSPACE/'work/textbooks-2026/raw';H=read(COMMON/'korea-housing.csv');note(COMMON/'korea-housing.csv','retained actual BIS observations');hp=raw/'korea-housing-real.csv'
if hp.is_file():
    note(hp,'original SDMX XML',True);tree=ET.fromstring(hp.read_text(encoding='utf-8'));o={e.attrib['TIME_PERIOD']:Q(e.attrib['OBS_VALUE']) for e in tree.iter() if e.tag.endswith('Obs')};assert len(o)==len(H)==180
    for r in H:same(o[r['quarter']],r['real'])
else:o={r['quarter']:Q(r['real']) for r in H}
h=[o['2024-Q'+str(i)] for i in range(1,5)];hm=avg(h);hv=sum(((x-hm)**2 for x in h),Q(0))/4
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(' ','_')])

aa=[Q(r['real']) for r in H if r['year']=='2023'];bb=[Q(r['real']) for r in H if r['year']=='2024'];dd=[y-x for x,y in zip(aa,bb)];cv=sum(((x-avg(aa))*(y-avg(bb)) for x,y in zip(aa,bb)),Q(0))/3;assert sv(dd)==sv(aa)+sv(bb)-2*cv
S=read(DATA/'actual2023-2024-real-housing-quarter-values.csv');note(DATA/'actual2023-2024-real-housing-quarter-values.csv','eight actual quarter observations');assert len(S)==8
for r,x in zip(S,aa+bb):same(x,r['reported_real_index_2010average100'])
S=read(DATA/'actual-four-matched-quarter-changes.csv');note(DATA/'actual-four-matched-quarter-changes.csv','four observed calendar-quarter pairs');assert len(S)==4
for r,x,y in zip(S,aa,bb):same(x,r['actual2023_real_index']);same(y,r['actual2024_real_index']);same(y-x,r['actual_same_quarter_year_over_year_index_point_change_exact']);same((y/x-1)*100,r['actual_percent_year_over_year_change_exact'])
country=dict(actual_pairs=4,known2023_mean_exact=avg(aa),known2024_mean_exact=avg(bb),known_mean_index_point_change_exact=avg(dd),change_sample_variance_exact=sv(dd),before_sample_variance_exact=sv(aa),after_sample_variance_exact=sv(bb),paired_sample_covariance_exact=cv,working_iid_pair_mean_SE_approx=math.sqrt(float(sv(dd)/4)),incorrect_independent_pair_SE_reference_approx=math.sqrt(float((sv(aa)+sv(bb))/4)))
S=read(DATA/'actual-paired-quarter-moments-and-SE-formula-comparison.csv');note(DATA/'actual-paired-quarter-moments-and-SE-formula-comparison.csv','paired moment/SE formula comparison')
for k,v in country.items():near(v,S[0][k]);add('housing_'+k,v)
S=read(DATA/'actual-people-SMSA-groups-and-missing-log-wages.csv');note(DATA/'actual-people-SMSA-groups-and-missing-log-wages.csv','all3613 SMSA person records preserved');assert len(S)==3613
for o,r in zip(people,S):
    same(o['person'],r['source_person_ID']);same(o['metro'],r['actual1976_SMSA_indicator'])
    if o['log_wage'] is None:assert r['source_trimmed_log_wage']==''
    else:same(o['log_wage'],r['source_trimmed_log_wage'])
WG=[];S=read(DATA/'actual-log-wage-two-group-moments.csv');note(DATA/'actual-log-wage-two-group-moments.csv','both actual SMSA-group sample moments')
for g,r in zip([1,0],S):
    allrows=[o for o in people if o['metro']==g];v=[o['log_wage'] for o in allrows if o['log_wage'] is not None];WG.append(v);vals=dict(all_actual_person_records=len(allrows),available_source_trimmed_log_wages=len(v),missing_source_log_wages=len(allrows)-len(v),mean_log_wage_exact=avg(v),sample_variance_log_wage_exact=sv(v))
    for k,x in vals.items():near(x,r[k]);add('people_group'+str(g)+'_'+k,x)
x,y=WG;n1,n0=len(x),len(y);v1,v0=sv(x),sv(y);delta=avg(x)-avg(y);se2=v1/n1+v0/n0;df=se2**2/((v1/n1)**2/(n1-1)+(v0/n0)**2/(n0-1));se=math.sqrt(float(se2));t=float(delta)/se;crit=student_quantile(.975,float(df));pv=2*student_sf(abs(t),float(df));sp=((n1-1)*v1+(n0-1)*v0)/(n1+n0-2)
vals=dict(n1=n1,n0=n0,observed_mean_log_difference_exact=delta,Welch_SE_squared_exact=se2,Welch_SE_approx=se,Welch_Satterthwaite_df_exact_from_sample_moments=df,Welch_df_approx=float(df),Welch_t_approx=t,Welch_two_sided_p_approx=pv,Welch_t975_critical_approx=crit,Welch_CI95_difference_lower_approx=float(delta)-crit*se,Welch_CI95_difference_upper_approx=float(delta)+crit*se,equal_variance_pooled_SE_reference_approx=math.sqrt(float(sp*(Q(1,n1)+Q(1,n0)))),equal_variance_pooled_df=n1+n0-2,geometric_center_ratio_approx=math.exp(float(delta)))
S=read(DATA/'actual-log-wage-Welch-comparison.csv');note(DATA/'actual-log-wage-Welch-comparison.csv','Welch approximate df and distribution independently recalculated')
for k,v in vals.items():near(v,S[0][k]);add('people_'+k,v)
S=read(DATA/'actual-customers-complaints-and-month12-churn.csv');note(DATA/'actual-customers-complaints-and-month12-churn.csv','all3150 actual complaint/churn pairs');assert len(S)==3150
for o,r in zip(U,S):same(Q(o['row_id']),r['source_row_id']);same(Q(o['complains']),r['actual_first9months_complaint_indicator']);same(Q(o['churn']),r['actual_month12_churn_indicator'])
S=read(DATA/'actual-complaint-by-churn-two-group-counts.csv');note(DATA/'actual-complaint-by-churn-two-group-counts.csv','four actual contingency cells with group denominators');G=[]
for g,r in zip([1,0],S):
    rows=[o for o in U if Q(o['complains'])==g];n=len(rows);events=sum((Q(o['churn']) for o in rows),Q(0));pp=events/n;G.append((n,events,pp));vals=dict(actual_records=n,actual_month12_churn_count=events,actual_month12_nonchurn_count=n-events,observed_churn_fraction_exact=pp)
    for k,v in vals.items():near(v,r[k]);add('customers_group'+str(g)+'_'+k,v)
(n1,e1,p1),(n0,e0,p0)=G;delta=p1-p0;pooled=(e1+e0)/(n1+n0);s02=pooled*(1-pooled)*(Q(1,n1)+Q(1,n0));su2=p1*(1-p1)/n1+p0*(1-p0)/n0;s0=math.sqrt(float(s02));su=math.sqrt(float(su2));z=float(delta)/s0;crit=normal_quantile(.975)
vals=dict(n_complaint=n1,n_no_complaint=n0,churn_complaint=e1,churn_no_complaint=e0,p_complaint_exact=p1,p_no_complaint_exact=p0,observed_proportion_difference_exact=delta,pooled_null_proportion_exact=pooled,pooled_null_SE_squared_exact=s02,unpooled_estimation_SE_squared_exact=su2,pooled_null_SE_approx=s0,unpooled_estimation_SE_approx=su,normal_reference_z_approx=z,normal_reference_two_sided_p_approx=math.erfc(abs(z)/math.sqrt(2)),unpooled_Wald95_lower_approx=float(delta)-crit*su,unpooled_Wald95_upper_approx=float(delta)+crit*su)
S=read(DATA/'actual-customer-two-proportion-comparison.csv');note(DATA/'actual-customer-two-proportion-comparison.csv','separate estimation and pooled null quantities independently recalculated')
for k,v in vals.items():near(v,S[0][k]);add('customers_'+k,v)

rpath=ROOT/'stat13-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 'p_approx' in k and v>0:assert abs(R[k]/v-1)<1e-10,(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/'stat13-results.json').write_text(json.dumps({'chapter':'STAT-13','metrics':METRICS,'exactFractions':EXACT,'numericalApproximationMetrics':APPROX,'inputAudit':AUDIT,'checks':CHECKS,'interpretation':'Actual source records are numeric inputs. Known annual quarter differences are descriptive, not validated iid temporal inference. Person Welch and customer pooled-null/Wald computations require working assumptions; causal migration/complaint intervention and representative iid sampling are not certified. Tiny p-values are cross-checked by relative error against base R.'},ensure_ascii=False,indent=2,allow_nan=False)+'\n',encoding='utf-8');print('STAT-13:',len(METRICS),'independent actual-source metrics; R comparisons',CHECKS['RmetricComparisons'])
