"""DATA-09: 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/'data09-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'
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

def avg(v):return sum(v,Q(0))/len(v)
def verify(name,expected):
 path=DATA/name;S=read(path);note(path,'actual source values and explicit mathematical summaries independently reconstructed');assert len(S)==len(expected),(name,len(S),len(expected))
 for row,o in zip(S,expected):
  assert set(row)==set(o),(name,set(row),set(o))
  for k,v in o.items():
   if isinstance(v,bool):assert row[k]==str(v)
   elif isinstance(v,(Q,int)):same(Q(v),row[k])
   elif isinstance(v,float):near(v,row[k])
   else:assert row[k]==str(v),(name,k,row[k],v)
 return S
H=read(COMMON/'korea-housing.csv');note(COMMON/'korea-housing.csv','actual retained real-price index');archive=raw/'korea-housing-real.csv'
if archive.is_file():
 note(archive,'original BIS180-period SDMX XML despite csv extension',True);tree=ET.fromstring(archive.read_text(encoding='utf-8'));original={e.attrib['TIME_PERIOD']:Q(e.attrib['OBS_VALUE']) for e in tree.iter() if e.tag.endswith('Obs')};assert len(original)==len(H)==180
 for r in H:same(original[r['quarter']],r['real'])
quarters=[dict(quarter=r['quarter'],actual_real_index_source_decimal=r['real'],reference='2010_average_eq100',quarter_is_one_of_all_four2024_periods=True) for r in H if r['year']=='2024'];verify('actual-four2024-Korea-real-housing-index-periods.csv',quarters);hv=[Q(r['actual_real_index_source_decimal']) for r in quarters];hs=dict(target='fixed_four2024_quarter_arithmetic_mean',all_quarters=4,available_quarters=4,unavailable_quarters=0,mean_index_exact=avg(hv),minimum_index_exact=min(hv),maximum_index_exact=max(hv),range_index_points_exact=max(hv)-min(hv),sampling_interval_applicable_to_this_fixed_record_target=False);verify('fixed-four-quarter-report-target-no-invented-sampling-CI.csv',[hs])
for i,x in enumerate(hv):add('country_actual_Q'+str(i+1),x)
for k,v in hs.items():
 if isinstance(v,(Q,int)) and not isinstance(v,bool):add('country_'+k,v)
persons=[dict(source_row_id=i,source_person_code=str(int(o['person'])),source_trimmed_log1976_hourly_cents_source_decimal=C[i-1]['log_wage']) for i,o in enumerate(people,1)];verify('actual3613-source-log-wages-and-original-unavailable-records.csv',persons);n=len(w);mu=avg(w);s2=sum(((x-mu)**2 for x in w),Q(0))/(n-1);sd=math.sqrt(float(s2));se=sd/math.sqrt(n);critical=student_quantile(.975,n-1);lo=float(mu)-critical*se;hi=float(mu)+critical*se
ps=dict(all_source_records=len(people),available_logs=n,unavailable_logs=len(people)-n,finite_available_log_mean_exact=mu,sample_log_variance_n_minus1_exact=s2,sample_log_SD_binary64_approx=sd,working_iid_mean_SE_binary64_approx=se,working_normal_t_df=n-1,t975_binary64_approx=critical,working_normal_CI95_log_mean_lower_binary64_approx=lo,working_normal_CI95_log_mean_upper_binary64_approx=hi,geometric_center1976USD_per_hour_binary64_approx=math.exp(float(mu))/100,working_normal_CI95_geometric_center1976USD_lower_binary64_approx=math.exp(lo)/100,working_normal_CI95_geometric_center1976USD_upper_binary64_approx=math.exp(hi)/100,source_design_establishes_iid_normal_population_sampling=False,interval_is_prediction_interval=False,transformed_center_is_arithmetic_level_mean=False);verify('actual-log-summary-and-explicit-working-model-intervals.csv',[ps])
for k,v in ps.items():
 if not isinstance(v,bool):add('person_'+k,v)
CH=read(COMMON/'churn.csv');note(COMMON/'churn.csv','actual retained3150 customer records');archive=raw/'churn.zip'
if archive.is_file():
 note(archive,'original UCI3150x14 customer observations',True)
 with zipfile.ZipFile(archive) as z:original=list(csv.DictReader(io.StringIO(z.read('Customer Churn.csv').decode('utf-8-sig'))))
 assert len(original)==len(CH)==3150
 for i,(r,o) in enumerate(zip(CH,original),1):
  same(Q(i),r['row_id'])
  for k,v in o.items():same(Q(v),r[k.strip().lower().replace(' ','_')])
customers=[dict(source_row_id=i,complaint_code_source_decimal=r['complains'],churn_code_source_decimal=r['churn']) for i,r in enumerate(CH,1)];verify('actual3150-customer-complaint-and-churn-records.csv',customers);z=normal_quantile(.975);cs=[]
for label,group in [('ALL',customers),('complaint0',[r for r in customers if Q(r['complaint_code_source_decimal'])==0]),('complaint1',[r for r in customers if Q(r['complaint_code_source_decimal'])==1])]:
 nn=len(group);s=sum(Q(r['churn_code_source_decimal'])==1 for r in group);phat=Q(s,nn);den=1+z*z/nn;center=(float(phat)+z*z/(2*nn))/den;half=z*math.sqrt(float(phat*(1-phat))/nn+z*z/(4*nn*nn))/den;row=dict(group=label,source_records=nn,available_churn_values=nn,churn_count=s,finite_observed_churn_fraction_exact=phat,normal975_binary64_approx=z,working_iid_Bernoulli_Wilson95_lower_binary64_approx=center-half,working_iid_Bernoulli_Wilson95_upper_binary64_approx=center+half,source_design_establishes_iid_target_sampling=False,interval_is_causal_effect_or_individual_prediction=False);cs.append(row)
 for k,v in row.items():
  if k!='group' and not isinstance(v,bool):add('company_'+label+'_'+k,v)
verify('actual-customer-rates-and-explicit-working-Bernoulli-Wilson-intervals.csv',cs)
CHECKS.update(caseJSONNumericInput=False,fixedFourQuarterTargetNotAssignedSamplingCI=True,SDNotSE=True,geometricCenterNotArithmeticWageMean=True,intervalsRequireUnestablishedWorkingModels=True,missingLogsPreserved=True,WilsonNominalCoverageNotUniversalExact=True,CIIsNotIndividualPredictionOrCausalEffect=True)

rpath=ROOT/'data09-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/'data09-results.json').write_text(json.dumps(dict(chapter='DATA-09',metrics=METRICS,exactFractions=EXACT,numericalApproximationMetrics=APPROX,inputAudit=AUDIT,checks=CHECKS,interpretation='Original observations are numeric inputs, never case JSON. Fixed four-quarter mean is known from all four retained reports and is not assigned invented sampling uncertainty. Separate source/measurement/revision limits remain. Exact available log moments support an explicitly additional iid-normal t working model, not source design certification; exp/100 gives a geometric center, not arithmetic wage mean. Customer finite proportions are known, and separate Wilson intervals require additional Bernoulli sampling assumptions with nominal rather than universal exact coverage. No personalized prediction or causal effect is inferred.'),ensure_ascii=False,indent=2,allow_nan=False)+'\n',encoding='utf-8')
print('DATA-09:',len(METRICS),'actual-source metrics; R comparisons',CHECKS['RmetricComparisons'])
