"""ML10 standalone PCA/SVD reproduction from native-field source CSVs.

Requires Python3 and NumPy. Example:
python ml10-public-analysis.py --source-dir ml10-sources --output-dir results

Exact Fraction original moments/rank and declared-basis projection are separate
from NumPy's approximate direct SVD. No JS/contract/model/author-checker/stored
answer/derived-result file is imported. Native feature selection is reconstructed
from the original-field CSVs. This is an authored reproduction,not a peer oracle.
The browser's small Gram/Jacobi algorithm and this direct SVD have different
conditioning behavior; tiny raw-scale eigenspaces need not agree digit-for-digit.
"""
from pathlib import Path
from fractions import Fraction as Q
import csv,json,math,argparse
import numpy as np

def number(v):
 if isinstance(v,bool)or v is None:raise ValueError('finite numeric token required')
 return Q(str(v))

def rank_exact(A):
 a=[list(r)for r in A];i=0
 for j in range(len(a[0])if a else 0):
  k=next((k for k in range(i,len(a))if a[k][j]),None)
  if k is None:continue
  a[i],a[k]=a[k],a[i];pivot=a[i][j]
  for k in range(i+1,len(a)):
   q=a[k][j]/pivot
   for h in range(j,len(a[k])):a[k][h]-=q*a[i][h]
  i+=1
  if i==len(a):break
 return i

def moments(a):
 rows=a['rows'];p=len(rows[0]['x']);out=[]
 for i,r in enumerate(rows):
  if len(r['x'])!=p:raise ValueError('consistent feature dimension')
  w=number(r.get('weight',1));x=[None if v is None else number(v)for v in r['x']]
  if w<0:raise ValueError('nonnegative weight')
  out.append(dict(r,id=r.get('id',i),x=x,weight=w))
 good=[r for r in out if r['weight']and None not in r['x']]
 if not good:raise ValueError('positive complete frame')
 W=sum((r['weight']for r in good),Q());mu=[sum((r['weight']*r['x'][j]for r in good),Q())/W for j in range(p)];scatter=[[sum((r['weight']*(r['x'][j]-mu[j])*(r['x'][k]-mu[k])for r in good),Q())for k in range(p)]for j in range(p)]
 norm=a.get('normalization','mass')
 if norm not in ['mass','unit-sample']:raise ValueError('known normalization')
 if norm=='unit-sample'and(len(good)<2 or any(r['weight']!=1 for r in good)):raise ValueError('unit sample requires >=2 unit-weight rows')
 den=W if norm=='mass'else Q(len(good)-1);cov=[[v/den for v in row]for row in scatter];lo=[min(r['x'][j]for r in good)for j in range(p)];hi=[max(r['x'][j]for r in good)for j in range(p)]
 return dict(rows=out,good=good,p=p,weight=W,mean=mu,scatter=scatter,covariance=cov,variance=[cov[j][j]for j in range(p)],trace=sum((cov[j][j]for j in range(p)),Q()),minimum=lo,maximum=hi,ranges=[b-a for a,b in zip(lo,hi)],exactRank=rank_exact(scatter),normalization=norm,denominator=den)

def inverse_exact(A):
 n=len(A);a=[list(row)+[Q(int(i==j))for j in range(n)]for i,row in enumerate(A)]
 for j in range(n):
  k=next((k for k in range(j,n)if a[k][j]),None)
  if k is None:raise ValueError('full-column-rank basis required')
  a[k],a[j]=a[j],a[k];q=a[j][j];a[j]=[v/q for v in a[j]]
  for k in range(n):
   if k!=j:q=a[k][j];a[k]=[v-q*b for v,b in zip(a[k],a[j])]
 return [r[n:]for r in a]

def projection(a):
 rows=a['rows'];p=len(rows[0]['x']);B=[[number(v)for v in r]for r in a['basis']];k=len(B[0]);center=[number(v)for v in a.get('center',[0]*p)]
 if len(B)!=p or any(len(r)!=k for r in B)or rank_exact(B)!=k:raise ValueError('independent p×k basis')
 G=[[sum((B[i][j]*B[i][h]for i in range(p)),Q())for h in range(k)]for j in range(k)];I=inverse_exact(G)if k else[];P=[[sum((B[i][j]*I[j][h]*B[l][h]for j in range(k)for h in range(k)),Q())for l in range(p)]for i in range(p)];records=[]
 for i,r in enumerate(rows):
  if None in r['x']:records.append(dict(id=r.get('id',i),defined=False));continue
  z=[number(v)-mu for v,mu in zip(r['x'],center)];hat=[sum((v*x for v,x in zip(row,z)),Q())for row in P];res=[v-h for v,h in zip(z,hat)];records.append(dict(id=r.get('id',i),defined=True,reconstruction=[v+mu for v,mu in zip(hat,center)],residual=res,squaredError=sum((v*v for v in res),Q())))
 return dict(projector=P,rows=records)

def sign_rows(V):
 V=V.copy()
 for v in V:
  if v[np.argmax(np.abs(v))]<0:v*=-1
 return V

def spectrum(a):
 M=[[number(v)for v in row]for row in a['matrix']];A=np.array([[float(v)for v in row]for row in M]);values,V=np.linalg.eigh(A);ix=np.argsort(-values,kind='stable');values=values[ix];V=sign_rows(V[:,ix].T)
 if np.min(values)<-1e-12*max(1,np.max(np.abs(A))):raise ValueError('PSD matrix required')
 return dict(matrix=M,exactRank=rank_exact(M),eigenvaluesApprox=values.tolist(),axesApprox=V.tolist())

def svd(a):
 exact=[[number(v)for v in row]for row in a['matrix']];A=np.array([[float(v)for v in row]for row in exact]);n,p=A.shape;U,s,V=np.linalg.svd(A,full_matrices=n<p);V=sign_rows(V);values=np.pad(s,(0,p-len(s)));scores=A@V.T;k=a.get('k',min(2,p));paths=[]
 for q in range(p+1):
  rec=scores[:,:q]@V[:q,:];paths.append(dict(k=q,FrobeniusSquaredErrorApprox=float(np.sum((A-rec)**2))))
 G=[[sum((r[j]*r[h]for r in exact),Q())for h in range(p)]for j in range(p)]
 return dict(exactRank=rank_exact(exact),gramExact=G,singularValuesApprox=values.tolist(),axesApprox=V.tolist(),reconstructionApprox=(scores[:,:k]@V[:k,:]).tolist(),errorPath=paths)

def pca(a):
 m=moments(dict(rows=a['rows']));p=m['p'];scaling=a.get('scaling','none');k=a.get('k',min(2,p))
 if not isinstance(k,int)or isinstance(k,bool)or not 0<=k<=p:raise ValueError('integer k0..p')
 if scaling not in ['none','std','range']:raise ValueError('known scaling')
 scales=np.array([math.sqrt(float(v))if scaling=='std'and v else float(r)if scaling=='range'and r else 1 for v,r in zip(m['variance'],m['ranges'])]);X=np.array([[float(v-mu)for v,mu in zip(r['x'],m['mean'])]for r in m['good']]);Z=X/scales;w=np.array([float(r['weight']/m['weight'])for r in m['good']]);A=Z*np.sqrt(w[:,None]);U,s,V=np.linalg.svd(A,full_matrices=A.shape[0]<p);V=sign_rows(V);eigen=np.pad(s*s,(0,p-len(s)));tr=float(sum(eigen));models=dict(moments=m,k=k,scaling=scaling,scalesApprox=scales.tolist(),axesApprox=V.tolist(),eigenvaluesApprox=eigen.tolist(),scaledCovarianceApprox=((Z.T*w)@Z).tolist(),explainedRatioApprox=eigen[:k].sum()/tr if tr else None)
 def transform(rows):
  records=[];loss=[dict(k=q,mass=0.,total=0.,features=np.zeros(p))for q in range(p+1)]
  for i,raw in enumerate(rows):
   rid=raw.get('id',i);xx=[None if v is None else number(v)for v in raw['x']];weight=number(raw.get('weight',1))
   if None in xx:records.append(dict(id=rid,defined=False));continue
   z=np.array([float(v-mu)for v,mu in zip(xx,m['mean'])])/scales;score=z@V.T;chosen=None
   for q in range(p+1):
    hat=score[:q]@V[:q,:];res=z-hat
    if weight>0:loss[q]['mass']+=float(weight);loss[q]['total']+=float(weight)*float(res@res);loss[q]['features']+=float(weight)*(res*scales)**2
    if q==k:chosen=hat
   rec=np.array([float(v)for v in m['mean']])+chosen*scales;res=np.array([float(v)for v in xx])-rec;records.append(dict(id=rid,defined=True,scoresApprox=score.tolist(),reconstructionApprox=rec.tolist(),actual=xx,residualApprox=res.tolist()))
  return records,[dict(k=v['k'],meanScaledSquaredErrorApprox=v['total']/v['mass']if v['mass']else None,perFeatureOriginalMSEApprox=(v['features']/v['mass']).tolist()if v['mass']else[None]*p)for v in loss]
 models['training'],models['trainingErrorPath']=transform(m['rows']);models['queries'],models['queryErrorPath']=transform(a.get('queries',[]));return models

def csvread(p):
 with Path(p).open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))

def read_sources(src):
 src=Path(src);raw=csvread(src/'actual320-country-four-indicators-original-2020-2024.csv');keys=['NY.GDP.PCAP.KD','NY.GDP.MKTP.KD.ZG','FP.CPI.TOTL.ZG','SP.DYN.LE00.IN'];lookup={(r['countryISO3'],int(r['date']),r['indicatorID']):r['originalValueToken']for r in raw};country=[]
 for code in sorted({r['countryISO3']for r in raw}):
  for year in range(2020,2025):
   x=[None if lookup[code,year,key]==''else str(Q(lookup[code,year,key]))for key in keys];country.append(dict(id=code+':'+str(year),sourceRow=code+':'+str(year),originalID=code,x=x,weight=1,role='excluded'if None in x else'outer-test'if year==2024 else'train'))
 person=[]
 for i,r in enumerate(csvread(src/'actual3613-NLS-original52-fields-and-PCA-selection.csv'),1):
  x=[None if r[k]=='.'else str(Q(r[k])/(100 if k=='wage76'else 1))for k in ['ed76','age76','wage76']];person.append(dict(id='person:'+str(i),sourceRow=i,originalID=r['id'],x=x,weight=1,role='excluded'if None in x else'outer-test'if i%5==0 else'train'))
 company=[]
 for i,r in enumerate(csvread(src/'actual3150-churn-original14-fields-and-PCA-selection.csv'),1):company.append(dict(id='customer:'+str(i),sourceRow=i,originalID=None,x=[str(Q(r[k]))for k in ['Call  Failure','Subscription  Length','Charge  Amount','Seconds of Use']],weight=1,role='outer-test'if i%5==0 else'train',annotationChurn=r['Churn']))
 features=dict(country=['GDP per capita','Real total GDP growth','CPI inflation','Period life expectancy'],person=['Schooling1976','Age1976','Raw wage1976'],company=['Call failure','Subscription length','Charge amount','Seconds of use']);units=dict(country=['constant2015USD/person','annual%','annual%','years'],person=['years','years','nominal1976USD/hour'],company=['count','months','ordinal native code','seconds']);return {k:dict(records=r,featureNames=features[k],featureUnits=units[k])for k,r in [('country',country),('person',person),('company',company)]}

_OMITTED=object()
def realdata(models,kind,options=_OMITTED):
 if options is _OMITTED:options={}
 if not isinstance(options,dict):raise ValueError('options object,not explicit None')
 m=models[kind];train=[r for r in m['records']if r['role']=='train'];outer=[r for r in m['records']if r['role']=='outer-test'];result=pca(dict(rows=train,queries=outer,k=options.get('k',2),scaling=options.get('scaling','std')));return dict(kind=kind,train=train,outer=outer,result=result,featureNames=m['featureNames'],featureUnits=m['featureUnits'])

def serial(x):
 if isinstance(x,Q):return str(x)
 if isinstance(x,np.generic):return x.item()
 if isinstance(x,np.ndarray):return x.tolist()
 if isinstance(x,dict):return {k:serial(v)for k,v in x.items()}
 if isinstance(x,(list,tuple)):return [serial(v)for v in x]
 return x

def writecsv(p,heads,rows):
 with Path(p).open('w',encoding='utf8',newline='')as f:w=csv.writer(f);w.writerow(heads);w.writerows([[''if v is None else str(v)for v in r]for r in rows])

PROFILES=[(kind+'-'+mode,kind,mode)for kind in ['country','person','company']for mode in ['none','std','range']]
def study(src,out):
 out=Path(out);out.mkdir(parents=True,exist_ok=True);models=read_sources(src);metrics=[];roles=[];mom=[];cov=[];eig=[];axes=[];scores=[];reconstruction=[];paths=[];floss=[];full={}
 for kind,m in models.items():
  for r in m['records']:roles.append([kind,r['id'],r['sourceRow'],r['originalID'],r['role'],r['weight'],*[r['x'][j]if j<len(r['x'])else None for j in range(4)],r.get('annotationChurn')])
  mm=moments(dict(rows=[r for r in m['records']if r['role']=='train']))
  for j,name in enumerate(m['featureNames']):mom.append([kind,j,name,m['featureUnits'][j],mm['mean'][j],mm['variance'][j],math.sqrt(float(mm['variance'][j])),mm['ranges'][j],mm['minimum'][j],mm['maximum'][j]])
 for name,kind,mode in PROFILES:
  z=realdata(models,kind,dict(scaling=mode,k=2));r=z['result'];m=r['moments'];p=m['p'];full[name]=z
  for key,value,exact in [('sourceModelRows',len(models[kind]['records']),True),('trainingRows',len(z['train']),True),('outerRows',len(z['outer']),True),('dimensions',p,True),('k',2,True),('exactRank',m['exactRank'],True),('retainedVarianceRatio',r['explainedRatioApprox'],False),('trainingScaledMSE',r['trainingErrorPath'][2]['meanScaledSquaredErrorApprox'],False),('outerScaledMSE',r['queryErrorPath'][2]['meanScaledSquaredErrorApprox'],False)]:metrics.append([name,key,value,exact])
  for j in range(p):
   metrics.extend([[name,'eigenvalue'+str(j),r['eigenvaluesApprox'][j],False],[name,'trainingOriginalMSE'+str(j),r['trainingErrorPath'][2]['perFeatureOriginalMSEApprox'][j],False],[name,'outerOriginalMSE'+str(j),r['queryErrorPath'][2]['perFeatureOriginalMSEApprox'][j],False]])
   eig.append([name,j,r['eigenvaluesApprox'][j],r['eigenvaluesApprox'][j]/sum(r['eigenvaluesApprox'])]);
   for h in range(p):cov.append([name,j,h,m['covariance'][j][h],r['scaledCovarianceApprox'][j][h]]);axes.append([name,j,h,z['featureNames'][h],r['axesApprox'][j][h]])
  for q in range(p+1):
   tr=r['trainingErrorPath'][q];te=r['queryErrorPath'][q];paths.append([name,q,tr['meanScaledSquaredErrorApprox'],te['meanScaledSquaredErrorApprox'],sum(r['eigenvaluesApprox'][q:])])
   for j in range(p):floss.append([name,q,j,z['featureNames'][j],tr['perFeatureOriginalMSEApprox'][j],te['perFeatureOriginalMSEApprox'][j]])
  for role,original,records in [('train',z['train'],r['training']),('outer-test',z['outer'],r['queries'])]:
   for source,v in zip(original,records):
    scores.append([name,role,v['id'],source['sourceRow'],*[v['scoresApprox'][j]if j<p else None for j in range(4)],v['defined']])
    for j in range(p):reconstruction.append([name,role,v['id'],source['sourceRow'],j,v['actual'][j],v['reconstructionApprox'][j],v['residualApprox'][j],v['residualApprox'][j]**2])
  print(name,'train',r['trainingErrorPath'][2]['meanScaledSquaredErrorApprox'],'outer',r['queryErrorPath'][2]['meanScaledSquaredErrorApprox'],flush=True)
 tables=[('metrics.csv',['profile','metric','value','isExact'],metrics),('source-roles.csv',['kind','id','sourceRow','nativeID','role','weight','x0','x1','x2','x3','churnAnnotation'],roles),('feature-moments.csv',['kind','feature','featureName','unit','meanExact','varianceExact','stdApprox','rangeExact','minExact','maxExact'],mom),('covariance.csv',['profile','feature0','feature1','originalCovarianceExact','scaledCovarianceApprox'],cov),('eigenvalues.csv',['profile','component','eigenvalueApprox','varianceRatioApprox'],eig),('axes.csv',['profile','component','feature','featureName','loadingApprox'],axes),('scores.csv',['profile','role','id','sourceRow','score0','score1','score2','score3','defined'],scores),('reconstruction.csv',['profile','role','id','sourceRow','feature','actual','reconstructionApprox','residualApprox','squaredErrorApprox'],reconstruction),('loss-paths.csv',['profile','k','trainingScaledMSEApprox','outerScaledMSEApprox','omittedEigenvalueSumApprox'],paths),('feature-loss-paths.csv',['profile','k','feature','featureName','trainingOriginalMSEApprox','outerOriginalMSEApprox'],floss)]
 for name,head,rows in tables:writecsv(out/name,head,rows)
 (out/'full-study.json').write_text(json.dumps(serial(full),indent=2)+'\n',encoding='utf8');print('metrics',len(metrics),'tables',len(tables))

if __name__=='__main__':
 parser=argparse.ArgumentParser();parser.add_argument('--source-dir',default='ml10-sources');parser.add_argument('--output-dir',default='ml10-results');args=parser.parse_args();study(args.source_dir,args.output_dir)
