"""STAT-24: 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/'stats24-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(' ','_')])

from statistics import NormalDist
from functools import lru_cache
def avg(v):return sum(v,Q(0))/len(v)
def variance(v):u=avg(v);return sum(((x-u)**2 for x in v),Q(0))/(len(v)-1)
def ceiling(q):return (q.numerator+q.denominator-1)//q.denominator
Y=[Q(o['gdp_pc']) for o in countries];NF=len(Y);mu=avg(Y);S2=variance(Y);z=Q(49,25)
path=DATA/'actual16-country-2024-GDP-finite-frame.csv';S=read(path);note(path,'complete actual finite-frame GDP values')
for o,r in zip(countries,S):assert o['country']==r['country'];same(Q(o['gdp_pc']),r['actual2024_GDPpc_constant2015USD_person'])
path=DATA/'chosen-SRS-known-frame-precision-all16-sample-sizes.csv';S=read(path);note(path,'exact SRS design variance and nominal normal halfwidth, not exact coverage')
for n,r in enumerate(S,1):
 v=(1-Q(n,NF))*S2/n;vals=dict(chosen_SRS_without_replacement_n=Q(n),actual_finite_frame_N=Q(NF),known_frame_mean_exact=mu,known_frame_variance_divide_Nminus1_exact=S2,exact_design_variance_of_sample_mean_exact=v,chosen_normal_multiplier_exact=z)
 for key,value in vals.items():same(value,r[key]);add('country_n'+str(n)+'_'+key,value)
 hw=float(z)*math.sqrt(float(v));near(hw,r['planning_halfwidth_numeric_approx']);add('country_n'+str(n)+'_halfwidth',hw)
path=DATA/'exhaustive-SRS-design-coverage-and-moment-checks.csv';S=read(path);note(path,'independent integer-scaled enumeration of all14690 subsets')
path=DATA/'lexicographic-subset-illustrations-not-random-samples.csv';EX=read(path);note(path,'only first16 lexicographic illustrations per n; not a random sample')
# Use an integer lattice for the independent enumeration rather than summing Fractions per subset.
den=math.lcm(*(v.denominator for v in Y));ints=[v.numerator*(den//v.denominator) for v in Y];total=sum(ints)
for n,r in zip([4,8],S):
 count=0;cover=0;sumraw=0;sumsq_error_scaled=0;threshold=z*z*(1-Q(n,NF))*S2/n
 for indices in itertools.combinations(range(NF),n):
  rawsum=sum(ints[i] for i in indices);errornum=NF*rawsum-n*total;count+=1;sumraw+=rawsum;sumsq_error_scaled+=errornum*errornum;error=Q(errornum,NF*n*den);cover+=error*error<=threshold
  if count<=16:
   e=next(o for o in EX if int(o['SRS_n'])==n and int(o['lexicographic_example_number_not_random_draw'])==count);same(Q(rawsum,n*den),e['actual_subset_mean_exact']);same(error,e['actual_subset_error_against_known_frame_mean_exact']);assert e['source_country_codes_in_subset']=='|'.join(countries[i]['country'] for i in indices) and (e['inside_chosen_known_S2_normal_interval']=='True')==(error*error<=threshold);same(Q(1,math.comb(NF,n)),e['example_subset_probability_under_SRS_exact'])
 emean=Q(sumraw,count*n*den);evar=Q(sumsq_error_scaled,count*(NF*n*den)**2);assert emean==mu and evar==(1-Q(n,NF))*S2/n;vals=dict(SRS_n=Q(n),all_possible_subsets=Q(count),subsets_covered_by_chosen_knownS2_196_interval=Q(cover),exact_finite_design_coverage_exact=Q(cover,count),exact_mean_over_all_subset_means_exact=emean,exact_variance_over_all_subset_means_exact=evar)
 for key,value in vals.items():same(value,r[key]);add('country_exhaustive_n'+str(n)+'_'+key,value)
path=DATA/'actual3613-person-source-logs-missing-preserved.csv';S=read(path);note(path,'all actual person rows, source1976 logs and unavailable603 retained')
for i,(o,r) in enumerate(zip(people,S),1):
 same(Q(i),r['sourceRow']);same(o['person'],r['source_person_code'])
 if o['log_wage'] is None:assert r['actual_source_trimmed1976_log_hourly_wage_cents']==''
 else:same(o['log_wage'],r['actual_source_trimmed1976_log_hourly_wage_cents'])
pilotvar=variance(w)
@lru_cache(None)
def binomial_at_least(B,n,a,b):
 # Independent exact PMF recurrence from k=0, then positive tail accumulation.
 p=Q(a,b);mass=(1-p)**B;tail=Q(0)
 for k in range(B+1):
  if k>=n:tail+=mass
  if k<B:mass*=Q(B-k,k+1)*p/(1-p)
 return tail
path=DATA/'hypothetical-precision-response-and-assurance-designs.csv';S=read(path);note(path,'exact ceiling/response-tail recurrence; no future sampling guarantee')
for i,((h,deff,response),r) in enumerate(zip(itertools.product([Q(1,20),Q(1,10)],[Q(1),Q(2)],[Q(3,5),Q(4,5)]),S)):
 need=ceiling(z*z*pilotvar*deff/(h*h));expinv=ceiling(Q(need)/response);a,b=response.numerator,response.denominator;inv=expinv
 # Linear search from expected-count benchmark differs from author bisection.
 while binomial_at_least(inv,need,a,b)<Q(9,10):inv+=1
 at=binomial_at_least(inv,need,a,b);before=binomial_at_least(inv-1,need,a,b);assert before<Q(9,10)<=at;vals=dict(chosen_halfwidth_log_units_exact=h,chosen_design_effect_exact=deff,chosen_independent_response_probability_exact=response,actual1976_available_log_sample_variance_exact=pilotvar,normal_planning_required_responses=Q(need),invites_for_expected_responses_at_least_required=Q(expinv),chosen_response_count_assurance_exact=Q(9,10),minimum_invites_for90percent_response_count_assurance=Q(inv))
 for key,value in vals.items():same(value,r[key]);add('person_plan'+str(i)+'_'+key,value)
 for key,value in [('probability_reaching_required_at_expected_invites_decimal_approx',binomial_at_least(expinv,need,a,b)),('assurance_probability_at_minimum_decimal_approx',at),('assurance_probability_one_fewer_decimal_approx',before)]:near(value,r[key]);assert abs(float(value)/float(Q(r[key]))-1)<1e-12;add('person_plan'+str(i)+'_'+key,value)
path=DATA/'actual3150-customer-records-all-source-fields.csv';S=read(path);note(path,'actual UCI cells, no treatment assignment exists')
for o,r in zip(U,S):
 for key,value in o.items():same(Q(value),r[key])
NU=len(U);events=sum(int(Q(o['churn'])) for o in U);p0=Q(events,NU);v0=p0*(1-p0);normal=NormalDist();za=normal.inv_cdf(.975)
def working_power(n,d):
 a=float(d)*math.sqrt(n/(2*float(v0)))
 return .5*math.erfc((za-a)/math.sqrt(2))+.5*math.erfc((za+a)/math.sqrt(2))
path=DATA/'hypothetical-two-arm-common-variance-normal-power-plans.csv';S=read(path);note(path,'known-reference Gaussian planning approximation, not exact binary power')
for i,((delta,wanted),r) in enumerate(zip(itertools.product([Q(3,100),Q(1,20),Q(2,25)],[Q(4,5),Q(9,10)]),S)):
 zb=normal.inv_cdf(float(wanted));continuous=2*float(v0)*(za+zb)**2/float(delta*delta);n=math.ceil(continuous);exact=dict(actual_reference_customers=Q(NU),actual_reference_events=Q(events),observed_pooled_reference_p_exact=p0,chosen_common_reference_Bernoulli_variance_exact=v0,hypothetical_absolute_churn_reduction_exact=delta,hypothetical_new_treatment_probability_exact=p0-delta,chosen_power_target_exact=wanted,chosen_two_sided_alpha_exact=Q(1,20),rounded_planned_per_arm_n=Q(n),rounded_total_n=Q(2*n));approx=dict(standard_normal_alpha_multiplier_numeric_approx=za,standard_normal_power_multiplier_numeric_approx=zb,normal_common_variance_continuous_per_arm_n_approx=continuous,power_under_chosen_common_variance_Gaussian_model_approx=working_power(n,delta))
 for key,value in exact.items():same(value,r[key]);add('company_plan'+str(i)+'_'+key,value)
 for key,value in approx.items():near(value,r[key]);add('company_plan'+str(i)+'_'+key,value)
path=DATA/'hypothetical-common-variance-normal-power-profile.csv';S=read(path);note(path,'93 normal-model powers for explicitly unobserved future effects')
for i,((n,delta),r) in enumerate(zip(itertools.product(range(100,3101,100),[Q(3,100),Q(1,20),Q(2,25)]),S)):
 same(Q(n),r['chosen_per_arm_n']);same(delta,r['hypothetical_absolute_reduction_exact']);value=working_power(n,delta);near(value,r['common_variance_normal_power_numeric_approx']);add('company_powerprofile'+str(i),value)
path=DATA/'explicit-independent-null-test-multiplicity-illustration.csv';S=read(path);note(path,'independent-null family illustration, not cumulative peeking probability')
for k,r in zip([1,2,5,10],S):same(Q(k),r['explicit_independent_null_tests']);same(1-Q(19,20)**k,r['exact_probability_at_least1_false_rejection_exact']);add('independentNullTests'+str(k)+'_falseRejectionProbability',1-Q(19,20)**k)
planpath=DATA/'teaching-analysis-plan-draft-not-preregistered.json';note(planpath,'after-observation local teaching plan, not registered study');plan=json.loads(planpath.read_text(encoding='utf-8'));assert plan['externalRegistrySubmissionMade'] is False
CHECKS['exhaustiveSRSSubsetsEnumerated']=14690;CHECKS['exactResponseAssuranceMinimalIntegersChecked']=8;CHECKS['noActualFutureTrialOrPreregistrationClaim']=True

rpath=ROOT/'stat24-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/'stat24-results.json').write_text(json.dumps(dict(chapter='STAT-24',metrics=METRICS,exactFractions=EXACT,numericalApproximationMetrics=APPROX,inputAudit=AUDIT,checks=CHECKS,interpretation='Known complete finite-frame sampling experiments and observed pilot summaries are distinct from assumed future variance, response, effects and trial design. Exact SRS moments do not guarantee nominal normal coverage. Exact Binomial response-count assurance differs from interval coverage. Common-variance Gaussian power is not exact binary power. The local plan follows observed data and is not a preregistration or independent empirical replication. Python independently uses integer-lattice subset enumeration and positive-tail PMF recurrence; base R uses combn, pbinom and pnorm.'),ensure_ascii=False,indent=2,allow_nan=False)+'\n',encoding='utf-8')
print('STAT-24:',len(METRICS),'actual-source metrics; R comparisons',CHECKS['RmetricComparisons'])
