"""ML18 factual sparse-regression studies, exact Fraction reference.
Run: python reproduce-sparse-selection.py [input-directory] [new-output-directory]
Reads four factual CSV files only. Does not read engine,model JSON or computed results.
Copied pure routines are this author's separate Fraction reference,not independent peer code.
Original observations are retained. Prefix experiments are explicitly labeled.
"""
from pathlib import Path
from fractions import Fraction as Q
from itertools import combinations
from collections import Counter
import csv,json,hashlib,sys,math
sys.set_int_max_str_digits(50000)
SRC=Path(sys.argv[1])if len(sys.argv)>1 else Path(__file__).resolve().parent
OUT=Path(sys.argv[2])if len(sys.argv)>2 else Path('ml18-python-output')
if OUT.exists():raise RuntimeError('Output directory exists;choose a new path to preserve earlier runs')
OUT.mkdir(parents=True)

def F(v):return None if v is None or v=='.'or v==''else Q(str(v))

def rows(a,need=True):
 out=[]
 for i,r in enumerate(a['rows']):
  x=list(map(F,r['x']));y=F(r.get('y'))if need else None;w=Q(str(r.get('weight',1)));complete=all(v is not None for v in x)and(not need or y is not None)
  out.append(dict(id=r.get('id','row:'+str(i+1)),index=i,x=x,y=y,w=w,role=r.get('role','train'),complete=complete,eligible=complete and w>0))
 return out

def dot(x,y):return sum((a*b for a,b in zip(x,y)),Q(0))

def solve(A,b):
 n=len(A);m=len(A[0])if n else 0;M=[r[:]+[t]for r,t in zip(A,b)];piv=[];k=0
 for j in range(m):
  h=next((i for i in range(k,n)if M[i][j]),None)
  if h is None:continue
  M[k],M[h]=M[h],M[k]
  for i in range(k+1,n):
   if M[i][j]:
    f=M[i][j]/M[k][j]
    M[i]=[v-f*u for v,u in zip(M[i],M[k])]
  piv.append(j);k+=1
  if k==n:break
 assert not any(all(not x for x in r[:-1])and r[-1]for r in M)
 def back(free):
  x=[Q(0)]*m
  for j,v in free.items():x[j]=v
  for i,j in reversed(list(enumerate(piv))):x[j]=(M[i][-1]-dot(M[i][j+1:m],x[j+1:m]))/M[i][j]
  return x
 part=back({});ns=[]
 for j in range(m):
  if j not in piv:
   x=back({j:Q(1)});ns.append([v-u for v,u in zip(x,part)])
 return dict(rank=len(piv),particular=part,nullspace=ns)

def frame(rr,p,scale='range',need=True):
 tr=[r for r in rr if r['role']=='train'and r['eligible']];wt=sum((r['w']for r in tr),Q(0))
 if not wt:return None
 mx=[sum((r['w']*r['x'][j]for r in tr),Q(0))/wt for j in range(p)];ranges=[max(r['x'][j]for r in tr)-min(r['x'][j]for r in tr)or Q(1)for j in range(p)];sc=ranges if scale=='range'else[Q(1)]*p
 my=sum((r['w']*r['y']for r in tr),Q(0))/wt if need else None;z=[[ (v-m)/s for v,m,s in zip(r['x'],mx,sc)]for r in tr]
 G=[[sum((r['w']*v[j]*v[k]for r,v in zip(tr,z)),Q(0))/wt for k in range(p)]for j in range(p)]
 g=[sum((r['w']*v[j]*(r['y']-my)for r,v in zip(tr,z)),Q(0))/wt for j in range(p)]if need else[Q(0)]*p
 vy=sum((r['w']*(r['y']-my)**2 for r in tr),Q(0))/wt if need else None
 return dict(tr=tr,p=p,W=wt,mx=mx,range=ranges,sc=sc,my=my,G=G,g=g,vy=vy)

def fsummary(f):return dict(defined=True,dimension=f['p'],trainingRows=len(f['tr']),trainingIDs=[r['id']for r in f['tr']],trainingWeight=f['W'],meanX=f['mx'],trainingRangeWithConstantOne=f['range'],scale=f['sc'],meanY=f['my'],centeredGram=f['G'],centeredXY=f['g'],varianceY=f['vy'])

def geom(f,s):
 p=f['p'];G=f['G'];q=solve(G,[Q(0)]*p);active=[j for j in range(p)if G[j][j]];zero=[j for j in range(p)if not G[j][j]];pairs=[dict(features=[k,j],squaredCorrelation=G[j][k]**2/(G[j][j]*G[k][k]))for h,j in enumerate(active)for k in active[:h]];mu=max([Q(0)]+[v['squaredCorrelation']for v in pairs]);bound=s==0 or(2*s-1)**2*mu<1
 return dict(defined=True,rank=q['rank'],centeredNullity=p-q['rank'],maximumCenteredRankFromRows=max(0,len(f['tr'])-1),centeredNullspace=q['nullspace'],activeColumns=active,constantColumns=zero,coherenceSquared=mu,pairLedger=pairs,sparsity=s,strictGershgorinInequalityOnActiveColumns=bound,originalDictionarySparseUniquenessSufficient=s==0 or(not zero and bound),allOriginalSlopesIdentified=q['rank']==p)

def fit(f,S):
 p=f['p'];q=solve([[f['G'][j][k]for k in S]for j in S],[f['g'][j]for j in S]);gamma=[Q(0)]*p
 for j,v in zip(S,q['particular']):gamma[j]=v
 ns=[]
 for u in q['nullspace']:
  v=[Q(0)]*p
  for j,t in zip(S,u):v[j]=t
  ns.append(v)
 beta=[v/s for v,s in zip(gamma,f['sc'])];rawns=[[v/s for v,s in zip(u,f['sc'])]for u in ns];mse=f['vy']-dot(f['g'],gamma);assert mse>=0
 return dict(support=list(S),rank=q['rank'],gamma=gamma,beta=beta,alpha=f['my']-dot(f['mx'],beta),ns=ns,rawns=rawns,mse=mse,identified=q['rank']==len(S))

def summary(f,q):return dict(support=q['support'],rank=q['rank'],trainingMSE=q['mse'],standardizedParticular=q['gamma'],rawParticularSlopes=q['beta'],rawParticularIntercept=q['alpha'],coefficientParticularIsUnique=q['identified'],standardizedNullspace=q['ns'],rawSlopeNullspace=q['rawns'],rawInterceptNullDirections=[-dot(f['mx'],u)for u in q['rawns']],coefficientIdentification=[all(not u[j]for u in q['ns'])for j in range(f['p'])])

def pred(f,q,x):
 if any(t is None for t in x):return dict(defined=False,reason='missing-query-X')
 z=[(v-m)/s for v,m,s in zip(x,f['mx'],f['sc'])];bad=next((u for u in q['ns']if dot(z,u)),None)
 return dict(defined=False,reason='query-not-identified-across-training-OLS-solutions',nullDirection=bad)if bad is not None else dict(defined=True,value=f['my']+dot(z,q['gamma']))

def allfit(f,maxs):
 fits=[fit(f,S)for s in range(maxs+1)for S in combinations(range(f['p']),s)];winners=[min((q for q in fits if len(q['support'])<=b),key=lambda q:(q['mse'],len(q['support']),q['support']))for b in range(maxs+1)];return fits,winners

def scores(rr,pp,role,ids=None):
 use=[r for r in rr if r['role']==role and r['eligible']and(ids is None or r['id']in ids)];cv=[r for r in use if pp[r['index']]['defined']];wt=sum((r['w']for r in cv),Q(0))
 return dict(role=role,eligibleRows=len(use),scoredRows=len(cv),coverageComplete=len(use)==len(cv),weight=wt,IDs=[r['id']for r in cv],MSE=dict(defined=True,value=sum((r['w']*(pp[r['index']]['value']-r['y'])**2 for r in cv),Q(0))/wt)if wt else dict(defined=False),MAE=dict(defined=True,value=sum((r['w']*abs(pp[r['index']]['value']-r['y'])for r in cv),Q(0))/wt)if wt else dict(defined=False))

def validation(a):
 rr=rows(a);p=a.get('dimension',len(rr[0]['x'])if rr else 0);f=frame(rr,p,a.get('scale','range'));mx=a.get('maxSupport',min(3,p));budgets=a.get('budgets',list(range(mx+1)))
 if f is None:return dict(frame=dict(defined=False,dimension=p,trainingRows=0,trainingWeight=Q(0)),selected=dict(defined=False),candidates=[])
 ff,ww=allfit(f,mx);pp=[[pred(f,ww[b],r['x'])for r in rr]for b in budgets];cc=[dict(index=j,budget=b,fit=summary(f,ww[b]),availableScores=[scores(rr,pp[j],role)for role in ['train','validation','test']])for j,b in enumerate(budgets)];valid=[j for j,v in enumerate(cc)if v['availableScores'][1]['coverageComplete']and v['availableScores'][1]['MSE']['defined']];sel=min(valid,key=lambda j:(cc[j]['availableScores'][1]['MSE']['value'],j))if valid else None
 common={}
 for role in ['train','validation','test']:
  ids={r['id']for r in rr if r['role']==role and r['eligible']and all(v[r['index']]['defined']for v in pp)}
  common[role]=dict(IDs=[r['id']for r in rr if r['id']in ids],candidateScores=[scores(rr,v,role,ids)for v in pp])
 return dict(frame=fsummary(f),geometry=geom(f,mx),maxSupport=mx,budgets=budgets,enumeratedSupports=len(ff),trainingSupportLedger=[dict(support=q['support'],rank=q['rank'],trainingMSE=q['mse'],coefficientsIdentified=q['identified'])for q in ff],candidates=cc,selected=dict(defined=False)if sel is None else dict(defined=True,candidateIndex=sel,budget=budgets[sel],support=ww[budgets[sel]]['support'],validationMSE=cc[sel]['availableScores'][1]['MSE']['value']),commonFrames=common,predictions=[dict(id=r['id'],index=r['index'],role=r['role'],actualY=r['y'],weight=r['w'],candidates=[dict(budget=b,prediction=pp[j][r['index']])for j,b in enumerate(budgets)],selected=dict(defined=False)if sel is None else pp[sel][r['index']])for r in rr])

def read(name):
 with(SRC/name).open(encoding='utf8',newline='')as f:return list(csv.DictReader(f))
native=read('actual48-country-revised-original-2023-2024.csv');derived=read('derived16-country-polynomial-features-and-roles.csv');lookup={(r['countryISO3'],r['indicatorID'],r['date']):r['originalValueToken']for r in native}
models={};meta={}
country=[]
for iso in sorted({r['countryISO3']for r in native}):
 g=F(lookup[iso,'NY.GDP.PCAP.KD','2023'])/10000;pi=F(lookup[iso,'FP.CPI.TOTL.ZG','2023'])/10
 country.append(dict(id=iso+':2024',sourceRow=next(i+1 for i,r in enumerate(derived)if r['countryISO3']==iso),x=list(map(str,[g,pi,g*g,pi*pi,g*pi,g**3,pi**3,g*g*pi,g*pi*pi,g])),y=lookup[iso,'NY.GDP.MKTP.KD.ZG','2024']))
models['country']=country
meta['country']=dict(featureNames=['g','pi','g2','pi2','g_pi','g3','pi3','g2_pi','g_pi2','g_duplicate'],yUnit='annual total GDP growth percent',MSEUnit='(percentage point)^2',xScope='g=GDPpc2023/10000constant2015USD,pi=CPI2023/10percent;explicit engineered monomials')
pn=read('actual3613-NLS-original52-fields-and-sparse-features.csv');person=[]
for i,d in enumerate(pn,1):
 marital=F(d['marsta76']);xx=[d[k]if F(d[k])is not None else None for k in ['ed76','age76','nearc4','nearc2','black','smsa76r','reg76r']]+[None if marital is None else str(int(marital==1))]
 person.append(dict(id='person-row:'+str(i),sourceRow=i,x=xx,y=None if F(d['lwage76'])is None else d['lwage76']))
models['person']=person
meta['person']=dict(featureNames=['ed76','age76','nearc4','nearc2','black','smsa76r','reg76r','married_spouse_present76'],yUnit='native trimmed log hourly wage1976',MSEUnit='squared log-wage units',xScope='native schooling/age/binary geographic/college-proximity plus observed marital indicator;no causal effect claim')
cn=read('actual3150-churn-original14-fields-and-sparse-features.csv');cfields=['Call  Failure','Complains','Subscription  Length','Charge  Amount','Seconds of Use','Frequency of use','Frequency of SMS','Age']
models['company']=[dict(id='customer-row:'+str(i),sourceRow=i,x=[d[k]for k in cfields],y=d['Churn'])for i,d in enumerate(cn,1)]
meta['company']=dict(featureNames=['CallFailure','Complains','SubscriptionLength','ChargeAmount','SecondsUse','FrequencyUse','FrequencySMS','Age'],yUnit='native Churn0/1',MSEUnit='squared binary-response units',xScope='native recorded feature units;linear predictions not automatically probabilities;retain charge10')
for kind,rr in models.items():
 for j,r in enumerate(sorted(rr,key=lambda r:(hashlib.sha256(('ML18|'+kind+'|'+r['id']).encode()).digest(),r['id']))):
  planned=['test','validation','train','train','train'][j%5];r.update(splitRank=j,plannedRole=planned,role=planned if r['y']is not None and all(v is not None for v in r['x'])else'excluded',weight='1')

tables={
 'computed-study-metrics.csv':[],
 'computed-frame-transforms.csv':[],
 'computed-gram-and-coherence.csv':[],
 'computed-support-ledger.csv':[],
 'computed-budget-coefficients.csv':[],
 'computed-budget-scores.csv':[],
 'computed-selected-budget.csv':[],
 'computed-row-predictions.csv':[],
 'computed-eligibility.csv':[],
 'computed-known-noise-law.csv':[]}
def tok(x):return ''if x is None else str(x)
def approx(x):
 if x is None:return ''
 try:v=float(x)
 except OverflowError:return 'overflow'
 if v==0 and x:return 'underflow:nonzero'
 if v==1 and x!=1:return 'rounded1:nonone'
 return format(v,'.17g')
def metric(kind,profile,name,value,unit):tables['computed-study-metrics.csv'].append(dict(kind=kind,profile=profile,metric=name,exact=tok(value),approximate=approx(value),defined=int(value is not None),unit=unit))
def scoreout(kind,profile,budget,which,s):
 v=s['MSE'].get('value');ma=s['MAE'].get('value');tables['computed-budget-scores.csv'].append(dict(kind=kind,profile=profile,budget=budget,frame=which,role=s['role'],eligibleRows=s['eligibleRows'],scoredRows=s['scoredRows'],coverageComplete=int(s['coverageComplete']),weight=tok(s['weight']),MSEExact=tok(v),MSEApprox=approx(v),MSEDefined=int(v is not None),MAEExact=tok(ma),MAEApprox=approx(ma),MAEDefined=int(ma is not None),MSEUnit=meta[kind]['MSEUnit'],MAEUnit=meta[kind]['yUnit'],scoredIDs='|'.join(s['IDs'])))
studies={}
for kind,original in models.items():
 ids=[r['id']for r in sorted((r for r in original if r['role']=='train'),key=lambda r:r['splitRank'])]
 for profile,limit in [('full',len(ids)),('prefix2',min(2,len(ids))),('prefix0',0)]:
  keep=set(ids[:limit]);rr=[{k:r[k]for k in ['id','x','y','role','weight']}for r in original]
  for r in rr:
   if r['role']=='train'and r['id']not in keep:r['role']='unused'
  inp=dict(rows=rr,dimension=len(meta[kind]['featureNames']),maxSupport=3,budgets=[0,1,2,3]);v=validation(inp);studies[kind+'|'+profile]=v;parsed=rows(inp)
  metric(kind,profile,'originalRows',Q(len(original)),'rows');metric(kind,profile,'eligibleTrainingRows',Q(limit),'rows');metric(kind,profile,'featureColumns',Q(inp['dimension']),'columns')
  for raw,r in zip(original,parsed):tables['computed-eligibility.csv'].append(dict(kind=kind,profile=profile,id=r['id'],sourceRow=raw['sourceRow'],splitRank=raw['splitRank'],plannedRole=raw['plannedRole'],effectiveRole=r['role'],complete=int(r['complete']),positiveWeight=int(r['w']>0),trainingUsed=int(r['role']=='train'and r['eligible']),weight=tok(r['w']),originalY=tok(r['y']),originalX='|'.join(tok(x)for x in r['x']),reason='missing-required-field'if not r['complete']else'zero-weight'if not r['w']else'explicitly-excluded'if r['role']=='excluded'else''))
  if not v['frame']['defined']:
   tables['computed-selected-budget.csv'].append(dict(kind=kind,profile=profile,defined=0,budget='',support='',featureNames='',validationMSEExact='',validationMSEApprox='',reason='no-positive-complete-training-mass'));metric(kind,profile,'rank',None,'rank');continue
  f=v['frame'];gg=v['geometry'];metric(kind,profile,'rank',Q(gg['rank']),'rank');metric(kind,profile,'centeredNullity',Q(gg['centeredNullity']),'dimensions');metric(kind,profile,'coherenceSquared',gg['coherenceSquared'],'dimensionless');metric(kind,profile,'s3SparseUniquenessSufficient',Q(int(gg['originalDictionarySparseUniquenessSufficient'])),'indicator')
  for j,name in enumerate(meta[kind]['featureNames']):tables['computed-frame-transforms.csv'].append(dict(kind=kind,profile=profile,feature=j,name=name,meanXExact=tok(f['meanX'][j]),meanXApprox=approx(f['meanX'][j]),rangeExact=tok(f['trainingRangeWithConstantOne'][j]),rangeApprox=approx(f['trainingRangeWithConstantOne'][j]),scaleExact=tok(f['scale'][j]),scaleApprox=approx(f['scale'][j]),centeredXYExact=tok(f['centeredXY'][j]),centeredXYApprox=approx(f['centeredXY'][j]),scope=meta[kind]['xScope']))
  for j in range(inp['dimension']):
   for k in range(inp['dimension']):
    g=f['centeredGram'];rho=g[j][k]**2/(g[j][j]*g[k][k])if j!=k and g[j][j]*g[k][k]else None
    tables['computed-gram-and-coherence.csv'].append(dict(kind=kind,profile=profile,rowFeature=j,columnFeature=k,GramExact=tok(g[j][k]),GramApprox=approx(g[j][k]),pairCoherenceSquaredExact=tok(rho),pairCoherenceSquaredApprox=approx(rho),pairDefined=int(rho is not None)))
  for q in v['trainingSupportLedger']:tables['computed-support-ledger.csv'].append(dict(kind=kind,profile=profile,support='|'.join(map(str,q['support'])),supportSize=len(q['support']),featureNames='|'.join(meta[kind]['featureNames'][j]for j in q['support']),rank=q['rank'],coefficientParticularIsUnique=int(q['coefficientsIdentified']),trainingMSEExact=tok(q['trainingMSE']),trainingMSEApprox=approx(q['trainingMSE']),MSEUnit=meta[kind]['MSEUnit']))
  for cand in v['candidates']:
   b=cand['budget'];fitrow=cand['fit'];ss=set(fitrow['support'])
   for j,name in enumerate(['intercept']+meta[kind]['featureNames']):
    z=fitrow['rawParticularIntercept']if j==0 else fitrow['rawParticularSlopes'][j-1];gamma=None if j==0 else fitrow['standardizedParticular'][j-1]
    tables['computed-budget-coefficients.csv'].append(dict(kind=kind,profile=profile,budget=b,feature=j-1,name=name,selected=int(j==0 or j-1 in ss),rawParticularExact=tok(z),rawParticularApprox=approx(z),standardizedExact=tok(gamma),standardizedApprox=approx(gamma),allSupportCoefficientsIdentified=int(fitrow['coefficientParticularIsUnique']),unit=meta[kind]['yUnit']if j==0 else meta[kind]['yUnit']+'/native feature unit'))
   for s in cand['availableScores']:scoreout(kind,profile,b,'available',s)
   for role in ['train','validation','test']:scoreout(kind,profile,b,'common',v['commonFrames'][role]['candidateScores'][cand['index']])
  selected=v['selected'];tables['computed-selected-budget.csv'].append(dict(kind=kind,profile=profile,defined=int(selected['defined']),budget=selected.get('budget',''),support='|'.join(map(str,selected.get('support',[]))),featureNames='|'.join(meta[kind]['featureNames'][j]for j in selected.get('support',[])),validationMSEExact=tok(selected.get('validationMSE')),validationMSEApprox=approx(selected.get('validationMSE')),reason=''if selected['defined']else'no-candidate-covers-positive-complete-validation-frame'))
  metric(kind,profile,'selectedBudget',Q(selected['budget'])if selected['defined']else None,'features maximum')
  for r in v['predictions']:
   for item in r['candidates']:
    prediction_row=item['prediction'];val=prediction_row.get('value');err=None if val is None or r['actualY']is None else val-r['actualY'];tables['computed-row-predictions.csv'].append(dict(kind=kind,profile=profile,id=r['id'],sourceRow=original[r['index']]['sourceRow'],role=r['role'],budget=item['budget'],isSelected=int(selected['defined']and item['budget']==selected['budget']),actualYExact=tok(r['actualY']),actualYApprox=approx(r['actualY']),predictionDefined=int(prediction_row['defined']),predictionExact=tok(val),predictionApprox=approx(val),residualPredictionMinusYExact=tok(err),squaredErrorExact=tok(None if err is None else err*err),weight=tok(r['weight']),reason=prediction_row.get('reason',''),yUnit=meta[kind]['yUnit']))

# A constructed complete joint law,explicitly separate from observed cases.
for scenario,prob,estimate,reported,lo,hi,covered in [('A',Q(1,3),Q(3),1,Q(2),Q(4),0),('B',Q(2,3),Q(0),0,None,None,0)]:tables['computed-known-noise-law.csv'].append(dict(kind='constructed-known-law',scenario=scenario,probabilityExact=tok(prob),trueFullSlope='1',zeroFilledEstimateExact=tok(estimate),reported=reported,diagnosticRadius='1',lower=tok(lo),upper=tok(hi),coversFixedTruth=covered,scope='X=(-1,1);jointnoise2Xprob1/3,-Xprob2/3;not actual data and not95% calibration'))
for name,value,unit in [('selectedProbability',Q(1,3),'probability'),('conditionalMean',Q(3),'slope'),('conditionalBias',Q(2),'slope'),('conditionalCoverage',Q(0),'probability'),('zeroFilledMean',Q(1),'slope'),('zeroFilledMSE',Q(2),'slope^2')]:metric('constructed-known-law','radius1',name,value,unit)

manifest=[]
for name,rr in tables.items():
 assert rr,name
 with(OUT/name).open('w',encoding='utf8',newline='')as f:w=csv.DictWriter(f,fieldnames=list(rr[0]));w.writeheader();w.writerows(rr)
 manifest.append(dict(file=name,rows=len(rr),columns=len(rr[0]),bodyFields=len(rr)*len(rr[0]),sha256=hashlib.sha256((OUT/name).read_bytes()).hexdigest()))
def serial(x):return str(x)if isinstance(x,Q)else{xk:serial(xv)for xk,xv in x.items()}if isinstance(x,dict)else[serial(v)for v in x]if isinstance(x,list)else x
(OUT/'study-results.json').write_text(json.dumps(serial(dict(meta=meta,studies=studies)),ensure_ascii=False,separators=(',',':'))+'\n',encoding='utf8')
report=dict(program='ML18 standalone exact Fraction,author implementation',inputFiles=[dict(file=p.name,sha256=hashlib.sha256(p.read_bytes()).hexdigest())for p in [SRC/'actual48-country-revised-original-2023-2024.csv',SRC/'derived16-country-polynomial-features-and-roles.csv',SRC/'actual3613-NLS-original52-fields-and-sparse-features.csv',SRC/'actual3150-churn-original14-fields-and-sparse-features.csv']],profiles=list(studies),tables=manifest,totalCSVBodyFields=sum(x['bodyFields']for x in manifest),actualSelectionValidIntervals=False,exactCoherenceRootDisplayNotUsed=True)
(OUT/'manifest.json').write_text(json.dumps(report,ensure_ascii=False,indent=2)+'\n',encoding='utf8');print(json.dumps(dict(profiles=len(studies),CSV=len(manifest),bodyFields=report['totalCSVBodyFields'])))
