{
  "metrics": {
    "python": {
      "six-cards": {
        "api": "metrics",
        "variant": "six-cards",
        "language": "python",
        "title": "Six-card confusion cells at threshold0.8",
        "codeFile": "ml14-code/metrics-six-cards.py",
        "codeSHA256": "d4eaf0d4cc1707d8e498cf35e452fdb68591d59a6eb20125a72fd8648ed77198",
        "code": "#!/usr/bin/env python3\n\"\"\"ML14 standalone exact finite study, Python standard library only.\nInputs: only the three retained factual source CSVs below.\nDerived role/target/group/eligibility columns in those CSVs are NOT inputs.\nRebuilds SHA256 roles, train-only medians/cell scores, validation thresholds,\ntest curves, binary-event reliability and descriptive group ledgers.\nCosts 1/1,1/5,5/1 are hypothetical units, not measured intervention returns.\nThis is author public reproduction, not independent scientific review.\n\"\"\"\n\"\"\"Author Fraction reference, separate from product JavaScript; not independent peer.\"\"\"\nfrom fractions import Fraction as F\nfrom collections import Counter,defaultdict\ndef read(raw):\n rows=[]\n for i,r in enumerate(raw):\n  s=None if r['score']is None else F(str(r['score']));y=None if r['y']is None else F(int(r['y']))if isinstance(r['y'],bool)else F(str(r['y']));w=F(str(r.get('weight','1')));role=r.get('role','evaluation')\n  rows.append(dict(id=r['id'],index=i,score=s,y=y,w=w,role=role,group=r.get('group'),eligible=s is not None and y is not None and w>0 and role!='excluded'))\n return rows\ndef scoped(rows,role='all'):return rows if role=='all'else[r for r in rows if r['role']==role]\ndef divide(n,d):return None if not d else n/d\ndef policy(v):return v if v in ['always-negative','always-positive']else F(str(v))\ndef positive(p,s):return p=='always-positive'if isinstance(p,str)else s>=p\ndef cost(a=None):\n a={}if a is None else a;fp=F(str(a.get('falsePositive','1')));fn=F(str(a.get('falseNegative','1')));return fp,fn\ndef metrics(rows,threshold=F(1,2),cc=(F(1),F(1))):\n counts=dict(TP=F(0),FP=F(0),FN=F(0),TN=F(0));brier=F(0);pred=[]\n for r in rows:\n  if not r['eligible']:pred.append(dict(id=r['id'],index=r['index'],eligible=False,decision=None,probability=None,Brier=None));continue\n  yes=positive(threshold,r['score']);cell=('T'if yes==bool(r['y'])else'F')+('P'if yes else'N');counts[cell]+=r['w'];loss=(r['score']-r['y'])**2;brier+=r['w']*loss;pred.append(dict(id=r['id'],index=r['index'],eligible=True,decision=int(yes),probability=r['score'],Brier=loss))\n TP,FP,FN,TN=[counts[k]for k in ['TP','FP','FN','TN']];P=TP+FN;N=TN+FP;mass=P+N;PP=TP+FP;PN=TN+FN;TPR=divide(TP,P);TNR=divide(TN,N);total=FP*cc[0]+FN*cc[1]\n return dict(confusion=counts,mass=mass,positiveTargetMass=P,negativeTargetMass=N,predictedPositiveMass=PP,predictedNegativeMass=PN,prevalence=divide(P,mass),selectionRate=divide(PP,mass),accuracy=divide(TP+TN,mass),precision=divide(TP,PP),negativePredictiveValue=divide(TN,PN),TPR=TPR,FPR=divide(FP,N),TNR=TNR,FNR=divide(FN,P),F1=divide(2*TP,2*TP+FP+FN),balancedAccuracy=None if TPR is None or TNR is None else(TPR+TNR)/2,Brier=divide(brier,mass),BrierSum=brier,totalCost=total,meanCost=divide(total,mass),predictions=pred,bayesThreshold=divide(cc[0],sum(cc)))\ndef curves(rows):\n use=[r for r in rows if r['eligible']];pos=Counter();neg=Counter()\n for r in use:(pos if r['y']else neg)[r['score']]+=r['w']\n P=sum(pos.values(),F(0));N=sum(neg.values(),F(0));pairs=F(0)\n for a,wa in pos.items():\n  for b,wb in neg.items():pairs+=wa*wb*(F(1)if a>b else F(1,2)if a==b else F(0))\n thresholds=['always-negative']+sorted({r['score']for r in use},reverse=True);points=[];AP=F(0);trap=F(0);lastR=F(0);lastP=F(1)\n for i,p in enumerate(thresholds):\n  m=metrics(rows,p);points.append(dict(policy=p,TP=m['confusion']['TP'],FP=m['confusion']['FP'],FN=m['confusion']['FN'],TN=m['confusion']['TN'],TPR=m['TPR'],FPR=m['FPR'],precision=m['precision'],recall=m['TPR']))\n  if i and P:\n   R=m['TPR'];PP=m['precision'];AP+=(R-lastR)*PP;trap+=(R-lastR)*(PP+lastP)/2;lastR=R;lastP=PP\n return dict(positiveMass=P,negativeMass=N,ROC_AUC=divide(pairs,P*N),weightedConcordantPlusHalfTiedMass=pairs,averagePrecision=AP if P else None,PRTrapezoidWithInitialPrecisionOne=trap if P else None,points=points)\ndef choose(rows,a,cc):\n sr=a.get('selectionRole','validation');er=a.get('evaluationRole','test');rr=scoped(rows,sr);thresholds=[policy(t)for t in a['thresholds']]if'thresholds'in a else['always-negative']+sorted({r['score']for r in rr if r['eligible']},reverse=True)\n candidates=[]\n for i,p in enumerate(thresholds):\n  m=metrics(rr,p,cc);reasons=[]\n  if'minTPR'in a and(m['TPR']is None or m['TPR']<F(str(a['minTPR']))):reasons.append('TPR-undefined'if m['TPR']is None else'below-minTPR')\n  if'maxFPR'in a and(m['FPR']is None or m['FPR']>F(str(a['maxFPR']))):reasons.append('FPR-undefined'if m['FPR']is None else'above-maxFPR')\n  candidates.append(dict(index=i,policy=p,metrics=m,feasible=not reasons,reasons=reasons))\n eligible=[c for c in candidates if c['feasible']];best=min(eligible,key=lambda c:(c['metrics']['meanCost'],c['index']))if eligible else None\n return dict(selectedIndex=None if best is None else best['index'],selectedPolicy=None if best is None else best['policy'],candidates=candidates,selectedValidation=None if best is None else best['metrics'],evaluation=None if best is None or er=='none'else metrics(scoped(rows,er),best['policy'],cc),selectionIDs=[r['id']for r in rr if r['eligible']])\ndef calibrate(rows,ee):\n buckets=[[]for _ in range(len(ee)-1)]\n for r in rows:\n  if not r['eligible']:continue\n  j=next((i for i in range(len(ee)-1)if r['score']<ee[i+1]),len(ee)-2);buckets[j].append(r)\n mass=sum((r['w']for r in rows if r['eligible']),F(0));P=sum((r['w']*r['y']for r in rows if r['eligible']),F(0));pi=divide(P,mass);Brier=None if not mass else sum((r['w']*(r['score']-r['y'])**2 for r in rows if r['eligible']),F(0))/mass;ECE=F(0);reliability=F(0);resolution=F(0);correction=F(0);bins=[]\n for i,rr in enumerate(buckets):\n  w=sum((r['w']for r in rr),F(0));mp=None if not w else sum((r['w']*r['score']for r in rr),F(0))/w;o=None if not w else sum((r['w']*r['y']for r in rr),F(0))/w\n  variance=None if not w else sum((r['w']*(r['score']-mp)**2 for r in rr),F(0))/w\n  covariance=None if not w else sum((r['w']*(r['score']-mp)*(r['y']-o)for r in rr),F(0))/w\n  bc=None if not w else variance-2*covariance;gap=None if not w else mp-o\n  bins.append(dict(index=i,rows=len(rr),mass=w,meanPrediction=mp,eventRate=o,gap=gap,absoluteGap=None if gap is None else abs(gap),scoreVariance=variance,scoreTargetCovariance=covariance,withinBinCorrection=bc,ids=[r['id']for r in rr]))\n  if w:\n   share=w/mass;ECE+=share*abs(gap);reliability+=share*gap**2;resolution+=share*(o-pi)**2;correction+=share*bc\n uncertainty=None if pi is None else pi*(1-pi);residual=None if Brier is None else Brier-(uncertainty-resolution+reliability+correction)\n return dict(mass=mass,prevalence=pi,Brier=Brier,ECE=ECE if mass else None,reliability=reliability if mass else None,resolution=resolution if mass else None,uncertainty=uncertainty,withinBinCorrection=correction if mass else None,BrierIdentityResidual=residual,bins=bins)\ndef typed(v):return type(v).__name__,v\ndef groups(rows,p,cc):\n bins={}\n for r in rows:\n  if r['group']is not None:bins.setdefault(typed(r['group']),[]).append(r)\n gm=[dict(group=rr[0]['group'],metrics=metrics(rr,p,cc))for rr in bins.values()];overall=metrics(rows,p,cc);unknown=metrics([r for r in rows if r['group']is None],p,cc);gaps={}\n for key in ['prevalence','selectionRate','TPR','FPR','precision','accuracy','meanCost']:\n  positive=[g for g in gm if g['metrics']['mass']>0];undefined=[g['group']for g in positive if g['metrics'][key]is None];vals=[g['metrics'][key]for g in positive if g['metrics'][key]is not None]\n  gaps[key]=dict(value=None if len(positive)<2 or undefined else max(vals)-min(vals),undefinedGroups=undefined,comparedPositiveMassGroups=[g['group']for g in positive])\n return dict(overall=overall,groups=gm,unknownGroup=unknown,gaps=gaps,partitionMassResidual=overall['mass']-unknown['mass']-sum((g['metrics']['mass']for g in gm),F(0)))\ndef actual_model(M):\n raw=M['records'];cat=M['categoricalFeatures'];p=len(raw[0]['x']);train=[r for r in raw if r['role']=='train'];medians=[]\n for j in range(p):\n  if j in cat:medians.append(None);continue\n  values=sorted(F(r['x'][j])for r in train);n=len(values);medians.append(values[n//2]if n%2 else(values[n//2-1]+values[n//2])/2)\n def transform(r):return[F(v)if j in cat else F(int(F(v)>medians[j]))for j,v in enumerate(r['x'])]\n counts={}\n for r in train:\n  key=tuple(transform(r));n,s=counts.get(key,(0,0));counts[key]=(n+1,s+int(r['y']))\n probabilities={k:F(s+1,n+2)for k,(n,s)in counts.items()};fallback=F(sum(int(r['y'])for r in train)+1,len(train)+2);scored=[]\n for i,r in enumerate(raw):\n  eligible=r['role']!='excluded';z=transform(r)if eligible else None;key=None if z is None else tuple(z);score=None if not eligible else probabilities.get(key,fallback)\n  scored.append(dict(id=r['id'],index=i,role=r['role'],group=r['group'],y=None if r['y']is None else F(r['y']),score=score,w=F(1),eligible=eligible,transformedX=z,unseenCell=None if not eligible else key not in probabilities))\n return dict(medians=medians,cells=counts,probabilities=probabilities,fallback=fallback,rows=scored,trainIDs=[r['id']for r in train])\n\n\nimport csv,json,hashlib,argparse,datetime\nfrom pathlib import Path\ndef missing(v):return None if v in ['', '.',None]else v\ndef load_sources(folder):\n def read_csv(name):\n  with (folder/name).open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))\n wb=read_csv('actual64-country-four-indicators-original-2024.csv')\n codes=['NY.GDP.PCAP.KD','NY.GDP.MKTP.KD.ZG','FP.CPI.TOTL.ZG','SP.DYN.LE00.IN']\n lookup={(r['countryISO3'],r['indicatorID']):r for r in wb};country=[]\n for i,iso in enumerate(sorted({r['countryISO3']for r in wb}),1):\n  native=[lookup[iso,c]for c in codes];v=[missing(r['originalValueToken'])for r in native]\n  country.append(dict(id=iso+':2024',sourceRow=i,originalID=iso,x=v[:3],y=None if v[3]is None else str(int(F(v[3])>=80)),group=None if v[0]is None else str(int(F(v[0])>=25000)),nativeTarget=v[3],nativeSourceRows=';'.join(r['sourceRow']for r in native)))\n nls=read_csv('actual3613-NLS-original52-fields-groups-roles.csv');person=[]\n for r in nls:\n  y=missing(r['wage76']);person.append(dict(id='person:'+r['sourceRow'],sourceRow=int(r['sourceRow']),originalID=r['id'],x=[missing(r[k])for k in ['ed76','age76','nearc4']],y=None if y is None else str(int(F(y)>=500)),group=missing(r['black']),nativeTarget=y,nativeSourceRows=r['sourceRow']))\n ch=read_csv('actual3150-churn-original14-fields-groups-roles.csv');company=[]\n for r in ch:\n  company.append(dict(id='customer:'+r['sourceRow'],sourceRow=int(r['sourceRow']),originalID='',x=[missing(r[k])for k in ['Call  Failure','Complains','Subscription  Length','Seconds of Use']],y=missing(r['Churn']),group=missing(r['Tariff Plan']),nativeTarget=missing(r['Churn']),nativeSourceRows=r['sourceRow']))\n assert len(wb)==64 and len(country)==16 and len(nls)==3613 and len(ch)==3150\n assert [int(r['sourceRow'])for r in ch if r['Charge  Amount']=='10']==[474,2174,2274,2374,2674,2924,2974]\n models={}\n for kind,raw,cat,units in [('country',country,[],['constant2015USD/person','annualPercent','annualPercent']),('person',person,[2],['years','years','nativeCategory']),('company',company,[1],['count','nativeCategory','months','seconds'])]:\n  order=sorted(range(len(raw)),key=lambda i:(hashlib.sha256(('ML14-role|'+kind+'|'+raw[i]['id']).encode()).hexdigest(),i))\n  for rank,i in enumerate(order):\n   r=raw[i];r['plannedRole']='test'if rank%5==0 else'validation'if rank%5==1 else'train';r['eligible']=None not in r['x']+[r['y']];r['role']=r['plannedRole']if r['eligible']else'excluded';r['weight']='1'\n  models[kind]=dict(records=raw,categoricalFeatures=cat,featureUnits=units)\n assert sum(r['eligible']for r in person)==3017\n return models\n\ndef exact(v):return ''if v is None else str(v)\ndef approx(v):return ''if v is None else format(float(v),'.17g')\ndef scalar_fields(m,keys):\n out={}\n for k in keys:\n  out[k+'Exact']=exact(m[k]);out[k+'Approx']=approx(m[k])\n return out\nCOUNTS=['mass','positiveTargetMass','negativeTargetMass','predictedPositiveMass','predictedNegativeMass']\nRATES=['prevalence','selectionRate','accuracy','precision','negativePredictiveValue','TPR','FPR','TNR','FNR','F1','balancedAccuracy','Brier','BrierSum','totalCost','meanCost']\nSCENARIOS=[('equal',F(1),F(1)),('miss-five',F(1),F(5)),('alarm-five',F(5),F(1))]\ndef packed(v):\n if isinstance(v,F):return str(v)\n if isinstance(v,dict):return{str(k):packed(x)for k,x in v.items()}\n if isinstance(v,(tuple,list)):return[packed(x)for x in v]\n return v\ndef run_study(source,out):\n out.mkdir(parents=True,exist_ok=True);models=load_sources(source)\n tables={name:[]for name in ['predictions','lineage','fit-medians','fit-cells','validation-candidates','test-metrics','test-curves','calibration-bins','group-metrics','chart-points']}\n studies={};charts=[]\n def point(kind,chart,series,index,x,y,xunit='dimensionless',yunit='dimensionless',role='test',tag=''):\n  tables['chart-points'].append(dict(kind=kind,chart=chart,series=series,index=index,xExact=exact(x),xApprox=approx(x),yExact=exact(y),yApprox=approx(y),xUnit=xunit,yUnit=yunit,role=role,tag=tag))\n for kind,M in models.items():\n  fit=actual_model(M);rr=fit['rows'];native=M['records'];test=scoped(rr,'test');cv=curves(test);cal=calibrate(test,[F(0),F(1,5),F(2,5),F(3,5),F(4,5),F(1)]);scenarios=[]\n  for i,r in enumerate(rr):\n   n=native[i];reason=''if r['eligible']else'required-X-or-Y-missing'\n   tables['predictions'].append(dict(kind=kind,id=r['id'],sourceRow=n['sourceRow'],originalID=n['originalID'],plannedRole=n['plannedRole'],role=r['role'],group=''if r['group']is None else r['group'],eligible=int(r['eligible']),targetExact=exact(r['y']),probabilityExact=exact(r['score']),probabilityApprox=approx(r['score']),unseenCell=''if r['unseenCell']is None else int(r['unseenCell']),transformedX=''if r['transformedX']is None else'|'.join(map(str,r['transformedX'])),reason=reason))\n   tables['lineage'].append(dict(kind=kind,id=r['id'],sourceRow=n['sourceRow'],originalID=n['originalID'],nativeSourceRows=n['nativeSourceRows'],rawX='|'.join(''if x is None else x for x in n['x']),nativeTarget=''if n['nativeTarget']is None else n['nativeTarget'],derivedTarget=exact(r['y']),nativeGroup=''if n['group']is None else n['group'],plannedRole=n['plannedRole'],role=r['role'],eligible=int(r['eligible']),analyticalMass='1',reason=reason))\n  for j,v in enumerate(fit['medians']):tables['fit-medians'].append(dict(kind=kind,feature=j,categorical=int(j in M['categoricalFeatures']),fitRows=len(fit['trainIDs']),medianExact=exact(v),medianApprox=approx(v),unit=M['featureUnits'][j]))\n  for key,(mass,pos)in fit['cells'].items():tables['fit-cells'].append(dict(kind=kind,cell='|'.join(map(str,key)),trainingRows=mass,positiveRows=pos,probabilityExact=exact(fit['probabilities'][key]),probabilityApprox=approx(fit['probabilities'][key]),fallbackExact=exact(fit['fallback']),fallbackApprox=approx(fit['fallback'])))\n  for j,p in enumerate(cv['points']):\n   policy=p['policy'];tables['test-curves'].append(dict(kind=kind,point=j,policy=policy if isinstance(policy,str)else'threshold',thresholdExact=''if isinstance(policy,str)else exact(policy),thresholdApprox=''if isinstance(policy,str)else approx(policy),**scalar_fields(p,['TP','FP','FN','TN','TPR','FPR','precision','recall'])))\n   point(kind,'roc','ROC',j,p['FPR'],p['TPR']);point(kind,'pr','PR-observed',j,p['recall'],p['precision'])\n  for b in cal['bins']:\n   tables['calibration-bins'].append(dict(kind=kind,bin=b['index'],leftExact=str(F(b['index'],5)),rightExact=str(F(b['index']+1,5)),rightClosed=int(b['index']==4),rows=b['rows'],ids=';'.join(str(i)for i in b['ids']),**scalar_fields(b,['mass','meanPrediction','eventRate','gap','absoluteGap','scoreVariance','scoreTargetCovariance','withinBinCorrection'])))\n   point(kind,'reliability','Binary event rate',b['index'],b['meanPrediction'],b['eventRate'],tag='rows='+str(b['rows']))\n  for j,r in enumerate(test):\n   point(kind,'test-scores','Training-fitted probability',j,F(j+1),r['score'],'test-row position','probability',tag=r['id'])\n   point(kind,'test-scores','Observed Y',j,F(j+1),r['y'],'test-row position','binary target',tag=r['id'])\n  for name,fp,fn in SCENARIOS:\n   choice=choose(rr,{},(fp,fn));gm=groups(test,choice['selectedPolicy'],(fp,fn));scenarios.append(dict(name=name,costs=dict(falsePositive=fp,falseNegative=fn),selection=choice,groups=gm));ev=choice['evaluation']\n   for c in choice['candidates']:\n    policy=c['policy'];mm=c['metrics'];tables['validation-candidates'].append(dict(kind=kind,scenario=name,candidate=c['index'],selected=int(c['index']==choice['selectedIndex']),policy=policy if isinstance(policy,str)else'threshold',thresholdExact=''if isinstance(policy,str)else exact(policy),thresholdApprox=''if isinstance(policy,str)else approx(policy),feasible=int(c['feasible']),reasons=';'.join(c['reasons']),**{k+'Exact':str(v)for k,v in mm['confusion'].items()},**scalar_fields(mm,COUNTS+['TPR','FPR','precision','meanCost','totalCost'])))\n    point(kind,'validation-cost',name,c['index'],F(c['index']),mm['meanCost'],'candidate index','hypothetical cost units/mass','validation',tag=exact(policy))\n   mm={**ev,**ev['confusion'],**{k:cv[k]for k in ['ROC_AUC','averagePrecision','PRTrapezoidWithInitialPrecisionOne']},**{k:cal[k]for k in ['ECE','reliability','resolution','uncertainty','withinBinCorrection','BrierIdentityResidual']}}\n   for key in ['TP','FP','FN','TN']+COUNTS+RATES+['ROC_AUC','averagePrecision','PRTrapezoidWithInitialPrecisionOne','ECE','reliability','resolution','uncertainty','withinBinCorrection','BrierIdentityResidual']:\n    unit='rows'if key in ['TP','FP','FN','TN']+COUNTS else'hypothetical cost units'if key=='totalCost'else'hypothetical cost units/mass'if key=='meanCost'else'sum squared-probability loss'if key=='BrierSum'else'dimensionless'\n    tables['test-metrics'].append(dict(kind=kind,scenario=name,metric=key,valueExact=exact(mm[key]),valueApprox=approx(mm[key]),unit=unit))\n   allg=[('overall','all',gm['overall'])]+[('known',str(g['group']),g['metrics'])for g in gm['groups']]+[('unknown','',gm['unknownGroup'])]\n   for j,(typ,token,g)in enumerate(allg):\n    tables['group-metrics'].append(dict(kind=kind,scenario=name,groupType=typ,groupToken=token,retainedRows=g.get('retainedRows',sum((r['group']==token)if typ=='known'else(r['group']is None)if typ=='unknown'else True for r in test)),**{k+'Exact':str(v)for k,v in g['confusion'].items()},**scalar_fields(g,COUNTS+RATES)))\n    if typ=='known':point(kind,'group-TPR',name,j-1,F(j-1),g['TPR'],'declared group position','TPR',tag=token)\n  studies[kind]=dict(kind=kind,rows=len(native),eligibleRows=sum(r['eligible']for r in rr),trainingIDs=fit['trainIDs'],fitMedians=fit['medians'],fitCells=[dict(cell=list(k),mass=n,positive=s,probability=fit['probabilities'][k])for k,(n,s)in fit['cells'].items()],fallback=fit['fallback'],scenarios=scenarios,testCurves=cv,testCalibration=cal,rowsScored=rr)\n files=[]\n for name,rows in tables.items():\n  p=out/('computed-'+name+'.csv')\n  with p.open('w',encoding='utf8',newline='')as f:w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows)\n  files.append(dict(file=p.name,rows=len(rows),columns=len(rows[0]),bodyFields=len(rows)*len(rows[0]),sha256=hashlib.sha256(p.read_bytes()).hexdigest()))\n (out/'study.json').write_text(json.dumps(packed(studies),ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\n sourceFiles=[source/n for n in ['actual64-country-four-indicators-original-2024.csv','actual3613-NLS-original52-fields-groups-roles.csv','actual3150-churn-original14-fields-groups-roles.csv']]\n provenance=dict(chapter='ML-14',arithmetic='Python stdlib Fraction exact finite values from original decimal strings; binary64 valueApprox is display only.',inputs=[dict(file=p.name,sha256=hashlib.sha256(p.read_bytes()).hexdigest())for p in sourceFiles],priorEngineModelsScoresOrComputedFilesRead=False,roleRule=\"SHA256('ML14-role|'+kind+'|'+ID),rankmod5=0test/1validation/others train before eligibility\",costs='Hypothetical1/1,1/5,5/1; no causal intervention returns',files=files,observations={k:dict(sourceRows=v['rows'],eligibleRows=v['eligibleRows'],trainingRows=len(v['trainingIDs']))for k,v in studies.items()})\n (out/'provenance.json').write_text(json.dumps(provenance,ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\n print(json.dumps(dict(status='PASS standalone completed',files=len(files),bodyFields=sum(f['bodyFields']for f in files),observations=provenance['observations'])))\n\n# Fixed declared examples: full web budget/option validation is not reproduced.\nfrom html import escape\nimport textwrap\ndef validated_rows(raw):\n for r in raw:\n  assert F(str(r.get('weight','1')))>=0,'negative analytical mass'\n  assert r['score']is None or 0<=F(str(r['score']))<=1,'score outside zero/one'\n  assert r['y']is None or F(str(int(r['y']))if isinstance(r['y'],bool)else str(r['y']))in [0,1],'binary target required'\n return read(raw)\ndef serial(v):\n if isinstance(v,F):return dict(exactFraction=str(v),value=float(v))\n if isinstance(v,(list,tuple)):return[serial(x)for x in v]\n if isinstance(v,dict):return{k:serial(x)for k,x in v.items()}\n return v\ndef fixed_svg(path,points,title,xlabel,ylabel,legend):\n use=[p for p in points if p['xExact']!=''and p['yExact']!=''];xs=[float(F(p['xExact']))for p in use];ys=[float(F(p['yExact']))for p in use]\n xmin=min(xs,default=0);xmax=max(xs,default=1);ymin=min([0]+ys);ymax=max([0]+ys)\n if xmin==xmax:xmin-=.5;xmax+=.5\n if ymin==ymax:ymax=ymin+1\n X=lambda v:85+(float(v)-xmin)/(xmax-xmin)*480;Y=lambda v:278-(float(v)-ymin)/(ymax-ymin)*175\n s='<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"620\" height=\"360\" viewBox=\"0 0 620 360\"><rect width=\"620\" height=\"360\" fill=\"white\"/><g font-family=\"Arial, sans-serif\" font-size=\"13\" fill=\"#17324d\">'\n for i,line in enumerate(textwrap.wrap(title,width=65)):s+='<text x=\"25\" y=\"'+str(24+i*18)+'\">'+escape(line)+'</text>'\n colors=['#176b9b','#b85e18','#437e4d']\n for i,label in enumerate(legend):s+='<circle cx=\"'+str(30+i*250)+'\" cy=\"76\" r=\"4\" fill=\"'+colors[i%3]+'\"/><text x=\"'+str(42+i*250)+'\" y=\"80\">'+escape(label)+'</text>'\n s+='<path d=\"M85 98V278H575\" fill=\"none\" stroke=\"#52677d\"/><text text-anchor=\"middle\" x=\"325\" y=\"338\">'+escape(xlabel)+'</text><text text-anchor=\"middle\" transform=\"translate(21,190) rotate(-90)\">'+escape(ylabel)+'</text>'\n for i in range(5):\n  xx=xmin+(xmax-xmin)*i/4;yy=ymin+(ymax-ymin)*i/4;s+='<text text-anchor=\"middle\" x=\"'+format(X(xx),'.9g')+'\" y=\"305\">'+format(xx,'.4g')+'</text><text text-anchor=\"end\" x=\"77\" y=\"'+format(Y(yy)+4,'.9g')+'\">'+format(yy,'.4g')+'</text>'\n for p in use:s+='<circle cx=\"'+format(X(F(p['xExact'])),'.9g')+'\" cy=\"'+format(Y(F(p['yExact'])),'.9g')+'\" r=\"3\" fill=\"'+colors[p['series']%3]+'\"/>'\n path.write_text(s+'</g></svg>',encoding='utf8')\ndef fixed_run():\n ap=argparse.ArgumentParser();ap.add_argument('--out',type=Path,default=Path('results'));ap.add_argument('--data-dir',type=Path,default=Path(__file__).resolve().parent.parent/'ml14-sources');args=ap.parse_args();args.out.mkdir(parents=True,exist_ok=True)\n api=FIXED['api'];a=FIXED['args'];summary=[];points=[];xlabel='Declared index';ylabel='Value';legend=['Declared result']\n def metric(name,v,unit='dimensionless'):\n  q=None if v is None else v if isinstance(v,F)else F(v);summary.append(dict(metric=name,value='undefined'if q is None else format(float(q),'.9g'),exactValue=''if q is None else str(q),unit=unit,defined=int(q is not None)))\n def pt(i,x,y,ident='',series=0):\n  points.append(dict(series=series,index=i,xExact=''if x is None else str(F(x)),x='undefined'if x is None else format(float(x),'.9g'),yExact=''if y is None else str(F(y)),y='undefined'if y is None else format(float(y),'.9g'),id=str(ident)))\n if api=='realdata':\n  models=load_sources(args.data_dir);model=models[a['kind']];fit=actual_model(model);rr=fit['rows'];test=scoped(rr,'test');scenarios=[]\n  for name,fp,fn in SCENARIOS:\n   c=choose(rr,{},(fp,fn));scenarios.append(dict(name=name,selection=c));metric(name+'Threshold',c['selectedPolicy']);metric(name+'TestCost',c['evaluation']['meanCost'],'hypothetical cost units/mass')\n  cv=curves(test);cal=calibrate(test,[F(0),F(1,5),F(2,5),F(3,5),F(4,5),F(1)]);metric('testAUC',cv['ROC_AUC']);metric('testAP',cv['averagePrecision']);metric('testBrier',cal['Brier']);metric('eligibleRows',sum(r['eligible']for r in rr),'rows')\n  for i,r in enumerate(test):pt(i,i+1,r['score'],r['id'],0);pt(i,i+1,r['y'],r['id'],1)\n  full=dict(kind=a['kind'],fitMedians=fit['medians'],fitCells=[dict(cell=list(k),mass=n,positive=s,probability=fit['probabilities'][k])for k,(n,s)in fit['cells'].items()],rowsScored=rr,scenarios=scenarios,testCurves=cv,testCalibration=cal);xlabel='Test row, native order';ylabel='Y or probability';legend=['Training-fitted probability','Observed Y']\n else:\n  rr=validated_rows(a['rows']);role=a.get('role','all');frame=scoped(rr,role);cc=cost(a.get('costs'));t=policy(a.get('threshold','1/2'))\n  if api=='metrics':\n   full=metrics(frame,t,cc)\n   for k in ['mass','accuracy','precision','TPR','FPR','F1','Brier','meanCost']:metric(k,full[k],'mass'if k=='mass'else'hypothetical cost units/mass'if k=='meanCost'else'dimensionless')\n   metric('BayesThreshold',full['bayesThreshold'])\n   for i,k in enumerate(['TP','FP','FN','TN']):pt(i,i,full['confusion'][k],k)\n   xlabel='TP / FP / FN / TN positions';ylabel='Analytical mass'\n  elif api=='curves':\n   full=curves(frame)\n   for k in ['ROC_AUC','averagePrecision','PRTrapezoidWithInitialPrecisionOne']:metric(k,full[k])\n   for i,p in enumerate(full['points']):pt(i,p['FPR'],p['TPR'],str(p['policy']))\n   xlabel='False positive rate';ylabel='True positive rate';legend=['Observed ROC operating points']\n  elif api=='choose':\n   full=choose(rr,a,cc);metric('selectedIndex',full['selectedIndex'],'candidate index');metric('minimumCost',None if full['selectedValidation']is None else full['selectedValidation']['meanCost'],'hypothetical cost units/mass');metric('feasible',int(full['selectedIndex']is not None),'indicator')\n   for c in full['candidates']:pt(c['index'],c['index'],c['metrics']['meanCost'],str(c['policy']))\n   xlabel='Validation candidate';ylabel='Assumed cost / mass';legend=['Validation candidate costs']\n  elif api=='calibrate':\n   full=calibrate(frame,[F(str(e))for e in a.get('binEdges',['0','1/5','2/5','3/5','4/5','1'])])\n   for k in ['ECE','Brier','uncertainty','resolution','reliability','withinBinCorrection','BrierIdentityResidual']:metric(k,full[k])\n   for b in full['bins']:pt(b['index'],b['meanPrediction'],b['eventRate'],'bin:'+str(b['index']))\n   xlabel='Bin mean forecast';ylabel='Bin event rate';legend=['Binary-event reliability']\n  elif api=='groups':\n   full=groups(frame,t,cc);metric('overallTPR',full['overall']['TPR']);metric('TPRGap',full['gaps']['TPR']['value']);metric('precisionGap',full['gaps']['precision']['value']);metric('unknownMass',full['unknownGroup']['mass'],'mass');metric('partitionResidual',full['partitionMassResidual'],'mass')\n   for i,g in enumerate(full['groups']):pt(i,i,g['metrics']['TPR'],str(g['group']))\n   xlabel='Declared group position';ylabel='True positive rate';legend=['Known-group TPR']\n  else:raise ValueError('unknown fixed API')\n def csvout(name,rows):\n  with(args.out/name).open('w',encoding='utf8',newline='')as f:w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows)\n csvout('summary.csv',summary);csvout('plot-points.csv',points);fixed_svg(args.out/'plot.svg',points,FIXED['title'],xlabel,ylabel,legend)\n (args.out/'full.json').write_text(json.dumps(dict(api=api,variant=FIXED['variant'],input=FIXED['args'],arithmetic='Python standard-library Fraction, declared fixed example; full web validator/budgets not reproduced',result=serial(full)),ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\n print(json.dumps(dict(api=api,variant=FIXED['variant'],summaryMetrics=len(summary),plotSlots=len(points))))\n\nFIXED={'api': 'metrics', 'variant': 'six-cards', 'args': {'rows': [{'id': 'a', 'score': '.9', 'y': 1, 'group': 'A'}, {'id': 'b', 'score': '.8', 'y': 1, 'group': 'A'}, {'id': 'c', 'score': '.8', 'y': 0, 'group': 'A'}, {'id': 'd', 'score': '.6', 'y': 0, 'group': 'B'}, {'id': 'e', 'score': '.4', 'y': 1, 'group': 'B'}, {'id': 'f', 'score': '.1', 'y': 0, 'group': 'B'}], 'threshold': '.8'}, 'title': 'Six-card confusion cells at threshold0.8'}\nif __name__=='__main__':fixed_run()\n",
        "codeText": "#!/usr/bin/env python3\n\"\"\"ML14 standalone exact finite study, Python standard library only.\nInputs: only the three retained factual source CSVs below.\nDerived role/target/group/eligibility columns in those CSVs are NOT inputs.\nRebuilds SHA256 roles, train-only medians/cell scores, validation thresholds,\ntest curves, binary-event reliability and descriptive group ledgers.\nCosts 1/1,1/5,5/1 are hypothetical units, not measured intervention returns.\nThis is author public reproduction, not independent scientific review.\n\"\"\"\n\"\"\"Author Fraction reference, separate from product JavaScript; not independent peer.\"\"\"\nfrom fractions import Fraction as F\nfrom collections import Counter,defaultdict\ndef read(raw):\n rows=[]\n for i,r in enumerate(raw):\n  s=None if r['score']is None else F(str(r['score']));y=None if r['y']is None else F(int(r['y']))if isinstance(r['y'],bool)else F(str(r['y']));w=F(str(r.get('weight','1')));role=r.get('role','evaluation')\n  rows.append(dict(id=r['id'],index=i,score=s,y=y,w=w,role=role,group=r.get('group'),eligible=s is not None and y is not None and w>0 and role!='excluded'))\n return rows\ndef scoped(rows,role='all'):return rows if role=='all'else[r for r in rows if r['role']==role]\ndef divide(n,d):return None if not d else n/d\ndef policy(v):return v if v in ['always-negative','always-positive']else F(str(v))\ndef positive(p,s):return p=='always-positive'if isinstance(p,str)else s>=p\ndef cost(a=None):\n a={}if a is None else a;fp=F(str(a.get('falsePositive','1')));fn=F(str(a.get('falseNegative','1')));return fp,fn\ndef metrics(rows,threshold=F(1,2),cc=(F(1),F(1))):\n counts=dict(TP=F(0),FP=F(0),FN=F(0),TN=F(0));brier=F(0);pred=[]\n for r in rows:\n  if not r['eligible']:pred.append(dict(id=r['id'],index=r['index'],eligible=False,decision=None,probability=None,Brier=None));continue\n  yes=positive(threshold,r['score']);cell=('T'if yes==bool(r['y'])else'F')+('P'if yes else'N');counts[cell]+=r['w'];loss=(r['score']-r['y'])**2;brier+=r['w']*loss;pred.append(dict(id=r['id'],index=r['index'],eligible=True,decision=int(yes),probability=r['score'],Brier=loss))\n TP,FP,FN,TN=[counts[k]for k in ['TP','FP','FN','TN']];P=TP+FN;N=TN+FP;mass=P+N;PP=TP+FP;PN=TN+FN;TPR=divide(TP,P);TNR=divide(TN,N);total=FP*cc[0]+FN*cc[1]\n return dict(confusion=counts,mass=mass,positiveTargetMass=P,negativeTargetMass=N,predictedPositiveMass=PP,predictedNegativeMass=PN,prevalence=divide(P,mass),selectionRate=divide(PP,mass),accuracy=divide(TP+TN,mass),precision=divide(TP,PP),negativePredictiveValue=divide(TN,PN),TPR=TPR,FPR=divide(FP,N),TNR=TNR,FNR=divide(FN,P),F1=divide(2*TP,2*TP+FP+FN),balancedAccuracy=None if TPR is None or TNR is None else(TPR+TNR)/2,Brier=divide(brier,mass),BrierSum=brier,totalCost=total,meanCost=divide(total,mass),predictions=pred,bayesThreshold=divide(cc[0],sum(cc)))\ndef curves(rows):\n use=[r for r in rows if r['eligible']];pos=Counter();neg=Counter()\n for r in use:(pos if r['y']else neg)[r['score']]+=r['w']\n P=sum(pos.values(),F(0));N=sum(neg.values(),F(0));pairs=F(0)\n for a,wa in pos.items():\n  for b,wb in neg.items():pairs+=wa*wb*(F(1)if a>b else F(1,2)if a==b else F(0))\n thresholds=['always-negative']+sorted({r['score']for r in use},reverse=True);points=[];AP=F(0);trap=F(0);lastR=F(0);lastP=F(1)\n for i,p in enumerate(thresholds):\n  m=metrics(rows,p);points.append(dict(policy=p,TP=m['confusion']['TP'],FP=m['confusion']['FP'],FN=m['confusion']['FN'],TN=m['confusion']['TN'],TPR=m['TPR'],FPR=m['FPR'],precision=m['precision'],recall=m['TPR']))\n  if i and P:\n   R=m['TPR'];PP=m['precision'];AP+=(R-lastR)*PP;trap+=(R-lastR)*(PP+lastP)/2;lastR=R;lastP=PP\n return dict(positiveMass=P,negativeMass=N,ROC_AUC=divide(pairs,P*N),weightedConcordantPlusHalfTiedMass=pairs,averagePrecision=AP if P else None,PRTrapezoidWithInitialPrecisionOne=trap if P else None,points=points)\ndef choose(rows,a,cc):\n sr=a.get('selectionRole','validation');er=a.get('evaluationRole','test');rr=scoped(rows,sr);thresholds=[policy(t)for t in a['thresholds']]if'thresholds'in a else['always-negative']+sorted({r['score']for r in rr if r['eligible']},reverse=True)\n candidates=[]\n for i,p in enumerate(thresholds):\n  m=metrics(rr,p,cc);reasons=[]\n  if'minTPR'in a and(m['TPR']is None or m['TPR']<F(str(a['minTPR']))):reasons.append('TPR-undefined'if m['TPR']is None else'below-minTPR')\n  if'maxFPR'in a and(m['FPR']is None or m['FPR']>F(str(a['maxFPR']))):reasons.append('FPR-undefined'if m['FPR']is None else'above-maxFPR')\n  candidates.append(dict(index=i,policy=p,metrics=m,feasible=not reasons,reasons=reasons))\n eligible=[c for c in candidates if c['feasible']];best=min(eligible,key=lambda c:(c['metrics']['meanCost'],c['index']))if eligible else None\n return dict(selectedIndex=None if best is None else best['index'],selectedPolicy=None if best is None else best['policy'],candidates=candidates,selectedValidation=None if best is None else best['metrics'],evaluation=None if best is None or er=='none'else metrics(scoped(rows,er),best['policy'],cc),selectionIDs=[r['id']for r in rr if r['eligible']])\ndef calibrate(rows,ee):\n buckets=[[]for _ in range(len(ee)-1)]\n for r in rows:\n  if not r['eligible']:continue\n  j=next((i for i in range(len(ee)-1)if r['score']<ee[i+1]),len(ee)-2);buckets[j].append(r)\n mass=sum((r['w']for r in rows if r['eligible']),F(0));P=sum((r['w']*r['y']for r in rows if r['eligible']),F(0));pi=divide(P,mass);Brier=None if not mass else sum((r['w']*(r['score']-r['y'])**2 for r in rows if r['eligible']),F(0))/mass;ECE=F(0);reliability=F(0);resolution=F(0);correction=F(0);bins=[]\n for i,rr in enumerate(buckets):\n  w=sum((r['w']for r in rr),F(0));mp=None if not w else sum((r['w']*r['score']for r in rr),F(0))/w;o=None if not w else sum((r['w']*r['y']for r in rr),F(0))/w\n  variance=None if not w else sum((r['w']*(r['score']-mp)**2 for r in rr),F(0))/w\n  covariance=None if not w else sum((r['w']*(r['score']-mp)*(r['y']-o)for r in rr),F(0))/w\n  bc=None if not w else variance-2*covariance;gap=None if not w else mp-o\n  bins.append(dict(index=i,rows=len(rr),mass=w,meanPrediction=mp,eventRate=o,gap=gap,absoluteGap=None if gap is None else abs(gap),scoreVariance=variance,scoreTargetCovariance=covariance,withinBinCorrection=bc,ids=[r['id']for r in rr]))\n  if w:\n   share=w/mass;ECE+=share*abs(gap);reliability+=share*gap**2;resolution+=share*(o-pi)**2;correction+=share*bc\n uncertainty=None if pi is None else pi*(1-pi);residual=None if Brier is None else Brier-(uncertainty-resolution+reliability+correction)\n return dict(mass=mass,prevalence=pi,Brier=Brier,ECE=ECE if mass else None,reliability=reliability if mass else None,resolution=resolution if mass else None,uncertainty=uncertainty,withinBinCorrection=correction if mass else None,BrierIdentityResidual=residual,bins=bins)\ndef typed(v):return type(v).__name__,v\ndef groups(rows,p,cc):\n bins={}\n for r in rows:\n  if r['group']is not None:bins.setdefault(typed(r['group']),[]).append(r)\n gm=[dict(group=rr[0]['group'],metrics=metrics(rr,p,cc))for rr in bins.values()];overall=metrics(rows,p,cc);unknown=metrics([r for r in rows if r['group']is None],p,cc);gaps={}\n for key in ['prevalence','selectionRate','TPR','FPR','precision','accuracy','meanCost']:\n  positive=[g for g in gm if g['metrics']['mass']>0];undefined=[g['group']for g in positive if g['metrics'][key]is None];vals=[g['metrics'][key]for g in positive if g['metrics'][key]is not None]\n  gaps[key]=dict(value=None if len(positive)<2 or undefined else max(vals)-min(vals),undefinedGroups=undefined,comparedPositiveMassGroups=[g['group']for g in positive])\n return dict(overall=overall,groups=gm,unknownGroup=unknown,gaps=gaps,partitionMassResidual=overall['mass']-unknown['mass']-sum((g['metrics']['mass']for g in gm),F(0)))\ndef actual_model(M):\n raw=M['records'];cat=M['categoricalFeatures'];p=len(raw[0]['x']);train=[r for r in raw if r['role']=='train'];medians=[]\n for j in range(p):\n  if j in cat:medians.append(None);continue\n  values=sorted(F(r['x'][j])for r in train);n=len(values);medians.append(values[n//2]if n%2 else(values[n//2-1]+values[n//2])/2)\n def transform(r):return[F(v)if j in cat else F(int(F(v)>medians[j]))for j,v in enumerate(r['x'])]\n counts={}\n for r in train:\n  key=tuple(transform(r));n,s=counts.get(key,(0,0));counts[key]=(n+1,s+int(r['y']))\n probabilities={k:F(s+1,n+2)for k,(n,s)in counts.items()};fallback=F(sum(int(r['y'])for r in train)+1,len(train)+2);scored=[]\n for i,r in enumerate(raw):\n  eligible=r['role']!='excluded';z=transform(r)if eligible else None;key=None if z is None else tuple(z);score=None if not eligible else probabilities.get(key,fallback)\n  scored.append(dict(id=r['id'],index=i,role=r['role'],group=r['group'],y=None if r['y']is None else F(r['y']),score=score,w=F(1),eligible=eligible,transformedX=z,unseenCell=None if not eligible else key not in probabilities))\n return dict(medians=medians,cells=counts,probabilities=probabilities,fallback=fallback,rows=scored,trainIDs=[r['id']for r in train])\n\n\nimport csv,json,hashlib,argparse,datetime\nfrom pathlib import Path\ndef missing(v):return None if v in ['', '.',None]else v\ndef load_sources(folder):\n def read_csv(name):\n  with (folder/name).open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))\n wb=read_csv('actual64-country-four-indicators-original-2024.csv')\n codes=['NY.GDP.PCAP.KD','NY.GDP.MKTP.KD.ZG','FP.CPI.TOTL.ZG','SP.DYN.LE00.IN']\n lookup={(r['countryISO3'],r['indicatorID']):r for r in wb};country=[]\n for i,iso in enumerate(sorted({r['countryISO3']for r in wb}),1):\n  native=[lookup[iso,c]for c in codes];v=[missing(r['originalValueToken'])for r in native]\n  country.append(dict(id=iso+':2024',sourceRow=i,originalID=iso,x=v[:3],y=None if v[3]is None else str(int(F(v[3])>=80)),group=None if v[0]is None else str(int(F(v[0])>=25000)),nativeTarget=v[3],nativeSourceRows=';'.join(r['sourceRow']for r in native)))\n nls=read_csv('actual3613-NLS-original52-fields-groups-roles.csv');person=[]\n for r in nls:\n  y=missing(r['wage76']);person.append(dict(id='person:'+r['sourceRow'],sourceRow=int(r['sourceRow']),originalID=r['id'],x=[missing(r[k])for k in ['ed76','age76','nearc4']],y=None if y is None else str(int(F(y)>=500)),group=missing(r['black']),nativeTarget=y,nativeSourceRows=r['sourceRow']))\n ch=read_csv('actual3150-churn-original14-fields-groups-roles.csv');company=[]\n for r in ch:\n  company.append(dict(id='customer:'+r['sourceRow'],sourceRow=int(r['sourceRow']),originalID='',x=[missing(r[k])for k in ['Call  Failure','Complains','Subscription  Length','Seconds of Use']],y=missing(r['Churn']),group=missing(r['Tariff Plan']),nativeTarget=missing(r['Churn']),nativeSourceRows=r['sourceRow']))\n assert len(wb)==64 and len(country)==16 and len(nls)==3613 and len(ch)==3150\n assert [int(r['sourceRow'])for r in ch if r['Charge  Amount']=='10']==[474,2174,2274,2374,2674,2924,2974]\n models={}\n for kind,raw,cat,units in [('country',country,[],['constant2015USD/person','annualPercent','annualPercent']),('person',person,[2],['years','years','nativeCategory']),('company',company,[1],['count','nativeCategory','months','seconds'])]:\n  order=sorted(range(len(raw)),key=lambda i:(hashlib.sha256(('ML14-role|'+kind+'|'+raw[i]['id']).encode()).hexdigest(),i))\n  for rank,i in enumerate(order):\n   r=raw[i];r['plannedRole']='test'if rank%5==0 else'validation'if rank%5==1 else'train';r['eligible']=None not in r['x']+[r['y']];r['role']=r['plannedRole']if r['eligible']else'excluded';r['weight']='1'\n  models[kind]=dict(records=raw,categoricalFeatures=cat,featureUnits=units)\n assert sum(r['eligible']for r in person)==3017\n return models\n\ndef exact(v):return ''if v is None else str(v)\ndef approx(v):return ''if v is None else format(float(v),'.17g')\ndef scalar_fields(m,keys):\n out={}\n for k in keys:\n  out[k+'Exact']=exact(m[k]);out[k+'Approx']=approx(m[k])\n return out\nCOUNTS=['mass','positiveTargetMass','negativeTargetMass','predictedPositiveMass','predictedNegativeMass']\nRATES=['prevalence','selectionRate','accuracy','precision','negativePredictiveValue','TPR','FPR','TNR','FNR','F1','balancedAccuracy','Brier','BrierSum','totalCost','meanCost']\nSCENARIOS=[('equal',F(1),F(1)),('miss-five',F(1),F(5)),('alarm-five',F(5),F(1))]\ndef packed(v):\n if isinstance(v,F):return str(v)\n if isinstance(v,dict):return{str(k):packed(x)for k,x in v.items()}\n if isinstance(v,(tuple,list)):return[packed(x)for x in v]\n return v\ndef run_study(source,out):\n out.mkdir(parents=True,exist_ok=True);models=load_sources(source)\n tables={name:[]for name in ['predictions','lineage','fit-medians','fit-cells','validation-candidates','test-metrics','test-curves','calibration-bins','group-metrics','chart-points']}\n studies={};charts=[]\n def point(kind,chart,series,index,x,y,xunit='dimensionless',yunit='dimensionless',role='test',tag=''):\n  tables['chart-points'].append(dict(kind=kind,chart=chart,series=series,index=index,xExact=exact(x),xApprox=approx(x),yExact=exact(y),yApprox=approx(y),xUnit=xunit,yUnit=yunit,role=role,tag=tag))\n for kind,M in models.items():\n  fit=actual_model(M);rr=fit['rows'];native=M['records'];test=scoped(rr,'test');cv=curves(test);cal=calibrate(test,[F(0),F(1,5),F(2,5),F(3,5),F(4,5),F(1)]);scenarios=[]\n  for i,r in enumerate(rr):\n   n=native[i];reason=''if r['eligible']else'required-X-or-Y-missing'\n   tables['predictions'].append(dict(kind=kind,id=r['id'],sourceRow=n['sourceRow'],originalID=n['originalID'],plannedRole=n['plannedRole'],role=r['role'],group=''if r['group']is None else r['group'],eligible=int(r['eligible']),targetExact=exact(r['y']),probabilityExact=exact(r['score']),probabilityApprox=approx(r['score']),unseenCell=''if r['unseenCell']is None else int(r['unseenCell']),transformedX=''if r['transformedX']is None else'|'.join(map(str,r['transformedX'])),reason=reason))\n   tables['lineage'].append(dict(kind=kind,id=r['id'],sourceRow=n['sourceRow'],originalID=n['originalID'],nativeSourceRows=n['nativeSourceRows'],rawX='|'.join(''if x is None else x for x in n['x']),nativeTarget=''if n['nativeTarget']is None else n['nativeTarget'],derivedTarget=exact(r['y']),nativeGroup=''if n['group']is None else n['group'],plannedRole=n['plannedRole'],role=r['role'],eligible=int(r['eligible']),analyticalMass='1',reason=reason))\n  for j,v in enumerate(fit['medians']):tables['fit-medians'].append(dict(kind=kind,feature=j,categorical=int(j in M['categoricalFeatures']),fitRows=len(fit['trainIDs']),medianExact=exact(v),medianApprox=approx(v),unit=M['featureUnits'][j]))\n  for key,(mass,pos)in fit['cells'].items():tables['fit-cells'].append(dict(kind=kind,cell='|'.join(map(str,key)),trainingRows=mass,positiveRows=pos,probabilityExact=exact(fit['probabilities'][key]),probabilityApprox=approx(fit['probabilities'][key]),fallbackExact=exact(fit['fallback']),fallbackApprox=approx(fit['fallback'])))\n  for j,p in enumerate(cv['points']):\n   policy=p['policy'];tables['test-curves'].append(dict(kind=kind,point=j,policy=policy if isinstance(policy,str)else'threshold',thresholdExact=''if isinstance(policy,str)else exact(policy),thresholdApprox=''if isinstance(policy,str)else approx(policy),**scalar_fields(p,['TP','FP','FN','TN','TPR','FPR','precision','recall'])))\n   point(kind,'roc','ROC',j,p['FPR'],p['TPR']);point(kind,'pr','PR-observed',j,p['recall'],p['precision'])\n  for b in cal['bins']:\n   tables['calibration-bins'].append(dict(kind=kind,bin=b['index'],leftExact=str(F(b['index'],5)),rightExact=str(F(b['index']+1,5)),rightClosed=int(b['index']==4),rows=b['rows'],ids=';'.join(str(i)for i in b['ids']),**scalar_fields(b,['mass','meanPrediction','eventRate','gap','absoluteGap','scoreVariance','scoreTargetCovariance','withinBinCorrection'])))\n   point(kind,'reliability','Binary event rate',b['index'],b['meanPrediction'],b['eventRate'],tag='rows='+str(b['rows']))\n  for j,r in enumerate(test):\n   point(kind,'test-scores','Training-fitted probability',j,F(j+1),r['score'],'test-row position','probability',tag=r['id'])\n   point(kind,'test-scores','Observed Y',j,F(j+1),r['y'],'test-row position','binary target',tag=r['id'])\n  for name,fp,fn in SCENARIOS:\n   choice=choose(rr,{},(fp,fn));gm=groups(test,choice['selectedPolicy'],(fp,fn));scenarios.append(dict(name=name,costs=dict(falsePositive=fp,falseNegative=fn),selection=choice,groups=gm));ev=choice['evaluation']\n   for c in choice['candidates']:\n    policy=c['policy'];mm=c['metrics'];tables['validation-candidates'].append(dict(kind=kind,scenario=name,candidate=c['index'],selected=int(c['index']==choice['selectedIndex']),policy=policy if isinstance(policy,str)else'threshold',thresholdExact=''if isinstance(policy,str)else exact(policy),thresholdApprox=''if isinstance(policy,str)else approx(policy),feasible=int(c['feasible']),reasons=';'.join(c['reasons']),**{k+'Exact':str(v)for k,v in mm['confusion'].items()},**scalar_fields(mm,COUNTS+['TPR','FPR','precision','meanCost','totalCost'])))\n    point(kind,'validation-cost',name,c['index'],F(c['index']),mm['meanCost'],'candidate index','hypothetical cost units/mass','validation',tag=exact(policy))\n   mm={**ev,**ev['confusion'],**{k:cv[k]for k in ['ROC_AUC','averagePrecision','PRTrapezoidWithInitialPrecisionOne']},**{k:cal[k]for k in ['ECE','reliability','resolution','uncertainty','withinBinCorrection','BrierIdentityResidual']}}\n   for key in ['TP','FP','FN','TN']+COUNTS+RATES+['ROC_AUC','averagePrecision','PRTrapezoidWithInitialPrecisionOne','ECE','reliability','resolution','uncertainty','withinBinCorrection','BrierIdentityResidual']:\n    unit='rows'if key in ['TP','FP','FN','TN']+COUNTS else'hypothetical cost units'if key=='totalCost'else'hypothetical cost units/mass'if key=='meanCost'else'sum squared-probability loss'if key=='BrierSum'else'dimensionless'\n    tables['test-metrics'].append(dict(kind=kind,scenario=name,metric=key,valueExact=exact(mm[key]),valueApprox=approx(mm[key]),unit=unit))\n   allg=[('overall','all',gm['overall'])]+[('known',str(g['group']),g['metrics'])for g in gm['groups']]+[('unknown','',gm['unknownGroup'])]\n   for j,(typ,token,g)in enumerate(allg):\n    tables['group-metrics'].append(dict(kind=kind,scenario=name,groupType=typ,groupToken=token,retainedRows=g.get('retainedRows',sum((r['group']==token)if typ=='known'else(r['group']is None)if typ=='unknown'else True for r in test)),**{k+'Exact':str(v)for k,v in g['confusion'].items()},**scalar_fields(g,COUNTS+RATES)))\n    if typ=='known':point(kind,'group-TPR',name,j-1,F(j-1),g['TPR'],'declared group position','TPR',tag=token)\n  studies[kind]=dict(kind=kind,rows=len(native),eligibleRows=sum(r['eligible']for r in rr),trainingIDs=fit['trainIDs'],fitMedians=fit['medians'],fitCells=[dict(cell=list(k),mass=n,positive=s,probability=fit['probabilities'][k])for k,(n,s)in fit['cells'].items()],fallback=fit['fallback'],scenarios=scenarios,testCurves=cv,testCalibration=cal,rowsScored=rr)\n files=[]\n for name,rows in tables.items():\n  p=out/('computed-'+name+'.csv')\n  with p.open('w',encoding='utf8',newline='')as f:w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows)\n  files.append(dict(file=p.name,rows=len(rows),columns=len(rows[0]),bodyFields=len(rows)*len(rows[0]),sha256=hashlib.sha256(p.read_bytes()).hexdigest()))\n (out/'study.json').write_text(json.dumps(packed(studies),ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\n sourceFiles=[source/n for n in ['actual64-country-four-indicators-original-2024.csv','actual3613-NLS-original52-fields-groups-roles.csv','actual3150-churn-original14-fields-groups-roles.csv']]\n provenance=dict(chapter='ML-14',arithmetic='Python stdlib Fraction exact finite values from original decimal strings; binary64 valueApprox is display only.',inputs=[dict(file=p.name,sha256=hashlib.sha256(p.read_bytes()).hexdigest())for p in sourceFiles],priorEngineModelsScoresOrComputedFilesRead=False,roleRule=\"SHA256('ML14-role|'+kind+'|'+ID),rankmod5=0test/1validation/others train before eligibility\",costs='Hypothetical1/1,1/5,5/1; no causal intervention returns',files=files,observations={k:dict(sourceRows=v['rows'],eligibleRows=v['eligibleRows'],trainingRows=len(v['trainingIDs']))for k,v in studies.items()})\n (out/'provenance.json').write_text(json.dumps(provenance,ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\n print(json.dumps(dict(status='PASS standalone completed',files=len(files),bodyFields=sum(f['bodyFields']for f in files),observations=provenance['observations'])))\n\n# Fixed declared examples: full web budget/option validation is not reproduced.\nfrom html import escape\nimport textwrap\ndef validated_rows(raw):\n for r in raw:\n  assert F(str(r.get('weight','1')))>=0,'negative analytical mass'\n  assert r['score']is None or 0<=F(str(r['score']))<=1,'score outside zero/one'\n  assert r['y']is None or F(str(int(r['y']))if isinstance(r['y'],bool)else str(r['y']))in [0,1],'binary target required'\n return read(raw)\ndef serial(v):\n if isinstance(v,F):return dict(exactFraction=str(v),value=float(v))\n if isinstance(v,(list,tuple)):return[serial(x)for x in v]\n if isinstance(v,dict):return{k:serial(x)for k,x in v.items()}\n return v\ndef fixed_svg(path,points,title,xlabel,ylabel,legend):\n use=[p for p in points if p['xExact']!=''and p['yExact']!=''];xs=[float(F(p['xExact']))for p in use];ys=[float(F(p['yExact']))for p in use]\n xmin=min(xs,default=0);xmax=max(xs,default=1);ymin=min([0]+ys);ymax=max([0]+ys)\n if xmin==xmax:xmin-=.5;xmax+=.5\n if ymin==ymax:ymax=ymin+1\n X=lambda v:85+(float(v)-xmin)/(xmax-xmin)*480;Y=lambda v:278-(float(v)-ymin)/(ymax-ymin)*175\n s='<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"620\" height=\"360\" viewBox=\"0 0 620 360\"><rect width=\"620\" height=\"360\" fill=\"white\"/><g font-family=\"Arial, sans-serif\" font-size=\"13\" fill=\"#17324d\">'\n for i,line in enumerate(textwrap.wrap(title,width=65)):s+='<text x=\"25\" y=\"'+str(24+i*18)+'\">'+escape(line)+'</text>'\n colors=['#176b9b','#b85e18','#437e4d']\n for i,label in enumerate(legend):s+='<circle cx=\"'+str(30+i*250)+'\" cy=\"76\" r=\"4\" fill=\"'+colors[i%3]+'\"/><text x=\"'+str(42+i*250)+'\" y=\"80\">'+escape(label)+'</text>'\n s+='<path d=\"M85 98V278H575\" fill=\"none\" stroke=\"#52677d\"/><text text-anchor=\"middle\" x=\"325\" y=\"338\">'+escape(xlabel)+'</text><text text-anchor=\"middle\" transform=\"translate(21,190) rotate(-90)\">'+escape(ylabel)+'</text>'\n for i in range(5):\n  xx=xmin+(xmax-xmin)*i/4;yy=ymin+(ymax-ymin)*i/4;s+='<text text-anchor=\"middle\" x=\"'+format(X(xx),'.9g')+'\" y=\"305\">'+format(xx,'.4g')+'</text><text text-anchor=\"end\" x=\"77\" y=\"'+format(Y(yy)+4,'.9g')+'\">'+format(yy,'.4g')+'</text>'\n for p in use:s+='<circle cx=\"'+format(X(F(p['xExact'])),'.9g')+'\" cy=\"'+format(Y(F(p['yExact'])),'.9g')+'\" r=\"3\" fill=\"'+colors[p['series']%3]+'\"/>'\n path.write_text(s+'</g></svg>',encoding='utf8')\ndef fixed_run():\n ap=argparse.ArgumentParser();ap.add_argument('--out',type=Path,default=Path('results'));ap.add_argument('--data-dir',type=Path,default=Path(__file__).resolve().parent.parent/'ml14-sources');args=ap.parse_args();args.out.mkdir(parents=True,exist_ok=True)\n api=FIXED['api'];a=FIXED['args'];summary=[];points=[];xlabel='Declared index';ylabel='Value';legend=['Declared result']\n def metric(name,v,unit='dimensionless'):\n  q=None if v is None else v if isinstance(v,F)else F(v);summary.append(dict(metric=name,value='undefined'if q is None else format(float(q),'.9g'),exactValue=''if q is None else str(q),unit=unit,defined=int(q is not None)))\n def pt(i,x,y,ident='',series=0):\n  points.append(dict(series=series,index=i,xExact=''if x is None else str(F(x)),x='undefined'if x is None else format(float(x),'.9g'),yExact=''if y is None else str(F(y)),y='undefined'if y is None else format(float(y),'.9g'),id=str(ident)))\n if api=='realdata':\n  models=load_sources(args.data_dir);model=models[a['kind']];fit=actual_model(model);rr=fit['rows'];test=scoped(rr,'test');scenarios=[]\n  for name,fp,fn in SCENARIOS:\n   c=choose(rr,{},(fp,fn));scenarios.append(dict(name=name,selection=c));metric(name+'Threshold',c['selectedPolicy']);metric(name+'TestCost',c['evaluation']['meanCost'],'hypothetical cost units/mass')\n  cv=curves(test);cal=calibrate(test,[F(0),F(1,5),F(2,5),F(3,5),F(4,5),F(1)]);metric('testAUC',cv['ROC_AUC']);metric('testAP',cv['averagePrecision']);metric('testBrier',cal['Brier']);metric('eligibleRows',sum(r['eligible']for r in rr),'rows')\n  for i,r in enumerate(test):pt(i,i+1,r['score'],r['id'],0);pt(i,i+1,r['y'],r['id'],1)\n  full=dict(kind=a['kind'],fitMedians=fit['medians'],fitCells=[dict(cell=list(k),mass=n,positive=s,probability=fit['probabilities'][k])for k,(n,s)in fit['cells'].items()],rowsScored=rr,scenarios=scenarios,testCurves=cv,testCalibration=cal);xlabel='Test row, native order';ylabel='Y or probability';legend=['Training-fitted probability','Observed Y']\n else:\n  rr=validated_rows(a['rows']);role=a.get('role','all');frame=scoped(rr,role);cc=cost(a.get('costs'));t=policy(a.get('threshold','1/2'))\n  if api=='metrics':\n   full=metrics(frame,t,cc)\n   for k in ['mass','accuracy','precision','TPR','FPR','F1','Brier','meanCost']:metric(k,full[k],'mass'if k=='mass'else'hypothetical cost units/mass'if k=='meanCost'else'dimensionless')\n   metric('BayesThreshold',full['bayesThreshold'])\n   for i,k in enumerate(['TP','FP','FN','TN']):pt(i,i,full['confusion'][k],k)\n   xlabel='TP / FP / FN / TN positions';ylabel='Analytical mass'\n  elif api=='curves':\n   full=curves(frame)\n   for k in ['ROC_AUC','averagePrecision','PRTrapezoidWithInitialPrecisionOne']:metric(k,full[k])\n   for i,p in enumerate(full['points']):pt(i,p['FPR'],p['TPR'],str(p['policy']))\n   xlabel='False positive rate';ylabel='True positive rate';legend=['Observed ROC operating points']\n  elif api=='choose':\n   full=choose(rr,a,cc);metric('selectedIndex',full['selectedIndex'],'candidate index');metric('minimumCost',None if full['selectedValidation']is None else full['selectedValidation']['meanCost'],'hypothetical cost units/mass');metric('feasible',int(full['selectedIndex']is not None),'indicator')\n   for c in full['candidates']:pt(c['index'],c['index'],c['metrics']['meanCost'],str(c['policy']))\n   xlabel='Validation candidate';ylabel='Assumed cost / mass';legend=['Validation candidate costs']\n  elif api=='calibrate':\n   full=calibrate(frame,[F(str(e))for e in a.get('binEdges',['0','1/5','2/5','3/5','4/5','1'])])\n   for k in ['ECE','Brier','uncertainty','resolution','reliability','withinBinCorrection','BrierIdentityResidual']:metric(k,full[k])\n   for b in full['bins']:pt(b['index'],b['meanPrediction'],b['eventRate'],'bin:'+str(b['index']))\n   xlabel='Bin mean forecast';ylabel='Bin event rate';legend=['Binary-event reliability']\n  elif api=='groups':\n   full=groups(frame,t,cc);metric('overallTPR',full['overall']['TPR']);metric('TPRGap',full['gaps']['TPR']['value']);metric('precisionGap',full['gaps']['precision']['value']);metric('unknownMass',full['unknownGroup']['mass'],'mass');metric('partitionResidual',full['partitionMassResidual'],'mass')\n   for i,g in enumerate(full['groups']):pt(i,i,g['metrics']['TPR'],str(g['group']))\n   xlabel='Declared group position';ylabel='True positive rate';legend=['Known-group TPR']\n  else:raise ValueError('unknown fixed API')\n def csvout(name,rows):\n  with(args.out/name).open('w',encoding='utf8',newline='')as f:w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows)\n csvout('summary.csv',summary);csvout('plot-points.csv',points);fixed_svg(args.out/'plot.svg',points,FIXED['title'],xlabel,ylabel,legend)\n (args.out/'full.json').write_text(json.dumps(dict(api=api,variant=FIXED['variant'],input=FIXED['args'],arithmetic='Python standard-library Fraction, declared fixed example; full web validator/budgets not reproduced',result=serial(full)),ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\n print(json.dumps(dict(api=api,variant=FIXED['variant'],summaryMetrics=len(summary),plotSlots=len(points))))\n\nFIXED={'api': 'metrics', 'variant': 'six-cards', 'args': {'rows': [{'id': 'a', 'score': '.9', 'y': 1, 'group': 'A'}, {'id': 'b', 'score': '.8', 'y': 1, 'group': 'A'}, {'id': 'c', 'score': '.8', 'y': 0, 'group': 'A'}, {'id': 'd', 'score': '.6', 'y': 0, 'group': 'B'}, {'id': 'e', 'score': '.4', 'y': 1, 'group': 'B'}, {'id': 'f', 'score': '.1', 'y': 0, 'group': 'B'}], 'threshold': '.8'}, 'title': 'Six-card confusion cells at threshold0.8'}\nif __name__=='__main__':fixed_run()\n",
        "input": {
          "rows": [
            {
              "id": "a",
              "score": ".9",
              "y": 1,
              "group": "A"
            },
            {
              "id": "b",
              "score": ".8",
              "y": 1,
              "group": "A"
            },
            {
              "id": "c",
              "score": ".8",
              "y": 0,
              "group": "A"
            },
            {
              "id": "d",
              "score": ".6",
              "y": 0,
              "group": "B"
            },
            {
              "id": "e",
              "score": ".4",
              "y": 1,
              "group": "B"
            },
            {
              "id": "f",
              "score": ".1",
              "y": 0,
              "group": "B"
            }
          ],
          "threshold": ".8"
        },
        "inputFiles": [],
        "returnCode": 0,
        "expectedFailure": false,
        "stdout": "{\"api\": \"metrics\", \"variant\": \"six-cards\", \"summaryMetrics\": 9, \"plotSlots\": 4}\n",
        "stderr": "",
        "summary": {
          "mass": "6",
          "accuracy": "0.666666667",
          "precision": "0.666666667",
          "TPR": "0.666666667",
          "FPR": "0.333333333",
          "F1": "0.666666667",
          "Brier": "0.236666667",
          "meanCost": "0.333333333",
          "BayesThreshold": "0.5"
        },
        "summaryRows": [
          {
            "metric": "mass",
            "value": "6",
            "exactValue": "6",
            "unit": "mass",
            "defined": "1"
          },
          {
            "metric": "accuracy",
            "value": "0.666666667",
            "exactValue": "2/3",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "precision",
            "value": "0.666666667",
            "exactValue": "2/3",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "TPR",
            "value": "0.666666667",
            "exactValue": "2/3",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "FPR",
            "value": "0.333333333",
            "exactValue": "1/3",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "F1",
            "value": "0.666666667",
            "exactValue": "2/3",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "Brier",
            "value": "0.236666667",
            "exactValue": "71/300",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "meanCost",
            "value": "0.333333333",
            "exactValue": "1/3",
            "unit": "hypothetical cost units/mass",
            "defined": "1"
          },
          {
            "metric": "BayesThreshold",
            "value": "0.5",
            "exactValue": "1/2",
            "unit": "dimensionless",
            "defined": "1"
          }
        ],
        "plotPoints": [
          {
            "series": "0",
            "index": "0",
            "xExact": "0",
            "x": "0",
            "yExact": "2",
            "y": "2",
            "id": "TP"
          },
          {
            "series": "0",
            "index": "1",
            "xExact": "1",
            "x": "1",
            "yExact": "1",
            "y": "1",
            "id": "FP"
          },
          {
            "series": "0",
            "index": "2",
            "xExact": "2",
            "x": "2",
            "yExact": "1",
            "y": "1",
            "id": "FN"
          },
          {
            "series": "0",
            "index": "3",
            "xExact": "3",
            "x": "3",
            "yExact": "2",
            "y": "2",
            "id": "TN"
          }
        ],
        "plotFile": "ml14-fixed-results/metrics-six-cards-python/plot.svg",
        "plotSHA256": "7f9d34a7e4caf40dc2a9d5ef54c7d9e64093703c32aa889497f95e5f83cabe98",
        "files": [
          {
            "file": "ml14-fixed-results/metrics-six-cards-python/full.json",
            "sha256": "4f3c4556f8bd5a2abdd312136dfc308b46c00f1dff73a317c13830ea8c218533",
            "bytes": 4892
          },
          {
            "file": "ml14-fixed-results/metrics-six-cards-python/plot-points.csv",
            "sha256": "19b0dc6c8d763014f8459f517021e72045d97b81b5f9248fd5d91ba526397b0d",
            "bytes": 99
          },
          {
            "file": "ml14-fixed-results/metrics-six-cards-python/plot.svg",
            "sha256": "7f9d34a7e4caf40dc2a9d5ef54c7d9e64093703c32aa889497f95e5f83cabe98",
            "bytes": 1289
          },
          {
            "file": "ml14-fixed-results/metrics-six-cards-python/summary.csv",
            "sha256": "e7f1359333299b57d7cc921d0ec57fa18f65c213760d2927c5159fcc3c41a48d",
            "bytes": 389
          }
        ],
        "scope": "Actually executed standalone fixed example, Python exact Fraction versus base-R binary64. Approximate R residuals retained; not universal exact arithmetic/web validation/native UI. Source programs read factual3CSV only."
      },
      "weighted": {
        "api": "metrics",
        "variant": "weighted",
        "language": "python",
        "title": "Double only the tied negative card mass",
        "codeFile": "ml14-code/metrics-weighted.py",
        "codeSHA256": "2b0da6114dee5ea79cfcbe5e751628504e024161f30610366f7b7fffa9ec4387",
        "code": "#!/usr/bin/env python3\n\"\"\"ML14 standalone exact finite study, Python standard library only.\nInputs: only the three retained factual source CSVs below.\nDerived role/target/group/eligibility columns in those CSVs are NOT inputs.\nRebuilds SHA256 roles, train-only medians/cell scores, validation thresholds,\ntest curves, binary-event reliability and descriptive group ledgers.\nCosts 1/1,1/5,5/1 are hypothetical units, not measured intervention returns.\nThis is author public reproduction, not independent scientific review.\n\"\"\"\n\"\"\"Author Fraction reference, separate from product JavaScript; not independent peer.\"\"\"\nfrom fractions import Fraction as F\nfrom collections import Counter,defaultdict\ndef read(raw):\n rows=[]\n for i,r in enumerate(raw):\n  s=None if r['score']is None else F(str(r['score']));y=None if r['y']is None else F(int(r['y']))if isinstance(r['y'],bool)else F(str(r['y']));w=F(str(r.get('weight','1')));role=r.get('role','evaluation')\n  rows.append(dict(id=r['id'],index=i,score=s,y=y,w=w,role=role,group=r.get('group'),eligible=s is not None and y is not None and w>0 and role!='excluded'))\n return rows\ndef scoped(rows,role='all'):return rows if role=='all'else[r for r in rows if r['role']==role]\ndef divide(n,d):return None if not d else n/d\ndef policy(v):return v if v in ['always-negative','always-positive']else F(str(v))\ndef positive(p,s):return p=='always-positive'if isinstance(p,str)else s>=p\ndef cost(a=None):\n a={}if a is None else a;fp=F(str(a.get('falsePositive','1')));fn=F(str(a.get('falseNegative','1')));return fp,fn\ndef metrics(rows,threshold=F(1,2),cc=(F(1),F(1))):\n counts=dict(TP=F(0),FP=F(0),FN=F(0),TN=F(0));brier=F(0);pred=[]\n for r in rows:\n  if not r['eligible']:pred.append(dict(id=r['id'],index=r['index'],eligible=False,decision=None,probability=None,Brier=None));continue\n  yes=positive(threshold,r['score']);cell=('T'if yes==bool(r['y'])else'F')+('P'if yes else'N');counts[cell]+=r['w'];loss=(r['score']-r['y'])**2;brier+=r['w']*loss;pred.append(dict(id=r['id'],index=r['index'],eligible=True,decision=int(yes),probability=r['score'],Brier=loss))\n TP,FP,FN,TN=[counts[k]for k in ['TP','FP','FN','TN']];P=TP+FN;N=TN+FP;mass=P+N;PP=TP+FP;PN=TN+FN;TPR=divide(TP,P);TNR=divide(TN,N);total=FP*cc[0]+FN*cc[1]\n return dict(confusion=counts,mass=mass,positiveTargetMass=P,negativeTargetMass=N,predictedPositiveMass=PP,predictedNegativeMass=PN,prevalence=divide(P,mass),selectionRate=divide(PP,mass),accuracy=divide(TP+TN,mass),precision=divide(TP,PP),negativePredictiveValue=divide(TN,PN),TPR=TPR,FPR=divide(FP,N),TNR=TNR,FNR=divide(FN,P),F1=divide(2*TP,2*TP+FP+FN),balancedAccuracy=None if TPR is None or TNR is None else(TPR+TNR)/2,Brier=divide(brier,mass),BrierSum=brier,totalCost=total,meanCost=divide(total,mass),predictions=pred,bayesThreshold=divide(cc[0],sum(cc)))\ndef curves(rows):\n use=[r for r in rows if r['eligible']];pos=Counter();neg=Counter()\n for r in use:(pos if r['y']else neg)[r['score']]+=r['w']\n P=sum(pos.values(),F(0));N=sum(neg.values(),F(0));pairs=F(0)\n for a,wa in pos.items():\n  for b,wb in neg.items():pairs+=wa*wb*(F(1)if a>b else F(1,2)if a==b else F(0))\n thresholds=['always-negative']+sorted({r['score']for r in use},reverse=True);points=[];AP=F(0);trap=F(0);lastR=F(0);lastP=F(1)\n for i,p in enumerate(thresholds):\n  m=metrics(rows,p);points.append(dict(policy=p,TP=m['confusion']['TP'],FP=m['confusion']['FP'],FN=m['confusion']['FN'],TN=m['confusion']['TN'],TPR=m['TPR'],FPR=m['FPR'],precision=m['precision'],recall=m['TPR']))\n  if i and P:\n   R=m['TPR'];PP=m['precision'];AP+=(R-lastR)*PP;trap+=(R-lastR)*(PP+lastP)/2;lastR=R;lastP=PP\n return dict(positiveMass=P,negativeMass=N,ROC_AUC=divide(pairs,P*N),weightedConcordantPlusHalfTiedMass=pairs,averagePrecision=AP if P else None,PRTrapezoidWithInitialPrecisionOne=trap if P else None,points=points)\ndef choose(rows,a,cc):\n sr=a.get('selectionRole','validation');er=a.get('evaluationRole','test');rr=scoped(rows,sr);thresholds=[policy(t)for t in a['thresholds']]if'thresholds'in a else['always-negative']+sorted({r['score']for r in rr if r['eligible']},reverse=True)\n candidates=[]\n for i,p in enumerate(thresholds):\n  m=metrics(rr,p,cc);reasons=[]\n  if'minTPR'in a and(m['TPR']is None or m['TPR']<F(str(a['minTPR']))):reasons.append('TPR-undefined'if m['TPR']is None else'below-minTPR')\n  if'maxFPR'in a and(m['FPR']is None or m['FPR']>F(str(a['maxFPR']))):reasons.append('FPR-undefined'if m['FPR']is None else'above-maxFPR')\n  candidates.append(dict(index=i,policy=p,metrics=m,feasible=not reasons,reasons=reasons))\n eligible=[c for c in candidates if c['feasible']];best=min(eligible,key=lambda c:(c['metrics']['meanCost'],c['index']))if eligible else None\n return dict(selectedIndex=None if best is None else best['index'],selectedPolicy=None if best is None else best['policy'],candidates=candidates,selectedValidation=None if best is None else best['metrics'],evaluation=None if best is None or er=='none'else metrics(scoped(rows,er),best['policy'],cc),selectionIDs=[r['id']for r in rr if r['eligible']])\ndef calibrate(rows,ee):\n buckets=[[]for _ in range(len(ee)-1)]\n for r in rows:\n  if not r['eligible']:continue\n  j=next((i for i in range(len(ee)-1)if r['score']<ee[i+1]),len(ee)-2);buckets[j].append(r)\n mass=sum((r['w']for r in rows if r['eligible']),F(0));P=sum((r['w']*r['y']for r in rows if r['eligible']),F(0));pi=divide(P,mass);Brier=None if not mass else sum((r['w']*(r['score']-r['y'])**2 for r in rows if r['eligible']),F(0))/mass;ECE=F(0);reliability=F(0);resolution=F(0);correction=F(0);bins=[]\n for i,rr in enumerate(buckets):\n  w=sum((r['w']for r in rr),F(0));mp=None if not w else sum((r['w']*r['score']for r in rr),F(0))/w;o=None if not w else sum((r['w']*r['y']for r in rr),F(0))/w\n  variance=None if not w else sum((r['w']*(r['score']-mp)**2 for r in rr),F(0))/w\n  covariance=None if not w else sum((r['w']*(r['score']-mp)*(r['y']-o)for r in rr),F(0))/w\n  bc=None if not w else variance-2*covariance;gap=None if not w else mp-o\n  bins.append(dict(index=i,rows=len(rr),mass=w,meanPrediction=mp,eventRate=o,gap=gap,absoluteGap=None if gap is None else abs(gap),scoreVariance=variance,scoreTargetCovariance=covariance,withinBinCorrection=bc,ids=[r['id']for r in rr]))\n  if w:\n   share=w/mass;ECE+=share*abs(gap);reliability+=share*gap**2;resolution+=share*(o-pi)**2;correction+=share*bc\n uncertainty=None if pi is None else pi*(1-pi);residual=None if Brier is None else Brier-(uncertainty-resolution+reliability+correction)\n return dict(mass=mass,prevalence=pi,Brier=Brier,ECE=ECE if mass else None,reliability=reliability if mass else None,resolution=resolution if mass else None,uncertainty=uncertainty,withinBinCorrection=correction if mass else None,BrierIdentityResidual=residual,bins=bins)\ndef typed(v):return type(v).__name__,v\ndef groups(rows,p,cc):\n bins={}\n for r in rows:\n  if r['group']is not None:bins.setdefault(typed(r['group']),[]).append(r)\n gm=[dict(group=rr[0]['group'],metrics=metrics(rr,p,cc))for rr in bins.values()];overall=metrics(rows,p,cc);unknown=metrics([r for r in rows if r['group']is None],p,cc);gaps={}\n for key in ['prevalence','selectionRate','TPR','FPR','precision','accuracy','meanCost']:\n  positive=[g for g in gm if g['metrics']['mass']>0];undefined=[g['group']for g in positive if g['metrics'][key]is None];vals=[g['metrics'][key]for g in positive if g['metrics'][key]is not None]\n  gaps[key]=dict(value=None if len(positive)<2 or undefined else max(vals)-min(vals),undefinedGroups=undefined,comparedPositiveMassGroups=[g['group']for g in positive])\n return dict(overall=overall,groups=gm,unknownGroup=unknown,gaps=gaps,partitionMassResidual=overall['mass']-unknown['mass']-sum((g['metrics']['mass']for g in gm),F(0)))\ndef actual_model(M):\n raw=M['records'];cat=M['categoricalFeatures'];p=len(raw[0]['x']);train=[r for r in raw if r['role']=='train'];medians=[]\n for j in range(p):\n  if j in cat:medians.append(None);continue\n  values=sorted(F(r['x'][j])for r in train);n=len(values);medians.append(values[n//2]if n%2 else(values[n//2-1]+values[n//2])/2)\n def transform(r):return[F(v)if j in cat else F(int(F(v)>medians[j]))for j,v in enumerate(r['x'])]\n counts={}\n for r in train:\n  key=tuple(transform(r));n,s=counts.get(key,(0,0));counts[key]=(n+1,s+int(r['y']))\n probabilities={k:F(s+1,n+2)for k,(n,s)in counts.items()};fallback=F(sum(int(r['y'])for r in train)+1,len(train)+2);scored=[]\n for i,r in enumerate(raw):\n  eligible=r['role']!='excluded';z=transform(r)if eligible else None;key=None if z is None else tuple(z);score=None if not eligible else probabilities.get(key,fallback)\n  scored.append(dict(id=r['id'],index=i,role=r['role'],group=r['group'],y=None if r['y']is None else F(r['y']),score=score,w=F(1),eligible=eligible,transformedX=z,unseenCell=None if not eligible else key not in probabilities))\n return dict(medians=medians,cells=counts,probabilities=probabilities,fallback=fallback,rows=scored,trainIDs=[r['id']for r in train])\n\n\nimport csv,json,hashlib,argparse,datetime\nfrom pathlib import Path\ndef missing(v):return None if v in ['', '.',None]else v\ndef load_sources(folder):\n def read_csv(name):\n  with (folder/name).open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))\n wb=read_csv('actual64-country-four-indicators-original-2024.csv')\n codes=['NY.GDP.PCAP.KD','NY.GDP.MKTP.KD.ZG','FP.CPI.TOTL.ZG','SP.DYN.LE00.IN']\n lookup={(r['countryISO3'],r['indicatorID']):r for r in wb};country=[]\n for i,iso in enumerate(sorted({r['countryISO3']for r in wb}),1):\n  native=[lookup[iso,c]for c in codes];v=[missing(r['originalValueToken'])for r in native]\n  country.append(dict(id=iso+':2024',sourceRow=i,originalID=iso,x=v[:3],y=None if v[3]is None else str(int(F(v[3])>=80)),group=None if v[0]is None else str(int(F(v[0])>=25000)),nativeTarget=v[3],nativeSourceRows=';'.join(r['sourceRow']for r in native)))\n nls=read_csv('actual3613-NLS-original52-fields-groups-roles.csv');person=[]\n for r in nls:\n  y=missing(r['wage76']);person.append(dict(id='person:'+r['sourceRow'],sourceRow=int(r['sourceRow']),originalID=r['id'],x=[missing(r[k])for k in ['ed76','age76','nearc4']],y=None if y is None else str(int(F(y)>=500)),group=missing(r['black']),nativeTarget=y,nativeSourceRows=r['sourceRow']))\n ch=read_csv('actual3150-churn-original14-fields-groups-roles.csv');company=[]\n for r in ch:\n  company.append(dict(id='customer:'+r['sourceRow'],sourceRow=int(r['sourceRow']),originalID='',x=[missing(r[k])for k in ['Call  Failure','Complains','Subscription  Length','Seconds of Use']],y=missing(r['Churn']),group=missing(r['Tariff Plan']),nativeTarget=missing(r['Churn']),nativeSourceRows=r['sourceRow']))\n assert len(wb)==64 and len(country)==16 and len(nls)==3613 and len(ch)==3150\n assert [int(r['sourceRow'])for r in ch if r['Charge  Amount']=='10']==[474,2174,2274,2374,2674,2924,2974]\n models={}\n for kind,raw,cat,units in [('country',country,[],['constant2015USD/person','annualPercent','annualPercent']),('person',person,[2],['years','years','nativeCategory']),('company',company,[1],['count','nativeCategory','months','seconds'])]:\n  order=sorted(range(len(raw)),key=lambda i:(hashlib.sha256(('ML14-role|'+kind+'|'+raw[i]['id']).encode()).hexdigest(),i))\n  for rank,i in enumerate(order):\n   r=raw[i];r['plannedRole']='test'if rank%5==0 else'validation'if rank%5==1 else'train';r['eligible']=None not in r['x']+[r['y']];r['role']=r['plannedRole']if r['eligible']else'excluded';r['weight']='1'\n  models[kind]=dict(records=raw,categoricalFeatures=cat,featureUnits=units)\n assert sum(r['eligible']for r in person)==3017\n return models\n\ndef exact(v):return ''if v is None else str(v)\ndef approx(v):return ''if v is None else format(float(v),'.17g')\ndef scalar_fields(m,keys):\n out={}\n for k in keys:\n  out[k+'Exact']=exact(m[k]);out[k+'Approx']=approx(m[k])\n return out\nCOUNTS=['mass','positiveTargetMass','negativeTargetMass','predictedPositiveMass','predictedNegativeMass']\nRATES=['prevalence','selectionRate','accuracy','precision','negativePredictiveValue','TPR','FPR','TNR','FNR','F1','balancedAccuracy','Brier','BrierSum','totalCost','meanCost']\nSCENARIOS=[('equal',F(1),F(1)),('miss-five',F(1),F(5)),('alarm-five',F(5),F(1))]\ndef packed(v):\n if isinstance(v,F):return str(v)\n if isinstance(v,dict):return{str(k):packed(x)for k,x in v.items()}\n if isinstance(v,(tuple,list)):return[packed(x)for x in v]\n return v\ndef run_study(source,out):\n out.mkdir(parents=True,exist_ok=True);models=load_sources(source)\n tables={name:[]for name in ['predictions','lineage','fit-medians','fit-cells','validation-candidates','test-metrics','test-curves','calibration-bins','group-metrics','chart-points']}\n studies={};charts=[]\n def point(kind,chart,series,index,x,y,xunit='dimensionless',yunit='dimensionless',role='test',tag=''):\n  tables['chart-points'].append(dict(kind=kind,chart=chart,series=series,index=index,xExact=exact(x),xApprox=approx(x),yExact=exact(y),yApprox=approx(y),xUnit=xunit,yUnit=yunit,role=role,tag=tag))\n for kind,M in models.items():\n  fit=actual_model(M);rr=fit['rows'];native=M['records'];test=scoped(rr,'test');cv=curves(test);cal=calibrate(test,[F(0),F(1,5),F(2,5),F(3,5),F(4,5),F(1)]);scenarios=[]\n  for i,r in enumerate(rr):\n   n=native[i];reason=''if r['eligible']else'required-X-or-Y-missing'\n   tables['predictions'].append(dict(kind=kind,id=r['id'],sourceRow=n['sourceRow'],originalID=n['originalID'],plannedRole=n['plannedRole'],role=r['role'],group=''if r['group']is None else r['group'],eligible=int(r['eligible']),targetExact=exact(r['y']),probabilityExact=exact(r['score']),probabilityApprox=approx(r['score']),unseenCell=''if r['unseenCell']is None else int(r['unseenCell']),transformedX=''if r['transformedX']is None else'|'.join(map(str,r['transformedX'])),reason=reason))\n   tables['lineage'].append(dict(kind=kind,id=r['id'],sourceRow=n['sourceRow'],originalID=n['originalID'],nativeSourceRows=n['nativeSourceRows'],rawX='|'.join(''if x is None else x for x in n['x']),nativeTarget=''if n['nativeTarget']is None else n['nativeTarget'],derivedTarget=exact(r['y']),nativeGroup=''if n['group']is None else n['group'],plannedRole=n['plannedRole'],role=r['role'],eligible=int(r['eligible']),analyticalMass='1',reason=reason))\n  for j,v in enumerate(fit['medians']):tables['fit-medians'].append(dict(kind=kind,feature=j,categorical=int(j in M['categoricalFeatures']),fitRows=len(fit['trainIDs']),medianExact=exact(v),medianApprox=approx(v),unit=M['featureUnits'][j]))\n  for key,(mass,pos)in fit['cells'].items():tables['fit-cells'].append(dict(kind=kind,cell='|'.join(map(str,key)),trainingRows=mass,positiveRows=pos,probabilityExact=exact(fit['probabilities'][key]),probabilityApprox=approx(fit['probabilities'][key]),fallbackExact=exact(fit['fallback']),fallbackApprox=approx(fit['fallback'])))\n  for j,p in enumerate(cv['points']):\n   policy=p['policy'];tables['test-curves'].append(dict(kind=kind,point=j,policy=policy if isinstance(policy,str)else'threshold',thresholdExact=''if isinstance(policy,str)else exact(policy),thresholdApprox=''if isinstance(policy,str)else approx(policy),**scalar_fields(p,['TP','FP','FN','TN','TPR','FPR','precision','recall'])))\n   point(kind,'roc','ROC',j,p['FPR'],p['TPR']);point(kind,'pr','PR-observed',j,p['recall'],p['precision'])\n  for b in cal['bins']:\n   tables['calibration-bins'].append(dict(kind=kind,bin=b['index'],leftExact=str(F(b['index'],5)),rightExact=str(F(b['index']+1,5)),rightClosed=int(b['index']==4),rows=b['rows'],ids=';'.join(str(i)for i in b['ids']),**scalar_fields(b,['mass','meanPrediction','eventRate','gap','absoluteGap','scoreVariance','scoreTargetCovariance','withinBinCorrection'])))\n   point(kind,'reliability','Binary event rate',b['index'],b['meanPrediction'],b['eventRate'],tag='rows='+str(b['rows']))\n  for j,r in enumerate(test):\n   point(kind,'test-scores','Training-fitted probability',j,F(j+1),r['score'],'test-row position','probability',tag=r['id'])\n   point(kind,'test-scores','Observed Y',j,F(j+1),r['y'],'test-row position','binary target',tag=r['id'])\n  for name,fp,fn in SCENARIOS:\n   choice=choose(rr,{},(fp,fn));gm=groups(test,choice['selectedPolicy'],(fp,fn));scenarios.append(dict(name=name,costs=dict(falsePositive=fp,falseNegative=fn),selection=choice,groups=gm));ev=choice['evaluation']\n   for c in choice['candidates']:\n    policy=c['policy'];mm=c['metrics'];tables['validation-candidates'].append(dict(kind=kind,scenario=name,candidate=c['index'],selected=int(c['index']==choice['selectedIndex']),policy=policy if isinstance(policy,str)else'threshold',thresholdExact=''if isinstance(policy,str)else exact(policy),thresholdApprox=''if isinstance(policy,str)else approx(policy),feasible=int(c['feasible']),reasons=';'.join(c['reasons']),**{k+'Exact':str(v)for k,v in mm['confusion'].items()},**scalar_fields(mm,COUNTS+['TPR','FPR','precision','meanCost','totalCost'])))\n    point(kind,'validation-cost',name,c['index'],F(c['index']),mm['meanCost'],'candidate index','hypothetical cost units/mass','validation',tag=exact(policy))\n   mm={**ev,**ev['confusion'],**{k:cv[k]for k in ['ROC_AUC','averagePrecision','PRTrapezoidWithInitialPrecisionOne']},**{k:cal[k]for k in ['ECE','reliability','resolution','uncertainty','withinBinCorrection','BrierIdentityResidual']}}\n   for key in ['TP','FP','FN','TN']+COUNTS+RATES+['ROC_AUC','averagePrecision','PRTrapezoidWithInitialPrecisionOne','ECE','reliability','resolution','uncertainty','withinBinCorrection','BrierIdentityResidual']:\n    unit='rows'if key in ['TP','FP','FN','TN']+COUNTS else'hypothetical cost units'if key=='totalCost'else'hypothetical cost units/mass'if key=='meanCost'else'sum squared-probability loss'if key=='BrierSum'else'dimensionless'\n    tables['test-metrics'].append(dict(kind=kind,scenario=name,metric=key,valueExact=exact(mm[key]),valueApprox=approx(mm[key]),unit=unit))\n   allg=[('overall','all',gm['overall'])]+[('known',str(g['group']),g['metrics'])for g in gm['groups']]+[('unknown','',gm['unknownGroup'])]\n   for j,(typ,token,g)in enumerate(allg):\n    tables['group-metrics'].append(dict(kind=kind,scenario=name,groupType=typ,groupToken=token,retainedRows=g.get('retainedRows',sum((r['group']==token)if typ=='known'else(r['group']is None)if typ=='unknown'else True for r in test)),**{k+'Exact':str(v)for k,v in g['confusion'].items()},**scalar_fields(g,COUNTS+RATES)))\n    if typ=='known':point(kind,'group-TPR',name,j-1,F(j-1),g['TPR'],'declared group position','TPR',tag=token)\n  studies[kind]=dict(kind=kind,rows=len(native),eligibleRows=sum(r['eligible']for r in rr),trainingIDs=fit['trainIDs'],fitMedians=fit['medians'],fitCells=[dict(cell=list(k),mass=n,positive=s,probability=fit['probabilities'][k])for k,(n,s)in fit['cells'].items()],fallback=fit['fallback'],scenarios=scenarios,testCurves=cv,testCalibration=cal,rowsScored=rr)\n files=[]\n for name,rows in tables.items():\n  p=out/('computed-'+name+'.csv')\n  with p.open('w',encoding='utf8',newline='')as f:w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows)\n  files.append(dict(file=p.name,rows=len(rows),columns=len(rows[0]),bodyFields=len(rows)*len(rows[0]),sha256=hashlib.sha256(p.read_bytes()).hexdigest()))\n (out/'study.json').write_text(json.dumps(packed(studies),ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\n sourceFiles=[source/n for n in ['actual64-country-four-indicators-original-2024.csv','actual3613-NLS-original52-fields-groups-roles.csv','actual3150-churn-original14-fields-groups-roles.csv']]\n provenance=dict(chapter='ML-14',arithmetic='Python stdlib Fraction exact finite values from original decimal strings; binary64 valueApprox is display only.',inputs=[dict(file=p.name,sha256=hashlib.sha256(p.read_bytes()).hexdigest())for p in sourceFiles],priorEngineModelsScoresOrComputedFilesRead=False,roleRule=\"SHA256('ML14-role|'+kind+'|'+ID),rankmod5=0test/1validation/others train before eligibility\",costs='Hypothetical1/1,1/5,5/1; no causal intervention returns',files=files,observations={k:dict(sourceRows=v['rows'],eligibleRows=v['eligibleRows'],trainingRows=len(v['trainingIDs']))for k,v in studies.items()})\n (out/'provenance.json').write_text(json.dumps(provenance,ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\n print(json.dumps(dict(status='PASS standalone completed',files=len(files),bodyFields=sum(f['bodyFields']for f in files),observations=provenance['observations'])))\n\n# Fixed declared examples: full web budget/option validation is not reproduced.\nfrom html import escape\nimport textwrap\ndef validated_rows(raw):\n for r in raw:\n  assert F(str(r.get('weight','1')))>=0,'negative analytical mass'\n  assert r['score']is None or 0<=F(str(r['score']))<=1,'score outside zero/one'\n  assert r['y']is None or F(str(int(r['y']))if isinstance(r['y'],bool)else str(r['y']))in [0,1],'binary target required'\n return read(raw)\ndef serial(v):\n if isinstance(v,F):return dict(exactFraction=str(v),value=float(v))\n if isinstance(v,(list,tuple)):return[serial(x)for x in v]\n if isinstance(v,dict):return{k:serial(x)for k,x in v.items()}\n return v\ndef fixed_svg(path,points,title,xlabel,ylabel,legend):\n use=[p for p in points if p['xExact']!=''and p['yExact']!=''];xs=[float(F(p['xExact']))for p in use];ys=[float(F(p['yExact']))for p in use]\n xmin=min(xs,default=0);xmax=max(xs,default=1);ymin=min([0]+ys);ymax=max([0]+ys)\n if xmin==xmax:xmin-=.5;xmax+=.5\n if ymin==ymax:ymax=ymin+1\n X=lambda v:85+(float(v)-xmin)/(xmax-xmin)*480;Y=lambda v:278-(float(v)-ymin)/(ymax-ymin)*175\n s='<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"620\" height=\"360\" viewBox=\"0 0 620 360\"><rect width=\"620\" height=\"360\" fill=\"white\"/><g font-family=\"Arial, sans-serif\" font-size=\"13\" fill=\"#17324d\">'\n for i,line in enumerate(textwrap.wrap(title,width=65)):s+='<text x=\"25\" y=\"'+str(24+i*18)+'\">'+escape(line)+'</text>'\n colors=['#176b9b','#b85e18','#437e4d']\n for i,label in enumerate(legend):s+='<circle cx=\"'+str(30+i*250)+'\" cy=\"76\" r=\"4\" fill=\"'+colors[i%3]+'\"/><text x=\"'+str(42+i*250)+'\" y=\"80\">'+escape(label)+'</text>'\n s+='<path d=\"M85 98V278H575\" fill=\"none\" stroke=\"#52677d\"/><text text-anchor=\"middle\" x=\"325\" y=\"338\">'+escape(xlabel)+'</text><text text-anchor=\"middle\" transform=\"translate(21,190) rotate(-90)\">'+escape(ylabel)+'</text>'\n for i in range(5):\n  xx=xmin+(xmax-xmin)*i/4;yy=ymin+(ymax-ymin)*i/4;s+='<text text-anchor=\"middle\" x=\"'+format(X(xx),'.9g')+'\" y=\"305\">'+format(xx,'.4g')+'</text><text text-anchor=\"end\" x=\"77\" y=\"'+format(Y(yy)+4,'.9g')+'\">'+format(yy,'.4g')+'</text>'\n for p in use:s+='<circle cx=\"'+format(X(F(p['xExact'])),'.9g')+'\" cy=\"'+format(Y(F(p['yExact'])),'.9g')+'\" r=\"3\" fill=\"'+colors[p['series']%3]+'\"/>'\n path.write_text(s+'</g></svg>',encoding='utf8')\ndef fixed_run():\n ap=argparse.ArgumentParser();ap.add_argument('--out',type=Path,default=Path('results'));ap.add_argument('--data-dir',type=Path,default=Path(__file__).resolve().parent.parent/'ml14-sources');args=ap.parse_args();args.out.mkdir(parents=True,exist_ok=True)\n api=FIXED['api'];a=FIXED['args'];summary=[];points=[];xlabel='Declared index';ylabel='Value';legend=['Declared result']\n def metric(name,v,unit='dimensionless'):\n  q=None if v is None else v if isinstance(v,F)else F(v);summary.append(dict(metric=name,value='undefined'if q is None else format(float(q),'.9g'),exactValue=''if q is None else str(q),unit=unit,defined=int(q is not None)))\n def pt(i,x,y,ident='',series=0):\n  points.append(dict(series=series,index=i,xExact=''if x is None else str(F(x)),x='undefined'if x is None else format(float(x),'.9g'),yExact=''if y is None else str(F(y)),y='undefined'if y is None else format(float(y),'.9g'),id=str(ident)))\n if api=='realdata':\n  models=load_sources(args.data_dir);model=models[a['kind']];fit=actual_model(model);rr=fit['rows'];test=scoped(rr,'test');scenarios=[]\n  for name,fp,fn in SCENARIOS:\n   c=choose(rr,{},(fp,fn));scenarios.append(dict(name=name,selection=c));metric(name+'Threshold',c['selectedPolicy']);metric(name+'TestCost',c['evaluation']['meanCost'],'hypothetical cost units/mass')\n  cv=curves(test);cal=calibrate(test,[F(0),F(1,5),F(2,5),F(3,5),F(4,5),F(1)]);metric('testAUC',cv['ROC_AUC']);metric('testAP',cv['averagePrecision']);metric('testBrier',cal['Brier']);metric('eligibleRows',sum(r['eligible']for r in rr),'rows')\n  for i,r in enumerate(test):pt(i,i+1,r['score'],r['id'],0);pt(i,i+1,r['y'],r['id'],1)\n  full=dict(kind=a['kind'],fitMedians=fit['medians'],fitCells=[dict(cell=list(k),mass=n,positive=s,probability=fit['probabilities'][k])for k,(n,s)in fit['cells'].items()],rowsScored=rr,scenarios=scenarios,testCurves=cv,testCalibration=cal);xlabel='Test row, native order';ylabel='Y or probability';legend=['Training-fitted probability','Observed Y']\n else:\n  rr=validated_rows(a['rows']);role=a.get('role','all');frame=scoped(rr,role);cc=cost(a.get('costs'));t=policy(a.get('threshold','1/2'))\n  if api=='metrics':\n   full=metrics(frame,t,cc)\n   for k in ['mass','accuracy','precision','TPR','FPR','F1','Brier','meanCost']:metric(k,full[k],'mass'if k=='mass'else'hypothetical cost units/mass'if k=='meanCost'else'dimensionless')\n   metric('BayesThreshold',full['bayesThreshold'])\n   for i,k in enumerate(['TP','FP','FN','TN']):pt(i,i,full['confusion'][k],k)\n   xlabel='TP / FP / FN / TN positions';ylabel='Analytical mass'\n  elif api=='curves':\n   full=curves(frame)\n   for k in ['ROC_AUC','averagePrecision','PRTrapezoidWithInitialPrecisionOne']:metric(k,full[k])\n   for i,p in enumerate(full['points']):pt(i,p['FPR'],p['TPR'],str(p['policy']))\n   xlabel='False positive rate';ylabel='True positive rate';legend=['Observed ROC operating points']\n  elif api=='choose':\n   full=choose(rr,a,cc);metric('selectedIndex',full['selectedIndex'],'candidate index');metric('minimumCost',None if full['selectedValidation']is None else full['selectedValidation']['meanCost'],'hypothetical cost units/mass');metric('feasible',int(full['selectedIndex']is not None),'indicator')\n   for c in full['candidates']:pt(c['index'],c['index'],c['metrics']['meanCost'],str(c['policy']))\n   xlabel='Validation candidate';ylabel='Assumed cost / mass';legend=['Validation candidate costs']\n  elif api=='calibrate':\n   full=calibrate(frame,[F(str(e))for e in a.get('binEdges',['0','1/5','2/5','3/5','4/5','1'])])\n   for k in ['ECE','Brier','uncertainty','resolution','reliability','withinBinCorrection','BrierIdentityResidual']:metric(k,full[k])\n   for b in full['bins']:pt(b['index'],b['meanPrediction'],b['eventRate'],'bin:'+str(b['index']))\n   xlabel='Bin mean forecast';ylabel='Bin event rate';legend=['Binary-event reliability']\n  elif api=='groups':\n   full=groups(frame,t,cc);metric('overallTPR',full['overall']['TPR']);metric('TPRGap',full['gaps']['TPR']['value']);metric('precisionGap',full['gaps']['precision']['value']);metric('unknownMass',full['unknownGroup']['mass'],'mass');metric('partitionResidual',full['partitionMassResidual'],'mass')\n   for i,g in enumerate(full['groups']):pt(i,i,g['metrics']['TPR'],str(g['group']))\n   xlabel='Declared group position';ylabel='True positive rate';legend=['Known-group TPR']\n  else:raise ValueError('unknown fixed API')\n def csvout(name,rows):\n  with(args.out/name).open('w',encoding='utf8',newline='')as f:w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows)\n csvout('summary.csv',summary);csvout('plot-points.csv',points);fixed_svg(args.out/'plot.svg',points,FIXED['title'],xlabel,ylabel,legend)\n (args.out/'full.json').write_text(json.dumps(dict(api=api,variant=FIXED['variant'],input=FIXED['args'],arithmetic='Python standard-library Fraction, declared fixed example; full web validator/budgets not reproduced',result=serial(full)),ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\n print(json.dumps(dict(api=api,variant=FIXED['variant'],summaryMetrics=len(summary),plotSlots=len(points))))\n\nFIXED={'api': 'metrics', 'variant': 'weighted', 'args': {'rows': [{'id': 'a', 'score': '.9', 'y': 1, 'group': 'A'}, {'id': 'b', 'score': '.8', 'y': 1, 'group': 'A'}, {'id': 'c', 'score': '.8', 'y': 0, 'group': 'A', 'weight': '2'}, {'id': 'd', 'score': '.6', 'y': 0, 'group': 'B'}, {'id': 'e', 'score': '.4', 'y': 1, 'group': 'B'}, {'id': 'f', 'score': '.1', 'y': 0, 'group': 'B'}], 'threshold': '.8'}, 'title': 'Double only the tied negative card mass'}\nif __name__=='__main__':fixed_run()\n",
        "codeText": "#!/usr/bin/env python3\n\"\"\"ML14 standalone exact finite study, Python standard library only.\nInputs: only the three retained factual source CSVs below.\nDerived role/target/group/eligibility columns in those CSVs are NOT inputs.\nRebuilds SHA256 roles, train-only medians/cell scores, validation thresholds,\ntest curves, binary-event reliability and descriptive group ledgers.\nCosts 1/1,1/5,5/1 are hypothetical units, not measured intervention returns.\nThis is author public reproduction, not independent scientific review.\n\"\"\"\n\"\"\"Author Fraction reference, separate from product JavaScript; not independent peer.\"\"\"\nfrom fractions import Fraction as F\nfrom collections import Counter,defaultdict\ndef read(raw):\n rows=[]\n for i,r in enumerate(raw):\n  s=None if r['score']is None else F(str(r['score']));y=None if r['y']is None else F(int(r['y']))if isinstance(r['y'],bool)else F(str(r['y']));w=F(str(r.get('weight','1')));role=r.get('role','evaluation')\n  rows.append(dict(id=r['id'],index=i,score=s,y=y,w=w,role=role,group=r.get('group'),eligible=s is not None and y is not None and w>0 and role!='excluded'))\n return rows\ndef scoped(rows,role='all'):return rows if role=='all'else[r for r in rows if r['role']==role]\ndef divide(n,d):return None if not d else n/d\ndef policy(v):return v if v in ['always-negative','always-positive']else F(str(v))\ndef positive(p,s):return p=='always-positive'if isinstance(p,str)else s>=p\ndef cost(a=None):\n a={}if a is None else a;fp=F(str(a.get('falsePositive','1')));fn=F(str(a.get('falseNegative','1')));return fp,fn\ndef metrics(rows,threshold=F(1,2),cc=(F(1),F(1))):\n counts=dict(TP=F(0),FP=F(0),FN=F(0),TN=F(0));brier=F(0);pred=[]\n for r in rows:\n  if not r['eligible']:pred.append(dict(id=r['id'],index=r['index'],eligible=False,decision=None,probability=None,Brier=None));continue\n  yes=positive(threshold,r['score']);cell=('T'if yes==bool(r['y'])else'F')+('P'if yes else'N');counts[cell]+=r['w'];loss=(r['score']-r['y'])**2;brier+=r['w']*loss;pred.append(dict(id=r['id'],index=r['index'],eligible=True,decision=int(yes),probability=r['score'],Brier=loss))\n TP,FP,FN,TN=[counts[k]for k in ['TP','FP','FN','TN']];P=TP+FN;N=TN+FP;mass=P+N;PP=TP+FP;PN=TN+FN;TPR=divide(TP,P);TNR=divide(TN,N);total=FP*cc[0]+FN*cc[1]\n return dict(confusion=counts,mass=mass,positiveTargetMass=P,negativeTargetMass=N,predictedPositiveMass=PP,predictedNegativeMass=PN,prevalence=divide(P,mass),selectionRate=divide(PP,mass),accuracy=divide(TP+TN,mass),precision=divide(TP,PP),negativePredictiveValue=divide(TN,PN),TPR=TPR,FPR=divide(FP,N),TNR=TNR,FNR=divide(FN,P),F1=divide(2*TP,2*TP+FP+FN),balancedAccuracy=None if TPR is None or TNR is None else(TPR+TNR)/2,Brier=divide(brier,mass),BrierSum=brier,totalCost=total,meanCost=divide(total,mass),predictions=pred,bayesThreshold=divide(cc[0],sum(cc)))\ndef curves(rows):\n use=[r for r in rows if r['eligible']];pos=Counter();neg=Counter()\n for r in use:(pos if r['y']else neg)[r['score']]+=r['w']\n P=sum(pos.values(),F(0));N=sum(neg.values(),F(0));pairs=F(0)\n for a,wa in pos.items():\n  for b,wb in neg.items():pairs+=wa*wb*(F(1)if a>b else F(1,2)if a==b else F(0))\n thresholds=['always-negative']+sorted({r['score']for r in use},reverse=True);points=[];AP=F(0);trap=F(0);lastR=F(0);lastP=F(1)\n for i,p in enumerate(thresholds):\n  m=metrics(rows,p);points.append(dict(policy=p,TP=m['confusion']['TP'],FP=m['confusion']['FP'],FN=m['confusion']['FN'],TN=m['confusion']['TN'],TPR=m['TPR'],FPR=m['FPR'],precision=m['precision'],recall=m['TPR']))\n  if i and P:\n   R=m['TPR'];PP=m['precision'];AP+=(R-lastR)*PP;trap+=(R-lastR)*(PP+lastP)/2;lastR=R;lastP=PP\n return dict(positiveMass=P,negativeMass=N,ROC_AUC=divide(pairs,P*N),weightedConcordantPlusHalfTiedMass=pairs,averagePrecision=AP if P else None,PRTrapezoidWithInitialPrecisionOne=trap if P else None,points=points)\ndef choose(rows,a,cc):\n sr=a.get('selectionRole','validation');er=a.get('evaluationRole','test');rr=scoped(rows,sr);thresholds=[policy(t)for t in a['thresholds']]if'thresholds'in a else['always-negative']+sorted({r['score']for r in rr if r['eligible']},reverse=True)\n candidates=[]\n for i,p in enumerate(thresholds):\n  m=metrics(rr,p,cc);reasons=[]\n  if'minTPR'in a and(m['TPR']is None or m['TPR']<F(str(a['minTPR']))):reasons.append('TPR-undefined'if m['TPR']is None else'below-minTPR')\n  if'maxFPR'in a and(m['FPR']is None or m['FPR']>F(str(a['maxFPR']))):reasons.append('FPR-undefined'if m['FPR']is None else'above-maxFPR')\n  candidates.append(dict(index=i,policy=p,metrics=m,feasible=not reasons,reasons=reasons))\n eligible=[c for c in candidates if c['feasible']];best=min(eligible,key=lambda c:(c['metrics']['meanCost'],c['index']))if eligible else None\n return dict(selectedIndex=None if best is None else best['index'],selectedPolicy=None if best is None else best['policy'],candidates=candidates,selectedValidation=None if best is None else best['metrics'],evaluation=None if best is None or er=='none'else metrics(scoped(rows,er),best['policy'],cc),selectionIDs=[r['id']for r in rr if r['eligible']])\ndef calibrate(rows,ee):\n buckets=[[]for _ in range(len(ee)-1)]\n for r in rows:\n  if not r['eligible']:continue\n  j=next((i for i in range(len(ee)-1)if r['score']<ee[i+1]),len(ee)-2);buckets[j].append(r)\n mass=sum((r['w']for r in rows if r['eligible']),F(0));P=sum((r['w']*r['y']for r in rows if r['eligible']),F(0));pi=divide(P,mass);Brier=None if not mass else sum((r['w']*(r['score']-r['y'])**2 for r in rows if r['eligible']),F(0))/mass;ECE=F(0);reliability=F(0);resolution=F(0);correction=F(0);bins=[]\n for i,rr in enumerate(buckets):\n  w=sum((r['w']for r in rr),F(0));mp=None if not w else sum((r['w']*r['score']for r in rr),F(0))/w;o=None if not w else sum((r['w']*r['y']for r in rr),F(0))/w\n  variance=None if not w else sum((r['w']*(r['score']-mp)**2 for r in rr),F(0))/w\n  covariance=None if not w else sum((r['w']*(r['score']-mp)*(r['y']-o)for r in rr),F(0))/w\n  bc=None if not w else variance-2*covariance;gap=None if not w else mp-o\n  bins.append(dict(index=i,rows=len(rr),mass=w,meanPrediction=mp,eventRate=o,gap=gap,absoluteGap=None if gap is None else abs(gap),scoreVariance=variance,scoreTargetCovariance=covariance,withinBinCorrection=bc,ids=[r['id']for r in rr]))\n  if w:\n   share=w/mass;ECE+=share*abs(gap);reliability+=share*gap**2;resolution+=share*(o-pi)**2;correction+=share*bc\n uncertainty=None if pi is None else pi*(1-pi);residual=None if Brier is None else Brier-(uncertainty-resolution+reliability+correction)\n return dict(mass=mass,prevalence=pi,Brier=Brier,ECE=ECE if mass else None,reliability=reliability if mass else None,resolution=resolution if mass else None,uncertainty=uncertainty,withinBinCorrection=correction if mass else None,BrierIdentityResidual=residual,bins=bins)\ndef typed(v):return type(v).__name__,v\ndef groups(rows,p,cc):\n bins={}\n for r in rows:\n  if r['group']is not None:bins.setdefault(typed(r['group']),[]).append(r)\n gm=[dict(group=rr[0]['group'],metrics=metrics(rr,p,cc))for rr in bins.values()];overall=metrics(rows,p,cc);unknown=metrics([r for r in rows if r['group']is None],p,cc);gaps={}\n for key in ['prevalence','selectionRate','TPR','FPR','precision','accuracy','meanCost']:\n  positive=[g for g in gm if g['metrics']['mass']>0];undefined=[g['group']for g in positive if g['metrics'][key]is None];vals=[g['metrics'][key]for g in positive if g['metrics'][key]is not None]\n  gaps[key]=dict(value=None if len(positive)<2 or undefined else max(vals)-min(vals),undefinedGroups=undefined,comparedPositiveMassGroups=[g['group']for g in positive])\n return dict(overall=overall,groups=gm,unknownGroup=unknown,gaps=gaps,partitionMassResidual=overall['mass']-unknown['mass']-sum((g['metrics']['mass']for g in gm),F(0)))\ndef actual_model(M):\n raw=M['records'];cat=M['categoricalFeatures'];p=len(raw[0]['x']);train=[r for r in raw if r['role']=='train'];medians=[]\n for j in range(p):\n  if j in cat:medians.append(None);continue\n  values=sorted(F(r['x'][j])for r in train);n=len(values);medians.append(values[n//2]if n%2 else(values[n//2-1]+values[n//2])/2)\n def transform(r):return[F(v)if j in cat else F(int(F(v)>medians[j]))for j,v in enumerate(r['x'])]\n counts={}\n for r in train:\n  key=tuple(transform(r));n,s=counts.get(key,(0,0));counts[key]=(n+1,s+int(r['y']))\n probabilities={k:F(s+1,n+2)for k,(n,s)in counts.items()};fallback=F(sum(int(r['y'])for r in train)+1,len(train)+2);scored=[]\n for i,r in enumerate(raw):\n  eligible=r['role']!='excluded';z=transform(r)if eligible else None;key=None if z is None else tuple(z);score=None if not eligible else probabilities.get(key,fallback)\n  scored.append(dict(id=r['id'],index=i,role=r['role'],group=r['group'],y=None if r['y']is None else F(r['y']),score=score,w=F(1),eligible=eligible,transformedX=z,unseenCell=None if not eligible else key not in probabilities))\n return dict(medians=medians,cells=counts,probabilities=probabilities,fallback=fallback,rows=scored,trainIDs=[r['id']for r in train])\n\n\nimport csv,json,hashlib,argparse,datetime\nfrom pathlib import Path\ndef missing(v):return None if v in ['', '.',None]else v\ndef load_sources(folder):\n def read_csv(name):\n  with (folder/name).open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))\n wb=read_csv('actual64-country-four-indicators-original-2024.csv')\n codes=['NY.GDP.PCAP.KD','NY.GDP.MKTP.KD.ZG','FP.CPI.TOTL.ZG','SP.DYN.LE00.IN']\n lookup={(r['countryISO3'],r['indicatorID']):r for r in wb};country=[]\n for i,iso in enumerate(sorted({r['countryISO3']for r in wb}),1):\n  native=[lookup[iso,c]for c in codes];v=[missing(r['originalValueToken'])for r in native]\n  country.append(dict(id=iso+':2024',sourceRow=i,originalID=iso,x=v[:3],y=None if v[3]is None else str(int(F(v[3])>=80)),group=None if v[0]is None else str(int(F(v[0])>=25000)),nativeTarget=v[3],nativeSourceRows=';'.join(r['sourceRow']for r in native)))\n nls=read_csv('actual3613-NLS-original52-fields-groups-roles.csv');person=[]\n for r in nls:\n  y=missing(r['wage76']);person.append(dict(id='person:'+r['sourceRow'],sourceRow=int(r['sourceRow']),originalID=r['id'],x=[missing(r[k])for k in ['ed76','age76','nearc4']],y=None if y is None else str(int(F(y)>=500)),group=missing(r['black']),nativeTarget=y,nativeSourceRows=r['sourceRow']))\n ch=read_csv('actual3150-churn-original14-fields-groups-roles.csv');company=[]\n for r in ch:\n  company.append(dict(id='customer:'+r['sourceRow'],sourceRow=int(r['sourceRow']),originalID='',x=[missing(r[k])for k in ['Call  Failure','Complains','Subscription  Length','Seconds of Use']],y=missing(r['Churn']),group=missing(r['Tariff Plan']),nativeTarget=missing(r['Churn']),nativeSourceRows=r['sourceRow']))\n assert len(wb)==64 and len(country)==16 and len(nls)==3613 and len(ch)==3150\n assert [int(r['sourceRow'])for r in ch if r['Charge  Amount']=='10']==[474,2174,2274,2374,2674,2924,2974]\n models={}\n for kind,raw,cat,units in [('country',country,[],['constant2015USD/person','annualPercent','annualPercent']),('person',person,[2],['years','years','nativeCategory']),('company',company,[1],['count','nativeCategory','months','seconds'])]:\n  order=sorted(range(len(raw)),key=lambda i:(hashlib.sha256(('ML14-role|'+kind+'|'+raw[i]['id']).encode()).hexdigest(),i))\n  for rank,i in enumerate(order):\n   r=raw[i];r['plannedRole']='test'if rank%5==0 else'validation'if rank%5==1 else'train';r['eligible']=None not in r['x']+[r['y']];r['role']=r['plannedRole']if r['eligible']else'excluded';r['weight']='1'\n  models[kind]=dict(records=raw,categoricalFeatures=cat,featureUnits=units)\n assert sum(r['eligible']for r in person)==3017\n return models\n\ndef exact(v):return ''if v is None else str(v)\ndef approx(v):return ''if v is None else format(float(v),'.17g')\ndef scalar_fields(m,keys):\n out={}\n for k in keys:\n  out[k+'Exact']=exact(m[k]);out[k+'Approx']=approx(m[k])\n return out\nCOUNTS=['mass','positiveTargetMass','negativeTargetMass','predictedPositiveMass','predictedNegativeMass']\nRATES=['prevalence','selectionRate','accuracy','precision','negativePredictiveValue','TPR','FPR','TNR','FNR','F1','balancedAccuracy','Brier','BrierSum','totalCost','meanCost']\nSCENARIOS=[('equal',F(1),F(1)),('miss-five',F(1),F(5)),('alarm-five',F(5),F(1))]\ndef packed(v):\n if isinstance(v,F):return str(v)\n if isinstance(v,dict):return{str(k):packed(x)for k,x in v.items()}\n if isinstance(v,(tuple,list)):return[packed(x)for x in v]\n return v\ndef run_study(source,out):\n out.mkdir(parents=True,exist_ok=True);models=load_sources(source)\n tables={name:[]for name in ['predictions','lineage','fit-medians','fit-cells','validation-candidates','test-metrics','test-curves','calibration-bins','group-metrics','chart-points']}\n studies={};charts=[]\n def point(kind,chart,series,index,x,y,xunit='dimensionless',yunit='dimensionless',role='test',tag=''):\n  tables['chart-points'].append(dict(kind=kind,chart=chart,series=series,index=index,xExact=exact(x),xApprox=approx(x),yExact=exact(y),yApprox=approx(y),xUnit=xunit,yUnit=yunit,role=role,tag=tag))\n for kind,M in models.items():\n  fit=actual_model(M);rr=fit['rows'];native=M['records'];test=scoped(rr,'test');cv=curves(test);cal=calibrate(test,[F(0),F(1,5),F(2,5),F(3,5),F(4,5),F(1)]);scenarios=[]\n  for i,r in enumerate(rr):\n   n=native[i];reason=''if r['eligible']else'required-X-or-Y-missing'\n   tables['predictions'].append(dict(kind=kind,id=r['id'],sourceRow=n['sourceRow'],originalID=n['originalID'],plannedRole=n['plannedRole'],role=r['role'],group=''if r['group']is None else r['group'],eligible=int(r['eligible']),targetExact=exact(r['y']),probabilityExact=exact(r['score']),probabilityApprox=approx(r['score']),unseenCell=''if r['unseenCell']is None else int(r['unseenCell']),transformedX=''if r['transformedX']is None else'|'.join(map(str,r['transformedX'])),reason=reason))\n   tables['lineage'].append(dict(kind=kind,id=r['id'],sourceRow=n['sourceRow'],originalID=n['originalID'],nativeSourceRows=n['nativeSourceRows'],rawX='|'.join(''if x is None else x for x in n['x']),nativeTarget=''if n['nativeTarget']is None else n['nativeTarget'],derivedTarget=exact(r['y']),nativeGroup=''if n['group']is None else n['group'],plannedRole=n['plannedRole'],role=r['role'],eligible=int(r['eligible']),analyticalMass='1',reason=reason))\n  for j,v in enumerate(fit['medians']):tables['fit-medians'].append(dict(kind=kind,feature=j,categorical=int(j in M['categoricalFeatures']),fitRows=len(fit['trainIDs']),medianExact=exact(v),medianApprox=approx(v),unit=M['featureUnits'][j]))\n  for key,(mass,pos)in fit['cells'].items():tables['fit-cells'].append(dict(kind=kind,cell='|'.join(map(str,key)),trainingRows=mass,positiveRows=pos,probabilityExact=exact(fit['probabilities'][key]),probabilityApprox=approx(fit['probabilities'][key]),fallbackExact=exact(fit['fallback']),fallbackApprox=approx(fit['fallback'])))\n  for j,p in enumerate(cv['points']):\n   policy=p['policy'];tables['test-curves'].append(dict(kind=kind,point=j,policy=policy if isinstance(policy,str)else'threshold',thresholdExact=''if isinstance(policy,str)else exact(policy),thresholdApprox=''if isinstance(policy,str)else approx(policy),**scalar_fields(p,['TP','FP','FN','TN','TPR','FPR','precision','recall'])))\n   point(kind,'roc','ROC',j,p['FPR'],p['TPR']);point(kind,'pr','PR-observed',j,p['recall'],p['precision'])\n  for b in cal['bins']:\n   tables['calibration-bins'].append(dict(kind=kind,bin=b['index'],leftExact=str(F(b['index'],5)),rightExact=str(F(b['index']+1,5)),rightClosed=int(b['index']==4),rows=b['rows'],ids=';'.join(str(i)for i in b['ids']),**scalar_fields(b,['mass','meanPrediction','eventRate','gap','absoluteGap','scoreVariance','scoreTargetCovariance','withinBinCorrection'])))\n   point(kind,'reliability','Binary event rate',b['index'],b['meanPrediction'],b['eventRate'],tag='rows='+str(b['rows']))\n  for j,r in enumerate(test):\n   point(kind,'test-scores','Training-fitted probability',j,F(j+1),r['score'],'test-row position','probability',tag=r['id'])\n   point(kind,'test-scores','Observed Y',j,F(j+1),r['y'],'test-row position','binary target',tag=r['id'])\n  for name,fp,fn in SCENARIOS:\n   choice=choose(rr,{},(fp,fn));gm=groups(test,choice['selectedPolicy'],(fp,fn));scenarios.append(dict(name=name,costs=dict(falsePositive=fp,falseNegative=fn),selection=choice,groups=gm));ev=choice['evaluation']\n   for c in choice['candidates']:\n    policy=c['policy'];mm=c['metrics'];tables['validation-candidates'].append(dict(kind=kind,scenario=name,candidate=c['index'],selected=int(c['index']==choice['selectedIndex']),policy=policy if isinstance(policy,str)else'threshold',thresholdExact=''if isinstance(policy,str)else exact(policy),thresholdApprox=''if isinstance(policy,str)else approx(policy),feasible=int(c['feasible']),reasons=';'.join(c['reasons']),**{k+'Exact':str(v)for k,v in mm['confusion'].items()},**scalar_fields(mm,COUNTS+['TPR','FPR','precision','meanCost','totalCost'])))\n    point(kind,'validation-cost',name,c['index'],F(c['index']),mm['meanCost'],'candidate index','hypothetical cost units/mass','validation',tag=exact(policy))\n   mm={**ev,**ev['confusion'],**{k:cv[k]for k in ['ROC_AUC','averagePrecision','PRTrapezoidWithInitialPrecisionOne']},**{k:cal[k]for k in ['ECE','reliability','resolution','uncertainty','withinBinCorrection','BrierIdentityResidual']}}\n   for key in ['TP','FP','FN','TN']+COUNTS+RATES+['ROC_AUC','averagePrecision','PRTrapezoidWithInitialPrecisionOne','ECE','reliability','resolution','uncertainty','withinBinCorrection','BrierIdentityResidual']:\n    unit='rows'if key in ['TP','FP','FN','TN']+COUNTS else'hypothetical cost units'if key=='totalCost'else'hypothetical cost units/mass'if key=='meanCost'else'sum squared-probability loss'if key=='BrierSum'else'dimensionless'\n    tables['test-metrics'].append(dict(kind=kind,scenario=name,metric=key,valueExact=exact(mm[key]),valueApprox=approx(mm[key]),unit=unit))\n   allg=[('overall','all',gm['overall'])]+[('known',str(g['group']),g['metrics'])for g in gm['groups']]+[('unknown','',gm['unknownGroup'])]\n   for j,(typ,token,g)in enumerate(allg):\n    tables['group-metrics'].append(dict(kind=kind,scenario=name,groupType=typ,groupToken=token,retainedRows=g.get('retainedRows',sum((r['group']==token)if typ=='known'else(r['group']is None)if typ=='unknown'else True for r in test)),**{k+'Exact':str(v)for k,v in g['confusion'].items()},**scalar_fields(g,COUNTS+RATES)))\n    if typ=='known':point(kind,'group-TPR',name,j-1,F(j-1),g['TPR'],'declared group position','TPR',tag=token)\n  studies[kind]=dict(kind=kind,rows=len(native),eligibleRows=sum(r['eligible']for r in rr),trainingIDs=fit['trainIDs'],fitMedians=fit['medians'],fitCells=[dict(cell=list(k),mass=n,positive=s,probability=fit['probabilities'][k])for k,(n,s)in fit['cells'].items()],fallback=fit['fallback'],scenarios=scenarios,testCurves=cv,testCalibration=cal,rowsScored=rr)\n files=[]\n for name,rows in tables.items():\n  p=out/('computed-'+name+'.csv')\n  with p.open('w',encoding='utf8',newline='')as f:w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows)\n  files.append(dict(file=p.name,rows=len(rows),columns=len(rows[0]),bodyFields=len(rows)*len(rows[0]),sha256=hashlib.sha256(p.read_bytes()).hexdigest()))\n (out/'study.json').write_text(json.dumps(packed(studies),ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\n sourceFiles=[source/n for n in ['actual64-country-four-indicators-original-2024.csv','actual3613-NLS-original52-fields-groups-roles.csv','actual3150-churn-original14-fields-groups-roles.csv']]\n provenance=dict(chapter='ML-14',arithmetic='Python stdlib Fraction exact finite values from original decimal strings; binary64 valueApprox is display only.',inputs=[dict(file=p.name,sha256=hashlib.sha256(p.read_bytes()).hexdigest())for p in sourceFiles],priorEngineModelsScoresOrComputedFilesRead=False,roleRule=\"SHA256('ML14-role|'+kind+'|'+ID),rankmod5=0test/1validation/others train before eligibility\",costs='Hypothetical1/1,1/5,5/1; no causal intervention returns',files=files,observations={k:dict(sourceRows=v['rows'],eligibleRows=v['eligibleRows'],trainingRows=len(v['trainingIDs']))for k,v in studies.items()})\n (out/'provenance.json').write_text(json.dumps(provenance,ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\n print(json.dumps(dict(status='PASS standalone completed',files=len(files),bodyFields=sum(f['bodyFields']for f in files),observations=provenance['observations'])))\n\n# Fixed declared examples: full web budget/option validation is not reproduced.\nfrom html import escape\nimport textwrap\ndef validated_rows(raw):\n for r in raw:\n  assert F(str(r.get('weight','1')))>=0,'negative analytical mass'\n  assert r['score']is None or 0<=F(str(r['score']))<=1,'score outside zero/one'\n  assert r['y']is None or F(str(int(r['y']))if isinstance(r['y'],bool)else str(r['y']))in [0,1],'binary target required'\n return read(raw)\ndef serial(v):\n if isinstance(v,F):return dict(exactFraction=str(v),value=float(v))\n if isinstance(v,(list,tuple)):return[serial(x)for x in v]\n if isinstance(v,dict):return{k:serial(x)for k,x in v.items()}\n return v\ndef fixed_svg(path,points,title,xlabel,ylabel,legend):\n use=[p for p in points if p['xExact']!=''and p['yExact']!=''];xs=[float(F(p['xExact']))for p in use];ys=[float(F(p['yExact']))for p in use]\n xmin=min(xs,default=0);xmax=max(xs,default=1);ymin=min([0]+ys);ymax=max([0]+ys)\n if xmin==xmax:xmin-=.5;xmax+=.5\n if ymin==ymax:ymax=ymin+1\n X=lambda v:85+(float(v)-xmin)/(xmax-xmin)*480;Y=lambda v:278-(float(v)-ymin)/(ymax-ymin)*175\n s='<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"620\" height=\"360\" viewBox=\"0 0 620 360\"><rect width=\"620\" height=\"360\" fill=\"white\"/><g font-family=\"Arial, sans-serif\" font-size=\"13\" fill=\"#17324d\">'\n for i,line in enumerate(textwrap.wrap(title,width=65)):s+='<text x=\"25\" y=\"'+str(24+i*18)+'\">'+escape(line)+'</text>'\n colors=['#176b9b','#b85e18','#437e4d']\n for i,label in enumerate(legend):s+='<circle cx=\"'+str(30+i*250)+'\" cy=\"76\" r=\"4\" fill=\"'+colors[i%3]+'\"/><text x=\"'+str(42+i*250)+'\" y=\"80\">'+escape(label)+'</text>'\n s+='<path d=\"M85 98V278H575\" fill=\"none\" stroke=\"#52677d\"/><text text-anchor=\"middle\" x=\"325\" y=\"338\">'+escape(xlabel)+'</text><text text-anchor=\"middle\" transform=\"translate(21,190) rotate(-90)\">'+escape(ylabel)+'</text>'\n for i in range(5):\n  xx=xmin+(xmax-xmin)*i/4;yy=ymin+(ymax-ymin)*i/4;s+='<text text-anchor=\"middle\" x=\"'+format(X(xx),'.9g')+'\" y=\"305\">'+format(xx,'.4g')+'</text><text text-anchor=\"end\" x=\"77\" y=\"'+format(Y(yy)+4,'.9g')+'\">'+format(yy,'.4g')+'</text>'\n for p in use:s+='<circle cx=\"'+format(X(F(p['xExact'])),'.9g')+'\" cy=\"'+format(Y(F(p['yExact'])),'.9g')+'\" r=\"3\" fill=\"'+colors[p['series']%3]+'\"/>'\n path.write_text(s+'</g></svg>',encoding='utf8')\ndef fixed_run():\n ap=argparse.ArgumentParser();ap.add_argument('--out',type=Path,default=Path('results'));ap.add_argument('--data-dir',type=Path,default=Path(__file__).resolve().parent.parent/'ml14-sources');args=ap.parse_args();args.out.mkdir(parents=True,exist_ok=True)\n api=FIXED['api'];a=FIXED['args'];summary=[];points=[];xlabel='Declared index';ylabel='Value';legend=['Declared result']\n def metric(name,v,unit='dimensionless'):\n  q=None if v is None else v if isinstance(v,F)else F(v);summary.append(dict(metric=name,value='undefined'if q is None else format(float(q),'.9g'),exactValue=''if q is None else str(q),unit=unit,defined=int(q is not None)))\n def pt(i,x,y,ident='',series=0):\n  points.append(dict(series=series,index=i,xExact=''if x is None else str(F(x)),x='undefined'if x is None else format(float(x),'.9g'),yExact=''if y is None else str(F(y)),y='undefined'if y is None else format(float(y),'.9g'),id=str(ident)))\n if api=='realdata':\n  models=load_sources(args.data_dir);model=models[a['kind']];fit=actual_model(model);rr=fit['rows'];test=scoped(rr,'test');scenarios=[]\n  for name,fp,fn in SCENARIOS:\n   c=choose(rr,{},(fp,fn));scenarios.append(dict(name=name,selection=c));metric(name+'Threshold',c['selectedPolicy']);metric(name+'TestCost',c['evaluation']['meanCost'],'hypothetical cost units/mass')\n  cv=curves(test);cal=calibrate(test,[F(0),F(1,5),F(2,5),F(3,5),F(4,5),F(1)]);metric('testAUC',cv['ROC_AUC']);metric('testAP',cv['averagePrecision']);metric('testBrier',cal['Brier']);metric('eligibleRows',sum(r['eligible']for r in rr),'rows')\n  for i,r in enumerate(test):pt(i,i+1,r['score'],r['id'],0);pt(i,i+1,r['y'],r['id'],1)\n  full=dict(kind=a['kind'],fitMedians=fit['medians'],fitCells=[dict(cell=list(k),mass=n,positive=s,probability=fit['probabilities'][k])for k,(n,s)in fit['cells'].items()],rowsScored=rr,scenarios=scenarios,testCurves=cv,testCalibration=cal);xlabel='Test row, native order';ylabel='Y or probability';legend=['Training-fitted probability','Observed Y']\n else:\n  rr=validated_rows(a['rows']);role=a.get('role','all');frame=scoped(rr,role);cc=cost(a.get('costs'));t=policy(a.get('threshold','1/2'))\n  if api=='metrics':\n   full=metrics(frame,t,cc)\n   for k in ['mass','accuracy','precision','TPR','FPR','F1','Brier','meanCost']:metric(k,full[k],'mass'if k=='mass'else'hypothetical cost units/mass'if k=='meanCost'else'dimensionless')\n   metric('BayesThreshold',full['bayesThreshold'])\n   for i,k in enumerate(['TP','FP','FN','TN']):pt(i,i,full['confusion'][k],k)\n   xlabel='TP / FP / FN / TN positions';ylabel='Analytical mass'\n  elif api=='curves':\n   full=curves(frame)\n   for k in ['ROC_AUC','averagePrecision','PRTrapezoidWithInitialPrecisionOne']:metric(k,full[k])\n   for i,p in enumerate(full['points']):pt(i,p['FPR'],p['TPR'],str(p['policy']))\n   xlabel='False positive rate';ylabel='True positive rate';legend=['Observed ROC operating points']\n  elif api=='choose':\n   full=choose(rr,a,cc);metric('selectedIndex',full['selectedIndex'],'candidate index');metric('minimumCost',None if full['selectedValidation']is None else full['selectedValidation']['meanCost'],'hypothetical cost units/mass');metric('feasible',int(full['selectedIndex']is not None),'indicator')\n   for c in full['candidates']:pt(c['index'],c['index'],c['metrics']['meanCost'],str(c['policy']))\n   xlabel='Validation candidate';ylabel='Assumed cost / mass';legend=['Validation candidate costs']\n  elif api=='calibrate':\n   full=calibrate(frame,[F(str(e))for e in a.get('binEdges',['0','1/5','2/5','3/5','4/5','1'])])\n   for k in ['ECE','Brier','uncertainty','resolution','reliability','withinBinCorrection','BrierIdentityResidual']:metric(k,full[k])\n   for b in full['bins']:pt(b['index'],b['meanPrediction'],b['eventRate'],'bin:'+str(b['index']))\n   xlabel='Bin mean forecast';ylabel='Bin event rate';legend=['Binary-event reliability']\n  elif api=='groups':\n   full=groups(frame,t,cc);metric('overallTPR',full['overall']['TPR']);metric('TPRGap',full['gaps']['TPR']['value']);metric('precisionGap',full['gaps']['precision']['value']);metric('unknownMass',full['unknownGroup']['mass'],'mass');metric('partitionResidual',full['partitionMassResidual'],'mass')\n   for i,g in enumerate(full['groups']):pt(i,i,g['metrics']['TPR'],str(g['group']))\n   xlabel='Declared group position';ylabel='True positive rate';legend=['Known-group TPR']\n  else:raise ValueError('unknown fixed API')\n def csvout(name,rows):\n  with(args.out/name).open('w',encoding='utf8',newline='')as f:w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows)\n csvout('summary.csv',summary);csvout('plot-points.csv',points);fixed_svg(args.out/'plot.svg',points,FIXED['title'],xlabel,ylabel,legend)\n (args.out/'full.json').write_text(json.dumps(dict(api=api,variant=FIXED['variant'],input=FIXED['args'],arithmetic='Python standard-library Fraction, declared fixed example; full web validator/budgets not reproduced',result=serial(full)),ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\n print(json.dumps(dict(api=api,variant=FIXED['variant'],summaryMetrics=len(summary),plotSlots=len(points))))\n\nFIXED={'api': 'metrics', 'variant': 'weighted', 'args': {'rows': [{'id': 'a', 'score': '.9', 'y': 1, 'group': 'A'}, {'id': 'b', 'score': '.8', 'y': 1, 'group': 'A'}, {'id': 'c', 'score': '.8', 'y': 0, 'group': 'A', 'weight': '2'}, {'id': 'd', 'score': '.6', 'y': 0, 'group': 'B'}, {'id': 'e', 'score': '.4', 'y': 1, 'group': 'B'}, {'id': 'f', 'score': '.1', 'y': 0, 'group': 'B'}], 'threshold': '.8'}, 'title': 'Double only the tied negative card mass'}\nif __name__=='__main__':fixed_run()\n",
        "input": {
          "rows": [
            {
              "id": "a",
              "score": ".9",
              "y": 1,
              "group": "A"
            },
            {
              "id": "b",
              "score": ".8",
              "y": 1,
              "group": "A"
            },
            {
              "id": "c",
              "score": ".8",
              "y": 0,
              "group": "A",
              "weight": "2"
            },
            {
              "id": "d",
              "score": ".6",
              "y": 0,
              "group": "B"
            },
            {
              "id": "e",
              "score": ".4",
              "y": 1,
              "group": "B"
            },
            {
              "id": "f",
              "score": ".1",
              "y": 0,
              "group": "B"
            }
          ],
          "threshold": ".8"
        },
        "inputFiles": [],
        "returnCode": 0,
        "expectedFailure": false,
        "stdout": "{\"api\": \"metrics\", \"variant\": \"weighted\", \"summaryMetrics\": 9, \"plotSlots\": 4}\n",
        "stderr": "",
        "summary": {
          "mass": "7",
          "accuracy": "0.571428571",
          "precision": "0.5",
          "TPR": "0.666666667",
          "FPR": "0.5",
          "F1": "0.571428571",
          "Brier": "0.294285714",
          "meanCost": "0.428571429",
          "BayesThreshold": "0.5"
        },
        "summaryRows": [
          {
            "metric": "mass",
            "value": "7",
            "exactValue": "7",
            "unit": "mass",
            "defined": "1"
          },
          {
            "metric": "accuracy",
            "value": "0.571428571",
            "exactValue": "4/7",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "precision",
            "value": "0.5",
            "exactValue": "1/2",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "TPR",
            "value": "0.666666667",
            "exactValue": "2/3",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "FPR",
            "value": "0.5",
            "exactValue": "1/2",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "F1",
            "value": "0.571428571",
            "exactValue": "4/7",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "Brier",
            "value": "0.294285714",
            "exactValue": "103/350",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "meanCost",
            "value": "0.428571429",
            "exactValue": "3/7",
            "unit": "hypothetical cost units/mass",
            "defined": "1"
          },
          {
            "metric": "BayesThreshold",
            "value": "0.5",
            "exactValue": "1/2",
            "unit": "dimensionless",
            "defined": "1"
          }
        ],
        "plotPoints": [
          {
            "series": "0",
            "index": "0",
            "xExact": "0",
            "x": "0",
            "yExact": "2",
            "y": "2",
            "id": "TP"
          },
          {
            "series": "0",
            "index": "1",
            "xExact": "1",
            "x": "1",
            "yExact": "2",
            "y": "2",
            "id": "FP"
          },
          {
            "series": "0",
            "index": "2",
            "xExact": "2",
            "x": "2",
            "yExact": "1",
            "y": "1",
            "id": "FN"
          },
          {
            "series": "0",
            "index": "3",
            "xExact": "3",
            "x": "3",
            "yExact": "2",
            "y": "2",
            "id": "TN"
          }
        ],
        "plotFile": "ml14-fixed-results/metrics-weighted-python/plot.svg",
        "plotSHA256": "6e01f4e91ac61539fef3bb0d70fc1b496672353b8e08680a31004f7d1a4745b9",
        "files": [
          {
            "file": "ml14-fixed-results/metrics-weighted-python/full.json",
            "sha256": "daaa218bd9d68892e5caab2074a7b35c07b5780a794c257f29dc2688ebbcc104",
            "bytes": 4905
          },
          {
            "file": "ml14-fixed-results/metrics-weighted-python/plot-points.csv",
            "sha256": "e3403cbfb549667b070a2c7d9040d312231f622f9176e7242c2b54a8724bc44c",
            "bytes": 99
          },
          {
            "file": "ml14-fixed-results/metrics-weighted-python/plot.svg",
            "sha256": "6e01f4e91ac61539fef3bb0d70fc1b496672353b8e08680a31004f7d1a4745b9",
            "bytes": 1286
          },
          {
            "file": "ml14-fixed-results/metrics-weighted-python/summary.csv",
            "sha256": "a78b2dcf7094c9c6eb41d1fc9347b6e07b9494b06b187b3ed2131bcb440d4715",
            "bytes": 374
          }
        ],
        "scope": "Actually executed standalone fixed example, Python exact Fraction versus base-R binary64. Approximate R residuals retained; not universal exact arithmetic/web validation/native UI. Source programs read factual3CSV only."
      },
      "zero-cost": {
        "api": "metrics",
        "variant": "zero-cost",
        "language": "python",
        "title": "Both hypothetical costs zero; Bayes ratio undefined",
        "codeFile": "ml14-code/metrics-zero-cost.py",
        "codeSHA256": "0ef4e27ae551ef9755d8a6dba1e30471a0249a33e0f81686ff1fdce456f6f577",
        "code": "#!/usr/bin/env python3\n\"\"\"ML14 standalone exact finite study, Python standard library only.\nInputs: only the three retained factual source CSVs below.\nDerived role/target/group/eligibility columns in those CSVs are NOT inputs.\nRebuilds SHA256 roles, train-only medians/cell scores, validation thresholds,\ntest curves, binary-event reliability and descriptive group ledgers.\nCosts 1/1,1/5,5/1 are hypothetical units, not measured intervention returns.\nThis is author public reproduction, not independent scientific review.\n\"\"\"\n\"\"\"Author Fraction reference, separate from product JavaScript; not independent peer.\"\"\"\nfrom fractions import Fraction as F\nfrom collections import Counter,defaultdict\ndef read(raw):\n rows=[]\n for i,r in enumerate(raw):\n  s=None if r['score']is None else F(str(r['score']));y=None if r['y']is None else F(int(r['y']))if isinstance(r['y'],bool)else F(str(r['y']));w=F(str(r.get('weight','1')));role=r.get('role','evaluation')\n  rows.append(dict(id=r['id'],index=i,score=s,y=y,w=w,role=role,group=r.get('group'),eligible=s is not None and y is not None and w>0 and role!='excluded'))\n return rows\ndef scoped(rows,role='all'):return rows if role=='all'else[r for r in rows if r['role']==role]\ndef divide(n,d):return None if not d else n/d\ndef policy(v):return v if v in ['always-negative','always-positive']else F(str(v))\ndef positive(p,s):return p=='always-positive'if isinstance(p,str)else s>=p\ndef cost(a=None):\n a={}if a is None else a;fp=F(str(a.get('falsePositive','1')));fn=F(str(a.get('falseNegative','1')));return fp,fn\ndef metrics(rows,threshold=F(1,2),cc=(F(1),F(1))):\n counts=dict(TP=F(0),FP=F(0),FN=F(0),TN=F(0));brier=F(0);pred=[]\n for r in rows:\n  if not r['eligible']:pred.append(dict(id=r['id'],index=r['index'],eligible=False,decision=None,probability=None,Brier=None));continue\n  yes=positive(threshold,r['score']);cell=('T'if yes==bool(r['y'])else'F')+('P'if yes else'N');counts[cell]+=r['w'];loss=(r['score']-r['y'])**2;brier+=r['w']*loss;pred.append(dict(id=r['id'],index=r['index'],eligible=True,decision=int(yes),probability=r['score'],Brier=loss))\n TP,FP,FN,TN=[counts[k]for k in ['TP','FP','FN','TN']];P=TP+FN;N=TN+FP;mass=P+N;PP=TP+FP;PN=TN+FN;TPR=divide(TP,P);TNR=divide(TN,N);total=FP*cc[0]+FN*cc[1]\n return dict(confusion=counts,mass=mass,positiveTargetMass=P,negativeTargetMass=N,predictedPositiveMass=PP,predictedNegativeMass=PN,prevalence=divide(P,mass),selectionRate=divide(PP,mass),accuracy=divide(TP+TN,mass),precision=divide(TP,PP),negativePredictiveValue=divide(TN,PN),TPR=TPR,FPR=divide(FP,N),TNR=TNR,FNR=divide(FN,P),F1=divide(2*TP,2*TP+FP+FN),balancedAccuracy=None if TPR is None or TNR is None else(TPR+TNR)/2,Brier=divide(brier,mass),BrierSum=brier,totalCost=total,meanCost=divide(total,mass),predictions=pred,bayesThreshold=divide(cc[0],sum(cc)))\ndef curves(rows):\n use=[r for r in rows if r['eligible']];pos=Counter();neg=Counter()\n for r in use:(pos if r['y']else neg)[r['score']]+=r['w']\n P=sum(pos.values(),F(0));N=sum(neg.values(),F(0));pairs=F(0)\n for a,wa in pos.items():\n  for b,wb in neg.items():pairs+=wa*wb*(F(1)if a>b else F(1,2)if a==b else F(0))\n thresholds=['always-negative']+sorted({r['score']for r in use},reverse=True);points=[];AP=F(0);trap=F(0);lastR=F(0);lastP=F(1)\n for i,p in enumerate(thresholds):\n  m=metrics(rows,p);points.append(dict(policy=p,TP=m['confusion']['TP'],FP=m['confusion']['FP'],FN=m['confusion']['FN'],TN=m['confusion']['TN'],TPR=m['TPR'],FPR=m['FPR'],precision=m['precision'],recall=m['TPR']))\n  if i and P:\n   R=m['TPR'];PP=m['precision'];AP+=(R-lastR)*PP;trap+=(R-lastR)*(PP+lastP)/2;lastR=R;lastP=PP\n return dict(positiveMass=P,negativeMass=N,ROC_AUC=divide(pairs,P*N),weightedConcordantPlusHalfTiedMass=pairs,averagePrecision=AP if P else None,PRTrapezoidWithInitialPrecisionOne=trap if P else None,points=points)\ndef choose(rows,a,cc):\n sr=a.get('selectionRole','validation');er=a.get('evaluationRole','test');rr=scoped(rows,sr);thresholds=[policy(t)for t in a['thresholds']]if'thresholds'in a else['always-negative']+sorted({r['score']for r in rr if r['eligible']},reverse=True)\n candidates=[]\n for i,p in enumerate(thresholds):\n  m=metrics(rr,p,cc);reasons=[]\n  if'minTPR'in a and(m['TPR']is None or m['TPR']<F(str(a['minTPR']))):reasons.append('TPR-undefined'if m['TPR']is None else'below-minTPR')\n  if'maxFPR'in a and(m['FPR']is None or m['FPR']>F(str(a['maxFPR']))):reasons.append('FPR-undefined'if m['FPR']is None else'above-maxFPR')\n  candidates.append(dict(index=i,policy=p,metrics=m,feasible=not reasons,reasons=reasons))\n eligible=[c for c in candidates if c['feasible']];best=min(eligible,key=lambda c:(c['metrics']['meanCost'],c['index']))if eligible else None\n return dict(selectedIndex=None if best is None else best['index'],selectedPolicy=None if best is None else best['policy'],candidates=candidates,selectedValidation=None if best is None else best['metrics'],evaluation=None if best is None or er=='none'else metrics(scoped(rows,er),best['policy'],cc),selectionIDs=[r['id']for r in rr if r['eligible']])\ndef calibrate(rows,ee):\n buckets=[[]for _ in range(len(ee)-1)]\n for r in rows:\n  if not r['eligible']:continue\n  j=next((i for i in range(len(ee)-1)if r['score']<ee[i+1]),len(ee)-2);buckets[j].append(r)\n mass=sum((r['w']for r in rows if r['eligible']),F(0));P=sum((r['w']*r['y']for r in rows if r['eligible']),F(0));pi=divide(P,mass);Brier=None if not mass else sum((r['w']*(r['score']-r['y'])**2 for r in rows if r['eligible']),F(0))/mass;ECE=F(0);reliability=F(0);resolution=F(0);correction=F(0);bins=[]\n for i,rr in enumerate(buckets):\n  w=sum((r['w']for r in rr),F(0));mp=None if not w else sum((r['w']*r['score']for r in rr),F(0))/w;o=None if not w else sum((r['w']*r['y']for r in rr),F(0))/w\n  variance=None if not w else sum((r['w']*(r['score']-mp)**2 for r in rr),F(0))/w\n  covariance=None if not w else sum((r['w']*(r['score']-mp)*(r['y']-o)for r in rr),F(0))/w\n  bc=None if not w else variance-2*covariance;gap=None if not w else mp-o\n  bins.append(dict(index=i,rows=len(rr),mass=w,meanPrediction=mp,eventRate=o,gap=gap,absoluteGap=None if gap is None else abs(gap),scoreVariance=variance,scoreTargetCovariance=covariance,withinBinCorrection=bc,ids=[r['id']for r in rr]))\n  if w:\n   share=w/mass;ECE+=share*abs(gap);reliability+=share*gap**2;resolution+=share*(o-pi)**2;correction+=share*bc\n uncertainty=None if pi is None else pi*(1-pi);residual=None if Brier is None else Brier-(uncertainty-resolution+reliability+correction)\n return dict(mass=mass,prevalence=pi,Brier=Brier,ECE=ECE if mass else None,reliability=reliability if mass else None,resolution=resolution if mass else None,uncertainty=uncertainty,withinBinCorrection=correction if mass else None,BrierIdentityResidual=residual,bins=bins)\ndef typed(v):return type(v).__name__,v\ndef groups(rows,p,cc):\n bins={}\n for r in rows:\n  if r['group']is not None:bins.setdefault(typed(r['group']),[]).append(r)\n gm=[dict(group=rr[0]['group'],metrics=metrics(rr,p,cc))for rr in bins.values()];overall=metrics(rows,p,cc);unknown=metrics([r for r in rows if r['group']is None],p,cc);gaps={}\n for key in ['prevalence','selectionRate','TPR','FPR','precision','accuracy','meanCost']:\n  positive=[g for g in gm if g['metrics']['mass']>0];undefined=[g['group']for g in positive if g['metrics'][key]is None];vals=[g['metrics'][key]for g in positive if g['metrics'][key]is not None]\n  gaps[key]=dict(value=None if len(positive)<2 or undefined else max(vals)-min(vals),undefinedGroups=undefined,comparedPositiveMassGroups=[g['group']for g in positive])\n return dict(overall=overall,groups=gm,unknownGroup=unknown,gaps=gaps,partitionMassResidual=overall['mass']-unknown['mass']-sum((g['metrics']['mass']for g in gm),F(0)))\ndef actual_model(M):\n raw=M['records'];cat=M['categoricalFeatures'];p=len(raw[0]['x']);train=[r for r in raw if r['role']=='train'];medians=[]\n for j in range(p):\n  if j in cat:medians.append(None);continue\n  values=sorted(F(r['x'][j])for r in train);n=len(values);medians.append(values[n//2]if n%2 else(values[n//2-1]+values[n//2])/2)\n def transform(r):return[F(v)if j in cat else F(int(F(v)>medians[j]))for j,v in enumerate(r['x'])]\n counts={}\n for r in train:\n  key=tuple(transform(r));n,s=counts.get(key,(0,0));counts[key]=(n+1,s+int(r['y']))\n probabilities={k:F(s+1,n+2)for k,(n,s)in counts.items()};fallback=F(sum(int(r['y'])for r in train)+1,len(train)+2);scored=[]\n for i,r in enumerate(raw):\n  eligible=r['role']!='excluded';z=transform(r)if eligible else None;key=None if z is None else tuple(z);score=None if not eligible else probabilities.get(key,fallback)\n  scored.append(dict(id=r['id'],index=i,role=r['role'],group=r['group'],y=None if r['y']is None else F(r['y']),score=score,w=F(1),eligible=eligible,transformedX=z,unseenCell=None if not eligible else key not in probabilities))\n return dict(medians=medians,cells=counts,probabilities=probabilities,fallback=fallback,rows=scored,trainIDs=[r['id']for r in train])\n\n\nimport csv,json,hashlib,argparse,datetime\nfrom pathlib import Path\ndef missing(v):return None if v in ['', '.',None]else v\ndef load_sources(folder):\n def read_csv(name):\n  with (folder/name).open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))\n wb=read_csv('actual64-country-four-indicators-original-2024.csv')\n codes=['NY.GDP.PCAP.KD','NY.GDP.MKTP.KD.ZG','FP.CPI.TOTL.ZG','SP.DYN.LE00.IN']\n lookup={(r['countryISO3'],r['indicatorID']):r for r in wb};country=[]\n for i,iso in enumerate(sorted({r['countryISO3']for r in wb}),1):\n  native=[lookup[iso,c]for c in codes];v=[missing(r['originalValueToken'])for r in native]\n  country.append(dict(id=iso+':2024',sourceRow=i,originalID=iso,x=v[:3],y=None if v[3]is None else str(int(F(v[3])>=80)),group=None if v[0]is None else str(int(F(v[0])>=25000)),nativeTarget=v[3],nativeSourceRows=';'.join(r['sourceRow']for r in native)))\n nls=read_csv('actual3613-NLS-original52-fields-groups-roles.csv');person=[]\n for r in nls:\n  y=missing(r['wage76']);person.append(dict(id='person:'+r['sourceRow'],sourceRow=int(r['sourceRow']),originalID=r['id'],x=[missing(r[k])for k in ['ed76','age76','nearc4']],y=None if y is None else str(int(F(y)>=500)),group=missing(r['black']),nativeTarget=y,nativeSourceRows=r['sourceRow']))\n ch=read_csv('actual3150-churn-original14-fields-groups-roles.csv');company=[]\n for r in ch:\n  company.append(dict(id='customer:'+r['sourceRow'],sourceRow=int(r['sourceRow']),originalID='',x=[missing(r[k])for k in ['Call  Failure','Complains','Subscription  Length','Seconds of Use']],y=missing(r['Churn']),group=missing(r['Tariff Plan']),nativeTarget=missing(r['Churn']),nativeSourceRows=r['sourceRow']))\n assert len(wb)==64 and len(country)==16 and len(nls)==3613 and len(ch)==3150\n assert [int(r['sourceRow'])for r in ch if r['Charge  Amount']=='10']==[474,2174,2274,2374,2674,2924,2974]\n models={}\n for kind,raw,cat,units in [('country',country,[],['constant2015USD/person','annualPercent','annualPercent']),('person',person,[2],['years','years','nativeCategory']),('company',company,[1],['count','nativeCategory','months','seconds'])]:\n  order=sorted(range(len(raw)),key=lambda i:(hashlib.sha256(('ML14-role|'+kind+'|'+raw[i]['id']).encode()).hexdigest(),i))\n  for rank,i in enumerate(order):\n   r=raw[i];r['plannedRole']='test'if rank%5==0 else'validation'if rank%5==1 else'train';r['eligible']=None not in r['x']+[r['y']];r['role']=r['plannedRole']if r['eligible']else'excluded';r['weight']='1'\n  models[kind]=dict(records=raw,categoricalFeatures=cat,featureUnits=units)\n assert sum(r['eligible']for r in person)==3017\n return models\n\ndef exact(v):return ''if v is None else str(v)\ndef approx(v):return ''if v is None else format(float(v),'.17g')\ndef scalar_fields(m,keys):\n out={}\n for k in keys:\n  out[k+'Exact']=exact(m[k]);out[k+'Approx']=approx(m[k])\n return out\nCOUNTS=['mass','positiveTargetMass','negativeTargetMass','predictedPositiveMass','predictedNegativeMass']\nRATES=['prevalence','selectionRate','accuracy','precision','negativePredictiveValue','TPR','FPR','TNR','FNR','F1','balancedAccuracy','Brier','BrierSum','totalCost','meanCost']\nSCENARIOS=[('equal',F(1),F(1)),('miss-five',F(1),F(5)),('alarm-five',F(5),F(1))]\ndef packed(v):\n if isinstance(v,F):return str(v)\n if isinstance(v,dict):return{str(k):packed(x)for k,x in v.items()}\n if isinstance(v,(tuple,list)):return[packed(x)for x in v]\n return v\ndef run_study(source,out):\n out.mkdir(parents=True,exist_ok=True);models=load_sources(source)\n tables={name:[]for name in ['predictions','lineage','fit-medians','fit-cells','validation-candidates','test-metrics','test-curves','calibration-bins','group-metrics','chart-points']}\n studies={};charts=[]\n def point(kind,chart,series,index,x,y,xunit='dimensionless',yunit='dimensionless',role='test',tag=''):\n  tables['chart-points'].append(dict(kind=kind,chart=chart,series=series,index=index,xExact=exact(x),xApprox=approx(x),yExact=exact(y),yApprox=approx(y),xUnit=xunit,yUnit=yunit,role=role,tag=tag))\n for kind,M in models.items():\n  fit=actual_model(M);rr=fit['rows'];native=M['records'];test=scoped(rr,'test');cv=curves(test);cal=calibrate(test,[F(0),F(1,5),F(2,5),F(3,5),F(4,5),F(1)]);scenarios=[]\n  for i,r in enumerate(rr):\n   n=native[i];reason=''if r['eligible']else'required-X-or-Y-missing'\n   tables['predictions'].append(dict(kind=kind,id=r['id'],sourceRow=n['sourceRow'],originalID=n['originalID'],plannedRole=n['plannedRole'],role=r['role'],group=''if r['group']is None else r['group'],eligible=int(r['eligible']),targetExact=exact(r['y']),probabilityExact=exact(r['score']),probabilityApprox=approx(r['score']),unseenCell=''if r['unseenCell']is None else int(r['unseenCell']),transformedX=''if r['transformedX']is None else'|'.join(map(str,r['transformedX'])),reason=reason))\n   tables['lineage'].append(dict(kind=kind,id=r['id'],sourceRow=n['sourceRow'],originalID=n['originalID'],nativeSourceRows=n['nativeSourceRows'],rawX='|'.join(''if x is None else x for x in n['x']),nativeTarget=''if n['nativeTarget']is None else n['nativeTarget'],derivedTarget=exact(r['y']),nativeGroup=''if n['group']is None else n['group'],plannedRole=n['plannedRole'],role=r['role'],eligible=int(r['eligible']),analyticalMass='1',reason=reason))\n  for j,v in enumerate(fit['medians']):tables['fit-medians'].append(dict(kind=kind,feature=j,categorical=int(j in M['categoricalFeatures']),fitRows=len(fit['trainIDs']),medianExact=exact(v),medianApprox=approx(v),unit=M['featureUnits'][j]))\n  for key,(mass,pos)in fit['cells'].items():tables['fit-cells'].append(dict(kind=kind,cell='|'.join(map(str,key)),trainingRows=mass,positiveRows=pos,probabilityExact=exact(fit['probabilities'][key]),probabilityApprox=approx(fit['probabilities'][key]),fallbackExact=exact(fit['fallback']),fallbackApprox=approx(fit['fallback'])))\n  for j,p in enumerate(cv['points']):\n   policy=p['policy'];tables['test-curves'].append(dict(kind=kind,point=j,policy=policy if isinstance(policy,str)else'threshold',thresholdExact=''if isinstance(policy,str)else exact(policy),thresholdApprox=''if isinstance(policy,str)else approx(policy),**scalar_fields(p,['TP','FP','FN','TN','TPR','FPR','precision','recall'])))\n   point(kind,'roc','ROC',j,p['FPR'],p['TPR']);point(kind,'pr','PR-observed',j,p['recall'],p['precision'])\n  for b in cal['bins']:\n   tables['calibration-bins'].append(dict(kind=kind,bin=b['index'],leftExact=str(F(b['index'],5)),rightExact=str(F(b['index']+1,5)),rightClosed=int(b['index']==4),rows=b['rows'],ids=';'.join(str(i)for i in b['ids']),**scalar_fields(b,['mass','meanPrediction','eventRate','gap','absoluteGap','scoreVariance','scoreTargetCovariance','withinBinCorrection'])))\n   point(kind,'reliability','Binary event rate',b['index'],b['meanPrediction'],b['eventRate'],tag='rows='+str(b['rows']))\n  for j,r in enumerate(test):\n   point(kind,'test-scores','Training-fitted probability',j,F(j+1),r['score'],'test-row position','probability',tag=r['id'])\n   point(kind,'test-scores','Observed Y',j,F(j+1),r['y'],'test-row position','binary target',tag=r['id'])\n  for name,fp,fn in SCENARIOS:\n   choice=choose(rr,{},(fp,fn));gm=groups(test,choice['selectedPolicy'],(fp,fn));scenarios.append(dict(name=name,costs=dict(falsePositive=fp,falseNegative=fn),selection=choice,groups=gm));ev=choice['evaluation']\n   for c in choice['candidates']:\n    policy=c['policy'];mm=c['metrics'];tables['validation-candidates'].append(dict(kind=kind,scenario=name,candidate=c['index'],selected=int(c['index']==choice['selectedIndex']),policy=policy if isinstance(policy,str)else'threshold',thresholdExact=''if isinstance(policy,str)else exact(policy),thresholdApprox=''if isinstance(policy,str)else approx(policy),feasible=int(c['feasible']),reasons=';'.join(c['reasons']),**{k+'Exact':str(v)for k,v in mm['confusion'].items()},**scalar_fields(mm,COUNTS+['TPR','FPR','precision','meanCost','totalCost'])))\n    point(kind,'validation-cost',name,c['index'],F(c['index']),mm['meanCost'],'candidate index','hypothetical cost units/mass','validation',tag=exact(policy))\n   mm={**ev,**ev['confusion'],**{k:cv[k]for k in ['ROC_AUC','averagePrecision','PRTrapezoidWithInitialPrecisionOne']},**{k:cal[k]for k in ['ECE','reliability','resolution','uncertainty','withinBinCorrection','BrierIdentityResidual']}}\n   for key in ['TP','FP','FN','TN']+COUNTS+RATES+['ROC_AUC','averagePrecision','PRTrapezoidWithInitialPrecisionOne','ECE','reliability','resolution','uncertainty','withinBinCorrection','BrierIdentityResidual']:\n    unit='rows'if key in ['TP','FP','FN','TN']+COUNTS else'hypothetical cost units'if key=='totalCost'else'hypothetical cost units/mass'if key=='meanCost'else'sum squared-probability loss'if key=='BrierSum'else'dimensionless'\n    tables['test-metrics'].append(dict(kind=kind,scenario=name,metric=key,valueExact=exact(mm[key]),valueApprox=approx(mm[key]),unit=unit))\n   allg=[('overall','all',gm['overall'])]+[('known',str(g['group']),g['metrics'])for g in gm['groups']]+[('unknown','',gm['unknownGroup'])]\n   for j,(typ,token,g)in enumerate(allg):\n    tables['group-metrics'].append(dict(kind=kind,scenario=name,groupType=typ,groupToken=token,retainedRows=g.get('retainedRows',sum((r['group']==token)if typ=='known'else(r['group']is None)if typ=='unknown'else True for r in test)),**{k+'Exact':str(v)for k,v in g['confusion'].items()},**scalar_fields(g,COUNTS+RATES)))\n    if typ=='known':point(kind,'group-TPR',name,j-1,F(j-1),g['TPR'],'declared group position','TPR',tag=token)\n  studies[kind]=dict(kind=kind,rows=len(native),eligibleRows=sum(r['eligible']for r in rr),trainingIDs=fit['trainIDs'],fitMedians=fit['medians'],fitCells=[dict(cell=list(k),mass=n,positive=s,probability=fit['probabilities'][k])for k,(n,s)in fit['cells'].items()],fallback=fit['fallback'],scenarios=scenarios,testCurves=cv,testCalibration=cal,rowsScored=rr)\n files=[]\n for name,rows in tables.items():\n  p=out/('computed-'+name+'.csv')\n  with p.open('w',encoding='utf8',newline='')as f:w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows)\n  files.append(dict(file=p.name,rows=len(rows),columns=len(rows[0]),bodyFields=len(rows)*len(rows[0]),sha256=hashlib.sha256(p.read_bytes()).hexdigest()))\n (out/'study.json').write_text(json.dumps(packed(studies),ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\n sourceFiles=[source/n for n in ['actual64-country-four-indicators-original-2024.csv','actual3613-NLS-original52-fields-groups-roles.csv','actual3150-churn-original14-fields-groups-roles.csv']]\n provenance=dict(chapter='ML-14',arithmetic='Python stdlib Fraction exact finite values from original decimal strings; binary64 valueApprox is display only.',inputs=[dict(file=p.name,sha256=hashlib.sha256(p.read_bytes()).hexdigest())for p in sourceFiles],priorEngineModelsScoresOrComputedFilesRead=False,roleRule=\"SHA256('ML14-role|'+kind+'|'+ID),rankmod5=0test/1validation/others train before eligibility\",costs='Hypothetical1/1,1/5,5/1; no causal intervention returns',files=files,observations={k:dict(sourceRows=v['rows'],eligibleRows=v['eligibleRows'],trainingRows=len(v['trainingIDs']))for k,v in studies.items()})\n (out/'provenance.json').write_text(json.dumps(provenance,ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\n print(json.dumps(dict(status='PASS standalone completed',files=len(files),bodyFields=sum(f['bodyFields']for f in files),observations=provenance['observations'])))\n\n# Fixed declared examples: full web budget/option validation is not reproduced.\nfrom html import escape\nimport textwrap\ndef validated_rows(raw):\n for r in raw:\n  assert F(str(r.get('weight','1')))>=0,'negative analytical mass'\n  assert r['score']is None or 0<=F(str(r['score']))<=1,'score outside zero/one'\n  assert r['y']is None or F(str(int(r['y']))if isinstance(r['y'],bool)else str(r['y']))in [0,1],'binary target required'\n return read(raw)\ndef serial(v):\n if isinstance(v,F):return dict(exactFraction=str(v),value=float(v))\n if isinstance(v,(list,tuple)):return[serial(x)for x in v]\n if isinstance(v,dict):return{k:serial(x)for k,x in v.items()}\n return v\ndef fixed_svg(path,points,title,xlabel,ylabel,legend):\n use=[p for p in points if p['xExact']!=''and p['yExact']!=''];xs=[float(F(p['xExact']))for p in use];ys=[float(F(p['yExact']))for p in use]\n xmin=min(xs,default=0);xmax=max(xs,default=1);ymin=min([0]+ys);ymax=max([0]+ys)\n if xmin==xmax:xmin-=.5;xmax+=.5\n if ymin==ymax:ymax=ymin+1\n X=lambda v:85+(float(v)-xmin)/(xmax-xmin)*480;Y=lambda v:278-(float(v)-ymin)/(ymax-ymin)*175\n s='<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"620\" height=\"360\" viewBox=\"0 0 620 360\"><rect width=\"620\" height=\"360\" fill=\"white\"/><g font-family=\"Arial, sans-serif\" font-size=\"13\" fill=\"#17324d\">'\n for i,line in enumerate(textwrap.wrap(title,width=65)):s+='<text x=\"25\" y=\"'+str(24+i*18)+'\">'+escape(line)+'</text>'\n colors=['#176b9b','#b85e18','#437e4d']\n for i,label in enumerate(legend):s+='<circle cx=\"'+str(30+i*250)+'\" cy=\"76\" r=\"4\" fill=\"'+colors[i%3]+'\"/><text x=\"'+str(42+i*250)+'\" y=\"80\">'+escape(label)+'</text>'\n s+='<path d=\"M85 98V278H575\" fill=\"none\" stroke=\"#52677d\"/><text text-anchor=\"middle\" x=\"325\" y=\"338\">'+escape(xlabel)+'</text><text text-anchor=\"middle\" transform=\"translate(21,190) rotate(-90)\">'+escape(ylabel)+'</text>'\n for i in range(5):\n  xx=xmin+(xmax-xmin)*i/4;yy=ymin+(ymax-ymin)*i/4;s+='<text text-anchor=\"middle\" x=\"'+format(X(xx),'.9g')+'\" y=\"305\">'+format(xx,'.4g')+'</text><text text-anchor=\"end\" x=\"77\" y=\"'+format(Y(yy)+4,'.9g')+'\">'+format(yy,'.4g')+'</text>'\n for p in use:s+='<circle cx=\"'+format(X(F(p['xExact'])),'.9g')+'\" cy=\"'+format(Y(F(p['yExact'])),'.9g')+'\" r=\"3\" fill=\"'+colors[p['series']%3]+'\"/>'\n path.write_text(s+'</g></svg>',encoding='utf8')\ndef fixed_run():\n ap=argparse.ArgumentParser();ap.add_argument('--out',type=Path,default=Path('results'));ap.add_argument('--data-dir',type=Path,default=Path(__file__).resolve().parent.parent/'ml14-sources');args=ap.parse_args();args.out.mkdir(parents=True,exist_ok=True)\n api=FIXED['api'];a=FIXED['args'];summary=[];points=[];xlabel='Declared index';ylabel='Value';legend=['Declared result']\n def metric(name,v,unit='dimensionless'):\n  q=None if v is None else v if isinstance(v,F)else F(v);summary.append(dict(metric=name,value='undefined'if q is None else format(float(q),'.9g'),exactValue=''if q is None else str(q),unit=unit,defined=int(q is not None)))\n def pt(i,x,y,ident='',series=0):\n  points.append(dict(series=series,index=i,xExact=''if x is None else str(F(x)),x='undefined'if x is None else format(float(x),'.9g'),yExact=''if y is None else str(F(y)),y='undefined'if y is None else format(float(y),'.9g'),id=str(ident)))\n if api=='realdata':\n  models=load_sources(args.data_dir);model=models[a['kind']];fit=actual_model(model);rr=fit['rows'];test=scoped(rr,'test');scenarios=[]\n  for name,fp,fn in SCENARIOS:\n   c=choose(rr,{},(fp,fn));scenarios.append(dict(name=name,selection=c));metric(name+'Threshold',c['selectedPolicy']);metric(name+'TestCost',c['evaluation']['meanCost'],'hypothetical cost units/mass')\n  cv=curves(test);cal=calibrate(test,[F(0),F(1,5),F(2,5),F(3,5),F(4,5),F(1)]);metric('testAUC',cv['ROC_AUC']);metric('testAP',cv['averagePrecision']);metric('testBrier',cal['Brier']);metric('eligibleRows',sum(r['eligible']for r in rr),'rows')\n  for i,r in enumerate(test):pt(i,i+1,r['score'],r['id'],0);pt(i,i+1,r['y'],r['id'],1)\n  full=dict(kind=a['kind'],fitMedians=fit['medians'],fitCells=[dict(cell=list(k),mass=n,positive=s,probability=fit['probabilities'][k])for k,(n,s)in fit['cells'].items()],rowsScored=rr,scenarios=scenarios,testCurves=cv,testCalibration=cal);xlabel='Test row, native order';ylabel='Y or probability';legend=['Training-fitted probability','Observed Y']\n else:\n  rr=validated_rows(a['rows']);role=a.get('role','all');frame=scoped(rr,role);cc=cost(a.get('costs'));t=policy(a.get('threshold','1/2'))\n  if api=='metrics':\n   full=metrics(frame,t,cc)\n   for k in ['mass','accuracy','precision','TPR','FPR','F1','Brier','meanCost']:metric(k,full[k],'mass'if k=='mass'else'hypothetical cost units/mass'if k=='meanCost'else'dimensionless')\n   metric('BayesThreshold',full['bayesThreshold'])\n   for i,k in enumerate(['TP','FP','FN','TN']):pt(i,i,full['confusion'][k],k)\n   xlabel='TP / FP / FN / TN positions';ylabel='Analytical mass'\n  elif api=='curves':\n   full=curves(frame)\n   for k in ['ROC_AUC','averagePrecision','PRTrapezoidWithInitialPrecisionOne']:metric(k,full[k])\n   for i,p in enumerate(full['points']):pt(i,p['FPR'],p['TPR'],str(p['policy']))\n   xlabel='False positive rate';ylabel='True positive rate';legend=['Observed ROC operating points']\n  elif api=='choose':\n   full=choose(rr,a,cc);metric('selectedIndex',full['selectedIndex'],'candidate index');metric('minimumCost',None if full['selectedValidation']is None else full['selectedValidation']['meanCost'],'hypothetical cost units/mass');metric('feasible',int(full['selectedIndex']is not None),'indicator')\n   for c in full['candidates']:pt(c['index'],c['index'],c['metrics']['meanCost'],str(c['policy']))\n   xlabel='Validation candidate';ylabel='Assumed cost / mass';legend=['Validation candidate costs']\n  elif api=='calibrate':\n   full=calibrate(frame,[F(str(e))for e in a.get('binEdges',['0','1/5','2/5','3/5','4/5','1'])])\n   for k in ['ECE','Brier','uncertainty','resolution','reliability','withinBinCorrection','BrierIdentityResidual']:metric(k,full[k])\n   for b in full['bins']:pt(b['index'],b['meanPrediction'],b['eventRate'],'bin:'+str(b['index']))\n   xlabel='Bin mean forecast';ylabel='Bin event rate';legend=['Binary-event reliability']\n  elif api=='groups':\n   full=groups(frame,t,cc);metric('overallTPR',full['overall']['TPR']);metric('TPRGap',full['gaps']['TPR']['value']);metric('precisionGap',full['gaps']['precision']['value']);metric('unknownMass',full['unknownGroup']['mass'],'mass');metric('partitionResidual',full['partitionMassResidual'],'mass')\n   for i,g in enumerate(full['groups']):pt(i,i,g['metrics']['TPR'],str(g['group']))\n   xlabel='Declared group position';ylabel='True positive rate';legend=['Known-group TPR']\n  else:raise ValueError('unknown fixed API')\n def csvout(name,rows):\n  with(args.out/name).open('w',encoding='utf8',newline='')as f:w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows)\n csvout('summary.csv',summary);csvout('plot-points.csv',points);fixed_svg(args.out/'plot.svg',points,FIXED['title'],xlabel,ylabel,legend)\n (args.out/'full.json').write_text(json.dumps(dict(api=api,variant=FIXED['variant'],input=FIXED['args'],arithmetic='Python standard-library Fraction, declared fixed example; full web validator/budgets not reproduced',result=serial(full)),ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\n print(json.dumps(dict(api=api,variant=FIXED['variant'],summaryMetrics=len(summary),plotSlots=len(points))))\n\nFIXED={'api': 'metrics', 'variant': 'zero-cost', 'args': {'rows': [{'id': 'a', 'score': '.9', 'y': 1, 'group': 'A'}, {'id': 'b', 'score': '.8', 'y': 1, 'group': 'A'}, {'id': 'c', 'score': '.8', 'y': 0, 'group': 'A'}, {'id': 'd', 'score': '.6', 'y': 0, 'group': 'B'}, {'id': 'e', 'score': '.4', 'y': 1, 'group': 'B'}, {'id': 'f', 'score': '.1', 'y': 0, 'group': 'B'}], 'costs': {'falsePositive': '0', 'falseNegative': '0'}}, 'title': 'Both hypothetical costs zero; Bayes ratio undefined'}\nif __name__=='__main__':fixed_run()\n",
        "codeText": "#!/usr/bin/env python3\n\"\"\"ML14 standalone exact finite study, Python standard library only.\nInputs: only the three retained factual source CSVs below.\nDerived role/target/group/eligibility columns in those CSVs are NOT inputs.\nRebuilds SHA256 roles, train-only medians/cell scores, validation thresholds,\ntest curves, binary-event reliability and descriptive group ledgers.\nCosts 1/1,1/5,5/1 are hypothetical units, not measured intervention returns.\nThis is author public reproduction, not independent scientific review.\n\"\"\"\n\"\"\"Author Fraction reference, separate from product JavaScript; not independent peer.\"\"\"\nfrom fractions import Fraction as F\nfrom collections import Counter,defaultdict\ndef read(raw):\n rows=[]\n for i,r in enumerate(raw):\n  s=None if r['score']is None else F(str(r['score']));y=None if r['y']is None else F(int(r['y']))if isinstance(r['y'],bool)else F(str(r['y']));w=F(str(r.get('weight','1')));role=r.get('role','evaluation')\n  rows.append(dict(id=r['id'],index=i,score=s,y=y,w=w,role=role,group=r.get('group'),eligible=s is not None and y is not None and w>0 and role!='excluded'))\n return rows\ndef scoped(rows,role='all'):return rows if role=='all'else[r for r in rows if r['role']==role]\ndef divide(n,d):return None if not d else n/d\ndef policy(v):return v if v in ['always-negative','always-positive']else F(str(v))\ndef positive(p,s):return p=='always-positive'if isinstance(p,str)else s>=p\ndef cost(a=None):\n a={}if a is None else a;fp=F(str(a.get('falsePositive','1')));fn=F(str(a.get('falseNegative','1')));return fp,fn\ndef metrics(rows,threshold=F(1,2),cc=(F(1),F(1))):\n counts=dict(TP=F(0),FP=F(0),FN=F(0),TN=F(0));brier=F(0);pred=[]\n for r in rows:\n  if not r['eligible']:pred.append(dict(id=r['id'],index=r['index'],eligible=False,decision=None,probability=None,Brier=None));continue\n  yes=positive(threshold,r['score']);cell=('T'if yes==bool(r['y'])else'F')+('P'if yes else'N');counts[cell]+=r['w'];loss=(r['score']-r['y'])**2;brier+=r['w']*loss;pred.append(dict(id=r['id'],index=r['index'],eligible=True,decision=int(yes),probability=r['score'],Brier=loss))\n TP,FP,FN,TN=[counts[k]for k in ['TP','FP','FN','TN']];P=TP+FN;N=TN+FP;mass=P+N;PP=TP+FP;PN=TN+FN;TPR=divide(TP,P);TNR=divide(TN,N);total=FP*cc[0]+FN*cc[1]\n return dict(confusion=counts,mass=mass,positiveTargetMass=P,negativeTargetMass=N,predictedPositiveMass=PP,predictedNegativeMass=PN,prevalence=divide(P,mass),selectionRate=divide(PP,mass),accuracy=divide(TP+TN,mass),precision=divide(TP,PP),negativePredictiveValue=divide(TN,PN),TPR=TPR,FPR=divide(FP,N),TNR=TNR,FNR=divide(FN,P),F1=divide(2*TP,2*TP+FP+FN),balancedAccuracy=None if TPR is None or TNR is None else(TPR+TNR)/2,Brier=divide(brier,mass),BrierSum=brier,totalCost=total,meanCost=divide(total,mass),predictions=pred,bayesThreshold=divide(cc[0],sum(cc)))\ndef curves(rows):\n use=[r for r in rows if r['eligible']];pos=Counter();neg=Counter()\n for r in use:(pos if r['y']else neg)[r['score']]+=r['w']\n P=sum(pos.values(),F(0));N=sum(neg.values(),F(0));pairs=F(0)\n for a,wa in pos.items():\n  for b,wb in neg.items():pairs+=wa*wb*(F(1)if a>b else F(1,2)if a==b else F(0))\n thresholds=['always-negative']+sorted({r['score']for r in use},reverse=True);points=[];AP=F(0);trap=F(0);lastR=F(0);lastP=F(1)\n for i,p in enumerate(thresholds):\n  m=metrics(rows,p);points.append(dict(policy=p,TP=m['confusion']['TP'],FP=m['confusion']['FP'],FN=m['confusion']['FN'],TN=m['confusion']['TN'],TPR=m['TPR'],FPR=m['FPR'],precision=m['precision'],recall=m['TPR']))\n  if i and P:\n   R=m['TPR'];PP=m['precision'];AP+=(R-lastR)*PP;trap+=(R-lastR)*(PP+lastP)/2;lastR=R;lastP=PP\n return dict(positiveMass=P,negativeMass=N,ROC_AUC=divide(pairs,P*N),weightedConcordantPlusHalfTiedMass=pairs,averagePrecision=AP if P else None,PRTrapezoidWithInitialPrecisionOne=trap if P else None,points=points)\ndef choose(rows,a,cc):\n sr=a.get('selectionRole','validation');er=a.get('evaluationRole','test');rr=scoped(rows,sr);thresholds=[policy(t)for t in a['thresholds']]if'thresholds'in a else['always-negative']+sorted({r['score']for r in rr if r['eligible']},reverse=True)\n candidates=[]\n for i,p in enumerate(thresholds):\n  m=metrics(rr,p,cc);reasons=[]\n  if'minTPR'in a and(m['TPR']is None or m['TPR']<F(str(a['minTPR']))):reasons.append('TPR-undefined'if m['TPR']is None else'below-minTPR')\n  if'maxFPR'in a and(m['FPR']is None or m['FPR']>F(str(a['maxFPR']))):reasons.append('FPR-undefined'if m['FPR']is None else'above-maxFPR')\n  candidates.append(dict(index=i,policy=p,metrics=m,feasible=not reasons,reasons=reasons))\n eligible=[c for c in candidates if c['feasible']];best=min(eligible,key=lambda c:(c['metrics']['meanCost'],c['index']))if eligible else None\n return dict(selectedIndex=None if best is None else best['index'],selectedPolicy=None if best is None else best['policy'],candidates=candidates,selectedValidation=None if best is None else best['metrics'],evaluation=None if best is None or er=='none'else metrics(scoped(rows,er),best['policy'],cc),selectionIDs=[r['id']for r in rr if r['eligible']])\ndef calibrate(rows,ee):\n buckets=[[]for _ in range(len(ee)-1)]\n for r in rows:\n  if not r['eligible']:continue\n  j=next((i for i in range(len(ee)-1)if r['score']<ee[i+1]),len(ee)-2);buckets[j].append(r)\n mass=sum((r['w']for r in rows if r['eligible']),F(0));P=sum((r['w']*r['y']for r in rows if r['eligible']),F(0));pi=divide(P,mass);Brier=None if not mass else sum((r['w']*(r['score']-r['y'])**2 for r in rows if r['eligible']),F(0))/mass;ECE=F(0);reliability=F(0);resolution=F(0);correction=F(0);bins=[]\n for i,rr in enumerate(buckets):\n  w=sum((r['w']for r in rr),F(0));mp=None if not w else sum((r['w']*r['score']for r in rr),F(0))/w;o=None if not w else sum((r['w']*r['y']for r in rr),F(0))/w\n  variance=None if not w else sum((r['w']*(r['score']-mp)**2 for r in rr),F(0))/w\n  covariance=None if not w else sum((r['w']*(r['score']-mp)*(r['y']-o)for r in rr),F(0))/w\n  bc=None if not w else variance-2*covariance;gap=None if not w else mp-o\n  bins.append(dict(index=i,rows=len(rr),mass=w,meanPrediction=mp,eventRate=o,gap=gap,absoluteGap=None if gap is None else abs(gap),scoreVariance=variance,scoreTargetCovariance=covariance,withinBinCorrection=bc,ids=[r['id']for r in rr]))\n  if w:\n   share=w/mass;ECE+=share*abs(gap);reliability+=share*gap**2;resolution+=share*(o-pi)**2;correction+=share*bc\n uncertainty=None if pi is None else pi*(1-pi);residual=None if Brier is None else Brier-(uncertainty-resolution+reliability+correction)\n return dict(mass=mass,prevalence=pi,Brier=Brier,ECE=ECE if mass else None,reliability=reliability if mass else None,resolution=resolution if mass else None,uncertainty=uncertainty,withinBinCorrection=correction if mass else None,BrierIdentityResidual=residual,bins=bins)\ndef typed(v):return type(v).__name__,v\ndef groups(rows,p,cc):\n bins={}\n for r in rows:\n  if r['group']is not None:bins.setdefault(typed(r['group']),[]).append(r)\n gm=[dict(group=rr[0]['group'],metrics=metrics(rr,p,cc))for rr in bins.values()];overall=metrics(rows,p,cc);unknown=metrics([r for r in rows if r['group']is None],p,cc);gaps={}\n for key in ['prevalence','selectionRate','TPR','FPR','precision','accuracy','meanCost']:\n  positive=[g for g in gm if g['metrics']['mass']>0];undefined=[g['group']for g in positive if g['metrics'][key]is None];vals=[g['metrics'][key]for g in positive if g['metrics'][key]is not None]\n  gaps[key]=dict(value=None if len(positive)<2 or undefined else max(vals)-min(vals),undefinedGroups=undefined,comparedPositiveMassGroups=[g['group']for g in positive])\n return dict(overall=overall,groups=gm,unknownGroup=unknown,gaps=gaps,partitionMassResidual=overall['mass']-unknown['mass']-sum((g['metrics']['mass']for g in gm),F(0)))\ndef actual_model(M):\n raw=M['records'];cat=M['categoricalFeatures'];p=len(raw[0]['x']);train=[r for r in raw if r['role']=='train'];medians=[]\n for j in range(p):\n  if j in cat:medians.append(None);continue\n  values=sorted(F(r['x'][j])for r in train);n=len(values);medians.append(values[n//2]if n%2 else(values[n//2-1]+values[n//2])/2)\n def transform(r):return[F(v)if j in cat else F(int(F(v)>medians[j]))for j,v in enumerate(r['x'])]\n counts={}\n for r in train:\n  key=tuple(transform(r));n,s=counts.get(key,(0,0));counts[key]=(n+1,s+int(r['y']))\n probabilities={k:F(s+1,n+2)for k,(n,s)in counts.items()};fallback=F(sum(int(r['y'])for r in train)+1,len(train)+2);scored=[]\n for i,r in enumerate(raw):\n  eligible=r['role']!='excluded';z=transform(r)if eligible else None;key=None if z is None else tuple(z);score=None if not eligible else probabilities.get(key,fallback)\n  scored.append(dict(id=r['id'],index=i,role=r['role'],group=r['group'],y=None if r['y']is None else F(r['y']),score=score,w=F(1),eligible=eligible,transformedX=z,unseenCell=None if not eligible else key not in probabilities))\n return dict(medians=medians,cells=counts,probabilities=probabilities,fallback=fallback,rows=scored,trainIDs=[r['id']for r in train])\n\n\nimport csv,json,hashlib,argparse,datetime\nfrom pathlib import Path\ndef missing(v):return None if v in ['', '.',None]else v\ndef load_sources(folder):\n def read_csv(name):\n  with (folder/name).open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))\n wb=read_csv('actual64-country-four-indicators-original-2024.csv')\n codes=['NY.GDP.PCAP.KD','NY.GDP.MKTP.KD.ZG','FP.CPI.TOTL.ZG','SP.DYN.LE00.IN']\n lookup={(r['countryISO3'],r['indicatorID']):r for r in wb};country=[]\n for i,iso in enumerate(sorted({r['countryISO3']for r in wb}),1):\n  native=[lookup[iso,c]for c in codes];v=[missing(r['originalValueToken'])for r in native]\n  country.append(dict(id=iso+':2024',sourceRow=i,originalID=iso,x=v[:3],y=None if v[3]is None else str(int(F(v[3])>=80)),group=None if v[0]is None else str(int(F(v[0])>=25000)),nativeTarget=v[3],nativeSourceRows=';'.join(r['sourceRow']for r in native)))\n nls=read_csv('actual3613-NLS-original52-fields-groups-roles.csv');person=[]\n for r in nls:\n  y=missing(r['wage76']);person.append(dict(id='person:'+r['sourceRow'],sourceRow=int(r['sourceRow']),originalID=r['id'],x=[missing(r[k])for k in ['ed76','age76','nearc4']],y=None if y is None else str(int(F(y)>=500)),group=missing(r['black']),nativeTarget=y,nativeSourceRows=r['sourceRow']))\n ch=read_csv('actual3150-churn-original14-fields-groups-roles.csv');company=[]\n for r in ch:\n  company.append(dict(id='customer:'+r['sourceRow'],sourceRow=int(r['sourceRow']),originalID='',x=[missing(r[k])for k in ['Call  Failure','Complains','Subscription  Length','Seconds of Use']],y=missing(r['Churn']),group=missing(r['Tariff Plan']),nativeTarget=missing(r['Churn']),nativeSourceRows=r['sourceRow']))\n assert len(wb)==64 and len(country)==16 and len(nls)==3613 and len(ch)==3150\n assert [int(r['sourceRow'])for r in ch if r['Charge  Amount']=='10']==[474,2174,2274,2374,2674,2924,2974]\n models={}\n for kind,raw,cat,units in [('country',country,[],['constant2015USD/person','annualPercent','annualPercent']),('person',person,[2],['years','years','nativeCategory']),('company',company,[1],['count','nativeCategory','months','seconds'])]:\n  order=sorted(range(len(raw)),key=lambda i:(hashlib.sha256(('ML14-role|'+kind+'|'+raw[i]['id']).encode()).hexdigest(),i))\n  for rank,i in enumerate(order):\n   r=raw[i];r['plannedRole']='test'if rank%5==0 else'validation'if rank%5==1 else'train';r['eligible']=None not in r['x']+[r['y']];r['role']=r['plannedRole']if r['eligible']else'excluded';r['weight']='1'\n  models[kind]=dict(records=raw,categoricalFeatures=cat,featureUnits=units)\n assert sum(r['eligible']for r in person)==3017\n return models\n\ndef exact(v):return ''if v is None else str(v)\ndef approx(v):return ''if v is None else format(float(v),'.17g')\ndef scalar_fields(m,keys):\n out={}\n for k in keys:\n  out[k+'Exact']=exact(m[k]);out[k+'Approx']=approx(m[k])\n return out\nCOUNTS=['mass','positiveTargetMass','negativeTargetMass','predictedPositiveMass','predictedNegativeMass']\nRATES=['prevalence','selectionRate','accuracy','precision','negativePredictiveValue','TPR','FPR','TNR','FNR','F1','balancedAccuracy','Brier','BrierSum','totalCost','meanCost']\nSCENARIOS=[('equal',F(1),F(1)),('miss-five',F(1),F(5)),('alarm-five',F(5),F(1))]\ndef packed(v):\n if isinstance(v,F):return str(v)\n if isinstance(v,dict):return{str(k):packed(x)for k,x in v.items()}\n if isinstance(v,(tuple,list)):return[packed(x)for x in v]\n return v\ndef run_study(source,out):\n out.mkdir(parents=True,exist_ok=True);models=load_sources(source)\n tables={name:[]for name in ['predictions','lineage','fit-medians','fit-cells','validation-candidates','test-metrics','test-curves','calibration-bins','group-metrics','chart-points']}\n studies={};charts=[]\n def point(kind,chart,series,index,x,y,xunit='dimensionless',yunit='dimensionless',role='test',tag=''):\n  tables['chart-points'].append(dict(kind=kind,chart=chart,series=series,index=index,xExact=exact(x),xApprox=approx(x),yExact=exact(y),yApprox=approx(y),xUnit=xunit,yUnit=yunit,role=role,tag=tag))\n for kind,M in models.items():\n  fit=actual_model(M);rr=fit['rows'];native=M['records'];test=scoped(rr,'test');cv=curves(test);cal=calibrate(test,[F(0),F(1,5),F(2,5),F(3,5),F(4,5),F(1)]);scenarios=[]\n  for i,r in enumerate(rr):\n   n=native[i];reason=''if r['eligible']else'required-X-or-Y-missing'\n   tables['predictions'].append(dict(kind=kind,id=r['id'],sourceRow=n['sourceRow'],originalID=n['originalID'],plannedRole=n['plannedRole'],role=r['role'],group=''if r['group']is None else r['group'],eligible=int(r['eligible']),targetExact=exact(r['y']),probabilityExact=exact(r['score']),probabilityApprox=approx(r['score']),unseenCell=''if r['unseenCell']is None else int(r['unseenCell']),transformedX=''if r['transformedX']is None else'|'.join(map(str,r['transformedX'])),reason=reason))\n   tables['lineage'].append(dict(kind=kind,id=r['id'],sourceRow=n['sourceRow'],originalID=n['originalID'],nativeSourceRows=n['nativeSourceRows'],rawX='|'.join(''if x is None else x for x in n['x']),nativeTarget=''if n['nativeTarget']is None else n['nativeTarget'],derivedTarget=exact(r['y']),nativeGroup=''if n['group']is None else n['group'],plannedRole=n['plannedRole'],role=r['role'],eligible=int(r['eligible']),analyticalMass='1',reason=reason))\n  for j,v in enumerate(fit['medians']):tables['fit-medians'].append(dict(kind=kind,feature=j,categorical=int(j in M['categoricalFeatures']),fitRows=len(fit['trainIDs']),medianExact=exact(v),medianApprox=approx(v),unit=M['featureUnits'][j]))\n  for key,(mass,pos)in fit['cells'].items():tables['fit-cells'].append(dict(kind=kind,cell='|'.join(map(str,key)),trainingRows=mass,positiveRows=pos,probabilityExact=exact(fit['probabilities'][key]),probabilityApprox=approx(fit['probabilities'][key]),fallbackExact=exact(fit['fallback']),fallbackApprox=approx(fit['fallback'])))\n  for j,p in enumerate(cv['points']):\n   policy=p['policy'];tables['test-curves'].append(dict(kind=kind,point=j,policy=policy if isinstance(policy,str)else'threshold',thresholdExact=''if isinstance(policy,str)else exact(policy),thresholdApprox=''if isinstance(policy,str)else approx(policy),**scalar_fields(p,['TP','FP','FN','TN','TPR','FPR','precision','recall'])))\n   point(kind,'roc','ROC',j,p['FPR'],p['TPR']);point(kind,'pr','PR-observed',j,p['recall'],p['precision'])\n  for b in cal['bins']:\n   tables['calibration-bins'].append(dict(kind=kind,bin=b['index'],leftExact=str(F(b['index'],5)),rightExact=str(F(b['index']+1,5)),rightClosed=int(b['index']==4),rows=b['rows'],ids=';'.join(str(i)for i in b['ids']),**scalar_fields(b,['mass','meanPrediction','eventRate','gap','absoluteGap','scoreVariance','scoreTargetCovariance','withinBinCorrection'])))\n   point(kind,'reliability','Binary event rate',b['index'],b['meanPrediction'],b['eventRate'],tag='rows='+str(b['rows']))\n  for j,r in enumerate(test):\n   point(kind,'test-scores','Training-fitted probability',j,F(j+1),r['score'],'test-row position','probability',tag=r['id'])\n   point(kind,'test-scores','Observed Y',j,F(j+1),r['y'],'test-row position','binary target',tag=r['id'])\n  for name,fp,fn in SCENARIOS:\n   choice=choose(rr,{},(fp,fn));gm=groups(test,choice['selectedPolicy'],(fp,fn));scenarios.append(dict(name=name,costs=dict(falsePositive=fp,falseNegative=fn),selection=choice,groups=gm));ev=choice['evaluation']\n   for c in choice['candidates']:\n    policy=c['policy'];mm=c['metrics'];tables['validation-candidates'].append(dict(kind=kind,scenario=name,candidate=c['index'],selected=int(c['index']==choice['selectedIndex']),policy=policy if isinstance(policy,str)else'threshold',thresholdExact=''if isinstance(policy,str)else exact(policy),thresholdApprox=''if isinstance(policy,str)else approx(policy),feasible=int(c['feasible']),reasons=';'.join(c['reasons']),**{k+'Exact':str(v)for k,v in mm['confusion'].items()},**scalar_fields(mm,COUNTS+['TPR','FPR','precision','meanCost','totalCost'])))\n    point(kind,'validation-cost',name,c['index'],F(c['index']),mm['meanCost'],'candidate index','hypothetical cost units/mass','validation',tag=exact(policy))\n   mm={**ev,**ev['confusion'],**{k:cv[k]for k in ['ROC_AUC','averagePrecision','PRTrapezoidWithInitialPrecisionOne']},**{k:cal[k]for k in ['ECE','reliability','resolution','uncertainty','withinBinCorrection','BrierIdentityResidual']}}\n   for key in ['TP','FP','FN','TN']+COUNTS+RATES+['ROC_AUC','averagePrecision','PRTrapezoidWithInitialPrecisionOne','ECE','reliability','resolution','uncertainty','withinBinCorrection','BrierIdentityResidual']:\n    unit='rows'if key in ['TP','FP','FN','TN']+COUNTS else'hypothetical cost units'if key=='totalCost'else'hypothetical cost units/mass'if key=='meanCost'else'sum squared-probability loss'if key=='BrierSum'else'dimensionless'\n    tables['test-metrics'].append(dict(kind=kind,scenario=name,metric=key,valueExact=exact(mm[key]),valueApprox=approx(mm[key]),unit=unit))\n   allg=[('overall','all',gm['overall'])]+[('known',str(g['group']),g['metrics'])for g in gm['groups']]+[('unknown','',gm['unknownGroup'])]\n   for j,(typ,token,g)in enumerate(allg):\n    tables['group-metrics'].append(dict(kind=kind,scenario=name,groupType=typ,groupToken=token,retainedRows=g.get('retainedRows',sum((r['group']==token)if typ=='known'else(r['group']is None)if typ=='unknown'else True for r in test)),**{k+'Exact':str(v)for k,v in g['confusion'].items()},**scalar_fields(g,COUNTS+RATES)))\n    if typ=='known':point(kind,'group-TPR',name,j-1,F(j-1),g['TPR'],'declared group position','TPR',tag=token)\n  studies[kind]=dict(kind=kind,rows=len(native),eligibleRows=sum(r['eligible']for r in rr),trainingIDs=fit['trainIDs'],fitMedians=fit['medians'],fitCells=[dict(cell=list(k),mass=n,positive=s,probability=fit['probabilities'][k])for k,(n,s)in fit['cells'].items()],fallback=fit['fallback'],scenarios=scenarios,testCurves=cv,testCalibration=cal,rowsScored=rr)\n files=[]\n for name,rows in tables.items():\n  p=out/('computed-'+name+'.csv')\n  with p.open('w',encoding='utf8',newline='')as f:w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows)\n  files.append(dict(file=p.name,rows=len(rows),columns=len(rows[0]),bodyFields=len(rows)*len(rows[0]),sha256=hashlib.sha256(p.read_bytes()).hexdigest()))\n (out/'study.json').write_text(json.dumps(packed(studies),ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\n sourceFiles=[source/n for n in ['actual64-country-four-indicators-original-2024.csv','actual3613-NLS-original52-fields-groups-roles.csv','actual3150-churn-original14-fields-groups-roles.csv']]\n provenance=dict(chapter='ML-14',arithmetic='Python stdlib Fraction exact finite values from original decimal strings; binary64 valueApprox is display only.',inputs=[dict(file=p.name,sha256=hashlib.sha256(p.read_bytes()).hexdigest())for p in sourceFiles],priorEngineModelsScoresOrComputedFilesRead=False,roleRule=\"SHA256('ML14-role|'+kind+'|'+ID),rankmod5=0test/1validation/others train before eligibility\",costs='Hypothetical1/1,1/5,5/1; no causal intervention returns',files=files,observations={k:dict(sourceRows=v['rows'],eligibleRows=v['eligibleRows'],trainingRows=len(v['trainingIDs']))for k,v in studies.items()})\n (out/'provenance.json').write_text(json.dumps(provenance,ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\n print(json.dumps(dict(status='PASS standalone completed',files=len(files),bodyFields=sum(f['bodyFields']for f in files),observations=provenance['observations'])))\n\n# Fixed declared examples: full web budget/option validation is not reproduced.\nfrom html import escape\nimport textwrap\ndef validated_rows(raw):\n for r in raw:\n  assert F(str(r.get('weight','1')))>=0,'negative analytical mass'\n  assert r['score']is None or 0<=F(str(r['score']))<=1,'score outside zero/one'\n  assert r['y']is None or F(str(int(r['y']))if isinstance(r['y'],bool)else str(r['y']))in [0,1],'binary target required'\n return read(raw)\ndef serial(v):\n if isinstance(v,F):return dict(exactFraction=str(v),value=float(v))\n if isinstance(v,(list,tuple)):return[serial(x)for x in v]\n if isinstance(v,dict):return{k:serial(x)for k,x in v.items()}\n return v\ndef fixed_svg(path,points,title,xlabel,ylabel,legend):\n use=[p for p in points if p['xExact']!=''and p['yExact']!=''];xs=[float(F(p['xExact']))for p in use];ys=[float(F(p['yExact']))for p in use]\n xmin=min(xs,default=0);xmax=max(xs,default=1);ymin=min([0]+ys);ymax=max([0]+ys)\n if xmin==xmax:xmin-=.5;xmax+=.5\n if ymin==ymax:ymax=ymin+1\n X=lambda v:85+(float(v)-xmin)/(xmax-xmin)*480;Y=lambda v:278-(float(v)-ymin)/(ymax-ymin)*175\n s='<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"620\" height=\"360\" viewBox=\"0 0 620 360\"><rect width=\"620\" height=\"360\" fill=\"white\"/><g font-family=\"Arial, sans-serif\" font-size=\"13\" fill=\"#17324d\">'\n for i,line in enumerate(textwrap.wrap(title,width=65)):s+='<text x=\"25\" y=\"'+str(24+i*18)+'\">'+escape(line)+'</text>'\n colors=['#176b9b','#b85e18','#437e4d']\n for i,label in enumerate(legend):s+='<circle cx=\"'+str(30+i*250)+'\" cy=\"76\" r=\"4\" fill=\"'+colors[i%3]+'\"/><text x=\"'+str(42+i*250)+'\" y=\"80\">'+escape(label)+'</text>'\n s+='<path d=\"M85 98V278H575\" fill=\"none\" stroke=\"#52677d\"/><text text-anchor=\"middle\" x=\"325\" y=\"338\">'+escape(xlabel)+'</text><text text-anchor=\"middle\" transform=\"translate(21,190) rotate(-90)\">'+escape(ylabel)+'</text>'\n for i in range(5):\n  xx=xmin+(xmax-xmin)*i/4;yy=ymin+(ymax-ymin)*i/4;s+='<text text-anchor=\"middle\" x=\"'+format(X(xx),'.9g')+'\" y=\"305\">'+format(xx,'.4g')+'</text><text text-anchor=\"end\" x=\"77\" y=\"'+format(Y(yy)+4,'.9g')+'\">'+format(yy,'.4g')+'</text>'\n for p in use:s+='<circle cx=\"'+format(X(F(p['xExact'])),'.9g')+'\" cy=\"'+format(Y(F(p['yExact'])),'.9g')+'\" r=\"3\" fill=\"'+colors[p['series']%3]+'\"/>'\n path.write_text(s+'</g></svg>',encoding='utf8')\ndef fixed_run():\n ap=argparse.ArgumentParser();ap.add_argument('--out',type=Path,default=Path('results'));ap.add_argument('--data-dir',type=Path,default=Path(__file__).resolve().parent.parent/'ml14-sources');args=ap.parse_args();args.out.mkdir(parents=True,exist_ok=True)\n api=FIXED['api'];a=FIXED['args'];summary=[];points=[];xlabel='Declared index';ylabel='Value';legend=['Declared result']\n def metric(name,v,unit='dimensionless'):\n  q=None if v is None else v if isinstance(v,F)else F(v);summary.append(dict(metric=name,value='undefined'if q is None else format(float(q),'.9g'),exactValue=''if q is None else str(q),unit=unit,defined=int(q is not None)))\n def pt(i,x,y,ident='',series=0):\n  points.append(dict(series=series,index=i,xExact=''if x is None else str(F(x)),x='undefined'if x is None else format(float(x),'.9g'),yExact=''if y is None else str(F(y)),y='undefined'if y is None else format(float(y),'.9g'),id=str(ident)))\n if api=='realdata':\n  models=load_sources(args.data_dir);model=models[a['kind']];fit=actual_model(model);rr=fit['rows'];test=scoped(rr,'test');scenarios=[]\n  for name,fp,fn in SCENARIOS:\n   c=choose(rr,{},(fp,fn));scenarios.append(dict(name=name,selection=c));metric(name+'Threshold',c['selectedPolicy']);metric(name+'TestCost',c['evaluation']['meanCost'],'hypothetical cost units/mass')\n  cv=curves(test);cal=calibrate(test,[F(0),F(1,5),F(2,5),F(3,5),F(4,5),F(1)]);metric('testAUC',cv['ROC_AUC']);metric('testAP',cv['averagePrecision']);metric('testBrier',cal['Brier']);metric('eligibleRows',sum(r['eligible']for r in rr),'rows')\n  for i,r in enumerate(test):pt(i,i+1,r['score'],r['id'],0);pt(i,i+1,r['y'],r['id'],1)\n  full=dict(kind=a['kind'],fitMedians=fit['medians'],fitCells=[dict(cell=list(k),mass=n,positive=s,probability=fit['probabilities'][k])for k,(n,s)in fit['cells'].items()],rowsScored=rr,scenarios=scenarios,testCurves=cv,testCalibration=cal);xlabel='Test row, native order';ylabel='Y or probability';legend=['Training-fitted probability','Observed Y']\n else:\n  rr=validated_rows(a['rows']);role=a.get('role','all');frame=scoped(rr,role);cc=cost(a.get('costs'));t=policy(a.get('threshold','1/2'))\n  if api=='metrics':\n   full=metrics(frame,t,cc)\n   for k in ['mass','accuracy','precision','TPR','FPR','F1','Brier','meanCost']:metric(k,full[k],'mass'if k=='mass'else'hypothetical cost units/mass'if k=='meanCost'else'dimensionless')\n   metric('BayesThreshold',full['bayesThreshold'])\n   for i,k in enumerate(['TP','FP','FN','TN']):pt(i,i,full['confusion'][k],k)\n   xlabel='TP / FP / FN / TN positions';ylabel='Analytical mass'\n  elif api=='curves':\n   full=curves(frame)\n   for k in ['ROC_AUC','averagePrecision','PRTrapezoidWithInitialPrecisionOne']:metric(k,full[k])\n   for i,p in enumerate(full['points']):pt(i,p['FPR'],p['TPR'],str(p['policy']))\n   xlabel='False positive rate';ylabel='True positive rate';legend=['Observed ROC operating points']\n  elif api=='choose':\n   full=choose(rr,a,cc);metric('selectedIndex',full['selectedIndex'],'candidate index');metric('minimumCost',None if full['selectedValidation']is None else full['selectedValidation']['meanCost'],'hypothetical cost units/mass');metric('feasible',int(full['selectedIndex']is not None),'indicator')\n   for c in full['candidates']:pt(c['index'],c['index'],c['metrics']['meanCost'],str(c['policy']))\n   xlabel='Validation candidate';ylabel='Assumed cost / mass';legend=['Validation candidate costs']\n  elif api=='calibrate':\n   full=calibrate(frame,[F(str(e))for e in a.get('binEdges',['0','1/5','2/5','3/5','4/5','1'])])\n   for k in ['ECE','Brier','uncertainty','resolution','reliability','withinBinCorrection','BrierIdentityResidual']:metric(k,full[k])\n   for b in full['bins']:pt(b['index'],b['meanPrediction'],b['eventRate'],'bin:'+str(b['index']))\n   xlabel='Bin mean forecast';ylabel='Bin event rate';legend=['Binary-event reliability']\n  elif api=='groups':\n   full=groups(frame,t,cc);metric('overallTPR',full['overall']['TPR']);metric('TPRGap',full['gaps']['TPR']['value']);metric('precisionGap',full['gaps']['precision']['value']);metric('unknownMass',full['unknownGroup']['mass'],'mass');metric('partitionResidual',full['partitionMassResidual'],'mass')\n   for i,g in enumerate(full['groups']):pt(i,i,g['metrics']['TPR'],str(g['group']))\n   xlabel='Declared group position';ylabel='True positive rate';legend=['Known-group TPR']\n  else:raise ValueError('unknown fixed API')\n def csvout(name,rows):\n  with(args.out/name).open('w',encoding='utf8',newline='')as f:w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows)\n csvout('summary.csv',summary);csvout('plot-points.csv',points);fixed_svg(args.out/'plot.svg',points,FIXED['title'],xlabel,ylabel,legend)\n (args.out/'full.json').write_text(json.dumps(dict(api=api,variant=FIXED['variant'],input=FIXED['args'],arithmetic='Python standard-library Fraction, declared fixed example; full web validator/budgets not reproduced',result=serial(full)),ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\n print(json.dumps(dict(api=api,variant=FIXED['variant'],summaryMetrics=len(summary),plotSlots=len(points))))\n\nFIXED={'api': 'metrics', 'variant': 'zero-cost', 'args': {'rows': [{'id': 'a', 'score': '.9', 'y': 1, 'group': 'A'}, {'id': 'b', 'score': '.8', 'y': 1, 'group': 'A'}, {'id': 'c', 'score': '.8', 'y': 0, 'group': 'A'}, {'id': 'd', 'score': '.6', 'y': 0, 'group': 'B'}, {'id': 'e', 'score': '.4', 'y': 1, 'group': 'B'}, {'id': 'f', 'score': '.1', 'y': 0, 'group': 'B'}], 'costs': {'falsePositive': '0', 'falseNegative': '0'}}, 'title': 'Both hypothetical costs zero; Bayes ratio undefined'}\nif __name__=='__main__':fixed_run()\n",
        "input": {
          "rows": [
            {
              "id": "a",
              "score": ".9",
              "y": 1,
              "group": "A"
            },
            {
              "id": "b",
              "score": ".8",
              "y": 1,
              "group": "A"
            },
            {
              "id": "c",
              "score": ".8",
              "y": 0,
              "group": "A"
            },
            {
              "id": "d",
              "score": ".6",
              "y": 0,
              "group": "B"
            },
            {
              "id": "e",
              "score": ".4",
              "y": 1,
              "group": "B"
            },
            {
              "id": "f",
              "score": ".1",
              "y": 0,
              "group": "B"
            }
          ],
          "costs": {
            "falsePositive": "0",
            "falseNegative": "0"
          }
        },
        "inputFiles": [],
        "returnCode": 0,
        "expectedFailure": false,
        "stdout": "{\"api\": \"metrics\", \"variant\": \"zero-cost\", \"summaryMetrics\": 9, \"plotSlots\": 4}\n",
        "stderr": "",
        "summary": {
          "mass": "6",
          "accuracy": "0.5",
          "precision": "0.5",
          "TPR": "0.666666667",
          "FPR": "0.666666667",
          "F1": "0.571428571",
          "Brier": "0.236666667",
          "meanCost": "0",
          "BayesThreshold": "undefined"
        },
        "summaryRows": [
          {
            "metric": "mass",
            "value": "6",
            "exactValue": "6",
            "unit": "mass",
            "defined": "1"
          },
          {
            "metric": "accuracy",
            "value": "0.5",
            "exactValue": "1/2",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "precision",
            "value": "0.5",
            "exactValue": "1/2",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "TPR",
            "value": "0.666666667",
            "exactValue": "2/3",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "FPR",
            "value": "0.666666667",
            "exactValue": "2/3",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "F1",
            "value": "0.571428571",
            "exactValue": "4/7",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "Brier",
            "value": "0.236666667",
            "exactValue": "71/300",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "meanCost",
            "value": "0",
            "exactValue": "0",
            "unit": "hypothetical cost units/mass",
            "defined": "1"
          },
          {
            "metric": "BayesThreshold",
            "value": "undefined",
            "exactValue": "",
            "unit": "dimensionless",
            "defined": "0"
          }
        ],
        "plotPoints": [
          {
            "series": "0",
            "index": "0",
            "xExact": "0",
            "x": "0",
            "yExact": "2",
            "y": "2",
            "id": "TP"
          },
          {
            "series": "0",
            "index": "1",
            "xExact": "1",
            "x": "1",
            "yExact": "2",
            "y": "2",
            "id": "FP"
          },
          {
            "series": "0",
            "index": "2",
            "xExact": "2",
            "x": "2",
            "yExact": "1",
            "y": "1",
            "id": "FN"
          },
          {
            "series": "0",
            "index": "3",
            "xExact": "3",
            "x": "3",
            "yExact": "1",
            "y": "1",
            "id": "TN"
          }
        ],
        "plotFile": "ml14-fixed-results/metrics-zero-cost-python/plot.svg",
        "plotSHA256": "9966cd3cb1a4e44b0a7d497af7ca73870a37d82e7481e8446e8ba3092c319987",
        "files": [
          {
            "file": "ml14-fixed-results/metrics-zero-cost-python/full.json",
            "sha256": "82f96e62a668322cf42273cbe18d4ec78e04216fd0617ff3c4813b62d623fdc2",
            "bytes": 4832
          },
          {
            "file": "ml14-fixed-results/metrics-zero-cost-python/plot-points.csv",
            "sha256": "7db7f9e75ca8ae7341014fd62e005ebfba38c530b2113142029c665cb56ef682",
            "bytes": 99
          },
          {
            "file": "ml14-fixed-results/metrics-zero-cost-python/plot.svg",
            "sha256": "9966cd3cb1a4e44b0a7d497af7ca73870a37d82e7481e8446e8ba3092c319987",
            "bytes": 1300
          },
          {
            "file": "ml14-fixed-results/metrics-zero-cost-python/summary.csv",
            "sha256": "f32d0fe6029a7525fadbb03b8f714da054649a83f686a525d890a8d1a2ee4b12",
            "bytes": 364
          }
        ],
        "scope": "Actually executed standalone fixed example, Python exact Fraction versus base-R binary64. Approximate R residuals retained; not universal exact arithmetic/web validation/native UI. Source programs read factual3CSV only."
      },
      "reject-negative-weight": {
        "api": "metrics",
        "variant": "reject-negative-weight",
        "language": "python",
        "title": "Reject a declared negative analytical mass",
        "codeFile": "ml14-code/metrics-reject-negative-weight.py",
        "codeSHA256": "ab271951e792dfd4626163d8adcf671653f691f8c48a968fed8ad022de306b14",
        "code": "#!/usr/bin/env python3\n\"\"\"ML14 standalone exact finite study, Python standard library only.\nInputs: only the three retained factual source CSVs below.\nDerived role/target/group/eligibility columns in those CSVs are NOT inputs.\nRebuilds SHA256 roles, train-only medians/cell scores, validation thresholds,\ntest curves, binary-event reliability and descriptive group ledgers.\nCosts 1/1,1/5,5/1 are hypothetical units, not measured intervention returns.\nThis is author public reproduction, not independent scientific review.\n\"\"\"\n\"\"\"Author Fraction reference, separate from product JavaScript; not independent peer.\"\"\"\nfrom fractions import Fraction as F\nfrom collections import Counter,defaultdict\ndef read(raw):\n rows=[]\n for i,r in enumerate(raw):\n  s=None if r['score']is None else F(str(r['score']));y=None if r['y']is None else F(int(r['y']))if isinstance(r['y'],bool)else F(str(r['y']));w=F(str(r.get('weight','1')));role=r.get('role','evaluation')\n  rows.append(dict(id=r['id'],index=i,score=s,y=y,w=w,role=role,group=r.get('group'),eligible=s is not None and y is not None and w>0 and role!='excluded'))\n return rows\ndef scoped(rows,role='all'):return rows if role=='all'else[r for r in rows if r['role']==role]\ndef divide(n,d):return None if not d else n/d\ndef policy(v):return v if v in ['always-negative','always-positive']else F(str(v))\ndef positive(p,s):return p=='always-positive'if isinstance(p,str)else s>=p\ndef cost(a=None):\n a={}if a is None else a;fp=F(str(a.get('falsePositive','1')));fn=F(str(a.get('falseNegative','1')));return fp,fn\ndef metrics(rows,threshold=F(1,2),cc=(F(1),F(1))):\n counts=dict(TP=F(0),FP=F(0),FN=F(0),TN=F(0));brier=F(0);pred=[]\n for r in rows:\n  if not r['eligible']:pred.append(dict(id=r['id'],index=r['index'],eligible=False,decision=None,probability=None,Brier=None));continue\n  yes=positive(threshold,r['score']);cell=('T'if yes==bool(r['y'])else'F')+('P'if yes else'N');counts[cell]+=r['w'];loss=(r['score']-r['y'])**2;brier+=r['w']*loss;pred.append(dict(id=r['id'],index=r['index'],eligible=True,decision=int(yes),probability=r['score'],Brier=loss))\n TP,FP,FN,TN=[counts[k]for k in ['TP','FP','FN','TN']];P=TP+FN;N=TN+FP;mass=P+N;PP=TP+FP;PN=TN+FN;TPR=divide(TP,P);TNR=divide(TN,N);total=FP*cc[0]+FN*cc[1]\n return dict(confusion=counts,mass=mass,positiveTargetMass=P,negativeTargetMass=N,predictedPositiveMass=PP,predictedNegativeMass=PN,prevalence=divide(P,mass),selectionRate=divide(PP,mass),accuracy=divide(TP+TN,mass),precision=divide(TP,PP),negativePredictiveValue=divide(TN,PN),TPR=TPR,FPR=divide(FP,N),TNR=TNR,FNR=divide(FN,P),F1=divide(2*TP,2*TP+FP+FN),balancedAccuracy=None if TPR is None or TNR is None else(TPR+TNR)/2,Brier=divide(brier,mass),BrierSum=brier,totalCost=total,meanCost=divide(total,mass),predictions=pred,bayesThreshold=divide(cc[0],sum(cc)))\ndef curves(rows):\n use=[r for r in rows if r['eligible']];pos=Counter();neg=Counter()\n for r in use:(pos if r['y']else neg)[r['score']]+=r['w']\n P=sum(pos.values(),F(0));N=sum(neg.values(),F(0));pairs=F(0)\n for a,wa in pos.items():\n  for b,wb in neg.items():pairs+=wa*wb*(F(1)if a>b else F(1,2)if a==b else F(0))\n thresholds=['always-negative']+sorted({r['score']for r in use},reverse=True);points=[];AP=F(0);trap=F(0);lastR=F(0);lastP=F(1)\n for i,p in enumerate(thresholds):\n  m=metrics(rows,p);points.append(dict(policy=p,TP=m['confusion']['TP'],FP=m['confusion']['FP'],FN=m['confusion']['FN'],TN=m['confusion']['TN'],TPR=m['TPR'],FPR=m['FPR'],precision=m['precision'],recall=m['TPR']))\n  if i and P:\n   R=m['TPR'];PP=m['precision'];AP+=(R-lastR)*PP;trap+=(R-lastR)*(PP+lastP)/2;lastR=R;lastP=PP\n return dict(positiveMass=P,negativeMass=N,ROC_AUC=divide(pairs,P*N),weightedConcordantPlusHalfTiedMass=pairs,averagePrecision=AP if P else None,PRTrapezoidWithInitialPrecisionOne=trap if P else None,points=points)\ndef choose(rows,a,cc):\n sr=a.get('selectionRole','validation');er=a.get('evaluationRole','test');rr=scoped(rows,sr);thresholds=[policy(t)for t in a['thresholds']]if'thresholds'in a else['always-negative']+sorted({r['score']for r in rr if r['eligible']},reverse=True)\n candidates=[]\n for i,p in enumerate(thresholds):\n  m=metrics(rr,p,cc);reasons=[]\n  if'minTPR'in a and(m['TPR']is None or m['TPR']<F(str(a['minTPR']))):reasons.append('TPR-undefined'if m['TPR']is None else'below-minTPR')\n  if'maxFPR'in a and(m['FPR']is None or m['FPR']>F(str(a['maxFPR']))):reasons.append('FPR-undefined'if m['FPR']is None else'above-maxFPR')\n  candidates.append(dict(index=i,policy=p,metrics=m,feasible=not reasons,reasons=reasons))\n eligible=[c for c in candidates if c['feasible']];best=min(eligible,key=lambda c:(c['metrics']['meanCost'],c['index']))if eligible else None\n return dict(selectedIndex=None if best is None else best['index'],selectedPolicy=None if best is None else best['policy'],candidates=candidates,selectedValidation=None if best is None else best['metrics'],evaluation=None if best is None or er=='none'else metrics(scoped(rows,er),best['policy'],cc),selectionIDs=[r['id']for r in rr if r['eligible']])\ndef calibrate(rows,ee):\n buckets=[[]for _ in range(len(ee)-1)]\n for r in rows:\n  if not r['eligible']:continue\n  j=next((i for i in range(len(ee)-1)if r['score']<ee[i+1]),len(ee)-2);buckets[j].append(r)\n mass=sum((r['w']for r in rows if r['eligible']),F(0));P=sum((r['w']*r['y']for r in rows if r['eligible']),F(0));pi=divide(P,mass);Brier=None if not mass else sum((r['w']*(r['score']-r['y'])**2 for r in rows if r['eligible']),F(0))/mass;ECE=F(0);reliability=F(0);resolution=F(0);correction=F(0);bins=[]\n for i,rr in enumerate(buckets):\n  w=sum((r['w']for r in rr),F(0));mp=None if not w else sum((r['w']*r['score']for r in rr),F(0))/w;o=None if not w else sum((r['w']*r['y']for r in rr),F(0))/w\n  variance=None if not w else sum((r['w']*(r['score']-mp)**2 for r in rr),F(0))/w\n  covariance=None if not w else sum((r['w']*(r['score']-mp)*(r['y']-o)for r in rr),F(0))/w\n  bc=None if not w else variance-2*covariance;gap=None if not w else mp-o\n  bins.append(dict(index=i,rows=len(rr),mass=w,meanPrediction=mp,eventRate=o,gap=gap,absoluteGap=None if gap is None else abs(gap),scoreVariance=variance,scoreTargetCovariance=covariance,withinBinCorrection=bc,ids=[r['id']for r in rr]))\n  if w:\n   share=w/mass;ECE+=share*abs(gap);reliability+=share*gap**2;resolution+=share*(o-pi)**2;correction+=share*bc\n uncertainty=None if pi is None else pi*(1-pi);residual=None if Brier is None else Brier-(uncertainty-resolution+reliability+correction)\n return dict(mass=mass,prevalence=pi,Brier=Brier,ECE=ECE if mass else None,reliability=reliability if mass else None,resolution=resolution if mass else None,uncertainty=uncertainty,withinBinCorrection=correction if mass else None,BrierIdentityResidual=residual,bins=bins)\ndef typed(v):return type(v).__name__,v\ndef groups(rows,p,cc):\n bins={}\n for r in rows:\n  if r['group']is not None:bins.setdefault(typed(r['group']),[]).append(r)\n gm=[dict(group=rr[0]['group'],metrics=metrics(rr,p,cc))for rr in bins.values()];overall=metrics(rows,p,cc);unknown=metrics([r for r in rows if r['group']is None],p,cc);gaps={}\n for key in ['prevalence','selectionRate','TPR','FPR','precision','accuracy','meanCost']:\n  positive=[g for g in gm if g['metrics']['mass']>0];undefined=[g['group']for g in positive if g['metrics'][key]is None];vals=[g['metrics'][key]for g in positive if g['metrics'][key]is not None]\n  gaps[key]=dict(value=None if len(positive)<2 or undefined else max(vals)-min(vals),undefinedGroups=undefined,comparedPositiveMassGroups=[g['group']for g in positive])\n return dict(overall=overall,groups=gm,unknownGroup=unknown,gaps=gaps,partitionMassResidual=overall['mass']-unknown['mass']-sum((g['metrics']['mass']for g in gm),F(0)))\ndef actual_model(M):\n raw=M['records'];cat=M['categoricalFeatures'];p=len(raw[0]['x']);train=[r for r in raw if r['role']=='train'];medians=[]\n for j in range(p):\n  if j in cat:medians.append(None);continue\n  values=sorted(F(r['x'][j])for r in train);n=len(values);medians.append(values[n//2]if n%2 else(values[n//2-1]+values[n//2])/2)\n def transform(r):return[F(v)if j in cat else F(int(F(v)>medians[j]))for j,v in enumerate(r['x'])]\n counts={}\n for r in train:\n  key=tuple(transform(r));n,s=counts.get(key,(0,0));counts[key]=(n+1,s+int(r['y']))\n probabilities={k:F(s+1,n+2)for k,(n,s)in counts.items()};fallback=F(sum(int(r['y'])for r in train)+1,len(train)+2);scored=[]\n for i,r in enumerate(raw):\n  eligible=r['role']!='excluded';z=transform(r)if eligible else None;key=None if z is None else tuple(z);score=None if not eligible else probabilities.get(key,fallback)\n  scored.append(dict(id=r['id'],index=i,role=r['role'],group=r['group'],y=None if r['y']is None else F(r['y']),score=score,w=F(1),eligible=eligible,transformedX=z,unseenCell=None if not eligible else key not in probabilities))\n return dict(medians=medians,cells=counts,probabilities=probabilities,fallback=fallback,rows=scored,trainIDs=[r['id']for r in train])\n\n\nimport csv,json,hashlib,argparse,datetime\nfrom pathlib import Path\ndef missing(v):return None if v in ['', '.',None]else v\ndef load_sources(folder):\n def read_csv(name):\n  with (folder/name).open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))\n wb=read_csv('actual64-country-four-indicators-original-2024.csv')\n codes=['NY.GDP.PCAP.KD','NY.GDP.MKTP.KD.ZG','FP.CPI.TOTL.ZG','SP.DYN.LE00.IN']\n lookup={(r['countryISO3'],r['indicatorID']):r for r in wb};country=[]\n for i,iso in enumerate(sorted({r['countryISO3']for r in wb}),1):\n  native=[lookup[iso,c]for c in codes];v=[missing(r['originalValueToken'])for r in native]\n  country.append(dict(id=iso+':2024',sourceRow=i,originalID=iso,x=v[:3],y=None if v[3]is None else str(int(F(v[3])>=80)),group=None if v[0]is None else str(int(F(v[0])>=25000)),nativeTarget=v[3],nativeSourceRows=';'.join(r['sourceRow']for r in native)))\n nls=read_csv('actual3613-NLS-original52-fields-groups-roles.csv');person=[]\n for r in nls:\n  y=missing(r['wage76']);person.append(dict(id='person:'+r['sourceRow'],sourceRow=int(r['sourceRow']),originalID=r['id'],x=[missing(r[k])for k in ['ed76','age76','nearc4']],y=None if y is None else str(int(F(y)>=500)),group=missing(r['black']),nativeTarget=y,nativeSourceRows=r['sourceRow']))\n ch=read_csv('actual3150-churn-original14-fields-groups-roles.csv');company=[]\n for r in ch:\n  company.append(dict(id='customer:'+r['sourceRow'],sourceRow=int(r['sourceRow']),originalID='',x=[missing(r[k])for k in ['Call  Failure','Complains','Subscription  Length','Seconds of Use']],y=missing(r['Churn']),group=missing(r['Tariff Plan']),nativeTarget=missing(r['Churn']),nativeSourceRows=r['sourceRow']))\n assert len(wb)==64 and len(country)==16 and len(nls)==3613 and len(ch)==3150\n assert [int(r['sourceRow'])for r in ch if r['Charge  Amount']=='10']==[474,2174,2274,2374,2674,2924,2974]\n models={}\n for kind,raw,cat,units in [('country',country,[],['constant2015USD/person','annualPercent','annualPercent']),('person',person,[2],['years','years','nativeCategory']),('company',company,[1],['count','nativeCategory','months','seconds'])]:\n  order=sorted(range(len(raw)),key=lambda i:(hashlib.sha256(('ML14-role|'+kind+'|'+raw[i]['id']).encode()).hexdigest(),i))\n  for rank,i in enumerate(order):\n   r=raw[i];r['plannedRole']='test'if rank%5==0 else'validation'if rank%5==1 else'train';r['eligible']=None not in r['x']+[r['y']];r['role']=r['plannedRole']if r['eligible']else'excluded';r['weight']='1'\n  models[kind]=dict(records=raw,categoricalFeatures=cat,featureUnits=units)\n assert sum(r['eligible']for r in person)==3017\n return models\n\ndef exact(v):return ''if v is None else str(v)\ndef approx(v):return ''if v is None else format(float(v),'.17g')\ndef scalar_fields(m,keys):\n out={}\n for k in keys:\n  out[k+'Exact']=exact(m[k]);out[k+'Approx']=approx(m[k])\n return out\nCOUNTS=['mass','positiveTargetMass','negativeTargetMass','predictedPositiveMass','predictedNegativeMass']\nRATES=['prevalence','selectionRate','accuracy','precision','negativePredictiveValue','TPR','FPR','TNR','FNR','F1','balancedAccuracy','Brier','BrierSum','totalCost','meanCost']\nSCENARIOS=[('equal',F(1),F(1)),('miss-five',F(1),F(5)),('alarm-five',F(5),F(1))]\ndef packed(v):\n if isinstance(v,F):return str(v)\n if isinstance(v,dict):return{str(k):packed(x)for k,x in v.items()}\n if isinstance(v,(tuple,list)):return[packed(x)for x in v]\n return v\ndef run_study(source,out):\n out.mkdir(parents=True,exist_ok=True);models=load_sources(source)\n tables={name:[]for name in ['predictions','lineage','fit-medians','fit-cells','validation-candidates','test-metrics','test-curves','calibration-bins','group-metrics','chart-points']}\n studies={};charts=[]\n def point(kind,chart,series,index,x,y,xunit='dimensionless',yunit='dimensionless',role='test',tag=''):\n  tables['chart-points'].append(dict(kind=kind,chart=chart,series=series,index=index,xExact=exact(x),xApprox=approx(x),yExact=exact(y),yApprox=approx(y),xUnit=xunit,yUnit=yunit,role=role,tag=tag))\n for kind,M in models.items():\n  fit=actual_model(M);rr=fit['rows'];native=M['records'];test=scoped(rr,'test');cv=curves(test);cal=calibrate(test,[F(0),F(1,5),F(2,5),F(3,5),F(4,5),F(1)]);scenarios=[]\n  for i,r in enumerate(rr):\n   n=native[i];reason=''if r['eligible']else'required-X-or-Y-missing'\n   tables['predictions'].append(dict(kind=kind,id=r['id'],sourceRow=n['sourceRow'],originalID=n['originalID'],plannedRole=n['plannedRole'],role=r['role'],group=''if r['group']is None else r['group'],eligible=int(r['eligible']),targetExact=exact(r['y']),probabilityExact=exact(r['score']),probabilityApprox=approx(r['score']),unseenCell=''if r['unseenCell']is None else int(r['unseenCell']),transformedX=''if r['transformedX']is None else'|'.join(map(str,r['transformedX'])),reason=reason))\n   tables['lineage'].append(dict(kind=kind,id=r['id'],sourceRow=n['sourceRow'],originalID=n['originalID'],nativeSourceRows=n['nativeSourceRows'],rawX='|'.join(''if x is None else x for x in n['x']),nativeTarget=''if n['nativeTarget']is None else n['nativeTarget'],derivedTarget=exact(r['y']),nativeGroup=''if n['group']is None else n['group'],plannedRole=n['plannedRole'],role=r['role'],eligible=int(r['eligible']),analyticalMass='1',reason=reason))\n  for j,v in enumerate(fit['medians']):tables['fit-medians'].append(dict(kind=kind,feature=j,categorical=int(j in M['categoricalFeatures']),fitRows=len(fit['trainIDs']),medianExact=exact(v),medianApprox=approx(v),unit=M['featureUnits'][j]))\n  for key,(mass,pos)in fit['cells'].items():tables['fit-cells'].append(dict(kind=kind,cell='|'.join(map(str,key)),trainingRows=mass,positiveRows=pos,probabilityExact=exact(fit['probabilities'][key]),probabilityApprox=approx(fit['probabilities'][key]),fallbackExact=exact(fit['fallback']),fallbackApprox=approx(fit['fallback'])))\n  for j,p in enumerate(cv['points']):\n   policy=p['policy'];tables['test-curves'].append(dict(kind=kind,point=j,policy=policy if isinstance(policy,str)else'threshold',thresholdExact=''if isinstance(policy,str)else exact(policy),thresholdApprox=''if isinstance(policy,str)else approx(policy),**scalar_fields(p,['TP','FP','FN','TN','TPR','FPR','precision','recall'])))\n   point(kind,'roc','ROC',j,p['FPR'],p['TPR']);point(kind,'pr','PR-observed',j,p['recall'],p['precision'])\n  for b in cal['bins']:\n   tables['calibration-bins'].append(dict(kind=kind,bin=b['index'],leftExact=str(F(b['index'],5)),rightExact=str(F(b['index']+1,5)),rightClosed=int(b['index']==4),rows=b['rows'],ids=';'.join(str(i)for i in b['ids']),**scalar_fields(b,['mass','meanPrediction','eventRate','gap','absoluteGap','scoreVariance','scoreTargetCovariance','withinBinCorrection'])))\n   point(kind,'reliability','Binary event rate',b['index'],b['meanPrediction'],b['eventRate'],tag='rows='+str(b['rows']))\n  for j,r in enumerate(test):\n   point(kind,'test-scores','Training-fitted probability',j,F(j+1),r['score'],'test-row position','probability',tag=r['id'])\n   point(kind,'test-scores','Observed Y',j,F(j+1),r['y'],'test-row position','binary target',tag=r['id'])\n  for name,fp,fn in SCENARIOS:\n   choice=choose(rr,{},(fp,fn));gm=groups(test,choice['selectedPolicy'],(fp,fn));scenarios.append(dict(name=name,costs=dict(falsePositive=fp,falseNegative=fn),selection=choice,groups=gm));ev=choice['evaluation']\n   for c in choice['candidates']:\n    policy=c['policy'];mm=c['metrics'];tables['validation-candidates'].append(dict(kind=kind,scenario=name,candidate=c['index'],selected=int(c['index']==choice['selectedIndex']),policy=policy if isinstance(policy,str)else'threshold',thresholdExact=''if isinstance(policy,str)else exact(policy),thresholdApprox=''if isinstance(policy,str)else approx(policy),feasible=int(c['feasible']),reasons=';'.join(c['reasons']),**{k+'Exact':str(v)for k,v in mm['confusion'].items()},**scalar_fields(mm,COUNTS+['TPR','FPR','precision','meanCost','totalCost'])))\n    point(kind,'validation-cost',name,c['index'],F(c['index']),mm['meanCost'],'candidate index','hypothetical cost units/mass','validation',tag=exact(policy))\n   mm={**ev,**ev['confusion'],**{k:cv[k]for k in ['ROC_AUC','averagePrecision','PRTrapezoidWithInitialPrecisionOne']},**{k:cal[k]for k in ['ECE','reliability','resolution','uncertainty','withinBinCorrection','BrierIdentityResidual']}}\n   for key in ['TP','FP','FN','TN']+COUNTS+RATES+['ROC_AUC','averagePrecision','PRTrapezoidWithInitialPrecisionOne','ECE','reliability','resolution','uncertainty','withinBinCorrection','BrierIdentityResidual']:\n    unit='rows'if key in ['TP','FP','FN','TN']+COUNTS else'hypothetical cost units'if key=='totalCost'else'hypothetical cost units/mass'if key=='meanCost'else'sum squared-probability loss'if key=='BrierSum'else'dimensionless'\n    tables['test-metrics'].append(dict(kind=kind,scenario=name,metric=key,valueExact=exact(mm[key]),valueApprox=approx(mm[key]),unit=unit))\n   allg=[('overall','all',gm['overall'])]+[('known',str(g['group']),g['metrics'])for g in gm['groups']]+[('unknown','',gm['unknownGroup'])]\n   for j,(typ,token,g)in enumerate(allg):\n    tables['group-metrics'].append(dict(kind=kind,scenario=name,groupType=typ,groupToken=token,retainedRows=g.get('retainedRows',sum((r['group']==token)if typ=='known'else(r['group']is None)if typ=='unknown'else True for r in test)),**{k+'Exact':str(v)for k,v in g['confusion'].items()},**scalar_fields(g,COUNTS+RATES)))\n    if typ=='known':point(kind,'group-TPR',name,j-1,F(j-1),g['TPR'],'declared group position','TPR',tag=token)\n  studies[kind]=dict(kind=kind,rows=len(native),eligibleRows=sum(r['eligible']for r in rr),trainingIDs=fit['trainIDs'],fitMedians=fit['medians'],fitCells=[dict(cell=list(k),mass=n,positive=s,probability=fit['probabilities'][k])for k,(n,s)in fit['cells'].items()],fallback=fit['fallback'],scenarios=scenarios,testCurves=cv,testCalibration=cal,rowsScored=rr)\n files=[]\n for name,rows in tables.items():\n  p=out/('computed-'+name+'.csv')\n  with p.open('w',encoding='utf8',newline='')as f:w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows)\n  files.append(dict(file=p.name,rows=len(rows),columns=len(rows[0]),bodyFields=len(rows)*len(rows[0]),sha256=hashlib.sha256(p.read_bytes()).hexdigest()))\n (out/'study.json').write_text(json.dumps(packed(studies),ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\n sourceFiles=[source/n for n in ['actual64-country-four-indicators-original-2024.csv','actual3613-NLS-original52-fields-groups-roles.csv','actual3150-churn-original14-fields-groups-roles.csv']]\n provenance=dict(chapter='ML-14',arithmetic='Python stdlib Fraction exact finite values from original decimal strings; binary64 valueApprox is display only.',inputs=[dict(file=p.name,sha256=hashlib.sha256(p.read_bytes()).hexdigest())for p in sourceFiles],priorEngineModelsScoresOrComputedFilesRead=False,roleRule=\"SHA256('ML14-role|'+kind+'|'+ID),rankmod5=0test/1validation/others train before eligibility\",costs='Hypothetical1/1,1/5,5/1; no causal intervention returns',files=files,observations={k:dict(sourceRows=v['rows'],eligibleRows=v['eligibleRows'],trainingRows=len(v['trainingIDs']))for k,v in studies.items()})\n (out/'provenance.json').write_text(json.dumps(provenance,ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\n print(json.dumps(dict(status='PASS standalone completed',files=len(files),bodyFields=sum(f['bodyFields']for f in files),observations=provenance['observations'])))\n\n# Fixed declared examples: full web budget/option validation is not reproduced.\nfrom html import escape\nimport textwrap\ndef validated_rows(raw):\n for r in raw:\n  assert F(str(r.get('weight','1')))>=0,'negative analytical mass'\n  assert r['score']is None or 0<=F(str(r['score']))<=1,'score outside zero/one'\n  assert r['y']is None or F(str(int(r['y']))if isinstance(r['y'],bool)else str(r['y']))in [0,1],'binary target required'\n return read(raw)\ndef serial(v):\n if isinstance(v,F):return dict(exactFraction=str(v),value=float(v))\n if isinstance(v,(list,tuple)):return[serial(x)for x in v]\n if isinstance(v,dict):return{k:serial(x)for k,x in v.items()}\n return v\ndef fixed_svg(path,points,title,xlabel,ylabel,legend):\n use=[p for p in points if p['xExact']!=''and p['yExact']!=''];xs=[float(F(p['xExact']))for p in use];ys=[float(F(p['yExact']))for p in use]\n xmin=min(xs,default=0);xmax=max(xs,default=1);ymin=min([0]+ys);ymax=max([0]+ys)\n if xmin==xmax:xmin-=.5;xmax+=.5\n if ymin==ymax:ymax=ymin+1\n X=lambda v:85+(float(v)-xmin)/(xmax-xmin)*480;Y=lambda v:278-(float(v)-ymin)/(ymax-ymin)*175\n s='<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"620\" height=\"360\" viewBox=\"0 0 620 360\"><rect width=\"620\" height=\"360\" fill=\"white\"/><g font-family=\"Arial, sans-serif\" font-size=\"13\" fill=\"#17324d\">'\n for i,line in enumerate(textwrap.wrap(title,width=65)):s+='<text x=\"25\" y=\"'+str(24+i*18)+'\">'+escape(line)+'</text>'\n colors=['#176b9b','#b85e18','#437e4d']\n for i,label in enumerate(legend):s+='<circle cx=\"'+str(30+i*250)+'\" cy=\"76\" r=\"4\" fill=\"'+colors[i%3]+'\"/><text x=\"'+str(42+i*250)+'\" y=\"80\">'+escape(label)+'</text>'\n s+='<path d=\"M85 98V278H575\" fill=\"none\" stroke=\"#52677d\"/><text text-anchor=\"middle\" x=\"325\" y=\"338\">'+escape(xlabel)+'</text><text text-anchor=\"middle\" transform=\"translate(21,190) rotate(-90)\">'+escape(ylabel)+'</text>'\n for i in range(5):\n  xx=xmin+(xmax-xmin)*i/4;yy=ymin+(ymax-ymin)*i/4;s+='<text text-anchor=\"middle\" x=\"'+format(X(xx),'.9g')+'\" y=\"305\">'+format(xx,'.4g')+'</text><text text-anchor=\"end\" x=\"77\" y=\"'+format(Y(yy)+4,'.9g')+'\">'+format(yy,'.4g')+'</text>'\n for p in use:s+='<circle cx=\"'+format(X(F(p['xExact'])),'.9g')+'\" cy=\"'+format(Y(F(p['yExact'])),'.9g')+'\" r=\"3\" fill=\"'+colors[p['series']%3]+'\"/>'\n path.write_text(s+'</g></svg>',encoding='utf8')\ndef fixed_run():\n ap=argparse.ArgumentParser();ap.add_argument('--out',type=Path,default=Path('results'));ap.add_argument('--data-dir',type=Path,default=Path(__file__).resolve().parent.parent/'ml14-sources');args=ap.parse_args();args.out.mkdir(parents=True,exist_ok=True)\n api=FIXED['api'];a=FIXED['args'];summary=[];points=[];xlabel='Declared index';ylabel='Value';legend=['Declared result']\n def metric(name,v,unit='dimensionless'):\n  q=None if v is None else v if isinstance(v,F)else F(v);summary.append(dict(metric=name,value='undefined'if q is None else format(float(q),'.9g'),exactValue=''if q is None else str(q),unit=unit,defined=int(q is not None)))\n def pt(i,x,y,ident='',series=0):\n  points.append(dict(series=series,index=i,xExact=''if x is None else str(F(x)),x='undefined'if x is None else format(float(x),'.9g'),yExact=''if y is None else str(F(y)),y='undefined'if y is None else format(float(y),'.9g'),id=str(ident)))\n if api=='realdata':\n  models=load_sources(args.data_dir);model=models[a['kind']];fit=actual_model(model);rr=fit['rows'];test=scoped(rr,'test');scenarios=[]\n  for name,fp,fn in SCENARIOS:\n   c=choose(rr,{},(fp,fn));scenarios.append(dict(name=name,selection=c));metric(name+'Threshold',c['selectedPolicy']);metric(name+'TestCost',c['evaluation']['meanCost'],'hypothetical cost units/mass')\n  cv=curves(test);cal=calibrate(test,[F(0),F(1,5),F(2,5),F(3,5),F(4,5),F(1)]);metric('testAUC',cv['ROC_AUC']);metric('testAP',cv['averagePrecision']);metric('testBrier',cal['Brier']);metric('eligibleRows',sum(r['eligible']for r in rr),'rows')\n  for i,r in enumerate(test):pt(i,i+1,r['score'],r['id'],0);pt(i,i+1,r['y'],r['id'],1)\n  full=dict(kind=a['kind'],fitMedians=fit['medians'],fitCells=[dict(cell=list(k),mass=n,positive=s,probability=fit['probabilities'][k])for k,(n,s)in fit['cells'].items()],rowsScored=rr,scenarios=scenarios,testCurves=cv,testCalibration=cal);xlabel='Test row, native order';ylabel='Y or probability';legend=['Training-fitted probability','Observed Y']\n else:\n  rr=validated_rows(a['rows']);role=a.get('role','all');frame=scoped(rr,role);cc=cost(a.get('costs'));t=policy(a.get('threshold','1/2'))\n  if api=='metrics':\n   full=metrics(frame,t,cc)\n   for k in ['mass','accuracy','precision','TPR','FPR','F1','Brier','meanCost']:metric(k,full[k],'mass'if k=='mass'else'hypothetical cost units/mass'if k=='meanCost'else'dimensionless')\n   metric('BayesThreshold',full['bayesThreshold'])\n   for i,k in enumerate(['TP','FP','FN','TN']):pt(i,i,full['confusion'][k],k)\n   xlabel='TP / FP / FN / TN positions';ylabel='Analytical mass'\n  elif api=='curves':\n   full=curves(frame)\n   for k in ['ROC_AUC','averagePrecision','PRTrapezoidWithInitialPrecisionOne']:metric(k,full[k])\n   for i,p in enumerate(full['points']):pt(i,p['FPR'],p['TPR'],str(p['policy']))\n   xlabel='False positive rate';ylabel='True positive rate';legend=['Observed ROC operating points']\n  elif api=='choose':\n   full=choose(rr,a,cc);metric('selectedIndex',full['selectedIndex'],'candidate index');metric('minimumCost',None if full['selectedValidation']is None else full['selectedValidation']['meanCost'],'hypothetical cost units/mass');metric('feasible',int(full['selectedIndex']is not None),'indicator')\n   for c in full['candidates']:pt(c['index'],c['index'],c['metrics']['meanCost'],str(c['policy']))\n   xlabel='Validation candidate';ylabel='Assumed cost / mass';legend=['Validation candidate costs']\n  elif api=='calibrate':\n   full=calibrate(frame,[F(str(e))for e in a.get('binEdges',['0','1/5','2/5','3/5','4/5','1'])])\n   for k in ['ECE','Brier','uncertainty','resolution','reliability','withinBinCorrection','BrierIdentityResidual']:metric(k,full[k])\n   for b in full['bins']:pt(b['index'],b['meanPrediction'],b['eventRate'],'bin:'+str(b['index']))\n   xlabel='Bin mean forecast';ylabel='Bin event rate';legend=['Binary-event reliability']\n  elif api=='groups':\n   full=groups(frame,t,cc);metric('overallTPR',full['overall']['TPR']);metric('TPRGap',full['gaps']['TPR']['value']);metric('precisionGap',full['gaps']['precision']['value']);metric('unknownMass',full['unknownGroup']['mass'],'mass');metric('partitionResidual',full['partitionMassResidual'],'mass')\n   for i,g in enumerate(full['groups']):pt(i,i,g['metrics']['TPR'],str(g['group']))\n   xlabel='Declared group position';ylabel='True positive rate';legend=['Known-group TPR']\n  else:raise ValueError('unknown fixed API')\n def csvout(name,rows):\n  with(args.out/name).open('w',encoding='utf8',newline='')as f:w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows)\n csvout('summary.csv',summary);csvout('plot-points.csv',points);fixed_svg(args.out/'plot.svg',points,FIXED['title'],xlabel,ylabel,legend)\n (args.out/'full.json').write_text(json.dumps(dict(api=api,variant=FIXED['variant'],input=FIXED['args'],arithmetic='Python standard-library Fraction, declared fixed example; full web validator/budgets not reproduced',result=serial(full)),ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\n print(json.dumps(dict(api=api,variant=FIXED['variant'],summaryMetrics=len(summary),plotSlots=len(points))))\n\nFIXED={'api': 'metrics', 'variant': 'reject-negative-weight', 'args': {'rows': [{'id': 'bad', 'score': '.5', 'y': 0, 'weight': '-1'}]}, 'title': 'Reject a declared negative analytical mass', 'expectedReject': True}\nif __name__=='__main__':fixed_run()\n",
        "codeText": "#!/usr/bin/env python3\n\"\"\"ML14 standalone exact finite study, Python standard library only.\nInputs: only the three retained factual source CSVs below.\nDerived role/target/group/eligibility columns in those CSVs are NOT inputs.\nRebuilds SHA256 roles, train-only medians/cell scores, validation thresholds,\ntest curves, binary-event reliability and descriptive group ledgers.\nCosts 1/1,1/5,5/1 are hypothetical units, not measured intervention returns.\nThis is author public reproduction, not independent scientific review.\n\"\"\"\n\"\"\"Author Fraction reference, separate from product JavaScript; not independent peer.\"\"\"\nfrom fractions import Fraction as F\nfrom collections import Counter,defaultdict\ndef read(raw):\n rows=[]\n for i,r in enumerate(raw):\n  s=None if r['score']is None else F(str(r['score']));y=None if r['y']is None else F(int(r['y']))if isinstance(r['y'],bool)else F(str(r['y']));w=F(str(r.get('weight','1')));role=r.get('role','evaluation')\n  rows.append(dict(id=r['id'],index=i,score=s,y=y,w=w,role=role,group=r.get('group'),eligible=s is not None and y is not None and w>0 and role!='excluded'))\n return rows\ndef scoped(rows,role='all'):return rows if role=='all'else[r for r in rows if r['role']==role]\ndef divide(n,d):return None if not d else n/d\ndef policy(v):return v if v in ['always-negative','always-positive']else F(str(v))\ndef positive(p,s):return p=='always-positive'if isinstance(p,str)else s>=p\ndef cost(a=None):\n a={}if a is None else a;fp=F(str(a.get('falsePositive','1')));fn=F(str(a.get('falseNegative','1')));return fp,fn\ndef metrics(rows,threshold=F(1,2),cc=(F(1),F(1))):\n counts=dict(TP=F(0),FP=F(0),FN=F(0),TN=F(0));brier=F(0);pred=[]\n for r in rows:\n  if not r['eligible']:pred.append(dict(id=r['id'],index=r['index'],eligible=False,decision=None,probability=None,Brier=None));continue\n  yes=positive(threshold,r['score']);cell=('T'if yes==bool(r['y'])else'F')+('P'if yes else'N');counts[cell]+=r['w'];loss=(r['score']-r['y'])**2;brier+=r['w']*loss;pred.append(dict(id=r['id'],index=r['index'],eligible=True,decision=int(yes),probability=r['score'],Brier=loss))\n TP,FP,FN,TN=[counts[k]for k in ['TP','FP','FN','TN']];P=TP+FN;N=TN+FP;mass=P+N;PP=TP+FP;PN=TN+FN;TPR=divide(TP,P);TNR=divide(TN,N);total=FP*cc[0]+FN*cc[1]\n return dict(confusion=counts,mass=mass,positiveTargetMass=P,negativeTargetMass=N,predictedPositiveMass=PP,predictedNegativeMass=PN,prevalence=divide(P,mass),selectionRate=divide(PP,mass),accuracy=divide(TP+TN,mass),precision=divide(TP,PP),negativePredictiveValue=divide(TN,PN),TPR=TPR,FPR=divide(FP,N),TNR=TNR,FNR=divide(FN,P),F1=divide(2*TP,2*TP+FP+FN),balancedAccuracy=None if TPR is None or TNR is None else(TPR+TNR)/2,Brier=divide(brier,mass),BrierSum=brier,totalCost=total,meanCost=divide(total,mass),predictions=pred,bayesThreshold=divide(cc[0],sum(cc)))\ndef curves(rows):\n use=[r for r in rows if r['eligible']];pos=Counter();neg=Counter()\n for r in use:(pos if r['y']else neg)[r['score']]+=r['w']\n P=sum(pos.values(),F(0));N=sum(neg.values(),F(0));pairs=F(0)\n for a,wa in pos.items():\n  for b,wb in neg.items():pairs+=wa*wb*(F(1)if a>b else F(1,2)if a==b else F(0))\n thresholds=['always-negative']+sorted({r['score']for r in use},reverse=True);points=[];AP=F(0);trap=F(0);lastR=F(0);lastP=F(1)\n for i,p in enumerate(thresholds):\n  m=metrics(rows,p);points.append(dict(policy=p,TP=m['confusion']['TP'],FP=m['confusion']['FP'],FN=m['confusion']['FN'],TN=m['confusion']['TN'],TPR=m['TPR'],FPR=m['FPR'],precision=m['precision'],recall=m['TPR']))\n  if i and P:\n   R=m['TPR'];PP=m['precision'];AP+=(R-lastR)*PP;trap+=(R-lastR)*(PP+lastP)/2;lastR=R;lastP=PP\n return dict(positiveMass=P,negativeMass=N,ROC_AUC=divide(pairs,P*N),weightedConcordantPlusHalfTiedMass=pairs,averagePrecision=AP if P else None,PRTrapezoidWithInitialPrecisionOne=trap if P else None,points=points)\ndef choose(rows,a,cc):\n sr=a.get('selectionRole','validation');er=a.get('evaluationRole','test');rr=scoped(rows,sr);thresholds=[policy(t)for t in a['thresholds']]if'thresholds'in a else['always-negative']+sorted({r['score']for r in rr if r['eligible']},reverse=True)\n candidates=[]\n for i,p in enumerate(thresholds):\n  m=metrics(rr,p,cc);reasons=[]\n  if'minTPR'in a and(m['TPR']is None or m['TPR']<F(str(a['minTPR']))):reasons.append('TPR-undefined'if m['TPR']is None else'below-minTPR')\n  if'maxFPR'in a and(m['FPR']is None or m['FPR']>F(str(a['maxFPR']))):reasons.append('FPR-undefined'if m['FPR']is None else'above-maxFPR')\n  candidates.append(dict(index=i,policy=p,metrics=m,feasible=not reasons,reasons=reasons))\n eligible=[c for c in candidates if c['feasible']];best=min(eligible,key=lambda c:(c['metrics']['meanCost'],c['index']))if eligible else None\n return dict(selectedIndex=None if best is None else best['index'],selectedPolicy=None if best is None else best['policy'],candidates=candidates,selectedValidation=None if best is None else best['metrics'],evaluation=None if best is None or er=='none'else metrics(scoped(rows,er),best['policy'],cc),selectionIDs=[r['id']for r in rr if r['eligible']])\ndef calibrate(rows,ee):\n buckets=[[]for _ in range(len(ee)-1)]\n for r in rows:\n  if not r['eligible']:continue\n  j=next((i for i in range(len(ee)-1)if r['score']<ee[i+1]),len(ee)-2);buckets[j].append(r)\n mass=sum((r['w']for r in rows if r['eligible']),F(0));P=sum((r['w']*r['y']for r in rows if r['eligible']),F(0));pi=divide(P,mass);Brier=None if not mass else sum((r['w']*(r['score']-r['y'])**2 for r in rows if r['eligible']),F(0))/mass;ECE=F(0);reliability=F(0);resolution=F(0);correction=F(0);bins=[]\n for i,rr in enumerate(buckets):\n  w=sum((r['w']for r in rr),F(0));mp=None if not w else sum((r['w']*r['score']for r in rr),F(0))/w;o=None if not w else sum((r['w']*r['y']for r in rr),F(0))/w\n  variance=None if not w else sum((r['w']*(r['score']-mp)**2 for r in rr),F(0))/w\n  covariance=None if not w else sum((r['w']*(r['score']-mp)*(r['y']-o)for r in rr),F(0))/w\n  bc=None if not w else variance-2*covariance;gap=None if not w else mp-o\n  bins.append(dict(index=i,rows=len(rr),mass=w,meanPrediction=mp,eventRate=o,gap=gap,absoluteGap=None if gap is None else abs(gap),scoreVariance=variance,scoreTargetCovariance=covariance,withinBinCorrection=bc,ids=[r['id']for r in rr]))\n  if w:\n   share=w/mass;ECE+=share*abs(gap);reliability+=share*gap**2;resolution+=share*(o-pi)**2;correction+=share*bc\n uncertainty=None if pi is None else pi*(1-pi);residual=None if Brier is None else Brier-(uncertainty-resolution+reliability+correction)\n return dict(mass=mass,prevalence=pi,Brier=Brier,ECE=ECE if mass else None,reliability=reliability if mass else None,resolution=resolution if mass else None,uncertainty=uncertainty,withinBinCorrection=correction if mass else None,BrierIdentityResidual=residual,bins=bins)\ndef typed(v):return type(v).__name__,v\ndef groups(rows,p,cc):\n bins={}\n for r in rows:\n  if r['group']is not None:bins.setdefault(typed(r['group']),[]).append(r)\n gm=[dict(group=rr[0]['group'],metrics=metrics(rr,p,cc))for rr in bins.values()];overall=metrics(rows,p,cc);unknown=metrics([r for r in rows if r['group']is None],p,cc);gaps={}\n for key in ['prevalence','selectionRate','TPR','FPR','precision','accuracy','meanCost']:\n  positive=[g for g in gm if g['metrics']['mass']>0];undefined=[g['group']for g in positive if g['metrics'][key]is None];vals=[g['metrics'][key]for g in positive if g['metrics'][key]is not None]\n  gaps[key]=dict(value=None if len(positive)<2 or undefined else max(vals)-min(vals),undefinedGroups=undefined,comparedPositiveMassGroups=[g['group']for g in positive])\n return dict(overall=overall,groups=gm,unknownGroup=unknown,gaps=gaps,partitionMassResidual=overall['mass']-unknown['mass']-sum((g['metrics']['mass']for g in gm),F(0)))\ndef actual_model(M):\n raw=M['records'];cat=M['categoricalFeatures'];p=len(raw[0]['x']);train=[r for r in raw if r['role']=='train'];medians=[]\n for j in range(p):\n  if j in cat:medians.append(None);continue\n  values=sorted(F(r['x'][j])for r in train);n=len(values);medians.append(values[n//2]if n%2 else(values[n//2-1]+values[n//2])/2)\n def transform(r):return[F(v)if j in cat else F(int(F(v)>medians[j]))for j,v in enumerate(r['x'])]\n counts={}\n for r in train:\n  key=tuple(transform(r));n,s=counts.get(key,(0,0));counts[key]=(n+1,s+int(r['y']))\n probabilities={k:F(s+1,n+2)for k,(n,s)in counts.items()};fallback=F(sum(int(r['y'])for r in train)+1,len(train)+2);scored=[]\n for i,r in enumerate(raw):\n  eligible=r['role']!='excluded';z=transform(r)if eligible else None;key=None if z is None else tuple(z);score=None if not eligible else probabilities.get(key,fallback)\n  scored.append(dict(id=r['id'],index=i,role=r['role'],group=r['group'],y=None if r['y']is None else F(r['y']),score=score,w=F(1),eligible=eligible,transformedX=z,unseenCell=None if not eligible else key not in probabilities))\n return dict(medians=medians,cells=counts,probabilities=probabilities,fallback=fallback,rows=scored,trainIDs=[r['id']for r in train])\n\n\nimport csv,json,hashlib,argparse,datetime\nfrom pathlib import Path\ndef missing(v):return None if v in ['', '.',None]else v\ndef load_sources(folder):\n def read_csv(name):\n  with (folder/name).open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))\n wb=read_csv('actual64-country-four-indicators-original-2024.csv')\n codes=['NY.GDP.PCAP.KD','NY.GDP.MKTP.KD.ZG','FP.CPI.TOTL.ZG','SP.DYN.LE00.IN']\n lookup={(r['countryISO3'],r['indicatorID']):r for r in wb};country=[]\n for i,iso in enumerate(sorted({r['countryISO3']for r in wb}),1):\n  native=[lookup[iso,c]for c in codes];v=[missing(r['originalValueToken'])for r in native]\n  country.append(dict(id=iso+':2024',sourceRow=i,originalID=iso,x=v[:3],y=None if v[3]is None else str(int(F(v[3])>=80)),group=None if v[0]is None else str(int(F(v[0])>=25000)),nativeTarget=v[3],nativeSourceRows=';'.join(r['sourceRow']for r in native)))\n nls=read_csv('actual3613-NLS-original52-fields-groups-roles.csv');person=[]\n for r in nls:\n  y=missing(r['wage76']);person.append(dict(id='person:'+r['sourceRow'],sourceRow=int(r['sourceRow']),originalID=r['id'],x=[missing(r[k])for k in ['ed76','age76','nearc4']],y=None if y is None else str(int(F(y)>=500)),group=missing(r['black']),nativeTarget=y,nativeSourceRows=r['sourceRow']))\n ch=read_csv('actual3150-churn-original14-fields-groups-roles.csv');company=[]\n for r in ch:\n  company.append(dict(id='customer:'+r['sourceRow'],sourceRow=int(r['sourceRow']),originalID='',x=[missing(r[k])for k in ['Call  Failure','Complains','Subscription  Length','Seconds of Use']],y=missing(r['Churn']),group=missing(r['Tariff Plan']),nativeTarget=missing(r['Churn']),nativeSourceRows=r['sourceRow']))\n assert len(wb)==64 and len(country)==16 and len(nls)==3613 and len(ch)==3150\n assert [int(r['sourceRow'])for r in ch if r['Charge  Amount']=='10']==[474,2174,2274,2374,2674,2924,2974]\n models={}\n for kind,raw,cat,units in [('country',country,[],['constant2015USD/person','annualPercent','annualPercent']),('person',person,[2],['years','years','nativeCategory']),('company',company,[1],['count','nativeCategory','months','seconds'])]:\n  order=sorted(range(len(raw)),key=lambda i:(hashlib.sha256(('ML14-role|'+kind+'|'+raw[i]['id']).encode()).hexdigest(),i))\n  for rank,i in enumerate(order):\n   r=raw[i];r['plannedRole']='test'if rank%5==0 else'validation'if rank%5==1 else'train';r['eligible']=None not in r['x']+[r['y']];r['role']=r['plannedRole']if r['eligible']else'excluded';r['weight']='1'\n  models[kind]=dict(records=raw,categoricalFeatures=cat,featureUnits=units)\n assert sum(r['eligible']for r in person)==3017\n return models\n\ndef exact(v):return ''if v is None else str(v)\ndef approx(v):return ''if v is None else format(float(v),'.17g')\ndef scalar_fields(m,keys):\n out={}\n for k in keys:\n  out[k+'Exact']=exact(m[k]);out[k+'Approx']=approx(m[k])\n return out\nCOUNTS=['mass','positiveTargetMass','negativeTargetMass','predictedPositiveMass','predictedNegativeMass']\nRATES=['prevalence','selectionRate','accuracy','precision','negativePredictiveValue','TPR','FPR','TNR','FNR','F1','balancedAccuracy','Brier','BrierSum','totalCost','meanCost']\nSCENARIOS=[('equal',F(1),F(1)),('miss-five',F(1),F(5)),('alarm-five',F(5),F(1))]\ndef packed(v):\n if isinstance(v,F):return str(v)\n if isinstance(v,dict):return{str(k):packed(x)for k,x in v.items()}\n if isinstance(v,(tuple,list)):return[packed(x)for x in v]\n return v\ndef run_study(source,out):\n out.mkdir(parents=True,exist_ok=True);models=load_sources(source)\n tables={name:[]for name in ['predictions','lineage','fit-medians','fit-cells','validation-candidates','test-metrics','test-curves','calibration-bins','group-metrics','chart-points']}\n studies={};charts=[]\n def point(kind,chart,series,index,x,y,xunit='dimensionless',yunit='dimensionless',role='test',tag=''):\n  tables['chart-points'].append(dict(kind=kind,chart=chart,series=series,index=index,xExact=exact(x),xApprox=approx(x),yExact=exact(y),yApprox=approx(y),xUnit=xunit,yUnit=yunit,role=role,tag=tag))\n for kind,M in models.items():\n  fit=actual_model(M);rr=fit['rows'];native=M['records'];test=scoped(rr,'test');cv=curves(test);cal=calibrate(test,[F(0),F(1,5),F(2,5),F(3,5),F(4,5),F(1)]);scenarios=[]\n  for i,r in enumerate(rr):\n   n=native[i];reason=''if r['eligible']else'required-X-or-Y-missing'\n   tables['predictions'].append(dict(kind=kind,id=r['id'],sourceRow=n['sourceRow'],originalID=n['originalID'],plannedRole=n['plannedRole'],role=r['role'],group=''if r['group']is None else r['group'],eligible=int(r['eligible']),targetExact=exact(r['y']),probabilityExact=exact(r['score']),probabilityApprox=approx(r['score']),unseenCell=''if r['unseenCell']is None else int(r['unseenCell']),transformedX=''if r['transformedX']is None else'|'.join(map(str,r['transformedX'])),reason=reason))\n   tables['lineage'].append(dict(kind=kind,id=r['id'],sourceRow=n['sourceRow'],originalID=n['originalID'],nativeSourceRows=n['nativeSourceRows'],rawX='|'.join(''if x is None else x for x in n['x']),nativeTarget=''if n['nativeTarget']is None else n['nativeTarget'],derivedTarget=exact(r['y']),nativeGroup=''if n['group']is None else n['group'],plannedRole=n['plannedRole'],role=r['role'],eligible=int(r['eligible']),analyticalMass='1',reason=reason))\n  for j,v in enumerate(fit['medians']):tables['fit-medians'].append(dict(kind=kind,feature=j,categorical=int(j in M['categoricalFeatures']),fitRows=len(fit['trainIDs']),medianExact=exact(v),medianApprox=approx(v),unit=M['featureUnits'][j]))\n  for key,(mass,pos)in fit['cells'].items():tables['fit-cells'].append(dict(kind=kind,cell='|'.join(map(str,key)),trainingRows=mass,positiveRows=pos,probabilityExact=exact(fit['probabilities'][key]),probabilityApprox=approx(fit['probabilities'][key]),fallbackExact=exact(fit['fallback']),fallbackApprox=approx(fit['fallback'])))\n  for j,p in enumerate(cv['points']):\n   policy=p['policy'];tables['test-curves'].append(dict(kind=kind,point=j,policy=policy if isinstance(policy,str)else'threshold',thresholdExact=''if isinstance(policy,str)else exact(policy),thresholdApprox=''if isinstance(policy,str)else approx(policy),**scalar_fields(p,['TP','FP','FN','TN','TPR','FPR','precision','recall'])))\n   point(kind,'roc','ROC',j,p['FPR'],p['TPR']);point(kind,'pr','PR-observed',j,p['recall'],p['precision'])\n  for b in cal['bins']:\n   tables['calibration-bins'].append(dict(kind=kind,bin=b['index'],leftExact=str(F(b['index'],5)),rightExact=str(F(b['index']+1,5)),rightClosed=int(b['index']==4),rows=b['rows'],ids=';'.join(str(i)for i in b['ids']),**scalar_fields(b,['mass','meanPrediction','eventRate','gap','absoluteGap','scoreVariance','scoreTargetCovariance','withinBinCorrection'])))\n   point(kind,'reliability','Binary event rate',b['index'],b['meanPrediction'],b['eventRate'],tag='rows='+str(b['rows']))\n  for j,r in enumerate(test):\n   point(kind,'test-scores','Training-fitted probability',j,F(j+1),r['score'],'test-row position','probability',tag=r['id'])\n   point(kind,'test-scores','Observed Y',j,F(j+1),r['y'],'test-row position','binary target',tag=r['id'])\n  for name,fp,fn in SCENARIOS:\n   choice=choose(rr,{},(fp,fn));gm=groups(test,choice['selectedPolicy'],(fp,fn));scenarios.append(dict(name=name,costs=dict(falsePositive=fp,falseNegative=fn),selection=choice,groups=gm));ev=choice['evaluation']\n   for c in choice['candidates']:\n    policy=c['policy'];mm=c['metrics'];tables['validation-candidates'].append(dict(kind=kind,scenario=name,candidate=c['index'],selected=int(c['index']==choice['selectedIndex']),policy=policy if isinstance(policy,str)else'threshold',thresholdExact=''if isinstance(policy,str)else exact(policy),thresholdApprox=''if isinstance(policy,str)else approx(policy),feasible=int(c['feasible']),reasons=';'.join(c['reasons']),**{k+'Exact':str(v)for k,v in mm['confusion'].items()},**scalar_fields(mm,COUNTS+['TPR','FPR','precision','meanCost','totalCost'])))\n    point(kind,'validation-cost',name,c['index'],F(c['index']),mm['meanCost'],'candidate index','hypothetical cost units/mass','validation',tag=exact(policy))\n   mm={**ev,**ev['confusion'],**{k:cv[k]for k in ['ROC_AUC','averagePrecision','PRTrapezoidWithInitialPrecisionOne']},**{k:cal[k]for k in ['ECE','reliability','resolution','uncertainty','withinBinCorrection','BrierIdentityResidual']}}\n   for key in ['TP','FP','FN','TN']+COUNTS+RATES+['ROC_AUC','averagePrecision','PRTrapezoidWithInitialPrecisionOne','ECE','reliability','resolution','uncertainty','withinBinCorrection','BrierIdentityResidual']:\n    unit='rows'if key in ['TP','FP','FN','TN']+COUNTS else'hypothetical cost units'if key=='totalCost'else'hypothetical cost units/mass'if key=='meanCost'else'sum squared-probability loss'if key=='BrierSum'else'dimensionless'\n    tables['test-metrics'].append(dict(kind=kind,scenario=name,metric=key,valueExact=exact(mm[key]),valueApprox=approx(mm[key]),unit=unit))\n   allg=[('overall','all',gm['overall'])]+[('known',str(g['group']),g['metrics'])for g in gm['groups']]+[('unknown','',gm['unknownGroup'])]\n   for j,(typ,token,g)in enumerate(allg):\n    tables['group-metrics'].append(dict(kind=kind,scenario=name,groupType=typ,groupToken=token,retainedRows=g.get('retainedRows',sum((r['group']==token)if typ=='known'else(r['group']is None)if typ=='unknown'else True for r in test)),**{k+'Exact':str(v)for k,v in g['confusion'].items()},**scalar_fields(g,COUNTS+RATES)))\n    if typ=='known':point(kind,'group-TPR',name,j-1,F(j-1),g['TPR'],'declared group position','TPR',tag=token)\n  studies[kind]=dict(kind=kind,rows=len(native),eligibleRows=sum(r['eligible']for r in rr),trainingIDs=fit['trainIDs'],fitMedians=fit['medians'],fitCells=[dict(cell=list(k),mass=n,positive=s,probability=fit['probabilities'][k])for k,(n,s)in fit['cells'].items()],fallback=fit['fallback'],scenarios=scenarios,testCurves=cv,testCalibration=cal,rowsScored=rr)\n files=[]\n for name,rows in tables.items():\n  p=out/('computed-'+name+'.csv')\n  with p.open('w',encoding='utf8',newline='')as f:w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows)\n  files.append(dict(file=p.name,rows=len(rows),columns=len(rows[0]),bodyFields=len(rows)*len(rows[0]),sha256=hashlib.sha256(p.read_bytes()).hexdigest()))\n (out/'study.json').write_text(json.dumps(packed(studies),ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\n sourceFiles=[source/n for n in ['actual64-country-four-indicators-original-2024.csv','actual3613-NLS-original52-fields-groups-roles.csv','actual3150-churn-original14-fields-groups-roles.csv']]\n provenance=dict(chapter='ML-14',arithmetic='Python stdlib Fraction exact finite values from original decimal strings; binary64 valueApprox is display only.',inputs=[dict(file=p.name,sha256=hashlib.sha256(p.read_bytes()).hexdigest())for p in sourceFiles],priorEngineModelsScoresOrComputedFilesRead=False,roleRule=\"SHA256('ML14-role|'+kind+'|'+ID),rankmod5=0test/1validation/others train before eligibility\",costs='Hypothetical1/1,1/5,5/1; no causal intervention returns',files=files,observations={k:dict(sourceRows=v['rows'],eligibleRows=v['eligibleRows'],trainingRows=len(v['trainingIDs']))for k,v in studies.items()})\n (out/'provenance.json').write_text(json.dumps(provenance,ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\n print(json.dumps(dict(status='PASS standalone completed',files=len(files),bodyFields=sum(f['bodyFields']for f in files),observations=provenance['observations'])))\n\n# Fixed declared examples: full web budget/option validation is not reproduced.\nfrom html import escape\nimport textwrap\ndef validated_rows(raw):\n for r in raw:\n  assert F(str(r.get('weight','1')))>=0,'negative analytical mass'\n  assert r['score']is None or 0<=F(str(r['score']))<=1,'score outside zero/one'\n  assert r['y']is None or F(str(int(r['y']))if isinstance(r['y'],bool)else str(r['y']))in [0,1],'binary target required'\n return read(raw)\ndef serial(v):\n if isinstance(v,F):return dict(exactFraction=str(v),value=float(v))\n if isinstance(v,(list,tuple)):return[serial(x)for x in v]\n if isinstance(v,dict):return{k:serial(x)for k,x in v.items()}\n return v\ndef fixed_svg(path,points,title,xlabel,ylabel,legend):\n use=[p for p in points if p['xExact']!=''and p['yExact']!=''];xs=[float(F(p['xExact']))for p in use];ys=[float(F(p['yExact']))for p in use]\n xmin=min(xs,default=0);xmax=max(xs,default=1);ymin=min([0]+ys);ymax=max([0]+ys)\n if xmin==xmax:xmin-=.5;xmax+=.5\n if ymin==ymax:ymax=ymin+1\n X=lambda v:85+(float(v)-xmin)/(xmax-xmin)*480;Y=lambda v:278-(float(v)-ymin)/(ymax-ymin)*175\n s='<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"620\" height=\"360\" viewBox=\"0 0 620 360\"><rect width=\"620\" height=\"360\" fill=\"white\"/><g font-family=\"Arial, sans-serif\" font-size=\"13\" fill=\"#17324d\">'\n for i,line in enumerate(textwrap.wrap(title,width=65)):s+='<text x=\"25\" y=\"'+str(24+i*18)+'\">'+escape(line)+'</text>'\n colors=['#176b9b','#b85e18','#437e4d']\n for i,label in enumerate(legend):s+='<circle cx=\"'+str(30+i*250)+'\" cy=\"76\" r=\"4\" fill=\"'+colors[i%3]+'\"/><text x=\"'+str(42+i*250)+'\" y=\"80\">'+escape(label)+'</text>'\n s+='<path d=\"M85 98V278H575\" fill=\"none\" stroke=\"#52677d\"/><text text-anchor=\"middle\" x=\"325\" y=\"338\">'+escape(xlabel)+'</text><text text-anchor=\"middle\" transform=\"translate(21,190) rotate(-90)\">'+escape(ylabel)+'</text>'\n for i in range(5):\n  xx=xmin+(xmax-xmin)*i/4;yy=ymin+(ymax-ymin)*i/4;s+='<text text-anchor=\"middle\" x=\"'+format(X(xx),'.9g')+'\" y=\"305\">'+format(xx,'.4g')+'</text><text text-anchor=\"end\" x=\"77\" y=\"'+format(Y(yy)+4,'.9g')+'\">'+format(yy,'.4g')+'</text>'\n for p in use:s+='<circle cx=\"'+format(X(F(p['xExact'])),'.9g')+'\" cy=\"'+format(Y(F(p['yExact'])),'.9g')+'\" r=\"3\" fill=\"'+colors[p['series']%3]+'\"/>'\n path.write_text(s+'</g></svg>',encoding='utf8')\ndef fixed_run():\n ap=argparse.ArgumentParser();ap.add_argument('--out',type=Path,default=Path('results'));ap.add_argument('--data-dir',type=Path,default=Path(__file__).resolve().parent.parent/'ml14-sources');args=ap.parse_args();args.out.mkdir(parents=True,exist_ok=True)\n api=FIXED['api'];a=FIXED['args'];summary=[];points=[];xlabel='Declared index';ylabel='Value';legend=['Declared result']\n def metric(name,v,unit='dimensionless'):\n  q=None if v is None else v if isinstance(v,F)else F(v);summary.append(dict(metric=name,value='undefined'if q is None else format(float(q),'.9g'),exactValue=''if q is None else str(q),unit=unit,defined=int(q is not None)))\n def pt(i,x,y,ident='',series=0):\n  points.append(dict(series=series,index=i,xExact=''if x is None else str(F(x)),x='undefined'if x is None else format(float(x),'.9g'),yExact=''if y is None else str(F(y)),y='undefined'if y is None else format(float(y),'.9g'),id=str(ident)))\n if api=='realdata':\n  models=load_sources(args.data_dir);model=models[a['kind']];fit=actual_model(model);rr=fit['rows'];test=scoped(rr,'test');scenarios=[]\n  for name,fp,fn in SCENARIOS:\n   c=choose(rr,{},(fp,fn));scenarios.append(dict(name=name,selection=c));metric(name+'Threshold',c['selectedPolicy']);metric(name+'TestCost',c['evaluation']['meanCost'],'hypothetical cost units/mass')\n  cv=curves(test);cal=calibrate(test,[F(0),F(1,5),F(2,5),F(3,5),F(4,5),F(1)]);metric('testAUC',cv['ROC_AUC']);metric('testAP',cv['averagePrecision']);metric('testBrier',cal['Brier']);metric('eligibleRows',sum(r['eligible']for r in rr),'rows')\n  for i,r in enumerate(test):pt(i,i+1,r['score'],r['id'],0);pt(i,i+1,r['y'],r['id'],1)\n  full=dict(kind=a['kind'],fitMedians=fit['medians'],fitCells=[dict(cell=list(k),mass=n,positive=s,probability=fit['probabilities'][k])for k,(n,s)in fit['cells'].items()],rowsScored=rr,scenarios=scenarios,testCurves=cv,testCalibration=cal);xlabel='Test row, native order';ylabel='Y or probability';legend=['Training-fitted probability','Observed Y']\n else:\n  rr=validated_rows(a['rows']);role=a.get('role','all');frame=scoped(rr,role);cc=cost(a.get('costs'));t=policy(a.get('threshold','1/2'))\n  if api=='metrics':\n   full=metrics(frame,t,cc)\n   for k in ['mass','accuracy','precision','TPR','FPR','F1','Brier','meanCost']:metric(k,full[k],'mass'if k=='mass'else'hypothetical cost units/mass'if k=='meanCost'else'dimensionless')\n   metric('BayesThreshold',full['bayesThreshold'])\n   for i,k in enumerate(['TP','FP','FN','TN']):pt(i,i,full['confusion'][k],k)\n   xlabel='TP / FP / FN / TN positions';ylabel='Analytical mass'\n  elif api=='curves':\n   full=curves(frame)\n   for k in ['ROC_AUC','averagePrecision','PRTrapezoidWithInitialPrecisionOne']:metric(k,full[k])\n   for i,p in enumerate(full['points']):pt(i,p['FPR'],p['TPR'],str(p['policy']))\n   xlabel='False positive rate';ylabel='True positive rate';legend=['Observed ROC operating points']\n  elif api=='choose':\n   full=choose(rr,a,cc);metric('selectedIndex',full['selectedIndex'],'candidate index');metric('minimumCost',None if full['selectedValidation']is None else full['selectedValidation']['meanCost'],'hypothetical cost units/mass');metric('feasible',int(full['selectedIndex']is not None),'indicator')\n   for c in full['candidates']:pt(c['index'],c['index'],c['metrics']['meanCost'],str(c['policy']))\n   xlabel='Validation candidate';ylabel='Assumed cost / mass';legend=['Validation candidate costs']\n  elif api=='calibrate':\n   full=calibrate(frame,[F(str(e))for e in a.get('binEdges',['0','1/5','2/5','3/5','4/5','1'])])\n   for k in ['ECE','Brier','uncertainty','resolution','reliability','withinBinCorrection','BrierIdentityResidual']:metric(k,full[k])\n   for b in full['bins']:pt(b['index'],b['meanPrediction'],b['eventRate'],'bin:'+str(b['index']))\n   xlabel='Bin mean forecast';ylabel='Bin event rate';legend=['Binary-event reliability']\n  elif api=='groups':\n   full=groups(frame,t,cc);metric('overallTPR',full['overall']['TPR']);metric('TPRGap',full['gaps']['TPR']['value']);metric('precisionGap',full['gaps']['precision']['value']);metric('unknownMass',full['unknownGroup']['mass'],'mass');metric('partitionResidual',full['partitionMassResidual'],'mass')\n   for i,g in enumerate(full['groups']):pt(i,i,g['metrics']['TPR'],str(g['group']))\n   xlabel='Declared group position';ylabel='True positive rate';legend=['Known-group TPR']\n  else:raise ValueError('unknown fixed API')\n def csvout(name,rows):\n  with(args.out/name).open('w',encoding='utf8',newline='')as f:w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows)\n csvout('summary.csv',summary);csvout('plot-points.csv',points);fixed_svg(args.out/'plot.svg',points,FIXED['title'],xlabel,ylabel,legend)\n (args.out/'full.json').write_text(json.dumps(dict(api=api,variant=FIXED['variant'],input=FIXED['args'],arithmetic='Python standard-library Fraction, declared fixed example; full web validator/budgets not reproduced',result=serial(full)),ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\n print(json.dumps(dict(api=api,variant=FIXED['variant'],summaryMetrics=len(summary),plotSlots=len(points))))\n\nFIXED={'api': 'metrics', 'variant': 'reject-negative-weight', 'args': {'rows': [{'id': 'bad', 'score': '.5', 'y': 0, 'weight': '-1'}]}, 'title': 'Reject a declared negative analytical mass', 'expectedReject': True}\nif __name__=='__main__':fixed_run()\n",
        "input": {
          "rows": [
            {
              "id": "bad",
              "score": ".5",
              "y": 0,
              "weight": "-1"
            }
          ]
        },
        "inputFiles": [],
        "returnCode": 1,
        "expectedFailure": true,
        "stdout": "",
        "stderr": "Traceback (most recent call last):\n  File \"[execution directory]\\work\\textbook-rewrite-2026\\ml14-fixed-author-processes\\metrics-reject-negative-weight-python\\metrics-reject-negative-weight.py\", line 265, in <module>\n    if __name__=='__main__':fixed_run()\n                            ^^^^^^^^^^^\n  File \"[execution directory]\\work\\textbook-rewrite-2026\\ml14-fixed-author-processes\\metrics-reject-negative-weight-python\\metrics-reject-negative-weight.py\", line 232, in fixed_run\n    rr=validated_rows(a['rows']);role=a.get('role','all');frame=scoped(rr,role);cc=cost(a.get('costs'));t=policy(a.get('threshold','1/2'))\n       ^^^^^^^^^^^^^^^^^^^^^^^^^\n  File \"[execution directory]\\work\\textbook-rewrite-2026\\ml14-fixed-author-processes\\metrics-reject-negative-weight-python\\metrics-reject-negative-weight.py\", line 193, in validated_rows\n    assert F(str(r.get('weight','1')))>=0,'negative analytical mass'\n           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\nAssertionError: negative analytical mass\n",
        "summary": {},
        "summaryRows": [],
        "plotPoints": [],
        "plotFile": null,
        "plotSHA256": null,
        "files": [],
        "scope": "Actually executed standalone fixed example, Python exact Fraction versus base-R binary64. Approximate R residuals retained; not universal exact arithmetic/web validation/native UI. Source programs read factual3CSV only."
      }
    },
    "r": {
      "six-cards": {
        "api": "metrics",
        "variant": "six-cards",
        "language": "r",
        "title": "Six-card confusion cells at threshold0.8",
        "codeFile": "ml14-code/metrics-six-cards.R",
        "codeSHA256": "e9c0760da39fc91126f223a089e389fc91c161733d309e8a525f47a3fa6f5345",
        "code": "# ML14 standalone public counterpart, base R only.\n# Inputs are only the three factual CSVs; derived columns/previous model answers unused.\n# Binary64 arithmetic, not arbitrary-precision Fraction. At numerical cost ties\n# within 1e-12 retain the earliest candidate. Exact claims belong to Python/web.\n# SHA256 infrastructure below is reused verbatim from the previous public study.\nargs<-commandArgs(trailingOnly=TRUE);filearg<-grep(\"^--file=\",commandArgs(),value=TRUE)\nhere<-if(dir.exists(\"ml14-sources\"))getwd()else if(length(filearg))dirname(normalizePath(sub(\"^--file=\",\"\",filearg[1])))else getwd()\noption<-function(key,default){i<-match(key,args);if(is.na(i))default else args[i+1]}\nsourceDir<-option(\"--source\",file.path(here,\"ml14-sources\"));outDir<-option(\"--out\",file.path(getwd(),\"ml14-r-results\"));dir.create(outDir,recursive=TRUE,showWarnings=FALSE)\nnum<-function(x){x[x%in%c(\"\",\".\")]<-NA_character_;as.numeric(x)}\nfmt<-function(x)ifelse(is.na(x),\"\",sprintf(\"%.17g\",x))\nratio<-function(a,b)if(b==0)NA_real_ else a/b\nreadnative<-function(name)read.csv(file.path(sourceDir,name),check.names=FALSE,colClasses=\"character\",na.strings=character(),stringsAsFactors=FALSE)\n# Vectorized SHA256 for the short ASCII keys used in this study.\n# Unsigned words use exact integer-valued doubles; bit operations use safe\n# 16-bit halves, avoiding R's reserved signed-INT_MIN/NA representation.\nMOD<-2^32\nxor32<-function(a,b) as.double(bitwXor(as.integer(floor(a/65536)),as.integer(floor(b/65536))))*65536+as.double(bitwXor(as.integer(a%%65536),as.integer(b%%65536)))\nand32<-function(a,b) as.double(bitwAnd(as.integer(floor(a/65536)),as.integer(floor(b/65536))))*65536+as.double(bitwAnd(as.integer(a%%65536),as.integer(b%%65536)))\nrot<-function(x,n) floor(x/2^n)+(x%%2^n)*2^(32-n)\nxor3<-function(a,b,c) xor32(xor32(a,b),c)\nK<-c(0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5,0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967,0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070,0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3,0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2)\nsha256<-function(strings) {\n n<-length(strings);bytes<-matrix(0,n,64)\n for(i in seq_len(n)) {v<-utf8ToInt(strings[i]);stopifnot(length(v)<56,all(v<128));if(length(v)) bytes[i,seq_along(v)]<-v;bytes[i,length(v)+1]<-128;bits<-length(v)*8;bytes[i,61:64]<-c(floor(bits/2^24)%%256,floor(bits/2^16)%%256,floor(bits/256)%%256,bits%%256)}\n w<-matrix(0,n,64)\n for(j in 1:16) {b<-4*(j-1)+1;w[,j]<-bytes[,b]*2^24+bytes[,b+1]*2^16+bytes[,b+2]*256+bytes[,b+3]}\n for(j in 17:64) {s0<-xor3(rot(w[,j-15],7),rot(w[,j-15],18),floor(w[,j-15]/8));s1<-xor3(rot(w[,j-2],17),rot(w[,j-2],19),floor(w[,j-2]/1024));w[,j]<-(w[,j-16]+s0+w[,j-7]+s1)%%MOD}\n init<-c(0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19)\n state<-lapply(init,function(v) rep(v,n));a<-state[[1]];b<-state[[2]];c<-state[[3]];d<-state[[4]];e<-state[[5]];f<-state[[6]];g<-state[[7]];h<-state[[8]]\n for(j in 1:64) {S1<-xor3(rot(e,6),rot(e,11),rot(e,25));ch<-xor32(and32(e,f),and32(MOD-1-e,g));t1<-(h+S1+ch+K[j]+w[,j])%%MOD;S0<-xor3(rot(a,2),rot(a,13),rot(a,22));maj<-xor3(and32(a,b),and32(a,c),and32(b,c));t2<-(S0+maj)%%MOD;h<-g;g<-f;f<-e;e<-(d+t1)%%MOD;d<-c;c<-b;b<-a;a<-(t1+t2)%%MOD}\n end<-list(a,b,c,d,e,f,g,h);hex<-lapply(1:8,function(j){v<-(end[[j]]+init[j])%%MOD;paste0(sprintf(\"%04x\",as.integer(floor(v/65536))),sprintf(\"%04x\",as.integer(v%%65536)))})\n do.call(paste0,hex)\n}\nstopifnot(identical(sha256(c(\"abc\",\"\")),c(\"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad\",\"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855\")))\n\nloadData<-function(){\n wb<-readnative(\"actual64-country-four-indicators-original-2024.csv\");codes<-c(\"NY.GDP.PCAP.KD\",\"NY.GDP.MKTP.KD.ZG\",\"FP.CPI.TOTL.ZG\",\"SP.DYN.LE00.IN\");iso<-sort(unique(wb$countryISO3));stopifnot(nrow(wb)==64,length(iso)==16)\n tokens<-t(vapply(iso,function(s)wb$originalValueToken[match(paste(s,codes),paste(wb$countryISO3,wb$indicatorID))],character(4)));vals<-matrix(num(as.vector(tokens)),nrow=nrow(tokens))\n country<-list(id=paste0(iso,\":2024\"),sourceRow=1:16,originalID=iso,x=vals[,1:3,drop=FALSE],rawX=tokens[,1:3,drop=FALSE],nativeTarget=tokens[,4],y=as.integer(vals[,4]>=80),group=ifelse(is.na(vals[,1]),NA_character_,as.character(as.integer(vals[,1]>=25000))),lineage=vapply(iso,function(s)paste(wb$sourceRow[match(paste(s,codes),paste(wb$countryISO3,wb$indicatorID))],collapse=\";\"),character(1)),cat=integer(),units=c(\"constant2015USD/person\",\"annualPercent\",\"annualPercent\"))\n nls<-readnative(\"actual3613-NLS-original52-fields-groups-roles.csv\");raw<-cbind(nls$ed76,nls$age76,nls$nearc4)\n person<-list(id=paste0(\"person:\",nls$sourceRow),sourceRow=as.integer(nls$sourceRow),originalID=nls$id,x=matrix(num(as.vector(raw)),nrow=nrow(raw)),rawX=raw,nativeTarget=nls$wage76,y=as.integer(num(nls$wage76)>=500),group=ifelse(nls$black%in%c(\"\",\".\"),NA_character_,nls$black),lineage=nls$sourceRow,cat=2L,units=c(\"years\",\"years\",\"nativeCategory\"))\n ch<-readnative(\"actual3150-churn-original14-fields-groups-roles.csv\");raw<-cbind(ch[[\"Call  Failure\"]],ch$Complains,ch[[\"Subscription  Length\"]],ch[[\"Seconds of Use\"]])\n company<-list(id=paste0(\"customer:\",ch$sourceRow),sourceRow=as.integer(ch$sourceRow),originalID=rep(\"\",nrow(ch)),x=matrix(num(as.vector(raw)),nrow=nrow(raw)),rawX=raw,nativeTarget=ch$Churn,y=as.integer(ch$Churn),group=ifelse(ch[[\"Tariff Plan\"]]%in%c(\"\",\".\"),NA_character_,ch[[\"Tariff Plan\"]]),lineage=ch$sourceRow,cat=1L,units=c(\"count\",\"nativeCategory\",\"months\",\"seconds\"))\n stopifnot(nrow(nls)==3613,nrow(ch)==3150,identical(as.integer(ch$sourceRow[ch[[\"Charge  Amount\"]]==\"10\"]),c(474L,2174L,2274L,2374L,2674L,2924L,2974L)))\n result<-list(country=country,person=person,company=company)\n for(k in names(result)){d<-result[[k]];n<-length(d$id);d$eligible<-!is.na(d$y)&rowSums(is.na(d$x))==0;hash<-sha256(paste0(\"ML14-role|\",k,\"|\",d$id));rank<-integer(n);rank[order(hash,seq_len(n))]<-seq_len(n)-1L;d$plannedRole<-ifelse(rank%%5==0,\"test\",ifelse(rank%%5==1,\"validation\",\"train\"));d$role<-ifelse(d$eligible,d$plannedRole,\"excluded\");result[[k]]<-d}\n stopifnot(sum(result$person$eligible)==3017);result\n}\nfitmodel<-function(d){\n ids<-which(d$role==\"train\");p<-ncol(d$x);m<-vapply(seq_len(p),function(j)if((j-1)%in%d$cat)NA_real_ else median(d$x[ids,j]),numeric(1));z<-d$x\n for(j in seq_len(p))if(!((j-1)%in%d$cat))z[,j]<-as.numeric(z[,j]>m[j])\n keys<-apply(z,1,function(v)paste(fmt(v),collapse=\"|\"));lev<-unique(keys[ids]);mass<-vapply(lev,function(k)sum(keys[ids]==k),integer(1));positive<-vapply(lev,function(k)sum(d$y[ids][keys[ids]==k]),integer(1));prob<-(positive+1)/(mass+2);fallback<-(sum(d$y[ids])+1)/(length(ids)+2);pred<-prob[match(keys,lev)];unseen<-is.na(pred);pred[unseen]<-fallback;pred[!d$eligible]<-NA_real_;unseen[!d$eligible]<-NA\n list(ids=ids,medians=m,z=z,keys=keys,lev=lev,mass=mass,positive=positive,prob=prob,fallback=fallback,pred=pred,unseen=unseen)\n}\nmeasure<-function(d,p,ids,t=.5,cost=c(1,1)){\n use<-ids[d$eligible[ids]&!is.na(p[ids])];y<-d$y[use];a<-if(is.character(t))rep(t==\"always-positive\",length(use))else p[use]>=t\n TP<-sum(a&y==1);FP<-sum(a&y==0);FN<-sum(!a&y==1);TN<-sum(!a&y==0);P<-TP+FN;N<-FP+TN;W<-P+N;PP<-TP+FP;PN<-TN+FN;TPR<-ratio(TP,P);TNR<-ratio(TN,N);bs<-sum((p[use]-y)^2);tc<-FP*cost[1]+FN*cost[2]\n list(TP=TP,FP=FP,FN=FN,TN=TN,mass=W,positiveTargetMass=P,negativeTargetMass=N,predictedPositiveMass=PP,predictedNegativeMass=PN,prevalence=ratio(P,W),selectionRate=ratio(PP,W),accuracy=ratio(TP+TN,W),precision=ratio(TP,PP),negativePredictiveValue=ratio(TN,PN),TPR=TPR,FPR=ratio(FP,N),TNR=TNR,FNR=ratio(FN,P),F1=ratio(2*TP,2*TP+FP+FN),balancedAccuracy=if(is.na(TPR)||is.na(TNR))NA_real_ else(TPR+TNR)/2,Brier=ratio(bs,W),BrierSum=bs,totalCost=tc,meanCost=ratio(tc,W))\n}\ncurves<-function(d,p,ids){\n use<-ids[d$eligible[ids]&!is.na(p[ids])];scores<-sort(unique(p[use]),decreasing=TRUE);policies<-c(list(\"always-negative\"),as.list(scores));points<-lapply(policies,function(t){m<-measure(d,p,ids,t);c(list(policy=t),m[c(\"TP\",\"FP\",\"FN\",\"TN\",\"TPR\",\"FPR\",\"precision\")],list(recall=m$TPR))})\n pos<-use[d$y[use]==1];neg<-use[d$y[use]==0];U<-0;for(i in pos)U<-U+sum(p[i]>p[neg])+.5*sum(p[i]==p[neg])\n AP<-0;trap<-0;lastR<-0;lastP<-1\n if(length(pos)&&length(scores))for(j in seq_along(scores)){z<-points[[j+1]];AP<-AP+(z$recall-lastR)*z$precision;trap<-trap+(z$recall-lastR)*(z$precision+lastP)/2;lastR<-z$recall;lastP<-z$precision}\n list(points=points,ROC_AUC=ratio(U,length(pos)*length(neg)),averagePrecision=if(length(pos))AP else NA_real_,PRTrapezoidWithInitialPrecisionOne=if(length(pos))trap else NA_real_)\n}\ncalibrate<-function(d,p,ids){\n use<-ids[d$eligible[ids]&!is.na(p[ids])];W<-length(use);pi<-if(W)mean(d$y[use])else NA_real_;bins<-list();ECE<-rel<-res<-correction<-0\n whichbin<-findInterval(p[use],seq(0,1,.2),rightmost.closed=TRUE,all.inside=TRUE)\n for(b in 1:5){rr<-use[whichbin==b];w<-length(rr);mp<-if(w)mean(p[rr])else NA_real_;o<-if(w)mean(d$y[rr])else NA_real_;variance<-if(w)mean((p[rr]-mp)^2)else NA_real_;covariance<-if(w)mean((p[rr]-mp)*(d$y[rr]-o))else NA_real_;bc<-variance-2*covariance;gap<-mp-o\n  bins[[b]]<-list(mass=w,meanPrediction=mp,eventRate=o,gap=gap,absoluteGap=abs(gap),scoreVariance=variance,scoreTargetCovariance=covariance,withinBinCorrection=bc,rows=w,ids=d$id[rr])\n  if(w){share<-w/W;ECE<-ECE+share*abs(gap);rel<-rel+share*gap^2;res<-res+share*(o-pi)^2;correction<-correction+share*bc}\n };bs<-if(W)mean((p[use]-d$y[use])^2)else NA_real_;unc<-pi*(1-pi)\n list(bins=bins,ECE=if(W)ECE else NA_real_,Brier=bs,reliability=if(W)rel else NA_real_,resolution=if(W)res else NA_real_,uncertainty=unc,withinBinCorrection=if(W)correction else NA_real_,BrierIdentityResidual=bs-(unc-res+rel+correction))\n}\ncounts<-c(\"mass\",\"positiveTargetMass\",\"negativeTargetMass\",\"predictedPositiveMass\",\"predictedNegativeMass\");rates<-c(\"prevalence\",\"selectionRate\",\"accuracy\",\"precision\",\"negativePredictiveValue\",\"TPR\",\"FPR\",\"TNR\",\"FNR\",\"F1\",\"balancedAccuracy\",\"Brier\",\"BrierSum\",\"totalCost\",\"meanCost\")\ntables<-setNames(lapply(1:10,function(i)list()),c(\"predictions\",\"lineage\",\"fit-medians\",\"fit-cells\",\"validation-candidates\",\"test-metrics\",\"test-curves\",\"calibration-bins\",\"group-metrics\",\"chart-points\"))\nadd<-function(name,row)tables[[name]][[length(tables[[name]])+1L]]<<-row\nscalars<-function(m,keys){out<-list();for(k in keys){out[[paste0(k,\"Exact\")]]<-\"\";out[[paste0(k,\"Approx\")]]<-fmt(m[[k]])};out}\ntagrow<-function(kind,...)c(list(kind=kind),list(...))\npoint<-function(kind,chart,series,index,x,y,xunit=\"dimensionless\",yunit=\"dimensionless\",role=\"test\",tag=\"\"){add(\"chart-points\",tagrow(kind,chart=chart,series=series,index=index,xExact=\"\",xApprox=fmt(x),yExact=\"\",yApprox=fmt(y),xUnit=xunit,yUnit=yunit,role=role,tag=tag))}\nstudy<-function(kind,d){\n f<-fitmodel(d);n<-length(d$id);train<-which(d$role==\"train\");validation<-which(d$role==\"validation\");test<-which(d$role==\"test\");p<-f$pred;cv<-curves(d,p,test);cal<-calibrate(d,p,test)\n for(i in seq_len(n)){\n  reason<-if(d$eligible[i])\"\"else\"required-X-or-Y-missing\";transformed<-if(d$eligible[i])paste(fmt(f$z[i,]),collapse=\"|\")else\"\"\n  add(\"predictions\",tagrow(kind,id=d$id[i],sourceRow=d$sourceRow[i],originalID=d$originalID[i],plannedRole=d$plannedRole[i],role=d$role[i],group=ifelse(is.na(d$group[i]),\"\",d$group[i]),eligible=as.integer(d$eligible[i]),targetExact=fmt(d$y[i]),probabilityExact=\"\",probabilityApprox=fmt(p[i]),unseenCell=ifelse(is.na(f$unseen[i]),\"\",as.character(as.integer(f$unseen[i]))),transformedX=transformed,reason=reason))\n  raw<-d$rawX[i,];raw[raw%in%c(\"\",\".\")]<-\"\";nativeY<-d$nativeTarget[i];if(nativeY%in%c(\"\",\".\"))nativeY<-\"\"\n  add(\"lineage\",tagrow(kind,id=d$id[i],sourceRow=d$sourceRow[i],originalID=d$originalID[i],nativeSourceRows=d$lineage[i],rawX=paste(raw,collapse=\"|\"),nativeTarget=nativeY,derivedTarget=fmt(d$y[i]),nativeGroup=ifelse(is.na(d$group[i]),\"\",d$group[i]),plannedRole=d$plannedRole[i],role=d$role[i],eligible=as.integer(d$eligible[i]),analyticalMass=\"1\",reason=reason))\n }\n for(j in seq_len(ncol(d$x)))add(\"fit-medians\",tagrow(kind,feature=j-1,categorical=as.integer((j-1)%in%d$cat),fitRows=length(train),medianExact=\"\",medianApprox=fmt(f$medians[j]),unit=d$units[j]))\n for(j in seq_along(f$lev))add(\"fit-cells\",tagrow(kind,cell=f$lev[j],trainingRows=f$mass[j],positiveRows=f$positive[j],probabilityExact=\"\",probabilityApprox=fmt(f$prob[j]),fallbackExact=\"\",fallbackApprox=fmt(f$fallback)))\n for(j in seq_along(cv$points)){\n  z<-cv$points[[j]];t<-z$policy;add(\"test-curves\",c(tagrow(kind,point=j-1,policy=if(is.character(t))t else\"threshold\",thresholdExact=\"\",thresholdApprox=if(is.character(t))\"\"else fmt(t)),scalars(z,c(\"TP\",\"FP\",\"FN\",\"TN\",\"TPR\",\"FPR\",\"precision\",\"recall\"))))\n  point(kind,\"roc\",\"ROC\",j-1,z$FPR,z$TPR);point(kind,\"pr\",\"PR-observed\",j-1,z$recall,z$precision)\n }\n for(b in 1:5){z<-cal$bins[[b]];add(\"calibration-bins\",c(tagrow(kind,bin=b-1,leftExact=c(\"0\",\"1/5\",\"2/5\",\"3/5\",\"4/5\")[b],rightExact=c(\"1/5\",\"2/5\",\"3/5\",\"4/5\",\"1\")[b],rightClosed=as.integer(b==5),rows=z$rows,ids=paste(z$ids,collapse=\";\")),scalars(z,c(\"mass\",\"meanPrediction\",\"eventRate\",\"gap\",\"absoluteGap\",\"scoreVariance\",\"scoreTargetCovariance\",\"withinBinCorrection\"))));point(kind,\"reliability\",\"Binary event rate\",b-1,z$meanPrediction,z$eventRate,tag=paste0(\"rows=\",z$rows))}\n for(j in seq_along(test)){i<-test[j];point(kind,\"test-scores\",\"Training-fitted probability\",j-1,j,p[i],\"test-row position\",\"probability\",tag=d$id[i]);point(kind,\"test-scores\",\"Observed Y\",j-1,j,d$y[i],\"test-row position\",\"binary target\",tag=d$id[i])}\n scenarioNames<-c(\"equal\",\"miss-five\",\"alarm-five\");costs<-list(c(1,1),c(1,5),c(5,1))\n for(s in 1:3){name<-scenarioNames[s];cost<-costs[[s]];grid<-c(list(\"always-negative\"),as.list(sort(unique(p[validation]),decreasing=TRUE)));candidates<-lapply(grid,function(t)measure(d,p,validation,t,cost));values<-vapply(candidates,function(m)m$meanCost,numeric(1));best<-which(values<=min(values)+1e-12)[1];chosen<-grid[[best]];ev<-measure(d,p,test,chosen,cost)\n  for(j in seq_along(grid)){t<-grid[[j]];m<-candidates[[j]];cell<-setNames(lapply(c(\"TP\",\"FP\",\"FN\",\"TN\"),function(k)fmt(m[[k]])),paste0(c(\"TP\",\"FP\",\"FN\",\"TN\"),\"Exact\"));add(\"validation-candidates\",c(tagrow(kind,scenario=name,candidate=j-1,selected=as.integer(j==best),policy=if(is.character(t))t else\"threshold\",thresholdExact=\"\",thresholdApprox=if(is.character(t))\"\"else fmt(t),feasible=1,reasons=\"\"),cell,scalars(m,c(counts,\"TPR\",\"FPR\",\"precision\",\"meanCost\",\"totalCost\"))));point(kind,\"validation-cost\",name,j-1,j-1,m$meanCost,\"candidate index\",\"hypothetical cost units/mass\",\"validation\",if(is.character(t))t else fmt(t))}\n  m<-c(ev,cv[c(\"ROC_AUC\",\"averagePrecision\",\"PRTrapezoidWithInitialPrecisionOne\")],cal[c(\"ECE\",\"reliability\",\"resolution\",\"uncertainty\",\"withinBinCorrection\",\"BrierIdentityResidual\")])\n  for(k in c(\"TP\",\"FP\",\"FN\",\"TN\",counts,rates,\"ROC_AUC\",\"averagePrecision\",\"PRTrapezoidWithInitialPrecisionOne\",\"ECE\",\"reliability\",\"resolution\",\"uncertainty\",\"withinBinCorrection\",\"BrierIdentityResidual\")){\n   unit<-if(k%in%c(\"TP\",\"FP\",\"FN\",\"TN\",counts))\"rows\"else if(k==\"totalCost\")\"hypothetical cost units\"else if(k==\"meanCost\")\"hypothetical cost units/mass\"else if(k==\"BrierSum\")\"sum squared-probability loss\"else\"dimensionless\"\n   add(\"test-metrics\",tagrow(kind,scenario=name,metric=k,valueExact=\"\",valueApprox=fmt(m[[k]]),unit=unit))\n  }\n  lev<-unique(d$group[test][!is.na(d$group[test])]);sets<-c(list(test),lapply(lev,function(g)test[!is.na(d$group[test])&d$group[test]==g]),list(test[is.na(d$group[test])]))\n  types<-c(\"overall\",rep(\"known\",length(lev)),\"unknown\");tokens<-c(\"all\",lev,\"\")\n  for(j in seq_along(sets)){ids<-sets[[j]];m<-measure(d,p,ids,chosen,cost);cell<-setNames(lapply(c(\"TP\",\"FP\",\"FN\",\"TN\"),function(k)fmt(m[[k]])),paste0(c(\"TP\",\"FP\",\"FN\",\"TN\"),\"Exact\"));add(\"group-metrics\",c(tagrow(kind,scenario=name,groupType=types[j],groupToken=tokens[j],retainedRows=length(ids)),cell,scalars(m,c(counts,rates))));if(types[j]==\"known\")point(kind,\"group-TPR\",name,j-2,j-2,m$TPR,\"declared group position\",\"TPR\",tag=tokens[j])}\n }\n invisible(NULL)\n}\n\n# Fixed finite inputs only; not the complete web input/budget validator.\nqnum<-function(v){if(is.null(v))return(NA_real_);if(is.logical(v))return(as.numeric(v));s<-as.character(v);if(grepl(\"/\",s,fixed=TRUE)){a<-strsplit(s,\"/\",fixed=TRUE)[[1]];return(as.numeric(a[1])/as.numeric(a[2]))};as.numeric(s)}\nrowsG<-function(raw){\n n<-length(raw);get<-function(r,k,default=NULL)if(is.null(r[[k]]))default else r[[k]]\n id<-vapply(raw,function(r)as.character(r$id),character(1));p<-vapply(raw,function(r)qnum(r$score),numeric(1));y<-vapply(raw,function(r)qnum(r$y),numeric(1));w<-vapply(raw,function(r)qnum(get(r,\"weight\",\"1\")),numeric(1));role<-vapply(raw,function(r)get(r,\"role\",\"evaluation\"),character(1));group<-vapply(raw,function(r)as.character(get(r,\"group\",NA_character_)),character(1))\n stopifnot(all(w>=0),all(is.na(p)|(p>=0&p<=1)),all(is.na(y)|y%in%c(0,1)),!anyDuplicated(id));list(id=id,p=p,y=y,w=w,role=role,group=group,eligible=!is.na(p)&!is.na(y)&w>0&role!=\"excluded\")\n}\nscopeG<-function(d,role=\"all\")if(role==\"all\")seq_along(d$id)else which(d$role==role)\nmetricsG<-function(d,ids,t=.5,cost=c(1,1)){\n use<-ids[d$eligible[ids]];p<-d$p[use];y<-d$y[use];w<-d$w[use];a<-if(is.character(t))rep(t==\"always-positive\",length(use))else p>=t\n TP<-sum(w[a&y==1]);FP<-sum(w[a&y==0]);FN<-sum(w[!a&y==1]);TN<-sum(w[!a&y==0]);P<-TP+FN;N<-FP+TN;W<-P+N;PP<-TP+FP;PN<-TN+FN;TPR<-ratio(TP,P);TNR<-ratio(TN,N);bs<-sum(w*(p-y)^2);tc<-FP*cost[1]+FN*cost[2]\n list(confusion=list(TP=TP,FP=FP,FN=FN,TN=TN),mass=W,positiveTargetMass=P,negativeTargetMass=N,predictedPositiveMass=PP,predictedNegativeMass=PN,prevalence=ratio(P,W),selectionRate=ratio(PP,W),accuracy=ratio(TP+TN,W),precision=ratio(TP,PP),negativePredictiveValue=ratio(TN,PN),TPR=TPR,FPR=ratio(FP,N),TNR=TNR,FNR=ratio(FN,P),F1=ratio(2*TP,2*TP+FP+FN),balancedAccuracy=if(is.na(TPR)||is.na(TNR))NA_real_ else(TPR+TNR)/2,Brier=ratio(bs,W),BrierSum=bs,totalCost=tc,meanCost=ratio(tc,W),bayesThreshold=ratio(cost[1],sum(cost)))\n}\ncurvesG<-function(d,ids){\n use<-ids[d$eligible[ids]];grid<-c(list(\"always-negative\"),as.list(sort(unique(d$p[use]),decreasing=TRUE)));points<-lapply(grid,function(t){m<-metricsG(d,ids,t);c(list(policy=t),m$confusion,m[c(\"TPR\",\"FPR\",\"precision\")],list(recall=m$TPR))});pos<-use[d$y[use]==1];neg<-use[d$y[use]==0];P<-sum(d$w[pos]);N<-sum(d$w[neg]);U<-0\n for(i in pos)U<-U+d$w[i]*sum(d$w[neg]*((d$p[i]>d$p[neg])+.5*(d$p[i]==d$p[neg])))\n AP<-trap<-lastR<-0;lastP<-1\n if(P&&length(grid)>1)for(j in 2:length(grid)){z<-points[[j]];AP<-AP+(z$recall-lastR)*z$precision;trap<-trap+(z$recall-lastR)*(z$precision+lastP)/2;lastR<-z$recall;lastP<-z$precision}\n list(points=points,ROC_AUC=ratio(U,P*N),averagePrecision=if(P)AP else NA_real_,PRTrapezoidWithInitialPrecisionOne=if(P)trap else NA_real_)\n}\nchooseG<-function(d,a,cost){\n role<-if(is.null(a$selectionRole))\"validation\"else a$selectionRole;er<-if(is.null(a$evaluationRole))\"test\"else a$evaluationRole;ids<-scopeG(d,role);use<-ids[d$eligible[ids]];stopifnot(length(use)>0);grid<-if(is.null(a$thresholds))c(list(\"always-negative\"),as.list(sort(unique(d$p[use]),decreasing=TRUE)))else lapply(a$thresholds,function(t)if(t%in%c(\"always-negative\",\"always-positive\"))t else qnum(t))\n candidates<-lapply(seq_along(grid),function(j){m<-metricsG(d,ids,grid[[j]],cost);feasible<-TRUE;if(!is.null(a$minTPR))feasible<-feasible&&!is.na(m$TPR)&&m$TPR>=qnum(a$minTPR);if(!is.null(a$maxFPR))feasible<-feasible&&!is.na(m$FPR)&&m$FPR<=qnum(a$maxFPR);list(index=j-1,policy=grid[[j]],metrics=m,feasible=feasible)})\n good<-which(vapply(candidates,function(c)c$feasible,logical(1)));best<-NA_integer_;if(length(good)){v<-vapply(candidates[good],function(c)c$metrics$meanCost,numeric(1));best<-good[which(v<=min(v)+1e-12)[1]]}\n list(selectedIndex=if(is.na(best))NA_integer_ else best-1,selectedPolicy=if(is.na(best))NULL else grid[[best]],selectedValidation=if(is.na(best))NULL else candidates[[best]]$metrics,candidates=candidates,evaluation=if(is.na(best)||er==\"none\")NULL else metricsG(d,scopeG(d,er),grid[[best]],cost))\n}\ncalibrateG<-function(d,ids,edges){\n use<-ids[d$eligible[ids]];W<-sum(d$w[use]);pi<-ratio(sum(d$w[use]*d$y[use]),W);bins<-list();ECE<-rel<-res<-correction<-0;assign<-findInterval(d$p[use],edges,rightmost.closed=TRUE,all.inside=TRUE)\n for(b in seq_len(length(edges)-1)){rr<-use[assign==b];w<-sum(d$w[rr]);mp<-ratio(sum(d$w[rr]*d$p[rr]),w);o<-ratio(sum(d$w[rr]*d$y[rr]),w);variance<-if(w)sum(d$w[rr]*(d$p[rr]-mp)^2)/w else NA_real_;covariance<-if(w)sum(d$w[rr]*(d$p[rr]-mp)*(d$y[rr]-o))/w else NA_real_;bc<-variance-2*covariance;gap<-mp-o;bins[[b]]<-list(index=b-1,mass=w,meanPrediction=mp,eventRate=o,scoreVariance=variance,scoreTargetCovariance=covariance,withinBinCorrection=bc,ids=d$id[rr])\n  if(w){s<-w/W;ECE<-ECE+s*abs(gap);rel<-rel+s*gap^2;res<-res+s*(o-pi)^2;correction<-correction+s*bc}\n };bs<-ratio(sum(d$w[use]*(d$p[use]-d$y[use])^2),W);unc<-pi*(1-pi);list(bins=bins,Brier=bs,ECE=if(W)ECE else NA_real_,uncertainty=unc,reliability=if(W)rel else NA_real_,resolution=if(W)res else NA_real_,withinBinCorrection=if(W)correction else NA_real_,BrierIdentityResidual=bs-(unc-res+rel+correction))\n}\ngroupsG<-function(d,ids,t,cost){\n lev<-unique(d$group[ids][!is.na(d$group[ids])]);groups<-lapply(lev,function(g)list(group=g,metrics=metricsG(d,ids[!is.na(d$group[ids])&d$group[ids]==g],t,cost)));overall<-metricsG(d,ids,t,cost);unknown<-metricsG(d,ids[is.na(d$group[ids])],t,cost);gaps<-list()\n for(k in c(\"prevalence\",\"selectionRate\",\"TPR\",\"FPR\",\"precision\",\"accuracy\",\"meanCost\")){use<-Filter(function(g)g$metrics$mass>0,groups);v<-vapply(use,function(g)g$metrics[[k]],numeric(1));gaps[[k]]<-if(length(use)<2||anyNA(v))NA_real_ else max(v)-min(v)}\n list(overall=overall,groups=groups,unknownGroup=unknown,gaps=gaps,partitionMassResidual=overall$mass-unknown$mass-sum(vapply(groups,function(g)g$metrics$mass,numeric(1))))\n}\nsvgFixed<-function(file,points,title,xlabel,ylabel,legend){\n finite<-points[points$y!=\"undefined\"&points$x!=\"undefined\",,drop=FALSE];x<-as.numeric(finite$x);y<-as.numeric(finite$y);xmin<-if(length(x))min(x)else 0;xmax<-if(length(x))max(x)else 1;ymin<-min(c(0,y));ymax<-max(c(0,y));if(xmin==xmax){xmin<-xmin-.5;xmax<-xmax+.5};if(ymin==ymax)ymax<-ymin+1;X<-function(v)85+(v-xmin)/(xmax-xmin)*480;Y<-function(v)278-(v-ymin)/(ymax-ymin)*175\n esc<-function(s){s<-gsub(\"&\",\"&amp;\",s,fixed=TRUE);s<-gsub(\"<\",\"&lt;\",s,fixed=TRUE);gsub(\">\",\"&gt;\",s,fixed=TRUE)};s<-'<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"620\" height=\"360\" viewBox=\"0 0 620 360\"><rect width=\"620\" height=\"360\" fill=\"white\"/><g font-family=\"Arial, sans-serif\" font-size=\"13\" fill=\"#17324d\">'\n lines<-strwrap(title,width=65);for(i in seq_along(lines))s<-paste0(s,'<text x=\"25\" y=\"',24+(i-1)*18,'\">',esc(lines[i]),'</text>');colors<-c(\"#176b9b\",\"#b85e18\",\"#437e4d\")\n for(i in seq_along(legend))s<-paste0(s,'<circle cx=\"',30+(i-1)*250,'\" cy=\"76\" r=\"4\" fill=\"',colors[(i-1)%%3+1],'\"/><text x=\"',42+(i-1)*250,'\" y=\"80\">',esc(legend[i]),'</text>')\n s<-paste0(s,'<path d=\"M85 98V278H575\" fill=\"none\" stroke=\"#52677d\"/><text text-anchor=\"middle\" x=\"325\" y=\"338\">',esc(xlabel),'</text><text text-anchor=\"middle\" transform=\"translate(21,190) rotate(-90)\">',esc(ylabel),'</text>')\n for(i in 0:4){xx<-xmin+(xmax-xmin)*i/4;yy<-ymin+(ymax-ymin)*i/4;s<-paste0(s,'<text text-anchor=\"middle\" x=\"',sprintf(\"%.9g\",X(xx)),'\" y=\"305\">',sprintf(\"%.4g\",xx),'</text><text text-anchor=\"end\" x=\"77\" y=\"',sprintf(\"%.9g\",Y(yy)+4),'\">',sprintf(\"%.4g\",yy),'</text>')}\n for(i in seq_len(nrow(finite)))s<-paste0(s,'<circle cx=\"',sprintf(\"%.9g\",X(x[i])),'\" cy=\"',sprintf(\"%.9g\",Y(y[i])),'\" r=\"3\" fill=\"',colors[as.integer(finite$series[i])%%3+1],'\"/>');writeLines(paste0(s,'</g></svg>'),file,useBytes=TRUE)\n}\nfixedRun<-function(){\n api<-FIXED$api;a<-FIXED$args;summary<-list();points<-list();xlabel<-\"Declared index\";ylabel<-\"Value\";legend<-\"Declared result\"\n metric<-function(name,v,unit=\"dimensionless\"){if(is.null(v))v<-NA_real_;summary[[length(summary)+1L]]<<-data.frame(metric=name,value=if(is.na(v))\"undefined\"else sprintf(\"%.9g\",v),exactValue=\"\",unit=unit,defined=as.integer(!is.na(v)),stringsAsFactors=FALSE)}\n pt<-function(i,x,y,id=\"\",series=0){points[[length(points)+1L]]<<-data.frame(series=series,index=i,xExact=\"\",x=if(is.na(x))\"undefined\"else sprintf(\"%.9g\",x),yExact=\"\",y=if(is.na(y))\"undefined\"else sprintf(\"%.9g\",y),id=as.character(id),stringsAsFactors=FALSE)}\n if(api==\"realdata\"){\n  native<-loadData()[[a$kind]];fit<-fitmodel(native);d<-list(id=native$id,p=fit$pred,y=native$y,w=rep(1,length(native$id)),role=native$role,group=native$group,eligible=native$eligible);scenarios<-list()\n  for(j in 1:3){name<-c(\"equal\",\"miss-five\",\"alarm-five\")[j];cst<-list(c(1,1),c(1,5),c(5,1))[[j]];sel<-chooseG(d,list(),cst);scenarios[[j]]<-list(name=name,selection=sel);metric(paste0(name,\"Threshold\"),sel$selectedPolicy);metric(paste0(name,\"TestCost\"),sel$evaluation$meanCost,\"hypothetical cost units/mass\")}\n  ids<-scopeG(d,\"test\");cv<-curvesG(d,ids);cal<-calibrateG(d,ids,seq(0,1,.2));metric(\"testAUC\",cv$ROC_AUC);metric(\"testAP\",cv$averagePrecision);metric(\"testBrier\",cal$Brier);metric(\"eligibleRows\",sum(d$eligible),\"rows\")\n  for(j in seq_along(ids)){i<-ids[j];pt(j-1,j,d$p[i],d$id[i],0);pt(j-1,j,d$y[i],d$id[i],1)}\n  full<-list(kind=a$kind,fit=fit,scenarios=scenarios,testCurves=cv,testCalibration=cal,rowsScored=d);xlabel<-\"Test row, native order\";ylabel<-\"Y or probability\";legend<-c(\"Training-fitted probability\",\"Observed Y\")\n }else{\n  d<-rowsG(a$rows);role<-if(is.null(a$role))\"all\"else a$role;ids<-scopeG(d,role);cost<-if(is.null(a$costs))c(1,1)else c(qnum(a$costs$falsePositive),qnum(a$costs$falseNegative));t<-if(is.null(a$threshold)).5 else if(a$threshold%in%c(\"always-positive\",\"always-negative\"))a$threshold else qnum(a$threshold)\n  if(api==\"metrics\"){\n   full<-metricsG(d,ids,t,cost);for(k in c(\"mass\",\"accuracy\",\"precision\",\"TPR\",\"FPR\",\"F1\",\"Brier\",\"meanCost\"))metric(k,full[[k]],if(k==\"mass\")\"mass\"else if(k==\"meanCost\")\"hypothetical cost units/mass\"else\"dimensionless\");metric(\"BayesThreshold\",full$bayesThreshold)\n   for(i in 1:4)pt(i-1,i-1,full$confusion[[i]],names(full$confusion)[i]);xlabel<-\"TP / FP / FN / TN positions\";ylabel<-\"Analytical mass\"\n  }else if(api==\"curves\"){\n   full<-curvesG(d,ids);for(k in c(\"ROC_AUC\",\"averagePrecision\",\"PRTrapezoidWithInitialPrecisionOne\"))metric(k,full[[k]])\n   for(j in seq_along(full$points)){p<-full$points[[j]];pt(j-1,p$FPR,p$TPR,if(is.character(p$policy))p$policy else sprintf(\"%.17g\",p$policy))};xlabel<-\"False positive rate\";ylabel<-\"True positive rate\";legend<-\"Observed ROC operating points\"\n  }else if(api==\"choose\"){\n   full<-chooseG(d,a,cost);metric(\"selectedIndex\",full$selectedIndex,\"candidate index\");metric(\"minimumCost\",if(is.null(full$selectedValidation))NULL else full$selectedValidation$meanCost,\"hypothetical cost units/mass\");metric(\"feasible\",as.integer(!is.na(full$selectedIndex)),\"indicator\")\n   for(c in full$candidates)pt(c$index,c$index,c$metrics$meanCost,if(is.character(c$policy))c$policy else sprintf(\"%.17g\",c$policy));xlabel<-\"Validation candidate\";ylabel<-\"Assumed cost / mass\";legend<-\"Validation candidate costs\"\n  }else if(api==\"calibrate\"){\n   edges<-if(is.null(a$binEdges))seq(0,1,.2)else vapply(a$binEdges,qnum,numeric(1));full<-calibrateG(d,ids,edges);for(k in c(\"ECE\",\"Brier\",\"uncertainty\",\"resolution\",\"reliability\",\"withinBinCorrection\",\"BrierIdentityResidual\"))metric(k,full[[k]])\n   for(b in full$bins)pt(b$index,b$meanPrediction,b$eventRate,paste0(\"bin:\",b$index));xlabel<-\"Bin mean forecast\";ylabel<-\"Bin event rate\";legend<-\"Binary-event reliability\"\n  }else if(api==\"groups\"){\n   full<-groupsG(d,ids,t,cost);metric(\"overallTPR\",full$overall$TPR);metric(\"TPRGap\",full$gaps$TPR);metric(\"precisionGap\",full$gaps$precision);metric(\"unknownMass\",full$unknownGroup$mass,\"mass\");metric(\"partitionResidual\",full$partitionMassResidual,\"mass\")\n   for(j in seq_along(full$groups))pt(j-1,j-1,full$groups[[j]]$metrics$TPR,full$groups[[j]]$group);xlabel<-\"Declared group position\";ylabel<-\"True positive rate\";legend<-\"Known-group TPR\"\n  }else stop(\"unknown declared fixed API\")\n }\n sm<-do.call(rbind,summary);pp<-do.call(rbind,points);write.csv(sm,file.path(outDir,\"summary.csv\"),row.names=FALSE,na=\"\");write.csv(pp,file.path(outDir,\"plot-points.csv\"),row.names=FALSE,na=\"\");svgFixed(file.path(outDir,\"plot.svg\"),pp,FIXED$title,xlabel,ylabel,legend);dput(list(api=api,variant=FIXED$variant,input=FIXED$args,arithmetic=\"Base-R binary64 fixed example; not an exact rational general validator\",result=full),file=file.path(outDir,\"full.txt\"));cat(\"PASS\",api,FIXED$variant,\"summary\",nrow(sm),\"points\",nrow(pp),\"\\n\")\n}\n\nFIXED<-list(api=\"metrics\",variant=\"six-cards\",args=list(rows=list(list(id=\"a\",score=\".9\",y=1,group=\"A\"),list(id=\"b\",score=\".8\",y=1,group=\"A\"),list(id=\"c\",score=\".8\",y=0,group=\"A\"),list(id=\"d\",score=\".6\",y=0,group=\"B\"),list(id=\"e\",score=\".4\",y=1,group=\"B\"),list(id=\"f\",score=\".1\",y=0,group=\"B\")),threshold=\".8\"),title=\"Six-card confusion cells at threshold0.8\")\nfixedRun()\n",
        "codeText": "# ML14 standalone public counterpart, base R only.\n# Inputs are only the three factual CSVs; derived columns/previous model answers unused.\n# Binary64 arithmetic, not arbitrary-precision Fraction. At numerical cost ties\n# within 1e-12 retain the earliest candidate. Exact claims belong to Python/web.\n# SHA256 infrastructure below is reused verbatim from the previous public study.\nargs<-commandArgs(trailingOnly=TRUE);filearg<-grep(\"^--file=\",commandArgs(),value=TRUE)\nhere<-if(dir.exists(\"ml14-sources\"))getwd()else if(length(filearg))dirname(normalizePath(sub(\"^--file=\",\"\",filearg[1])))else getwd()\noption<-function(key,default){i<-match(key,args);if(is.na(i))default else args[i+1]}\nsourceDir<-option(\"--source\",file.path(here,\"ml14-sources\"));outDir<-option(\"--out\",file.path(getwd(),\"ml14-r-results\"));dir.create(outDir,recursive=TRUE,showWarnings=FALSE)\nnum<-function(x){x[x%in%c(\"\",\".\")]<-NA_character_;as.numeric(x)}\nfmt<-function(x)ifelse(is.na(x),\"\",sprintf(\"%.17g\",x))\nratio<-function(a,b)if(b==0)NA_real_ else a/b\nreadnative<-function(name)read.csv(file.path(sourceDir,name),check.names=FALSE,colClasses=\"character\",na.strings=character(),stringsAsFactors=FALSE)\n# Vectorized SHA256 for the short ASCII keys used in this study.\n# Unsigned words use exact integer-valued doubles; bit operations use safe\n# 16-bit halves, avoiding R's reserved signed-INT_MIN/NA representation.\nMOD<-2^32\nxor32<-function(a,b) as.double(bitwXor(as.integer(floor(a/65536)),as.integer(floor(b/65536))))*65536+as.double(bitwXor(as.integer(a%%65536),as.integer(b%%65536)))\nand32<-function(a,b) as.double(bitwAnd(as.integer(floor(a/65536)),as.integer(floor(b/65536))))*65536+as.double(bitwAnd(as.integer(a%%65536),as.integer(b%%65536)))\nrot<-function(x,n) floor(x/2^n)+(x%%2^n)*2^(32-n)\nxor3<-function(a,b,c) xor32(xor32(a,b),c)\nK<-c(0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5,0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967,0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070,0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3,0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2)\nsha256<-function(strings) {\n n<-length(strings);bytes<-matrix(0,n,64)\n for(i in seq_len(n)) {v<-utf8ToInt(strings[i]);stopifnot(length(v)<56,all(v<128));if(length(v)) bytes[i,seq_along(v)]<-v;bytes[i,length(v)+1]<-128;bits<-length(v)*8;bytes[i,61:64]<-c(floor(bits/2^24)%%256,floor(bits/2^16)%%256,floor(bits/256)%%256,bits%%256)}\n w<-matrix(0,n,64)\n for(j in 1:16) {b<-4*(j-1)+1;w[,j]<-bytes[,b]*2^24+bytes[,b+1]*2^16+bytes[,b+2]*256+bytes[,b+3]}\n for(j in 17:64) {s0<-xor3(rot(w[,j-15],7),rot(w[,j-15],18),floor(w[,j-15]/8));s1<-xor3(rot(w[,j-2],17),rot(w[,j-2],19),floor(w[,j-2]/1024));w[,j]<-(w[,j-16]+s0+w[,j-7]+s1)%%MOD}\n init<-c(0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19)\n state<-lapply(init,function(v) rep(v,n));a<-state[[1]];b<-state[[2]];c<-state[[3]];d<-state[[4]];e<-state[[5]];f<-state[[6]];g<-state[[7]];h<-state[[8]]\n for(j in 1:64) {S1<-xor3(rot(e,6),rot(e,11),rot(e,25));ch<-xor32(and32(e,f),and32(MOD-1-e,g));t1<-(h+S1+ch+K[j]+w[,j])%%MOD;S0<-xor3(rot(a,2),rot(a,13),rot(a,22));maj<-xor3(and32(a,b),and32(a,c),and32(b,c));t2<-(S0+maj)%%MOD;h<-g;g<-f;f<-e;e<-(d+t1)%%MOD;d<-c;c<-b;b<-a;a<-(t1+t2)%%MOD}\n end<-list(a,b,c,d,e,f,g,h);hex<-lapply(1:8,function(j){v<-(end[[j]]+init[j])%%MOD;paste0(sprintf(\"%04x\",as.integer(floor(v/65536))),sprintf(\"%04x\",as.integer(v%%65536)))})\n do.call(paste0,hex)\n}\nstopifnot(identical(sha256(c(\"abc\",\"\")),c(\"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad\",\"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855\")))\n\nloadData<-function(){\n wb<-readnative(\"actual64-country-four-indicators-original-2024.csv\");codes<-c(\"NY.GDP.PCAP.KD\",\"NY.GDP.MKTP.KD.ZG\",\"FP.CPI.TOTL.ZG\",\"SP.DYN.LE00.IN\");iso<-sort(unique(wb$countryISO3));stopifnot(nrow(wb)==64,length(iso)==16)\n tokens<-t(vapply(iso,function(s)wb$originalValueToken[match(paste(s,codes),paste(wb$countryISO3,wb$indicatorID))],character(4)));vals<-matrix(num(as.vector(tokens)),nrow=nrow(tokens))\n country<-list(id=paste0(iso,\":2024\"),sourceRow=1:16,originalID=iso,x=vals[,1:3,drop=FALSE],rawX=tokens[,1:3,drop=FALSE],nativeTarget=tokens[,4],y=as.integer(vals[,4]>=80),group=ifelse(is.na(vals[,1]),NA_character_,as.character(as.integer(vals[,1]>=25000))),lineage=vapply(iso,function(s)paste(wb$sourceRow[match(paste(s,codes),paste(wb$countryISO3,wb$indicatorID))],collapse=\";\"),character(1)),cat=integer(),units=c(\"constant2015USD/person\",\"annualPercent\",\"annualPercent\"))\n nls<-readnative(\"actual3613-NLS-original52-fields-groups-roles.csv\");raw<-cbind(nls$ed76,nls$age76,nls$nearc4)\n person<-list(id=paste0(\"person:\",nls$sourceRow),sourceRow=as.integer(nls$sourceRow),originalID=nls$id,x=matrix(num(as.vector(raw)),nrow=nrow(raw)),rawX=raw,nativeTarget=nls$wage76,y=as.integer(num(nls$wage76)>=500),group=ifelse(nls$black%in%c(\"\",\".\"),NA_character_,nls$black),lineage=nls$sourceRow,cat=2L,units=c(\"years\",\"years\",\"nativeCategory\"))\n ch<-readnative(\"actual3150-churn-original14-fields-groups-roles.csv\");raw<-cbind(ch[[\"Call  Failure\"]],ch$Complains,ch[[\"Subscription  Length\"]],ch[[\"Seconds of Use\"]])\n company<-list(id=paste0(\"customer:\",ch$sourceRow),sourceRow=as.integer(ch$sourceRow),originalID=rep(\"\",nrow(ch)),x=matrix(num(as.vector(raw)),nrow=nrow(raw)),rawX=raw,nativeTarget=ch$Churn,y=as.integer(ch$Churn),group=ifelse(ch[[\"Tariff Plan\"]]%in%c(\"\",\".\"),NA_character_,ch[[\"Tariff Plan\"]]),lineage=ch$sourceRow,cat=1L,units=c(\"count\",\"nativeCategory\",\"months\",\"seconds\"))\n stopifnot(nrow(nls)==3613,nrow(ch)==3150,identical(as.integer(ch$sourceRow[ch[[\"Charge  Amount\"]]==\"10\"]),c(474L,2174L,2274L,2374L,2674L,2924L,2974L)))\n result<-list(country=country,person=person,company=company)\n for(k in names(result)){d<-result[[k]];n<-length(d$id);d$eligible<-!is.na(d$y)&rowSums(is.na(d$x))==0;hash<-sha256(paste0(\"ML14-role|\",k,\"|\",d$id));rank<-integer(n);rank[order(hash,seq_len(n))]<-seq_len(n)-1L;d$plannedRole<-ifelse(rank%%5==0,\"test\",ifelse(rank%%5==1,\"validation\",\"train\"));d$role<-ifelse(d$eligible,d$plannedRole,\"excluded\");result[[k]]<-d}\n stopifnot(sum(result$person$eligible)==3017);result\n}\nfitmodel<-function(d){\n ids<-which(d$role==\"train\");p<-ncol(d$x);m<-vapply(seq_len(p),function(j)if((j-1)%in%d$cat)NA_real_ else median(d$x[ids,j]),numeric(1));z<-d$x\n for(j in seq_len(p))if(!((j-1)%in%d$cat))z[,j]<-as.numeric(z[,j]>m[j])\n keys<-apply(z,1,function(v)paste(fmt(v),collapse=\"|\"));lev<-unique(keys[ids]);mass<-vapply(lev,function(k)sum(keys[ids]==k),integer(1));positive<-vapply(lev,function(k)sum(d$y[ids][keys[ids]==k]),integer(1));prob<-(positive+1)/(mass+2);fallback<-(sum(d$y[ids])+1)/(length(ids)+2);pred<-prob[match(keys,lev)];unseen<-is.na(pred);pred[unseen]<-fallback;pred[!d$eligible]<-NA_real_;unseen[!d$eligible]<-NA\n list(ids=ids,medians=m,z=z,keys=keys,lev=lev,mass=mass,positive=positive,prob=prob,fallback=fallback,pred=pred,unseen=unseen)\n}\nmeasure<-function(d,p,ids,t=.5,cost=c(1,1)){\n use<-ids[d$eligible[ids]&!is.na(p[ids])];y<-d$y[use];a<-if(is.character(t))rep(t==\"always-positive\",length(use))else p[use]>=t\n TP<-sum(a&y==1);FP<-sum(a&y==0);FN<-sum(!a&y==1);TN<-sum(!a&y==0);P<-TP+FN;N<-FP+TN;W<-P+N;PP<-TP+FP;PN<-TN+FN;TPR<-ratio(TP,P);TNR<-ratio(TN,N);bs<-sum((p[use]-y)^2);tc<-FP*cost[1]+FN*cost[2]\n list(TP=TP,FP=FP,FN=FN,TN=TN,mass=W,positiveTargetMass=P,negativeTargetMass=N,predictedPositiveMass=PP,predictedNegativeMass=PN,prevalence=ratio(P,W),selectionRate=ratio(PP,W),accuracy=ratio(TP+TN,W),precision=ratio(TP,PP),negativePredictiveValue=ratio(TN,PN),TPR=TPR,FPR=ratio(FP,N),TNR=TNR,FNR=ratio(FN,P),F1=ratio(2*TP,2*TP+FP+FN),balancedAccuracy=if(is.na(TPR)||is.na(TNR))NA_real_ else(TPR+TNR)/2,Brier=ratio(bs,W),BrierSum=bs,totalCost=tc,meanCost=ratio(tc,W))\n}\ncurves<-function(d,p,ids){\n use<-ids[d$eligible[ids]&!is.na(p[ids])];scores<-sort(unique(p[use]),decreasing=TRUE);policies<-c(list(\"always-negative\"),as.list(scores));points<-lapply(policies,function(t){m<-measure(d,p,ids,t);c(list(policy=t),m[c(\"TP\",\"FP\",\"FN\",\"TN\",\"TPR\",\"FPR\",\"precision\")],list(recall=m$TPR))})\n pos<-use[d$y[use]==1];neg<-use[d$y[use]==0];U<-0;for(i in pos)U<-U+sum(p[i]>p[neg])+.5*sum(p[i]==p[neg])\n AP<-0;trap<-0;lastR<-0;lastP<-1\n if(length(pos)&&length(scores))for(j in seq_along(scores)){z<-points[[j+1]];AP<-AP+(z$recall-lastR)*z$precision;trap<-trap+(z$recall-lastR)*(z$precision+lastP)/2;lastR<-z$recall;lastP<-z$precision}\n list(points=points,ROC_AUC=ratio(U,length(pos)*length(neg)),averagePrecision=if(length(pos))AP else NA_real_,PRTrapezoidWithInitialPrecisionOne=if(length(pos))trap else NA_real_)\n}\ncalibrate<-function(d,p,ids){\n use<-ids[d$eligible[ids]&!is.na(p[ids])];W<-length(use);pi<-if(W)mean(d$y[use])else NA_real_;bins<-list();ECE<-rel<-res<-correction<-0\n whichbin<-findInterval(p[use],seq(0,1,.2),rightmost.closed=TRUE,all.inside=TRUE)\n for(b in 1:5){rr<-use[whichbin==b];w<-length(rr);mp<-if(w)mean(p[rr])else NA_real_;o<-if(w)mean(d$y[rr])else NA_real_;variance<-if(w)mean((p[rr]-mp)^2)else NA_real_;covariance<-if(w)mean((p[rr]-mp)*(d$y[rr]-o))else NA_real_;bc<-variance-2*covariance;gap<-mp-o\n  bins[[b]]<-list(mass=w,meanPrediction=mp,eventRate=o,gap=gap,absoluteGap=abs(gap),scoreVariance=variance,scoreTargetCovariance=covariance,withinBinCorrection=bc,rows=w,ids=d$id[rr])\n  if(w){share<-w/W;ECE<-ECE+share*abs(gap);rel<-rel+share*gap^2;res<-res+share*(o-pi)^2;correction<-correction+share*bc}\n };bs<-if(W)mean((p[use]-d$y[use])^2)else NA_real_;unc<-pi*(1-pi)\n list(bins=bins,ECE=if(W)ECE else NA_real_,Brier=bs,reliability=if(W)rel else NA_real_,resolution=if(W)res else NA_real_,uncertainty=unc,withinBinCorrection=if(W)correction else NA_real_,BrierIdentityResidual=bs-(unc-res+rel+correction))\n}\ncounts<-c(\"mass\",\"positiveTargetMass\",\"negativeTargetMass\",\"predictedPositiveMass\",\"predictedNegativeMass\");rates<-c(\"prevalence\",\"selectionRate\",\"accuracy\",\"precision\",\"negativePredictiveValue\",\"TPR\",\"FPR\",\"TNR\",\"FNR\",\"F1\",\"balancedAccuracy\",\"Brier\",\"BrierSum\",\"totalCost\",\"meanCost\")\ntables<-setNames(lapply(1:10,function(i)list()),c(\"predictions\",\"lineage\",\"fit-medians\",\"fit-cells\",\"validation-candidates\",\"test-metrics\",\"test-curves\",\"calibration-bins\",\"group-metrics\",\"chart-points\"))\nadd<-function(name,row)tables[[name]][[length(tables[[name]])+1L]]<<-row\nscalars<-function(m,keys){out<-list();for(k in keys){out[[paste0(k,\"Exact\")]]<-\"\";out[[paste0(k,\"Approx\")]]<-fmt(m[[k]])};out}\ntagrow<-function(kind,...)c(list(kind=kind),list(...))\npoint<-function(kind,chart,series,index,x,y,xunit=\"dimensionless\",yunit=\"dimensionless\",role=\"test\",tag=\"\"){add(\"chart-points\",tagrow(kind,chart=chart,series=series,index=index,xExact=\"\",xApprox=fmt(x),yExact=\"\",yApprox=fmt(y),xUnit=xunit,yUnit=yunit,role=role,tag=tag))}\nstudy<-function(kind,d){\n f<-fitmodel(d);n<-length(d$id);train<-which(d$role==\"train\");validation<-which(d$role==\"validation\");test<-which(d$role==\"test\");p<-f$pred;cv<-curves(d,p,test);cal<-calibrate(d,p,test)\n for(i in seq_len(n)){\n  reason<-if(d$eligible[i])\"\"else\"required-X-or-Y-missing\";transformed<-if(d$eligible[i])paste(fmt(f$z[i,]),collapse=\"|\")else\"\"\n  add(\"predictions\",tagrow(kind,id=d$id[i],sourceRow=d$sourceRow[i],originalID=d$originalID[i],plannedRole=d$plannedRole[i],role=d$role[i],group=ifelse(is.na(d$group[i]),\"\",d$group[i]),eligible=as.integer(d$eligible[i]),targetExact=fmt(d$y[i]),probabilityExact=\"\",probabilityApprox=fmt(p[i]),unseenCell=ifelse(is.na(f$unseen[i]),\"\",as.character(as.integer(f$unseen[i]))),transformedX=transformed,reason=reason))\n  raw<-d$rawX[i,];raw[raw%in%c(\"\",\".\")]<-\"\";nativeY<-d$nativeTarget[i];if(nativeY%in%c(\"\",\".\"))nativeY<-\"\"\n  add(\"lineage\",tagrow(kind,id=d$id[i],sourceRow=d$sourceRow[i],originalID=d$originalID[i],nativeSourceRows=d$lineage[i],rawX=paste(raw,collapse=\"|\"),nativeTarget=nativeY,derivedTarget=fmt(d$y[i]),nativeGroup=ifelse(is.na(d$group[i]),\"\",d$group[i]),plannedRole=d$plannedRole[i],role=d$role[i],eligible=as.integer(d$eligible[i]),analyticalMass=\"1\",reason=reason))\n }\n for(j in seq_len(ncol(d$x)))add(\"fit-medians\",tagrow(kind,feature=j-1,categorical=as.integer((j-1)%in%d$cat),fitRows=length(train),medianExact=\"\",medianApprox=fmt(f$medians[j]),unit=d$units[j]))\n for(j in seq_along(f$lev))add(\"fit-cells\",tagrow(kind,cell=f$lev[j],trainingRows=f$mass[j],positiveRows=f$positive[j],probabilityExact=\"\",probabilityApprox=fmt(f$prob[j]),fallbackExact=\"\",fallbackApprox=fmt(f$fallback)))\n for(j in seq_along(cv$points)){\n  z<-cv$points[[j]];t<-z$policy;add(\"test-curves\",c(tagrow(kind,point=j-1,policy=if(is.character(t))t else\"threshold\",thresholdExact=\"\",thresholdApprox=if(is.character(t))\"\"else fmt(t)),scalars(z,c(\"TP\",\"FP\",\"FN\",\"TN\",\"TPR\",\"FPR\",\"precision\",\"recall\"))))\n  point(kind,\"roc\",\"ROC\",j-1,z$FPR,z$TPR);point(kind,\"pr\",\"PR-observed\",j-1,z$recall,z$precision)\n }\n for(b in 1:5){z<-cal$bins[[b]];add(\"calibration-bins\",c(tagrow(kind,bin=b-1,leftExact=c(\"0\",\"1/5\",\"2/5\",\"3/5\",\"4/5\")[b],rightExact=c(\"1/5\",\"2/5\",\"3/5\",\"4/5\",\"1\")[b],rightClosed=as.integer(b==5),rows=z$rows,ids=paste(z$ids,collapse=\";\")),scalars(z,c(\"mass\",\"meanPrediction\",\"eventRate\",\"gap\",\"absoluteGap\",\"scoreVariance\",\"scoreTargetCovariance\",\"withinBinCorrection\"))));point(kind,\"reliability\",\"Binary event rate\",b-1,z$meanPrediction,z$eventRate,tag=paste0(\"rows=\",z$rows))}\n for(j in seq_along(test)){i<-test[j];point(kind,\"test-scores\",\"Training-fitted probability\",j-1,j,p[i],\"test-row position\",\"probability\",tag=d$id[i]);point(kind,\"test-scores\",\"Observed Y\",j-1,j,d$y[i],\"test-row position\",\"binary target\",tag=d$id[i])}\n scenarioNames<-c(\"equal\",\"miss-five\",\"alarm-five\");costs<-list(c(1,1),c(1,5),c(5,1))\n for(s in 1:3){name<-scenarioNames[s];cost<-costs[[s]];grid<-c(list(\"always-negative\"),as.list(sort(unique(p[validation]),decreasing=TRUE)));candidates<-lapply(grid,function(t)measure(d,p,validation,t,cost));values<-vapply(candidates,function(m)m$meanCost,numeric(1));best<-which(values<=min(values)+1e-12)[1];chosen<-grid[[best]];ev<-measure(d,p,test,chosen,cost)\n  for(j in seq_along(grid)){t<-grid[[j]];m<-candidates[[j]];cell<-setNames(lapply(c(\"TP\",\"FP\",\"FN\",\"TN\"),function(k)fmt(m[[k]])),paste0(c(\"TP\",\"FP\",\"FN\",\"TN\"),\"Exact\"));add(\"validation-candidates\",c(tagrow(kind,scenario=name,candidate=j-1,selected=as.integer(j==best),policy=if(is.character(t))t else\"threshold\",thresholdExact=\"\",thresholdApprox=if(is.character(t))\"\"else fmt(t),feasible=1,reasons=\"\"),cell,scalars(m,c(counts,\"TPR\",\"FPR\",\"precision\",\"meanCost\",\"totalCost\"))));point(kind,\"validation-cost\",name,j-1,j-1,m$meanCost,\"candidate index\",\"hypothetical cost units/mass\",\"validation\",if(is.character(t))t else fmt(t))}\n  m<-c(ev,cv[c(\"ROC_AUC\",\"averagePrecision\",\"PRTrapezoidWithInitialPrecisionOne\")],cal[c(\"ECE\",\"reliability\",\"resolution\",\"uncertainty\",\"withinBinCorrection\",\"BrierIdentityResidual\")])\n  for(k in c(\"TP\",\"FP\",\"FN\",\"TN\",counts,rates,\"ROC_AUC\",\"averagePrecision\",\"PRTrapezoidWithInitialPrecisionOne\",\"ECE\",\"reliability\",\"resolution\",\"uncertainty\",\"withinBinCorrection\",\"BrierIdentityResidual\")){\n   unit<-if(k%in%c(\"TP\",\"FP\",\"FN\",\"TN\",counts))\"rows\"else if(k==\"totalCost\")\"hypothetical cost units\"else if(k==\"meanCost\")\"hypothetical cost units/mass\"else if(k==\"BrierSum\")\"sum squared-probability loss\"else\"dimensionless\"\n   add(\"test-metrics\",tagrow(kind,scenario=name,metric=k,valueExact=\"\",valueApprox=fmt(m[[k]]),unit=unit))\n  }\n  lev<-unique(d$group[test][!is.na(d$group[test])]);sets<-c(list(test),lapply(lev,function(g)test[!is.na(d$group[test])&d$group[test]==g]),list(test[is.na(d$group[test])]))\n  types<-c(\"overall\",rep(\"known\",length(lev)),\"unknown\");tokens<-c(\"all\",lev,\"\")\n  for(j in seq_along(sets)){ids<-sets[[j]];m<-measure(d,p,ids,chosen,cost);cell<-setNames(lapply(c(\"TP\",\"FP\",\"FN\",\"TN\"),function(k)fmt(m[[k]])),paste0(c(\"TP\",\"FP\",\"FN\",\"TN\"),\"Exact\"));add(\"group-metrics\",c(tagrow(kind,scenario=name,groupType=types[j],groupToken=tokens[j],retainedRows=length(ids)),cell,scalars(m,c(counts,rates))));if(types[j]==\"known\")point(kind,\"group-TPR\",name,j-2,j-2,m$TPR,\"declared group position\",\"TPR\",tag=tokens[j])}\n }\n invisible(NULL)\n}\n\n# Fixed finite inputs only; not the complete web input/budget validator.\nqnum<-function(v){if(is.null(v))return(NA_real_);if(is.logical(v))return(as.numeric(v));s<-as.character(v);if(grepl(\"/\",s,fixed=TRUE)){a<-strsplit(s,\"/\",fixed=TRUE)[[1]];return(as.numeric(a[1])/as.numeric(a[2]))};as.numeric(s)}\nrowsG<-function(raw){\n n<-length(raw);get<-function(r,k,default=NULL)if(is.null(r[[k]]))default else r[[k]]\n id<-vapply(raw,function(r)as.character(r$id),character(1));p<-vapply(raw,function(r)qnum(r$score),numeric(1));y<-vapply(raw,function(r)qnum(r$y),numeric(1));w<-vapply(raw,function(r)qnum(get(r,\"weight\",\"1\")),numeric(1));role<-vapply(raw,function(r)get(r,\"role\",\"evaluation\"),character(1));group<-vapply(raw,function(r)as.character(get(r,\"group\",NA_character_)),character(1))\n stopifnot(all(w>=0),all(is.na(p)|(p>=0&p<=1)),all(is.na(y)|y%in%c(0,1)),!anyDuplicated(id));list(id=id,p=p,y=y,w=w,role=role,group=group,eligible=!is.na(p)&!is.na(y)&w>0&role!=\"excluded\")\n}\nscopeG<-function(d,role=\"all\")if(role==\"all\")seq_along(d$id)else which(d$role==role)\nmetricsG<-function(d,ids,t=.5,cost=c(1,1)){\n use<-ids[d$eligible[ids]];p<-d$p[use];y<-d$y[use];w<-d$w[use];a<-if(is.character(t))rep(t==\"always-positive\",length(use))else p>=t\n TP<-sum(w[a&y==1]);FP<-sum(w[a&y==0]);FN<-sum(w[!a&y==1]);TN<-sum(w[!a&y==0]);P<-TP+FN;N<-FP+TN;W<-P+N;PP<-TP+FP;PN<-TN+FN;TPR<-ratio(TP,P);TNR<-ratio(TN,N);bs<-sum(w*(p-y)^2);tc<-FP*cost[1]+FN*cost[2]\n list(confusion=list(TP=TP,FP=FP,FN=FN,TN=TN),mass=W,positiveTargetMass=P,negativeTargetMass=N,predictedPositiveMass=PP,predictedNegativeMass=PN,prevalence=ratio(P,W),selectionRate=ratio(PP,W),accuracy=ratio(TP+TN,W),precision=ratio(TP,PP),negativePredictiveValue=ratio(TN,PN),TPR=TPR,FPR=ratio(FP,N),TNR=TNR,FNR=ratio(FN,P),F1=ratio(2*TP,2*TP+FP+FN),balancedAccuracy=if(is.na(TPR)||is.na(TNR))NA_real_ else(TPR+TNR)/2,Brier=ratio(bs,W),BrierSum=bs,totalCost=tc,meanCost=ratio(tc,W),bayesThreshold=ratio(cost[1],sum(cost)))\n}\ncurvesG<-function(d,ids){\n use<-ids[d$eligible[ids]];grid<-c(list(\"always-negative\"),as.list(sort(unique(d$p[use]),decreasing=TRUE)));points<-lapply(grid,function(t){m<-metricsG(d,ids,t);c(list(policy=t),m$confusion,m[c(\"TPR\",\"FPR\",\"precision\")],list(recall=m$TPR))});pos<-use[d$y[use]==1];neg<-use[d$y[use]==0];P<-sum(d$w[pos]);N<-sum(d$w[neg]);U<-0\n for(i in pos)U<-U+d$w[i]*sum(d$w[neg]*((d$p[i]>d$p[neg])+.5*(d$p[i]==d$p[neg])))\n AP<-trap<-lastR<-0;lastP<-1\n if(P&&length(grid)>1)for(j in 2:length(grid)){z<-points[[j]];AP<-AP+(z$recall-lastR)*z$precision;trap<-trap+(z$recall-lastR)*(z$precision+lastP)/2;lastR<-z$recall;lastP<-z$precision}\n list(points=points,ROC_AUC=ratio(U,P*N),averagePrecision=if(P)AP else NA_real_,PRTrapezoidWithInitialPrecisionOne=if(P)trap else NA_real_)\n}\nchooseG<-function(d,a,cost){\n role<-if(is.null(a$selectionRole))\"validation\"else a$selectionRole;er<-if(is.null(a$evaluationRole))\"test\"else a$evaluationRole;ids<-scopeG(d,role);use<-ids[d$eligible[ids]];stopifnot(length(use)>0);grid<-if(is.null(a$thresholds))c(list(\"always-negative\"),as.list(sort(unique(d$p[use]),decreasing=TRUE)))else lapply(a$thresholds,function(t)if(t%in%c(\"always-negative\",\"always-positive\"))t else qnum(t))\n candidates<-lapply(seq_along(grid),function(j){m<-metricsG(d,ids,grid[[j]],cost);feasible<-TRUE;if(!is.null(a$minTPR))feasible<-feasible&&!is.na(m$TPR)&&m$TPR>=qnum(a$minTPR);if(!is.null(a$maxFPR))feasible<-feasible&&!is.na(m$FPR)&&m$FPR<=qnum(a$maxFPR);list(index=j-1,policy=grid[[j]],metrics=m,feasible=feasible)})\n good<-which(vapply(candidates,function(c)c$feasible,logical(1)));best<-NA_integer_;if(length(good)){v<-vapply(candidates[good],function(c)c$metrics$meanCost,numeric(1));best<-good[which(v<=min(v)+1e-12)[1]]}\n list(selectedIndex=if(is.na(best))NA_integer_ else best-1,selectedPolicy=if(is.na(best))NULL else grid[[best]],selectedValidation=if(is.na(best))NULL else candidates[[best]]$metrics,candidates=candidates,evaluation=if(is.na(best)||er==\"none\")NULL else metricsG(d,scopeG(d,er),grid[[best]],cost))\n}\ncalibrateG<-function(d,ids,edges){\n use<-ids[d$eligible[ids]];W<-sum(d$w[use]);pi<-ratio(sum(d$w[use]*d$y[use]),W);bins<-list();ECE<-rel<-res<-correction<-0;assign<-findInterval(d$p[use],edges,rightmost.closed=TRUE,all.inside=TRUE)\n for(b in seq_len(length(edges)-1)){rr<-use[assign==b];w<-sum(d$w[rr]);mp<-ratio(sum(d$w[rr]*d$p[rr]),w);o<-ratio(sum(d$w[rr]*d$y[rr]),w);variance<-if(w)sum(d$w[rr]*(d$p[rr]-mp)^2)/w else NA_real_;covariance<-if(w)sum(d$w[rr]*(d$p[rr]-mp)*(d$y[rr]-o))/w else NA_real_;bc<-variance-2*covariance;gap<-mp-o;bins[[b]]<-list(index=b-1,mass=w,meanPrediction=mp,eventRate=o,scoreVariance=variance,scoreTargetCovariance=covariance,withinBinCorrection=bc,ids=d$id[rr])\n  if(w){s<-w/W;ECE<-ECE+s*abs(gap);rel<-rel+s*gap^2;res<-res+s*(o-pi)^2;correction<-correction+s*bc}\n };bs<-ratio(sum(d$w[use]*(d$p[use]-d$y[use])^2),W);unc<-pi*(1-pi);list(bins=bins,Brier=bs,ECE=if(W)ECE else NA_real_,uncertainty=unc,reliability=if(W)rel else NA_real_,resolution=if(W)res else NA_real_,withinBinCorrection=if(W)correction else NA_real_,BrierIdentityResidual=bs-(unc-res+rel+correction))\n}\ngroupsG<-function(d,ids,t,cost){\n lev<-unique(d$group[ids][!is.na(d$group[ids])]);groups<-lapply(lev,function(g)list(group=g,metrics=metricsG(d,ids[!is.na(d$group[ids])&d$group[ids]==g],t,cost)));overall<-metricsG(d,ids,t,cost);unknown<-metricsG(d,ids[is.na(d$group[ids])],t,cost);gaps<-list()\n for(k in c(\"prevalence\",\"selectionRate\",\"TPR\",\"FPR\",\"precision\",\"accuracy\",\"meanCost\")){use<-Filter(function(g)g$metrics$mass>0,groups);v<-vapply(use,function(g)g$metrics[[k]],numeric(1));gaps[[k]]<-if(length(use)<2||anyNA(v))NA_real_ else max(v)-min(v)}\n list(overall=overall,groups=groups,unknownGroup=unknown,gaps=gaps,partitionMassResidual=overall$mass-unknown$mass-sum(vapply(groups,function(g)g$metrics$mass,numeric(1))))\n}\nsvgFixed<-function(file,points,title,xlabel,ylabel,legend){\n finite<-points[points$y!=\"undefined\"&points$x!=\"undefined\",,drop=FALSE];x<-as.numeric(finite$x);y<-as.numeric(finite$y);xmin<-if(length(x))min(x)else 0;xmax<-if(length(x))max(x)else 1;ymin<-min(c(0,y));ymax<-max(c(0,y));if(xmin==xmax){xmin<-xmin-.5;xmax<-xmax+.5};if(ymin==ymax)ymax<-ymin+1;X<-function(v)85+(v-xmin)/(xmax-xmin)*480;Y<-function(v)278-(v-ymin)/(ymax-ymin)*175\n esc<-function(s){s<-gsub(\"&\",\"&amp;\",s,fixed=TRUE);s<-gsub(\"<\",\"&lt;\",s,fixed=TRUE);gsub(\">\",\"&gt;\",s,fixed=TRUE)};s<-'<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"620\" height=\"360\" viewBox=\"0 0 620 360\"><rect width=\"620\" height=\"360\" fill=\"white\"/><g font-family=\"Arial, sans-serif\" font-size=\"13\" fill=\"#17324d\">'\n lines<-strwrap(title,width=65);for(i in seq_along(lines))s<-paste0(s,'<text x=\"25\" y=\"',24+(i-1)*18,'\">',esc(lines[i]),'</text>');colors<-c(\"#176b9b\",\"#b85e18\",\"#437e4d\")\n for(i in seq_along(legend))s<-paste0(s,'<circle cx=\"',30+(i-1)*250,'\" cy=\"76\" r=\"4\" fill=\"',colors[(i-1)%%3+1],'\"/><text x=\"',42+(i-1)*250,'\" y=\"80\">',esc(legend[i]),'</text>')\n s<-paste0(s,'<path d=\"M85 98V278H575\" fill=\"none\" stroke=\"#52677d\"/><text text-anchor=\"middle\" x=\"325\" y=\"338\">',esc(xlabel),'</text><text text-anchor=\"middle\" transform=\"translate(21,190) rotate(-90)\">',esc(ylabel),'</text>')\n for(i in 0:4){xx<-xmin+(xmax-xmin)*i/4;yy<-ymin+(ymax-ymin)*i/4;s<-paste0(s,'<text text-anchor=\"middle\" x=\"',sprintf(\"%.9g\",X(xx)),'\" y=\"305\">',sprintf(\"%.4g\",xx),'</text><text text-anchor=\"end\" x=\"77\" y=\"',sprintf(\"%.9g\",Y(yy)+4),'\">',sprintf(\"%.4g\",yy),'</text>')}\n for(i in seq_len(nrow(finite)))s<-paste0(s,'<circle cx=\"',sprintf(\"%.9g\",X(x[i])),'\" cy=\"',sprintf(\"%.9g\",Y(y[i])),'\" r=\"3\" fill=\"',colors[as.integer(finite$series[i])%%3+1],'\"/>');writeLines(paste0(s,'</g></svg>'),file,useBytes=TRUE)\n}\nfixedRun<-function(){\n api<-FIXED$api;a<-FIXED$args;summary<-list();points<-list();xlabel<-\"Declared index\";ylabel<-\"Value\";legend<-\"Declared result\"\n metric<-function(name,v,unit=\"dimensionless\"){if(is.null(v))v<-NA_real_;summary[[length(summary)+1L]]<<-data.frame(metric=name,value=if(is.na(v))\"undefined\"else sprintf(\"%.9g\",v),exactValue=\"\",unit=unit,defined=as.integer(!is.na(v)),stringsAsFactors=FALSE)}\n pt<-function(i,x,y,id=\"\",series=0){points[[length(points)+1L]]<<-data.frame(series=series,index=i,xExact=\"\",x=if(is.na(x))\"undefined\"else sprintf(\"%.9g\",x),yExact=\"\",y=if(is.na(y))\"undefined\"else sprintf(\"%.9g\",y),id=as.character(id),stringsAsFactors=FALSE)}\n if(api==\"realdata\"){\n  native<-loadData()[[a$kind]];fit<-fitmodel(native);d<-list(id=native$id,p=fit$pred,y=native$y,w=rep(1,length(native$id)),role=native$role,group=native$group,eligible=native$eligible);scenarios<-list()\n  for(j in 1:3){name<-c(\"equal\",\"miss-five\",\"alarm-five\")[j];cst<-list(c(1,1),c(1,5),c(5,1))[[j]];sel<-chooseG(d,list(),cst);scenarios[[j]]<-list(name=name,selection=sel);metric(paste0(name,\"Threshold\"),sel$selectedPolicy);metric(paste0(name,\"TestCost\"),sel$evaluation$meanCost,\"hypothetical cost units/mass\")}\n  ids<-scopeG(d,\"test\");cv<-curvesG(d,ids);cal<-calibrateG(d,ids,seq(0,1,.2));metric(\"testAUC\",cv$ROC_AUC);metric(\"testAP\",cv$averagePrecision);metric(\"testBrier\",cal$Brier);metric(\"eligibleRows\",sum(d$eligible),\"rows\")\n  for(j in seq_along(ids)){i<-ids[j];pt(j-1,j,d$p[i],d$id[i],0);pt(j-1,j,d$y[i],d$id[i],1)}\n  full<-list(kind=a$kind,fit=fit,scenarios=scenarios,testCurves=cv,testCalibration=cal,rowsScored=d);xlabel<-\"Test row, native order\";ylabel<-\"Y or probability\";legend<-c(\"Training-fitted probability\",\"Observed Y\")\n }else{\n  d<-rowsG(a$rows);role<-if(is.null(a$role))\"all\"else a$role;ids<-scopeG(d,role);cost<-if(is.null(a$costs))c(1,1)else c(qnum(a$costs$falsePositive),qnum(a$costs$falseNegative));t<-if(is.null(a$threshold)).5 else if(a$threshold%in%c(\"always-positive\",\"always-negative\"))a$threshold else qnum(a$threshold)\n  if(api==\"metrics\"){\n   full<-metricsG(d,ids,t,cost);for(k in c(\"mass\",\"accuracy\",\"precision\",\"TPR\",\"FPR\",\"F1\",\"Brier\",\"meanCost\"))metric(k,full[[k]],if(k==\"mass\")\"mass\"else if(k==\"meanCost\")\"hypothetical cost units/mass\"else\"dimensionless\");metric(\"BayesThreshold\",full$bayesThreshold)\n   for(i in 1:4)pt(i-1,i-1,full$confusion[[i]],names(full$confusion)[i]);xlabel<-\"TP / FP / FN / TN positions\";ylabel<-\"Analytical mass\"\n  }else if(api==\"curves\"){\n   full<-curvesG(d,ids);for(k in c(\"ROC_AUC\",\"averagePrecision\",\"PRTrapezoidWithInitialPrecisionOne\"))metric(k,full[[k]])\n   for(j in seq_along(full$points)){p<-full$points[[j]];pt(j-1,p$FPR,p$TPR,if(is.character(p$policy))p$policy else sprintf(\"%.17g\",p$policy))};xlabel<-\"False positive rate\";ylabel<-\"True positive rate\";legend<-\"Observed ROC operating points\"\n  }else if(api==\"choose\"){\n   full<-chooseG(d,a,cost);metric(\"selectedIndex\",full$selectedIndex,\"candidate index\");metric(\"minimumCost\",if(is.null(full$selectedValidation))NULL else full$selectedValidation$meanCost,\"hypothetical cost units/mass\");metric(\"feasible\",as.integer(!is.na(full$selectedIndex)),\"indicator\")\n   for(c in full$candidates)pt(c$index,c$index,c$metrics$meanCost,if(is.character(c$policy))c$policy else sprintf(\"%.17g\",c$policy));xlabel<-\"Validation candidate\";ylabel<-\"Assumed cost / mass\";legend<-\"Validation candidate costs\"\n  }else if(api==\"calibrate\"){\n   edges<-if(is.null(a$binEdges))seq(0,1,.2)else vapply(a$binEdges,qnum,numeric(1));full<-calibrateG(d,ids,edges);for(k in c(\"ECE\",\"Brier\",\"uncertainty\",\"resolution\",\"reliability\",\"withinBinCorrection\",\"BrierIdentityResidual\"))metric(k,full[[k]])\n   for(b in full$bins)pt(b$index,b$meanPrediction,b$eventRate,paste0(\"bin:\",b$index));xlabel<-\"Bin mean forecast\";ylabel<-\"Bin event rate\";legend<-\"Binary-event reliability\"\n  }else if(api==\"groups\"){\n   full<-groupsG(d,ids,t,cost);metric(\"overallTPR\",full$overall$TPR);metric(\"TPRGap\",full$gaps$TPR);metric(\"precisionGap\",full$gaps$precision);metric(\"unknownMass\",full$unknownGroup$mass,\"mass\");metric(\"partitionResidual\",full$partitionMassResidual,\"mass\")\n   for(j in seq_along(full$groups))pt(j-1,j-1,full$groups[[j]]$metrics$TPR,full$groups[[j]]$group);xlabel<-\"Declared group position\";ylabel<-\"True positive rate\";legend<-\"Known-group TPR\"\n  }else stop(\"unknown declared fixed API\")\n }\n sm<-do.call(rbind,summary);pp<-do.call(rbind,points);write.csv(sm,file.path(outDir,\"summary.csv\"),row.names=FALSE,na=\"\");write.csv(pp,file.path(outDir,\"plot-points.csv\"),row.names=FALSE,na=\"\");svgFixed(file.path(outDir,\"plot.svg\"),pp,FIXED$title,xlabel,ylabel,legend);dput(list(api=api,variant=FIXED$variant,input=FIXED$args,arithmetic=\"Base-R binary64 fixed example; not an exact rational general validator\",result=full),file=file.path(outDir,\"full.txt\"));cat(\"PASS\",api,FIXED$variant,\"summary\",nrow(sm),\"points\",nrow(pp),\"\\n\")\n}\n\nFIXED<-list(api=\"metrics\",variant=\"six-cards\",args=list(rows=list(list(id=\"a\",score=\".9\",y=1,group=\"A\"),list(id=\"b\",score=\".8\",y=1,group=\"A\"),list(id=\"c\",score=\".8\",y=0,group=\"A\"),list(id=\"d\",score=\".6\",y=0,group=\"B\"),list(id=\"e\",score=\".4\",y=1,group=\"B\"),list(id=\"f\",score=\".1\",y=0,group=\"B\")),threshold=\".8\"),title=\"Six-card confusion cells at threshold0.8\")\nfixedRun()\n",
        "input": {
          "rows": [
            {
              "id": "a",
              "score": ".9",
              "y": 1,
              "group": "A"
            },
            {
              "id": "b",
              "score": ".8",
              "y": 1,
              "group": "A"
            },
            {
              "id": "c",
              "score": ".8",
              "y": 0,
              "group": "A"
            },
            {
              "id": "d",
              "score": ".6",
              "y": 0,
              "group": "B"
            },
            {
              "id": "e",
              "score": ".4",
              "y": 1,
              "group": "B"
            },
            {
              "id": "f",
              "score": ".1",
              "y": 0,
              "group": "B"
            }
          ],
          "threshold": ".8"
        },
        "inputFiles": [],
        "returnCode": 0,
        "expectedFailure": false,
        "stdout": "PASS metrics six-cards summary 9 points 4 \n",
        "stderr": "During startup - Warning messages:\n1: Setting LC_COLLATE=C.UTF-8 failed \n2: Setting LC_CTYPE=C.UTF-8 failed \n3: Setting LC_MONETARY=C.UTF-8 failed \n4: Setting LC_TIME=C.UTF-8 failed \n",
        "summary": {
          "mass": "6",
          "accuracy": "0.666666667",
          "precision": "0.666666667",
          "TPR": "0.666666667",
          "FPR": "0.333333333",
          "F1": "0.666666667",
          "Brier": "0.236666667",
          "meanCost": "0.333333333",
          "BayesThreshold": "0.5"
        },
        "summaryRows": [
          {
            "metric": "mass",
            "value": "6",
            "exactValue": "",
            "unit": "mass",
            "defined": "1"
          },
          {
            "metric": "accuracy",
            "value": "0.666666667",
            "exactValue": "",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "precision",
            "value": "0.666666667",
            "exactValue": "",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "TPR",
            "value": "0.666666667",
            "exactValue": "",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "FPR",
            "value": "0.333333333",
            "exactValue": "",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "F1",
            "value": "0.666666667",
            "exactValue": "",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "Brier",
            "value": "0.236666667",
            "exactValue": "",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "meanCost",
            "value": "0.333333333",
            "exactValue": "",
            "unit": "hypothetical cost units/mass",
            "defined": "1"
          },
          {
            "metric": "BayesThreshold",
            "value": "0.5",
            "exactValue": "",
            "unit": "dimensionless",
            "defined": "1"
          }
        ],
        "plotPoints": [
          {
            "series": "0",
            "index": "0",
            "xExact": "",
            "x": "0",
            "yExact": "",
            "y": "2",
            "id": "TP"
          },
          {
            "series": "0",
            "index": "1",
            "xExact": "",
            "x": "1",
            "yExact": "",
            "y": "1",
            "id": "FP"
          },
          {
            "series": "0",
            "index": "2",
            "xExact": "",
            "x": "2",
            "yExact": "",
            "y": "1",
            "id": "FN"
          },
          {
            "series": "0",
            "index": "3",
            "xExact": "",
            "x": "3",
            "yExact": "",
            "y": "2",
            "id": "TN"
          }
        ],
        "plotFile": "ml14-fixed-results/metrics-six-cards-r/plot.svg",
        "plotSHA256": "179313fdc3e0e47c32cfa479d9f5cae7888b63914d95423cfe72109499424292",
        "files": [
          {
            "file": "ml14-fixed-results/metrics-six-cards-r/full.txt",
            "sha256": "0049ed6bbfc782b25939e3f7e67a2c1d7a99c81195c1f0955005d0583b98839a",
            "bytes": 1207
          },
          {
            "file": "ml14-fixed-results/metrics-six-cards-r/plot-points.csv",
            "sha256": "7b046b647b3a65a3930f4f9b53cf0379c47735917edc4f9de7b755e8d6eda076",
            "bytes": 145
          },
          {
            "file": "ml14-fixed-results/metrics-six-cards-r/plot.svg",
            "sha256": "179313fdc3e0e47c32cfa479d9f5cae7888b63914d95423cfe72109499424292",
            "bytes": 1291
          },
          {
            "file": "ml14-fixed-results/metrics-six-cards-r/summary.csv",
            "sha256": "11df76f4597d2deb998cab537d7c7588b34f0c6fa287cded52a66e06243e23f0",
            "bytes": 443
          }
        ],
        "scope": "Actually executed standalone fixed example, Python exact Fraction versus base-R binary64. Approximate R residuals retained; not universal exact arithmetic/web validation/native UI. Source programs read factual3CSV only."
      },
      "weighted": {
        "api": "metrics",
        "variant": "weighted",
        "language": "r",
        "title": "Double only the tied negative card mass",
        "codeFile": "ml14-code/metrics-weighted.R",
        "codeSHA256": "2b782b16938e1f1cf5de3bb17c89f0ca24a5c56858f5b8d8214c51c3dfc52734",
        "code": "# ML14 standalone public counterpart, base R only.\n# Inputs are only the three factual CSVs; derived columns/previous model answers unused.\n# Binary64 arithmetic, not arbitrary-precision Fraction. At numerical cost ties\n# within 1e-12 retain the earliest candidate. Exact claims belong to Python/web.\n# SHA256 infrastructure below is reused verbatim from the previous public study.\nargs<-commandArgs(trailingOnly=TRUE);filearg<-grep(\"^--file=\",commandArgs(),value=TRUE)\nhere<-if(dir.exists(\"ml14-sources\"))getwd()else if(length(filearg))dirname(normalizePath(sub(\"^--file=\",\"\",filearg[1])))else getwd()\noption<-function(key,default){i<-match(key,args);if(is.na(i))default else args[i+1]}\nsourceDir<-option(\"--source\",file.path(here,\"ml14-sources\"));outDir<-option(\"--out\",file.path(getwd(),\"ml14-r-results\"));dir.create(outDir,recursive=TRUE,showWarnings=FALSE)\nnum<-function(x){x[x%in%c(\"\",\".\")]<-NA_character_;as.numeric(x)}\nfmt<-function(x)ifelse(is.na(x),\"\",sprintf(\"%.17g\",x))\nratio<-function(a,b)if(b==0)NA_real_ else a/b\nreadnative<-function(name)read.csv(file.path(sourceDir,name),check.names=FALSE,colClasses=\"character\",na.strings=character(),stringsAsFactors=FALSE)\n# Vectorized SHA256 for the short ASCII keys used in this study.\n# Unsigned words use exact integer-valued doubles; bit operations use safe\n# 16-bit halves, avoiding R's reserved signed-INT_MIN/NA representation.\nMOD<-2^32\nxor32<-function(a,b) as.double(bitwXor(as.integer(floor(a/65536)),as.integer(floor(b/65536))))*65536+as.double(bitwXor(as.integer(a%%65536),as.integer(b%%65536)))\nand32<-function(a,b) as.double(bitwAnd(as.integer(floor(a/65536)),as.integer(floor(b/65536))))*65536+as.double(bitwAnd(as.integer(a%%65536),as.integer(b%%65536)))\nrot<-function(x,n) floor(x/2^n)+(x%%2^n)*2^(32-n)\nxor3<-function(a,b,c) xor32(xor32(a,b),c)\nK<-c(0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5,0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967,0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070,0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3,0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2)\nsha256<-function(strings) {\n n<-length(strings);bytes<-matrix(0,n,64)\n for(i in seq_len(n)) {v<-utf8ToInt(strings[i]);stopifnot(length(v)<56,all(v<128));if(length(v)) bytes[i,seq_along(v)]<-v;bytes[i,length(v)+1]<-128;bits<-length(v)*8;bytes[i,61:64]<-c(floor(bits/2^24)%%256,floor(bits/2^16)%%256,floor(bits/256)%%256,bits%%256)}\n w<-matrix(0,n,64)\n for(j in 1:16) {b<-4*(j-1)+1;w[,j]<-bytes[,b]*2^24+bytes[,b+1]*2^16+bytes[,b+2]*256+bytes[,b+3]}\n for(j in 17:64) {s0<-xor3(rot(w[,j-15],7),rot(w[,j-15],18),floor(w[,j-15]/8));s1<-xor3(rot(w[,j-2],17),rot(w[,j-2],19),floor(w[,j-2]/1024));w[,j]<-(w[,j-16]+s0+w[,j-7]+s1)%%MOD}\n init<-c(0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19)\n state<-lapply(init,function(v) rep(v,n));a<-state[[1]];b<-state[[2]];c<-state[[3]];d<-state[[4]];e<-state[[5]];f<-state[[6]];g<-state[[7]];h<-state[[8]]\n for(j in 1:64) {S1<-xor3(rot(e,6),rot(e,11),rot(e,25));ch<-xor32(and32(e,f),and32(MOD-1-e,g));t1<-(h+S1+ch+K[j]+w[,j])%%MOD;S0<-xor3(rot(a,2),rot(a,13),rot(a,22));maj<-xor3(and32(a,b),and32(a,c),and32(b,c));t2<-(S0+maj)%%MOD;h<-g;g<-f;f<-e;e<-(d+t1)%%MOD;d<-c;c<-b;b<-a;a<-(t1+t2)%%MOD}\n end<-list(a,b,c,d,e,f,g,h);hex<-lapply(1:8,function(j){v<-(end[[j]]+init[j])%%MOD;paste0(sprintf(\"%04x\",as.integer(floor(v/65536))),sprintf(\"%04x\",as.integer(v%%65536)))})\n do.call(paste0,hex)\n}\nstopifnot(identical(sha256(c(\"abc\",\"\")),c(\"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad\",\"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855\")))\n\nloadData<-function(){\n wb<-readnative(\"actual64-country-four-indicators-original-2024.csv\");codes<-c(\"NY.GDP.PCAP.KD\",\"NY.GDP.MKTP.KD.ZG\",\"FP.CPI.TOTL.ZG\",\"SP.DYN.LE00.IN\");iso<-sort(unique(wb$countryISO3));stopifnot(nrow(wb)==64,length(iso)==16)\n tokens<-t(vapply(iso,function(s)wb$originalValueToken[match(paste(s,codes),paste(wb$countryISO3,wb$indicatorID))],character(4)));vals<-matrix(num(as.vector(tokens)),nrow=nrow(tokens))\n country<-list(id=paste0(iso,\":2024\"),sourceRow=1:16,originalID=iso,x=vals[,1:3,drop=FALSE],rawX=tokens[,1:3,drop=FALSE],nativeTarget=tokens[,4],y=as.integer(vals[,4]>=80),group=ifelse(is.na(vals[,1]),NA_character_,as.character(as.integer(vals[,1]>=25000))),lineage=vapply(iso,function(s)paste(wb$sourceRow[match(paste(s,codes),paste(wb$countryISO3,wb$indicatorID))],collapse=\";\"),character(1)),cat=integer(),units=c(\"constant2015USD/person\",\"annualPercent\",\"annualPercent\"))\n nls<-readnative(\"actual3613-NLS-original52-fields-groups-roles.csv\");raw<-cbind(nls$ed76,nls$age76,nls$nearc4)\n person<-list(id=paste0(\"person:\",nls$sourceRow),sourceRow=as.integer(nls$sourceRow),originalID=nls$id,x=matrix(num(as.vector(raw)),nrow=nrow(raw)),rawX=raw,nativeTarget=nls$wage76,y=as.integer(num(nls$wage76)>=500),group=ifelse(nls$black%in%c(\"\",\".\"),NA_character_,nls$black),lineage=nls$sourceRow,cat=2L,units=c(\"years\",\"years\",\"nativeCategory\"))\n ch<-readnative(\"actual3150-churn-original14-fields-groups-roles.csv\");raw<-cbind(ch[[\"Call  Failure\"]],ch$Complains,ch[[\"Subscription  Length\"]],ch[[\"Seconds of Use\"]])\n company<-list(id=paste0(\"customer:\",ch$sourceRow),sourceRow=as.integer(ch$sourceRow),originalID=rep(\"\",nrow(ch)),x=matrix(num(as.vector(raw)),nrow=nrow(raw)),rawX=raw,nativeTarget=ch$Churn,y=as.integer(ch$Churn),group=ifelse(ch[[\"Tariff Plan\"]]%in%c(\"\",\".\"),NA_character_,ch[[\"Tariff Plan\"]]),lineage=ch$sourceRow,cat=1L,units=c(\"count\",\"nativeCategory\",\"months\",\"seconds\"))\n stopifnot(nrow(nls)==3613,nrow(ch)==3150,identical(as.integer(ch$sourceRow[ch[[\"Charge  Amount\"]]==\"10\"]),c(474L,2174L,2274L,2374L,2674L,2924L,2974L)))\n result<-list(country=country,person=person,company=company)\n for(k in names(result)){d<-result[[k]];n<-length(d$id);d$eligible<-!is.na(d$y)&rowSums(is.na(d$x))==0;hash<-sha256(paste0(\"ML14-role|\",k,\"|\",d$id));rank<-integer(n);rank[order(hash,seq_len(n))]<-seq_len(n)-1L;d$plannedRole<-ifelse(rank%%5==0,\"test\",ifelse(rank%%5==1,\"validation\",\"train\"));d$role<-ifelse(d$eligible,d$plannedRole,\"excluded\");result[[k]]<-d}\n stopifnot(sum(result$person$eligible)==3017);result\n}\nfitmodel<-function(d){\n ids<-which(d$role==\"train\");p<-ncol(d$x);m<-vapply(seq_len(p),function(j)if((j-1)%in%d$cat)NA_real_ else median(d$x[ids,j]),numeric(1));z<-d$x\n for(j in seq_len(p))if(!((j-1)%in%d$cat))z[,j]<-as.numeric(z[,j]>m[j])\n keys<-apply(z,1,function(v)paste(fmt(v),collapse=\"|\"));lev<-unique(keys[ids]);mass<-vapply(lev,function(k)sum(keys[ids]==k),integer(1));positive<-vapply(lev,function(k)sum(d$y[ids][keys[ids]==k]),integer(1));prob<-(positive+1)/(mass+2);fallback<-(sum(d$y[ids])+1)/(length(ids)+2);pred<-prob[match(keys,lev)];unseen<-is.na(pred);pred[unseen]<-fallback;pred[!d$eligible]<-NA_real_;unseen[!d$eligible]<-NA\n list(ids=ids,medians=m,z=z,keys=keys,lev=lev,mass=mass,positive=positive,prob=prob,fallback=fallback,pred=pred,unseen=unseen)\n}\nmeasure<-function(d,p,ids,t=.5,cost=c(1,1)){\n use<-ids[d$eligible[ids]&!is.na(p[ids])];y<-d$y[use];a<-if(is.character(t))rep(t==\"always-positive\",length(use))else p[use]>=t\n TP<-sum(a&y==1);FP<-sum(a&y==0);FN<-sum(!a&y==1);TN<-sum(!a&y==0);P<-TP+FN;N<-FP+TN;W<-P+N;PP<-TP+FP;PN<-TN+FN;TPR<-ratio(TP,P);TNR<-ratio(TN,N);bs<-sum((p[use]-y)^2);tc<-FP*cost[1]+FN*cost[2]\n list(TP=TP,FP=FP,FN=FN,TN=TN,mass=W,positiveTargetMass=P,negativeTargetMass=N,predictedPositiveMass=PP,predictedNegativeMass=PN,prevalence=ratio(P,W),selectionRate=ratio(PP,W),accuracy=ratio(TP+TN,W),precision=ratio(TP,PP),negativePredictiveValue=ratio(TN,PN),TPR=TPR,FPR=ratio(FP,N),TNR=TNR,FNR=ratio(FN,P),F1=ratio(2*TP,2*TP+FP+FN),balancedAccuracy=if(is.na(TPR)||is.na(TNR))NA_real_ else(TPR+TNR)/2,Brier=ratio(bs,W),BrierSum=bs,totalCost=tc,meanCost=ratio(tc,W))\n}\ncurves<-function(d,p,ids){\n use<-ids[d$eligible[ids]&!is.na(p[ids])];scores<-sort(unique(p[use]),decreasing=TRUE);policies<-c(list(\"always-negative\"),as.list(scores));points<-lapply(policies,function(t){m<-measure(d,p,ids,t);c(list(policy=t),m[c(\"TP\",\"FP\",\"FN\",\"TN\",\"TPR\",\"FPR\",\"precision\")],list(recall=m$TPR))})\n pos<-use[d$y[use]==1];neg<-use[d$y[use]==0];U<-0;for(i in pos)U<-U+sum(p[i]>p[neg])+.5*sum(p[i]==p[neg])\n AP<-0;trap<-0;lastR<-0;lastP<-1\n if(length(pos)&&length(scores))for(j in seq_along(scores)){z<-points[[j+1]];AP<-AP+(z$recall-lastR)*z$precision;trap<-trap+(z$recall-lastR)*(z$precision+lastP)/2;lastR<-z$recall;lastP<-z$precision}\n list(points=points,ROC_AUC=ratio(U,length(pos)*length(neg)),averagePrecision=if(length(pos))AP else NA_real_,PRTrapezoidWithInitialPrecisionOne=if(length(pos))trap else NA_real_)\n}\ncalibrate<-function(d,p,ids){\n use<-ids[d$eligible[ids]&!is.na(p[ids])];W<-length(use);pi<-if(W)mean(d$y[use])else NA_real_;bins<-list();ECE<-rel<-res<-correction<-0\n whichbin<-findInterval(p[use],seq(0,1,.2),rightmost.closed=TRUE,all.inside=TRUE)\n for(b in 1:5){rr<-use[whichbin==b];w<-length(rr);mp<-if(w)mean(p[rr])else NA_real_;o<-if(w)mean(d$y[rr])else NA_real_;variance<-if(w)mean((p[rr]-mp)^2)else NA_real_;covariance<-if(w)mean((p[rr]-mp)*(d$y[rr]-o))else NA_real_;bc<-variance-2*covariance;gap<-mp-o\n  bins[[b]]<-list(mass=w,meanPrediction=mp,eventRate=o,gap=gap,absoluteGap=abs(gap),scoreVariance=variance,scoreTargetCovariance=covariance,withinBinCorrection=bc,rows=w,ids=d$id[rr])\n  if(w){share<-w/W;ECE<-ECE+share*abs(gap);rel<-rel+share*gap^2;res<-res+share*(o-pi)^2;correction<-correction+share*bc}\n };bs<-if(W)mean((p[use]-d$y[use])^2)else NA_real_;unc<-pi*(1-pi)\n list(bins=bins,ECE=if(W)ECE else NA_real_,Brier=bs,reliability=if(W)rel else NA_real_,resolution=if(W)res else NA_real_,uncertainty=unc,withinBinCorrection=if(W)correction else NA_real_,BrierIdentityResidual=bs-(unc-res+rel+correction))\n}\ncounts<-c(\"mass\",\"positiveTargetMass\",\"negativeTargetMass\",\"predictedPositiveMass\",\"predictedNegativeMass\");rates<-c(\"prevalence\",\"selectionRate\",\"accuracy\",\"precision\",\"negativePredictiveValue\",\"TPR\",\"FPR\",\"TNR\",\"FNR\",\"F1\",\"balancedAccuracy\",\"Brier\",\"BrierSum\",\"totalCost\",\"meanCost\")\ntables<-setNames(lapply(1:10,function(i)list()),c(\"predictions\",\"lineage\",\"fit-medians\",\"fit-cells\",\"validation-candidates\",\"test-metrics\",\"test-curves\",\"calibration-bins\",\"group-metrics\",\"chart-points\"))\nadd<-function(name,row)tables[[name]][[length(tables[[name]])+1L]]<<-row\nscalars<-function(m,keys){out<-list();for(k in keys){out[[paste0(k,\"Exact\")]]<-\"\";out[[paste0(k,\"Approx\")]]<-fmt(m[[k]])};out}\ntagrow<-function(kind,...)c(list(kind=kind),list(...))\npoint<-function(kind,chart,series,index,x,y,xunit=\"dimensionless\",yunit=\"dimensionless\",role=\"test\",tag=\"\"){add(\"chart-points\",tagrow(kind,chart=chart,series=series,index=index,xExact=\"\",xApprox=fmt(x),yExact=\"\",yApprox=fmt(y),xUnit=xunit,yUnit=yunit,role=role,tag=tag))}\nstudy<-function(kind,d){\n f<-fitmodel(d);n<-length(d$id);train<-which(d$role==\"train\");validation<-which(d$role==\"validation\");test<-which(d$role==\"test\");p<-f$pred;cv<-curves(d,p,test);cal<-calibrate(d,p,test)\n for(i in seq_len(n)){\n  reason<-if(d$eligible[i])\"\"else\"required-X-or-Y-missing\";transformed<-if(d$eligible[i])paste(fmt(f$z[i,]),collapse=\"|\")else\"\"\n  add(\"predictions\",tagrow(kind,id=d$id[i],sourceRow=d$sourceRow[i],originalID=d$originalID[i],plannedRole=d$plannedRole[i],role=d$role[i],group=ifelse(is.na(d$group[i]),\"\",d$group[i]),eligible=as.integer(d$eligible[i]),targetExact=fmt(d$y[i]),probabilityExact=\"\",probabilityApprox=fmt(p[i]),unseenCell=ifelse(is.na(f$unseen[i]),\"\",as.character(as.integer(f$unseen[i]))),transformedX=transformed,reason=reason))\n  raw<-d$rawX[i,];raw[raw%in%c(\"\",\".\")]<-\"\";nativeY<-d$nativeTarget[i];if(nativeY%in%c(\"\",\".\"))nativeY<-\"\"\n  add(\"lineage\",tagrow(kind,id=d$id[i],sourceRow=d$sourceRow[i],originalID=d$originalID[i],nativeSourceRows=d$lineage[i],rawX=paste(raw,collapse=\"|\"),nativeTarget=nativeY,derivedTarget=fmt(d$y[i]),nativeGroup=ifelse(is.na(d$group[i]),\"\",d$group[i]),plannedRole=d$plannedRole[i],role=d$role[i],eligible=as.integer(d$eligible[i]),analyticalMass=\"1\",reason=reason))\n }\n for(j in seq_len(ncol(d$x)))add(\"fit-medians\",tagrow(kind,feature=j-1,categorical=as.integer((j-1)%in%d$cat),fitRows=length(train),medianExact=\"\",medianApprox=fmt(f$medians[j]),unit=d$units[j]))\n for(j in seq_along(f$lev))add(\"fit-cells\",tagrow(kind,cell=f$lev[j],trainingRows=f$mass[j],positiveRows=f$positive[j],probabilityExact=\"\",probabilityApprox=fmt(f$prob[j]),fallbackExact=\"\",fallbackApprox=fmt(f$fallback)))\n for(j in seq_along(cv$points)){\n  z<-cv$points[[j]];t<-z$policy;add(\"test-curves\",c(tagrow(kind,point=j-1,policy=if(is.character(t))t else\"threshold\",thresholdExact=\"\",thresholdApprox=if(is.character(t))\"\"else fmt(t)),scalars(z,c(\"TP\",\"FP\",\"FN\",\"TN\",\"TPR\",\"FPR\",\"precision\",\"recall\"))))\n  point(kind,\"roc\",\"ROC\",j-1,z$FPR,z$TPR);point(kind,\"pr\",\"PR-observed\",j-1,z$recall,z$precision)\n }\n for(b in 1:5){z<-cal$bins[[b]];add(\"calibration-bins\",c(tagrow(kind,bin=b-1,leftExact=c(\"0\",\"1/5\",\"2/5\",\"3/5\",\"4/5\")[b],rightExact=c(\"1/5\",\"2/5\",\"3/5\",\"4/5\",\"1\")[b],rightClosed=as.integer(b==5),rows=z$rows,ids=paste(z$ids,collapse=\";\")),scalars(z,c(\"mass\",\"meanPrediction\",\"eventRate\",\"gap\",\"absoluteGap\",\"scoreVariance\",\"scoreTargetCovariance\",\"withinBinCorrection\"))));point(kind,\"reliability\",\"Binary event rate\",b-1,z$meanPrediction,z$eventRate,tag=paste0(\"rows=\",z$rows))}\n for(j in seq_along(test)){i<-test[j];point(kind,\"test-scores\",\"Training-fitted probability\",j-1,j,p[i],\"test-row position\",\"probability\",tag=d$id[i]);point(kind,\"test-scores\",\"Observed Y\",j-1,j,d$y[i],\"test-row position\",\"binary target\",tag=d$id[i])}\n scenarioNames<-c(\"equal\",\"miss-five\",\"alarm-five\");costs<-list(c(1,1),c(1,5),c(5,1))\n for(s in 1:3){name<-scenarioNames[s];cost<-costs[[s]];grid<-c(list(\"always-negative\"),as.list(sort(unique(p[validation]),decreasing=TRUE)));candidates<-lapply(grid,function(t)measure(d,p,validation,t,cost));values<-vapply(candidates,function(m)m$meanCost,numeric(1));best<-which(values<=min(values)+1e-12)[1];chosen<-grid[[best]];ev<-measure(d,p,test,chosen,cost)\n  for(j in seq_along(grid)){t<-grid[[j]];m<-candidates[[j]];cell<-setNames(lapply(c(\"TP\",\"FP\",\"FN\",\"TN\"),function(k)fmt(m[[k]])),paste0(c(\"TP\",\"FP\",\"FN\",\"TN\"),\"Exact\"));add(\"validation-candidates\",c(tagrow(kind,scenario=name,candidate=j-1,selected=as.integer(j==best),policy=if(is.character(t))t else\"threshold\",thresholdExact=\"\",thresholdApprox=if(is.character(t))\"\"else fmt(t),feasible=1,reasons=\"\"),cell,scalars(m,c(counts,\"TPR\",\"FPR\",\"precision\",\"meanCost\",\"totalCost\"))));point(kind,\"validation-cost\",name,j-1,j-1,m$meanCost,\"candidate index\",\"hypothetical cost units/mass\",\"validation\",if(is.character(t))t else fmt(t))}\n  m<-c(ev,cv[c(\"ROC_AUC\",\"averagePrecision\",\"PRTrapezoidWithInitialPrecisionOne\")],cal[c(\"ECE\",\"reliability\",\"resolution\",\"uncertainty\",\"withinBinCorrection\",\"BrierIdentityResidual\")])\n  for(k in c(\"TP\",\"FP\",\"FN\",\"TN\",counts,rates,\"ROC_AUC\",\"averagePrecision\",\"PRTrapezoidWithInitialPrecisionOne\",\"ECE\",\"reliability\",\"resolution\",\"uncertainty\",\"withinBinCorrection\",\"BrierIdentityResidual\")){\n   unit<-if(k%in%c(\"TP\",\"FP\",\"FN\",\"TN\",counts))\"rows\"else if(k==\"totalCost\")\"hypothetical cost units\"else if(k==\"meanCost\")\"hypothetical cost units/mass\"else if(k==\"BrierSum\")\"sum squared-probability loss\"else\"dimensionless\"\n   add(\"test-metrics\",tagrow(kind,scenario=name,metric=k,valueExact=\"\",valueApprox=fmt(m[[k]]),unit=unit))\n  }\n  lev<-unique(d$group[test][!is.na(d$group[test])]);sets<-c(list(test),lapply(lev,function(g)test[!is.na(d$group[test])&d$group[test]==g]),list(test[is.na(d$group[test])]))\n  types<-c(\"overall\",rep(\"known\",length(lev)),\"unknown\");tokens<-c(\"all\",lev,\"\")\n  for(j in seq_along(sets)){ids<-sets[[j]];m<-measure(d,p,ids,chosen,cost);cell<-setNames(lapply(c(\"TP\",\"FP\",\"FN\",\"TN\"),function(k)fmt(m[[k]])),paste0(c(\"TP\",\"FP\",\"FN\",\"TN\"),\"Exact\"));add(\"group-metrics\",c(tagrow(kind,scenario=name,groupType=types[j],groupToken=tokens[j],retainedRows=length(ids)),cell,scalars(m,c(counts,rates))));if(types[j]==\"known\")point(kind,\"group-TPR\",name,j-2,j-2,m$TPR,\"declared group position\",\"TPR\",tag=tokens[j])}\n }\n invisible(NULL)\n}\n\n# Fixed finite inputs only; not the complete web input/budget validator.\nqnum<-function(v){if(is.null(v))return(NA_real_);if(is.logical(v))return(as.numeric(v));s<-as.character(v);if(grepl(\"/\",s,fixed=TRUE)){a<-strsplit(s,\"/\",fixed=TRUE)[[1]];return(as.numeric(a[1])/as.numeric(a[2]))};as.numeric(s)}\nrowsG<-function(raw){\n n<-length(raw);get<-function(r,k,default=NULL)if(is.null(r[[k]]))default else r[[k]]\n id<-vapply(raw,function(r)as.character(r$id),character(1));p<-vapply(raw,function(r)qnum(r$score),numeric(1));y<-vapply(raw,function(r)qnum(r$y),numeric(1));w<-vapply(raw,function(r)qnum(get(r,\"weight\",\"1\")),numeric(1));role<-vapply(raw,function(r)get(r,\"role\",\"evaluation\"),character(1));group<-vapply(raw,function(r)as.character(get(r,\"group\",NA_character_)),character(1))\n stopifnot(all(w>=0),all(is.na(p)|(p>=0&p<=1)),all(is.na(y)|y%in%c(0,1)),!anyDuplicated(id));list(id=id,p=p,y=y,w=w,role=role,group=group,eligible=!is.na(p)&!is.na(y)&w>0&role!=\"excluded\")\n}\nscopeG<-function(d,role=\"all\")if(role==\"all\")seq_along(d$id)else which(d$role==role)\nmetricsG<-function(d,ids,t=.5,cost=c(1,1)){\n use<-ids[d$eligible[ids]];p<-d$p[use];y<-d$y[use];w<-d$w[use];a<-if(is.character(t))rep(t==\"always-positive\",length(use))else p>=t\n TP<-sum(w[a&y==1]);FP<-sum(w[a&y==0]);FN<-sum(w[!a&y==1]);TN<-sum(w[!a&y==0]);P<-TP+FN;N<-FP+TN;W<-P+N;PP<-TP+FP;PN<-TN+FN;TPR<-ratio(TP,P);TNR<-ratio(TN,N);bs<-sum(w*(p-y)^2);tc<-FP*cost[1]+FN*cost[2]\n list(confusion=list(TP=TP,FP=FP,FN=FN,TN=TN),mass=W,positiveTargetMass=P,negativeTargetMass=N,predictedPositiveMass=PP,predictedNegativeMass=PN,prevalence=ratio(P,W),selectionRate=ratio(PP,W),accuracy=ratio(TP+TN,W),precision=ratio(TP,PP),negativePredictiveValue=ratio(TN,PN),TPR=TPR,FPR=ratio(FP,N),TNR=TNR,FNR=ratio(FN,P),F1=ratio(2*TP,2*TP+FP+FN),balancedAccuracy=if(is.na(TPR)||is.na(TNR))NA_real_ else(TPR+TNR)/2,Brier=ratio(bs,W),BrierSum=bs,totalCost=tc,meanCost=ratio(tc,W),bayesThreshold=ratio(cost[1],sum(cost)))\n}\ncurvesG<-function(d,ids){\n use<-ids[d$eligible[ids]];grid<-c(list(\"always-negative\"),as.list(sort(unique(d$p[use]),decreasing=TRUE)));points<-lapply(grid,function(t){m<-metricsG(d,ids,t);c(list(policy=t),m$confusion,m[c(\"TPR\",\"FPR\",\"precision\")],list(recall=m$TPR))});pos<-use[d$y[use]==1];neg<-use[d$y[use]==0];P<-sum(d$w[pos]);N<-sum(d$w[neg]);U<-0\n for(i in pos)U<-U+d$w[i]*sum(d$w[neg]*((d$p[i]>d$p[neg])+.5*(d$p[i]==d$p[neg])))\n AP<-trap<-lastR<-0;lastP<-1\n if(P&&length(grid)>1)for(j in 2:length(grid)){z<-points[[j]];AP<-AP+(z$recall-lastR)*z$precision;trap<-trap+(z$recall-lastR)*(z$precision+lastP)/2;lastR<-z$recall;lastP<-z$precision}\n list(points=points,ROC_AUC=ratio(U,P*N),averagePrecision=if(P)AP else NA_real_,PRTrapezoidWithInitialPrecisionOne=if(P)trap else NA_real_)\n}\nchooseG<-function(d,a,cost){\n role<-if(is.null(a$selectionRole))\"validation\"else a$selectionRole;er<-if(is.null(a$evaluationRole))\"test\"else a$evaluationRole;ids<-scopeG(d,role);use<-ids[d$eligible[ids]];stopifnot(length(use)>0);grid<-if(is.null(a$thresholds))c(list(\"always-negative\"),as.list(sort(unique(d$p[use]),decreasing=TRUE)))else lapply(a$thresholds,function(t)if(t%in%c(\"always-negative\",\"always-positive\"))t else qnum(t))\n candidates<-lapply(seq_along(grid),function(j){m<-metricsG(d,ids,grid[[j]],cost);feasible<-TRUE;if(!is.null(a$minTPR))feasible<-feasible&&!is.na(m$TPR)&&m$TPR>=qnum(a$minTPR);if(!is.null(a$maxFPR))feasible<-feasible&&!is.na(m$FPR)&&m$FPR<=qnum(a$maxFPR);list(index=j-1,policy=grid[[j]],metrics=m,feasible=feasible)})\n good<-which(vapply(candidates,function(c)c$feasible,logical(1)));best<-NA_integer_;if(length(good)){v<-vapply(candidates[good],function(c)c$metrics$meanCost,numeric(1));best<-good[which(v<=min(v)+1e-12)[1]]}\n list(selectedIndex=if(is.na(best))NA_integer_ else best-1,selectedPolicy=if(is.na(best))NULL else grid[[best]],selectedValidation=if(is.na(best))NULL else candidates[[best]]$metrics,candidates=candidates,evaluation=if(is.na(best)||er==\"none\")NULL else metricsG(d,scopeG(d,er),grid[[best]],cost))\n}\ncalibrateG<-function(d,ids,edges){\n use<-ids[d$eligible[ids]];W<-sum(d$w[use]);pi<-ratio(sum(d$w[use]*d$y[use]),W);bins<-list();ECE<-rel<-res<-correction<-0;assign<-findInterval(d$p[use],edges,rightmost.closed=TRUE,all.inside=TRUE)\n for(b in seq_len(length(edges)-1)){rr<-use[assign==b];w<-sum(d$w[rr]);mp<-ratio(sum(d$w[rr]*d$p[rr]),w);o<-ratio(sum(d$w[rr]*d$y[rr]),w);variance<-if(w)sum(d$w[rr]*(d$p[rr]-mp)^2)/w else NA_real_;covariance<-if(w)sum(d$w[rr]*(d$p[rr]-mp)*(d$y[rr]-o))/w else NA_real_;bc<-variance-2*covariance;gap<-mp-o;bins[[b]]<-list(index=b-1,mass=w,meanPrediction=mp,eventRate=o,scoreVariance=variance,scoreTargetCovariance=covariance,withinBinCorrection=bc,ids=d$id[rr])\n  if(w){s<-w/W;ECE<-ECE+s*abs(gap);rel<-rel+s*gap^2;res<-res+s*(o-pi)^2;correction<-correction+s*bc}\n };bs<-ratio(sum(d$w[use]*(d$p[use]-d$y[use])^2),W);unc<-pi*(1-pi);list(bins=bins,Brier=bs,ECE=if(W)ECE else NA_real_,uncertainty=unc,reliability=if(W)rel else NA_real_,resolution=if(W)res else NA_real_,withinBinCorrection=if(W)correction else NA_real_,BrierIdentityResidual=bs-(unc-res+rel+correction))\n}\ngroupsG<-function(d,ids,t,cost){\n lev<-unique(d$group[ids][!is.na(d$group[ids])]);groups<-lapply(lev,function(g)list(group=g,metrics=metricsG(d,ids[!is.na(d$group[ids])&d$group[ids]==g],t,cost)));overall<-metricsG(d,ids,t,cost);unknown<-metricsG(d,ids[is.na(d$group[ids])],t,cost);gaps<-list()\n for(k in c(\"prevalence\",\"selectionRate\",\"TPR\",\"FPR\",\"precision\",\"accuracy\",\"meanCost\")){use<-Filter(function(g)g$metrics$mass>0,groups);v<-vapply(use,function(g)g$metrics[[k]],numeric(1));gaps[[k]]<-if(length(use)<2||anyNA(v))NA_real_ else max(v)-min(v)}\n list(overall=overall,groups=groups,unknownGroup=unknown,gaps=gaps,partitionMassResidual=overall$mass-unknown$mass-sum(vapply(groups,function(g)g$metrics$mass,numeric(1))))\n}\nsvgFixed<-function(file,points,title,xlabel,ylabel,legend){\n finite<-points[points$y!=\"undefined\"&points$x!=\"undefined\",,drop=FALSE];x<-as.numeric(finite$x);y<-as.numeric(finite$y);xmin<-if(length(x))min(x)else 0;xmax<-if(length(x))max(x)else 1;ymin<-min(c(0,y));ymax<-max(c(0,y));if(xmin==xmax){xmin<-xmin-.5;xmax<-xmax+.5};if(ymin==ymax)ymax<-ymin+1;X<-function(v)85+(v-xmin)/(xmax-xmin)*480;Y<-function(v)278-(v-ymin)/(ymax-ymin)*175\n esc<-function(s){s<-gsub(\"&\",\"&amp;\",s,fixed=TRUE);s<-gsub(\"<\",\"&lt;\",s,fixed=TRUE);gsub(\">\",\"&gt;\",s,fixed=TRUE)};s<-'<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"620\" height=\"360\" viewBox=\"0 0 620 360\"><rect width=\"620\" height=\"360\" fill=\"white\"/><g font-family=\"Arial, sans-serif\" font-size=\"13\" fill=\"#17324d\">'\n lines<-strwrap(title,width=65);for(i in seq_along(lines))s<-paste0(s,'<text x=\"25\" y=\"',24+(i-1)*18,'\">',esc(lines[i]),'</text>');colors<-c(\"#176b9b\",\"#b85e18\",\"#437e4d\")\n for(i in seq_along(legend))s<-paste0(s,'<circle cx=\"',30+(i-1)*250,'\" cy=\"76\" r=\"4\" fill=\"',colors[(i-1)%%3+1],'\"/><text x=\"',42+(i-1)*250,'\" y=\"80\">',esc(legend[i]),'</text>')\n s<-paste0(s,'<path d=\"M85 98V278H575\" fill=\"none\" stroke=\"#52677d\"/><text text-anchor=\"middle\" x=\"325\" y=\"338\">',esc(xlabel),'</text><text text-anchor=\"middle\" transform=\"translate(21,190) rotate(-90)\">',esc(ylabel),'</text>')\n for(i in 0:4){xx<-xmin+(xmax-xmin)*i/4;yy<-ymin+(ymax-ymin)*i/4;s<-paste0(s,'<text text-anchor=\"middle\" x=\"',sprintf(\"%.9g\",X(xx)),'\" y=\"305\">',sprintf(\"%.4g\",xx),'</text><text text-anchor=\"end\" x=\"77\" y=\"',sprintf(\"%.9g\",Y(yy)+4),'\">',sprintf(\"%.4g\",yy),'</text>')}\n for(i in seq_len(nrow(finite)))s<-paste0(s,'<circle cx=\"',sprintf(\"%.9g\",X(x[i])),'\" cy=\"',sprintf(\"%.9g\",Y(y[i])),'\" r=\"3\" fill=\"',colors[as.integer(finite$series[i])%%3+1],'\"/>');writeLines(paste0(s,'</g></svg>'),file,useBytes=TRUE)\n}\nfixedRun<-function(){\n api<-FIXED$api;a<-FIXED$args;summary<-list();points<-list();xlabel<-\"Declared index\";ylabel<-\"Value\";legend<-\"Declared result\"\n metric<-function(name,v,unit=\"dimensionless\"){if(is.null(v))v<-NA_real_;summary[[length(summary)+1L]]<<-data.frame(metric=name,value=if(is.na(v))\"undefined\"else sprintf(\"%.9g\",v),exactValue=\"\",unit=unit,defined=as.integer(!is.na(v)),stringsAsFactors=FALSE)}\n pt<-function(i,x,y,id=\"\",series=0){points[[length(points)+1L]]<<-data.frame(series=series,index=i,xExact=\"\",x=if(is.na(x))\"undefined\"else sprintf(\"%.9g\",x),yExact=\"\",y=if(is.na(y))\"undefined\"else sprintf(\"%.9g\",y),id=as.character(id),stringsAsFactors=FALSE)}\n if(api==\"realdata\"){\n  native<-loadData()[[a$kind]];fit<-fitmodel(native);d<-list(id=native$id,p=fit$pred,y=native$y,w=rep(1,length(native$id)),role=native$role,group=native$group,eligible=native$eligible);scenarios<-list()\n  for(j in 1:3){name<-c(\"equal\",\"miss-five\",\"alarm-five\")[j];cst<-list(c(1,1),c(1,5),c(5,1))[[j]];sel<-chooseG(d,list(),cst);scenarios[[j]]<-list(name=name,selection=sel);metric(paste0(name,\"Threshold\"),sel$selectedPolicy);metric(paste0(name,\"TestCost\"),sel$evaluation$meanCost,\"hypothetical cost units/mass\")}\n  ids<-scopeG(d,\"test\");cv<-curvesG(d,ids);cal<-calibrateG(d,ids,seq(0,1,.2));metric(\"testAUC\",cv$ROC_AUC);metric(\"testAP\",cv$averagePrecision);metric(\"testBrier\",cal$Brier);metric(\"eligibleRows\",sum(d$eligible),\"rows\")\n  for(j in seq_along(ids)){i<-ids[j];pt(j-1,j,d$p[i],d$id[i],0);pt(j-1,j,d$y[i],d$id[i],1)}\n  full<-list(kind=a$kind,fit=fit,scenarios=scenarios,testCurves=cv,testCalibration=cal,rowsScored=d);xlabel<-\"Test row, native order\";ylabel<-\"Y or probability\";legend<-c(\"Training-fitted probability\",\"Observed Y\")\n }else{\n  d<-rowsG(a$rows);role<-if(is.null(a$role))\"all\"else a$role;ids<-scopeG(d,role);cost<-if(is.null(a$costs))c(1,1)else c(qnum(a$costs$falsePositive),qnum(a$costs$falseNegative));t<-if(is.null(a$threshold)).5 else if(a$threshold%in%c(\"always-positive\",\"always-negative\"))a$threshold else qnum(a$threshold)\n  if(api==\"metrics\"){\n   full<-metricsG(d,ids,t,cost);for(k in c(\"mass\",\"accuracy\",\"precision\",\"TPR\",\"FPR\",\"F1\",\"Brier\",\"meanCost\"))metric(k,full[[k]],if(k==\"mass\")\"mass\"else if(k==\"meanCost\")\"hypothetical cost units/mass\"else\"dimensionless\");metric(\"BayesThreshold\",full$bayesThreshold)\n   for(i in 1:4)pt(i-1,i-1,full$confusion[[i]],names(full$confusion)[i]);xlabel<-\"TP / FP / FN / TN positions\";ylabel<-\"Analytical mass\"\n  }else if(api==\"curves\"){\n   full<-curvesG(d,ids);for(k in c(\"ROC_AUC\",\"averagePrecision\",\"PRTrapezoidWithInitialPrecisionOne\"))metric(k,full[[k]])\n   for(j in seq_along(full$points)){p<-full$points[[j]];pt(j-1,p$FPR,p$TPR,if(is.character(p$policy))p$policy else sprintf(\"%.17g\",p$policy))};xlabel<-\"False positive rate\";ylabel<-\"True positive rate\";legend<-\"Observed ROC operating points\"\n  }else if(api==\"choose\"){\n   full<-chooseG(d,a,cost);metric(\"selectedIndex\",full$selectedIndex,\"candidate index\");metric(\"minimumCost\",if(is.null(full$selectedValidation))NULL else full$selectedValidation$meanCost,\"hypothetical cost units/mass\");metric(\"feasible\",as.integer(!is.na(full$selectedIndex)),\"indicator\")\n   for(c in full$candidates)pt(c$index,c$index,c$metrics$meanCost,if(is.character(c$policy))c$policy else sprintf(\"%.17g\",c$policy));xlabel<-\"Validation candidate\";ylabel<-\"Assumed cost / mass\";legend<-\"Validation candidate costs\"\n  }else if(api==\"calibrate\"){\n   edges<-if(is.null(a$binEdges))seq(0,1,.2)else vapply(a$binEdges,qnum,numeric(1));full<-calibrateG(d,ids,edges);for(k in c(\"ECE\",\"Brier\",\"uncertainty\",\"resolution\",\"reliability\",\"withinBinCorrection\",\"BrierIdentityResidual\"))metric(k,full[[k]])\n   for(b in full$bins)pt(b$index,b$meanPrediction,b$eventRate,paste0(\"bin:\",b$index));xlabel<-\"Bin mean forecast\";ylabel<-\"Bin event rate\";legend<-\"Binary-event reliability\"\n  }else if(api==\"groups\"){\n   full<-groupsG(d,ids,t,cost);metric(\"overallTPR\",full$overall$TPR);metric(\"TPRGap\",full$gaps$TPR);metric(\"precisionGap\",full$gaps$precision);metric(\"unknownMass\",full$unknownGroup$mass,\"mass\");metric(\"partitionResidual\",full$partitionMassResidual,\"mass\")\n   for(j in seq_along(full$groups))pt(j-1,j-1,full$groups[[j]]$metrics$TPR,full$groups[[j]]$group);xlabel<-\"Declared group position\";ylabel<-\"True positive rate\";legend<-\"Known-group TPR\"\n  }else stop(\"unknown declared fixed API\")\n }\n sm<-do.call(rbind,summary);pp<-do.call(rbind,points);write.csv(sm,file.path(outDir,\"summary.csv\"),row.names=FALSE,na=\"\");write.csv(pp,file.path(outDir,\"plot-points.csv\"),row.names=FALSE,na=\"\");svgFixed(file.path(outDir,\"plot.svg\"),pp,FIXED$title,xlabel,ylabel,legend);dput(list(api=api,variant=FIXED$variant,input=FIXED$args,arithmetic=\"Base-R binary64 fixed example; not an exact rational general validator\",result=full),file=file.path(outDir,\"full.txt\"));cat(\"PASS\",api,FIXED$variant,\"summary\",nrow(sm),\"points\",nrow(pp),\"\\n\")\n}\n\nFIXED<-list(api=\"metrics\",variant=\"weighted\",args=list(rows=list(list(id=\"a\",score=\".9\",y=1,group=\"A\"),list(id=\"b\",score=\".8\",y=1,group=\"A\"),list(id=\"c\",score=\".8\",y=0,group=\"A\",weight=\"2\"),list(id=\"d\",score=\".6\",y=0,group=\"B\"),list(id=\"e\",score=\".4\",y=1,group=\"B\"),list(id=\"f\",score=\".1\",y=0,group=\"B\")),threshold=\".8\"),title=\"Double only the tied negative card mass\")\nfixedRun()\n",
        "codeText": "# ML14 standalone public counterpart, base R only.\n# Inputs are only the three factual CSVs; derived columns/previous model answers unused.\n# Binary64 arithmetic, not arbitrary-precision Fraction. At numerical cost ties\n# within 1e-12 retain the earliest candidate. Exact claims belong to Python/web.\n# SHA256 infrastructure below is reused verbatim from the previous public study.\nargs<-commandArgs(trailingOnly=TRUE);filearg<-grep(\"^--file=\",commandArgs(),value=TRUE)\nhere<-if(dir.exists(\"ml14-sources\"))getwd()else if(length(filearg))dirname(normalizePath(sub(\"^--file=\",\"\",filearg[1])))else getwd()\noption<-function(key,default){i<-match(key,args);if(is.na(i))default else args[i+1]}\nsourceDir<-option(\"--source\",file.path(here,\"ml14-sources\"));outDir<-option(\"--out\",file.path(getwd(),\"ml14-r-results\"));dir.create(outDir,recursive=TRUE,showWarnings=FALSE)\nnum<-function(x){x[x%in%c(\"\",\".\")]<-NA_character_;as.numeric(x)}\nfmt<-function(x)ifelse(is.na(x),\"\",sprintf(\"%.17g\",x))\nratio<-function(a,b)if(b==0)NA_real_ else a/b\nreadnative<-function(name)read.csv(file.path(sourceDir,name),check.names=FALSE,colClasses=\"character\",na.strings=character(),stringsAsFactors=FALSE)\n# Vectorized SHA256 for the short ASCII keys used in this study.\n# Unsigned words use exact integer-valued doubles; bit operations use safe\n# 16-bit halves, avoiding R's reserved signed-INT_MIN/NA representation.\nMOD<-2^32\nxor32<-function(a,b) as.double(bitwXor(as.integer(floor(a/65536)),as.integer(floor(b/65536))))*65536+as.double(bitwXor(as.integer(a%%65536),as.integer(b%%65536)))\nand32<-function(a,b) as.double(bitwAnd(as.integer(floor(a/65536)),as.integer(floor(b/65536))))*65536+as.double(bitwAnd(as.integer(a%%65536),as.integer(b%%65536)))\nrot<-function(x,n) floor(x/2^n)+(x%%2^n)*2^(32-n)\nxor3<-function(a,b,c) xor32(xor32(a,b),c)\nK<-c(0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5,0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967,0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070,0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3,0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2)\nsha256<-function(strings) {\n n<-length(strings);bytes<-matrix(0,n,64)\n for(i in seq_len(n)) {v<-utf8ToInt(strings[i]);stopifnot(length(v)<56,all(v<128));if(length(v)) bytes[i,seq_along(v)]<-v;bytes[i,length(v)+1]<-128;bits<-length(v)*8;bytes[i,61:64]<-c(floor(bits/2^24)%%256,floor(bits/2^16)%%256,floor(bits/256)%%256,bits%%256)}\n w<-matrix(0,n,64)\n for(j in 1:16) {b<-4*(j-1)+1;w[,j]<-bytes[,b]*2^24+bytes[,b+1]*2^16+bytes[,b+2]*256+bytes[,b+3]}\n for(j in 17:64) {s0<-xor3(rot(w[,j-15],7),rot(w[,j-15],18),floor(w[,j-15]/8));s1<-xor3(rot(w[,j-2],17),rot(w[,j-2],19),floor(w[,j-2]/1024));w[,j]<-(w[,j-16]+s0+w[,j-7]+s1)%%MOD}\n init<-c(0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19)\n state<-lapply(init,function(v) rep(v,n));a<-state[[1]];b<-state[[2]];c<-state[[3]];d<-state[[4]];e<-state[[5]];f<-state[[6]];g<-state[[7]];h<-state[[8]]\n for(j in 1:64) {S1<-xor3(rot(e,6),rot(e,11),rot(e,25));ch<-xor32(and32(e,f),and32(MOD-1-e,g));t1<-(h+S1+ch+K[j]+w[,j])%%MOD;S0<-xor3(rot(a,2),rot(a,13),rot(a,22));maj<-xor3(and32(a,b),and32(a,c),and32(b,c));t2<-(S0+maj)%%MOD;h<-g;g<-f;f<-e;e<-(d+t1)%%MOD;d<-c;c<-b;b<-a;a<-(t1+t2)%%MOD}\n end<-list(a,b,c,d,e,f,g,h);hex<-lapply(1:8,function(j){v<-(end[[j]]+init[j])%%MOD;paste0(sprintf(\"%04x\",as.integer(floor(v/65536))),sprintf(\"%04x\",as.integer(v%%65536)))})\n do.call(paste0,hex)\n}\nstopifnot(identical(sha256(c(\"abc\",\"\")),c(\"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad\",\"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855\")))\n\nloadData<-function(){\n wb<-readnative(\"actual64-country-four-indicators-original-2024.csv\");codes<-c(\"NY.GDP.PCAP.KD\",\"NY.GDP.MKTP.KD.ZG\",\"FP.CPI.TOTL.ZG\",\"SP.DYN.LE00.IN\");iso<-sort(unique(wb$countryISO3));stopifnot(nrow(wb)==64,length(iso)==16)\n tokens<-t(vapply(iso,function(s)wb$originalValueToken[match(paste(s,codes),paste(wb$countryISO3,wb$indicatorID))],character(4)));vals<-matrix(num(as.vector(tokens)),nrow=nrow(tokens))\n country<-list(id=paste0(iso,\":2024\"),sourceRow=1:16,originalID=iso,x=vals[,1:3,drop=FALSE],rawX=tokens[,1:3,drop=FALSE],nativeTarget=tokens[,4],y=as.integer(vals[,4]>=80),group=ifelse(is.na(vals[,1]),NA_character_,as.character(as.integer(vals[,1]>=25000))),lineage=vapply(iso,function(s)paste(wb$sourceRow[match(paste(s,codes),paste(wb$countryISO3,wb$indicatorID))],collapse=\";\"),character(1)),cat=integer(),units=c(\"constant2015USD/person\",\"annualPercent\",\"annualPercent\"))\n nls<-readnative(\"actual3613-NLS-original52-fields-groups-roles.csv\");raw<-cbind(nls$ed76,nls$age76,nls$nearc4)\n person<-list(id=paste0(\"person:\",nls$sourceRow),sourceRow=as.integer(nls$sourceRow),originalID=nls$id,x=matrix(num(as.vector(raw)),nrow=nrow(raw)),rawX=raw,nativeTarget=nls$wage76,y=as.integer(num(nls$wage76)>=500),group=ifelse(nls$black%in%c(\"\",\".\"),NA_character_,nls$black),lineage=nls$sourceRow,cat=2L,units=c(\"years\",\"years\",\"nativeCategory\"))\n ch<-readnative(\"actual3150-churn-original14-fields-groups-roles.csv\");raw<-cbind(ch[[\"Call  Failure\"]],ch$Complains,ch[[\"Subscription  Length\"]],ch[[\"Seconds of Use\"]])\n company<-list(id=paste0(\"customer:\",ch$sourceRow),sourceRow=as.integer(ch$sourceRow),originalID=rep(\"\",nrow(ch)),x=matrix(num(as.vector(raw)),nrow=nrow(raw)),rawX=raw,nativeTarget=ch$Churn,y=as.integer(ch$Churn),group=ifelse(ch[[\"Tariff Plan\"]]%in%c(\"\",\".\"),NA_character_,ch[[\"Tariff Plan\"]]),lineage=ch$sourceRow,cat=1L,units=c(\"count\",\"nativeCategory\",\"months\",\"seconds\"))\n stopifnot(nrow(nls)==3613,nrow(ch)==3150,identical(as.integer(ch$sourceRow[ch[[\"Charge  Amount\"]]==\"10\"]),c(474L,2174L,2274L,2374L,2674L,2924L,2974L)))\n result<-list(country=country,person=person,company=company)\n for(k in names(result)){d<-result[[k]];n<-length(d$id);d$eligible<-!is.na(d$y)&rowSums(is.na(d$x))==0;hash<-sha256(paste0(\"ML14-role|\",k,\"|\",d$id));rank<-integer(n);rank[order(hash,seq_len(n))]<-seq_len(n)-1L;d$plannedRole<-ifelse(rank%%5==0,\"test\",ifelse(rank%%5==1,\"validation\",\"train\"));d$role<-ifelse(d$eligible,d$plannedRole,\"excluded\");result[[k]]<-d}\n stopifnot(sum(result$person$eligible)==3017);result\n}\nfitmodel<-function(d){\n ids<-which(d$role==\"train\");p<-ncol(d$x);m<-vapply(seq_len(p),function(j)if((j-1)%in%d$cat)NA_real_ else median(d$x[ids,j]),numeric(1));z<-d$x\n for(j in seq_len(p))if(!((j-1)%in%d$cat))z[,j]<-as.numeric(z[,j]>m[j])\n keys<-apply(z,1,function(v)paste(fmt(v),collapse=\"|\"));lev<-unique(keys[ids]);mass<-vapply(lev,function(k)sum(keys[ids]==k),integer(1));positive<-vapply(lev,function(k)sum(d$y[ids][keys[ids]==k]),integer(1));prob<-(positive+1)/(mass+2);fallback<-(sum(d$y[ids])+1)/(length(ids)+2);pred<-prob[match(keys,lev)];unseen<-is.na(pred);pred[unseen]<-fallback;pred[!d$eligible]<-NA_real_;unseen[!d$eligible]<-NA\n list(ids=ids,medians=m,z=z,keys=keys,lev=lev,mass=mass,positive=positive,prob=prob,fallback=fallback,pred=pred,unseen=unseen)\n}\nmeasure<-function(d,p,ids,t=.5,cost=c(1,1)){\n use<-ids[d$eligible[ids]&!is.na(p[ids])];y<-d$y[use];a<-if(is.character(t))rep(t==\"always-positive\",length(use))else p[use]>=t\n TP<-sum(a&y==1);FP<-sum(a&y==0);FN<-sum(!a&y==1);TN<-sum(!a&y==0);P<-TP+FN;N<-FP+TN;W<-P+N;PP<-TP+FP;PN<-TN+FN;TPR<-ratio(TP,P);TNR<-ratio(TN,N);bs<-sum((p[use]-y)^2);tc<-FP*cost[1]+FN*cost[2]\n list(TP=TP,FP=FP,FN=FN,TN=TN,mass=W,positiveTargetMass=P,negativeTargetMass=N,predictedPositiveMass=PP,predictedNegativeMass=PN,prevalence=ratio(P,W),selectionRate=ratio(PP,W),accuracy=ratio(TP+TN,W),precision=ratio(TP,PP),negativePredictiveValue=ratio(TN,PN),TPR=TPR,FPR=ratio(FP,N),TNR=TNR,FNR=ratio(FN,P),F1=ratio(2*TP,2*TP+FP+FN),balancedAccuracy=if(is.na(TPR)||is.na(TNR))NA_real_ else(TPR+TNR)/2,Brier=ratio(bs,W),BrierSum=bs,totalCost=tc,meanCost=ratio(tc,W))\n}\ncurves<-function(d,p,ids){\n use<-ids[d$eligible[ids]&!is.na(p[ids])];scores<-sort(unique(p[use]),decreasing=TRUE);policies<-c(list(\"always-negative\"),as.list(scores));points<-lapply(policies,function(t){m<-measure(d,p,ids,t);c(list(policy=t),m[c(\"TP\",\"FP\",\"FN\",\"TN\",\"TPR\",\"FPR\",\"precision\")],list(recall=m$TPR))})\n pos<-use[d$y[use]==1];neg<-use[d$y[use]==0];U<-0;for(i in pos)U<-U+sum(p[i]>p[neg])+.5*sum(p[i]==p[neg])\n AP<-0;trap<-0;lastR<-0;lastP<-1\n if(length(pos)&&length(scores))for(j in seq_along(scores)){z<-points[[j+1]];AP<-AP+(z$recall-lastR)*z$precision;trap<-trap+(z$recall-lastR)*(z$precision+lastP)/2;lastR<-z$recall;lastP<-z$precision}\n list(points=points,ROC_AUC=ratio(U,length(pos)*length(neg)),averagePrecision=if(length(pos))AP else NA_real_,PRTrapezoidWithInitialPrecisionOne=if(length(pos))trap else NA_real_)\n}\ncalibrate<-function(d,p,ids){\n use<-ids[d$eligible[ids]&!is.na(p[ids])];W<-length(use);pi<-if(W)mean(d$y[use])else NA_real_;bins<-list();ECE<-rel<-res<-correction<-0\n whichbin<-findInterval(p[use],seq(0,1,.2),rightmost.closed=TRUE,all.inside=TRUE)\n for(b in 1:5){rr<-use[whichbin==b];w<-length(rr);mp<-if(w)mean(p[rr])else NA_real_;o<-if(w)mean(d$y[rr])else NA_real_;variance<-if(w)mean((p[rr]-mp)^2)else NA_real_;covariance<-if(w)mean((p[rr]-mp)*(d$y[rr]-o))else NA_real_;bc<-variance-2*covariance;gap<-mp-o\n  bins[[b]]<-list(mass=w,meanPrediction=mp,eventRate=o,gap=gap,absoluteGap=abs(gap),scoreVariance=variance,scoreTargetCovariance=covariance,withinBinCorrection=bc,rows=w,ids=d$id[rr])\n  if(w){share<-w/W;ECE<-ECE+share*abs(gap);rel<-rel+share*gap^2;res<-res+share*(o-pi)^2;correction<-correction+share*bc}\n };bs<-if(W)mean((p[use]-d$y[use])^2)else NA_real_;unc<-pi*(1-pi)\n list(bins=bins,ECE=if(W)ECE else NA_real_,Brier=bs,reliability=if(W)rel else NA_real_,resolution=if(W)res else NA_real_,uncertainty=unc,withinBinCorrection=if(W)correction else NA_real_,BrierIdentityResidual=bs-(unc-res+rel+correction))\n}\ncounts<-c(\"mass\",\"positiveTargetMass\",\"negativeTargetMass\",\"predictedPositiveMass\",\"predictedNegativeMass\");rates<-c(\"prevalence\",\"selectionRate\",\"accuracy\",\"precision\",\"negativePredictiveValue\",\"TPR\",\"FPR\",\"TNR\",\"FNR\",\"F1\",\"balancedAccuracy\",\"Brier\",\"BrierSum\",\"totalCost\",\"meanCost\")\ntables<-setNames(lapply(1:10,function(i)list()),c(\"predictions\",\"lineage\",\"fit-medians\",\"fit-cells\",\"validation-candidates\",\"test-metrics\",\"test-curves\",\"calibration-bins\",\"group-metrics\",\"chart-points\"))\nadd<-function(name,row)tables[[name]][[length(tables[[name]])+1L]]<<-row\nscalars<-function(m,keys){out<-list();for(k in keys){out[[paste0(k,\"Exact\")]]<-\"\";out[[paste0(k,\"Approx\")]]<-fmt(m[[k]])};out}\ntagrow<-function(kind,...)c(list(kind=kind),list(...))\npoint<-function(kind,chart,series,index,x,y,xunit=\"dimensionless\",yunit=\"dimensionless\",role=\"test\",tag=\"\"){add(\"chart-points\",tagrow(kind,chart=chart,series=series,index=index,xExact=\"\",xApprox=fmt(x),yExact=\"\",yApprox=fmt(y),xUnit=xunit,yUnit=yunit,role=role,tag=tag))}\nstudy<-function(kind,d){\n f<-fitmodel(d);n<-length(d$id);train<-which(d$role==\"train\");validation<-which(d$role==\"validation\");test<-which(d$role==\"test\");p<-f$pred;cv<-curves(d,p,test);cal<-calibrate(d,p,test)\n for(i in seq_len(n)){\n  reason<-if(d$eligible[i])\"\"else\"required-X-or-Y-missing\";transformed<-if(d$eligible[i])paste(fmt(f$z[i,]),collapse=\"|\")else\"\"\n  add(\"predictions\",tagrow(kind,id=d$id[i],sourceRow=d$sourceRow[i],originalID=d$originalID[i],plannedRole=d$plannedRole[i],role=d$role[i],group=ifelse(is.na(d$group[i]),\"\",d$group[i]),eligible=as.integer(d$eligible[i]),targetExact=fmt(d$y[i]),probabilityExact=\"\",probabilityApprox=fmt(p[i]),unseenCell=ifelse(is.na(f$unseen[i]),\"\",as.character(as.integer(f$unseen[i]))),transformedX=transformed,reason=reason))\n  raw<-d$rawX[i,];raw[raw%in%c(\"\",\".\")]<-\"\";nativeY<-d$nativeTarget[i];if(nativeY%in%c(\"\",\".\"))nativeY<-\"\"\n  add(\"lineage\",tagrow(kind,id=d$id[i],sourceRow=d$sourceRow[i],originalID=d$originalID[i],nativeSourceRows=d$lineage[i],rawX=paste(raw,collapse=\"|\"),nativeTarget=nativeY,derivedTarget=fmt(d$y[i]),nativeGroup=ifelse(is.na(d$group[i]),\"\",d$group[i]),plannedRole=d$plannedRole[i],role=d$role[i],eligible=as.integer(d$eligible[i]),analyticalMass=\"1\",reason=reason))\n }\n for(j in seq_len(ncol(d$x)))add(\"fit-medians\",tagrow(kind,feature=j-1,categorical=as.integer((j-1)%in%d$cat),fitRows=length(train),medianExact=\"\",medianApprox=fmt(f$medians[j]),unit=d$units[j]))\n for(j in seq_along(f$lev))add(\"fit-cells\",tagrow(kind,cell=f$lev[j],trainingRows=f$mass[j],positiveRows=f$positive[j],probabilityExact=\"\",probabilityApprox=fmt(f$prob[j]),fallbackExact=\"\",fallbackApprox=fmt(f$fallback)))\n for(j in seq_along(cv$points)){\n  z<-cv$points[[j]];t<-z$policy;add(\"test-curves\",c(tagrow(kind,point=j-1,policy=if(is.character(t))t else\"threshold\",thresholdExact=\"\",thresholdApprox=if(is.character(t))\"\"else fmt(t)),scalars(z,c(\"TP\",\"FP\",\"FN\",\"TN\",\"TPR\",\"FPR\",\"precision\",\"recall\"))))\n  point(kind,\"roc\",\"ROC\",j-1,z$FPR,z$TPR);point(kind,\"pr\",\"PR-observed\",j-1,z$recall,z$precision)\n }\n for(b in 1:5){z<-cal$bins[[b]];add(\"calibration-bins\",c(tagrow(kind,bin=b-1,leftExact=c(\"0\",\"1/5\",\"2/5\",\"3/5\",\"4/5\")[b],rightExact=c(\"1/5\",\"2/5\",\"3/5\",\"4/5\",\"1\")[b],rightClosed=as.integer(b==5),rows=z$rows,ids=paste(z$ids,collapse=\";\")),scalars(z,c(\"mass\",\"meanPrediction\",\"eventRate\",\"gap\",\"absoluteGap\",\"scoreVariance\",\"scoreTargetCovariance\",\"withinBinCorrection\"))));point(kind,\"reliability\",\"Binary event rate\",b-1,z$meanPrediction,z$eventRate,tag=paste0(\"rows=\",z$rows))}\n for(j in seq_along(test)){i<-test[j];point(kind,\"test-scores\",\"Training-fitted probability\",j-1,j,p[i],\"test-row position\",\"probability\",tag=d$id[i]);point(kind,\"test-scores\",\"Observed Y\",j-1,j,d$y[i],\"test-row position\",\"binary target\",tag=d$id[i])}\n scenarioNames<-c(\"equal\",\"miss-five\",\"alarm-five\");costs<-list(c(1,1),c(1,5),c(5,1))\n for(s in 1:3){name<-scenarioNames[s];cost<-costs[[s]];grid<-c(list(\"always-negative\"),as.list(sort(unique(p[validation]),decreasing=TRUE)));candidates<-lapply(grid,function(t)measure(d,p,validation,t,cost));values<-vapply(candidates,function(m)m$meanCost,numeric(1));best<-which(values<=min(values)+1e-12)[1];chosen<-grid[[best]];ev<-measure(d,p,test,chosen,cost)\n  for(j in seq_along(grid)){t<-grid[[j]];m<-candidates[[j]];cell<-setNames(lapply(c(\"TP\",\"FP\",\"FN\",\"TN\"),function(k)fmt(m[[k]])),paste0(c(\"TP\",\"FP\",\"FN\",\"TN\"),\"Exact\"));add(\"validation-candidates\",c(tagrow(kind,scenario=name,candidate=j-1,selected=as.integer(j==best),policy=if(is.character(t))t else\"threshold\",thresholdExact=\"\",thresholdApprox=if(is.character(t))\"\"else fmt(t),feasible=1,reasons=\"\"),cell,scalars(m,c(counts,\"TPR\",\"FPR\",\"precision\",\"meanCost\",\"totalCost\"))));point(kind,\"validation-cost\",name,j-1,j-1,m$meanCost,\"candidate index\",\"hypothetical cost units/mass\",\"validation\",if(is.character(t))t else fmt(t))}\n  m<-c(ev,cv[c(\"ROC_AUC\",\"averagePrecision\",\"PRTrapezoidWithInitialPrecisionOne\")],cal[c(\"ECE\",\"reliability\",\"resolution\",\"uncertainty\",\"withinBinCorrection\",\"BrierIdentityResidual\")])\n  for(k in c(\"TP\",\"FP\",\"FN\",\"TN\",counts,rates,\"ROC_AUC\",\"averagePrecision\",\"PRTrapezoidWithInitialPrecisionOne\",\"ECE\",\"reliability\",\"resolution\",\"uncertainty\",\"withinBinCorrection\",\"BrierIdentityResidual\")){\n   unit<-if(k%in%c(\"TP\",\"FP\",\"FN\",\"TN\",counts))\"rows\"else if(k==\"totalCost\")\"hypothetical cost units\"else if(k==\"meanCost\")\"hypothetical cost units/mass\"else if(k==\"BrierSum\")\"sum squared-probability loss\"else\"dimensionless\"\n   add(\"test-metrics\",tagrow(kind,scenario=name,metric=k,valueExact=\"\",valueApprox=fmt(m[[k]]),unit=unit))\n  }\n  lev<-unique(d$group[test][!is.na(d$group[test])]);sets<-c(list(test),lapply(lev,function(g)test[!is.na(d$group[test])&d$group[test]==g]),list(test[is.na(d$group[test])]))\n  types<-c(\"overall\",rep(\"known\",length(lev)),\"unknown\");tokens<-c(\"all\",lev,\"\")\n  for(j in seq_along(sets)){ids<-sets[[j]];m<-measure(d,p,ids,chosen,cost);cell<-setNames(lapply(c(\"TP\",\"FP\",\"FN\",\"TN\"),function(k)fmt(m[[k]])),paste0(c(\"TP\",\"FP\",\"FN\",\"TN\"),\"Exact\"));add(\"group-metrics\",c(tagrow(kind,scenario=name,groupType=types[j],groupToken=tokens[j],retainedRows=length(ids)),cell,scalars(m,c(counts,rates))));if(types[j]==\"known\")point(kind,\"group-TPR\",name,j-2,j-2,m$TPR,\"declared group position\",\"TPR\",tag=tokens[j])}\n }\n invisible(NULL)\n}\n\n# Fixed finite inputs only; not the complete web input/budget validator.\nqnum<-function(v){if(is.null(v))return(NA_real_);if(is.logical(v))return(as.numeric(v));s<-as.character(v);if(grepl(\"/\",s,fixed=TRUE)){a<-strsplit(s,\"/\",fixed=TRUE)[[1]];return(as.numeric(a[1])/as.numeric(a[2]))};as.numeric(s)}\nrowsG<-function(raw){\n n<-length(raw);get<-function(r,k,default=NULL)if(is.null(r[[k]]))default else r[[k]]\n id<-vapply(raw,function(r)as.character(r$id),character(1));p<-vapply(raw,function(r)qnum(r$score),numeric(1));y<-vapply(raw,function(r)qnum(r$y),numeric(1));w<-vapply(raw,function(r)qnum(get(r,\"weight\",\"1\")),numeric(1));role<-vapply(raw,function(r)get(r,\"role\",\"evaluation\"),character(1));group<-vapply(raw,function(r)as.character(get(r,\"group\",NA_character_)),character(1))\n stopifnot(all(w>=0),all(is.na(p)|(p>=0&p<=1)),all(is.na(y)|y%in%c(0,1)),!anyDuplicated(id));list(id=id,p=p,y=y,w=w,role=role,group=group,eligible=!is.na(p)&!is.na(y)&w>0&role!=\"excluded\")\n}\nscopeG<-function(d,role=\"all\")if(role==\"all\")seq_along(d$id)else which(d$role==role)\nmetricsG<-function(d,ids,t=.5,cost=c(1,1)){\n use<-ids[d$eligible[ids]];p<-d$p[use];y<-d$y[use];w<-d$w[use];a<-if(is.character(t))rep(t==\"always-positive\",length(use))else p>=t\n TP<-sum(w[a&y==1]);FP<-sum(w[a&y==0]);FN<-sum(w[!a&y==1]);TN<-sum(w[!a&y==0]);P<-TP+FN;N<-FP+TN;W<-P+N;PP<-TP+FP;PN<-TN+FN;TPR<-ratio(TP,P);TNR<-ratio(TN,N);bs<-sum(w*(p-y)^2);tc<-FP*cost[1]+FN*cost[2]\n list(confusion=list(TP=TP,FP=FP,FN=FN,TN=TN),mass=W,positiveTargetMass=P,negativeTargetMass=N,predictedPositiveMass=PP,predictedNegativeMass=PN,prevalence=ratio(P,W),selectionRate=ratio(PP,W),accuracy=ratio(TP+TN,W),precision=ratio(TP,PP),negativePredictiveValue=ratio(TN,PN),TPR=TPR,FPR=ratio(FP,N),TNR=TNR,FNR=ratio(FN,P),F1=ratio(2*TP,2*TP+FP+FN),balancedAccuracy=if(is.na(TPR)||is.na(TNR))NA_real_ else(TPR+TNR)/2,Brier=ratio(bs,W),BrierSum=bs,totalCost=tc,meanCost=ratio(tc,W),bayesThreshold=ratio(cost[1],sum(cost)))\n}\ncurvesG<-function(d,ids){\n use<-ids[d$eligible[ids]];grid<-c(list(\"always-negative\"),as.list(sort(unique(d$p[use]),decreasing=TRUE)));points<-lapply(grid,function(t){m<-metricsG(d,ids,t);c(list(policy=t),m$confusion,m[c(\"TPR\",\"FPR\",\"precision\")],list(recall=m$TPR))});pos<-use[d$y[use]==1];neg<-use[d$y[use]==0];P<-sum(d$w[pos]);N<-sum(d$w[neg]);U<-0\n for(i in pos)U<-U+d$w[i]*sum(d$w[neg]*((d$p[i]>d$p[neg])+.5*(d$p[i]==d$p[neg])))\n AP<-trap<-lastR<-0;lastP<-1\n if(P&&length(grid)>1)for(j in 2:length(grid)){z<-points[[j]];AP<-AP+(z$recall-lastR)*z$precision;trap<-trap+(z$recall-lastR)*(z$precision+lastP)/2;lastR<-z$recall;lastP<-z$precision}\n list(points=points,ROC_AUC=ratio(U,P*N),averagePrecision=if(P)AP else NA_real_,PRTrapezoidWithInitialPrecisionOne=if(P)trap else NA_real_)\n}\nchooseG<-function(d,a,cost){\n role<-if(is.null(a$selectionRole))\"validation\"else a$selectionRole;er<-if(is.null(a$evaluationRole))\"test\"else a$evaluationRole;ids<-scopeG(d,role);use<-ids[d$eligible[ids]];stopifnot(length(use)>0);grid<-if(is.null(a$thresholds))c(list(\"always-negative\"),as.list(sort(unique(d$p[use]),decreasing=TRUE)))else lapply(a$thresholds,function(t)if(t%in%c(\"always-negative\",\"always-positive\"))t else qnum(t))\n candidates<-lapply(seq_along(grid),function(j){m<-metricsG(d,ids,grid[[j]],cost);feasible<-TRUE;if(!is.null(a$minTPR))feasible<-feasible&&!is.na(m$TPR)&&m$TPR>=qnum(a$minTPR);if(!is.null(a$maxFPR))feasible<-feasible&&!is.na(m$FPR)&&m$FPR<=qnum(a$maxFPR);list(index=j-1,policy=grid[[j]],metrics=m,feasible=feasible)})\n good<-which(vapply(candidates,function(c)c$feasible,logical(1)));best<-NA_integer_;if(length(good)){v<-vapply(candidates[good],function(c)c$metrics$meanCost,numeric(1));best<-good[which(v<=min(v)+1e-12)[1]]}\n list(selectedIndex=if(is.na(best))NA_integer_ else best-1,selectedPolicy=if(is.na(best))NULL else grid[[best]],selectedValidation=if(is.na(best))NULL else candidates[[best]]$metrics,candidates=candidates,evaluation=if(is.na(best)||er==\"none\")NULL else metricsG(d,scopeG(d,er),grid[[best]],cost))\n}\ncalibrateG<-function(d,ids,edges){\n use<-ids[d$eligible[ids]];W<-sum(d$w[use]);pi<-ratio(sum(d$w[use]*d$y[use]),W);bins<-list();ECE<-rel<-res<-correction<-0;assign<-findInterval(d$p[use],edges,rightmost.closed=TRUE,all.inside=TRUE)\n for(b in seq_len(length(edges)-1)){rr<-use[assign==b];w<-sum(d$w[rr]);mp<-ratio(sum(d$w[rr]*d$p[rr]),w);o<-ratio(sum(d$w[rr]*d$y[rr]),w);variance<-if(w)sum(d$w[rr]*(d$p[rr]-mp)^2)/w else NA_real_;covariance<-if(w)sum(d$w[rr]*(d$p[rr]-mp)*(d$y[rr]-o))/w else NA_real_;bc<-variance-2*covariance;gap<-mp-o;bins[[b]]<-list(index=b-1,mass=w,meanPrediction=mp,eventRate=o,scoreVariance=variance,scoreTargetCovariance=covariance,withinBinCorrection=bc,ids=d$id[rr])\n  if(w){s<-w/W;ECE<-ECE+s*abs(gap);rel<-rel+s*gap^2;res<-res+s*(o-pi)^2;correction<-correction+s*bc}\n };bs<-ratio(sum(d$w[use]*(d$p[use]-d$y[use])^2),W);unc<-pi*(1-pi);list(bins=bins,Brier=bs,ECE=if(W)ECE else NA_real_,uncertainty=unc,reliability=if(W)rel else NA_real_,resolution=if(W)res else NA_real_,withinBinCorrection=if(W)correction else NA_real_,BrierIdentityResidual=bs-(unc-res+rel+correction))\n}\ngroupsG<-function(d,ids,t,cost){\n lev<-unique(d$group[ids][!is.na(d$group[ids])]);groups<-lapply(lev,function(g)list(group=g,metrics=metricsG(d,ids[!is.na(d$group[ids])&d$group[ids]==g],t,cost)));overall<-metricsG(d,ids,t,cost);unknown<-metricsG(d,ids[is.na(d$group[ids])],t,cost);gaps<-list()\n for(k in c(\"prevalence\",\"selectionRate\",\"TPR\",\"FPR\",\"precision\",\"accuracy\",\"meanCost\")){use<-Filter(function(g)g$metrics$mass>0,groups);v<-vapply(use,function(g)g$metrics[[k]],numeric(1));gaps[[k]]<-if(length(use)<2||anyNA(v))NA_real_ else max(v)-min(v)}\n list(overall=overall,groups=groups,unknownGroup=unknown,gaps=gaps,partitionMassResidual=overall$mass-unknown$mass-sum(vapply(groups,function(g)g$metrics$mass,numeric(1))))\n}\nsvgFixed<-function(file,points,title,xlabel,ylabel,legend){\n finite<-points[points$y!=\"undefined\"&points$x!=\"undefined\",,drop=FALSE];x<-as.numeric(finite$x);y<-as.numeric(finite$y);xmin<-if(length(x))min(x)else 0;xmax<-if(length(x))max(x)else 1;ymin<-min(c(0,y));ymax<-max(c(0,y));if(xmin==xmax){xmin<-xmin-.5;xmax<-xmax+.5};if(ymin==ymax)ymax<-ymin+1;X<-function(v)85+(v-xmin)/(xmax-xmin)*480;Y<-function(v)278-(v-ymin)/(ymax-ymin)*175\n esc<-function(s){s<-gsub(\"&\",\"&amp;\",s,fixed=TRUE);s<-gsub(\"<\",\"&lt;\",s,fixed=TRUE);gsub(\">\",\"&gt;\",s,fixed=TRUE)};s<-'<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"620\" height=\"360\" viewBox=\"0 0 620 360\"><rect width=\"620\" height=\"360\" fill=\"white\"/><g font-family=\"Arial, sans-serif\" font-size=\"13\" fill=\"#17324d\">'\n lines<-strwrap(title,width=65);for(i in seq_along(lines))s<-paste0(s,'<text x=\"25\" y=\"',24+(i-1)*18,'\">',esc(lines[i]),'</text>');colors<-c(\"#176b9b\",\"#b85e18\",\"#437e4d\")\n for(i in seq_along(legend))s<-paste0(s,'<circle cx=\"',30+(i-1)*250,'\" cy=\"76\" r=\"4\" fill=\"',colors[(i-1)%%3+1],'\"/><text x=\"',42+(i-1)*250,'\" y=\"80\">',esc(legend[i]),'</text>')\n s<-paste0(s,'<path d=\"M85 98V278H575\" fill=\"none\" stroke=\"#52677d\"/><text text-anchor=\"middle\" x=\"325\" y=\"338\">',esc(xlabel),'</text><text text-anchor=\"middle\" transform=\"translate(21,190) rotate(-90)\">',esc(ylabel),'</text>')\n for(i in 0:4){xx<-xmin+(xmax-xmin)*i/4;yy<-ymin+(ymax-ymin)*i/4;s<-paste0(s,'<text text-anchor=\"middle\" x=\"',sprintf(\"%.9g\",X(xx)),'\" y=\"305\">',sprintf(\"%.4g\",xx),'</text><text text-anchor=\"end\" x=\"77\" y=\"',sprintf(\"%.9g\",Y(yy)+4),'\">',sprintf(\"%.4g\",yy),'</text>')}\n for(i in seq_len(nrow(finite)))s<-paste0(s,'<circle cx=\"',sprintf(\"%.9g\",X(x[i])),'\" cy=\"',sprintf(\"%.9g\",Y(y[i])),'\" r=\"3\" fill=\"',colors[as.integer(finite$series[i])%%3+1],'\"/>');writeLines(paste0(s,'</g></svg>'),file,useBytes=TRUE)\n}\nfixedRun<-function(){\n api<-FIXED$api;a<-FIXED$args;summary<-list();points<-list();xlabel<-\"Declared index\";ylabel<-\"Value\";legend<-\"Declared result\"\n metric<-function(name,v,unit=\"dimensionless\"){if(is.null(v))v<-NA_real_;summary[[length(summary)+1L]]<<-data.frame(metric=name,value=if(is.na(v))\"undefined\"else sprintf(\"%.9g\",v),exactValue=\"\",unit=unit,defined=as.integer(!is.na(v)),stringsAsFactors=FALSE)}\n pt<-function(i,x,y,id=\"\",series=0){points[[length(points)+1L]]<<-data.frame(series=series,index=i,xExact=\"\",x=if(is.na(x))\"undefined\"else sprintf(\"%.9g\",x),yExact=\"\",y=if(is.na(y))\"undefined\"else sprintf(\"%.9g\",y),id=as.character(id),stringsAsFactors=FALSE)}\n if(api==\"realdata\"){\n  native<-loadData()[[a$kind]];fit<-fitmodel(native);d<-list(id=native$id,p=fit$pred,y=native$y,w=rep(1,length(native$id)),role=native$role,group=native$group,eligible=native$eligible);scenarios<-list()\n  for(j in 1:3){name<-c(\"equal\",\"miss-five\",\"alarm-five\")[j];cst<-list(c(1,1),c(1,5),c(5,1))[[j]];sel<-chooseG(d,list(),cst);scenarios[[j]]<-list(name=name,selection=sel);metric(paste0(name,\"Threshold\"),sel$selectedPolicy);metric(paste0(name,\"TestCost\"),sel$evaluation$meanCost,\"hypothetical cost units/mass\")}\n  ids<-scopeG(d,\"test\");cv<-curvesG(d,ids);cal<-calibrateG(d,ids,seq(0,1,.2));metric(\"testAUC\",cv$ROC_AUC);metric(\"testAP\",cv$averagePrecision);metric(\"testBrier\",cal$Brier);metric(\"eligibleRows\",sum(d$eligible),\"rows\")\n  for(j in seq_along(ids)){i<-ids[j];pt(j-1,j,d$p[i],d$id[i],0);pt(j-1,j,d$y[i],d$id[i],1)}\n  full<-list(kind=a$kind,fit=fit,scenarios=scenarios,testCurves=cv,testCalibration=cal,rowsScored=d);xlabel<-\"Test row, native order\";ylabel<-\"Y or probability\";legend<-c(\"Training-fitted probability\",\"Observed Y\")\n }else{\n  d<-rowsG(a$rows);role<-if(is.null(a$role))\"all\"else a$role;ids<-scopeG(d,role);cost<-if(is.null(a$costs))c(1,1)else c(qnum(a$costs$falsePositive),qnum(a$costs$falseNegative));t<-if(is.null(a$threshold)).5 else if(a$threshold%in%c(\"always-positive\",\"always-negative\"))a$threshold else qnum(a$threshold)\n  if(api==\"metrics\"){\n   full<-metricsG(d,ids,t,cost);for(k in c(\"mass\",\"accuracy\",\"precision\",\"TPR\",\"FPR\",\"F1\",\"Brier\",\"meanCost\"))metric(k,full[[k]],if(k==\"mass\")\"mass\"else if(k==\"meanCost\")\"hypothetical cost units/mass\"else\"dimensionless\");metric(\"BayesThreshold\",full$bayesThreshold)\n   for(i in 1:4)pt(i-1,i-1,full$confusion[[i]],names(full$confusion)[i]);xlabel<-\"TP / FP / FN / TN positions\";ylabel<-\"Analytical mass\"\n  }else if(api==\"curves\"){\n   full<-curvesG(d,ids);for(k in c(\"ROC_AUC\",\"averagePrecision\",\"PRTrapezoidWithInitialPrecisionOne\"))metric(k,full[[k]])\n   for(j in seq_along(full$points)){p<-full$points[[j]];pt(j-1,p$FPR,p$TPR,if(is.character(p$policy))p$policy else sprintf(\"%.17g\",p$policy))};xlabel<-\"False positive rate\";ylabel<-\"True positive rate\";legend<-\"Observed ROC operating points\"\n  }else if(api==\"choose\"){\n   full<-chooseG(d,a,cost);metric(\"selectedIndex\",full$selectedIndex,\"candidate index\");metric(\"minimumCost\",if(is.null(full$selectedValidation))NULL else full$selectedValidation$meanCost,\"hypothetical cost units/mass\");metric(\"feasible\",as.integer(!is.na(full$selectedIndex)),\"indicator\")\n   for(c in full$candidates)pt(c$index,c$index,c$metrics$meanCost,if(is.character(c$policy))c$policy else sprintf(\"%.17g\",c$policy));xlabel<-\"Validation candidate\";ylabel<-\"Assumed cost / mass\";legend<-\"Validation candidate costs\"\n  }else if(api==\"calibrate\"){\n   edges<-if(is.null(a$binEdges))seq(0,1,.2)else vapply(a$binEdges,qnum,numeric(1));full<-calibrateG(d,ids,edges);for(k in c(\"ECE\",\"Brier\",\"uncertainty\",\"resolution\",\"reliability\",\"withinBinCorrection\",\"BrierIdentityResidual\"))metric(k,full[[k]])\n   for(b in full$bins)pt(b$index,b$meanPrediction,b$eventRate,paste0(\"bin:\",b$index));xlabel<-\"Bin mean forecast\";ylabel<-\"Bin event rate\";legend<-\"Binary-event reliability\"\n  }else if(api==\"groups\"){\n   full<-groupsG(d,ids,t,cost);metric(\"overallTPR\",full$overall$TPR);metric(\"TPRGap\",full$gaps$TPR);metric(\"precisionGap\",full$gaps$precision);metric(\"unknownMass\",full$unknownGroup$mass,\"mass\");metric(\"partitionResidual\",full$partitionMassResidual,\"mass\")\n   for(j in seq_along(full$groups))pt(j-1,j-1,full$groups[[j]]$metrics$TPR,full$groups[[j]]$group);xlabel<-\"Declared group position\";ylabel<-\"True positive rate\";legend<-\"Known-group TPR\"\n  }else stop(\"unknown declared fixed API\")\n }\n sm<-do.call(rbind,summary);pp<-do.call(rbind,points);write.csv(sm,file.path(outDir,\"summary.csv\"),row.names=FALSE,na=\"\");write.csv(pp,file.path(outDir,\"plot-points.csv\"),row.names=FALSE,na=\"\");svgFixed(file.path(outDir,\"plot.svg\"),pp,FIXED$title,xlabel,ylabel,legend);dput(list(api=api,variant=FIXED$variant,input=FIXED$args,arithmetic=\"Base-R binary64 fixed example; not an exact rational general validator\",result=full),file=file.path(outDir,\"full.txt\"));cat(\"PASS\",api,FIXED$variant,\"summary\",nrow(sm),\"points\",nrow(pp),\"\\n\")\n}\n\nFIXED<-list(api=\"metrics\",variant=\"weighted\",args=list(rows=list(list(id=\"a\",score=\".9\",y=1,group=\"A\"),list(id=\"b\",score=\".8\",y=1,group=\"A\"),list(id=\"c\",score=\".8\",y=0,group=\"A\",weight=\"2\"),list(id=\"d\",score=\".6\",y=0,group=\"B\"),list(id=\"e\",score=\".4\",y=1,group=\"B\"),list(id=\"f\",score=\".1\",y=0,group=\"B\")),threshold=\".8\"),title=\"Double only the tied negative card mass\")\nfixedRun()\n",
        "input": {
          "rows": [
            {
              "id": "a",
              "score": ".9",
              "y": 1,
              "group": "A"
            },
            {
              "id": "b",
              "score": ".8",
              "y": 1,
              "group": "A"
            },
            {
              "id": "c",
              "score": ".8",
              "y": 0,
              "group": "A",
              "weight": "2"
            },
            {
              "id": "d",
              "score": ".6",
              "y": 0,
              "group": "B"
            },
            {
              "id": "e",
              "score": ".4",
              "y": 1,
              "group": "B"
            },
            {
              "id": "f",
              "score": ".1",
              "y": 0,
              "group": "B"
            }
          ],
          "threshold": ".8"
        },
        "inputFiles": [],
        "returnCode": 0,
        "expectedFailure": false,
        "stdout": "PASS metrics weighted summary 9 points 4 \n",
        "stderr": "During startup - Warning messages:\n1: Setting LC_COLLATE=C.UTF-8 failed \n2: Setting LC_CTYPE=C.UTF-8 failed \n3: Setting LC_MONETARY=C.UTF-8 failed \n4: Setting LC_TIME=C.UTF-8 failed \n",
        "summary": {
          "mass": "7",
          "accuracy": "0.571428571",
          "precision": "0.5",
          "TPR": "0.666666667",
          "FPR": "0.5",
          "F1": "0.571428571",
          "Brier": "0.294285714",
          "meanCost": "0.428571429",
          "BayesThreshold": "0.5"
        },
        "summaryRows": [
          {
            "metric": "mass",
            "value": "7",
            "exactValue": "",
            "unit": "mass",
            "defined": "1"
          },
          {
            "metric": "accuracy",
            "value": "0.571428571",
            "exactValue": "",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "precision",
            "value": "0.5",
            "exactValue": "",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "TPR",
            "value": "0.666666667",
            "exactValue": "",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "FPR",
            "value": "0.5",
            "exactValue": "",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "F1",
            "value": "0.571428571",
            "exactValue": "",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "Brier",
            "value": "0.294285714",
            "exactValue": "",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "meanCost",
            "value": "0.428571429",
            "exactValue": "",
            "unit": "hypothetical cost units/mass",
            "defined": "1"
          },
          {
            "metric": "BayesThreshold",
            "value": "0.5",
            "exactValue": "",
            "unit": "dimensionless",
            "defined": "1"
          }
        ],
        "plotPoints": [
          {
            "series": "0",
            "index": "0",
            "xExact": "",
            "x": "0",
            "yExact": "",
            "y": "2",
            "id": "TP"
          },
          {
            "series": "0",
            "index": "1",
            "xExact": "",
            "x": "1",
            "yExact": "",
            "y": "2",
            "id": "FP"
          },
          {
            "series": "0",
            "index": "2",
            "xExact": "",
            "x": "2",
            "yExact": "",
            "y": "1",
            "id": "FN"
          },
          {
            "series": "0",
            "index": "3",
            "xExact": "",
            "x": "3",
            "yExact": "",
            "y": "2",
            "id": "TN"
          }
        ],
        "plotFile": "ml14-fixed-results/metrics-weighted-r/plot.svg",
        "plotSHA256": "a5c654ed1c463d5537eb017c77d05f92b42934470f28fce7e185fd0717a6099e",
        "files": [
          {
            "file": "ml14-fixed-results/metrics-weighted-r/full.txt",
            "sha256": "a479a94ee8c5675ed0da521268321ed5dbb1e61cdf6650af22179222f2aefb2c",
            "bytes": 1210
          },
          {
            "file": "ml14-fixed-results/metrics-weighted-r/plot-points.csv",
            "sha256": "22c31ea9b562a620481899e03e09b1a8855285f65ee84d2b9f82b4f25681146d",
            "bytes": 145
          },
          {
            "file": "ml14-fixed-results/metrics-weighted-r/plot.svg",
            "sha256": "a5c654ed1c463d5537eb017c77d05f92b42934470f28fce7e185fd0717a6099e",
            "bytes": 1288
          },
          {
            "file": "ml14-fixed-results/metrics-weighted-r/summary.csv",
            "sha256": "80da71e76318b6cc2520a83a422248c92ec4d39271445514c4a816050c1602a4",
            "bytes": 427
          }
        ],
        "scope": "Actually executed standalone fixed example, Python exact Fraction versus base-R binary64. Approximate R residuals retained; not universal exact arithmetic/web validation/native UI. Source programs read factual3CSV only."
      },
      "zero-cost": {
        "api": "metrics",
        "variant": "zero-cost",
        "language": "r",
        "title": "Both hypothetical costs zero; Bayes ratio undefined",
        "codeFile": "ml14-code/metrics-zero-cost.R",
        "codeSHA256": "acb4836e08c6ddd788cb0996ed8553268ecefa625514a2c316336a7780aae618",
        "code": "# ML14 standalone public counterpart, base R only.\n# Inputs are only the three factual CSVs; derived columns/previous model answers unused.\n# Binary64 arithmetic, not arbitrary-precision Fraction. At numerical cost ties\n# within 1e-12 retain the earliest candidate. Exact claims belong to Python/web.\n# SHA256 infrastructure below is reused verbatim from the previous public study.\nargs<-commandArgs(trailingOnly=TRUE);filearg<-grep(\"^--file=\",commandArgs(),value=TRUE)\nhere<-if(dir.exists(\"ml14-sources\"))getwd()else if(length(filearg))dirname(normalizePath(sub(\"^--file=\",\"\",filearg[1])))else getwd()\noption<-function(key,default){i<-match(key,args);if(is.na(i))default else args[i+1]}\nsourceDir<-option(\"--source\",file.path(here,\"ml14-sources\"));outDir<-option(\"--out\",file.path(getwd(),\"ml14-r-results\"));dir.create(outDir,recursive=TRUE,showWarnings=FALSE)\nnum<-function(x){x[x%in%c(\"\",\".\")]<-NA_character_;as.numeric(x)}\nfmt<-function(x)ifelse(is.na(x),\"\",sprintf(\"%.17g\",x))\nratio<-function(a,b)if(b==0)NA_real_ else a/b\nreadnative<-function(name)read.csv(file.path(sourceDir,name),check.names=FALSE,colClasses=\"character\",na.strings=character(),stringsAsFactors=FALSE)\n# Vectorized SHA256 for the short ASCII keys used in this study.\n# Unsigned words use exact integer-valued doubles; bit operations use safe\n# 16-bit halves, avoiding R's reserved signed-INT_MIN/NA representation.\nMOD<-2^32\nxor32<-function(a,b) as.double(bitwXor(as.integer(floor(a/65536)),as.integer(floor(b/65536))))*65536+as.double(bitwXor(as.integer(a%%65536),as.integer(b%%65536)))\nand32<-function(a,b) as.double(bitwAnd(as.integer(floor(a/65536)),as.integer(floor(b/65536))))*65536+as.double(bitwAnd(as.integer(a%%65536),as.integer(b%%65536)))\nrot<-function(x,n) floor(x/2^n)+(x%%2^n)*2^(32-n)\nxor3<-function(a,b,c) xor32(xor32(a,b),c)\nK<-c(0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5,0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967,0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070,0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3,0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2)\nsha256<-function(strings) {\n n<-length(strings);bytes<-matrix(0,n,64)\n for(i in seq_len(n)) {v<-utf8ToInt(strings[i]);stopifnot(length(v)<56,all(v<128));if(length(v)) bytes[i,seq_along(v)]<-v;bytes[i,length(v)+1]<-128;bits<-length(v)*8;bytes[i,61:64]<-c(floor(bits/2^24)%%256,floor(bits/2^16)%%256,floor(bits/256)%%256,bits%%256)}\n w<-matrix(0,n,64)\n for(j in 1:16) {b<-4*(j-1)+1;w[,j]<-bytes[,b]*2^24+bytes[,b+1]*2^16+bytes[,b+2]*256+bytes[,b+3]}\n for(j in 17:64) {s0<-xor3(rot(w[,j-15],7),rot(w[,j-15],18),floor(w[,j-15]/8));s1<-xor3(rot(w[,j-2],17),rot(w[,j-2],19),floor(w[,j-2]/1024));w[,j]<-(w[,j-16]+s0+w[,j-7]+s1)%%MOD}\n init<-c(0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19)\n state<-lapply(init,function(v) rep(v,n));a<-state[[1]];b<-state[[2]];c<-state[[3]];d<-state[[4]];e<-state[[5]];f<-state[[6]];g<-state[[7]];h<-state[[8]]\n for(j in 1:64) {S1<-xor3(rot(e,6),rot(e,11),rot(e,25));ch<-xor32(and32(e,f),and32(MOD-1-e,g));t1<-(h+S1+ch+K[j]+w[,j])%%MOD;S0<-xor3(rot(a,2),rot(a,13),rot(a,22));maj<-xor3(and32(a,b),and32(a,c),and32(b,c));t2<-(S0+maj)%%MOD;h<-g;g<-f;f<-e;e<-(d+t1)%%MOD;d<-c;c<-b;b<-a;a<-(t1+t2)%%MOD}\n end<-list(a,b,c,d,e,f,g,h);hex<-lapply(1:8,function(j){v<-(end[[j]]+init[j])%%MOD;paste0(sprintf(\"%04x\",as.integer(floor(v/65536))),sprintf(\"%04x\",as.integer(v%%65536)))})\n do.call(paste0,hex)\n}\nstopifnot(identical(sha256(c(\"abc\",\"\")),c(\"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad\",\"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855\")))\n\nloadData<-function(){\n wb<-readnative(\"actual64-country-four-indicators-original-2024.csv\");codes<-c(\"NY.GDP.PCAP.KD\",\"NY.GDP.MKTP.KD.ZG\",\"FP.CPI.TOTL.ZG\",\"SP.DYN.LE00.IN\");iso<-sort(unique(wb$countryISO3));stopifnot(nrow(wb)==64,length(iso)==16)\n tokens<-t(vapply(iso,function(s)wb$originalValueToken[match(paste(s,codes),paste(wb$countryISO3,wb$indicatorID))],character(4)));vals<-matrix(num(as.vector(tokens)),nrow=nrow(tokens))\n country<-list(id=paste0(iso,\":2024\"),sourceRow=1:16,originalID=iso,x=vals[,1:3,drop=FALSE],rawX=tokens[,1:3,drop=FALSE],nativeTarget=tokens[,4],y=as.integer(vals[,4]>=80),group=ifelse(is.na(vals[,1]),NA_character_,as.character(as.integer(vals[,1]>=25000))),lineage=vapply(iso,function(s)paste(wb$sourceRow[match(paste(s,codes),paste(wb$countryISO3,wb$indicatorID))],collapse=\";\"),character(1)),cat=integer(),units=c(\"constant2015USD/person\",\"annualPercent\",\"annualPercent\"))\n nls<-readnative(\"actual3613-NLS-original52-fields-groups-roles.csv\");raw<-cbind(nls$ed76,nls$age76,nls$nearc4)\n person<-list(id=paste0(\"person:\",nls$sourceRow),sourceRow=as.integer(nls$sourceRow),originalID=nls$id,x=matrix(num(as.vector(raw)),nrow=nrow(raw)),rawX=raw,nativeTarget=nls$wage76,y=as.integer(num(nls$wage76)>=500),group=ifelse(nls$black%in%c(\"\",\".\"),NA_character_,nls$black),lineage=nls$sourceRow,cat=2L,units=c(\"years\",\"years\",\"nativeCategory\"))\n ch<-readnative(\"actual3150-churn-original14-fields-groups-roles.csv\");raw<-cbind(ch[[\"Call  Failure\"]],ch$Complains,ch[[\"Subscription  Length\"]],ch[[\"Seconds of Use\"]])\n company<-list(id=paste0(\"customer:\",ch$sourceRow),sourceRow=as.integer(ch$sourceRow),originalID=rep(\"\",nrow(ch)),x=matrix(num(as.vector(raw)),nrow=nrow(raw)),rawX=raw,nativeTarget=ch$Churn,y=as.integer(ch$Churn),group=ifelse(ch[[\"Tariff Plan\"]]%in%c(\"\",\".\"),NA_character_,ch[[\"Tariff Plan\"]]),lineage=ch$sourceRow,cat=1L,units=c(\"count\",\"nativeCategory\",\"months\",\"seconds\"))\n stopifnot(nrow(nls)==3613,nrow(ch)==3150,identical(as.integer(ch$sourceRow[ch[[\"Charge  Amount\"]]==\"10\"]),c(474L,2174L,2274L,2374L,2674L,2924L,2974L)))\n result<-list(country=country,person=person,company=company)\n for(k in names(result)){d<-result[[k]];n<-length(d$id);d$eligible<-!is.na(d$y)&rowSums(is.na(d$x))==0;hash<-sha256(paste0(\"ML14-role|\",k,\"|\",d$id));rank<-integer(n);rank[order(hash,seq_len(n))]<-seq_len(n)-1L;d$plannedRole<-ifelse(rank%%5==0,\"test\",ifelse(rank%%5==1,\"validation\",\"train\"));d$role<-ifelse(d$eligible,d$plannedRole,\"excluded\");result[[k]]<-d}\n stopifnot(sum(result$person$eligible)==3017);result\n}\nfitmodel<-function(d){\n ids<-which(d$role==\"train\");p<-ncol(d$x);m<-vapply(seq_len(p),function(j)if((j-1)%in%d$cat)NA_real_ else median(d$x[ids,j]),numeric(1));z<-d$x\n for(j in seq_len(p))if(!((j-1)%in%d$cat))z[,j]<-as.numeric(z[,j]>m[j])\n keys<-apply(z,1,function(v)paste(fmt(v),collapse=\"|\"));lev<-unique(keys[ids]);mass<-vapply(lev,function(k)sum(keys[ids]==k),integer(1));positive<-vapply(lev,function(k)sum(d$y[ids][keys[ids]==k]),integer(1));prob<-(positive+1)/(mass+2);fallback<-(sum(d$y[ids])+1)/(length(ids)+2);pred<-prob[match(keys,lev)];unseen<-is.na(pred);pred[unseen]<-fallback;pred[!d$eligible]<-NA_real_;unseen[!d$eligible]<-NA\n list(ids=ids,medians=m,z=z,keys=keys,lev=lev,mass=mass,positive=positive,prob=prob,fallback=fallback,pred=pred,unseen=unseen)\n}\nmeasure<-function(d,p,ids,t=.5,cost=c(1,1)){\n use<-ids[d$eligible[ids]&!is.na(p[ids])];y<-d$y[use];a<-if(is.character(t))rep(t==\"always-positive\",length(use))else p[use]>=t\n TP<-sum(a&y==1);FP<-sum(a&y==0);FN<-sum(!a&y==1);TN<-sum(!a&y==0);P<-TP+FN;N<-FP+TN;W<-P+N;PP<-TP+FP;PN<-TN+FN;TPR<-ratio(TP,P);TNR<-ratio(TN,N);bs<-sum((p[use]-y)^2);tc<-FP*cost[1]+FN*cost[2]\n list(TP=TP,FP=FP,FN=FN,TN=TN,mass=W,positiveTargetMass=P,negativeTargetMass=N,predictedPositiveMass=PP,predictedNegativeMass=PN,prevalence=ratio(P,W),selectionRate=ratio(PP,W),accuracy=ratio(TP+TN,W),precision=ratio(TP,PP),negativePredictiveValue=ratio(TN,PN),TPR=TPR,FPR=ratio(FP,N),TNR=TNR,FNR=ratio(FN,P),F1=ratio(2*TP,2*TP+FP+FN),balancedAccuracy=if(is.na(TPR)||is.na(TNR))NA_real_ else(TPR+TNR)/2,Brier=ratio(bs,W),BrierSum=bs,totalCost=tc,meanCost=ratio(tc,W))\n}\ncurves<-function(d,p,ids){\n use<-ids[d$eligible[ids]&!is.na(p[ids])];scores<-sort(unique(p[use]),decreasing=TRUE);policies<-c(list(\"always-negative\"),as.list(scores));points<-lapply(policies,function(t){m<-measure(d,p,ids,t);c(list(policy=t),m[c(\"TP\",\"FP\",\"FN\",\"TN\",\"TPR\",\"FPR\",\"precision\")],list(recall=m$TPR))})\n pos<-use[d$y[use]==1];neg<-use[d$y[use]==0];U<-0;for(i in pos)U<-U+sum(p[i]>p[neg])+.5*sum(p[i]==p[neg])\n AP<-0;trap<-0;lastR<-0;lastP<-1\n if(length(pos)&&length(scores))for(j in seq_along(scores)){z<-points[[j+1]];AP<-AP+(z$recall-lastR)*z$precision;trap<-trap+(z$recall-lastR)*(z$precision+lastP)/2;lastR<-z$recall;lastP<-z$precision}\n list(points=points,ROC_AUC=ratio(U,length(pos)*length(neg)),averagePrecision=if(length(pos))AP else NA_real_,PRTrapezoidWithInitialPrecisionOne=if(length(pos))trap else NA_real_)\n}\ncalibrate<-function(d,p,ids){\n use<-ids[d$eligible[ids]&!is.na(p[ids])];W<-length(use);pi<-if(W)mean(d$y[use])else NA_real_;bins<-list();ECE<-rel<-res<-correction<-0\n whichbin<-findInterval(p[use],seq(0,1,.2),rightmost.closed=TRUE,all.inside=TRUE)\n for(b in 1:5){rr<-use[whichbin==b];w<-length(rr);mp<-if(w)mean(p[rr])else NA_real_;o<-if(w)mean(d$y[rr])else NA_real_;variance<-if(w)mean((p[rr]-mp)^2)else NA_real_;covariance<-if(w)mean((p[rr]-mp)*(d$y[rr]-o))else NA_real_;bc<-variance-2*covariance;gap<-mp-o\n  bins[[b]]<-list(mass=w,meanPrediction=mp,eventRate=o,gap=gap,absoluteGap=abs(gap),scoreVariance=variance,scoreTargetCovariance=covariance,withinBinCorrection=bc,rows=w,ids=d$id[rr])\n  if(w){share<-w/W;ECE<-ECE+share*abs(gap);rel<-rel+share*gap^2;res<-res+share*(o-pi)^2;correction<-correction+share*bc}\n };bs<-if(W)mean((p[use]-d$y[use])^2)else NA_real_;unc<-pi*(1-pi)\n list(bins=bins,ECE=if(W)ECE else NA_real_,Brier=bs,reliability=if(W)rel else NA_real_,resolution=if(W)res else NA_real_,uncertainty=unc,withinBinCorrection=if(W)correction else NA_real_,BrierIdentityResidual=bs-(unc-res+rel+correction))\n}\ncounts<-c(\"mass\",\"positiveTargetMass\",\"negativeTargetMass\",\"predictedPositiveMass\",\"predictedNegativeMass\");rates<-c(\"prevalence\",\"selectionRate\",\"accuracy\",\"precision\",\"negativePredictiveValue\",\"TPR\",\"FPR\",\"TNR\",\"FNR\",\"F1\",\"balancedAccuracy\",\"Brier\",\"BrierSum\",\"totalCost\",\"meanCost\")\ntables<-setNames(lapply(1:10,function(i)list()),c(\"predictions\",\"lineage\",\"fit-medians\",\"fit-cells\",\"validation-candidates\",\"test-metrics\",\"test-curves\",\"calibration-bins\",\"group-metrics\",\"chart-points\"))\nadd<-function(name,row)tables[[name]][[length(tables[[name]])+1L]]<<-row\nscalars<-function(m,keys){out<-list();for(k in keys){out[[paste0(k,\"Exact\")]]<-\"\";out[[paste0(k,\"Approx\")]]<-fmt(m[[k]])};out}\ntagrow<-function(kind,...)c(list(kind=kind),list(...))\npoint<-function(kind,chart,series,index,x,y,xunit=\"dimensionless\",yunit=\"dimensionless\",role=\"test\",tag=\"\"){add(\"chart-points\",tagrow(kind,chart=chart,series=series,index=index,xExact=\"\",xApprox=fmt(x),yExact=\"\",yApprox=fmt(y),xUnit=xunit,yUnit=yunit,role=role,tag=tag))}\nstudy<-function(kind,d){\n f<-fitmodel(d);n<-length(d$id);train<-which(d$role==\"train\");validation<-which(d$role==\"validation\");test<-which(d$role==\"test\");p<-f$pred;cv<-curves(d,p,test);cal<-calibrate(d,p,test)\n for(i in seq_len(n)){\n  reason<-if(d$eligible[i])\"\"else\"required-X-or-Y-missing\";transformed<-if(d$eligible[i])paste(fmt(f$z[i,]),collapse=\"|\")else\"\"\n  add(\"predictions\",tagrow(kind,id=d$id[i],sourceRow=d$sourceRow[i],originalID=d$originalID[i],plannedRole=d$plannedRole[i],role=d$role[i],group=ifelse(is.na(d$group[i]),\"\",d$group[i]),eligible=as.integer(d$eligible[i]),targetExact=fmt(d$y[i]),probabilityExact=\"\",probabilityApprox=fmt(p[i]),unseenCell=ifelse(is.na(f$unseen[i]),\"\",as.character(as.integer(f$unseen[i]))),transformedX=transformed,reason=reason))\n  raw<-d$rawX[i,];raw[raw%in%c(\"\",\".\")]<-\"\";nativeY<-d$nativeTarget[i];if(nativeY%in%c(\"\",\".\"))nativeY<-\"\"\n  add(\"lineage\",tagrow(kind,id=d$id[i],sourceRow=d$sourceRow[i],originalID=d$originalID[i],nativeSourceRows=d$lineage[i],rawX=paste(raw,collapse=\"|\"),nativeTarget=nativeY,derivedTarget=fmt(d$y[i]),nativeGroup=ifelse(is.na(d$group[i]),\"\",d$group[i]),plannedRole=d$plannedRole[i],role=d$role[i],eligible=as.integer(d$eligible[i]),analyticalMass=\"1\",reason=reason))\n }\n for(j in seq_len(ncol(d$x)))add(\"fit-medians\",tagrow(kind,feature=j-1,categorical=as.integer((j-1)%in%d$cat),fitRows=length(train),medianExact=\"\",medianApprox=fmt(f$medians[j]),unit=d$units[j]))\n for(j in seq_along(f$lev))add(\"fit-cells\",tagrow(kind,cell=f$lev[j],trainingRows=f$mass[j],positiveRows=f$positive[j],probabilityExact=\"\",probabilityApprox=fmt(f$prob[j]),fallbackExact=\"\",fallbackApprox=fmt(f$fallback)))\n for(j in seq_along(cv$points)){\n  z<-cv$points[[j]];t<-z$policy;add(\"test-curves\",c(tagrow(kind,point=j-1,policy=if(is.character(t))t else\"threshold\",thresholdExact=\"\",thresholdApprox=if(is.character(t))\"\"else fmt(t)),scalars(z,c(\"TP\",\"FP\",\"FN\",\"TN\",\"TPR\",\"FPR\",\"precision\",\"recall\"))))\n  point(kind,\"roc\",\"ROC\",j-1,z$FPR,z$TPR);point(kind,\"pr\",\"PR-observed\",j-1,z$recall,z$precision)\n }\n for(b in 1:5){z<-cal$bins[[b]];add(\"calibration-bins\",c(tagrow(kind,bin=b-1,leftExact=c(\"0\",\"1/5\",\"2/5\",\"3/5\",\"4/5\")[b],rightExact=c(\"1/5\",\"2/5\",\"3/5\",\"4/5\",\"1\")[b],rightClosed=as.integer(b==5),rows=z$rows,ids=paste(z$ids,collapse=\";\")),scalars(z,c(\"mass\",\"meanPrediction\",\"eventRate\",\"gap\",\"absoluteGap\",\"scoreVariance\",\"scoreTargetCovariance\",\"withinBinCorrection\"))));point(kind,\"reliability\",\"Binary event rate\",b-1,z$meanPrediction,z$eventRate,tag=paste0(\"rows=\",z$rows))}\n for(j in seq_along(test)){i<-test[j];point(kind,\"test-scores\",\"Training-fitted probability\",j-1,j,p[i],\"test-row position\",\"probability\",tag=d$id[i]);point(kind,\"test-scores\",\"Observed Y\",j-1,j,d$y[i],\"test-row position\",\"binary target\",tag=d$id[i])}\n scenarioNames<-c(\"equal\",\"miss-five\",\"alarm-five\");costs<-list(c(1,1),c(1,5),c(5,1))\n for(s in 1:3){name<-scenarioNames[s];cost<-costs[[s]];grid<-c(list(\"always-negative\"),as.list(sort(unique(p[validation]),decreasing=TRUE)));candidates<-lapply(grid,function(t)measure(d,p,validation,t,cost));values<-vapply(candidates,function(m)m$meanCost,numeric(1));best<-which(values<=min(values)+1e-12)[1];chosen<-grid[[best]];ev<-measure(d,p,test,chosen,cost)\n  for(j in seq_along(grid)){t<-grid[[j]];m<-candidates[[j]];cell<-setNames(lapply(c(\"TP\",\"FP\",\"FN\",\"TN\"),function(k)fmt(m[[k]])),paste0(c(\"TP\",\"FP\",\"FN\",\"TN\"),\"Exact\"));add(\"validation-candidates\",c(tagrow(kind,scenario=name,candidate=j-1,selected=as.integer(j==best),policy=if(is.character(t))t else\"threshold\",thresholdExact=\"\",thresholdApprox=if(is.character(t))\"\"else fmt(t),feasible=1,reasons=\"\"),cell,scalars(m,c(counts,\"TPR\",\"FPR\",\"precision\",\"meanCost\",\"totalCost\"))));point(kind,\"validation-cost\",name,j-1,j-1,m$meanCost,\"candidate index\",\"hypothetical cost units/mass\",\"validation\",if(is.character(t))t else fmt(t))}\n  m<-c(ev,cv[c(\"ROC_AUC\",\"averagePrecision\",\"PRTrapezoidWithInitialPrecisionOne\")],cal[c(\"ECE\",\"reliability\",\"resolution\",\"uncertainty\",\"withinBinCorrection\",\"BrierIdentityResidual\")])\n  for(k in c(\"TP\",\"FP\",\"FN\",\"TN\",counts,rates,\"ROC_AUC\",\"averagePrecision\",\"PRTrapezoidWithInitialPrecisionOne\",\"ECE\",\"reliability\",\"resolution\",\"uncertainty\",\"withinBinCorrection\",\"BrierIdentityResidual\")){\n   unit<-if(k%in%c(\"TP\",\"FP\",\"FN\",\"TN\",counts))\"rows\"else if(k==\"totalCost\")\"hypothetical cost units\"else if(k==\"meanCost\")\"hypothetical cost units/mass\"else if(k==\"BrierSum\")\"sum squared-probability loss\"else\"dimensionless\"\n   add(\"test-metrics\",tagrow(kind,scenario=name,metric=k,valueExact=\"\",valueApprox=fmt(m[[k]]),unit=unit))\n  }\n  lev<-unique(d$group[test][!is.na(d$group[test])]);sets<-c(list(test),lapply(lev,function(g)test[!is.na(d$group[test])&d$group[test]==g]),list(test[is.na(d$group[test])]))\n  types<-c(\"overall\",rep(\"known\",length(lev)),\"unknown\");tokens<-c(\"all\",lev,\"\")\n  for(j in seq_along(sets)){ids<-sets[[j]];m<-measure(d,p,ids,chosen,cost);cell<-setNames(lapply(c(\"TP\",\"FP\",\"FN\",\"TN\"),function(k)fmt(m[[k]])),paste0(c(\"TP\",\"FP\",\"FN\",\"TN\"),\"Exact\"));add(\"group-metrics\",c(tagrow(kind,scenario=name,groupType=types[j],groupToken=tokens[j],retainedRows=length(ids)),cell,scalars(m,c(counts,rates))));if(types[j]==\"known\")point(kind,\"group-TPR\",name,j-2,j-2,m$TPR,\"declared group position\",\"TPR\",tag=tokens[j])}\n }\n invisible(NULL)\n}\n\n# Fixed finite inputs only; not the complete web input/budget validator.\nqnum<-function(v){if(is.null(v))return(NA_real_);if(is.logical(v))return(as.numeric(v));s<-as.character(v);if(grepl(\"/\",s,fixed=TRUE)){a<-strsplit(s,\"/\",fixed=TRUE)[[1]];return(as.numeric(a[1])/as.numeric(a[2]))};as.numeric(s)}\nrowsG<-function(raw){\n n<-length(raw);get<-function(r,k,default=NULL)if(is.null(r[[k]]))default else r[[k]]\n id<-vapply(raw,function(r)as.character(r$id),character(1));p<-vapply(raw,function(r)qnum(r$score),numeric(1));y<-vapply(raw,function(r)qnum(r$y),numeric(1));w<-vapply(raw,function(r)qnum(get(r,\"weight\",\"1\")),numeric(1));role<-vapply(raw,function(r)get(r,\"role\",\"evaluation\"),character(1));group<-vapply(raw,function(r)as.character(get(r,\"group\",NA_character_)),character(1))\n stopifnot(all(w>=0),all(is.na(p)|(p>=0&p<=1)),all(is.na(y)|y%in%c(0,1)),!anyDuplicated(id));list(id=id,p=p,y=y,w=w,role=role,group=group,eligible=!is.na(p)&!is.na(y)&w>0&role!=\"excluded\")\n}\nscopeG<-function(d,role=\"all\")if(role==\"all\")seq_along(d$id)else which(d$role==role)\nmetricsG<-function(d,ids,t=.5,cost=c(1,1)){\n use<-ids[d$eligible[ids]];p<-d$p[use];y<-d$y[use];w<-d$w[use];a<-if(is.character(t))rep(t==\"always-positive\",length(use))else p>=t\n TP<-sum(w[a&y==1]);FP<-sum(w[a&y==0]);FN<-sum(w[!a&y==1]);TN<-sum(w[!a&y==0]);P<-TP+FN;N<-FP+TN;W<-P+N;PP<-TP+FP;PN<-TN+FN;TPR<-ratio(TP,P);TNR<-ratio(TN,N);bs<-sum(w*(p-y)^2);tc<-FP*cost[1]+FN*cost[2]\n list(confusion=list(TP=TP,FP=FP,FN=FN,TN=TN),mass=W,positiveTargetMass=P,negativeTargetMass=N,predictedPositiveMass=PP,predictedNegativeMass=PN,prevalence=ratio(P,W),selectionRate=ratio(PP,W),accuracy=ratio(TP+TN,W),precision=ratio(TP,PP),negativePredictiveValue=ratio(TN,PN),TPR=TPR,FPR=ratio(FP,N),TNR=TNR,FNR=ratio(FN,P),F1=ratio(2*TP,2*TP+FP+FN),balancedAccuracy=if(is.na(TPR)||is.na(TNR))NA_real_ else(TPR+TNR)/2,Brier=ratio(bs,W),BrierSum=bs,totalCost=tc,meanCost=ratio(tc,W),bayesThreshold=ratio(cost[1],sum(cost)))\n}\ncurvesG<-function(d,ids){\n use<-ids[d$eligible[ids]];grid<-c(list(\"always-negative\"),as.list(sort(unique(d$p[use]),decreasing=TRUE)));points<-lapply(grid,function(t){m<-metricsG(d,ids,t);c(list(policy=t),m$confusion,m[c(\"TPR\",\"FPR\",\"precision\")],list(recall=m$TPR))});pos<-use[d$y[use]==1];neg<-use[d$y[use]==0];P<-sum(d$w[pos]);N<-sum(d$w[neg]);U<-0\n for(i in pos)U<-U+d$w[i]*sum(d$w[neg]*((d$p[i]>d$p[neg])+.5*(d$p[i]==d$p[neg])))\n AP<-trap<-lastR<-0;lastP<-1\n if(P&&length(grid)>1)for(j in 2:length(grid)){z<-points[[j]];AP<-AP+(z$recall-lastR)*z$precision;trap<-trap+(z$recall-lastR)*(z$precision+lastP)/2;lastR<-z$recall;lastP<-z$precision}\n list(points=points,ROC_AUC=ratio(U,P*N),averagePrecision=if(P)AP else NA_real_,PRTrapezoidWithInitialPrecisionOne=if(P)trap else NA_real_)\n}\nchooseG<-function(d,a,cost){\n role<-if(is.null(a$selectionRole))\"validation\"else a$selectionRole;er<-if(is.null(a$evaluationRole))\"test\"else a$evaluationRole;ids<-scopeG(d,role);use<-ids[d$eligible[ids]];stopifnot(length(use)>0);grid<-if(is.null(a$thresholds))c(list(\"always-negative\"),as.list(sort(unique(d$p[use]),decreasing=TRUE)))else lapply(a$thresholds,function(t)if(t%in%c(\"always-negative\",\"always-positive\"))t else qnum(t))\n candidates<-lapply(seq_along(grid),function(j){m<-metricsG(d,ids,grid[[j]],cost);feasible<-TRUE;if(!is.null(a$minTPR))feasible<-feasible&&!is.na(m$TPR)&&m$TPR>=qnum(a$minTPR);if(!is.null(a$maxFPR))feasible<-feasible&&!is.na(m$FPR)&&m$FPR<=qnum(a$maxFPR);list(index=j-1,policy=grid[[j]],metrics=m,feasible=feasible)})\n good<-which(vapply(candidates,function(c)c$feasible,logical(1)));best<-NA_integer_;if(length(good)){v<-vapply(candidates[good],function(c)c$metrics$meanCost,numeric(1));best<-good[which(v<=min(v)+1e-12)[1]]}\n list(selectedIndex=if(is.na(best))NA_integer_ else best-1,selectedPolicy=if(is.na(best))NULL else grid[[best]],selectedValidation=if(is.na(best))NULL else candidates[[best]]$metrics,candidates=candidates,evaluation=if(is.na(best)||er==\"none\")NULL else metricsG(d,scopeG(d,er),grid[[best]],cost))\n}\ncalibrateG<-function(d,ids,edges){\n use<-ids[d$eligible[ids]];W<-sum(d$w[use]);pi<-ratio(sum(d$w[use]*d$y[use]),W);bins<-list();ECE<-rel<-res<-correction<-0;assign<-findInterval(d$p[use],edges,rightmost.closed=TRUE,all.inside=TRUE)\n for(b in seq_len(length(edges)-1)){rr<-use[assign==b];w<-sum(d$w[rr]);mp<-ratio(sum(d$w[rr]*d$p[rr]),w);o<-ratio(sum(d$w[rr]*d$y[rr]),w);variance<-if(w)sum(d$w[rr]*(d$p[rr]-mp)^2)/w else NA_real_;covariance<-if(w)sum(d$w[rr]*(d$p[rr]-mp)*(d$y[rr]-o))/w else NA_real_;bc<-variance-2*covariance;gap<-mp-o;bins[[b]]<-list(index=b-1,mass=w,meanPrediction=mp,eventRate=o,scoreVariance=variance,scoreTargetCovariance=covariance,withinBinCorrection=bc,ids=d$id[rr])\n  if(w){s<-w/W;ECE<-ECE+s*abs(gap);rel<-rel+s*gap^2;res<-res+s*(o-pi)^2;correction<-correction+s*bc}\n };bs<-ratio(sum(d$w[use]*(d$p[use]-d$y[use])^2),W);unc<-pi*(1-pi);list(bins=bins,Brier=bs,ECE=if(W)ECE else NA_real_,uncertainty=unc,reliability=if(W)rel else NA_real_,resolution=if(W)res else NA_real_,withinBinCorrection=if(W)correction else NA_real_,BrierIdentityResidual=bs-(unc-res+rel+correction))\n}\ngroupsG<-function(d,ids,t,cost){\n lev<-unique(d$group[ids][!is.na(d$group[ids])]);groups<-lapply(lev,function(g)list(group=g,metrics=metricsG(d,ids[!is.na(d$group[ids])&d$group[ids]==g],t,cost)));overall<-metricsG(d,ids,t,cost);unknown<-metricsG(d,ids[is.na(d$group[ids])],t,cost);gaps<-list()\n for(k in c(\"prevalence\",\"selectionRate\",\"TPR\",\"FPR\",\"precision\",\"accuracy\",\"meanCost\")){use<-Filter(function(g)g$metrics$mass>0,groups);v<-vapply(use,function(g)g$metrics[[k]],numeric(1));gaps[[k]]<-if(length(use)<2||anyNA(v))NA_real_ else max(v)-min(v)}\n list(overall=overall,groups=groups,unknownGroup=unknown,gaps=gaps,partitionMassResidual=overall$mass-unknown$mass-sum(vapply(groups,function(g)g$metrics$mass,numeric(1))))\n}\nsvgFixed<-function(file,points,title,xlabel,ylabel,legend){\n finite<-points[points$y!=\"undefined\"&points$x!=\"undefined\",,drop=FALSE];x<-as.numeric(finite$x);y<-as.numeric(finite$y);xmin<-if(length(x))min(x)else 0;xmax<-if(length(x))max(x)else 1;ymin<-min(c(0,y));ymax<-max(c(0,y));if(xmin==xmax){xmin<-xmin-.5;xmax<-xmax+.5};if(ymin==ymax)ymax<-ymin+1;X<-function(v)85+(v-xmin)/(xmax-xmin)*480;Y<-function(v)278-(v-ymin)/(ymax-ymin)*175\n esc<-function(s){s<-gsub(\"&\",\"&amp;\",s,fixed=TRUE);s<-gsub(\"<\",\"&lt;\",s,fixed=TRUE);gsub(\">\",\"&gt;\",s,fixed=TRUE)};s<-'<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"620\" height=\"360\" viewBox=\"0 0 620 360\"><rect width=\"620\" height=\"360\" fill=\"white\"/><g font-family=\"Arial, sans-serif\" font-size=\"13\" fill=\"#17324d\">'\n lines<-strwrap(title,width=65);for(i in seq_along(lines))s<-paste0(s,'<text x=\"25\" y=\"',24+(i-1)*18,'\">',esc(lines[i]),'</text>');colors<-c(\"#176b9b\",\"#b85e18\",\"#437e4d\")\n for(i in seq_along(legend))s<-paste0(s,'<circle cx=\"',30+(i-1)*250,'\" cy=\"76\" r=\"4\" fill=\"',colors[(i-1)%%3+1],'\"/><text x=\"',42+(i-1)*250,'\" y=\"80\">',esc(legend[i]),'</text>')\n s<-paste0(s,'<path d=\"M85 98V278H575\" fill=\"none\" stroke=\"#52677d\"/><text text-anchor=\"middle\" x=\"325\" y=\"338\">',esc(xlabel),'</text><text text-anchor=\"middle\" transform=\"translate(21,190) rotate(-90)\">',esc(ylabel),'</text>')\n for(i in 0:4){xx<-xmin+(xmax-xmin)*i/4;yy<-ymin+(ymax-ymin)*i/4;s<-paste0(s,'<text text-anchor=\"middle\" x=\"',sprintf(\"%.9g\",X(xx)),'\" y=\"305\">',sprintf(\"%.4g\",xx),'</text><text text-anchor=\"end\" x=\"77\" y=\"',sprintf(\"%.9g\",Y(yy)+4),'\">',sprintf(\"%.4g\",yy),'</text>')}\n for(i in seq_len(nrow(finite)))s<-paste0(s,'<circle cx=\"',sprintf(\"%.9g\",X(x[i])),'\" cy=\"',sprintf(\"%.9g\",Y(y[i])),'\" r=\"3\" fill=\"',colors[as.integer(finite$series[i])%%3+1],'\"/>');writeLines(paste0(s,'</g></svg>'),file,useBytes=TRUE)\n}\nfixedRun<-function(){\n api<-FIXED$api;a<-FIXED$args;summary<-list();points<-list();xlabel<-\"Declared index\";ylabel<-\"Value\";legend<-\"Declared result\"\n metric<-function(name,v,unit=\"dimensionless\"){if(is.null(v))v<-NA_real_;summary[[length(summary)+1L]]<<-data.frame(metric=name,value=if(is.na(v))\"undefined\"else sprintf(\"%.9g\",v),exactValue=\"\",unit=unit,defined=as.integer(!is.na(v)),stringsAsFactors=FALSE)}\n pt<-function(i,x,y,id=\"\",series=0){points[[length(points)+1L]]<<-data.frame(series=series,index=i,xExact=\"\",x=if(is.na(x))\"undefined\"else sprintf(\"%.9g\",x),yExact=\"\",y=if(is.na(y))\"undefined\"else sprintf(\"%.9g\",y),id=as.character(id),stringsAsFactors=FALSE)}\n if(api==\"realdata\"){\n  native<-loadData()[[a$kind]];fit<-fitmodel(native);d<-list(id=native$id,p=fit$pred,y=native$y,w=rep(1,length(native$id)),role=native$role,group=native$group,eligible=native$eligible);scenarios<-list()\n  for(j in 1:3){name<-c(\"equal\",\"miss-five\",\"alarm-five\")[j];cst<-list(c(1,1),c(1,5),c(5,1))[[j]];sel<-chooseG(d,list(),cst);scenarios[[j]]<-list(name=name,selection=sel);metric(paste0(name,\"Threshold\"),sel$selectedPolicy);metric(paste0(name,\"TestCost\"),sel$evaluation$meanCost,\"hypothetical cost units/mass\")}\n  ids<-scopeG(d,\"test\");cv<-curvesG(d,ids);cal<-calibrateG(d,ids,seq(0,1,.2));metric(\"testAUC\",cv$ROC_AUC);metric(\"testAP\",cv$averagePrecision);metric(\"testBrier\",cal$Brier);metric(\"eligibleRows\",sum(d$eligible),\"rows\")\n  for(j in seq_along(ids)){i<-ids[j];pt(j-1,j,d$p[i],d$id[i],0);pt(j-1,j,d$y[i],d$id[i],1)}\n  full<-list(kind=a$kind,fit=fit,scenarios=scenarios,testCurves=cv,testCalibration=cal,rowsScored=d);xlabel<-\"Test row, native order\";ylabel<-\"Y or probability\";legend<-c(\"Training-fitted probability\",\"Observed Y\")\n }else{\n  d<-rowsG(a$rows);role<-if(is.null(a$role))\"all\"else a$role;ids<-scopeG(d,role);cost<-if(is.null(a$costs))c(1,1)else c(qnum(a$costs$falsePositive),qnum(a$costs$falseNegative));t<-if(is.null(a$threshold)).5 else if(a$threshold%in%c(\"always-positive\",\"always-negative\"))a$threshold else qnum(a$threshold)\n  if(api==\"metrics\"){\n   full<-metricsG(d,ids,t,cost);for(k in c(\"mass\",\"accuracy\",\"precision\",\"TPR\",\"FPR\",\"F1\",\"Brier\",\"meanCost\"))metric(k,full[[k]],if(k==\"mass\")\"mass\"else if(k==\"meanCost\")\"hypothetical cost units/mass\"else\"dimensionless\");metric(\"BayesThreshold\",full$bayesThreshold)\n   for(i in 1:4)pt(i-1,i-1,full$confusion[[i]],names(full$confusion)[i]);xlabel<-\"TP / FP / FN / TN positions\";ylabel<-\"Analytical mass\"\n  }else if(api==\"curves\"){\n   full<-curvesG(d,ids);for(k in c(\"ROC_AUC\",\"averagePrecision\",\"PRTrapezoidWithInitialPrecisionOne\"))metric(k,full[[k]])\n   for(j in seq_along(full$points)){p<-full$points[[j]];pt(j-1,p$FPR,p$TPR,if(is.character(p$policy))p$policy else sprintf(\"%.17g\",p$policy))};xlabel<-\"False positive rate\";ylabel<-\"True positive rate\";legend<-\"Observed ROC operating points\"\n  }else if(api==\"choose\"){\n   full<-chooseG(d,a,cost);metric(\"selectedIndex\",full$selectedIndex,\"candidate index\");metric(\"minimumCost\",if(is.null(full$selectedValidation))NULL else full$selectedValidation$meanCost,\"hypothetical cost units/mass\");metric(\"feasible\",as.integer(!is.na(full$selectedIndex)),\"indicator\")\n   for(c in full$candidates)pt(c$index,c$index,c$metrics$meanCost,if(is.character(c$policy))c$policy else sprintf(\"%.17g\",c$policy));xlabel<-\"Validation candidate\";ylabel<-\"Assumed cost / mass\";legend<-\"Validation candidate costs\"\n  }else if(api==\"calibrate\"){\n   edges<-if(is.null(a$binEdges))seq(0,1,.2)else vapply(a$binEdges,qnum,numeric(1));full<-calibrateG(d,ids,edges);for(k in c(\"ECE\",\"Brier\",\"uncertainty\",\"resolution\",\"reliability\",\"withinBinCorrection\",\"BrierIdentityResidual\"))metric(k,full[[k]])\n   for(b in full$bins)pt(b$index,b$meanPrediction,b$eventRate,paste0(\"bin:\",b$index));xlabel<-\"Bin mean forecast\";ylabel<-\"Bin event rate\";legend<-\"Binary-event reliability\"\n  }else if(api==\"groups\"){\n   full<-groupsG(d,ids,t,cost);metric(\"overallTPR\",full$overall$TPR);metric(\"TPRGap\",full$gaps$TPR);metric(\"precisionGap\",full$gaps$precision);metric(\"unknownMass\",full$unknownGroup$mass,\"mass\");metric(\"partitionResidual\",full$partitionMassResidual,\"mass\")\n   for(j in seq_along(full$groups))pt(j-1,j-1,full$groups[[j]]$metrics$TPR,full$groups[[j]]$group);xlabel<-\"Declared group position\";ylabel<-\"True positive rate\";legend<-\"Known-group TPR\"\n  }else stop(\"unknown declared fixed API\")\n }\n sm<-do.call(rbind,summary);pp<-do.call(rbind,points);write.csv(sm,file.path(outDir,\"summary.csv\"),row.names=FALSE,na=\"\");write.csv(pp,file.path(outDir,\"plot-points.csv\"),row.names=FALSE,na=\"\");svgFixed(file.path(outDir,\"plot.svg\"),pp,FIXED$title,xlabel,ylabel,legend);dput(list(api=api,variant=FIXED$variant,input=FIXED$args,arithmetic=\"Base-R binary64 fixed example; not an exact rational general validator\",result=full),file=file.path(outDir,\"full.txt\"));cat(\"PASS\",api,FIXED$variant,\"summary\",nrow(sm),\"points\",nrow(pp),\"\\n\")\n}\n\nFIXED<-list(api=\"metrics\",variant=\"zero-cost\",args=list(rows=list(list(id=\"a\",score=\".9\",y=1,group=\"A\"),list(id=\"b\",score=\".8\",y=1,group=\"A\"),list(id=\"c\",score=\".8\",y=0,group=\"A\"),list(id=\"d\",score=\".6\",y=0,group=\"B\"),list(id=\"e\",score=\".4\",y=1,group=\"B\"),list(id=\"f\",score=\".1\",y=0,group=\"B\")),costs=list(falsePositive=\"0\",falseNegative=\"0\")),title=\"Both hypothetical costs zero; Bayes ratio undefined\")\nfixedRun()\n",
        "codeText": "# ML14 standalone public counterpart, base R only.\n# Inputs are only the three factual CSVs; derived columns/previous model answers unused.\n# Binary64 arithmetic, not arbitrary-precision Fraction. At numerical cost ties\n# within 1e-12 retain the earliest candidate. Exact claims belong to Python/web.\n# SHA256 infrastructure below is reused verbatim from the previous public study.\nargs<-commandArgs(trailingOnly=TRUE);filearg<-grep(\"^--file=\",commandArgs(),value=TRUE)\nhere<-if(dir.exists(\"ml14-sources\"))getwd()else if(length(filearg))dirname(normalizePath(sub(\"^--file=\",\"\",filearg[1])))else getwd()\noption<-function(key,default){i<-match(key,args);if(is.na(i))default else args[i+1]}\nsourceDir<-option(\"--source\",file.path(here,\"ml14-sources\"));outDir<-option(\"--out\",file.path(getwd(),\"ml14-r-results\"));dir.create(outDir,recursive=TRUE,showWarnings=FALSE)\nnum<-function(x){x[x%in%c(\"\",\".\")]<-NA_character_;as.numeric(x)}\nfmt<-function(x)ifelse(is.na(x),\"\",sprintf(\"%.17g\",x))\nratio<-function(a,b)if(b==0)NA_real_ else a/b\nreadnative<-function(name)read.csv(file.path(sourceDir,name),check.names=FALSE,colClasses=\"character\",na.strings=character(),stringsAsFactors=FALSE)\n# Vectorized SHA256 for the short ASCII keys used in this study.\n# Unsigned words use exact integer-valued doubles; bit operations use safe\n# 16-bit halves, avoiding R's reserved signed-INT_MIN/NA representation.\nMOD<-2^32\nxor32<-function(a,b) as.double(bitwXor(as.integer(floor(a/65536)),as.integer(floor(b/65536))))*65536+as.double(bitwXor(as.integer(a%%65536),as.integer(b%%65536)))\nand32<-function(a,b) as.double(bitwAnd(as.integer(floor(a/65536)),as.integer(floor(b/65536))))*65536+as.double(bitwAnd(as.integer(a%%65536),as.integer(b%%65536)))\nrot<-function(x,n) floor(x/2^n)+(x%%2^n)*2^(32-n)\nxor3<-function(a,b,c) xor32(xor32(a,b),c)\nK<-c(0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5,0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967,0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070,0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3,0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2)\nsha256<-function(strings) {\n n<-length(strings);bytes<-matrix(0,n,64)\n for(i in seq_len(n)) {v<-utf8ToInt(strings[i]);stopifnot(length(v)<56,all(v<128));if(length(v)) bytes[i,seq_along(v)]<-v;bytes[i,length(v)+1]<-128;bits<-length(v)*8;bytes[i,61:64]<-c(floor(bits/2^24)%%256,floor(bits/2^16)%%256,floor(bits/256)%%256,bits%%256)}\n w<-matrix(0,n,64)\n for(j in 1:16) {b<-4*(j-1)+1;w[,j]<-bytes[,b]*2^24+bytes[,b+1]*2^16+bytes[,b+2]*256+bytes[,b+3]}\n for(j in 17:64) {s0<-xor3(rot(w[,j-15],7),rot(w[,j-15],18),floor(w[,j-15]/8));s1<-xor3(rot(w[,j-2],17),rot(w[,j-2],19),floor(w[,j-2]/1024));w[,j]<-(w[,j-16]+s0+w[,j-7]+s1)%%MOD}\n init<-c(0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19)\n state<-lapply(init,function(v) rep(v,n));a<-state[[1]];b<-state[[2]];c<-state[[3]];d<-state[[4]];e<-state[[5]];f<-state[[6]];g<-state[[7]];h<-state[[8]]\n for(j in 1:64) {S1<-xor3(rot(e,6),rot(e,11),rot(e,25));ch<-xor32(and32(e,f),and32(MOD-1-e,g));t1<-(h+S1+ch+K[j]+w[,j])%%MOD;S0<-xor3(rot(a,2),rot(a,13),rot(a,22));maj<-xor3(and32(a,b),and32(a,c),and32(b,c));t2<-(S0+maj)%%MOD;h<-g;g<-f;f<-e;e<-(d+t1)%%MOD;d<-c;c<-b;b<-a;a<-(t1+t2)%%MOD}\n end<-list(a,b,c,d,e,f,g,h);hex<-lapply(1:8,function(j){v<-(end[[j]]+init[j])%%MOD;paste0(sprintf(\"%04x\",as.integer(floor(v/65536))),sprintf(\"%04x\",as.integer(v%%65536)))})\n do.call(paste0,hex)\n}\nstopifnot(identical(sha256(c(\"abc\",\"\")),c(\"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad\",\"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855\")))\n\nloadData<-function(){\n wb<-readnative(\"actual64-country-four-indicators-original-2024.csv\");codes<-c(\"NY.GDP.PCAP.KD\",\"NY.GDP.MKTP.KD.ZG\",\"FP.CPI.TOTL.ZG\",\"SP.DYN.LE00.IN\");iso<-sort(unique(wb$countryISO3));stopifnot(nrow(wb)==64,length(iso)==16)\n tokens<-t(vapply(iso,function(s)wb$originalValueToken[match(paste(s,codes),paste(wb$countryISO3,wb$indicatorID))],character(4)));vals<-matrix(num(as.vector(tokens)),nrow=nrow(tokens))\n country<-list(id=paste0(iso,\":2024\"),sourceRow=1:16,originalID=iso,x=vals[,1:3,drop=FALSE],rawX=tokens[,1:3,drop=FALSE],nativeTarget=tokens[,4],y=as.integer(vals[,4]>=80),group=ifelse(is.na(vals[,1]),NA_character_,as.character(as.integer(vals[,1]>=25000))),lineage=vapply(iso,function(s)paste(wb$sourceRow[match(paste(s,codes),paste(wb$countryISO3,wb$indicatorID))],collapse=\";\"),character(1)),cat=integer(),units=c(\"constant2015USD/person\",\"annualPercent\",\"annualPercent\"))\n nls<-readnative(\"actual3613-NLS-original52-fields-groups-roles.csv\");raw<-cbind(nls$ed76,nls$age76,nls$nearc4)\n person<-list(id=paste0(\"person:\",nls$sourceRow),sourceRow=as.integer(nls$sourceRow),originalID=nls$id,x=matrix(num(as.vector(raw)),nrow=nrow(raw)),rawX=raw,nativeTarget=nls$wage76,y=as.integer(num(nls$wage76)>=500),group=ifelse(nls$black%in%c(\"\",\".\"),NA_character_,nls$black),lineage=nls$sourceRow,cat=2L,units=c(\"years\",\"years\",\"nativeCategory\"))\n ch<-readnative(\"actual3150-churn-original14-fields-groups-roles.csv\");raw<-cbind(ch[[\"Call  Failure\"]],ch$Complains,ch[[\"Subscription  Length\"]],ch[[\"Seconds of Use\"]])\n company<-list(id=paste0(\"customer:\",ch$sourceRow),sourceRow=as.integer(ch$sourceRow),originalID=rep(\"\",nrow(ch)),x=matrix(num(as.vector(raw)),nrow=nrow(raw)),rawX=raw,nativeTarget=ch$Churn,y=as.integer(ch$Churn),group=ifelse(ch[[\"Tariff Plan\"]]%in%c(\"\",\".\"),NA_character_,ch[[\"Tariff Plan\"]]),lineage=ch$sourceRow,cat=1L,units=c(\"count\",\"nativeCategory\",\"months\",\"seconds\"))\n stopifnot(nrow(nls)==3613,nrow(ch)==3150,identical(as.integer(ch$sourceRow[ch[[\"Charge  Amount\"]]==\"10\"]),c(474L,2174L,2274L,2374L,2674L,2924L,2974L)))\n result<-list(country=country,person=person,company=company)\n for(k in names(result)){d<-result[[k]];n<-length(d$id);d$eligible<-!is.na(d$y)&rowSums(is.na(d$x))==0;hash<-sha256(paste0(\"ML14-role|\",k,\"|\",d$id));rank<-integer(n);rank[order(hash,seq_len(n))]<-seq_len(n)-1L;d$plannedRole<-ifelse(rank%%5==0,\"test\",ifelse(rank%%5==1,\"validation\",\"train\"));d$role<-ifelse(d$eligible,d$plannedRole,\"excluded\");result[[k]]<-d}\n stopifnot(sum(result$person$eligible)==3017);result\n}\nfitmodel<-function(d){\n ids<-which(d$role==\"train\");p<-ncol(d$x);m<-vapply(seq_len(p),function(j)if((j-1)%in%d$cat)NA_real_ else median(d$x[ids,j]),numeric(1));z<-d$x\n for(j in seq_len(p))if(!((j-1)%in%d$cat))z[,j]<-as.numeric(z[,j]>m[j])\n keys<-apply(z,1,function(v)paste(fmt(v),collapse=\"|\"));lev<-unique(keys[ids]);mass<-vapply(lev,function(k)sum(keys[ids]==k),integer(1));positive<-vapply(lev,function(k)sum(d$y[ids][keys[ids]==k]),integer(1));prob<-(positive+1)/(mass+2);fallback<-(sum(d$y[ids])+1)/(length(ids)+2);pred<-prob[match(keys,lev)];unseen<-is.na(pred);pred[unseen]<-fallback;pred[!d$eligible]<-NA_real_;unseen[!d$eligible]<-NA\n list(ids=ids,medians=m,z=z,keys=keys,lev=lev,mass=mass,positive=positive,prob=prob,fallback=fallback,pred=pred,unseen=unseen)\n}\nmeasure<-function(d,p,ids,t=.5,cost=c(1,1)){\n use<-ids[d$eligible[ids]&!is.na(p[ids])];y<-d$y[use];a<-if(is.character(t))rep(t==\"always-positive\",length(use))else p[use]>=t\n TP<-sum(a&y==1);FP<-sum(a&y==0);FN<-sum(!a&y==1);TN<-sum(!a&y==0);P<-TP+FN;N<-FP+TN;W<-P+N;PP<-TP+FP;PN<-TN+FN;TPR<-ratio(TP,P);TNR<-ratio(TN,N);bs<-sum((p[use]-y)^2);tc<-FP*cost[1]+FN*cost[2]\n list(TP=TP,FP=FP,FN=FN,TN=TN,mass=W,positiveTargetMass=P,negativeTargetMass=N,predictedPositiveMass=PP,predictedNegativeMass=PN,prevalence=ratio(P,W),selectionRate=ratio(PP,W),accuracy=ratio(TP+TN,W),precision=ratio(TP,PP),negativePredictiveValue=ratio(TN,PN),TPR=TPR,FPR=ratio(FP,N),TNR=TNR,FNR=ratio(FN,P),F1=ratio(2*TP,2*TP+FP+FN),balancedAccuracy=if(is.na(TPR)||is.na(TNR))NA_real_ else(TPR+TNR)/2,Brier=ratio(bs,W),BrierSum=bs,totalCost=tc,meanCost=ratio(tc,W))\n}\ncurves<-function(d,p,ids){\n use<-ids[d$eligible[ids]&!is.na(p[ids])];scores<-sort(unique(p[use]),decreasing=TRUE);policies<-c(list(\"always-negative\"),as.list(scores));points<-lapply(policies,function(t){m<-measure(d,p,ids,t);c(list(policy=t),m[c(\"TP\",\"FP\",\"FN\",\"TN\",\"TPR\",\"FPR\",\"precision\")],list(recall=m$TPR))})\n pos<-use[d$y[use]==1];neg<-use[d$y[use]==0];U<-0;for(i in pos)U<-U+sum(p[i]>p[neg])+.5*sum(p[i]==p[neg])\n AP<-0;trap<-0;lastR<-0;lastP<-1\n if(length(pos)&&length(scores))for(j in seq_along(scores)){z<-points[[j+1]];AP<-AP+(z$recall-lastR)*z$precision;trap<-trap+(z$recall-lastR)*(z$precision+lastP)/2;lastR<-z$recall;lastP<-z$precision}\n list(points=points,ROC_AUC=ratio(U,length(pos)*length(neg)),averagePrecision=if(length(pos))AP else NA_real_,PRTrapezoidWithInitialPrecisionOne=if(length(pos))trap else NA_real_)\n}\ncalibrate<-function(d,p,ids){\n use<-ids[d$eligible[ids]&!is.na(p[ids])];W<-length(use);pi<-if(W)mean(d$y[use])else NA_real_;bins<-list();ECE<-rel<-res<-correction<-0\n whichbin<-findInterval(p[use],seq(0,1,.2),rightmost.closed=TRUE,all.inside=TRUE)\n for(b in 1:5){rr<-use[whichbin==b];w<-length(rr);mp<-if(w)mean(p[rr])else NA_real_;o<-if(w)mean(d$y[rr])else NA_real_;variance<-if(w)mean((p[rr]-mp)^2)else NA_real_;covariance<-if(w)mean((p[rr]-mp)*(d$y[rr]-o))else NA_real_;bc<-variance-2*covariance;gap<-mp-o\n  bins[[b]]<-list(mass=w,meanPrediction=mp,eventRate=o,gap=gap,absoluteGap=abs(gap),scoreVariance=variance,scoreTargetCovariance=covariance,withinBinCorrection=bc,rows=w,ids=d$id[rr])\n  if(w){share<-w/W;ECE<-ECE+share*abs(gap);rel<-rel+share*gap^2;res<-res+share*(o-pi)^2;correction<-correction+share*bc}\n };bs<-if(W)mean((p[use]-d$y[use])^2)else NA_real_;unc<-pi*(1-pi)\n list(bins=bins,ECE=if(W)ECE else NA_real_,Brier=bs,reliability=if(W)rel else NA_real_,resolution=if(W)res else NA_real_,uncertainty=unc,withinBinCorrection=if(W)correction else NA_real_,BrierIdentityResidual=bs-(unc-res+rel+correction))\n}\ncounts<-c(\"mass\",\"positiveTargetMass\",\"negativeTargetMass\",\"predictedPositiveMass\",\"predictedNegativeMass\");rates<-c(\"prevalence\",\"selectionRate\",\"accuracy\",\"precision\",\"negativePredictiveValue\",\"TPR\",\"FPR\",\"TNR\",\"FNR\",\"F1\",\"balancedAccuracy\",\"Brier\",\"BrierSum\",\"totalCost\",\"meanCost\")\ntables<-setNames(lapply(1:10,function(i)list()),c(\"predictions\",\"lineage\",\"fit-medians\",\"fit-cells\",\"validation-candidates\",\"test-metrics\",\"test-curves\",\"calibration-bins\",\"group-metrics\",\"chart-points\"))\nadd<-function(name,row)tables[[name]][[length(tables[[name]])+1L]]<<-row\nscalars<-function(m,keys){out<-list();for(k in keys){out[[paste0(k,\"Exact\")]]<-\"\";out[[paste0(k,\"Approx\")]]<-fmt(m[[k]])};out}\ntagrow<-function(kind,...)c(list(kind=kind),list(...))\npoint<-function(kind,chart,series,index,x,y,xunit=\"dimensionless\",yunit=\"dimensionless\",role=\"test\",tag=\"\"){add(\"chart-points\",tagrow(kind,chart=chart,series=series,index=index,xExact=\"\",xApprox=fmt(x),yExact=\"\",yApprox=fmt(y),xUnit=xunit,yUnit=yunit,role=role,tag=tag))}\nstudy<-function(kind,d){\n f<-fitmodel(d);n<-length(d$id);train<-which(d$role==\"train\");validation<-which(d$role==\"validation\");test<-which(d$role==\"test\");p<-f$pred;cv<-curves(d,p,test);cal<-calibrate(d,p,test)\n for(i in seq_len(n)){\n  reason<-if(d$eligible[i])\"\"else\"required-X-or-Y-missing\";transformed<-if(d$eligible[i])paste(fmt(f$z[i,]),collapse=\"|\")else\"\"\n  add(\"predictions\",tagrow(kind,id=d$id[i],sourceRow=d$sourceRow[i],originalID=d$originalID[i],plannedRole=d$plannedRole[i],role=d$role[i],group=ifelse(is.na(d$group[i]),\"\",d$group[i]),eligible=as.integer(d$eligible[i]),targetExact=fmt(d$y[i]),probabilityExact=\"\",probabilityApprox=fmt(p[i]),unseenCell=ifelse(is.na(f$unseen[i]),\"\",as.character(as.integer(f$unseen[i]))),transformedX=transformed,reason=reason))\n  raw<-d$rawX[i,];raw[raw%in%c(\"\",\".\")]<-\"\";nativeY<-d$nativeTarget[i];if(nativeY%in%c(\"\",\".\"))nativeY<-\"\"\n  add(\"lineage\",tagrow(kind,id=d$id[i],sourceRow=d$sourceRow[i],originalID=d$originalID[i],nativeSourceRows=d$lineage[i],rawX=paste(raw,collapse=\"|\"),nativeTarget=nativeY,derivedTarget=fmt(d$y[i]),nativeGroup=ifelse(is.na(d$group[i]),\"\",d$group[i]),plannedRole=d$plannedRole[i],role=d$role[i],eligible=as.integer(d$eligible[i]),analyticalMass=\"1\",reason=reason))\n }\n for(j in seq_len(ncol(d$x)))add(\"fit-medians\",tagrow(kind,feature=j-1,categorical=as.integer((j-1)%in%d$cat),fitRows=length(train),medianExact=\"\",medianApprox=fmt(f$medians[j]),unit=d$units[j]))\n for(j in seq_along(f$lev))add(\"fit-cells\",tagrow(kind,cell=f$lev[j],trainingRows=f$mass[j],positiveRows=f$positive[j],probabilityExact=\"\",probabilityApprox=fmt(f$prob[j]),fallbackExact=\"\",fallbackApprox=fmt(f$fallback)))\n for(j in seq_along(cv$points)){\n  z<-cv$points[[j]];t<-z$policy;add(\"test-curves\",c(tagrow(kind,point=j-1,policy=if(is.character(t))t else\"threshold\",thresholdExact=\"\",thresholdApprox=if(is.character(t))\"\"else fmt(t)),scalars(z,c(\"TP\",\"FP\",\"FN\",\"TN\",\"TPR\",\"FPR\",\"precision\",\"recall\"))))\n  point(kind,\"roc\",\"ROC\",j-1,z$FPR,z$TPR);point(kind,\"pr\",\"PR-observed\",j-1,z$recall,z$precision)\n }\n for(b in 1:5){z<-cal$bins[[b]];add(\"calibration-bins\",c(tagrow(kind,bin=b-1,leftExact=c(\"0\",\"1/5\",\"2/5\",\"3/5\",\"4/5\")[b],rightExact=c(\"1/5\",\"2/5\",\"3/5\",\"4/5\",\"1\")[b],rightClosed=as.integer(b==5),rows=z$rows,ids=paste(z$ids,collapse=\";\")),scalars(z,c(\"mass\",\"meanPrediction\",\"eventRate\",\"gap\",\"absoluteGap\",\"scoreVariance\",\"scoreTargetCovariance\",\"withinBinCorrection\"))));point(kind,\"reliability\",\"Binary event rate\",b-1,z$meanPrediction,z$eventRate,tag=paste0(\"rows=\",z$rows))}\n for(j in seq_along(test)){i<-test[j];point(kind,\"test-scores\",\"Training-fitted probability\",j-1,j,p[i],\"test-row position\",\"probability\",tag=d$id[i]);point(kind,\"test-scores\",\"Observed Y\",j-1,j,d$y[i],\"test-row position\",\"binary target\",tag=d$id[i])}\n scenarioNames<-c(\"equal\",\"miss-five\",\"alarm-five\");costs<-list(c(1,1),c(1,5),c(5,1))\n for(s in 1:3){name<-scenarioNames[s];cost<-costs[[s]];grid<-c(list(\"always-negative\"),as.list(sort(unique(p[validation]),decreasing=TRUE)));candidates<-lapply(grid,function(t)measure(d,p,validation,t,cost));values<-vapply(candidates,function(m)m$meanCost,numeric(1));best<-which(values<=min(values)+1e-12)[1];chosen<-grid[[best]];ev<-measure(d,p,test,chosen,cost)\n  for(j in seq_along(grid)){t<-grid[[j]];m<-candidates[[j]];cell<-setNames(lapply(c(\"TP\",\"FP\",\"FN\",\"TN\"),function(k)fmt(m[[k]])),paste0(c(\"TP\",\"FP\",\"FN\",\"TN\"),\"Exact\"));add(\"validation-candidates\",c(tagrow(kind,scenario=name,candidate=j-1,selected=as.integer(j==best),policy=if(is.character(t))t else\"threshold\",thresholdExact=\"\",thresholdApprox=if(is.character(t))\"\"else fmt(t),feasible=1,reasons=\"\"),cell,scalars(m,c(counts,\"TPR\",\"FPR\",\"precision\",\"meanCost\",\"totalCost\"))));point(kind,\"validation-cost\",name,j-1,j-1,m$meanCost,\"candidate index\",\"hypothetical cost units/mass\",\"validation\",if(is.character(t))t else fmt(t))}\n  m<-c(ev,cv[c(\"ROC_AUC\",\"averagePrecision\",\"PRTrapezoidWithInitialPrecisionOne\")],cal[c(\"ECE\",\"reliability\",\"resolution\",\"uncertainty\",\"withinBinCorrection\",\"BrierIdentityResidual\")])\n  for(k in c(\"TP\",\"FP\",\"FN\",\"TN\",counts,rates,\"ROC_AUC\",\"averagePrecision\",\"PRTrapezoidWithInitialPrecisionOne\",\"ECE\",\"reliability\",\"resolution\",\"uncertainty\",\"withinBinCorrection\",\"BrierIdentityResidual\")){\n   unit<-if(k%in%c(\"TP\",\"FP\",\"FN\",\"TN\",counts))\"rows\"else if(k==\"totalCost\")\"hypothetical cost units\"else if(k==\"meanCost\")\"hypothetical cost units/mass\"else if(k==\"BrierSum\")\"sum squared-probability loss\"else\"dimensionless\"\n   add(\"test-metrics\",tagrow(kind,scenario=name,metric=k,valueExact=\"\",valueApprox=fmt(m[[k]]),unit=unit))\n  }\n  lev<-unique(d$group[test][!is.na(d$group[test])]);sets<-c(list(test),lapply(lev,function(g)test[!is.na(d$group[test])&d$group[test]==g]),list(test[is.na(d$group[test])]))\n  types<-c(\"overall\",rep(\"known\",length(lev)),\"unknown\");tokens<-c(\"all\",lev,\"\")\n  for(j in seq_along(sets)){ids<-sets[[j]];m<-measure(d,p,ids,chosen,cost);cell<-setNames(lapply(c(\"TP\",\"FP\",\"FN\",\"TN\"),function(k)fmt(m[[k]])),paste0(c(\"TP\",\"FP\",\"FN\",\"TN\"),\"Exact\"));add(\"group-metrics\",c(tagrow(kind,scenario=name,groupType=types[j],groupToken=tokens[j],retainedRows=length(ids)),cell,scalars(m,c(counts,rates))));if(types[j]==\"known\")point(kind,\"group-TPR\",name,j-2,j-2,m$TPR,\"declared group position\",\"TPR\",tag=tokens[j])}\n }\n invisible(NULL)\n}\n\n# Fixed finite inputs only; not the complete web input/budget validator.\nqnum<-function(v){if(is.null(v))return(NA_real_);if(is.logical(v))return(as.numeric(v));s<-as.character(v);if(grepl(\"/\",s,fixed=TRUE)){a<-strsplit(s,\"/\",fixed=TRUE)[[1]];return(as.numeric(a[1])/as.numeric(a[2]))};as.numeric(s)}\nrowsG<-function(raw){\n n<-length(raw);get<-function(r,k,default=NULL)if(is.null(r[[k]]))default else r[[k]]\n id<-vapply(raw,function(r)as.character(r$id),character(1));p<-vapply(raw,function(r)qnum(r$score),numeric(1));y<-vapply(raw,function(r)qnum(r$y),numeric(1));w<-vapply(raw,function(r)qnum(get(r,\"weight\",\"1\")),numeric(1));role<-vapply(raw,function(r)get(r,\"role\",\"evaluation\"),character(1));group<-vapply(raw,function(r)as.character(get(r,\"group\",NA_character_)),character(1))\n stopifnot(all(w>=0),all(is.na(p)|(p>=0&p<=1)),all(is.na(y)|y%in%c(0,1)),!anyDuplicated(id));list(id=id,p=p,y=y,w=w,role=role,group=group,eligible=!is.na(p)&!is.na(y)&w>0&role!=\"excluded\")\n}\nscopeG<-function(d,role=\"all\")if(role==\"all\")seq_along(d$id)else which(d$role==role)\nmetricsG<-function(d,ids,t=.5,cost=c(1,1)){\n use<-ids[d$eligible[ids]];p<-d$p[use];y<-d$y[use];w<-d$w[use];a<-if(is.character(t))rep(t==\"always-positive\",length(use))else p>=t\n TP<-sum(w[a&y==1]);FP<-sum(w[a&y==0]);FN<-sum(w[!a&y==1]);TN<-sum(w[!a&y==0]);P<-TP+FN;N<-FP+TN;W<-P+N;PP<-TP+FP;PN<-TN+FN;TPR<-ratio(TP,P);TNR<-ratio(TN,N);bs<-sum(w*(p-y)^2);tc<-FP*cost[1]+FN*cost[2]\n list(confusion=list(TP=TP,FP=FP,FN=FN,TN=TN),mass=W,positiveTargetMass=P,negativeTargetMass=N,predictedPositiveMass=PP,predictedNegativeMass=PN,prevalence=ratio(P,W),selectionRate=ratio(PP,W),accuracy=ratio(TP+TN,W),precision=ratio(TP,PP),negativePredictiveValue=ratio(TN,PN),TPR=TPR,FPR=ratio(FP,N),TNR=TNR,FNR=ratio(FN,P),F1=ratio(2*TP,2*TP+FP+FN),balancedAccuracy=if(is.na(TPR)||is.na(TNR))NA_real_ else(TPR+TNR)/2,Brier=ratio(bs,W),BrierSum=bs,totalCost=tc,meanCost=ratio(tc,W),bayesThreshold=ratio(cost[1],sum(cost)))\n}\ncurvesG<-function(d,ids){\n use<-ids[d$eligible[ids]];grid<-c(list(\"always-negative\"),as.list(sort(unique(d$p[use]),decreasing=TRUE)));points<-lapply(grid,function(t){m<-metricsG(d,ids,t);c(list(policy=t),m$confusion,m[c(\"TPR\",\"FPR\",\"precision\")],list(recall=m$TPR))});pos<-use[d$y[use]==1];neg<-use[d$y[use]==0];P<-sum(d$w[pos]);N<-sum(d$w[neg]);U<-0\n for(i in pos)U<-U+d$w[i]*sum(d$w[neg]*((d$p[i]>d$p[neg])+.5*(d$p[i]==d$p[neg])))\n AP<-trap<-lastR<-0;lastP<-1\n if(P&&length(grid)>1)for(j in 2:length(grid)){z<-points[[j]];AP<-AP+(z$recall-lastR)*z$precision;trap<-trap+(z$recall-lastR)*(z$precision+lastP)/2;lastR<-z$recall;lastP<-z$precision}\n list(points=points,ROC_AUC=ratio(U,P*N),averagePrecision=if(P)AP else NA_real_,PRTrapezoidWithInitialPrecisionOne=if(P)trap else NA_real_)\n}\nchooseG<-function(d,a,cost){\n role<-if(is.null(a$selectionRole))\"validation\"else a$selectionRole;er<-if(is.null(a$evaluationRole))\"test\"else a$evaluationRole;ids<-scopeG(d,role);use<-ids[d$eligible[ids]];stopifnot(length(use)>0);grid<-if(is.null(a$thresholds))c(list(\"always-negative\"),as.list(sort(unique(d$p[use]),decreasing=TRUE)))else lapply(a$thresholds,function(t)if(t%in%c(\"always-negative\",\"always-positive\"))t else qnum(t))\n candidates<-lapply(seq_along(grid),function(j){m<-metricsG(d,ids,grid[[j]],cost);feasible<-TRUE;if(!is.null(a$minTPR))feasible<-feasible&&!is.na(m$TPR)&&m$TPR>=qnum(a$minTPR);if(!is.null(a$maxFPR))feasible<-feasible&&!is.na(m$FPR)&&m$FPR<=qnum(a$maxFPR);list(index=j-1,policy=grid[[j]],metrics=m,feasible=feasible)})\n good<-which(vapply(candidates,function(c)c$feasible,logical(1)));best<-NA_integer_;if(length(good)){v<-vapply(candidates[good],function(c)c$metrics$meanCost,numeric(1));best<-good[which(v<=min(v)+1e-12)[1]]}\n list(selectedIndex=if(is.na(best))NA_integer_ else best-1,selectedPolicy=if(is.na(best))NULL else grid[[best]],selectedValidation=if(is.na(best))NULL else candidates[[best]]$metrics,candidates=candidates,evaluation=if(is.na(best)||er==\"none\")NULL else metricsG(d,scopeG(d,er),grid[[best]],cost))\n}\ncalibrateG<-function(d,ids,edges){\n use<-ids[d$eligible[ids]];W<-sum(d$w[use]);pi<-ratio(sum(d$w[use]*d$y[use]),W);bins<-list();ECE<-rel<-res<-correction<-0;assign<-findInterval(d$p[use],edges,rightmost.closed=TRUE,all.inside=TRUE)\n for(b in seq_len(length(edges)-1)){rr<-use[assign==b];w<-sum(d$w[rr]);mp<-ratio(sum(d$w[rr]*d$p[rr]),w);o<-ratio(sum(d$w[rr]*d$y[rr]),w);variance<-if(w)sum(d$w[rr]*(d$p[rr]-mp)^2)/w else NA_real_;covariance<-if(w)sum(d$w[rr]*(d$p[rr]-mp)*(d$y[rr]-o))/w else NA_real_;bc<-variance-2*covariance;gap<-mp-o;bins[[b]]<-list(index=b-1,mass=w,meanPrediction=mp,eventRate=o,scoreVariance=variance,scoreTargetCovariance=covariance,withinBinCorrection=bc,ids=d$id[rr])\n  if(w){s<-w/W;ECE<-ECE+s*abs(gap);rel<-rel+s*gap^2;res<-res+s*(o-pi)^2;correction<-correction+s*bc}\n };bs<-ratio(sum(d$w[use]*(d$p[use]-d$y[use])^2),W);unc<-pi*(1-pi);list(bins=bins,Brier=bs,ECE=if(W)ECE else NA_real_,uncertainty=unc,reliability=if(W)rel else NA_real_,resolution=if(W)res else NA_real_,withinBinCorrection=if(W)correction else NA_real_,BrierIdentityResidual=bs-(unc-res+rel+correction))\n}\ngroupsG<-function(d,ids,t,cost){\n lev<-unique(d$group[ids][!is.na(d$group[ids])]);groups<-lapply(lev,function(g)list(group=g,metrics=metricsG(d,ids[!is.na(d$group[ids])&d$group[ids]==g],t,cost)));overall<-metricsG(d,ids,t,cost);unknown<-metricsG(d,ids[is.na(d$group[ids])],t,cost);gaps<-list()\n for(k in c(\"prevalence\",\"selectionRate\",\"TPR\",\"FPR\",\"precision\",\"accuracy\",\"meanCost\")){use<-Filter(function(g)g$metrics$mass>0,groups);v<-vapply(use,function(g)g$metrics[[k]],numeric(1));gaps[[k]]<-if(length(use)<2||anyNA(v))NA_real_ else max(v)-min(v)}\n list(overall=overall,groups=groups,unknownGroup=unknown,gaps=gaps,partitionMassResidual=overall$mass-unknown$mass-sum(vapply(groups,function(g)g$metrics$mass,numeric(1))))\n}\nsvgFixed<-function(file,points,title,xlabel,ylabel,legend){\n finite<-points[points$y!=\"undefined\"&points$x!=\"undefined\",,drop=FALSE];x<-as.numeric(finite$x);y<-as.numeric(finite$y);xmin<-if(length(x))min(x)else 0;xmax<-if(length(x))max(x)else 1;ymin<-min(c(0,y));ymax<-max(c(0,y));if(xmin==xmax){xmin<-xmin-.5;xmax<-xmax+.5};if(ymin==ymax)ymax<-ymin+1;X<-function(v)85+(v-xmin)/(xmax-xmin)*480;Y<-function(v)278-(v-ymin)/(ymax-ymin)*175\n esc<-function(s){s<-gsub(\"&\",\"&amp;\",s,fixed=TRUE);s<-gsub(\"<\",\"&lt;\",s,fixed=TRUE);gsub(\">\",\"&gt;\",s,fixed=TRUE)};s<-'<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"620\" height=\"360\" viewBox=\"0 0 620 360\"><rect width=\"620\" height=\"360\" fill=\"white\"/><g font-family=\"Arial, sans-serif\" font-size=\"13\" fill=\"#17324d\">'\n lines<-strwrap(title,width=65);for(i in seq_along(lines))s<-paste0(s,'<text x=\"25\" y=\"',24+(i-1)*18,'\">',esc(lines[i]),'</text>');colors<-c(\"#176b9b\",\"#b85e18\",\"#437e4d\")\n for(i in seq_along(legend))s<-paste0(s,'<circle cx=\"',30+(i-1)*250,'\" cy=\"76\" r=\"4\" fill=\"',colors[(i-1)%%3+1],'\"/><text x=\"',42+(i-1)*250,'\" y=\"80\">',esc(legend[i]),'</text>')\n s<-paste0(s,'<path d=\"M85 98V278H575\" fill=\"none\" stroke=\"#52677d\"/><text text-anchor=\"middle\" x=\"325\" y=\"338\">',esc(xlabel),'</text><text text-anchor=\"middle\" transform=\"translate(21,190) rotate(-90)\">',esc(ylabel),'</text>')\n for(i in 0:4){xx<-xmin+(xmax-xmin)*i/4;yy<-ymin+(ymax-ymin)*i/4;s<-paste0(s,'<text text-anchor=\"middle\" x=\"',sprintf(\"%.9g\",X(xx)),'\" y=\"305\">',sprintf(\"%.4g\",xx),'</text><text text-anchor=\"end\" x=\"77\" y=\"',sprintf(\"%.9g\",Y(yy)+4),'\">',sprintf(\"%.4g\",yy),'</text>')}\n for(i in seq_len(nrow(finite)))s<-paste0(s,'<circle cx=\"',sprintf(\"%.9g\",X(x[i])),'\" cy=\"',sprintf(\"%.9g\",Y(y[i])),'\" r=\"3\" fill=\"',colors[as.integer(finite$series[i])%%3+1],'\"/>');writeLines(paste0(s,'</g></svg>'),file,useBytes=TRUE)\n}\nfixedRun<-function(){\n api<-FIXED$api;a<-FIXED$args;summary<-list();points<-list();xlabel<-\"Declared index\";ylabel<-\"Value\";legend<-\"Declared result\"\n metric<-function(name,v,unit=\"dimensionless\"){if(is.null(v))v<-NA_real_;summary[[length(summary)+1L]]<<-data.frame(metric=name,value=if(is.na(v))\"undefined\"else sprintf(\"%.9g\",v),exactValue=\"\",unit=unit,defined=as.integer(!is.na(v)),stringsAsFactors=FALSE)}\n pt<-function(i,x,y,id=\"\",series=0){points[[length(points)+1L]]<<-data.frame(series=series,index=i,xExact=\"\",x=if(is.na(x))\"undefined\"else sprintf(\"%.9g\",x),yExact=\"\",y=if(is.na(y))\"undefined\"else sprintf(\"%.9g\",y),id=as.character(id),stringsAsFactors=FALSE)}\n if(api==\"realdata\"){\n  native<-loadData()[[a$kind]];fit<-fitmodel(native);d<-list(id=native$id,p=fit$pred,y=native$y,w=rep(1,length(native$id)),role=native$role,group=native$group,eligible=native$eligible);scenarios<-list()\n  for(j in 1:3){name<-c(\"equal\",\"miss-five\",\"alarm-five\")[j];cst<-list(c(1,1),c(1,5),c(5,1))[[j]];sel<-chooseG(d,list(),cst);scenarios[[j]]<-list(name=name,selection=sel);metric(paste0(name,\"Threshold\"),sel$selectedPolicy);metric(paste0(name,\"TestCost\"),sel$evaluation$meanCost,\"hypothetical cost units/mass\")}\n  ids<-scopeG(d,\"test\");cv<-curvesG(d,ids);cal<-calibrateG(d,ids,seq(0,1,.2));metric(\"testAUC\",cv$ROC_AUC);metric(\"testAP\",cv$averagePrecision);metric(\"testBrier\",cal$Brier);metric(\"eligibleRows\",sum(d$eligible),\"rows\")\n  for(j in seq_along(ids)){i<-ids[j];pt(j-1,j,d$p[i],d$id[i],0);pt(j-1,j,d$y[i],d$id[i],1)}\n  full<-list(kind=a$kind,fit=fit,scenarios=scenarios,testCurves=cv,testCalibration=cal,rowsScored=d);xlabel<-\"Test row, native order\";ylabel<-\"Y or probability\";legend<-c(\"Training-fitted probability\",\"Observed Y\")\n }else{\n  d<-rowsG(a$rows);role<-if(is.null(a$role))\"all\"else a$role;ids<-scopeG(d,role);cost<-if(is.null(a$costs))c(1,1)else c(qnum(a$costs$falsePositive),qnum(a$costs$falseNegative));t<-if(is.null(a$threshold)).5 else if(a$threshold%in%c(\"always-positive\",\"always-negative\"))a$threshold else qnum(a$threshold)\n  if(api==\"metrics\"){\n   full<-metricsG(d,ids,t,cost);for(k in c(\"mass\",\"accuracy\",\"precision\",\"TPR\",\"FPR\",\"F1\",\"Brier\",\"meanCost\"))metric(k,full[[k]],if(k==\"mass\")\"mass\"else if(k==\"meanCost\")\"hypothetical cost units/mass\"else\"dimensionless\");metric(\"BayesThreshold\",full$bayesThreshold)\n   for(i in 1:4)pt(i-1,i-1,full$confusion[[i]],names(full$confusion)[i]);xlabel<-\"TP / FP / FN / TN positions\";ylabel<-\"Analytical mass\"\n  }else if(api==\"curves\"){\n   full<-curvesG(d,ids);for(k in c(\"ROC_AUC\",\"averagePrecision\",\"PRTrapezoidWithInitialPrecisionOne\"))metric(k,full[[k]])\n   for(j in seq_along(full$points)){p<-full$points[[j]];pt(j-1,p$FPR,p$TPR,if(is.character(p$policy))p$policy else sprintf(\"%.17g\",p$policy))};xlabel<-\"False positive rate\";ylabel<-\"True positive rate\";legend<-\"Observed ROC operating points\"\n  }else if(api==\"choose\"){\n   full<-chooseG(d,a,cost);metric(\"selectedIndex\",full$selectedIndex,\"candidate index\");metric(\"minimumCost\",if(is.null(full$selectedValidation))NULL else full$selectedValidation$meanCost,\"hypothetical cost units/mass\");metric(\"feasible\",as.integer(!is.na(full$selectedIndex)),\"indicator\")\n   for(c in full$candidates)pt(c$index,c$index,c$metrics$meanCost,if(is.character(c$policy))c$policy else sprintf(\"%.17g\",c$policy));xlabel<-\"Validation candidate\";ylabel<-\"Assumed cost / mass\";legend<-\"Validation candidate costs\"\n  }else if(api==\"calibrate\"){\n   edges<-if(is.null(a$binEdges))seq(0,1,.2)else vapply(a$binEdges,qnum,numeric(1));full<-calibrateG(d,ids,edges);for(k in c(\"ECE\",\"Brier\",\"uncertainty\",\"resolution\",\"reliability\",\"withinBinCorrection\",\"BrierIdentityResidual\"))metric(k,full[[k]])\n   for(b in full$bins)pt(b$index,b$meanPrediction,b$eventRate,paste0(\"bin:\",b$index));xlabel<-\"Bin mean forecast\";ylabel<-\"Bin event rate\";legend<-\"Binary-event reliability\"\n  }else if(api==\"groups\"){\n   full<-groupsG(d,ids,t,cost);metric(\"overallTPR\",full$overall$TPR);metric(\"TPRGap\",full$gaps$TPR);metric(\"precisionGap\",full$gaps$precision);metric(\"unknownMass\",full$unknownGroup$mass,\"mass\");metric(\"partitionResidual\",full$partitionMassResidual,\"mass\")\n   for(j in seq_along(full$groups))pt(j-1,j-1,full$groups[[j]]$metrics$TPR,full$groups[[j]]$group);xlabel<-\"Declared group position\";ylabel<-\"True positive rate\";legend<-\"Known-group TPR\"\n  }else stop(\"unknown declared fixed API\")\n }\n sm<-do.call(rbind,summary);pp<-do.call(rbind,points);write.csv(sm,file.path(outDir,\"summary.csv\"),row.names=FALSE,na=\"\");write.csv(pp,file.path(outDir,\"plot-points.csv\"),row.names=FALSE,na=\"\");svgFixed(file.path(outDir,\"plot.svg\"),pp,FIXED$title,xlabel,ylabel,legend);dput(list(api=api,variant=FIXED$variant,input=FIXED$args,arithmetic=\"Base-R binary64 fixed example; not an exact rational general validator\",result=full),file=file.path(outDir,\"full.txt\"));cat(\"PASS\",api,FIXED$variant,\"summary\",nrow(sm),\"points\",nrow(pp),\"\\n\")\n}\n\nFIXED<-list(api=\"metrics\",variant=\"zero-cost\",args=list(rows=list(list(id=\"a\",score=\".9\",y=1,group=\"A\"),list(id=\"b\",score=\".8\",y=1,group=\"A\"),list(id=\"c\",score=\".8\",y=0,group=\"A\"),list(id=\"d\",score=\".6\",y=0,group=\"B\"),list(id=\"e\",score=\".4\",y=1,group=\"B\"),list(id=\"f\",score=\".1\",y=0,group=\"B\")),costs=list(falsePositive=\"0\",falseNegative=\"0\")),title=\"Both hypothetical costs zero; Bayes ratio undefined\")\nfixedRun()\n",
        "input": {
          "rows": [
            {
              "id": "a",
              "score": ".9",
              "y": 1,
              "group": "A"
            },
            {
              "id": "b",
              "score": ".8",
              "y": 1,
              "group": "A"
            },
            {
              "id": "c",
              "score": ".8",
              "y": 0,
              "group": "A"
            },
            {
              "id": "d",
              "score": ".6",
              "y": 0,
              "group": "B"
            },
            {
              "id": "e",
              "score": ".4",
              "y": 1,
              "group": "B"
            },
            {
              "id": "f",
              "score": ".1",
              "y": 0,
              "group": "B"
            }
          ],
          "costs": {
            "falsePositive": "0",
            "falseNegative": "0"
          }
        },
        "inputFiles": [],
        "returnCode": 0,
        "expectedFailure": false,
        "stdout": "PASS metrics zero-cost summary 9 points 4 \n",
        "stderr": "During startup - Warning messages:\n1: Setting LC_COLLATE=C.UTF-8 failed \n2: Setting LC_CTYPE=C.UTF-8 failed \n3: Setting LC_MONETARY=C.UTF-8 failed \n4: Setting LC_TIME=C.UTF-8 failed \n",
        "summary": {
          "mass": "6",
          "accuracy": "0.5",
          "precision": "0.5",
          "TPR": "0.666666667",
          "FPR": "0.666666667",
          "F1": "0.571428571",
          "Brier": "0.236666667",
          "meanCost": "0",
          "BayesThreshold": "undefined"
        },
        "summaryRows": [
          {
            "metric": "mass",
            "value": "6",
            "exactValue": "",
            "unit": "mass",
            "defined": "1"
          },
          {
            "metric": "accuracy",
            "value": "0.5",
            "exactValue": "",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "precision",
            "value": "0.5",
            "exactValue": "",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "TPR",
            "value": "0.666666667",
            "exactValue": "",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "FPR",
            "value": "0.666666667",
            "exactValue": "",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "F1",
            "value": "0.571428571",
            "exactValue": "",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "Brier",
            "value": "0.236666667",
            "exactValue": "",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "meanCost",
            "value": "0",
            "exactValue": "",
            "unit": "hypothetical cost units/mass",
            "defined": "1"
          },
          {
            "metric": "BayesThreshold",
            "value": "undefined",
            "exactValue": "",
            "unit": "dimensionless",
            "defined": "0"
          }
        ],
        "plotPoints": [
          {
            "series": "0",
            "index": "0",
            "xExact": "",
            "x": "0",
            "yExact": "",
            "y": "2",
            "id": "TP"
          },
          {
            "series": "0",
            "index": "1",
            "xExact": "",
            "x": "1",
            "yExact": "",
            "y": "2",
            "id": "FP"
          },
          {
            "series": "0",
            "index": "2",
            "xExact": "",
            "x": "2",
            "yExact": "",
            "y": "1",
            "id": "FN"
          },
          {
            "series": "0",
            "index": "3",
            "xExact": "",
            "x": "3",
            "yExact": "",
            "y": "1",
            "id": "TN"
          }
        ],
        "plotFile": "ml14-fixed-results/metrics-zero-cost-r/plot.svg",
        "plotSHA256": "264f725b86aa215398093442a1105c59c98fec2161746ab278e76c814f558ff5",
        "files": [
          {
            "file": "ml14-fixed-results/metrics-zero-cost-r/full.txt",
            "sha256": "803ac0480abb4e44cfd1150e72deebcc073b79b009a1032fa7f186cb14017fcf",
            "bytes": 1192
          },
          {
            "file": "ml14-fixed-results/metrics-zero-cost-r/plot-points.csv",
            "sha256": "3e4efc2ce063d94002cf433130b38776be00fa34b5cf46f731f17c94f9c71eaf",
            "bytes": 145
          },
          {
            "file": "ml14-fixed-results/metrics-zero-cost-r/plot.svg",
            "sha256": "264f725b86aa215398093442a1105c59c98fec2161746ab278e76c814f558ff5",
            "bytes": 1302
          },
          {
            "file": "ml14-fixed-results/metrics-zero-cost-r/summary.csv",
            "sha256": "9915ecc5461c38a078ac6194d03850c5d2f69a464cd2214b0d581e03f29bcb47",
            "bytes": 423
          }
        ],
        "scope": "Actually executed standalone fixed example, Python exact Fraction versus base-R binary64. Approximate R residuals retained; not universal exact arithmetic/web validation/native UI. Source programs read factual3CSV only."
      },
      "reject-negative-weight": {
        "api": "metrics",
        "variant": "reject-negative-weight",
        "language": "r",
        "title": "Reject a declared negative analytical mass",
        "codeFile": "ml14-code/metrics-reject-negative-weight.R",
        "codeSHA256": "e148ec9e0a0702b75760d625b0d6730b599b2116a37316f70668396e10754a25",
        "code": "# ML14 standalone public counterpart, base R only.\n# Inputs are only the three factual CSVs; derived columns/previous model answers unused.\n# Binary64 arithmetic, not arbitrary-precision Fraction. At numerical cost ties\n# within 1e-12 retain the earliest candidate. Exact claims belong to Python/web.\n# SHA256 infrastructure below is reused verbatim from the previous public study.\nargs<-commandArgs(trailingOnly=TRUE);filearg<-grep(\"^--file=\",commandArgs(),value=TRUE)\nhere<-if(dir.exists(\"ml14-sources\"))getwd()else if(length(filearg))dirname(normalizePath(sub(\"^--file=\",\"\",filearg[1])))else getwd()\noption<-function(key,default){i<-match(key,args);if(is.na(i))default else args[i+1]}\nsourceDir<-option(\"--source\",file.path(here,\"ml14-sources\"));outDir<-option(\"--out\",file.path(getwd(),\"ml14-r-results\"));dir.create(outDir,recursive=TRUE,showWarnings=FALSE)\nnum<-function(x){x[x%in%c(\"\",\".\")]<-NA_character_;as.numeric(x)}\nfmt<-function(x)ifelse(is.na(x),\"\",sprintf(\"%.17g\",x))\nratio<-function(a,b)if(b==0)NA_real_ else a/b\nreadnative<-function(name)read.csv(file.path(sourceDir,name),check.names=FALSE,colClasses=\"character\",na.strings=character(),stringsAsFactors=FALSE)\n# Vectorized SHA256 for the short ASCII keys used in this study.\n# Unsigned words use exact integer-valued doubles; bit operations use safe\n# 16-bit halves, avoiding R's reserved signed-INT_MIN/NA representation.\nMOD<-2^32\nxor32<-function(a,b) as.double(bitwXor(as.integer(floor(a/65536)),as.integer(floor(b/65536))))*65536+as.double(bitwXor(as.integer(a%%65536),as.integer(b%%65536)))\nand32<-function(a,b) as.double(bitwAnd(as.integer(floor(a/65536)),as.integer(floor(b/65536))))*65536+as.double(bitwAnd(as.integer(a%%65536),as.integer(b%%65536)))\nrot<-function(x,n) floor(x/2^n)+(x%%2^n)*2^(32-n)\nxor3<-function(a,b,c) xor32(xor32(a,b),c)\nK<-c(0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5,0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967,0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070,0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3,0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2)\nsha256<-function(strings) {\n n<-length(strings);bytes<-matrix(0,n,64)\n for(i in seq_len(n)) {v<-utf8ToInt(strings[i]);stopifnot(length(v)<56,all(v<128));if(length(v)) bytes[i,seq_along(v)]<-v;bytes[i,length(v)+1]<-128;bits<-length(v)*8;bytes[i,61:64]<-c(floor(bits/2^24)%%256,floor(bits/2^16)%%256,floor(bits/256)%%256,bits%%256)}\n w<-matrix(0,n,64)\n for(j in 1:16) {b<-4*(j-1)+1;w[,j]<-bytes[,b]*2^24+bytes[,b+1]*2^16+bytes[,b+2]*256+bytes[,b+3]}\n for(j in 17:64) {s0<-xor3(rot(w[,j-15],7),rot(w[,j-15],18),floor(w[,j-15]/8));s1<-xor3(rot(w[,j-2],17),rot(w[,j-2],19),floor(w[,j-2]/1024));w[,j]<-(w[,j-16]+s0+w[,j-7]+s1)%%MOD}\n init<-c(0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19)\n state<-lapply(init,function(v) rep(v,n));a<-state[[1]];b<-state[[2]];c<-state[[3]];d<-state[[4]];e<-state[[5]];f<-state[[6]];g<-state[[7]];h<-state[[8]]\n for(j in 1:64) {S1<-xor3(rot(e,6),rot(e,11),rot(e,25));ch<-xor32(and32(e,f),and32(MOD-1-e,g));t1<-(h+S1+ch+K[j]+w[,j])%%MOD;S0<-xor3(rot(a,2),rot(a,13),rot(a,22));maj<-xor3(and32(a,b),and32(a,c),and32(b,c));t2<-(S0+maj)%%MOD;h<-g;g<-f;f<-e;e<-(d+t1)%%MOD;d<-c;c<-b;b<-a;a<-(t1+t2)%%MOD}\n end<-list(a,b,c,d,e,f,g,h);hex<-lapply(1:8,function(j){v<-(end[[j]]+init[j])%%MOD;paste0(sprintf(\"%04x\",as.integer(floor(v/65536))),sprintf(\"%04x\",as.integer(v%%65536)))})\n do.call(paste0,hex)\n}\nstopifnot(identical(sha256(c(\"abc\",\"\")),c(\"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad\",\"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855\")))\n\nloadData<-function(){\n wb<-readnative(\"actual64-country-four-indicators-original-2024.csv\");codes<-c(\"NY.GDP.PCAP.KD\",\"NY.GDP.MKTP.KD.ZG\",\"FP.CPI.TOTL.ZG\",\"SP.DYN.LE00.IN\");iso<-sort(unique(wb$countryISO3));stopifnot(nrow(wb)==64,length(iso)==16)\n tokens<-t(vapply(iso,function(s)wb$originalValueToken[match(paste(s,codes),paste(wb$countryISO3,wb$indicatorID))],character(4)));vals<-matrix(num(as.vector(tokens)),nrow=nrow(tokens))\n country<-list(id=paste0(iso,\":2024\"),sourceRow=1:16,originalID=iso,x=vals[,1:3,drop=FALSE],rawX=tokens[,1:3,drop=FALSE],nativeTarget=tokens[,4],y=as.integer(vals[,4]>=80),group=ifelse(is.na(vals[,1]),NA_character_,as.character(as.integer(vals[,1]>=25000))),lineage=vapply(iso,function(s)paste(wb$sourceRow[match(paste(s,codes),paste(wb$countryISO3,wb$indicatorID))],collapse=\";\"),character(1)),cat=integer(),units=c(\"constant2015USD/person\",\"annualPercent\",\"annualPercent\"))\n nls<-readnative(\"actual3613-NLS-original52-fields-groups-roles.csv\");raw<-cbind(nls$ed76,nls$age76,nls$nearc4)\n person<-list(id=paste0(\"person:\",nls$sourceRow),sourceRow=as.integer(nls$sourceRow),originalID=nls$id,x=matrix(num(as.vector(raw)),nrow=nrow(raw)),rawX=raw,nativeTarget=nls$wage76,y=as.integer(num(nls$wage76)>=500),group=ifelse(nls$black%in%c(\"\",\".\"),NA_character_,nls$black),lineage=nls$sourceRow,cat=2L,units=c(\"years\",\"years\",\"nativeCategory\"))\n ch<-readnative(\"actual3150-churn-original14-fields-groups-roles.csv\");raw<-cbind(ch[[\"Call  Failure\"]],ch$Complains,ch[[\"Subscription  Length\"]],ch[[\"Seconds of Use\"]])\n company<-list(id=paste0(\"customer:\",ch$sourceRow),sourceRow=as.integer(ch$sourceRow),originalID=rep(\"\",nrow(ch)),x=matrix(num(as.vector(raw)),nrow=nrow(raw)),rawX=raw,nativeTarget=ch$Churn,y=as.integer(ch$Churn),group=ifelse(ch[[\"Tariff Plan\"]]%in%c(\"\",\".\"),NA_character_,ch[[\"Tariff Plan\"]]),lineage=ch$sourceRow,cat=1L,units=c(\"count\",\"nativeCategory\",\"months\",\"seconds\"))\n stopifnot(nrow(nls)==3613,nrow(ch)==3150,identical(as.integer(ch$sourceRow[ch[[\"Charge  Amount\"]]==\"10\"]),c(474L,2174L,2274L,2374L,2674L,2924L,2974L)))\n result<-list(country=country,person=person,company=company)\n for(k in names(result)){d<-result[[k]];n<-length(d$id);d$eligible<-!is.na(d$y)&rowSums(is.na(d$x))==0;hash<-sha256(paste0(\"ML14-role|\",k,\"|\",d$id));rank<-integer(n);rank[order(hash,seq_len(n))]<-seq_len(n)-1L;d$plannedRole<-ifelse(rank%%5==0,\"test\",ifelse(rank%%5==1,\"validation\",\"train\"));d$role<-ifelse(d$eligible,d$plannedRole,\"excluded\");result[[k]]<-d}\n stopifnot(sum(result$person$eligible)==3017);result\n}\nfitmodel<-function(d){\n ids<-which(d$role==\"train\");p<-ncol(d$x);m<-vapply(seq_len(p),function(j)if((j-1)%in%d$cat)NA_real_ else median(d$x[ids,j]),numeric(1));z<-d$x\n for(j in seq_len(p))if(!((j-1)%in%d$cat))z[,j]<-as.numeric(z[,j]>m[j])\n keys<-apply(z,1,function(v)paste(fmt(v),collapse=\"|\"));lev<-unique(keys[ids]);mass<-vapply(lev,function(k)sum(keys[ids]==k),integer(1));positive<-vapply(lev,function(k)sum(d$y[ids][keys[ids]==k]),integer(1));prob<-(positive+1)/(mass+2);fallback<-(sum(d$y[ids])+1)/(length(ids)+2);pred<-prob[match(keys,lev)];unseen<-is.na(pred);pred[unseen]<-fallback;pred[!d$eligible]<-NA_real_;unseen[!d$eligible]<-NA\n list(ids=ids,medians=m,z=z,keys=keys,lev=lev,mass=mass,positive=positive,prob=prob,fallback=fallback,pred=pred,unseen=unseen)\n}\nmeasure<-function(d,p,ids,t=.5,cost=c(1,1)){\n use<-ids[d$eligible[ids]&!is.na(p[ids])];y<-d$y[use];a<-if(is.character(t))rep(t==\"always-positive\",length(use))else p[use]>=t\n TP<-sum(a&y==1);FP<-sum(a&y==0);FN<-sum(!a&y==1);TN<-sum(!a&y==0);P<-TP+FN;N<-FP+TN;W<-P+N;PP<-TP+FP;PN<-TN+FN;TPR<-ratio(TP,P);TNR<-ratio(TN,N);bs<-sum((p[use]-y)^2);tc<-FP*cost[1]+FN*cost[2]\n list(TP=TP,FP=FP,FN=FN,TN=TN,mass=W,positiveTargetMass=P,negativeTargetMass=N,predictedPositiveMass=PP,predictedNegativeMass=PN,prevalence=ratio(P,W),selectionRate=ratio(PP,W),accuracy=ratio(TP+TN,W),precision=ratio(TP,PP),negativePredictiveValue=ratio(TN,PN),TPR=TPR,FPR=ratio(FP,N),TNR=TNR,FNR=ratio(FN,P),F1=ratio(2*TP,2*TP+FP+FN),balancedAccuracy=if(is.na(TPR)||is.na(TNR))NA_real_ else(TPR+TNR)/2,Brier=ratio(bs,W),BrierSum=bs,totalCost=tc,meanCost=ratio(tc,W))\n}\ncurves<-function(d,p,ids){\n use<-ids[d$eligible[ids]&!is.na(p[ids])];scores<-sort(unique(p[use]),decreasing=TRUE);policies<-c(list(\"always-negative\"),as.list(scores));points<-lapply(policies,function(t){m<-measure(d,p,ids,t);c(list(policy=t),m[c(\"TP\",\"FP\",\"FN\",\"TN\",\"TPR\",\"FPR\",\"precision\")],list(recall=m$TPR))})\n pos<-use[d$y[use]==1];neg<-use[d$y[use]==0];U<-0;for(i in pos)U<-U+sum(p[i]>p[neg])+.5*sum(p[i]==p[neg])\n AP<-0;trap<-0;lastR<-0;lastP<-1\n if(length(pos)&&length(scores))for(j in seq_along(scores)){z<-points[[j+1]];AP<-AP+(z$recall-lastR)*z$precision;trap<-trap+(z$recall-lastR)*(z$precision+lastP)/2;lastR<-z$recall;lastP<-z$precision}\n list(points=points,ROC_AUC=ratio(U,length(pos)*length(neg)),averagePrecision=if(length(pos))AP else NA_real_,PRTrapezoidWithInitialPrecisionOne=if(length(pos))trap else NA_real_)\n}\ncalibrate<-function(d,p,ids){\n use<-ids[d$eligible[ids]&!is.na(p[ids])];W<-length(use);pi<-if(W)mean(d$y[use])else NA_real_;bins<-list();ECE<-rel<-res<-correction<-0\n whichbin<-findInterval(p[use],seq(0,1,.2),rightmost.closed=TRUE,all.inside=TRUE)\n for(b in 1:5){rr<-use[whichbin==b];w<-length(rr);mp<-if(w)mean(p[rr])else NA_real_;o<-if(w)mean(d$y[rr])else NA_real_;variance<-if(w)mean((p[rr]-mp)^2)else NA_real_;covariance<-if(w)mean((p[rr]-mp)*(d$y[rr]-o))else NA_real_;bc<-variance-2*covariance;gap<-mp-o\n  bins[[b]]<-list(mass=w,meanPrediction=mp,eventRate=o,gap=gap,absoluteGap=abs(gap),scoreVariance=variance,scoreTargetCovariance=covariance,withinBinCorrection=bc,rows=w,ids=d$id[rr])\n  if(w){share<-w/W;ECE<-ECE+share*abs(gap);rel<-rel+share*gap^2;res<-res+share*(o-pi)^2;correction<-correction+share*bc}\n };bs<-if(W)mean((p[use]-d$y[use])^2)else NA_real_;unc<-pi*(1-pi)\n list(bins=bins,ECE=if(W)ECE else NA_real_,Brier=bs,reliability=if(W)rel else NA_real_,resolution=if(W)res else NA_real_,uncertainty=unc,withinBinCorrection=if(W)correction else NA_real_,BrierIdentityResidual=bs-(unc-res+rel+correction))\n}\ncounts<-c(\"mass\",\"positiveTargetMass\",\"negativeTargetMass\",\"predictedPositiveMass\",\"predictedNegativeMass\");rates<-c(\"prevalence\",\"selectionRate\",\"accuracy\",\"precision\",\"negativePredictiveValue\",\"TPR\",\"FPR\",\"TNR\",\"FNR\",\"F1\",\"balancedAccuracy\",\"Brier\",\"BrierSum\",\"totalCost\",\"meanCost\")\ntables<-setNames(lapply(1:10,function(i)list()),c(\"predictions\",\"lineage\",\"fit-medians\",\"fit-cells\",\"validation-candidates\",\"test-metrics\",\"test-curves\",\"calibration-bins\",\"group-metrics\",\"chart-points\"))\nadd<-function(name,row)tables[[name]][[length(tables[[name]])+1L]]<<-row\nscalars<-function(m,keys){out<-list();for(k in keys){out[[paste0(k,\"Exact\")]]<-\"\";out[[paste0(k,\"Approx\")]]<-fmt(m[[k]])};out}\ntagrow<-function(kind,...)c(list(kind=kind),list(...))\npoint<-function(kind,chart,series,index,x,y,xunit=\"dimensionless\",yunit=\"dimensionless\",role=\"test\",tag=\"\"){add(\"chart-points\",tagrow(kind,chart=chart,series=series,index=index,xExact=\"\",xApprox=fmt(x),yExact=\"\",yApprox=fmt(y),xUnit=xunit,yUnit=yunit,role=role,tag=tag))}\nstudy<-function(kind,d){\n f<-fitmodel(d);n<-length(d$id);train<-which(d$role==\"train\");validation<-which(d$role==\"validation\");test<-which(d$role==\"test\");p<-f$pred;cv<-curves(d,p,test);cal<-calibrate(d,p,test)\n for(i in seq_len(n)){\n  reason<-if(d$eligible[i])\"\"else\"required-X-or-Y-missing\";transformed<-if(d$eligible[i])paste(fmt(f$z[i,]),collapse=\"|\")else\"\"\n  add(\"predictions\",tagrow(kind,id=d$id[i],sourceRow=d$sourceRow[i],originalID=d$originalID[i],plannedRole=d$plannedRole[i],role=d$role[i],group=ifelse(is.na(d$group[i]),\"\",d$group[i]),eligible=as.integer(d$eligible[i]),targetExact=fmt(d$y[i]),probabilityExact=\"\",probabilityApprox=fmt(p[i]),unseenCell=ifelse(is.na(f$unseen[i]),\"\",as.character(as.integer(f$unseen[i]))),transformedX=transformed,reason=reason))\n  raw<-d$rawX[i,];raw[raw%in%c(\"\",\".\")]<-\"\";nativeY<-d$nativeTarget[i];if(nativeY%in%c(\"\",\".\"))nativeY<-\"\"\n  add(\"lineage\",tagrow(kind,id=d$id[i],sourceRow=d$sourceRow[i],originalID=d$originalID[i],nativeSourceRows=d$lineage[i],rawX=paste(raw,collapse=\"|\"),nativeTarget=nativeY,derivedTarget=fmt(d$y[i]),nativeGroup=ifelse(is.na(d$group[i]),\"\",d$group[i]),plannedRole=d$plannedRole[i],role=d$role[i],eligible=as.integer(d$eligible[i]),analyticalMass=\"1\",reason=reason))\n }\n for(j in seq_len(ncol(d$x)))add(\"fit-medians\",tagrow(kind,feature=j-1,categorical=as.integer((j-1)%in%d$cat),fitRows=length(train),medianExact=\"\",medianApprox=fmt(f$medians[j]),unit=d$units[j]))\n for(j in seq_along(f$lev))add(\"fit-cells\",tagrow(kind,cell=f$lev[j],trainingRows=f$mass[j],positiveRows=f$positive[j],probabilityExact=\"\",probabilityApprox=fmt(f$prob[j]),fallbackExact=\"\",fallbackApprox=fmt(f$fallback)))\n for(j in seq_along(cv$points)){\n  z<-cv$points[[j]];t<-z$policy;add(\"test-curves\",c(tagrow(kind,point=j-1,policy=if(is.character(t))t else\"threshold\",thresholdExact=\"\",thresholdApprox=if(is.character(t))\"\"else fmt(t)),scalars(z,c(\"TP\",\"FP\",\"FN\",\"TN\",\"TPR\",\"FPR\",\"precision\",\"recall\"))))\n  point(kind,\"roc\",\"ROC\",j-1,z$FPR,z$TPR);point(kind,\"pr\",\"PR-observed\",j-1,z$recall,z$precision)\n }\n for(b in 1:5){z<-cal$bins[[b]];add(\"calibration-bins\",c(tagrow(kind,bin=b-1,leftExact=c(\"0\",\"1/5\",\"2/5\",\"3/5\",\"4/5\")[b],rightExact=c(\"1/5\",\"2/5\",\"3/5\",\"4/5\",\"1\")[b],rightClosed=as.integer(b==5),rows=z$rows,ids=paste(z$ids,collapse=\";\")),scalars(z,c(\"mass\",\"meanPrediction\",\"eventRate\",\"gap\",\"absoluteGap\",\"scoreVariance\",\"scoreTargetCovariance\",\"withinBinCorrection\"))));point(kind,\"reliability\",\"Binary event rate\",b-1,z$meanPrediction,z$eventRate,tag=paste0(\"rows=\",z$rows))}\n for(j in seq_along(test)){i<-test[j];point(kind,\"test-scores\",\"Training-fitted probability\",j-1,j,p[i],\"test-row position\",\"probability\",tag=d$id[i]);point(kind,\"test-scores\",\"Observed Y\",j-1,j,d$y[i],\"test-row position\",\"binary target\",tag=d$id[i])}\n scenarioNames<-c(\"equal\",\"miss-five\",\"alarm-five\");costs<-list(c(1,1),c(1,5),c(5,1))\n for(s in 1:3){name<-scenarioNames[s];cost<-costs[[s]];grid<-c(list(\"always-negative\"),as.list(sort(unique(p[validation]),decreasing=TRUE)));candidates<-lapply(grid,function(t)measure(d,p,validation,t,cost));values<-vapply(candidates,function(m)m$meanCost,numeric(1));best<-which(values<=min(values)+1e-12)[1];chosen<-grid[[best]];ev<-measure(d,p,test,chosen,cost)\n  for(j in seq_along(grid)){t<-grid[[j]];m<-candidates[[j]];cell<-setNames(lapply(c(\"TP\",\"FP\",\"FN\",\"TN\"),function(k)fmt(m[[k]])),paste0(c(\"TP\",\"FP\",\"FN\",\"TN\"),\"Exact\"));add(\"validation-candidates\",c(tagrow(kind,scenario=name,candidate=j-1,selected=as.integer(j==best),policy=if(is.character(t))t else\"threshold\",thresholdExact=\"\",thresholdApprox=if(is.character(t))\"\"else fmt(t),feasible=1,reasons=\"\"),cell,scalars(m,c(counts,\"TPR\",\"FPR\",\"precision\",\"meanCost\",\"totalCost\"))));point(kind,\"validation-cost\",name,j-1,j-1,m$meanCost,\"candidate index\",\"hypothetical cost units/mass\",\"validation\",if(is.character(t))t else fmt(t))}\n  m<-c(ev,cv[c(\"ROC_AUC\",\"averagePrecision\",\"PRTrapezoidWithInitialPrecisionOne\")],cal[c(\"ECE\",\"reliability\",\"resolution\",\"uncertainty\",\"withinBinCorrection\",\"BrierIdentityResidual\")])\n  for(k in c(\"TP\",\"FP\",\"FN\",\"TN\",counts,rates,\"ROC_AUC\",\"averagePrecision\",\"PRTrapezoidWithInitialPrecisionOne\",\"ECE\",\"reliability\",\"resolution\",\"uncertainty\",\"withinBinCorrection\",\"BrierIdentityResidual\")){\n   unit<-if(k%in%c(\"TP\",\"FP\",\"FN\",\"TN\",counts))\"rows\"else if(k==\"totalCost\")\"hypothetical cost units\"else if(k==\"meanCost\")\"hypothetical cost units/mass\"else if(k==\"BrierSum\")\"sum squared-probability loss\"else\"dimensionless\"\n   add(\"test-metrics\",tagrow(kind,scenario=name,metric=k,valueExact=\"\",valueApprox=fmt(m[[k]]),unit=unit))\n  }\n  lev<-unique(d$group[test][!is.na(d$group[test])]);sets<-c(list(test),lapply(lev,function(g)test[!is.na(d$group[test])&d$group[test]==g]),list(test[is.na(d$group[test])]))\n  types<-c(\"overall\",rep(\"known\",length(lev)),\"unknown\");tokens<-c(\"all\",lev,\"\")\n  for(j in seq_along(sets)){ids<-sets[[j]];m<-measure(d,p,ids,chosen,cost);cell<-setNames(lapply(c(\"TP\",\"FP\",\"FN\",\"TN\"),function(k)fmt(m[[k]])),paste0(c(\"TP\",\"FP\",\"FN\",\"TN\"),\"Exact\"));add(\"group-metrics\",c(tagrow(kind,scenario=name,groupType=types[j],groupToken=tokens[j],retainedRows=length(ids)),cell,scalars(m,c(counts,rates))));if(types[j]==\"known\")point(kind,\"group-TPR\",name,j-2,j-2,m$TPR,\"declared group position\",\"TPR\",tag=tokens[j])}\n }\n invisible(NULL)\n}\n\n# Fixed finite inputs only; not the complete web input/budget validator.\nqnum<-function(v){if(is.null(v))return(NA_real_);if(is.logical(v))return(as.numeric(v));s<-as.character(v);if(grepl(\"/\",s,fixed=TRUE)){a<-strsplit(s,\"/\",fixed=TRUE)[[1]];return(as.numeric(a[1])/as.numeric(a[2]))};as.numeric(s)}\nrowsG<-function(raw){\n n<-length(raw);get<-function(r,k,default=NULL)if(is.null(r[[k]]))default else r[[k]]\n id<-vapply(raw,function(r)as.character(r$id),character(1));p<-vapply(raw,function(r)qnum(r$score),numeric(1));y<-vapply(raw,function(r)qnum(r$y),numeric(1));w<-vapply(raw,function(r)qnum(get(r,\"weight\",\"1\")),numeric(1));role<-vapply(raw,function(r)get(r,\"role\",\"evaluation\"),character(1));group<-vapply(raw,function(r)as.character(get(r,\"group\",NA_character_)),character(1))\n stopifnot(all(w>=0),all(is.na(p)|(p>=0&p<=1)),all(is.na(y)|y%in%c(0,1)),!anyDuplicated(id));list(id=id,p=p,y=y,w=w,role=role,group=group,eligible=!is.na(p)&!is.na(y)&w>0&role!=\"excluded\")\n}\nscopeG<-function(d,role=\"all\")if(role==\"all\")seq_along(d$id)else which(d$role==role)\nmetricsG<-function(d,ids,t=.5,cost=c(1,1)){\n use<-ids[d$eligible[ids]];p<-d$p[use];y<-d$y[use];w<-d$w[use];a<-if(is.character(t))rep(t==\"always-positive\",length(use))else p>=t\n TP<-sum(w[a&y==1]);FP<-sum(w[a&y==0]);FN<-sum(w[!a&y==1]);TN<-sum(w[!a&y==0]);P<-TP+FN;N<-FP+TN;W<-P+N;PP<-TP+FP;PN<-TN+FN;TPR<-ratio(TP,P);TNR<-ratio(TN,N);bs<-sum(w*(p-y)^2);tc<-FP*cost[1]+FN*cost[2]\n list(confusion=list(TP=TP,FP=FP,FN=FN,TN=TN),mass=W,positiveTargetMass=P,negativeTargetMass=N,predictedPositiveMass=PP,predictedNegativeMass=PN,prevalence=ratio(P,W),selectionRate=ratio(PP,W),accuracy=ratio(TP+TN,W),precision=ratio(TP,PP),negativePredictiveValue=ratio(TN,PN),TPR=TPR,FPR=ratio(FP,N),TNR=TNR,FNR=ratio(FN,P),F1=ratio(2*TP,2*TP+FP+FN),balancedAccuracy=if(is.na(TPR)||is.na(TNR))NA_real_ else(TPR+TNR)/2,Brier=ratio(bs,W),BrierSum=bs,totalCost=tc,meanCost=ratio(tc,W),bayesThreshold=ratio(cost[1],sum(cost)))\n}\ncurvesG<-function(d,ids){\n use<-ids[d$eligible[ids]];grid<-c(list(\"always-negative\"),as.list(sort(unique(d$p[use]),decreasing=TRUE)));points<-lapply(grid,function(t){m<-metricsG(d,ids,t);c(list(policy=t),m$confusion,m[c(\"TPR\",\"FPR\",\"precision\")],list(recall=m$TPR))});pos<-use[d$y[use]==1];neg<-use[d$y[use]==0];P<-sum(d$w[pos]);N<-sum(d$w[neg]);U<-0\n for(i in pos)U<-U+d$w[i]*sum(d$w[neg]*((d$p[i]>d$p[neg])+.5*(d$p[i]==d$p[neg])))\n AP<-trap<-lastR<-0;lastP<-1\n if(P&&length(grid)>1)for(j in 2:length(grid)){z<-points[[j]];AP<-AP+(z$recall-lastR)*z$precision;trap<-trap+(z$recall-lastR)*(z$precision+lastP)/2;lastR<-z$recall;lastP<-z$precision}\n list(points=points,ROC_AUC=ratio(U,P*N),averagePrecision=if(P)AP else NA_real_,PRTrapezoidWithInitialPrecisionOne=if(P)trap else NA_real_)\n}\nchooseG<-function(d,a,cost){\n role<-if(is.null(a$selectionRole))\"validation\"else a$selectionRole;er<-if(is.null(a$evaluationRole))\"test\"else a$evaluationRole;ids<-scopeG(d,role);use<-ids[d$eligible[ids]];stopifnot(length(use)>0);grid<-if(is.null(a$thresholds))c(list(\"always-negative\"),as.list(sort(unique(d$p[use]),decreasing=TRUE)))else lapply(a$thresholds,function(t)if(t%in%c(\"always-negative\",\"always-positive\"))t else qnum(t))\n candidates<-lapply(seq_along(grid),function(j){m<-metricsG(d,ids,grid[[j]],cost);feasible<-TRUE;if(!is.null(a$minTPR))feasible<-feasible&&!is.na(m$TPR)&&m$TPR>=qnum(a$minTPR);if(!is.null(a$maxFPR))feasible<-feasible&&!is.na(m$FPR)&&m$FPR<=qnum(a$maxFPR);list(index=j-1,policy=grid[[j]],metrics=m,feasible=feasible)})\n good<-which(vapply(candidates,function(c)c$feasible,logical(1)));best<-NA_integer_;if(length(good)){v<-vapply(candidates[good],function(c)c$metrics$meanCost,numeric(1));best<-good[which(v<=min(v)+1e-12)[1]]}\n list(selectedIndex=if(is.na(best))NA_integer_ else best-1,selectedPolicy=if(is.na(best))NULL else grid[[best]],selectedValidation=if(is.na(best))NULL else candidates[[best]]$metrics,candidates=candidates,evaluation=if(is.na(best)||er==\"none\")NULL else metricsG(d,scopeG(d,er),grid[[best]],cost))\n}\ncalibrateG<-function(d,ids,edges){\n use<-ids[d$eligible[ids]];W<-sum(d$w[use]);pi<-ratio(sum(d$w[use]*d$y[use]),W);bins<-list();ECE<-rel<-res<-correction<-0;assign<-findInterval(d$p[use],edges,rightmost.closed=TRUE,all.inside=TRUE)\n for(b in seq_len(length(edges)-1)){rr<-use[assign==b];w<-sum(d$w[rr]);mp<-ratio(sum(d$w[rr]*d$p[rr]),w);o<-ratio(sum(d$w[rr]*d$y[rr]),w);variance<-if(w)sum(d$w[rr]*(d$p[rr]-mp)^2)/w else NA_real_;covariance<-if(w)sum(d$w[rr]*(d$p[rr]-mp)*(d$y[rr]-o))/w else NA_real_;bc<-variance-2*covariance;gap<-mp-o;bins[[b]]<-list(index=b-1,mass=w,meanPrediction=mp,eventRate=o,scoreVariance=variance,scoreTargetCovariance=covariance,withinBinCorrection=bc,ids=d$id[rr])\n  if(w){s<-w/W;ECE<-ECE+s*abs(gap);rel<-rel+s*gap^2;res<-res+s*(o-pi)^2;correction<-correction+s*bc}\n };bs<-ratio(sum(d$w[use]*(d$p[use]-d$y[use])^2),W);unc<-pi*(1-pi);list(bins=bins,Brier=bs,ECE=if(W)ECE else NA_real_,uncertainty=unc,reliability=if(W)rel else NA_real_,resolution=if(W)res else NA_real_,withinBinCorrection=if(W)correction else NA_real_,BrierIdentityResidual=bs-(unc-res+rel+correction))\n}\ngroupsG<-function(d,ids,t,cost){\n lev<-unique(d$group[ids][!is.na(d$group[ids])]);groups<-lapply(lev,function(g)list(group=g,metrics=metricsG(d,ids[!is.na(d$group[ids])&d$group[ids]==g],t,cost)));overall<-metricsG(d,ids,t,cost);unknown<-metricsG(d,ids[is.na(d$group[ids])],t,cost);gaps<-list()\n for(k in c(\"prevalence\",\"selectionRate\",\"TPR\",\"FPR\",\"precision\",\"accuracy\",\"meanCost\")){use<-Filter(function(g)g$metrics$mass>0,groups);v<-vapply(use,function(g)g$metrics[[k]],numeric(1));gaps[[k]]<-if(length(use)<2||anyNA(v))NA_real_ else max(v)-min(v)}\n list(overall=overall,groups=groups,unknownGroup=unknown,gaps=gaps,partitionMassResidual=overall$mass-unknown$mass-sum(vapply(groups,function(g)g$metrics$mass,numeric(1))))\n}\nsvgFixed<-function(file,points,title,xlabel,ylabel,legend){\n finite<-points[points$y!=\"undefined\"&points$x!=\"undefined\",,drop=FALSE];x<-as.numeric(finite$x);y<-as.numeric(finite$y);xmin<-if(length(x))min(x)else 0;xmax<-if(length(x))max(x)else 1;ymin<-min(c(0,y));ymax<-max(c(0,y));if(xmin==xmax){xmin<-xmin-.5;xmax<-xmax+.5};if(ymin==ymax)ymax<-ymin+1;X<-function(v)85+(v-xmin)/(xmax-xmin)*480;Y<-function(v)278-(v-ymin)/(ymax-ymin)*175\n esc<-function(s){s<-gsub(\"&\",\"&amp;\",s,fixed=TRUE);s<-gsub(\"<\",\"&lt;\",s,fixed=TRUE);gsub(\">\",\"&gt;\",s,fixed=TRUE)};s<-'<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"620\" height=\"360\" viewBox=\"0 0 620 360\"><rect width=\"620\" height=\"360\" fill=\"white\"/><g font-family=\"Arial, sans-serif\" font-size=\"13\" fill=\"#17324d\">'\n lines<-strwrap(title,width=65);for(i in seq_along(lines))s<-paste0(s,'<text x=\"25\" y=\"',24+(i-1)*18,'\">',esc(lines[i]),'</text>');colors<-c(\"#176b9b\",\"#b85e18\",\"#437e4d\")\n for(i in seq_along(legend))s<-paste0(s,'<circle cx=\"',30+(i-1)*250,'\" cy=\"76\" r=\"4\" fill=\"',colors[(i-1)%%3+1],'\"/><text x=\"',42+(i-1)*250,'\" y=\"80\">',esc(legend[i]),'</text>')\n s<-paste0(s,'<path d=\"M85 98V278H575\" fill=\"none\" stroke=\"#52677d\"/><text text-anchor=\"middle\" x=\"325\" y=\"338\">',esc(xlabel),'</text><text text-anchor=\"middle\" transform=\"translate(21,190) rotate(-90)\">',esc(ylabel),'</text>')\n for(i in 0:4){xx<-xmin+(xmax-xmin)*i/4;yy<-ymin+(ymax-ymin)*i/4;s<-paste0(s,'<text text-anchor=\"middle\" x=\"',sprintf(\"%.9g\",X(xx)),'\" y=\"305\">',sprintf(\"%.4g\",xx),'</text><text text-anchor=\"end\" x=\"77\" y=\"',sprintf(\"%.9g\",Y(yy)+4),'\">',sprintf(\"%.4g\",yy),'</text>')}\n for(i in seq_len(nrow(finite)))s<-paste0(s,'<circle cx=\"',sprintf(\"%.9g\",X(x[i])),'\" cy=\"',sprintf(\"%.9g\",Y(y[i])),'\" r=\"3\" fill=\"',colors[as.integer(finite$series[i])%%3+1],'\"/>');writeLines(paste0(s,'</g></svg>'),file,useBytes=TRUE)\n}\nfixedRun<-function(){\n api<-FIXED$api;a<-FIXED$args;summary<-list();points<-list();xlabel<-\"Declared index\";ylabel<-\"Value\";legend<-\"Declared result\"\n metric<-function(name,v,unit=\"dimensionless\"){if(is.null(v))v<-NA_real_;summary[[length(summary)+1L]]<<-data.frame(metric=name,value=if(is.na(v))\"undefined\"else sprintf(\"%.9g\",v),exactValue=\"\",unit=unit,defined=as.integer(!is.na(v)),stringsAsFactors=FALSE)}\n pt<-function(i,x,y,id=\"\",series=0){points[[length(points)+1L]]<<-data.frame(series=series,index=i,xExact=\"\",x=if(is.na(x))\"undefined\"else sprintf(\"%.9g\",x),yExact=\"\",y=if(is.na(y))\"undefined\"else sprintf(\"%.9g\",y),id=as.character(id),stringsAsFactors=FALSE)}\n if(api==\"realdata\"){\n  native<-loadData()[[a$kind]];fit<-fitmodel(native);d<-list(id=native$id,p=fit$pred,y=native$y,w=rep(1,length(native$id)),role=native$role,group=native$group,eligible=native$eligible);scenarios<-list()\n  for(j in 1:3){name<-c(\"equal\",\"miss-five\",\"alarm-five\")[j];cst<-list(c(1,1),c(1,5),c(5,1))[[j]];sel<-chooseG(d,list(),cst);scenarios[[j]]<-list(name=name,selection=sel);metric(paste0(name,\"Threshold\"),sel$selectedPolicy);metric(paste0(name,\"TestCost\"),sel$evaluation$meanCost,\"hypothetical cost units/mass\")}\n  ids<-scopeG(d,\"test\");cv<-curvesG(d,ids);cal<-calibrateG(d,ids,seq(0,1,.2));metric(\"testAUC\",cv$ROC_AUC);metric(\"testAP\",cv$averagePrecision);metric(\"testBrier\",cal$Brier);metric(\"eligibleRows\",sum(d$eligible),\"rows\")\n  for(j in seq_along(ids)){i<-ids[j];pt(j-1,j,d$p[i],d$id[i],0);pt(j-1,j,d$y[i],d$id[i],1)}\n  full<-list(kind=a$kind,fit=fit,scenarios=scenarios,testCurves=cv,testCalibration=cal,rowsScored=d);xlabel<-\"Test row, native order\";ylabel<-\"Y or probability\";legend<-c(\"Training-fitted probability\",\"Observed Y\")\n }else{\n  d<-rowsG(a$rows);role<-if(is.null(a$role))\"all\"else a$role;ids<-scopeG(d,role);cost<-if(is.null(a$costs))c(1,1)else c(qnum(a$costs$falsePositive),qnum(a$costs$falseNegative));t<-if(is.null(a$threshold)).5 else if(a$threshold%in%c(\"always-positive\",\"always-negative\"))a$threshold else qnum(a$threshold)\n  if(api==\"metrics\"){\n   full<-metricsG(d,ids,t,cost);for(k in c(\"mass\",\"accuracy\",\"precision\",\"TPR\",\"FPR\",\"F1\",\"Brier\",\"meanCost\"))metric(k,full[[k]],if(k==\"mass\")\"mass\"else if(k==\"meanCost\")\"hypothetical cost units/mass\"else\"dimensionless\");metric(\"BayesThreshold\",full$bayesThreshold)\n   for(i in 1:4)pt(i-1,i-1,full$confusion[[i]],names(full$confusion)[i]);xlabel<-\"TP / FP / FN / TN positions\";ylabel<-\"Analytical mass\"\n  }else if(api==\"curves\"){\n   full<-curvesG(d,ids);for(k in c(\"ROC_AUC\",\"averagePrecision\",\"PRTrapezoidWithInitialPrecisionOne\"))metric(k,full[[k]])\n   for(j in seq_along(full$points)){p<-full$points[[j]];pt(j-1,p$FPR,p$TPR,if(is.character(p$policy))p$policy else sprintf(\"%.17g\",p$policy))};xlabel<-\"False positive rate\";ylabel<-\"True positive rate\";legend<-\"Observed ROC operating points\"\n  }else if(api==\"choose\"){\n   full<-chooseG(d,a,cost);metric(\"selectedIndex\",full$selectedIndex,\"candidate index\");metric(\"minimumCost\",if(is.null(full$selectedValidation))NULL else full$selectedValidation$meanCost,\"hypothetical cost units/mass\");metric(\"feasible\",as.integer(!is.na(full$selectedIndex)),\"indicator\")\n   for(c in full$candidates)pt(c$index,c$index,c$metrics$meanCost,if(is.character(c$policy))c$policy else sprintf(\"%.17g\",c$policy));xlabel<-\"Validation candidate\";ylabel<-\"Assumed cost / mass\";legend<-\"Validation candidate costs\"\n  }else if(api==\"calibrate\"){\n   edges<-if(is.null(a$binEdges))seq(0,1,.2)else vapply(a$binEdges,qnum,numeric(1));full<-calibrateG(d,ids,edges);for(k in c(\"ECE\",\"Brier\",\"uncertainty\",\"resolution\",\"reliability\",\"withinBinCorrection\",\"BrierIdentityResidual\"))metric(k,full[[k]])\n   for(b in full$bins)pt(b$index,b$meanPrediction,b$eventRate,paste0(\"bin:\",b$index));xlabel<-\"Bin mean forecast\";ylabel<-\"Bin event rate\";legend<-\"Binary-event reliability\"\n  }else if(api==\"groups\"){\n   full<-groupsG(d,ids,t,cost);metric(\"overallTPR\",full$overall$TPR);metric(\"TPRGap\",full$gaps$TPR);metric(\"precisionGap\",full$gaps$precision);metric(\"unknownMass\",full$unknownGroup$mass,\"mass\");metric(\"partitionResidual\",full$partitionMassResidual,\"mass\")\n   for(j in seq_along(full$groups))pt(j-1,j-1,full$groups[[j]]$metrics$TPR,full$groups[[j]]$group);xlabel<-\"Declared group position\";ylabel<-\"True positive rate\";legend<-\"Known-group TPR\"\n  }else stop(\"unknown declared fixed API\")\n }\n sm<-do.call(rbind,summary);pp<-do.call(rbind,points);write.csv(sm,file.path(outDir,\"summary.csv\"),row.names=FALSE,na=\"\");write.csv(pp,file.path(outDir,\"plot-points.csv\"),row.names=FALSE,na=\"\");svgFixed(file.path(outDir,\"plot.svg\"),pp,FIXED$title,xlabel,ylabel,legend);dput(list(api=api,variant=FIXED$variant,input=FIXED$args,arithmetic=\"Base-R binary64 fixed example; not an exact rational general validator\",result=full),file=file.path(outDir,\"full.txt\"));cat(\"PASS\",api,FIXED$variant,\"summary\",nrow(sm),\"points\",nrow(pp),\"\\n\")\n}\n\nFIXED<-list(api=\"metrics\",variant=\"reject-negative-weight\",args=list(rows=list(list(id=\"bad\",score=\".5\",y=0,weight=\"-1\"))),title=\"Reject a declared negative analytical mass\",expectedReject=TRUE)\nfixedRun()\n",
        "codeText": "# ML14 standalone public counterpart, base R only.\n# Inputs are only the three factual CSVs; derived columns/previous model answers unused.\n# Binary64 arithmetic, not arbitrary-precision Fraction. At numerical cost ties\n# within 1e-12 retain the earliest candidate. Exact claims belong to Python/web.\n# SHA256 infrastructure below is reused verbatim from the previous public study.\nargs<-commandArgs(trailingOnly=TRUE);filearg<-grep(\"^--file=\",commandArgs(),value=TRUE)\nhere<-if(dir.exists(\"ml14-sources\"))getwd()else if(length(filearg))dirname(normalizePath(sub(\"^--file=\",\"\",filearg[1])))else getwd()\noption<-function(key,default){i<-match(key,args);if(is.na(i))default else args[i+1]}\nsourceDir<-option(\"--source\",file.path(here,\"ml14-sources\"));outDir<-option(\"--out\",file.path(getwd(),\"ml14-r-results\"));dir.create(outDir,recursive=TRUE,showWarnings=FALSE)\nnum<-function(x){x[x%in%c(\"\",\".\")]<-NA_character_;as.numeric(x)}\nfmt<-function(x)ifelse(is.na(x),\"\",sprintf(\"%.17g\",x))\nratio<-function(a,b)if(b==0)NA_real_ else a/b\nreadnative<-function(name)read.csv(file.path(sourceDir,name),check.names=FALSE,colClasses=\"character\",na.strings=character(),stringsAsFactors=FALSE)\n# Vectorized SHA256 for the short ASCII keys used in this study.\n# Unsigned words use exact integer-valued doubles; bit operations use safe\n# 16-bit halves, avoiding R's reserved signed-INT_MIN/NA representation.\nMOD<-2^32\nxor32<-function(a,b) as.double(bitwXor(as.integer(floor(a/65536)),as.integer(floor(b/65536))))*65536+as.double(bitwXor(as.integer(a%%65536),as.integer(b%%65536)))\nand32<-function(a,b) as.double(bitwAnd(as.integer(floor(a/65536)),as.integer(floor(b/65536))))*65536+as.double(bitwAnd(as.integer(a%%65536),as.integer(b%%65536)))\nrot<-function(x,n) floor(x/2^n)+(x%%2^n)*2^(32-n)\nxor3<-function(a,b,c) xor32(xor32(a,b),c)\nK<-c(0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5,0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967,0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070,0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3,0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2)\nsha256<-function(strings) {\n n<-length(strings);bytes<-matrix(0,n,64)\n for(i in seq_len(n)) {v<-utf8ToInt(strings[i]);stopifnot(length(v)<56,all(v<128));if(length(v)) bytes[i,seq_along(v)]<-v;bytes[i,length(v)+1]<-128;bits<-length(v)*8;bytes[i,61:64]<-c(floor(bits/2^24)%%256,floor(bits/2^16)%%256,floor(bits/256)%%256,bits%%256)}\n w<-matrix(0,n,64)\n for(j in 1:16) {b<-4*(j-1)+1;w[,j]<-bytes[,b]*2^24+bytes[,b+1]*2^16+bytes[,b+2]*256+bytes[,b+3]}\n for(j in 17:64) {s0<-xor3(rot(w[,j-15],7),rot(w[,j-15],18),floor(w[,j-15]/8));s1<-xor3(rot(w[,j-2],17),rot(w[,j-2],19),floor(w[,j-2]/1024));w[,j]<-(w[,j-16]+s0+w[,j-7]+s1)%%MOD}\n init<-c(0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19)\n state<-lapply(init,function(v) rep(v,n));a<-state[[1]];b<-state[[2]];c<-state[[3]];d<-state[[4]];e<-state[[5]];f<-state[[6]];g<-state[[7]];h<-state[[8]]\n for(j in 1:64) {S1<-xor3(rot(e,6),rot(e,11),rot(e,25));ch<-xor32(and32(e,f),and32(MOD-1-e,g));t1<-(h+S1+ch+K[j]+w[,j])%%MOD;S0<-xor3(rot(a,2),rot(a,13),rot(a,22));maj<-xor3(and32(a,b),and32(a,c),and32(b,c));t2<-(S0+maj)%%MOD;h<-g;g<-f;f<-e;e<-(d+t1)%%MOD;d<-c;c<-b;b<-a;a<-(t1+t2)%%MOD}\n end<-list(a,b,c,d,e,f,g,h);hex<-lapply(1:8,function(j){v<-(end[[j]]+init[j])%%MOD;paste0(sprintf(\"%04x\",as.integer(floor(v/65536))),sprintf(\"%04x\",as.integer(v%%65536)))})\n do.call(paste0,hex)\n}\nstopifnot(identical(sha256(c(\"abc\",\"\")),c(\"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad\",\"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855\")))\n\nloadData<-function(){\n wb<-readnative(\"actual64-country-four-indicators-original-2024.csv\");codes<-c(\"NY.GDP.PCAP.KD\",\"NY.GDP.MKTP.KD.ZG\",\"FP.CPI.TOTL.ZG\",\"SP.DYN.LE00.IN\");iso<-sort(unique(wb$countryISO3));stopifnot(nrow(wb)==64,length(iso)==16)\n tokens<-t(vapply(iso,function(s)wb$originalValueToken[match(paste(s,codes),paste(wb$countryISO3,wb$indicatorID))],character(4)));vals<-matrix(num(as.vector(tokens)),nrow=nrow(tokens))\n country<-list(id=paste0(iso,\":2024\"),sourceRow=1:16,originalID=iso,x=vals[,1:3,drop=FALSE],rawX=tokens[,1:3,drop=FALSE],nativeTarget=tokens[,4],y=as.integer(vals[,4]>=80),group=ifelse(is.na(vals[,1]),NA_character_,as.character(as.integer(vals[,1]>=25000))),lineage=vapply(iso,function(s)paste(wb$sourceRow[match(paste(s,codes),paste(wb$countryISO3,wb$indicatorID))],collapse=\";\"),character(1)),cat=integer(),units=c(\"constant2015USD/person\",\"annualPercent\",\"annualPercent\"))\n nls<-readnative(\"actual3613-NLS-original52-fields-groups-roles.csv\");raw<-cbind(nls$ed76,nls$age76,nls$nearc4)\n person<-list(id=paste0(\"person:\",nls$sourceRow),sourceRow=as.integer(nls$sourceRow),originalID=nls$id,x=matrix(num(as.vector(raw)),nrow=nrow(raw)),rawX=raw,nativeTarget=nls$wage76,y=as.integer(num(nls$wage76)>=500),group=ifelse(nls$black%in%c(\"\",\".\"),NA_character_,nls$black),lineage=nls$sourceRow,cat=2L,units=c(\"years\",\"years\",\"nativeCategory\"))\n ch<-readnative(\"actual3150-churn-original14-fields-groups-roles.csv\");raw<-cbind(ch[[\"Call  Failure\"]],ch$Complains,ch[[\"Subscription  Length\"]],ch[[\"Seconds of Use\"]])\n company<-list(id=paste0(\"customer:\",ch$sourceRow),sourceRow=as.integer(ch$sourceRow),originalID=rep(\"\",nrow(ch)),x=matrix(num(as.vector(raw)),nrow=nrow(raw)),rawX=raw,nativeTarget=ch$Churn,y=as.integer(ch$Churn),group=ifelse(ch[[\"Tariff Plan\"]]%in%c(\"\",\".\"),NA_character_,ch[[\"Tariff Plan\"]]),lineage=ch$sourceRow,cat=1L,units=c(\"count\",\"nativeCategory\",\"months\",\"seconds\"))\n stopifnot(nrow(nls)==3613,nrow(ch)==3150,identical(as.integer(ch$sourceRow[ch[[\"Charge  Amount\"]]==\"10\"]),c(474L,2174L,2274L,2374L,2674L,2924L,2974L)))\n result<-list(country=country,person=person,company=company)\n for(k in names(result)){d<-result[[k]];n<-length(d$id);d$eligible<-!is.na(d$y)&rowSums(is.na(d$x))==0;hash<-sha256(paste0(\"ML14-role|\",k,\"|\",d$id));rank<-integer(n);rank[order(hash,seq_len(n))]<-seq_len(n)-1L;d$plannedRole<-ifelse(rank%%5==0,\"test\",ifelse(rank%%5==1,\"validation\",\"train\"));d$role<-ifelse(d$eligible,d$plannedRole,\"excluded\");result[[k]]<-d}\n stopifnot(sum(result$person$eligible)==3017);result\n}\nfitmodel<-function(d){\n ids<-which(d$role==\"train\");p<-ncol(d$x);m<-vapply(seq_len(p),function(j)if((j-1)%in%d$cat)NA_real_ else median(d$x[ids,j]),numeric(1));z<-d$x\n for(j in seq_len(p))if(!((j-1)%in%d$cat))z[,j]<-as.numeric(z[,j]>m[j])\n keys<-apply(z,1,function(v)paste(fmt(v),collapse=\"|\"));lev<-unique(keys[ids]);mass<-vapply(lev,function(k)sum(keys[ids]==k),integer(1));positive<-vapply(lev,function(k)sum(d$y[ids][keys[ids]==k]),integer(1));prob<-(positive+1)/(mass+2);fallback<-(sum(d$y[ids])+1)/(length(ids)+2);pred<-prob[match(keys,lev)];unseen<-is.na(pred);pred[unseen]<-fallback;pred[!d$eligible]<-NA_real_;unseen[!d$eligible]<-NA\n list(ids=ids,medians=m,z=z,keys=keys,lev=lev,mass=mass,positive=positive,prob=prob,fallback=fallback,pred=pred,unseen=unseen)\n}\nmeasure<-function(d,p,ids,t=.5,cost=c(1,1)){\n use<-ids[d$eligible[ids]&!is.na(p[ids])];y<-d$y[use];a<-if(is.character(t))rep(t==\"always-positive\",length(use))else p[use]>=t\n TP<-sum(a&y==1);FP<-sum(a&y==0);FN<-sum(!a&y==1);TN<-sum(!a&y==0);P<-TP+FN;N<-FP+TN;W<-P+N;PP<-TP+FP;PN<-TN+FN;TPR<-ratio(TP,P);TNR<-ratio(TN,N);bs<-sum((p[use]-y)^2);tc<-FP*cost[1]+FN*cost[2]\n list(TP=TP,FP=FP,FN=FN,TN=TN,mass=W,positiveTargetMass=P,negativeTargetMass=N,predictedPositiveMass=PP,predictedNegativeMass=PN,prevalence=ratio(P,W),selectionRate=ratio(PP,W),accuracy=ratio(TP+TN,W),precision=ratio(TP,PP),negativePredictiveValue=ratio(TN,PN),TPR=TPR,FPR=ratio(FP,N),TNR=TNR,FNR=ratio(FN,P),F1=ratio(2*TP,2*TP+FP+FN),balancedAccuracy=if(is.na(TPR)||is.na(TNR))NA_real_ else(TPR+TNR)/2,Brier=ratio(bs,W),BrierSum=bs,totalCost=tc,meanCost=ratio(tc,W))\n}\ncurves<-function(d,p,ids){\n use<-ids[d$eligible[ids]&!is.na(p[ids])];scores<-sort(unique(p[use]),decreasing=TRUE);policies<-c(list(\"always-negative\"),as.list(scores));points<-lapply(policies,function(t){m<-measure(d,p,ids,t);c(list(policy=t),m[c(\"TP\",\"FP\",\"FN\",\"TN\",\"TPR\",\"FPR\",\"precision\")],list(recall=m$TPR))})\n pos<-use[d$y[use]==1];neg<-use[d$y[use]==0];U<-0;for(i in pos)U<-U+sum(p[i]>p[neg])+.5*sum(p[i]==p[neg])\n AP<-0;trap<-0;lastR<-0;lastP<-1\n if(length(pos)&&length(scores))for(j in seq_along(scores)){z<-points[[j+1]];AP<-AP+(z$recall-lastR)*z$precision;trap<-trap+(z$recall-lastR)*(z$precision+lastP)/2;lastR<-z$recall;lastP<-z$precision}\n list(points=points,ROC_AUC=ratio(U,length(pos)*length(neg)),averagePrecision=if(length(pos))AP else NA_real_,PRTrapezoidWithInitialPrecisionOne=if(length(pos))trap else NA_real_)\n}\ncalibrate<-function(d,p,ids){\n use<-ids[d$eligible[ids]&!is.na(p[ids])];W<-length(use);pi<-if(W)mean(d$y[use])else NA_real_;bins<-list();ECE<-rel<-res<-correction<-0\n whichbin<-findInterval(p[use],seq(0,1,.2),rightmost.closed=TRUE,all.inside=TRUE)\n for(b in 1:5){rr<-use[whichbin==b];w<-length(rr);mp<-if(w)mean(p[rr])else NA_real_;o<-if(w)mean(d$y[rr])else NA_real_;variance<-if(w)mean((p[rr]-mp)^2)else NA_real_;covariance<-if(w)mean((p[rr]-mp)*(d$y[rr]-o))else NA_real_;bc<-variance-2*covariance;gap<-mp-o\n  bins[[b]]<-list(mass=w,meanPrediction=mp,eventRate=o,gap=gap,absoluteGap=abs(gap),scoreVariance=variance,scoreTargetCovariance=covariance,withinBinCorrection=bc,rows=w,ids=d$id[rr])\n  if(w){share<-w/W;ECE<-ECE+share*abs(gap);rel<-rel+share*gap^2;res<-res+share*(o-pi)^2;correction<-correction+share*bc}\n };bs<-if(W)mean((p[use]-d$y[use])^2)else NA_real_;unc<-pi*(1-pi)\n list(bins=bins,ECE=if(W)ECE else NA_real_,Brier=bs,reliability=if(W)rel else NA_real_,resolution=if(W)res else NA_real_,uncertainty=unc,withinBinCorrection=if(W)correction else NA_real_,BrierIdentityResidual=bs-(unc-res+rel+correction))\n}\ncounts<-c(\"mass\",\"positiveTargetMass\",\"negativeTargetMass\",\"predictedPositiveMass\",\"predictedNegativeMass\");rates<-c(\"prevalence\",\"selectionRate\",\"accuracy\",\"precision\",\"negativePredictiveValue\",\"TPR\",\"FPR\",\"TNR\",\"FNR\",\"F1\",\"balancedAccuracy\",\"Brier\",\"BrierSum\",\"totalCost\",\"meanCost\")\ntables<-setNames(lapply(1:10,function(i)list()),c(\"predictions\",\"lineage\",\"fit-medians\",\"fit-cells\",\"validation-candidates\",\"test-metrics\",\"test-curves\",\"calibration-bins\",\"group-metrics\",\"chart-points\"))\nadd<-function(name,row)tables[[name]][[length(tables[[name]])+1L]]<<-row\nscalars<-function(m,keys){out<-list();for(k in keys){out[[paste0(k,\"Exact\")]]<-\"\";out[[paste0(k,\"Approx\")]]<-fmt(m[[k]])};out}\ntagrow<-function(kind,...)c(list(kind=kind),list(...))\npoint<-function(kind,chart,series,index,x,y,xunit=\"dimensionless\",yunit=\"dimensionless\",role=\"test\",tag=\"\"){add(\"chart-points\",tagrow(kind,chart=chart,series=series,index=index,xExact=\"\",xApprox=fmt(x),yExact=\"\",yApprox=fmt(y),xUnit=xunit,yUnit=yunit,role=role,tag=tag))}\nstudy<-function(kind,d){\n f<-fitmodel(d);n<-length(d$id);train<-which(d$role==\"train\");validation<-which(d$role==\"validation\");test<-which(d$role==\"test\");p<-f$pred;cv<-curves(d,p,test);cal<-calibrate(d,p,test)\n for(i in seq_len(n)){\n  reason<-if(d$eligible[i])\"\"else\"required-X-or-Y-missing\";transformed<-if(d$eligible[i])paste(fmt(f$z[i,]),collapse=\"|\")else\"\"\n  add(\"predictions\",tagrow(kind,id=d$id[i],sourceRow=d$sourceRow[i],originalID=d$originalID[i],plannedRole=d$plannedRole[i],role=d$role[i],group=ifelse(is.na(d$group[i]),\"\",d$group[i]),eligible=as.integer(d$eligible[i]),targetExact=fmt(d$y[i]),probabilityExact=\"\",probabilityApprox=fmt(p[i]),unseenCell=ifelse(is.na(f$unseen[i]),\"\",as.character(as.integer(f$unseen[i]))),transformedX=transformed,reason=reason))\n  raw<-d$rawX[i,];raw[raw%in%c(\"\",\".\")]<-\"\";nativeY<-d$nativeTarget[i];if(nativeY%in%c(\"\",\".\"))nativeY<-\"\"\n  add(\"lineage\",tagrow(kind,id=d$id[i],sourceRow=d$sourceRow[i],originalID=d$originalID[i],nativeSourceRows=d$lineage[i],rawX=paste(raw,collapse=\"|\"),nativeTarget=nativeY,derivedTarget=fmt(d$y[i]),nativeGroup=ifelse(is.na(d$group[i]),\"\",d$group[i]),plannedRole=d$plannedRole[i],role=d$role[i],eligible=as.integer(d$eligible[i]),analyticalMass=\"1\",reason=reason))\n }\n for(j in seq_len(ncol(d$x)))add(\"fit-medians\",tagrow(kind,feature=j-1,categorical=as.integer((j-1)%in%d$cat),fitRows=length(train),medianExact=\"\",medianApprox=fmt(f$medians[j]),unit=d$units[j]))\n for(j in seq_along(f$lev))add(\"fit-cells\",tagrow(kind,cell=f$lev[j],trainingRows=f$mass[j],positiveRows=f$positive[j],probabilityExact=\"\",probabilityApprox=fmt(f$prob[j]),fallbackExact=\"\",fallbackApprox=fmt(f$fallback)))\n for(j in seq_along(cv$points)){\n  z<-cv$points[[j]];t<-z$policy;add(\"test-curves\",c(tagrow(kind,point=j-1,policy=if(is.character(t))t else\"threshold\",thresholdExact=\"\",thresholdApprox=if(is.character(t))\"\"else fmt(t)),scalars(z,c(\"TP\",\"FP\",\"FN\",\"TN\",\"TPR\",\"FPR\",\"precision\",\"recall\"))))\n  point(kind,\"roc\",\"ROC\",j-1,z$FPR,z$TPR);point(kind,\"pr\",\"PR-observed\",j-1,z$recall,z$precision)\n }\n for(b in 1:5){z<-cal$bins[[b]];add(\"calibration-bins\",c(tagrow(kind,bin=b-1,leftExact=c(\"0\",\"1/5\",\"2/5\",\"3/5\",\"4/5\")[b],rightExact=c(\"1/5\",\"2/5\",\"3/5\",\"4/5\",\"1\")[b],rightClosed=as.integer(b==5),rows=z$rows,ids=paste(z$ids,collapse=\";\")),scalars(z,c(\"mass\",\"meanPrediction\",\"eventRate\",\"gap\",\"absoluteGap\",\"scoreVariance\",\"scoreTargetCovariance\",\"withinBinCorrection\"))));point(kind,\"reliability\",\"Binary event rate\",b-1,z$meanPrediction,z$eventRate,tag=paste0(\"rows=\",z$rows))}\n for(j in seq_along(test)){i<-test[j];point(kind,\"test-scores\",\"Training-fitted probability\",j-1,j,p[i],\"test-row position\",\"probability\",tag=d$id[i]);point(kind,\"test-scores\",\"Observed Y\",j-1,j,d$y[i],\"test-row position\",\"binary target\",tag=d$id[i])}\n scenarioNames<-c(\"equal\",\"miss-five\",\"alarm-five\");costs<-list(c(1,1),c(1,5),c(5,1))\n for(s in 1:3){name<-scenarioNames[s];cost<-costs[[s]];grid<-c(list(\"always-negative\"),as.list(sort(unique(p[validation]),decreasing=TRUE)));candidates<-lapply(grid,function(t)measure(d,p,validation,t,cost));values<-vapply(candidates,function(m)m$meanCost,numeric(1));best<-which(values<=min(values)+1e-12)[1];chosen<-grid[[best]];ev<-measure(d,p,test,chosen,cost)\n  for(j in seq_along(grid)){t<-grid[[j]];m<-candidates[[j]];cell<-setNames(lapply(c(\"TP\",\"FP\",\"FN\",\"TN\"),function(k)fmt(m[[k]])),paste0(c(\"TP\",\"FP\",\"FN\",\"TN\"),\"Exact\"));add(\"validation-candidates\",c(tagrow(kind,scenario=name,candidate=j-1,selected=as.integer(j==best),policy=if(is.character(t))t else\"threshold\",thresholdExact=\"\",thresholdApprox=if(is.character(t))\"\"else fmt(t),feasible=1,reasons=\"\"),cell,scalars(m,c(counts,\"TPR\",\"FPR\",\"precision\",\"meanCost\",\"totalCost\"))));point(kind,\"validation-cost\",name,j-1,j-1,m$meanCost,\"candidate index\",\"hypothetical cost units/mass\",\"validation\",if(is.character(t))t else fmt(t))}\n  m<-c(ev,cv[c(\"ROC_AUC\",\"averagePrecision\",\"PRTrapezoidWithInitialPrecisionOne\")],cal[c(\"ECE\",\"reliability\",\"resolution\",\"uncertainty\",\"withinBinCorrection\",\"BrierIdentityResidual\")])\n  for(k in c(\"TP\",\"FP\",\"FN\",\"TN\",counts,rates,\"ROC_AUC\",\"averagePrecision\",\"PRTrapezoidWithInitialPrecisionOne\",\"ECE\",\"reliability\",\"resolution\",\"uncertainty\",\"withinBinCorrection\",\"BrierIdentityResidual\")){\n   unit<-if(k%in%c(\"TP\",\"FP\",\"FN\",\"TN\",counts))\"rows\"else if(k==\"totalCost\")\"hypothetical cost units\"else if(k==\"meanCost\")\"hypothetical cost units/mass\"else if(k==\"BrierSum\")\"sum squared-probability loss\"else\"dimensionless\"\n   add(\"test-metrics\",tagrow(kind,scenario=name,metric=k,valueExact=\"\",valueApprox=fmt(m[[k]]),unit=unit))\n  }\n  lev<-unique(d$group[test][!is.na(d$group[test])]);sets<-c(list(test),lapply(lev,function(g)test[!is.na(d$group[test])&d$group[test]==g]),list(test[is.na(d$group[test])]))\n  types<-c(\"overall\",rep(\"known\",length(lev)),\"unknown\");tokens<-c(\"all\",lev,\"\")\n  for(j in seq_along(sets)){ids<-sets[[j]];m<-measure(d,p,ids,chosen,cost);cell<-setNames(lapply(c(\"TP\",\"FP\",\"FN\",\"TN\"),function(k)fmt(m[[k]])),paste0(c(\"TP\",\"FP\",\"FN\",\"TN\"),\"Exact\"));add(\"group-metrics\",c(tagrow(kind,scenario=name,groupType=types[j],groupToken=tokens[j],retainedRows=length(ids)),cell,scalars(m,c(counts,rates))));if(types[j]==\"known\")point(kind,\"group-TPR\",name,j-2,j-2,m$TPR,\"declared group position\",\"TPR\",tag=tokens[j])}\n }\n invisible(NULL)\n}\n\n# Fixed finite inputs only; not the complete web input/budget validator.\nqnum<-function(v){if(is.null(v))return(NA_real_);if(is.logical(v))return(as.numeric(v));s<-as.character(v);if(grepl(\"/\",s,fixed=TRUE)){a<-strsplit(s,\"/\",fixed=TRUE)[[1]];return(as.numeric(a[1])/as.numeric(a[2]))};as.numeric(s)}\nrowsG<-function(raw){\n n<-length(raw);get<-function(r,k,default=NULL)if(is.null(r[[k]]))default else r[[k]]\n id<-vapply(raw,function(r)as.character(r$id),character(1));p<-vapply(raw,function(r)qnum(r$score),numeric(1));y<-vapply(raw,function(r)qnum(r$y),numeric(1));w<-vapply(raw,function(r)qnum(get(r,\"weight\",\"1\")),numeric(1));role<-vapply(raw,function(r)get(r,\"role\",\"evaluation\"),character(1));group<-vapply(raw,function(r)as.character(get(r,\"group\",NA_character_)),character(1))\n stopifnot(all(w>=0),all(is.na(p)|(p>=0&p<=1)),all(is.na(y)|y%in%c(0,1)),!anyDuplicated(id));list(id=id,p=p,y=y,w=w,role=role,group=group,eligible=!is.na(p)&!is.na(y)&w>0&role!=\"excluded\")\n}\nscopeG<-function(d,role=\"all\")if(role==\"all\")seq_along(d$id)else which(d$role==role)\nmetricsG<-function(d,ids,t=.5,cost=c(1,1)){\n use<-ids[d$eligible[ids]];p<-d$p[use];y<-d$y[use];w<-d$w[use];a<-if(is.character(t))rep(t==\"always-positive\",length(use))else p>=t\n TP<-sum(w[a&y==1]);FP<-sum(w[a&y==0]);FN<-sum(w[!a&y==1]);TN<-sum(w[!a&y==0]);P<-TP+FN;N<-FP+TN;W<-P+N;PP<-TP+FP;PN<-TN+FN;TPR<-ratio(TP,P);TNR<-ratio(TN,N);bs<-sum(w*(p-y)^2);tc<-FP*cost[1]+FN*cost[2]\n list(confusion=list(TP=TP,FP=FP,FN=FN,TN=TN),mass=W,positiveTargetMass=P,negativeTargetMass=N,predictedPositiveMass=PP,predictedNegativeMass=PN,prevalence=ratio(P,W),selectionRate=ratio(PP,W),accuracy=ratio(TP+TN,W),precision=ratio(TP,PP),negativePredictiveValue=ratio(TN,PN),TPR=TPR,FPR=ratio(FP,N),TNR=TNR,FNR=ratio(FN,P),F1=ratio(2*TP,2*TP+FP+FN),balancedAccuracy=if(is.na(TPR)||is.na(TNR))NA_real_ else(TPR+TNR)/2,Brier=ratio(bs,W),BrierSum=bs,totalCost=tc,meanCost=ratio(tc,W),bayesThreshold=ratio(cost[1],sum(cost)))\n}\ncurvesG<-function(d,ids){\n use<-ids[d$eligible[ids]];grid<-c(list(\"always-negative\"),as.list(sort(unique(d$p[use]),decreasing=TRUE)));points<-lapply(grid,function(t){m<-metricsG(d,ids,t);c(list(policy=t),m$confusion,m[c(\"TPR\",\"FPR\",\"precision\")],list(recall=m$TPR))});pos<-use[d$y[use]==1];neg<-use[d$y[use]==0];P<-sum(d$w[pos]);N<-sum(d$w[neg]);U<-0\n for(i in pos)U<-U+d$w[i]*sum(d$w[neg]*((d$p[i]>d$p[neg])+.5*(d$p[i]==d$p[neg])))\n AP<-trap<-lastR<-0;lastP<-1\n if(P&&length(grid)>1)for(j in 2:length(grid)){z<-points[[j]];AP<-AP+(z$recall-lastR)*z$precision;trap<-trap+(z$recall-lastR)*(z$precision+lastP)/2;lastR<-z$recall;lastP<-z$precision}\n list(points=points,ROC_AUC=ratio(U,P*N),averagePrecision=if(P)AP else NA_real_,PRTrapezoidWithInitialPrecisionOne=if(P)trap else NA_real_)\n}\nchooseG<-function(d,a,cost){\n role<-if(is.null(a$selectionRole))\"validation\"else a$selectionRole;er<-if(is.null(a$evaluationRole))\"test\"else a$evaluationRole;ids<-scopeG(d,role);use<-ids[d$eligible[ids]];stopifnot(length(use)>0);grid<-if(is.null(a$thresholds))c(list(\"always-negative\"),as.list(sort(unique(d$p[use]),decreasing=TRUE)))else lapply(a$thresholds,function(t)if(t%in%c(\"always-negative\",\"always-positive\"))t else qnum(t))\n candidates<-lapply(seq_along(grid),function(j){m<-metricsG(d,ids,grid[[j]],cost);feasible<-TRUE;if(!is.null(a$minTPR))feasible<-feasible&&!is.na(m$TPR)&&m$TPR>=qnum(a$minTPR);if(!is.null(a$maxFPR))feasible<-feasible&&!is.na(m$FPR)&&m$FPR<=qnum(a$maxFPR);list(index=j-1,policy=grid[[j]],metrics=m,feasible=feasible)})\n good<-which(vapply(candidates,function(c)c$feasible,logical(1)));best<-NA_integer_;if(length(good)){v<-vapply(candidates[good],function(c)c$metrics$meanCost,numeric(1));best<-good[which(v<=min(v)+1e-12)[1]]}\n list(selectedIndex=if(is.na(best))NA_integer_ else best-1,selectedPolicy=if(is.na(best))NULL else grid[[best]],selectedValidation=if(is.na(best))NULL else candidates[[best]]$metrics,candidates=candidates,evaluation=if(is.na(best)||er==\"none\")NULL else metricsG(d,scopeG(d,er),grid[[best]],cost))\n}\ncalibrateG<-function(d,ids,edges){\n use<-ids[d$eligible[ids]];W<-sum(d$w[use]);pi<-ratio(sum(d$w[use]*d$y[use]),W);bins<-list();ECE<-rel<-res<-correction<-0;assign<-findInterval(d$p[use],edges,rightmost.closed=TRUE,all.inside=TRUE)\n for(b in seq_len(length(edges)-1)){rr<-use[assign==b];w<-sum(d$w[rr]);mp<-ratio(sum(d$w[rr]*d$p[rr]),w);o<-ratio(sum(d$w[rr]*d$y[rr]),w);variance<-if(w)sum(d$w[rr]*(d$p[rr]-mp)^2)/w else NA_real_;covariance<-if(w)sum(d$w[rr]*(d$p[rr]-mp)*(d$y[rr]-o))/w else NA_real_;bc<-variance-2*covariance;gap<-mp-o;bins[[b]]<-list(index=b-1,mass=w,meanPrediction=mp,eventRate=o,scoreVariance=variance,scoreTargetCovariance=covariance,withinBinCorrection=bc,ids=d$id[rr])\n  if(w){s<-w/W;ECE<-ECE+s*abs(gap);rel<-rel+s*gap^2;res<-res+s*(o-pi)^2;correction<-correction+s*bc}\n };bs<-ratio(sum(d$w[use]*(d$p[use]-d$y[use])^2),W);unc<-pi*(1-pi);list(bins=bins,Brier=bs,ECE=if(W)ECE else NA_real_,uncertainty=unc,reliability=if(W)rel else NA_real_,resolution=if(W)res else NA_real_,withinBinCorrection=if(W)correction else NA_real_,BrierIdentityResidual=bs-(unc-res+rel+correction))\n}\ngroupsG<-function(d,ids,t,cost){\n lev<-unique(d$group[ids][!is.na(d$group[ids])]);groups<-lapply(lev,function(g)list(group=g,metrics=metricsG(d,ids[!is.na(d$group[ids])&d$group[ids]==g],t,cost)));overall<-metricsG(d,ids,t,cost);unknown<-metricsG(d,ids[is.na(d$group[ids])],t,cost);gaps<-list()\n for(k in c(\"prevalence\",\"selectionRate\",\"TPR\",\"FPR\",\"precision\",\"accuracy\",\"meanCost\")){use<-Filter(function(g)g$metrics$mass>0,groups);v<-vapply(use,function(g)g$metrics[[k]],numeric(1));gaps[[k]]<-if(length(use)<2||anyNA(v))NA_real_ else max(v)-min(v)}\n list(overall=overall,groups=groups,unknownGroup=unknown,gaps=gaps,partitionMassResidual=overall$mass-unknown$mass-sum(vapply(groups,function(g)g$metrics$mass,numeric(1))))\n}\nsvgFixed<-function(file,points,title,xlabel,ylabel,legend){\n finite<-points[points$y!=\"undefined\"&points$x!=\"undefined\",,drop=FALSE];x<-as.numeric(finite$x);y<-as.numeric(finite$y);xmin<-if(length(x))min(x)else 0;xmax<-if(length(x))max(x)else 1;ymin<-min(c(0,y));ymax<-max(c(0,y));if(xmin==xmax){xmin<-xmin-.5;xmax<-xmax+.5};if(ymin==ymax)ymax<-ymin+1;X<-function(v)85+(v-xmin)/(xmax-xmin)*480;Y<-function(v)278-(v-ymin)/(ymax-ymin)*175\n esc<-function(s){s<-gsub(\"&\",\"&amp;\",s,fixed=TRUE);s<-gsub(\"<\",\"&lt;\",s,fixed=TRUE);gsub(\">\",\"&gt;\",s,fixed=TRUE)};s<-'<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"620\" height=\"360\" viewBox=\"0 0 620 360\"><rect width=\"620\" height=\"360\" fill=\"white\"/><g font-family=\"Arial, sans-serif\" font-size=\"13\" fill=\"#17324d\">'\n lines<-strwrap(title,width=65);for(i in seq_along(lines))s<-paste0(s,'<text x=\"25\" y=\"',24+(i-1)*18,'\">',esc(lines[i]),'</text>');colors<-c(\"#176b9b\",\"#b85e18\",\"#437e4d\")\n for(i in seq_along(legend))s<-paste0(s,'<circle cx=\"',30+(i-1)*250,'\" cy=\"76\" r=\"4\" fill=\"',colors[(i-1)%%3+1],'\"/><text x=\"',42+(i-1)*250,'\" y=\"80\">',esc(legend[i]),'</text>')\n s<-paste0(s,'<path d=\"M85 98V278H575\" fill=\"none\" stroke=\"#52677d\"/><text text-anchor=\"middle\" x=\"325\" y=\"338\">',esc(xlabel),'</text><text text-anchor=\"middle\" transform=\"translate(21,190) rotate(-90)\">',esc(ylabel),'</text>')\n for(i in 0:4){xx<-xmin+(xmax-xmin)*i/4;yy<-ymin+(ymax-ymin)*i/4;s<-paste0(s,'<text text-anchor=\"middle\" x=\"',sprintf(\"%.9g\",X(xx)),'\" y=\"305\">',sprintf(\"%.4g\",xx),'</text><text text-anchor=\"end\" x=\"77\" y=\"',sprintf(\"%.9g\",Y(yy)+4),'\">',sprintf(\"%.4g\",yy),'</text>')}\n for(i in seq_len(nrow(finite)))s<-paste0(s,'<circle cx=\"',sprintf(\"%.9g\",X(x[i])),'\" cy=\"',sprintf(\"%.9g\",Y(y[i])),'\" r=\"3\" fill=\"',colors[as.integer(finite$series[i])%%3+1],'\"/>');writeLines(paste0(s,'</g></svg>'),file,useBytes=TRUE)\n}\nfixedRun<-function(){\n api<-FIXED$api;a<-FIXED$args;summary<-list();points<-list();xlabel<-\"Declared index\";ylabel<-\"Value\";legend<-\"Declared result\"\n metric<-function(name,v,unit=\"dimensionless\"){if(is.null(v))v<-NA_real_;summary[[length(summary)+1L]]<<-data.frame(metric=name,value=if(is.na(v))\"undefined\"else sprintf(\"%.9g\",v),exactValue=\"\",unit=unit,defined=as.integer(!is.na(v)),stringsAsFactors=FALSE)}\n pt<-function(i,x,y,id=\"\",series=0){points[[length(points)+1L]]<<-data.frame(series=series,index=i,xExact=\"\",x=if(is.na(x))\"undefined\"else sprintf(\"%.9g\",x),yExact=\"\",y=if(is.na(y))\"undefined\"else sprintf(\"%.9g\",y),id=as.character(id),stringsAsFactors=FALSE)}\n if(api==\"realdata\"){\n  native<-loadData()[[a$kind]];fit<-fitmodel(native);d<-list(id=native$id,p=fit$pred,y=native$y,w=rep(1,length(native$id)),role=native$role,group=native$group,eligible=native$eligible);scenarios<-list()\n  for(j in 1:3){name<-c(\"equal\",\"miss-five\",\"alarm-five\")[j];cst<-list(c(1,1),c(1,5),c(5,1))[[j]];sel<-chooseG(d,list(),cst);scenarios[[j]]<-list(name=name,selection=sel);metric(paste0(name,\"Threshold\"),sel$selectedPolicy);metric(paste0(name,\"TestCost\"),sel$evaluation$meanCost,\"hypothetical cost units/mass\")}\n  ids<-scopeG(d,\"test\");cv<-curvesG(d,ids);cal<-calibrateG(d,ids,seq(0,1,.2));metric(\"testAUC\",cv$ROC_AUC);metric(\"testAP\",cv$averagePrecision);metric(\"testBrier\",cal$Brier);metric(\"eligibleRows\",sum(d$eligible),\"rows\")\n  for(j in seq_along(ids)){i<-ids[j];pt(j-1,j,d$p[i],d$id[i],0);pt(j-1,j,d$y[i],d$id[i],1)}\n  full<-list(kind=a$kind,fit=fit,scenarios=scenarios,testCurves=cv,testCalibration=cal,rowsScored=d);xlabel<-\"Test row, native order\";ylabel<-\"Y or probability\";legend<-c(\"Training-fitted probability\",\"Observed Y\")\n }else{\n  d<-rowsG(a$rows);role<-if(is.null(a$role))\"all\"else a$role;ids<-scopeG(d,role);cost<-if(is.null(a$costs))c(1,1)else c(qnum(a$costs$falsePositive),qnum(a$costs$falseNegative));t<-if(is.null(a$threshold)).5 else if(a$threshold%in%c(\"always-positive\",\"always-negative\"))a$threshold else qnum(a$threshold)\n  if(api==\"metrics\"){\n   full<-metricsG(d,ids,t,cost);for(k in c(\"mass\",\"accuracy\",\"precision\",\"TPR\",\"FPR\",\"F1\",\"Brier\",\"meanCost\"))metric(k,full[[k]],if(k==\"mass\")\"mass\"else if(k==\"meanCost\")\"hypothetical cost units/mass\"else\"dimensionless\");metric(\"BayesThreshold\",full$bayesThreshold)\n   for(i in 1:4)pt(i-1,i-1,full$confusion[[i]],names(full$confusion)[i]);xlabel<-\"TP / FP / FN / TN positions\";ylabel<-\"Analytical mass\"\n  }else if(api==\"curves\"){\n   full<-curvesG(d,ids);for(k in c(\"ROC_AUC\",\"averagePrecision\",\"PRTrapezoidWithInitialPrecisionOne\"))metric(k,full[[k]])\n   for(j in seq_along(full$points)){p<-full$points[[j]];pt(j-1,p$FPR,p$TPR,if(is.character(p$policy))p$policy else sprintf(\"%.17g\",p$policy))};xlabel<-\"False positive rate\";ylabel<-\"True positive rate\";legend<-\"Observed ROC operating points\"\n  }else if(api==\"choose\"){\n   full<-chooseG(d,a,cost);metric(\"selectedIndex\",full$selectedIndex,\"candidate index\");metric(\"minimumCost\",if(is.null(full$selectedValidation))NULL else full$selectedValidation$meanCost,\"hypothetical cost units/mass\");metric(\"feasible\",as.integer(!is.na(full$selectedIndex)),\"indicator\")\n   for(c in full$candidates)pt(c$index,c$index,c$metrics$meanCost,if(is.character(c$policy))c$policy else sprintf(\"%.17g\",c$policy));xlabel<-\"Validation candidate\";ylabel<-\"Assumed cost / mass\";legend<-\"Validation candidate costs\"\n  }else if(api==\"calibrate\"){\n   edges<-if(is.null(a$binEdges))seq(0,1,.2)else vapply(a$binEdges,qnum,numeric(1));full<-calibrateG(d,ids,edges);for(k in c(\"ECE\",\"Brier\",\"uncertainty\",\"resolution\",\"reliability\",\"withinBinCorrection\",\"BrierIdentityResidual\"))metric(k,full[[k]])\n   for(b in full$bins)pt(b$index,b$meanPrediction,b$eventRate,paste0(\"bin:\",b$index));xlabel<-\"Bin mean forecast\";ylabel<-\"Bin event rate\";legend<-\"Binary-event reliability\"\n  }else if(api==\"groups\"){\n   full<-groupsG(d,ids,t,cost);metric(\"overallTPR\",full$overall$TPR);metric(\"TPRGap\",full$gaps$TPR);metric(\"precisionGap\",full$gaps$precision);metric(\"unknownMass\",full$unknownGroup$mass,\"mass\");metric(\"partitionResidual\",full$partitionMassResidual,\"mass\")\n   for(j in seq_along(full$groups))pt(j-1,j-1,full$groups[[j]]$metrics$TPR,full$groups[[j]]$group);xlabel<-\"Declared group position\";ylabel<-\"True positive rate\";legend<-\"Known-group TPR\"\n  }else stop(\"unknown declared fixed API\")\n }\n sm<-do.call(rbind,summary);pp<-do.call(rbind,points);write.csv(sm,file.path(outDir,\"summary.csv\"),row.names=FALSE,na=\"\");write.csv(pp,file.path(outDir,\"plot-points.csv\"),row.names=FALSE,na=\"\");svgFixed(file.path(outDir,\"plot.svg\"),pp,FIXED$title,xlabel,ylabel,legend);dput(list(api=api,variant=FIXED$variant,input=FIXED$args,arithmetic=\"Base-R binary64 fixed example; not an exact rational general validator\",result=full),file=file.path(outDir,\"full.txt\"));cat(\"PASS\",api,FIXED$variant,\"summary\",nrow(sm),\"points\",nrow(pp),\"\\n\")\n}\n\nFIXED<-list(api=\"metrics\",variant=\"reject-negative-weight\",args=list(rows=list(list(id=\"bad\",score=\".5\",y=0,weight=\"-1\"))),title=\"Reject a declared negative analytical mass\",expectedReject=TRUE)\nfixedRun()\n",
        "input": {
          "rows": [
            {
              "id": "bad",
              "score": ".5",
              "y": 0,
              "weight": "-1"
            }
          ]
        },
        "inputFiles": [],
        "returnCode": 1,
        "expectedFailure": true,
        "stdout": "",
        "stderr": "During startup - Warning messages:\n1: Setting LC_COLLATE=C.UTF-8 failed \n2: Setting LC_CTYPE=C.UTF-8 failed \n3: Setting LC_MONETARY=C.UTF-8 failed \n4: Setting LC_TIME=C.UTF-8 failed \nError in rowsG(a$rows) : all(w >= 0) is not TRUE\nCalls: fixedRun -> rowsG -> stopifnot\nExecution halted\n",
        "summary": {},
        "summaryRows": [],
        "plotPoints": [],
        "plotFile": null,
        "plotSHA256": null,
        "files": [],
        "scope": "Actually executed standalone fixed example, Python exact Fraction versus base-R binary64. Approximate R residuals retained; not universal exact arithmetic/web validation/native UI. Source programs read factual3CSV only."
      }
    }
  },
  "curves": {
    "python": {
      "six-cards": {
        "api": "curves",
        "variant": "six-cards",
        "language": "python",
        "title": "Tied-score six-card ROC, AP and labeled PR trapezoid",
        "codeFile": "ml14-code/curves-six-cards.py",
        "codeSHA256": "382e788306e480577768abab6a8b010ee5ceb80e4f88600baa4eea3db1214269",
        "code": "#!/usr/bin/env python3\n\"\"\"ML14 standalone exact finite study, Python standard library only.\nInputs: only the three retained factual source CSVs below.\nDerived role/target/group/eligibility columns in those CSVs are NOT inputs.\nRebuilds SHA256 roles, train-only medians/cell scores, validation thresholds,\ntest curves, binary-event reliability and descriptive group ledgers.\nCosts 1/1,1/5,5/1 are hypothetical units, not measured intervention returns.\nThis is author public reproduction, not independent scientific review.\n\"\"\"\n\"\"\"Author Fraction reference, separate from product JavaScript; not independent peer.\"\"\"\nfrom fractions import Fraction as F\nfrom collections import Counter,defaultdict\ndef read(raw):\n rows=[]\n for i,r in enumerate(raw):\n  s=None if r['score']is None else F(str(r['score']));y=None if r['y']is None else F(int(r['y']))if isinstance(r['y'],bool)else F(str(r['y']));w=F(str(r.get('weight','1')));role=r.get('role','evaluation')\n  rows.append(dict(id=r['id'],index=i,score=s,y=y,w=w,role=role,group=r.get('group'),eligible=s is not None and y is not None and w>0 and role!='excluded'))\n return rows\ndef scoped(rows,role='all'):return rows if role=='all'else[r for r in rows if r['role']==role]\ndef divide(n,d):return None if not d else n/d\ndef policy(v):return v if v in ['always-negative','always-positive']else F(str(v))\ndef positive(p,s):return p=='always-positive'if isinstance(p,str)else s>=p\ndef cost(a=None):\n a={}if a is None else a;fp=F(str(a.get('falsePositive','1')));fn=F(str(a.get('falseNegative','1')));return fp,fn\ndef metrics(rows,threshold=F(1,2),cc=(F(1),F(1))):\n counts=dict(TP=F(0),FP=F(0),FN=F(0),TN=F(0));brier=F(0);pred=[]\n for r in rows:\n  if not r['eligible']:pred.append(dict(id=r['id'],index=r['index'],eligible=False,decision=None,probability=None,Brier=None));continue\n  yes=positive(threshold,r['score']);cell=('T'if yes==bool(r['y'])else'F')+('P'if yes else'N');counts[cell]+=r['w'];loss=(r['score']-r['y'])**2;brier+=r['w']*loss;pred.append(dict(id=r['id'],index=r['index'],eligible=True,decision=int(yes),probability=r['score'],Brier=loss))\n TP,FP,FN,TN=[counts[k]for k in ['TP','FP','FN','TN']];P=TP+FN;N=TN+FP;mass=P+N;PP=TP+FP;PN=TN+FN;TPR=divide(TP,P);TNR=divide(TN,N);total=FP*cc[0]+FN*cc[1]\n return dict(confusion=counts,mass=mass,positiveTargetMass=P,negativeTargetMass=N,predictedPositiveMass=PP,predictedNegativeMass=PN,prevalence=divide(P,mass),selectionRate=divide(PP,mass),accuracy=divide(TP+TN,mass),precision=divide(TP,PP),negativePredictiveValue=divide(TN,PN),TPR=TPR,FPR=divide(FP,N),TNR=TNR,FNR=divide(FN,P),F1=divide(2*TP,2*TP+FP+FN),balancedAccuracy=None if TPR is None or TNR is None else(TPR+TNR)/2,Brier=divide(brier,mass),BrierSum=brier,totalCost=total,meanCost=divide(total,mass),predictions=pred,bayesThreshold=divide(cc[0],sum(cc)))\ndef curves(rows):\n use=[r for r in rows if r['eligible']];pos=Counter();neg=Counter()\n for r in use:(pos if r['y']else neg)[r['score']]+=r['w']\n P=sum(pos.values(),F(0));N=sum(neg.values(),F(0));pairs=F(0)\n for a,wa in pos.items():\n  for b,wb in neg.items():pairs+=wa*wb*(F(1)if a>b else F(1,2)if a==b else F(0))\n thresholds=['always-negative']+sorted({r['score']for r in use},reverse=True);points=[];AP=F(0);trap=F(0);lastR=F(0);lastP=F(1)\n for i,p in enumerate(thresholds):\n  m=metrics(rows,p);points.append(dict(policy=p,TP=m['confusion']['TP'],FP=m['confusion']['FP'],FN=m['confusion']['FN'],TN=m['confusion']['TN'],TPR=m['TPR'],FPR=m['FPR'],precision=m['precision'],recall=m['TPR']))\n  if i and P:\n   R=m['TPR'];PP=m['precision'];AP+=(R-lastR)*PP;trap+=(R-lastR)*(PP+lastP)/2;lastR=R;lastP=PP\n return dict(positiveMass=P,negativeMass=N,ROC_AUC=divide(pairs,P*N),weightedConcordantPlusHalfTiedMass=pairs,averagePrecision=AP if P else None,PRTrapezoidWithInitialPrecisionOne=trap if P else None,points=points)\ndef choose(rows,a,cc):\n sr=a.get('selectionRole','validation');er=a.get('evaluationRole','test');rr=scoped(rows,sr);thresholds=[policy(t)for t in a['thresholds']]if'thresholds'in a else['always-negative']+sorted({r['score']for r in rr if r['eligible']},reverse=True)\n candidates=[]\n for i,p in enumerate(thresholds):\n  m=metrics(rr,p,cc);reasons=[]\n  if'minTPR'in a and(m['TPR']is None or m['TPR']<F(str(a['minTPR']))):reasons.append('TPR-undefined'if m['TPR']is None else'below-minTPR')\n  if'maxFPR'in a and(m['FPR']is None or m['FPR']>F(str(a['maxFPR']))):reasons.append('FPR-undefined'if m['FPR']is None else'above-maxFPR')\n  candidates.append(dict(index=i,policy=p,metrics=m,feasible=not reasons,reasons=reasons))\n eligible=[c for c in candidates if c['feasible']];best=min(eligible,key=lambda c:(c['metrics']['meanCost'],c['index']))if eligible else None\n return dict(selectedIndex=None if best is None else best['index'],selectedPolicy=None if best is None else best['policy'],candidates=candidates,selectedValidation=None if best is None else best['metrics'],evaluation=None if best is None or er=='none'else metrics(scoped(rows,er),best['policy'],cc),selectionIDs=[r['id']for r in rr if r['eligible']])\ndef calibrate(rows,ee):\n buckets=[[]for _ in range(len(ee)-1)]\n for r in rows:\n  if not r['eligible']:continue\n  j=next((i for i in range(len(ee)-1)if r['score']<ee[i+1]),len(ee)-2);buckets[j].append(r)\n mass=sum((r['w']for r in rows if r['eligible']),F(0));P=sum((r['w']*r['y']for r in rows if r['eligible']),F(0));pi=divide(P,mass);Brier=None if not mass else sum((r['w']*(r['score']-r['y'])**2 for r in rows if r['eligible']),F(0))/mass;ECE=F(0);reliability=F(0);resolution=F(0);correction=F(0);bins=[]\n for i,rr in enumerate(buckets):\n  w=sum((r['w']for r in rr),F(0));mp=None if not w else sum((r['w']*r['score']for r in rr),F(0))/w;o=None if not w else sum((r['w']*r['y']for r in rr),F(0))/w\n  variance=None if not w else sum((r['w']*(r['score']-mp)**2 for r in rr),F(0))/w\n  covariance=None if not w else sum((r['w']*(r['score']-mp)*(r['y']-o)for r in rr),F(0))/w\n  bc=None if not w else variance-2*covariance;gap=None if not w else mp-o\n  bins.append(dict(index=i,rows=len(rr),mass=w,meanPrediction=mp,eventRate=o,gap=gap,absoluteGap=None if gap is None else abs(gap),scoreVariance=variance,scoreTargetCovariance=covariance,withinBinCorrection=bc,ids=[r['id']for r in rr]))\n  if w:\n   share=w/mass;ECE+=share*abs(gap);reliability+=share*gap**2;resolution+=share*(o-pi)**2;correction+=share*bc\n uncertainty=None if pi is None else pi*(1-pi);residual=None if Brier is None else Brier-(uncertainty-resolution+reliability+correction)\n return dict(mass=mass,prevalence=pi,Brier=Brier,ECE=ECE if mass else None,reliability=reliability if mass else None,resolution=resolution if mass else None,uncertainty=uncertainty,withinBinCorrection=correction if mass else None,BrierIdentityResidual=residual,bins=bins)\ndef typed(v):return type(v).__name__,v\ndef groups(rows,p,cc):\n bins={}\n for r in rows:\n  if r['group']is not None:bins.setdefault(typed(r['group']),[]).append(r)\n gm=[dict(group=rr[0]['group'],metrics=metrics(rr,p,cc))for rr in bins.values()];overall=metrics(rows,p,cc);unknown=metrics([r for r in rows if r['group']is None],p,cc);gaps={}\n for key in ['prevalence','selectionRate','TPR','FPR','precision','accuracy','meanCost']:\n  positive=[g for g in gm if g['metrics']['mass']>0];undefined=[g['group']for g in positive if g['metrics'][key]is None];vals=[g['metrics'][key]for g in positive if g['metrics'][key]is not None]\n  gaps[key]=dict(value=None if len(positive)<2 or undefined else max(vals)-min(vals),undefinedGroups=undefined,comparedPositiveMassGroups=[g['group']for g in positive])\n return dict(overall=overall,groups=gm,unknownGroup=unknown,gaps=gaps,partitionMassResidual=overall['mass']-unknown['mass']-sum((g['metrics']['mass']for g in gm),F(0)))\ndef actual_model(M):\n raw=M['records'];cat=M['categoricalFeatures'];p=len(raw[0]['x']);train=[r for r in raw if r['role']=='train'];medians=[]\n for j in range(p):\n  if j in cat:medians.append(None);continue\n  values=sorted(F(r['x'][j])for r in train);n=len(values);medians.append(values[n//2]if n%2 else(values[n//2-1]+values[n//2])/2)\n def transform(r):return[F(v)if j in cat else F(int(F(v)>medians[j]))for j,v in enumerate(r['x'])]\n counts={}\n for r in train:\n  key=tuple(transform(r));n,s=counts.get(key,(0,0));counts[key]=(n+1,s+int(r['y']))\n probabilities={k:F(s+1,n+2)for k,(n,s)in counts.items()};fallback=F(sum(int(r['y'])for r in train)+1,len(train)+2);scored=[]\n for i,r in enumerate(raw):\n  eligible=r['role']!='excluded';z=transform(r)if eligible else None;key=None if z is None else tuple(z);score=None if not eligible else probabilities.get(key,fallback)\n  scored.append(dict(id=r['id'],index=i,role=r['role'],group=r['group'],y=None if r['y']is None else F(r['y']),score=score,w=F(1),eligible=eligible,transformedX=z,unseenCell=None if not eligible else key not in probabilities))\n return dict(medians=medians,cells=counts,probabilities=probabilities,fallback=fallback,rows=scored,trainIDs=[r['id']for r in train])\n\n\nimport csv,json,hashlib,argparse,datetime\nfrom pathlib import Path\ndef missing(v):return None if v in ['', '.',None]else v\ndef load_sources(folder):\n def read_csv(name):\n  with (folder/name).open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))\n wb=read_csv('actual64-country-four-indicators-original-2024.csv')\n codes=['NY.GDP.PCAP.KD','NY.GDP.MKTP.KD.ZG','FP.CPI.TOTL.ZG','SP.DYN.LE00.IN']\n lookup={(r['countryISO3'],r['indicatorID']):r for r in wb};country=[]\n for i,iso in enumerate(sorted({r['countryISO3']for r in wb}),1):\n  native=[lookup[iso,c]for c in codes];v=[missing(r['originalValueToken'])for r in native]\n  country.append(dict(id=iso+':2024',sourceRow=i,originalID=iso,x=v[:3],y=None if v[3]is None else str(int(F(v[3])>=80)),group=None if v[0]is None else str(int(F(v[0])>=25000)),nativeTarget=v[3],nativeSourceRows=';'.join(r['sourceRow']for r in native)))\n nls=read_csv('actual3613-NLS-original52-fields-groups-roles.csv');person=[]\n for r in nls:\n  y=missing(r['wage76']);person.append(dict(id='person:'+r['sourceRow'],sourceRow=int(r['sourceRow']),originalID=r['id'],x=[missing(r[k])for k in ['ed76','age76','nearc4']],y=None if y is None else str(int(F(y)>=500)),group=missing(r['black']),nativeTarget=y,nativeSourceRows=r['sourceRow']))\n ch=read_csv('actual3150-churn-original14-fields-groups-roles.csv');company=[]\n for r in ch:\n  company.append(dict(id='customer:'+r['sourceRow'],sourceRow=int(r['sourceRow']),originalID='',x=[missing(r[k])for k in ['Call  Failure','Complains','Subscription  Length','Seconds of Use']],y=missing(r['Churn']),group=missing(r['Tariff Plan']),nativeTarget=missing(r['Churn']),nativeSourceRows=r['sourceRow']))\n assert len(wb)==64 and len(country)==16 and len(nls)==3613 and len(ch)==3150\n assert [int(r['sourceRow'])for r in ch if r['Charge  Amount']=='10']==[474,2174,2274,2374,2674,2924,2974]\n models={}\n for kind,raw,cat,units in [('country',country,[],['constant2015USD/person','annualPercent','annualPercent']),('person',person,[2],['years','years','nativeCategory']),('company',company,[1],['count','nativeCategory','months','seconds'])]:\n  order=sorted(range(len(raw)),key=lambda i:(hashlib.sha256(('ML14-role|'+kind+'|'+raw[i]['id']).encode()).hexdigest(),i))\n  for rank,i in enumerate(order):\n   r=raw[i];r['plannedRole']='test'if rank%5==0 else'validation'if rank%5==1 else'train';r['eligible']=None not in r['x']+[r['y']];r['role']=r['plannedRole']if r['eligible']else'excluded';r['weight']='1'\n  models[kind]=dict(records=raw,categoricalFeatures=cat,featureUnits=units)\n assert sum(r['eligible']for r in person)==3017\n return models\n\ndef exact(v):return ''if v is None else str(v)\ndef approx(v):return ''if v is None else format(float(v),'.17g')\ndef scalar_fields(m,keys):\n out={}\n for k in keys:\n  out[k+'Exact']=exact(m[k]);out[k+'Approx']=approx(m[k])\n return out\nCOUNTS=['mass','positiveTargetMass','negativeTargetMass','predictedPositiveMass','predictedNegativeMass']\nRATES=['prevalence','selectionRate','accuracy','precision','negativePredictiveValue','TPR','FPR','TNR','FNR','F1','balancedAccuracy','Brier','BrierSum','totalCost','meanCost']\nSCENARIOS=[('equal',F(1),F(1)),('miss-five',F(1),F(5)),('alarm-five',F(5),F(1))]\ndef packed(v):\n if isinstance(v,F):return str(v)\n if isinstance(v,dict):return{str(k):packed(x)for k,x in v.items()}\n if isinstance(v,(tuple,list)):return[packed(x)for x in v]\n return v\ndef run_study(source,out):\n out.mkdir(parents=True,exist_ok=True);models=load_sources(source)\n tables={name:[]for name in ['predictions','lineage','fit-medians','fit-cells','validation-candidates','test-metrics','test-curves','calibration-bins','group-metrics','chart-points']}\n studies={};charts=[]\n def point(kind,chart,series,index,x,y,xunit='dimensionless',yunit='dimensionless',role='test',tag=''):\n  tables['chart-points'].append(dict(kind=kind,chart=chart,series=series,index=index,xExact=exact(x),xApprox=approx(x),yExact=exact(y),yApprox=approx(y),xUnit=xunit,yUnit=yunit,role=role,tag=tag))\n for kind,M in models.items():\n  fit=actual_model(M);rr=fit['rows'];native=M['records'];test=scoped(rr,'test');cv=curves(test);cal=calibrate(test,[F(0),F(1,5),F(2,5),F(3,5),F(4,5),F(1)]);scenarios=[]\n  for i,r in enumerate(rr):\n   n=native[i];reason=''if r['eligible']else'required-X-or-Y-missing'\n   tables['predictions'].append(dict(kind=kind,id=r['id'],sourceRow=n['sourceRow'],originalID=n['originalID'],plannedRole=n['plannedRole'],role=r['role'],group=''if r['group']is None else r['group'],eligible=int(r['eligible']),targetExact=exact(r['y']),probabilityExact=exact(r['score']),probabilityApprox=approx(r['score']),unseenCell=''if r['unseenCell']is None else int(r['unseenCell']),transformedX=''if r['transformedX']is None else'|'.join(map(str,r['transformedX'])),reason=reason))\n   tables['lineage'].append(dict(kind=kind,id=r['id'],sourceRow=n['sourceRow'],originalID=n['originalID'],nativeSourceRows=n['nativeSourceRows'],rawX='|'.join(''if x is None else x for x in n['x']),nativeTarget=''if n['nativeTarget']is None else n['nativeTarget'],derivedTarget=exact(r['y']),nativeGroup=''if n['group']is None else n['group'],plannedRole=n['plannedRole'],role=r['role'],eligible=int(r['eligible']),analyticalMass='1',reason=reason))\n  for j,v in enumerate(fit['medians']):tables['fit-medians'].append(dict(kind=kind,feature=j,categorical=int(j in M['categoricalFeatures']),fitRows=len(fit['trainIDs']),medianExact=exact(v),medianApprox=approx(v),unit=M['featureUnits'][j]))\n  for key,(mass,pos)in fit['cells'].items():tables['fit-cells'].append(dict(kind=kind,cell='|'.join(map(str,key)),trainingRows=mass,positiveRows=pos,probabilityExact=exact(fit['probabilities'][key]),probabilityApprox=approx(fit['probabilities'][key]),fallbackExact=exact(fit['fallback']),fallbackApprox=approx(fit['fallback'])))\n  for j,p in enumerate(cv['points']):\n   policy=p['policy'];tables['test-curves'].append(dict(kind=kind,point=j,policy=policy if isinstance(policy,str)else'threshold',thresholdExact=''if isinstance(policy,str)else exact(policy),thresholdApprox=''if isinstance(policy,str)else approx(policy),**scalar_fields(p,['TP','FP','FN','TN','TPR','FPR','precision','recall'])))\n   point(kind,'roc','ROC',j,p['FPR'],p['TPR']);point(kind,'pr','PR-observed',j,p['recall'],p['precision'])\n  for b in cal['bins']:\n   tables['calibration-bins'].append(dict(kind=kind,bin=b['index'],leftExact=str(F(b['index'],5)),rightExact=str(F(b['index']+1,5)),rightClosed=int(b['index']==4),rows=b['rows'],ids=';'.join(str(i)for i in b['ids']),**scalar_fields(b,['mass','meanPrediction','eventRate','gap','absoluteGap','scoreVariance','scoreTargetCovariance','withinBinCorrection'])))\n   point(kind,'reliability','Binary event rate',b['index'],b['meanPrediction'],b['eventRate'],tag='rows='+str(b['rows']))\n  for j,r in enumerate(test):\n   point(kind,'test-scores','Training-fitted probability',j,F(j+1),r['score'],'test-row position','probability',tag=r['id'])\n   point(kind,'test-scores','Observed Y',j,F(j+1),r['y'],'test-row position','binary target',tag=r['id'])\n  for name,fp,fn in SCENARIOS:\n   choice=choose(rr,{},(fp,fn));gm=groups(test,choice['selectedPolicy'],(fp,fn));scenarios.append(dict(name=name,costs=dict(falsePositive=fp,falseNegative=fn),selection=choice,groups=gm));ev=choice['evaluation']\n   for c in choice['candidates']:\n    policy=c['policy'];mm=c['metrics'];tables['validation-candidates'].append(dict(kind=kind,scenario=name,candidate=c['index'],selected=int(c['index']==choice['selectedIndex']),policy=policy if isinstance(policy,str)else'threshold',thresholdExact=''if isinstance(policy,str)else exact(policy),thresholdApprox=''if isinstance(policy,str)else approx(policy),feasible=int(c['feasible']),reasons=';'.join(c['reasons']),**{k+'Exact':str(v)for k,v in mm['confusion'].items()},**scalar_fields(mm,COUNTS+['TPR','FPR','precision','meanCost','totalCost'])))\n    point(kind,'validation-cost',name,c['index'],F(c['index']),mm['meanCost'],'candidate index','hypothetical cost units/mass','validation',tag=exact(policy))\n   mm={**ev,**ev['confusion'],**{k:cv[k]for k in ['ROC_AUC','averagePrecision','PRTrapezoidWithInitialPrecisionOne']},**{k:cal[k]for k in ['ECE','reliability','resolution','uncertainty','withinBinCorrection','BrierIdentityResidual']}}\n   for key in ['TP','FP','FN','TN']+COUNTS+RATES+['ROC_AUC','averagePrecision','PRTrapezoidWithInitialPrecisionOne','ECE','reliability','resolution','uncertainty','withinBinCorrection','BrierIdentityResidual']:\n    unit='rows'if key in ['TP','FP','FN','TN']+COUNTS else'hypothetical cost units'if key=='totalCost'else'hypothetical cost units/mass'if key=='meanCost'else'sum squared-probability loss'if key=='BrierSum'else'dimensionless'\n    tables['test-metrics'].append(dict(kind=kind,scenario=name,metric=key,valueExact=exact(mm[key]),valueApprox=approx(mm[key]),unit=unit))\n   allg=[('overall','all',gm['overall'])]+[('known',str(g['group']),g['metrics'])for g in gm['groups']]+[('unknown','',gm['unknownGroup'])]\n   for j,(typ,token,g)in enumerate(allg):\n    tables['group-metrics'].append(dict(kind=kind,scenario=name,groupType=typ,groupToken=token,retainedRows=g.get('retainedRows',sum((r['group']==token)if typ=='known'else(r['group']is None)if typ=='unknown'else True for r in test)),**{k+'Exact':str(v)for k,v in g['confusion'].items()},**scalar_fields(g,COUNTS+RATES)))\n    if typ=='known':point(kind,'group-TPR',name,j-1,F(j-1),g['TPR'],'declared group position','TPR',tag=token)\n  studies[kind]=dict(kind=kind,rows=len(native),eligibleRows=sum(r['eligible']for r in rr),trainingIDs=fit['trainIDs'],fitMedians=fit['medians'],fitCells=[dict(cell=list(k),mass=n,positive=s,probability=fit['probabilities'][k])for k,(n,s)in fit['cells'].items()],fallback=fit['fallback'],scenarios=scenarios,testCurves=cv,testCalibration=cal,rowsScored=rr)\n files=[]\n for name,rows in tables.items():\n  p=out/('computed-'+name+'.csv')\n  with p.open('w',encoding='utf8',newline='')as f:w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows)\n  files.append(dict(file=p.name,rows=len(rows),columns=len(rows[0]),bodyFields=len(rows)*len(rows[0]),sha256=hashlib.sha256(p.read_bytes()).hexdigest()))\n (out/'study.json').write_text(json.dumps(packed(studies),ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\n sourceFiles=[source/n for n in ['actual64-country-four-indicators-original-2024.csv','actual3613-NLS-original52-fields-groups-roles.csv','actual3150-churn-original14-fields-groups-roles.csv']]\n provenance=dict(chapter='ML-14',arithmetic='Python stdlib Fraction exact finite values from original decimal strings; binary64 valueApprox is display only.',inputs=[dict(file=p.name,sha256=hashlib.sha256(p.read_bytes()).hexdigest())for p in sourceFiles],priorEngineModelsScoresOrComputedFilesRead=False,roleRule=\"SHA256('ML14-role|'+kind+'|'+ID),rankmod5=0test/1validation/others train before eligibility\",costs='Hypothetical1/1,1/5,5/1; no causal intervention returns',files=files,observations={k:dict(sourceRows=v['rows'],eligibleRows=v['eligibleRows'],trainingRows=len(v['trainingIDs']))for k,v in studies.items()})\n (out/'provenance.json').write_text(json.dumps(provenance,ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\n print(json.dumps(dict(status='PASS standalone completed',files=len(files),bodyFields=sum(f['bodyFields']for f in files),observations=provenance['observations'])))\n\n# Fixed declared examples: full web budget/option validation is not reproduced.\nfrom html import escape\nimport textwrap\ndef validated_rows(raw):\n for r in raw:\n  assert F(str(r.get('weight','1')))>=0,'negative analytical mass'\n  assert r['score']is None or 0<=F(str(r['score']))<=1,'score outside zero/one'\n  assert r['y']is None or F(str(int(r['y']))if isinstance(r['y'],bool)else str(r['y']))in [0,1],'binary target required'\n return read(raw)\ndef serial(v):\n if isinstance(v,F):return dict(exactFraction=str(v),value=float(v))\n if isinstance(v,(list,tuple)):return[serial(x)for x in v]\n if isinstance(v,dict):return{k:serial(x)for k,x in v.items()}\n return v\ndef fixed_svg(path,points,title,xlabel,ylabel,legend):\n use=[p for p in points if p['xExact']!=''and p['yExact']!=''];xs=[float(F(p['xExact']))for p in use];ys=[float(F(p['yExact']))for p in use]\n xmin=min(xs,default=0);xmax=max(xs,default=1);ymin=min([0]+ys);ymax=max([0]+ys)\n if xmin==xmax:xmin-=.5;xmax+=.5\n if ymin==ymax:ymax=ymin+1\n X=lambda v:85+(float(v)-xmin)/(xmax-xmin)*480;Y=lambda v:278-(float(v)-ymin)/(ymax-ymin)*175\n s='<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"620\" height=\"360\" viewBox=\"0 0 620 360\"><rect width=\"620\" height=\"360\" fill=\"white\"/><g font-family=\"Arial, sans-serif\" font-size=\"13\" fill=\"#17324d\">'\n for i,line in enumerate(textwrap.wrap(title,width=65)):s+='<text x=\"25\" y=\"'+str(24+i*18)+'\">'+escape(line)+'</text>'\n colors=['#176b9b','#b85e18','#437e4d']\n for i,label in enumerate(legend):s+='<circle cx=\"'+str(30+i*250)+'\" cy=\"76\" r=\"4\" fill=\"'+colors[i%3]+'\"/><text x=\"'+str(42+i*250)+'\" y=\"80\">'+escape(label)+'</text>'\n s+='<path d=\"M85 98V278H575\" fill=\"none\" stroke=\"#52677d\"/><text text-anchor=\"middle\" x=\"325\" y=\"338\">'+escape(xlabel)+'</text><text text-anchor=\"middle\" transform=\"translate(21,190) rotate(-90)\">'+escape(ylabel)+'</text>'\n for i in range(5):\n  xx=xmin+(xmax-xmin)*i/4;yy=ymin+(ymax-ymin)*i/4;s+='<text text-anchor=\"middle\" x=\"'+format(X(xx),'.9g')+'\" y=\"305\">'+format(xx,'.4g')+'</text><text text-anchor=\"end\" x=\"77\" y=\"'+format(Y(yy)+4,'.9g')+'\">'+format(yy,'.4g')+'</text>'\n for p in use:s+='<circle cx=\"'+format(X(F(p['xExact'])),'.9g')+'\" cy=\"'+format(Y(F(p['yExact'])),'.9g')+'\" r=\"3\" fill=\"'+colors[p['series']%3]+'\"/>'\n path.write_text(s+'</g></svg>',encoding='utf8')\ndef fixed_run():\n ap=argparse.ArgumentParser();ap.add_argument('--out',type=Path,default=Path('results'));ap.add_argument('--data-dir',type=Path,default=Path(__file__).resolve().parent.parent/'ml14-sources');args=ap.parse_args();args.out.mkdir(parents=True,exist_ok=True)\n api=FIXED['api'];a=FIXED['args'];summary=[];points=[];xlabel='Declared index';ylabel='Value';legend=['Declared result']\n def metric(name,v,unit='dimensionless'):\n  q=None if v is None else v if isinstance(v,F)else F(v);summary.append(dict(metric=name,value='undefined'if q is None else format(float(q),'.9g'),exactValue=''if q is None else str(q),unit=unit,defined=int(q is not None)))\n def pt(i,x,y,ident='',series=0):\n  points.append(dict(series=series,index=i,xExact=''if x is None else str(F(x)),x='undefined'if x is None else format(float(x),'.9g'),yExact=''if y is None else str(F(y)),y='undefined'if y is None else format(float(y),'.9g'),id=str(ident)))\n if api=='realdata':\n  models=load_sources(args.data_dir);model=models[a['kind']];fit=actual_model(model);rr=fit['rows'];test=scoped(rr,'test');scenarios=[]\n  for name,fp,fn in SCENARIOS:\n   c=choose(rr,{},(fp,fn));scenarios.append(dict(name=name,selection=c));metric(name+'Threshold',c['selectedPolicy']);metric(name+'TestCost',c['evaluation']['meanCost'],'hypothetical cost units/mass')\n  cv=curves(test);cal=calibrate(test,[F(0),F(1,5),F(2,5),F(3,5),F(4,5),F(1)]);metric('testAUC',cv['ROC_AUC']);metric('testAP',cv['averagePrecision']);metric('testBrier',cal['Brier']);metric('eligibleRows',sum(r['eligible']for r in rr),'rows')\n  for i,r in enumerate(test):pt(i,i+1,r['score'],r['id'],0);pt(i,i+1,r['y'],r['id'],1)\n  full=dict(kind=a['kind'],fitMedians=fit['medians'],fitCells=[dict(cell=list(k),mass=n,positive=s,probability=fit['probabilities'][k])for k,(n,s)in fit['cells'].items()],rowsScored=rr,scenarios=scenarios,testCurves=cv,testCalibration=cal);xlabel='Test row, native order';ylabel='Y or probability';legend=['Training-fitted probability','Observed Y']\n else:\n  rr=validated_rows(a['rows']);role=a.get('role','all');frame=scoped(rr,role);cc=cost(a.get('costs'));t=policy(a.get('threshold','1/2'))\n  if api=='metrics':\n   full=metrics(frame,t,cc)\n   for k in ['mass','accuracy','precision','TPR','FPR','F1','Brier','meanCost']:metric(k,full[k],'mass'if k=='mass'else'hypothetical cost units/mass'if k=='meanCost'else'dimensionless')\n   metric('BayesThreshold',full['bayesThreshold'])\n   for i,k in enumerate(['TP','FP','FN','TN']):pt(i,i,full['confusion'][k],k)\n   xlabel='TP / FP / FN / TN positions';ylabel='Analytical mass'\n  elif api=='curves':\n   full=curves(frame)\n   for k in ['ROC_AUC','averagePrecision','PRTrapezoidWithInitialPrecisionOne']:metric(k,full[k])\n   for i,p in enumerate(full['points']):pt(i,p['FPR'],p['TPR'],str(p['policy']))\n   xlabel='False positive rate';ylabel='True positive rate';legend=['Observed ROC operating points']\n  elif api=='choose':\n   full=choose(rr,a,cc);metric('selectedIndex',full['selectedIndex'],'candidate index');metric('minimumCost',None if full['selectedValidation']is None else full['selectedValidation']['meanCost'],'hypothetical cost units/mass');metric('feasible',int(full['selectedIndex']is not None),'indicator')\n   for c in full['candidates']:pt(c['index'],c['index'],c['metrics']['meanCost'],str(c['policy']))\n   xlabel='Validation candidate';ylabel='Assumed cost / mass';legend=['Validation candidate costs']\n  elif api=='calibrate':\n   full=calibrate(frame,[F(str(e))for e in a.get('binEdges',['0','1/5','2/5','3/5','4/5','1'])])\n   for k in ['ECE','Brier','uncertainty','resolution','reliability','withinBinCorrection','BrierIdentityResidual']:metric(k,full[k])\n   for b in full['bins']:pt(b['index'],b['meanPrediction'],b['eventRate'],'bin:'+str(b['index']))\n   xlabel='Bin mean forecast';ylabel='Bin event rate';legend=['Binary-event reliability']\n  elif api=='groups':\n   full=groups(frame,t,cc);metric('overallTPR',full['overall']['TPR']);metric('TPRGap',full['gaps']['TPR']['value']);metric('precisionGap',full['gaps']['precision']['value']);metric('unknownMass',full['unknownGroup']['mass'],'mass');metric('partitionResidual',full['partitionMassResidual'],'mass')\n   for i,g in enumerate(full['groups']):pt(i,i,g['metrics']['TPR'],str(g['group']))\n   xlabel='Declared group position';ylabel='True positive rate';legend=['Known-group TPR']\n  else:raise ValueError('unknown fixed API')\n def csvout(name,rows):\n  with(args.out/name).open('w',encoding='utf8',newline='')as f:w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows)\n csvout('summary.csv',summary);csvout('plot-points.csv',points);fixed_svg(args.out/'plot.svg',points,FIXED['title'],xlabel,ylabel,legend)\n (args.out/'full.json').write_text(json.dumps(dict(api=api,variant=FIXED['variant'],input=FIXED['args'],arithmetic='Python standard-library Fraction, declared fixed example; full web validator/budgets not reproduced',result=serial(full)),ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\n print(json.dumps(dict(api=api,variant=FIXED['variant'],summaryMetrics=len(summary),plotSlots=len(points))))\n\nFIXED={'api': 'curves', 'variant': 'six-cards', 'args': {'rows': [{'id': 'a', 'score': '.9', 'y': 1, 'group': 'A'}, {'id': 'b', 'score': '.8', 'y': 1, 'group': 'A'}, {'id': 'c', 'score': '.8', 'y': 0, 'group': 'A'}, {'id': 'd', 'score': '.6', 'y': 0, 'group': 'B'}, {'id': 'e', 'score': '.4', 'y': 1, 'group': 'B'}, {'id': 'f', 'score': '.1', 'y': 0, 'group': 'B'}]}, 'title': 'Tied-score six-card ROC, AP and labeled PR trapezoid'}\nif __name__=='__main__':fixed_run()\n",
        "codeText": "#!/usr/bin/env python3\n\"\"\"ML14 standalone exact finite study, Python standard library only.\nInputs: only the three retained factual source CSVs below.\nDerived role/target/group/eligibility columns in those CSVs are NOT inputs.\nRebuilds SHA256 roles, train-only medians/cell scores, validation thresholds,\ntest curves, binary-event reliability and descriptive group ledgers.\nCosts 1/1,1/5,5/1 are hypothetical units, not measured intervention returns.\nThis is author public reproduction, not independent scientific review.\n\"\"\"\n\"\"\"Author Fraction reference, separate from product JavaScript; not independent peer.\"\"\"\nfrom fractions import Fraction as F\nfrom collections import Counter,defaultdict\ndef read(raw):\n rows=[]\n for i,r in enumerate(raw):\n  s=None if r['score']is None else F(str(r['score']));y=None if r['y']is None else F(int(r['y']))if isinstance(r['y'],bool)else F(str(r['y']));w=F(str(r.get('weight','1')));role=r.get('role','evaluation')\n  rows.append(dict(id=r['id'],index=i,score=s,y=y,w=w,role=role,group=r.get('group'),eligible=s is not None and y is not None and w>0 and role!='excluded'))\n return rows\ndef scoped(rows,role='all'):return rows if role=='all'else[r for r in rows if r['role']==role]\ndef divide(n,d):return None if not d else n/d\ndef policy(v):return v if v in ['always-negative','always-positive']else F(str(v))\ndef positive(p,s):return p=='always-positive'if isinstance(p,str)else s>=p\ndef cost(a=None):\n a={}if a is None else a;fp=F(str(a.get('falsePositive','1')));fn=F(str(a.get('falseNegative','1')));return fp,fn\ndef metrics(rows,threshold=F(1,2),cc=(F(1),F(1))):\n counts=dict(TP=F(0),FP=F(0),FN=F(0),TN=F(0));brier=F(0);pred=[]\n for r in rows:\n  if not r['eligible']:pred.append(dict(id=r['id'],index=r['index'],eligible=False,decision=None,probability=None,Brier=None));continue\n  yes=positive(threshold,r['score']);cell=('T'if yes==bool(r['y'])else'F')+('P'if yes else'N');counts[cell]+=r['w'];loss=(r['score']-r['y'])**2;brier+=r['w']*loss;pred.append(dict(id=r['id'],index=r['index'],eligible=True,decision=int(yes),probability=r['score'],Brier=loss))\n TP,FP,FN,TN=[counts[k]for k in ['TP','FP','FN','TN']];P=TP+FN;N=TN+FP;mass=P+N;PP=TP+FP;PN=TN+FN;TPR=divide(TP,P);TNR=divide(TN,N);total=FP*cc[0]+FN*cc[1]\n return dict(confusion=counts,mass=mass,positiveTargetMass=P,negativeTargetMass=N,predictedPositiveMass=PP,predictedNegativeMass=PN,prevalence=divide(P,mass),selectionRate=divide(PP,mass),accuracy=divide(TP+TN,mass),precision=divide(TP,PP),negativePredictiveValue=divide(TN,PN),TPR=TPR,FPR=divide(FP,N),TNR=TNR,FNR=divide(FN,P),F1=divide(2*TP,2*TP+FP+FN),balancedAccuracy=None if TPR is None or TNR is None else(TPR+TNR)/2,Brier=divide(brier,mass),BrierSum=brier,totalCost=total,meanCost=divide(total,mass),predictions=pred,bayesThreshold=divide(cc[0],sum(cc)))\ndef curves(rows):\n use=[r for r in rows if r['eligible']];pos=Counter();neg=Counter()\n for r in use:(pos if r['y']else neg)[r['score']]+=r['w']\n P=sum(pos.values(),F(0));N=sum(neg.values(),F(0));pairs=F(0)\n for a,wa in pos.items():\n  for b,wb in neg.items():pairs+=wa*wb*(F(1)if a>b else F(1,2)if a==b else F(0))\n thresholds=['always-negative']+sorted({r['score']for r in use},reverse=True);points=[];AP=F(0);trap=F(0);lastR=F(0);lastP=F(1)\n for i,p in enumerate(thresholds):\n  m=metrics(rows,p);points.append(dict(policy=p,TP=m['confusion']['TP'],FP=m['confusion']['FP'],FN=m['confusion']['FN'],TN=m['confusion']['TN'],TPR=m['TPR'],FPR=m['FPR'],precision=m['precision'],recall=m['TPR']))\n  if i and P:\n   R=m['TPR'];PP=m['precision'];AP+=(R-lastR)*PP;trap+=(R-lastR)*(PP+lastP)/2;lastR=R;lastP=PP\n return dict(positiveMass=P,negativeMass=N,ROC_AUC=divide(pairs,P*N),weightedConcordantPlusHalfTiedMass=pairs,averagePrecision=AP if P else None,PRTrapezoidWithInitialPrecisionOne=trap if P else None,points=points)\ndef choose(rows,a,cc):\n sr=a.get('selectionRole','validation');er=a.get('evaluationRole','test');rr=scoped(rows,sr);thresholds=[policy(t)for t in a['thresholds']]if'thresholds'in a else['always-negative']+sorted({r['score']for r in rr if r['eligible']},reverse=True)\n candidates=[]\n for i,p in enumerate(thresholds):\n  m=metrics(rr,p,cc);reasons=[]\n  if'minTPR'in a and(m['TPR']is None or m['TPR']<F(str(a['minTPR']))):reasons.append('TPR-undefined'if m['TPR']is None else'below-minTPR')\n  if'maxFPR'in a and(m['FPR']is None or m['FPR']>F(str(a['maxFPR']))):reasons.append('FPR-undefined'if m['FPR']is None else'above-maxFPR')\n  candidates.append(dict(index=i,policy=p,metrics=m,feasible=not reasons,reasons=reasons))\n eligible=[c for c in candidates if c['feasible']];best=min(eligible,key=lambda c:(c['metrics']['meanCost'],c['index']))if eligible else None\n return dict(selectedIndex=None if best is None else best['index'],selectedPolicy=None if best is None else best['policy'],candidates=candidates,selectedValidation=None if best is None else best['metrics'],evaluation=None if best is None or er=='none'else metrics(scoped(rows,er),best['policy'],cc),selectionIDs=[r['id']for r in rr if r['eligible']])\ndef calibrate(rows,ee):\n buckets=[[]for _ in range(len(ee)-1)]\n for r in rows:\n  if not r['eligible']:continue\n  j=next((i for i in range(len(ee)-1)if r['score']<ee[i+1]),len(ee)-2);buckets[j].append(r)\n mass=sum((r['w']for r in rows if r['eligible']),F(0));P=sum((r['w']*r['y']for r in rows if r['eligible']),F(0));pi=divide(P,mass);Brier=None if not mass else sum((r['w']*(r['score']-r['y'])**2 for r in rows if r['eligible']),F(0))/mass;ECE=F(0);reliability=F(0);resolution=F(0);correction=F(0);bins=[]\n for i,rr in enumerate(buckets):\n  w=sum((r['w']for r in rr),F(0));mp=None if not w else sum((r['w']*r['score']for r in rr),F(0))/w;o=None if not w else sum((r['w']*r['y']for r in rr),F(0))/w\n  variance=None if not w else sum((r['w']*(r['score']-mp)**2 for r in rr),F(0))/w\n  covariance=None if not w else sum((r['w']*(r['score']-mp)*(r['y']-o)for r in rr),F(0))/w\n  bc=None if not w else variance-2*covariance;gap=None if not w else mp-o\n  bins.append(dict(index=i,rows=len(rr),mass=w,meanPrediction=mp,eventRate=o,gap=gap,absoluteGap=None if gap is None else abs(gap),scoreVariance=variance,scoreTargetCovariance=covariance,withinBinCorrection=bc,ids=[r['id']for r in rr]))\n  if w:\n   share=w/mass;ECE+=share*abs(gap);reliability+=share*gap**2;resolution+=share*(o-pi)**2;correction+=share*bc\n uncertainty=None if pi is None else pi*(1-pi);residual=None if Brier is None else Brier-(uncertainty-resolution+reliability+correction)\n return dict(mass=mass,prevalence=pi,Brier=Brier,ECE=ECE if mass else None,reliability=reliability if mass else None,resolution=resolution if mass else None,uncertainty=uncertainty,withinBinCorrection=correction if mass else None,BrierIdentityResidual=residual,bins=bins)\ndef typed(v):return type(v).__name__,v\ndef groups(rows,p,cc):\n bins={}\n for r in rows:\n  if r['group']is not None:bins.setdefault(typed(r['group']),[]).append(r)\n gm=[dict(group=rr[0]['group'],metrics=metrics(rr,p,cc))for rr in bins.values()];overall=metrics(rows,p,cc);unknown=metrics([r for r in rows if r['group']is None],p,cc);gaps={}\n for key in ['prevalence','selectionRate','TPR','FPR','precision','accuracy','meanCost']:\n  positive=[g for g in gm if g['metrics']['mass']>0];undefined=[g['group']for g in positive if g['metrics'][key]is None];vals=[g['metrics'][key]for g in positive if g['metrics'][key]is not None]\n  gaps[key]=dict(value=None if len(positive)<2 or undefined else max(vals)-min(vals),undefinedGroups=undefined,comparedPositiveMassGroups=[g['group']for g in positive])\n return dict(overall=overall,groups=gm,unknownGroup=unknown,gaps=gaps,partitionMassResidual=overall['mass']-unknown['mass']-sum((g['metrics']['mass']for g in gm),F(0)))\ndef actual_model(M):\n raw=M['records'];cat=M['categoricalFeatures'];p=len(raw[0]['x']);train=[r for r in raw if r['role']=='train'];medians=[]\n for j in range(p):\n  if j in cat:medians.append(None);continue\n  values=sorted(F(r['x'][j])for r in train);n=len(values);medians.append(values[n//2]if n%2 else(values[n//2-1]+values[n//2])/2)\n def transform(r):return[F(v)if j in cat else F(int(F(v)>medians[j]))for j,v in enumerate(r['x'])]\n counts={}\n for r in train:\n  key=tuple(transform(r));n,s=counts.get(key,(0,0));counts[key]=(n+1,s+int(r['y']))\n probabilities={k:F(s+1,n+2)for k,(n,s)in counts.items()};fallback=F(sum(int(r['y'])for r in train)+1,len(train)+2);scored=[]\n for i,r in enumerate(raw):\n  eligible=r['role']!='excluded';z=transform(r)if eligible else None;key=None if z is None else tuple(z);score=None if not eligible else probabilities.get(key,fallback)\n  scored.append(dict(id=r['id'],index=i,role=r['role'],group=r['group'],y=None if r['y']is None else F(r['y']),score=score,w=F(1),eligible=eligible,transformedX=z,unseenCell=None if not eligible else key not in probabilities))\n return dict(medians=medians,cells=counts,probabilities=probabilities,fallback=fallback,rows=scored,trainIDs=[r['id']for r in train])\n\n\nimport csv,json,hashlib,argparse,datetime\nfrom pathlib import Path\ndef missing(v):return None if v in ['', '.',None]else v\ndef load_sources(folder):\n def read_csv(name):\n  with (folder/name).open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))\n wb=read_csv('actual64-country-four-indicators-original-2024.csv')\n codes=['NY.GDP.PCAP.KD','NY.GDP.MKTP.KD.ZG','FP.CPI.TOTL.ZG','SP.DYN.LE00.IN']\n lookup={(r['countryISO3'],r['indicatorID']):r for r in wb};country=[]\n for i,iso in enumerate(sorted({r['countryISO3']for r in wb}),1):\n  native=[lookup[iso,c]for c in codes];v=[missing(r['originalValueToken'])for r in native]\n  country.append(dict(id=iso+':2024',sourceRow=i,originalID=iso,x=v[:3],y=None if v[3]is None else str(int(F(v[3])>=80)),group=None if v[0]is None else str(int(F(v[0])>=25000)),nativeTarget=v[3],nativeSourceRows=';'.join(r['sourceRow']for r in native)))\n nls=read_csv('actual3613-NLS-original52-fields-groups-roles.csv');person=[]\n for r in nls:\n  y=missing(r['wage76']);person.append(dict(id='person:'+r['sourceRow'],sourceRow=int(r['sourceRow']),originalID=r['id'],x=[missing(r[k])for k in ['ed76','age76','nearc4']],y=None if y is None else str(int(F(y)>=500)),group=missing(r['black']),nativeTarget=y,nativeSourceRows=r['sourceRow']))\n ch=read_csv('actual3150-churn-original14-fields-groups-roles.csv');company=[]\n for r in ch:\n  company.append(dict(id='customer:'+r['sourceRow'],sourceRow=int(r['sourceRow']),originalID='',x=[missing(r[k])for k in ['Call  Failure','Complains','Subscription  Length','Seconds of Use']],y=missing(r['Churn']),group=missing(r['Tariff Plan']),nativeTarget=missing(r['Churn']),nativeSourceRows=r['sourceRow']))\n assert len(wb)==64 and len(country)==16 and len(nls)==3613 and len(ch)==3150\n assert [int(r['sourceRow'])for r in ch if r['Charge  Amount']=='10']==[474,2174,2274,2374,2674,2924,2974]\n models={}\n for kind,raw,cat,units in [('country',country,[],['constant2015USD/person','annualPercent','annualPercent']),('person',person,[2],['years','years','nativeCategory']),('company',company,[1],['count','nativeCategory','months','seconds'])]:\n  order=sorted(range(len(raw)),key=lambda i:(hashlib.sha256(('ML14-role|'+kind+'|'+raw[i]['id']).encode()).hexdigest(),i))\n  for rank,i in enumerate(order):\n   r=raw[i];r['plannedRole']='test'if rank%5==0 else'validation'if rank%5==1 else'train';r['eligible']=None not in r['x']+[r['y']];r['role']=r['plannedRole']if r['eligible']else'excluded';r['weight']='1'\n  models[kind]=dict(records=raw,categoricalFeatures=cat,featureUnits=units)\n assert sum(r['eligible']for r in person)==3017\n return models\n\ndef exact(v):return ''if v is None else str(v)\ndef approx(v):return ''if v is None else format(float(v),'.17g')\ndef scalar_fields(m,keys):\n out={}\n for k in keys:\n  out[k+'Exact']=exact(m[k]);out[k+'Approx']=approx(m[k])\n return out\nCOUNTS=['mass','positiveTargetMass','negativeTargetMass','predictedPositiveMass','predictedNegativeMass']\nRATES=['prevalence','selectionRate','accuracy','precision','negativePredictiveValue','TPR','FPR','TNR','FNR','F1','balancedAccuracy','Brier','BrierSum','totalCost','meanCost']\nSCENARIOS=[('equal',F(1),F(1)),('miss-five',F(1),F(5)),('alarm-five',F(5),F(1))]\ndef packed(v):\n if isinstance(v,F):return str(v)\n if isinstance(v,dict):return{str(k):packed(x)for k,x in v.items()}\n if isinstance(v,(tuple,list)):return[packed(x)for x in v]\n return v\ndef run_study(source,out):\n out.mkdir(parents=True,exist_ok=True);models=load_sources(source)\n tables={name:[]for name in ['predictions','lineage','fit-medians','fit-cells','validation-candidates','test-metrics','test-curves','calibration-bins','group-metrics','chart-points']}\n studies={};charts=[]\n def point(kind,chart,series,index,x,y,xunit='dimensionless',yunit='dimensionless',role='test',tag=''):\n  tables['chart-points'].append(dict(kind=kind,chart=chart,series=series,index=index,xExact=exact(x),xApprox=approx(x),yExact=exact(y),yApprox=approx(y),xUnit=xunit,yUnit=yunit,role=role,tag=tag))\n for kind,M in models.items():\n  fit=actual_model(M);rr=fit['rows'];native=M['records'];test=scoped(rr,'test');cv=curves(test);cal=calibrate(test,[F(0),F(1,5),F(2,5),F(3,5),F(4,5),F(1)]);scenarios=[]\n  for i,r in enumerate(rr):\n   n=native[i];reason=''if r['eligible']else'required-X-or-Y-missing'\n   tables['predictions'].append(dict(kind=kind,id=r['id'],sourceRow=n['sourceRow'],originalID=n['originalID'],plannedRole=n['plannedRole'],role=r['role'],group=''if r['group']is None else r['group'],eligible=int(r['eligible']),targetExact=exact(r['y']),probabilityExact=exact(r['score']),probabilityApprox=approx(r['score']),unseenCell=''if r['unseenCell']is None else int(r['unseenCell']),transformedX=''if r['transformedX']is None else'|'.join(map(str,r['transformedX'])),reason=reason))\n   tables['lineage'].append(dict(kind=kind,id=r['id'],sourceRow=n['sourceRow'],originalID=n['originalID'],nativeSourceRows=n['nativeSourceRows'],rawX='|'.join(''if x is None else x for x in n['x']),nativeTarget=''if n['nativeTarget']is None else n['nativeTarget'],derivedTarget=exact(r['y']),nativeGroup=''if n['group']is None else n['group'],plannedRole=n['plannedRole'],role=r['role'],eligible=int(r['eligible']),analyticalMass='1',reason=reason))\n  for j,v in enumerate(fit['medians']):tables['fit-medians'].append(dict(kind=kind,feature=j,categorical=int(j in M['categoricalFeatures']),fitRows=len(fit['trainIDs']),medianExact=exact(v),medianApprox=approx(v),unit=M['featureUnits'][j]))\n  for key,(mass,pos)in fit['cells'].items():tables['fit-cells'].append(dict(kind=kind,cell='|'.join(map(str,key)),trainingRows=mass,positiveRows=pos,probabilityExact=exact(fit['probabilities'][key]),probabilityApprox=approx(fit['probabilities'][key]),fallbackExact=exact(fit['fallback']),fallbackApprox=approx(fit['fallback'])))\n  for j,p in enumerate(cv['points']):\n   policy=p['policy'];tables['test-curves'].append(dict(kind=kind,point=j,policy=policy if isinstance(policy,str)else'threshold',thresholdExact=''if isinstance(policy,str)else exact(policy),thresholdApprox=''if isinstance(policy,str)else approx(policy),**scalar_fields(p,['TP','FP','FN','TN','TPR','FPR','precision','recall'])))\n   point(kind,'roc','ROC',j,p['FPR'],p['TPR']);point(kind,'pr','PR-observed',j,p['recall'],p['precision'])\n  for b in cal['bins']:\n   tables['calibration-bins'].append(dict(kind=kind,bin=b['index'],leftExact=str(F(b['index'],5)),rightExact=str(F(b['index']+1,5)),rightClosed=int(b['index']==4),rows=b['rows'],ids=';'.join(str(i)for i in b['ids']),**scalar_fields(b,['mass','meanPrediction','eventRate','gap','absoluteGap','scoreVariance','scoreTargetCovariance','withinBinCorrection'])))\n   point(kind,'reliability','Binary event rate',b['index'],b['meanPrediction'],b['eventRate'],tag='rows='+str(b['rows']))\n  for j,r in enumerate(test):\n   point(kind,'test-scores','Training-fitted probability',j,F(j+1),r['score'],'test-row position','probability',tag=r['id'])\n   point(kind,'test-scores','Observed Y',j,F(j+1),r['y'],'test-row position','binary target',tag=r['id'])\n  for name,fp,fn in SCENARIOS:\n   choice=choose(rr,{},(fp,fn));gm=groups(test,choice['selectedPolicy'],(fp,fn));scenarios.append(dict(name=name,costs=dict(falsePositive=fp,falseNegative=fn),selection=choice,groups=gm));ev=choice['evaluation']\n   for c in choice['candidates']:\n    policy=c['policy'];mm=c['metrics'];tables['validation-candidates'].append(dict(kind=kind,scenario=name,candidate=c['index'],selected=int(c['index']==choice['selectedIndex']),policy=policy if isinstance(policy,str)else'threshold',thresholdExact=''if isinstance(policy,str)else exact(policy),thresholdApprox=''if isinstance(policy,str)else approx(policy),feasible=int(c['feasible']),reasons=';'.join(c['reasons']),**{k+'Exact':str(v)for k,v in mm['confusion'].items()},**scalar_fields(mm,COUNTS+['TPR','FPR','precision','meanCost','totalCost'])))\n    point(kind,'validation-cost',name,c['index'],F(c['index']),mm['meanCost'],'candidate index','hypothetical cost units/mass','validation',tag=exact(policy))\n   mm={**ev,**ev['confusion'],**{k:cv[k]for k in ['ROC_AUC','averagePrecision','PRTrapezoidWithInitialPrecisionOne']},**{k:cal[k]for k in ['ECE','reliability','resolution','uncertainty','withinBinCorrection','BrierIdentityResidual']}}\n   for key in ['TP','FP','FN','TN']+COUNTS+RATES+['ROC_AUC','averagePrecision','PRTrapezoidWithInitialPrecisionOne','ECE','reliability','resolution','uncertainty','withinBinCorrection','BrierIdentityResidual']:\n    unit='rows'if key in ['TP','FP','FN','TN']+COUNTS else'hypothetical cost units'if key=='totalCost'else'hypothetical cost units/mass'if key=='meanCost'else'sum squared-probability loss'if key=='BrierSum'else'dimensionless'\n    tables['test-metrics'].append(dict(kind=kind,scenario=name,metric=key,valueExact=exact(mm[key]),valueApprox=approx(mm[key]),unit=unit))\n   allg=[('overall','all',gm['overall'])]+[('known',str(g['group']),g['metrics'])for g in gm['groups']]+[('unknown','',gm['unknownGroup'])]\n   for j,(typ,token,g)in enumerate(allg):\n    tables['group-metrics'].append(dict(kind=kind,scenario=name,groupType=typ,groupToken=token,retainedRows=g.get('retainedRows',sum((r['group']==token)if typ=='known'else(r['group']is None)if typ=='unknown'else True for r in test)),**{k+'Exact':str(v)for k,v in g['confusion'].items()},**scalar_fields(g,COUNTS+RATES)))\n    if typ=='known':point(kind,'group-TPR',name,j-1,F(j-1),g['TPR'],'declared group position','TPR',tag=token)\n  studies[kind]=dict(kind=kind,rows=len(native),eligibleRows=sum(r['eligible']for r in rr),trainingIDs=fit['trainIDs'],fitMedians=fit['medians'],fitCells=[dict(cell=list(k),mass=n,positive=s,probability=fit['probabilities'][k])for k,(n,s)in fit['cells'].items()],fallback=fit['fallback'],scenarios=scenarios,testCurves=cv,testCalibration=cal,rowsScored=rr)\n files=[]\n for name,rows in tables.items():\n  p=out/('computed-'+name+'.csv')\n  with p.open('w',encoding='utf8',newline='')as f:w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows)\n  files.append(dict(file=p.name,rows=len(rows),columns=len(rows[0]),bodyFields=len(rows)*len(rows[0]),sha256=hashlib.sha256(p.read_bytes()).hexdigest()))\n (out/'study.json').write_text(json.dumps(packed(studies),ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\n sourceFiles=[source/n for n in ['actual64-country-four-indicators-original-2024.csv','actual3613-NLS-original52-fields-groups-roles.csv','actual3150-churn-original14-fields-groups-roles.csv']]\n provenance=dict(chapter='ML-14',arithmetic='Python stdlib Fraction exact finite values from original decimal strings; binary64 valueApprox is display only.',inputs=[dict(file=p.name,sha256=hashlib.sha256(p.read_bytes()).hexdigest())for p in sourceFiles],priorEngineModelsScoresOrComputedFilesRead=False,roleRule=\"SHA256('ML14-role|'+kind+'|'+ID),rankmod5=0test/1validation/others train before eligibility\",costs='Hypothetical1/1,1/5,5/1; no causal intervention returns',files=files,observations={k:dict(sourceRows=v['rows'],eligibleRows=v['eligibleRows'],trainingRows=len(v['trainingIDs']))for k,v in studies.items()})\n (out/'provenance.json').write_text(json.dumps(provenance,ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\n print(json.dumps(dict(status='PASS standalone completed',files=len(files),bodyFields=sum(f['bodyFields']for f in files),observations=provenance['observations'])))\n\n# Fixed declared examples: full web budget/option validation is not reproduced.\nfrom html import escape\nimport textwrap\ndef validated_rows(raw):\n for r in raw:\n  assert F(str(r.get('weight','1')))>=0,'negative analytical mass'\n  assert r['score']is None or 0<=F(str(r['score']))<=1,'score outside zero/one'\n  assert r['y']is None or F(str(int(r['y']))if isinstance(r['y'],bool)else str(r['y']))in [0,1],'binary target required'\n return read(raw)\ndef serial(v):\n if isinstance(v,F):return dict(exactFraction=str(v),value=float(v))\n if isinstance(v,(list,tuple)):return[serial(x)for x in v]\n if isinstance(v,dict):return{k:serial(x)for k,x in v.items()}\n return v\ndef fixed_svg(path,points,title,xlabel,ylabel,legend):\n use=[p for p in points if p['xExact']!=''and p['yExact']!=''];xs=[float(F(p['xExact']))for p in use];ys=[float(F(p['yExact']))for p in use]\n xmin=min(xs,default=0);xmax=max(xs,default=1);ymin=min([0]+ys);ymax=max([0]+ys)\n if xmin==xmax:xmin-=.5;xmax+=.5\n if ymin==ymax:ymax=ymin+1\n X=lambda v:85+(float(v)-xmin)/(xmax-xmin)*480;Y=lambda v:278-(float(v)-ymin)/(ymax-ymin)*175\n s='<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"620\" height=\"360\" viewBox=\"0 0 620 360\"><rect width=\"620\" height=\"360\" fill=\"white\"/><g font-family=\"Arial, sans-serif\" font-size=\"13\" fill=\"#17324d\">'\n for i,line in enumerate(textwrap.wrap(title,width=65)):s+='<text x=\"25\" y=\"'+str(24+i*18)+'\">'+escape(line)+'</text>'\n colors=['#176b9b','#b85e18','#437e4d']\n for i,label in enumerate(legend):s+='<circle cx=\"'+str(30+i*250)+'\" cy=\"76\" r=\"4\" fill=\"'+colors[i%3]+'\"/><text x=\"'+str(42+i*250)+'\" y=\"80\">'+escape(label)+'</text>'\n s+='<path d=\"M85 98V278H575\" fill=\"none\" stroke=\"#52677d\"/><text text-anchor=\"middle\" x=\"325\" y=\"338\">'+escape(xlabel)+'</text><text text-anchor=\"middle\" transform=\"translate(21,190) rotate(-90)\">'+escape(ylabel)+'</text>'\n for i in range(5):\n  xx=xmin+(xmax-xmin)*i/4;yy=ymin+(ymax-ymin)*i/4;s+='<text text-anchor=\"middle\" x=\"'+format(X(xx),'.9g')+'\" y=\"305\">'+format(xx,'.4g')+'</text><text text-anchor=\"end\" x=\"77\" y=\"'+format(Y(yy)+4,'.9g')+'\">'+format(yy,'.4g')+'</text>'\n for p in use:s+='<circle cx=\"'+format(X(F(p['xExact'])),'.9g')+'\" cy=\"'+format(Y(F(p['yExact'])),'.9g')+'\" r=\"3\" fill=\"'+colors[p['series']%3]+'\"/>'\n path.write_text(s+'</g></svg>',encoding='utf8')\ndef fixed_run():\n ap=argparse.ArgumentParser();ap.add_argument('--out',type=Path,default=Path('results'));ap.add_argument('--data-dir',type=Path,default=Path(__file__).resolve().parent.parent/'ml14-sources');args=ap.parse_args();args.out.mkdir(parents=True,exist_ok=True)\n api=FIXED['api'];a=FIXED['args'];summary=[];points=[];xlabel='Declared index';ylabel='Value';legend=['Declared result']\n def metric(name,v,unit='dimensionless'):\n  q=None if v is None else v if isinstance(v,F)else F(v);summary.append(dict(metric=name,value='undefined'if q is None else format(float(q),'.9g'),exactValue=''if q is None else str(q),unit=unit,defined=int(q is not None)))\n def pt(i,x,y,ident='',series=0):\n  points.append(dict(series=series,index=i,xExact=''if x is None else str(F(x)),x='undefined'if x is None else format(float(x),'.9g'),yExact=''if y is None else str(F(y)),y='undefined'if y is None else format(float(y),'.9g'),id=str(ident)))\n if api=='realdata':\n  models=load_sources(args.data_dir);model=models[a['kind']];fit=actual_model(model);rr=fit['rows'];test=scoped(rr,'test');scenarios=[]\n  for name,fp,fn in SCENARIOS:\n   c=choose(rr,{},(fp,fn));scenarios.append(dict(name=name,selection=c));metric(name+'Threshold',c['selectedPolicy']);metric(name+'TestCost',c['evaluation']['meanCost'],'hypothetical cost units/mass')\n  cv=curves(test);cal=calibrate(test,[F(0),F(1,5),F(2,5),F(3,5),F(4,5),F(1)]);metric('testAUC',cv['ROC_AUC']);metric('testAP',cv['averagePrecision']);metric('testBrier',cal['Brier']);metric('eligibleRows',sum(r['eligible']for r in rr),'rows')\n  for i,r in enumerate(test):pt(i,i+1,r['score'],r['id'],0);pt(i,i+1,r['y'],r['id'],1)\n  full=dict(kind=a['kind'],fitMedians=fit['medians'],fitCells=[dict(cell=list(k),mass=n,positive=s,probability=fit['probabilities'][k])for k,(n,s)in fit['cells'].items()],rowsScored=rr,scenarios=scenarios,testCurves=cv,testCalibration=cal);xlabel='Test row, native order';ylabel='Y or probability';legend=['Training-fitted probability','Observed Y']\n else:\n  rr=validated_rows(a['rows']);role=a.get('role','all');frame=scoped(rr,role);cc=cost(a.get('costs'));t=policy(a.get('threshold','1/2'))\n  if api=='metrics':\n   full=metrics(frame,t,cc)\n   for k in ['mass','accuracy','precision','TPR','FPR','F1','Brier','meanCost']:metric(k,full[k],'mass'if k=='mass'else'hypothetical cost units/mass'if k=='meanCost'else'dimensionless')\n   metric('BayesThreshold',full['bayesThreshold'])\n   for i,k in enumerate(['TP','FP','FN','TN']):pt(i,i,full['confusion'][k],k)\n   xlabel='TP / FP / FN / TN positions';ylabel='Analytical mass'\n  elif api=='curves':\n   full=curves(frame)\n   for k in ['ROC_AUC','averagePrecision','PRTrapezoidWithInitialPrecisionOne']:metric(k,full[k])\n   for i,p in enumerate(full['points']):pt(i,p['FPR'],p['TPR'],str(p['policy']))\n   xlabel='False positive rate';ylabel='True positive rate';legend=['Observed ROC operating points']\n  elif api=='choose':\n   full=choose(rr,a,cc);metric('selectedIndex',full['selectedIndex'],'candidate index');metric('minimumCost',None if full['selectedValidation']is None else full['selectedValidation']['meanCost'],'hypothetical cost units/mass');metric('feasible',int(full['selectedIndex']is not None),'indicator')\n   for c in full['candidates']:pt(c['index'],c['index'],c['metrics']['meanCost'],str(c['policy']))\n   xlabel='Validation candidate';ylabel='Assumed cost / mass';legend=['Validation candidate costs']\n  elif api=='calibrate':\n   full=calibrate(frame,[F(str(e))for e in a.get('binEdges',['0','1/5','2/5','3/5','4/5','1'])])\n   for k in ['ECE','Brier','uncertainty','resolution','reliability','withinBinCorrection','BrierIdentityResidual']:metric(k,full[k])\n   for b in full['bins']:pt(b['index'],b['meanPrediction'],b['eventRate'],'bin:'+str(b['index']))\n   xlabel='Bin mean forecast';ylabel='Bin event rate';legend=['Binary-event reliability']\n  elif api=='groups':\n   full=groups(frame,t,cc);metric('overallTPR',full['overall']['TPR']);metric('TPRGap',full['gaps']['TPR']['value']);metric('precisionGap',full['gaps']['precision']['value']);metric('unknownMass',full['unknownGroup']['mass'],'mass');metric('partitionResidual',full['partitionMassResidual'],'mass')\n   for i,g in enumerate(full['groups']):pt(i,i,g['metrics']['TPR'],str(g['group']))\n   xlabel='Declared group position';ylabel='True positive rate';legend=['Known-group TPR']\n  else:raise ValueError('unknown fixed API')\n def csvout(name,rows):\n  with(args.out/name).open('w',encoding='utf8',newline='')as f:w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows)\n csvout('summary.csv',summary);csvout('plot-points.csv',points);fixed_svg(args.out/'plot.svg',points,FIXED['title'],xlabel,ylabel,legend)\n (args.out/'full.json').write_text(json.dumps(dict(api=api,variant=FIXED['variant'],input=FIXED['args'],arithmetic='Python standard-library Fraction, declared fixed example; full web validator/budgets not reproduced',result=serial(full)),ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\n print(json.dumps(dict(api=api,variant=FIXED['variant'],summaryMetrics=len(summary),plotSlots=len(points))))\n\nFIXED={'api': 'curves', 'variant': 'six-cards', 'args': {'rows': [{'id': 'a', 'score': '.9', 'y': 1, 'group': 'A'}, {'id': 'b', 'score': '.8', 'y': 1, 'group': 'A'}, {'id': 'c', 'score': '.8', 'y': 0, 'group': 'A'}, {'id': 'd', 'score': '.6', 'y': 0, 'group': 'B'}, {'id': 'e', 'score': '.4', 'y': 1, 'group': 'B'}, {'id': 'f', 'score': '.1', 'y': 0, 'group': 'B'}]}, 'title': 'Tied-score six-card ROC, AP and labeled PR trapezoid'}\nif __name__=='__main__':fixed_run()\n",
        "input": {
          "rows": [
            {
              "id": "a",
              "score": ".9",
              "y": 1,
              "group": "A"
            },
            {
              "id": "b",
              "score": ".8",
              "y": 1,
              "group": "A"
            },
            {
              "id": "c",
              "score": ".8",
              "y": 0,
              "group": "A"
            },
            {
              "id": "d",
              "score": ".6",
              "y": 0,
              "group": "B"
            },
            {
              "id": "e",
              "score": ".4",
              "y": 1,
              "group": "B"
            },
            {
              "id": "f",
              "score": ".1",
              "y": 0,
              "group": "B"
            }
          ]
        },
        "inputFiles": [],
        "returnCode": 0,
        "expectedFailure": false,
        "stdout": "{\"api\": \"curves\", \"variant\": \"six-cards\", \"summaryMetrics\": 3, \"plotSlots\": 6}\n",
        "stderr": "",
        "summary": {
          "ROC_AUC": "0.722222222",
          "averagePrecision": "0.755555556",
          "PRTrapezoidWithInitialPrecisionOne": "0.794444444"
        },
        "summaryRows": [
          {
            "metric": "ROC_AUC",
            "value": "0.722222222",
            "exactValue": "13/18",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "averagePrecision",
            "value": "0.755555556",
            "exactValue": "34/45",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "PRTrapezoidWithInitialPrecisionOne",
            "value": "0.794444444",
            "exactValue": "143/180",
            "unit": "dimensionless",
            "defined": "1"
          }
        ],
        "plotPoints": [
          {
            "series": "0",
            "index": "0",
            "xExact": "0",
            "x": "0",
            "yExact": "0",
            "y": "0",
            "id": "always-negative"
          },
          {
            "series": "0",
            "index": "1",
            "xExact": "0",
            "x": "0",
            "yExact": "1/3",
            "y": "0.333333333",
            "id": "9/10"
          },
          {
            "series": "0",
            "index": "2",
            "xExact": "1/3",
            "x": "0.333333333",
            "yExact": "2/3",
            "y": "0.666666667",
            "id": "4/5"
          },
          {
            "series": "0",
            "index": "3",
            "xExact": "2/3",
            "x": "0.666666667",
            "yExact": "2/3",
            "y": "0.666666667",
            "id": "3/5"
          },
          {
            "series": "0",
            "index": "4",
            "xExact": "2/3",
            "x": "0.666666667",
            "yExact": "1",
            "y": "1",
            "id": "2/5"
          },
          {
            "series": "0",
            "index": "5",
            "xExact": "1",
            "x": "1",
            "yExact": "1",
            "y": "1",
            "id": "1/10"
          }
        ],
        "plotFile": "ml14-fixed-results/curves-six-cards-python/plot.svg",
        "plotSHA256": "1d7e295c7e7ffacb59cbd5b8ccb8365d7e41662e9d29ae556851de9fc814ea9e",
        "files": [
          {
            "file": "ml14-fixed-results/curves-six-cards-python/full.json",
            "sha256": "04da6eb98d842d40d1dad196c0d089137ab213d077f8c5ad798860de6ac9d1fe",
            "bytes": 6379
          },
          {
            "file": "ml14-fixed-results/curves-six-cards-python/plot-points.csv",
            "sha256": "61f016413744d5af530fc2a07fe2c692070d31f0549acf9a6ce0ea04b1fe4791",
            "bytes": 223
          },
          {
            "file": "ml14-fixed-results/curves-six-cards-python/plot.svg",
            "sha256": "1d7e295c7e7ffacb59cbd5b8ccb8365d7e41662e9d29ae556851de9fc814ea9e",
            "bytes": 1426
          },
          {
            "file": "ml14-fixed-results/curves-six-cards-python/summary.csv",
            "sha256": "500e0f3125c7141c885fb51b9db71abc6c350523f6a5d7226236c5ae87ad1d92",
            "bytes": 205
          }
        ],
        "scope": "Actually executed standalone fixed example, Python exact Fraction versus base-R binary64. Approximate R residuals retained; not universal exact arithmetic/web validation/native UI. Source programs read factual3CSV only."
      },
      "all-tied": {
        "api": "curves",
        "variant": "all-tied",
        "language": "python",
        "title": "All scores tied: half pair credit and prevalence AP",
        "codeFile": "ml14-code/curves-all-tied.py",
        "codeSHA256": "d78e83223999a274aed7c389a42131fa564acf352f4d6b600cc9934c42906664",
        "code": "#!/usr/bin/env python3\n\"\"\"ML14 standalone exact finite study, Python standard library only.\nInputs: only the three retained factual source CSVs below.\nDerived role/target/group/eligibility columns in those CSVs are NOT inputs.\nRebuilds SHA256 roles, train-only medians/cell scores, validation thresholds,\ntest curves, binary-event reliability and descriptive group ledgers.\nCosts 1/1,1/5,5/1 are hypothetical units, not measured intervention returns.\nThis is author public reproduction, not independent scientific review.\n\"\"\"\n\"\"\"Author Fraction reference, separate from product JavaScript; not independent peer.\"\"\"\nfrom fractions import Fraction as F\nfrom collections import Counter,defaultdict\ndef read(raw):\n rows=[]\n for i,r in enumerate(raw):\n  s=None if r['score']is None else F(str(r['score']));y=None if r['y']is None else F(int(r['y']))if isinstance(r['y'],bool)else F(str(r['y']));w=F(str(r.get('weight','1')));role=r.get('role','evaluation')\n  rows.append(dict(id=r['id'],index=i,score=s,y=y,w=w,role=role,group=r.get('group'),eligible=s is not None and y is not None and w>0 and role!='excluded'))\n return rows\ndef scoped(rows,role='all'):return rows if role=='all'else[r for r in rows if r['role']==role]\ndef divide(n,d):return None if not d else n/d\ndef policy(v):return v if v in ['always-negative','always-positive']else F(str(v))\ndef positive(p,s):return p=='always-positive'if isinstance(p,str)else s>=p\ndef cost(a=None):\n a={}if a is None else a;fp=F(str(a.get('falsePositive','1')));fn=F(str(a.get('falseNegative','1')));return fp,fn\ndef metrics(rows,threshold=F(1,2),cc=(F(1),F(1))):\n counts=dict(TP=F(0),FP=F(0),FN=F(0),TN=F(0));brier=F(0);pred=[]\n for r in rows:\n  if not r['eligible']:pred.append(dict(id=r['id'],index=r['index'],eligible=False,decision=None,probability=None,Brier=None));continue\n  yes=positive(threshold,r['score']);cell=('T'if yes==bool(r['y'])else'F')+('P'if yes else'N');counts[cell]+=r['w'];loss=(r['score']-r['y'])**2;brier+=r['w']*loss;pred.append(dict(id=r['id'],index=r['index'],eligible=True,decision=int(yes),probability=r['score'],Brier=loss))\n TP,FP,FN,TN=[counts[k]for k in ['TP','FP','FN','TN']];P=TP+FN;N=TN+FP;mass=P+N;PP=TP+FP;PN=TN+FN;TPR=divide(TP,P);TNR=divide(TN,N);total=FP*cc[0]+FN*cc[1]\n return dict(confusion=counts,mass=mass,positiveTargetMass=P,negativeTargetMass=N,predictedPositiveMass=PP,predictedNegativeMass=PN,prevalence=divide(P,mass),selectionRate=divide(PP,mass),accuracy=divide(TP+TN,mass),precision=divide(TP,PP),negativePredictiveValue=divide(TN,PN),TPR=TPR,FPR=divide(FP,N),TNR=TNR,FNR=divide(FN,P),F1=divide(2*TP,2*TP+FP+FN),balancedAccuracy=None if TPR is None or TNR is None else(TPR+TNR)/2,Brier=divide(brier,mass),BrierSum=brier,totalCost=total,meanCost=divide(total,mass),predictions=pred,bayesThreshold=divide(cc[0],sum(cc)))\ndef curves(rows):\n use=[r for r in rows if r['eligible']];pos=Counter();neg=Counter()\n for r in use:(pos if r['y']else neg)[r['score']]+=r['w']\n P=sum(pos.values(),F(0));N=sum(neg.values(),F(0));pairs=F(0)\n for a,wa in pos.items():\n  for b,wb in neg.items():pairs+=wa*wb*(F(1)if a>b else F(1,2)if a==b else F(0))\n thresholds=['always-negative']+sorted({r['score']for r in use},reverse=True);points=[];AP=F(0);trap=F(0);lastR=F(0);lastP=F(1)\n for i,p in enumerate(thresholds):\n  m=metrics(rows,p);points.append(dict(policy=p,TP=m['confusion']['TP'],FP=m['confusion']['FP'],FN=m['confusion']['FN'],TN=m['confusion']['TN'],TPR=m['TPR'],FPR=m['FPR'],precision=m['precision'],recall=m['TPR']))\n  if i and P:\n   R=m['TPR'];PP=m['precision'];AP+=(R-lastR)*PP;trap+=(R-lastR)*(PP+lastP)/2;lastR=R;lastP=PP\n return dict(positiveMass=P,negativeMass=N,ROC_AUC=divide(pairs,P*N),weightedConcordantPlusHalfTiedMass=pairs,averagePrecision=AP if P else None,PRTrapezoidWithInitialPrecisionOne=trap if P else None,points=points)\ndef choose(rows,a,cc):\n sr=a.get('selectionRole','validation');er=a.get('evaluationRole','test');rr=scoped(rows,sr);thresholds=[policy(t)for t in a['thresholds']]if'thresholds'in a else['always-negative']+sorted({r['score']for r in rr if r['eligible']},reverse=True)\n candidates=[]\n for i,p in enumerate(thresholds):\n  m=metrics(rr,p,cc);reasons=[]\n  if'minTPR'in a and(m['TPR']is None or m['TPR']<F(str(a['minTPR']))):reasons.append('TPR-undefined'if m['TPR']is None else'below-minTPR')\n  if'maxFPR'in a and(m['FPR']is None or m['FPR']>F(str(a['maxFPR']))):reasons.append('FPR-undefined'if m['FPR']is None else'above-maxFPR')\n  candidates.append(dict(index=i,policy=p,metrics=m,feasible=not reasons,reasons=reasons))\n eligible=[c for c in candidates if c['feasible']];best=min(eligible,key=lambda c:(c['metrics']['meanCost'],c['index']))if eligible else None\n return dict(selectedIndex=None if best is None else best['index'],selectedPolicy=None if best is None else best['policy'],candidates=candidates,selectedValidation=None if best is None else best['metrics'],evaluation=None if best is None or er=='none'else metrics(scoped(rows,er),best['policy'],cc),selectionIDs=[r['id']for r in rr if r['eligible']])\ndef calibrate(rows,ee):\n buckets=[[]for _ in range(len(ee)-1)]\n for r in rows:\n  if not r['eligible']:continue\n  j=next((i for i in range(len(ee)-1)if r['score']<ee[i+1]),len(ee)-2);buckets[j].append(r)\n mass=sum((r['w']for r in rows if r['eligible']),F(0));P=sum((r['w']*r['y']for r in rows if r['eligible']),F(0));pi=divide(P,mass);Brier=None if not mass else sum((r['w']*(r['score']-r['y'])**2 for r in rows if r['eligible']),F(0))/mass;ECE=F(0);reliability=F(0);resolution=F(0);correction=F(0);bins=[]\n for i,rr in enumerate(buckets):\n  w=sum((r['w']for r in rr),F(0));mp=None if not w else sum((r['w']*r['score']for r in rr),F(0))/w;o=None if not w else sum((r['w']*r['y']for r in rr),F(0))/w\n  variance=None if not w else sum((r['w']*(r['score']-mp)**2 for r in rr),F(0))/w\n  covariance=None if not w else sum((r['w']*(r['score']-mp)*(r['y']-o)for r in rr),F(0))/w\n  bc=None if not w else variance-2*covariance;gap=None if not w else mp-o\n  bins.append(dict(index=i,rows=len(rr),mass=w,meanPrediction=mp,eventRate=o,gap=gap,absoluteGap=None if gap is None else abs(gap),scoreVariance=variance,scoreTargetCovariance=covariance,withinBinCorrection=bc,ids=[r['id']for r in rr]))\n  if w:\n   share=w/mass;ECE+=share*abs(gap);reliability+=share*gap**2;resolution+=share*(o-pi)**2;correction+=share*bc\n uncertainty=None if pi is None else pi*(1-pi);residual=None if Brier is None else Brier-(uncertainty-resolution+reliability+correction)\n return dict(mass=mass,prevalence=pi,Brier=Brier,ECE=ECE if mass else None,reliability=reliability if mass else None,resolution=resolution if mass else None,uncertainty=uncertainty,withinBinCorrection=correction if mass else None,BrierIdentityResidual=residual,bins=bins)\ndef typed(v):return type(v).__name__,v\ndef groups(rows,p,cc):\n bins={}\n for r in rows:\n  if r['group']is not None:bins.setdefault(typed(r['group']),[]).append(r)\n gm=[dict(group=rr[0]['group'],metrics=metrics(rr,p,cc))for rr in bins.values()];overall=metrics(rows,p,cc);unknown=metrics([r for r in rows if r['group']is None],p,cc);gaps={}\n for key in ['prevalence','selectionRate','TPR','FPR','precision','accuracy','meanCost']:\n  positive=[g for g in gm if g['metrics']['mass']>0];undefined=[g['group']for g in positive if g['metrics'][key]is None];vals=[g['metrics'][key]for g in positive if g['metrics'][key]is not None]\n  gaps[key]=dict(value=None if len(positive)<2 or undefined else max(vals)-min(vals),undefinedGroups=undefined,comparedPositiveMassGroups=[g['group']for g in positive])\n return dict(overall=overall,groups=gm,unknownGroup=unknown,gaps=gaps,partitionMassResidual=overall['mass']-unknown['mass']-sum((g['metrics']['mass']for g in gm),F(0)))\ndef actual_model(M):\n raw=M['records'];cat=M['categoricalFeatures'];p=len(raw[0]['x']);train=[r for r in raw if r['role']=='train'];medians=[]\n for j in range(p):\n  if j in cat:medians.append(None);continue\n  values=sorted(F(r['x'][j])for r in train);n=len(values);medians.append(values[n//2]if n%2 else(values[n//2-1]+values[n//2])/2)\n def transform(r):return[F(v)if j in cat else F(int(F(v)>medians[j]))for j,v in enumerate(r['x'])]\n counts={}\n for r in train:\n  key=tuple(transform(r));n,s=counts.get(key,(0,0));counts[key]=(n+1,s+int(r['y']))\n probabilities={k:F(s+1,n+2)for k,(n,s)in counts.items()};fallback=F(sum(int(r['y'])for r in train)+1,len(train)+2);scored=[]\n for i,r in enumerate(raw):\n  eligible=r['role']!='excluded';z=transform(r)if eligible else None;key=None if z is None else tuple(z);score=None if not eligible else probabilities.get(key,fallback)\n  scored.append(dict(id=r['id'],index=i,role=r['role'],group=r['group'],y=None if r['y']is None else F(r['y']),score=score,w=F(1),eligible=eligible,transformedX=z,unseenCell=None if not eligible else key not in probabilities))\n return dict(medians=medians,cells=counts,probabilities=probabilities,fallback=fallback,rows=scored,trainIDs=[r['id']for r in train])\n\n\nimport csv,json,hashlib,argparse,datetime\nfrom pathlib import Path\ndef missing(v):return None if v in ['', '.',None]else v\ndef load_sources(folder):\n def read_csv(name):\n  with (folder/name).open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))\n wb=read_csv('actual64-country-four-indicators-original-2024.csv')\n codes=['NY.GDP.PCAP.KD','NY.GDP.MKTP.KD.ZG','FP.CPI.TOTL.ZG','SP.DYN.LE00.IN']\n lookup={(r['countryISO3'],r['indicatorID']):r for r in wb};country=[]\n for i,iso in enumerate(sorted({r['countryISO3']for r in wb}),1):\n  native=[lookup[iso,c]for c in codes];v=[missing(r['originalValueToken'])for r in native]\n  country.append(dict(id=iso+':2024',sourceRow=i,originalID=iso,x=v[:3],y=None if v[3]is None else str(int(F(v[3])>=80)),group=None if v[0]is None else str(int(F(v[0])>=25000)),nativeTarget=v[3],nativeSourceRows=';'.join(r['sourceRow']for r in native)))\n nls=read_csv('actual3613-NLS-original52-fields-groups-roles.csv');person=[]\n for r in nls:\n  y=missing(r['wage76']);person.append(dict(id='person:'+r['sourceRow'],sourceRow=int(r['sourceRow']),originalID=r['id'],x=[missing(r[k])for k in ['ed76','age76','nearc4']],y=None if y is None else str(int(F(y)>=500)),group=missing(r['black']),nativeTarget=y,nativeSourceRows=r['sourceRow']))\n ch=read_csv('actual3150-churn-original14-fields-groups-roles.csv');company=[]\n for r in ch:\n  company.append(dict(id='customer:'+r['sourceRow'],sourceRow=int(r['sourceRow']),originalID='',x=[missing(r[k])for k in ['Call  Failure','Complains','Subscription  Length','Seconds of Use']],y=missing(r['Churn']),group=missing(r['Tariff Plan']),nativeTarget=missing(r['Churn']),nativeSourceRows=r['sourceRow']))\n assert len(wb)==64 and len(country)==16 and len(nls)==3613 and len(ch)==3150\n assert [int(r['sourceRow'])for r in ch if r['Charge  Amount']=='10']==[474,2174,2274,2374,2674,2924,2974]\n models={}\n for kind,raw,cat,units in [('country',country,[],['constant2015USD/person','annualPercent','annualPercent']),('person',person,[2],['years','years','nativeCategory']),('company',company,[1],['count','nativeCategory','months','seconds'])]:\n  order=sorted(range(len(raw)),key=lambda i:(hashlib.sha256(('ML14-role|'+kind+'|'+raw[i]['id']).encode()).hexdigest(),i))\n  for rank,i in enumerate(order):\n   r=raw[i];r['plannedRole']='test'if rank%5==0 else'validation'if rank%5==1 else'train';r['eligible']=None not in r['x']+[r['y']];r['role']=r['plannedRole']if r['eligible']else'excluded';r['weight']='1'\n  models[kind]=dict(records=raw,categoricalFeatures=cat,featureUnits=units)\n assert sum(r['eligible']for r in person)==3017\n return models\n\ndef exact(v):return ''if v is None else str(v)\ndef approx(v):return ''if v is None else format(float(v),'.17g')\ndef scalar_fields(m,keys):\n out={}\n for k in keys:\n  out[k+'Exact']=exact(m[k]);out[k+'Approx']=approx(m[k])\n return out\nCOUNTS=['mass','positiveTargetMass','negativeTargetMass','predictedPositiveMass','predictedNegativeMass']\nRATES=['prevalence','selectionRate','accuracy','precision','negativePredictiveValue','TPR','FPR','TNR','FNR','F1','balancedAccuracy','Brier','BrierSum','totalCost','meanCost']\nSCENARIOS=[('equal',F(1),F(1)),('miss-five',F(1),F(5)),('alarm-five',F(5),F(1))]\ndef packed(v):\n if isinstance(v,F):return str(v)\n if isinstance(v,dict):return{str(k):packed(x)for k,x in v.items()}\n if isinstance(v,(tuple,list)):return[packed(x)for x in v]\n return v\ndef run_study(source,out):\n out.mkdir(parents=True,exist_ok=True);models=load_sources(source)\n tables={name:[]for name in ['predictions','lineage','fit-medians','fit-cells','validation-candidates','test-metrics','test-curves','calibration-bins','group-metrics','chart-points']}\n studies={};charts=[]\n def point(kind,chart,series,index,x,y,xunit='dimensionless',yunit='dimensionless',role='test',tag=''):\n  tables['chart-points'].append(dict(kind=kind,chart=chart,series=series,index=index,xExact=exact(x),xApprox=approx(x),yExact=exact(y),yApprox=approx(y),xUnit=xunit,yUnit=yunit,role=role,tag=tag))\n for kind,M in models.items():\n  fit=actual_model(M);rr=fit['rows'];native=M['records'];test=scoped(rr,'test');cv=curves(test);cal=calibrate(test,[F(0),F(1,5),F(2,5),F(3,5),F(4,5),F(1)]);scenarios=[]\n  for i,r in enumerate(rr):\n   n=native[i];reason=''if r['eligible']else'required-X-or-Y-missing'\n   tables['predictions'].append(dict(kind=kind,id=r['id'],sourceRow=n['sourceRow'],originalID=n['originalID'],plannedRole=n['plannedRole'],role=r['role'],group=''if r['group']is None else r['group'],eligible=int(r['eligible']),targetExact=exact(r['y']),probabilityExact=exact(r['score']),probabilityApprox=approx(r['score']),unseenCell=''if r['unseenCell']is None else int(r['unseenCell']),transformedX=''if r['transformedX']is None else'|'.join(map(str,r['transformedX'])),reason=reason))\n   tables['lineage'].append(dict(kind=kind,id=r['id'],sourceRow=n['sourceRow'],originalID=n['originalID'],nativeSourceRows=n['nativeSourceRows'],rawX='|'.join(''if x is None else x for x in n['x']),nativeTarget=''if n['nativeTarget']is None else n['nativeTarget'],derivedTarget=exact(r['y']),nativeGroup=''if n['group']is None else n['group'],plannedRole=n['plannedRole'],role=r['role'],eligible=int(r['eligible']),analyticalMass='1',reason=reason))\n  for j,v in enumerate(fit['medians']):tables['fit-medians'].append(dict(kind=kind,feature=j,categorical=int(j in M['categoricalFeatures']),fitRows=len(fit['trainIDs']),medianExact=exact(v),medianApprox=approx(v),unit=M['featureUnits'][j]))\n  for key,(mass,pos)in fit['cells'].items():tables['fit-cells'].append(dict(kind=kind,cell='|'.join(map(str,key)),trainingRows=mass,positiveRows=pos,probabilityExact=exact(fit['probabilities'][key]),probabilityApprox=approx(fit['probabilities'][key]),fallbackExact=exact(fit['fallback']),fallbackApprox=approx(fit['fallback'])))\n  for j,p in enumerate(cv['points']):\n   policy=p['policy'];tables['test-curves'].append(dict(kind=kind,point=j,policy=policy if isinstance(policy,str)else'threshold',thresholdExact=''if isinstance(policy,str)else exact(policy),thresholdApprox=''if isinstance(policy,str)else approx(policy),**scalar_fields(p,['TP','FP','FN','TN','TPR','FPR','precision','recall'])))\n   point(kind,'roc','ROC',j,p['FPR'],p['TPR']);point(kind,'pr','PR-observed',j,p['recall'],p['precision'])\n  for b in cal['bins']:\n   tables['calibration-bins'].append(dict(kind=kind,bin=b['index'],leftExact=str(F(b['index'],5)),rightExact=str(F(b['index']+1,5)),rightClosed=int(b['index']==4),rows=b['rows'],ids=';'.join(str(i)for i in b['ids']),**scalar_fields(b,['mass','meanPrediction','eventRate','gap','absoluteGap','scoreVariance','scoreTargetCovariance','withinBinCorrection'])))\n   point(kind,'reliability','Binary event rate',b['index'],b['meanPrediction'],b['eventRate'],tag='rows='+str(b['rows']))\n  for j,r in enumerate(test):\n   point(kind,'test-scores','Training-fitted probability',j,F(j+1),r['score'],'test-row position','probability',tag=r['id'])\n   point(kind,'test-scores','Observed Y',j,F(j+1),r['y'],'test-row position','binary target',tag=r['id'])\n  for name,fp,fn in SCENARIOS:\n   choice=choose(rr,{},(fp,fn));gm=groups(test,choice['selectedPolicy'],(fp,fn));scenarios.append(dict(name=name,costs=dict(falsePositive=fp,falseNegative=fn),selection=choice,groups=gm));ev=choice['evaluation']\n   for c in choice['candidates']:\n    policy=c['policy'];mm=c['metrics'];tables['validation-candidates'].append(dict(kind=kind,scenario=name,candidate=c['index'],selected=int(c['index']==choice['selectedIndex']),policy=policy if isinstance(policy,str)else'threshold',thresholdExact=''if isinstance(policy,str)else exact(policy),thresholdApprox=''if isinstance(policy,str)else approx(policy),feasible=int(c['feasible']),reasons=';'.join(c['reasons']),**{k+'Exact':str(v)for k,v in mm['confusion'].items()},**scalar_fields(mm,COUNTS+['TPR','FPR','precision','meanCost','totalCost'])))\n    point(kind,'validation-cost',name,c['index'],F(c['index']),mm['meanCost'],'candidate index','hypothetical cost units/mass','validation',tag=exact(policy))\n   mm={**ev,**ev['confusion'],**{k:cv[k]for k in ['ROC_AUC','averagePrecision','PRTrapezoidWithInitialPrecisionOne']},**{k:cal[k]for k in ['ECE','reliability','resolution','uncertainty','withinBinCorrection','BrierIdentityResidual']}}\n   for key in ['TP','FP','FN','TN']+COUNTS+RATES+['ROC_AUC','averagePrecision','PRTrapezoidWithInitialPrecisionOne','ECE','reliability','resolution','uncertainty','withinBinCorrection','BrierIdentityResidual']:\n    unit='rows'if key in ['TP','FP','FN','TN']+COUNTS else'hypothetical cost units'if key=='totalCost'else'hypothetical cost units/mass'if key=='meanCost'else'sum squared-probability loss'if key=='BrierSum'else'dimensionless'\n    tables['test-metrics'].append(dict(kind=kind,scenario=name,metric=key,valueExact=exact(mm[key]),valueApprox=approx(mm[key]),unit=unit))\n   allg=[('overall','all',gm['overall'])]+[('known',str(g['group']),g['metrics'])for g in gm['groups']]+[('unknown','',gm['unknownGroup'])]\n   for j,(typ,token,g)in enumerate(allg):\n    tables['group-metrics'].append(dict(kind=kind,scenario=name,groupType=typ,groupToken=token,retainedRows=g.get('retainedRows',sum((r['group']==token)if typ=='known'else(r['group']is None)if typ=='unknown'else True for r in test)),**{k+'Exact':str(v)for k,v in g['confusion'].items()},**scalar_fields(g,COUNTS+RATES)))\n    if typ=='known':point(kind,'group-TPR',name,j-1,F(j-1),g['TPR'],'declared group position','TPR',tag=token)\n  studies[kind]=dict(kind=kind,rows=len(native),eligibleRows=sum(r['eligible']for r in rr),trainingIDs=fit['trainIDs'],fitMedians=fit['medians'],fitCells=[dict(cell=list(k),mass=n,positive=s,probability=fit['probabilities'][k])for k,(n,s)in fit['cells'].items()],fallback=fit['fallback'],scenarios=scenarios,testCurves=cv,testCalibration=cal,rowsScored=rr)\n files=[]\n for name,rows in tables.items():\n  p=out/('computed-'+name+'.csv')\n  with p.open('w',encoding='utf8',newline='')as f:w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows)\n  files.append(dict(file=p.name,rows=len(rows),columns=len(rows[0]),bodyFields=len(rows)*len(rows[0]),sha256=hashlib.sha256(p.read_bytes()).hexdigest()))\n (out/'study.json').write_text(json.dumps(packed(studies),ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\n sourceFiles=[source/n for n in ['actual64-country-four-indicators-original-2024.csv','actual3613-NLS-original52-fields-groups-roles.csv','actual3150-churn-original14-fields-groups-roles.csv']]\n provenance=dict(chapter='ML-14',arithmetic='Python stdlib Fraction exact finite values from original decimal strings; binary64 valueApprox is display only.',inputs=[dict(file=p.name,sha256=hashlib.sha256(p.read_bytes()).hexdigest())for p in sourceFiles],priorEngineModelsScoresOrComputedFilesRead=False,roleRule=\"SHA256('ML14-role|'+kind+'|'+ID),rankmod5=0test/1validation/others train before eligibility\",costs='Hypothetical1/1,1/5,5/1; no causal intervention returns',files=files,observations={k:dict(sourceRows=v['rows'],eligibleRows=v['eligibleRows'],trainingRows=len(v['trainingIDs']))for k,v in studies.items()})\n (out/'provenance.json').write_text(json.dumps(provenance,ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\n print(json.dumps(dict(status='PASS standalone completed',files=len(files),bodyFields=sum(f['bodyFields']for f in files),observations=provenance['observations'])))\n\n# Fixed declared examples: full web budget/option validation is not reproduced.\nfrom html import escape\nimport textwrap\ndef validated_rows(raw):\n for r in raw:\n  assert F(str(r.get('weight','1')))>=0,'negative analytical mass'\n  assert r['score']is None or 0<=F(str(r['score']))<=1,'score outside zero/one'\n  assert r['y']is None or F(str(int(r['y']))if isinstance(r['y'],bool)else str(r['y']))in [0,1],'binary target required'\n return read(raw)\ndef serial(v):\n if isinstance(v,F):return dict(exactFraction=str(v),value=float(v))\n if isinstance(v,(list,tuple)):return[serial(x)for x in v]\n if isinstance(v,dict):return{k:serial(x)for k,x in v.items()}\n return v\ndef fixed_svg(path,points,title,xlabel,ylabel,legend):\n use=[p for p in points if p['xExact']!=''and p['yExact']!=''];xs=[float(F(p['xExact']))for p in use];ys=[float(F(p['yExact']))for p in use]\n xmin=min(xs,default=0);xmax=max(xs,default=1);ymin=min([0]+ys);ymax=max([0]+ys)\n if xmin==xmax:xmin-=.5;xmax+=.5\n if ymin==ymax:ymax=ymin+1\n X=lambda v:85+(float(v)-xmin)/(xmax-xmin)*480;Y=lambda v:278-(float(v)-ymin)/(ymax-ymin)*175\n s='<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"620\" height=\"360\" viewBox=\"0 0 620 360\"><rect width=\"620\" height=\"360\" fill=\"white\"/><g font-family=\"Arial, sans-serif\" font-size=\"13\" fill=\"#17324d\">'\n for i,line in enumerate(textwrap.wrap(title,width=65)):s+='<text x=\"25\" y=\"'+str(24+i*18)+'\">'+escape(line)+'</text>'\n colors=['#176b9b','#b85e18','#437e4d']\n for i,label in enumerate(legend):s+='<circle cx=\"'+str(30+i*250)+'\" cy=\"76\" r=\"4\" fill=\"'+colors[i%3]+'\"/><text x=\"'+str(42+i*250)+'\" y=\"80\">'+escape(label)+'</text>'\n s+='<path d=\"M85 98V278H575\" fill=\"none\" stroke=\"#52677d\"/><text text-anchor=\"middle\" x=\"325\" y=\"338\">'+escape(xlabel)+'</text><text text-anchor=\"middle\" transform=\"translate(21,190) rotate(-90)\">'+escape(ylabel)+'</text>'\n for i in range(5):\n  xx=xmin+(xmax-xmin)*i/4;yy=ymin+(ymax-ymin)*i/4;s+='<text text-anchor=\"middle\" x=\"'+format(X(xx),'.9g')+'\" y=\"305\">'+format(xx,'.4g')+'</text><text text-anchor=\"end\" x=\"77\" y=\"'+format(Y(yy)+4,'.9g')+'\">'+format(yy,'.4g')+'</text>'\n for p in use:s+='<circle cx=\"'+format(X(F(p['xExact'])),'.9g')+'\" cy=\"'+format(Y(F(p['yExact'])),'.9g')+'\" r=\"3\" fill=\"'+colors[p['series']%3]+'\"/>'\n path.write_text(s+'</g></svg>',encoding='utf8')\ndef fixed_run():\n ap=argparse.ArgumentParser();ap.add_argument('--out',type=Path,default=Path('results'));ap.add_argument('--data-dir',type=Path,default=Path(__file__).resolve().parent.parent/'ml14-sources');args=ap.parse_args();args.out.mkdir(parents=True,exist_ok=True)\n api=FIXED['api'];a=FIXED['args'];summary=[];points=[];xlabel='Declared index';ylabel='Value';legend=['Declared result']\n def metric(name,v,unit='dimensionless'):\n  q=None if v is None else v if isinstance(v,F)else F(v);summary.append(dict(metric=name,value='undefined'if q is None else format(float(q),'.9g'),exactValue=''if q is None else str(q),unit=unit,defined=int(q is not None)))\n def pt(i,x,y,ident='',series=0):\n  points.append(dict(series=series,index=i,xExact=''if x is None else str(F(x)),x='undefined'if x is None else format(float(x),'.9g'),yExact=''if y is None else str(F(y)),y='undefined'if y is None else format(float(y),'.9g'),id=str(ident)))\n if api=='realdata':\n  models=load_sources(args.data_dir);model=models[a['kind']];fit=actual_model(model);rr=fit['rows'];test=scoped(rr,'test');scenarios=[]\n  for name,fp,fn in SCENARIOS:\n   c=choose(rr,{},(fp,fn));scenarios.append(dict(name=name,selection=c));metric(name+'Threshold',c['selectedPolicy']);metric(name+'TestCost',c['evaluation']['meanCost'],'hypothetical cost units/mass')\n  cv=curves(test);cal=calibrate(test,[F(0),F(1,5),F(2,5),F(3,5),F(4,5),F(1)]);metric('testAUC',cv['ROC_AUC']);metric('testAP',cv['averagePrecision']);metric('testBrier',cal['Brier']);metric('eligibleRows',sum(r['eligible']for r in rr),'rows')\n  for i,r in enumerate(test):pt(i,i+1,r['score'],r['id'],0);pt(i,i+1,r['y'],r['id'],1)\n  full=dict(kind=a['kind'],fitMedians=fit['medians'],fitCells=[dict(cell=list(k),mass=n,positive=s,probability=fit['probabilities'][k])for k,(n,s)in fit['cells'].items()],rowsScored=rr,scenarios=scenarios,testCurves=cv,testCalibration=cal);xlabel='Test row, native order';ylabel='Y or probability';legend=['Training-fitted probability','Observed Y']\n else:\n  rr=validated_rows(a['rows']);role=a.get('role','all');frame=scoped(rr,role);cc=cost(a.get('costs'));t=policy(a.get('threshold','1/2'))\n  if api=='metrics':\n   full=metrics(frame,t,cc)\n   for k in ['mass','accuracy','precision','TPR','FPR','F1','Brier','meanCost']:metric(k,full[k],'mass'if k=='mass'else'hypothetical cost units/mass'if k=='meanCost'else'dimensionless')\n   metric('BayesThreshold',full['bayesThreshold'])\n   for i,k in enumerate(['TP','FP','FN','TN']):pt(i,i,full['confusion'][k],k)\n   xlabel='TP / FP / FN / TN positions';ylabel='Analytical mass'\n  elif api=='curves':\n   full=curves(frame)\n   for k in ['ROC_AUC','averagePrecision','PRTrapezoidWithInitialPrecisionOne']:metric(k,full[k])\n   for i,p in enumerate(full['points']):pt(i,p['FPR'],p['TPR'],str(p['policy']))\n   xlabel='False positive rate';ylabel='True positive rate';legend=['Observed ROC operating points']\n  elif api=='choose':\n   full=choose(rr,a,cc);metric('selectedIndex',full['selectedIndex'],'candidate index');metric('minimumCost',None if full['selectedValidation']is None else full['selectedValidation']['meanCost'],'hypothetical cost units/mass');metric('feasible',int(full['selectedIndex']is not None),'indicator')\n   for c in full['candidates']:pt(c['index'],c['index'],c['metrics']['meanCost'],str(c['policy']))\n   xlabel='Validation candidate';ylabel='Assumed cost / mass';legend=['Validation candidate costs']\n  elif api=='calibrate':\n   full=calibrate(frame,[F(str(e))for e in a.get('binEdges',['0','1/5','2/5','3/5','4/5','1'])])\n   for k in ['ECE','Brier','uncertainty','resolution','reliability','withinBinCorrection','BrierIdentityResidual']:metric(k,full[k])\n   for b in full['bins']:pt(b['index'],b['meanPrediction'],b['eventRate'],'bin:'+str(b['index']))\n   xlabel='Bin mean forecast';ylabel='Bin event rate';legend=['Binary-event reliability']\n  elif api=='groups':\n   full=groups(frame,t,cc);metric('overallTPR',full['overall']['TPR']);metric('TPRGap',full['gaps']['TPR']['value']);metric('precisionGap',full['gaps']['precision']['value']);metric('unknownMass',full['unknownGroup']['mass'],'mass');metric('partitionResidual',full['partitionMassResidual'],'mass')\n   for i,g in enumerate(full['groups']):pt(i,i,g['metrics']['TPR'],str(g['group']))\n   xlabel='Declared group position';ylabel='True positive rate';legend=['Known-group TPR']\n  else:raise ValueError('unknown fixed API')\n def csvout(name,rows):\n  with(args.out/name).open('w',encoding='utf8',newline='')as f:w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows)\n csvout('summary.csv',summary);csvout('plot-points.csv',points);fixed_svg(args.out/'plot.svg',points,FIXED['title'],xlabel,ylabel,legend)\n (args.out/'full.json').write_text(json.dumps(dict(api=api,variant=FIXED['variant'],input=FIXED['args'],arithmetic='Python standard-library Fraction, declared fixed example; full web validator/budgets not reproduced',result=serial(full)),ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\n print(json.dumps(dict(api=api,variant=FIXED['variant'],summaryMetrics=len(summary),plotSlots=len(points))))\n\nFIXED={'api': 'curves', 'variant': 'all-tied', 'args': {'rows': [{'id': 'a', 'score': '.5', 'y': 1, 'group': 'A'}, {'id': 'b', 'score': '.5', 'y': 1, 'group': 'A'}, {'id': 'c', 'score': '.5', 'y': 0, 'group': 'A'}, {'id': 'd', 'score': '.5', 'y': 0, 'group': 'B'}, {'id': 'e', 'score': '.5', 'y': 1, 'group': 'B'}, {'id': 'f', 'score': '.5', 'y': 0, 'group': 'B'}]}, 'title': 'All scores tied: half pair credit and prevalence AP'}\nif __name__=='__main__':fixed_run()\n",
        "codeText": "#!/usr/bin/env python3\n\"\"\"ML14 standalone exact finite study, Python standard library only.\nInputs: only the three retained factual source CSVs below.\nDerived role/target/group/eligibility columns in those CSVs are NOT inputs.\nRebuilds SHA256 roles, train-only medians/cell scores, validation thresholds,\ntest curves, binary-event reliability and descriptive group ledgers.\nCosts 1/1,1/5,5/1 are hypothetical units, not measured intervention returns.\nThis is author public reproduction, not independent scientific review.\n\"\"\"\n\"\"\"Author Fraction reference, separate from product JavaScript; not independent peer.\"\"\"\nfrom fractions import Fraction as F\nfrom collections import Counter,defaultdict\ndef read(raw):\n rows=[]\n for i,r in enumerate(raw):\n  s=None if r['score']is None else F(str(r['score']));y=None if r['y']is None else F(int(r['y']))if isinstance(r['y'],bool)else F(str(r['y']));w=F(str(r.get('weight','1')));role=r.get('role','evaluation')\n  rows.append(dict(id=r['id'],index=i,score=s,y=y,w=w,role=role,group=r.get('group'),eligible=s is not None and y is not None and w>0 and role!='excluded'))\n return rows\ndef scoped(rows,role='all'):return rows if role=='all'else[r for r in rows if r['role']==role]\ndef divide(n,d):return None if not d else n/d\ndef policy(v):return v if v in ['always-negative','always-positive']else F(str(v))\ndef positive(p,s):return p=='always-positive'if isinstance(p,str)else s>=p\ndef cost(a=None):\n a={}if a is None else a;fp=F(str(a.get('falsePositive','1')));fn=F(str(a.get('falseNegative','1')));return fp,fn\ndef metrics(rows,threshold=F(1,2),cc=(F(1),F(1))):\n counts=dict(TP=F(0),FP=F(0),FN=F(0),TN=F(0));brier=F(0);pred=[]\n for r in rows:\n  if not r['eligible']:pred.append(dict(id=r['id'],index=r['index'],eligible=False,decision=None,probability=None,Brier=None));continue\n  yes=positive(threshold,r['score']);cell=('T'if yes==bool(r['y'])else'F')+('P'if yes else'N');counts[cell]+=r['w'];loss=(r['score']-r['y'])**2;brier+=r['w']*loss;pred.append(dict(id=r['id'],index=r['index'],eligible=True,decision=int(yes),probability=r['score'],Brier=loss))\n TP,FP,FN,TN=[counts[k]for k in ['TP','FP','FN','TN']];P=TP+FN;N=TN+FP;mass=P+N;PP=TP+FP;PN=TN+FN;TPR=divide(TP,P);TNR=divide(TN,N);total=FP*cc[0]+FN*cc[1]\n return dict(confusion=counts,mass=mass,positiveTargetMass=P,negativeTargetMass=N,predictedPositiveMass=PP,predictedNegativeMass=PN,prevalence=divide(P,mass),selectionRate=divide(PP,mass),accuracy=divide(TP+TN,mass),precision=divide(TP,PP),negativePredictiveValue=divide(TN,PN),TPR=TPR,FPR=divide(FP,N),TNR=TNR,FNR=divide(FN,P),F1=divide(2*TP,2*TP+FP+FN),balancedAccuracy=None if TPR is None or TNR is None else(TPR+TNR)/2,Brier=divide(brier,mass),BrierSum=brier,totalCost=total,meanCost=divide(total,mass),predictions=pred,bayesThreshold=divide(cc[0],sum(cc)))\ndef curves(rows):\n use=[r for r in rows if r['eligible']];pos=Counter();neg=Counter()\n for r in use:(pos if r['y']else neg)[r['score']]+=r['w']\n P=sum(pos.values(),F(0));N=sum(neg.values(),F(0));pairs=F(0)\n for a,wa in pos.items():\n  for b,wb in neg.items():pairs+=wa*wb*(F(1)if a>b else F(1,2)if a==b else F(0))\n thresholds=['always-negative']+sorted({r['score']for r in use},reverse=True);points=[];AP=F(0);trap=F(0);lastR=F(0);lastP=F(1)\n for i,p in enumerate(thresholds):\n  m=metrics(rows,p);points.append(dict(policy=p,TP=m['confusion']['TP'],FP=m['confusion']['FP'],FN=m['confusion']['FN'],TN=m['confusion']['TN'],TPR=m['TPR'],FPR=m['FPR'],precision=m['precision'],recall=m['TPR']))\n  if i and P:\n   R=m['TPR'];PP=m['precision'];AP+=(R-lastR)*PP;trap+=(R-lastR)*(PP+lastP)/2;lastR=R;lastP=PP\n return dict(positiveMass=P,negativeMass=N,ROC_AUC=divide(pairs,P*N),weightedConcordantPlusHalfTiedMass=pairs,averagePrecision=AP if P else None,PRTrapezoidWithInitialPrecisionOne=trap if P else None,points=points)\ndef choose(rows,a,cc):\n sr=a.get('selectionRole','validation');er=a.get('evaluationRole','test');rr=scoped(rows,sr);thresholds=[policy(t)for t in a['thresholds']]if'thresholds'in a else['always-negative']+sorted({r['score']for r in rr if r['eligible']},reverse=True)\n candidates=[]\n for i,p in enumerate(thresholds):\n  m=metrics(rr,p,cc);reasons=[]\n  if'minTPR'in a and(m['TPR']is None or m['TPR']<F(str(a['minTPR']))):reasons.append('TPR-undefined'if m['TPR']is None else'below-minTPR')\n  if'maxFPR'in a and(m['FPR']is None or m['FPR']>F(str(a['maxFPR']))):reasons.append('FPR-undefined'if m['FPR']is None else'above-maxFPR')\n  candidates.append(dict(index=i,policy=p,metrics=m,feasible=not reasons,reasons=reasons))\n eligible=[c for c in candidates if c['feasible']];best=min(eligible,key=lambda c:(c['metrics']['meanCost'],c['index']))if eligible else None\n return dict(selectedIndex=None if best is None else best['index'],selectedPolicy=None if best is None else best['policy'],candidates=candidates,selectedValidation=None if best is None else best['metrics'],evaluation=None if best is None or er=='none'else metrics(scoped(rows,er),best['policy'],cc),selectionIDs=[r['id']for r in rr if r['eligible']])\ndef calibrate(rows,ee):\n buckets=[[]for _ in range(len(ee)-1)]\n for r in rows:\n  if not r['eligible']:continue\n  j=next((i for i in range(len(ee)-1)if r['score']<ee[i+1]),len(ee)-2);buckets[j].append(r)\n mass=sum((r['w']for r in rows if r['eligible']),F(0));P=sum((r['w']*r['y']for r in rows if r['eligible']),F(0));pi=divide(P,mass);Brier=None if not mass else sum((r['w']*(r['score']-r['y'])**2 for r in rows if r['eligible']),F(0))/mass;ECE=F(0);reliability=F(0);resolution=F(0);correction=F(0);bins=[]\n for i,rr in enumerate(buckets):\n  w=sum((r['w']for r in rr),F(0));mp=None if not w else sum((r['w']*r['score']for r in rr),F(0))/w;o=None if not w else sum((r['w']*r['y']for r in rr),F(0))/w\n  variance=None if not w else sum((r['w']*(r['score']-mp)**2 for r in rr),F(0))/w\n  covariance=None if not w else sum((r['w']*(r['score']-mp)*(r['y']-o)for r in rr),F(0))/w\n  bc=None if not w else variance-2*covariance;gap=None if not w else mp-o\n  bins.append(dict(index=i,rows=len(rr),mass=w,meanPrediction=mp,eventRate=o,gap=gap,absoluteGap=None if gap is None else abs(gap),scoreVariance=variance,scoreTargetCovariance=covariance,withinBinCorrection=bc,ids=[r['id']for r in rr]))\n  if w:\n   share=w/mass;ECE+=share*abs(gap);reliability+=share*gap**2;resolution+=share*(o-pi)**2;correction+=share*bc\n uncertainty=None if pi is None else pi*(1-pi);residual=None if Brier is None else Brier-(uncertainty-resolution+reliability+correction)\n return dict(mass=mass,prevalence=pi,Brier=Brier,ECE=ECE if mass else None,reliability=reliability if mass else None,resolution=resolution if mass else None,uncertainty=uncertainty,withinBinCorrection=correction if mass else None,BrierIdentityResidual=residual,bins=bins)\ndef typed(v):return type(v).__name__,v\ndef groups(rows,p,cc):\n bins={}\n for r in rows:\n  if r['group']is not None:bins.setdefault(typed(r['group']),[]).append(r)\n gm=[dict(group=rr[0]['group'],metrics=metrics(rr,p,cc))for rr in bins.values()];overall=metrics(rows,p,cc);unknown=metrics([r for r in rows if r['group']is None],p,cc);gaps={}\n for key in ['prevalence','selectionRate','TPR','FPR','precision','accuracy','meanCost']:\n  positive=[g for g in gm if g['metrics']['mass']>0];undefined=[g['group']for g in positive if g['metrics'][key]is None];vals=[g['metrics'][key]for g in positive if g['metrics'][key]is not None]\n  gaps[key]=dict(value=None if len(positive)<2 or undefined else max(vals)-min(vals),undefinedGroups=undefined,comparedPositiveMassGroups=[g['group']for g in positive])\n return dict(overall=overall,groups=gm,unknownGroup=unknown,gaps=gaps,partitionMassResidual=overall['mass']-unknown['mass']-sum((g['metrics']['mass']for g in gm),F(0)))\ndef actual_model(M):\n raw=M['records'];cat=M['categoricalFeatures'];p=len(raw[0]['x']);train=[r for r in raw if r['role']=='train'];medians=[]\n for j in range(p):\n  if j in cat:medians.append(None);continue\n  values=sorted(F(r['x'][j])for r in train);n=len(values);medians.append(values[n//2]if n%2 else(values[n//2-1]+values[n//2])/2)\n def transform(r):return[F(v)if j in cat else F(int(F(v)>medians[j]))for j,v in enumerate(r['x'])]\n counts={}\n for r in train:\n  key=tuple(transform(r));n,s=counts.get(key,(0,0));counts[key]=(n+1,s+int(r['y']))\n probabilities={k:F(s+1,n+2)for k,(n,s)in counts.items()};fallback=F(sum(int(r['y'])for r in train)+1,len(train)+2);scored=[]\n for i,r in enumerate(raw):\n  eligible=r['role']!='excluded';z=transform(r)if eligible else None;key=None if z is None else tuple(z);score=None if not eligible else probabilities.get(key,fallback)\n  scored.append(dict(id=r['id'],index=i,role=r['role'],group=r['group'],y=None if r['y']is None else F(r['y']),score=score,w=F(1),eligible=eligible,transformedX=z,unseenCell=None if not eligible else key not in probabilities))\n return dict(medians=medians,cells=counts,probabilities=probabilities,fallback=fallback,rows=scored,trainIDs=[r['id']for r in train])\n\n\nimport csv,json,hashlib,argparse,datetime\nfrom pathlib import Path\ndef missing(v):return None if v in ['', '.',None]else v\ndef load_sources(folder):\n def read_csv(name):\n  with (folder/name).open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))\n wb=read_csv('actual64-country-four-indicators-original-2024.csv')\n codes=['NY.GDP.PCAP.KD','NY.GDP.MKTP.KD.ZG','FP.CPI.TOTL.ZG','SP.DYN.LE00.IN']\n lookup={(r['countryISO3'],r['indicatorID']):r for r in wb};country=[]\n for i,iso in enumerate(sorted({r['countryISO3']for r in wb}),1):\n  native=[lookup[iso,c]for c in codes];v=[missing(r['originalValueToken'])for r in native]\n  country.append(dict(id=iso+':2024',sourceRow=i,originalID=iso,x=v[:3],y=None if v[3]is None else str(int(F(v[3])>=80)),group=None if v[0]is None else str(int(F(v[0])>=25000)),nativeTarget=v[3],nativeSourceRows=';'.join(r['sourceRow']for r in native)))\n nls=read_csv('actual3613-NLS-original52-fields-groups-roles.csv');person=[]\n for r in nls:\n  y=missing(r['wage76']);person.append(dict(id='person:'+r['sourceRow'],sourceRow=int(r['sourceRow']),originalID=r['id'],x=[missing(r[k])for k in ['ed76','age76','nearc4']],y=None if y is None else str(int(F(y)>=500)),group=missing(r['black']),nativeTarget=y,nativeSourceRows=r['sourceRow']))\n ch=read_csv('actual3150-churn-original14-fields-groups-roles.csv');company=[]\n for r in ch:\n  company.append(dict(id='customer:'+r['sourceRow'],sourceRow=int(r['sourceRow']),originalID='',x=[missing(r[k])for k in ['Call  Failure','Complains','Subscription  Length','Seconds of Use']],y=missing(r['Churn']),group=missing(r['Tariff Plan']),nativeTarget=missing(r['Churn']),nativeSourceRows=r['sourceRow']))\n assert len(wb)==64 and len(country)==16 and len(nls)==3613 and len(ch)==3150\n assert [int(r['sourceRow'])for r in ch if r['Charge  Amount']=='10']==[474,2174,2274,2374,2674,2924,2974]\n models={}\n for kind,raw,cat,units in [('country',country,[],['constant2015USD/person','annualPercent','annualPercent']),('person',person,[2],['years','years','nativeCategory']),('company',company,[1],['count','nativeCategory','months','seconds'])]:\n  order=sorted(range(len(raw)),key=lambda i:(hashlib.sha256(('ML14-role|'+kind+'|'+raw[i]['id']).encode()).hexdigest(),i))\n  for rank,i in enumerate(order):\n   r=raw[i];r['plannedRole']='test'if rank%5==0 else'validation'if rank%5==1 else'train';r['eligible']=None not in r['x']+[r['y']];r['role']=r['plannedRole']if r['eligible']else'excluded';r['weight']='1'\n  models[kind]=dict(records=raw,categoricalFeatures=cat,featureUnits=units)\n assert sum(r['eligible']for r in person)==3017\n return models\n\ndef exact(v):return ''if v is None else str(v)\ndef approx(v):return ''if v is None else format(float(v),'.17g')\ndef scalar_fields(m,keys):\n out={}\n for k in keys:\n  out[k+'Exact']=exact(m[k]);out[k+'Approx']=approx(m[k])\n return out\nCOUNTS=['mass','positiveTargetMass','negativeTargetMass','predictedPositiveMass','predictedNegativeMass']\nRATES=['prevalence','selectionRate','accuracy','precision','negativePredictiveValue','TPR','FPR','TNR','FNR','F1','balancedAccuracy','Brier','BrierSum','totalCost','meanCost']\nSCENARIOS=[('equal',F(1),F(1)),('miss-five',F(1),F(5)),('alarm-five',F(5),F(1))]\ndef packed(v):\n if isinstance(v,F):return str(v)\n if isinstance(v,dict):return{str(k):packed(x)for k,x in v.items()}\n if isinstance(v,(tuple,list)):return[packed(x)for x in v]\n return v\ndef run_study(source,out):\n out.mkdir(parents=True,exist_ok=True);models=load_sources(source)\n tables={name:[]for name in ['predictions','lineage','fit-medians','fit-cells','validation-candidates','test-metrics','test-curves','calibration-bins','group-metrics','chart-points']}\n studies={};charts=[]\n def point(kind,chart,series,index,x,y,xunit='dimensionless',yunit='dimensionless',role='test',tag=''):\n  tables['chart-points'].append(dict(kind=kind,chart=chart,series=series,index=index,xExact=exact(x),xApprox=approx(x),yExact=exact(y),yApprox=approx(y),xUnit=xunit,yUnit=yunit,role=role,tag=tag))\n for kind,M in models.items():\n  fit=actual_model(M);rr=fit['rows'];native=M['records'];test=scoped(rr,'test');cv=curves(test);cal=calibrate(test,[F(0),F(1,5),F(2,5),F(3,5),F(4,5),F(1)]);scenarios=[]\n  for i,r in enumerate(rr):\n   n=native[i];reason=''if r['eligible']else'required-X-or-Y-missing'\n   tables['predictions'].append(dict(kind=kind,id=r['id'],sourceRow=n['sourceRow'],originalID=n['originalID'],plannedRole=n['plannedRole'],role=r['role'],group=''if r['group']is None else r['group'],eligible=int(r['eligible']),targetExact=exact(r['y']),probabilityExact=exact(r['score']),probabilityApprox=approx(r['score']),unseenCell=''if r['unseenCell']is None else int(r['unseenCell']),transformedX=''if r['transformedX']is None else'|'.join(map(str,r['transformedX'])),reason=reason))\n   tables['lineage'].append(dict(kind=kind,id=r['id'],sourceRow=n['sourceRow'],originalID=n['originalID'],nativeSourceRows=n['nativeSourceRows'],rawX='|'.join(''if x is None else x for x in n['x']),nativeTarget=''if n['nativeTarget']is None else n['nativeTarget'],derivedTarget=exact(r['y']),nativeGroup=''if n['group']is None else n['group'],plannedRole=n['plannedRole'],role=r['role'],eligible=int(r['eligible']),analyticalMass='1',reason=reason))\n  for j,v in enumerate(fit['medians']):tables['fit-medians'].append(dict(kind=kind,feature=j,categorical=int(j in M['categoricalFeatures']),fitRows=len(fit['trainIDs']),medianExact=exact(v),medianApprox=approx(v),unit=M['featureUnits'][j]))\n  for key,(mass,pos)in fit['cells'].items():tables['fit-cells'].append(dict(kind=kind,cell='|'.join(map(str,key)),trainingRows=mass,positiveRows=pos,probabilityExact=exact(fit['probabilities'][key]),probabilityApprox=approx(fit['probabilities'][key]),fallbackExact=exact(fit['fallback']),fallbackApprox=approx(fit['fallback'])))\n  for j,p in enumerate(cv['points']):\n   policy=p['policy'];tables['test-curves'].append(dict(kind=kind,point=j,policy=policy if isinstance(policy,str)else'threshold',thresholdExact=''if isinstance(policy,str)else exact(policy),thresholdApprox=''if isinstance(policy,str)else approx(policy),**scalar_fields(p,['TP','FP','FN','TN','TPR','FPR','precision','recall'])))\n   point(kind,'roc','ROC',j,p['FPR'],p['TPR']);point(kind,'pr','PR-observed',j,p['recall'],p['precision'])\n  for b in cal['bins']:\n   tables['calibration-bins'].append(dict(kind=kind,bin=b['index'],leftExact=str(F(b['index'],5)),rightExact=str(F(b['index']+1,5)),rightClosed=int(b['index']==4),rows=b['rows'],ids=';'.join(str(i)for i in b['ids']),**scalar_fields(b,['mass','meanPrediction','eventRate','gap','absoluteGap','scoreVariance','scoreTargetCovariance','withinBinCorrection'])))\n   point(kind,'reliability','Binary event rate',b['index'],b['meanPrediction'],b['eventRate'],tag='rows='+str(b['rows']))\n  for j,r in enumerate(test):\n   point(kind,'test-scores','Training-fitted probability',j,F(j+1),r['score'],'test-row position','probability',tag=r['id'])\n   point(kind,'test-scores','Observed Y',j,F(j+1),r['y'],'test-row position','binary target',tag=r['id'])\n  for name,fp,fn in SCENARIOS:\n   choice=choose(rr,{},(fp,fn));gm=groups(test,choice['selectedPolicy'],(fp,fn));scenarios.append(dict(name=name,costs=dict(falsePositive=fp,falseNegative=fn),selection=choice,groups=gm));ev=choice['evaluation']\n   for c in choice['candidates']:\n    policy=c['policy'];mm=c['metrics'];tables['validation-candidates'].append(dict(kind=kind,scenario=name,candidate=c['index'],selected=int(c['index']==choice['selectedIndex']),policy=policy if isinstance(policy,str)else'threshold',thresholdExact=''if isinstance(policy,str)else exact(policy),thresholdApprox=''if isinstance(policy,str)else approx(policy),feasible=int(c['feasible']),reasons=';'.join(c['reasons']),**{k+'Exact':str(v)for k,v in mm['confusion'].items()},**scalar_fields(mm,COUNTS+['TPR','FPR','precision','meanCost','totalCost'])))\n    point(kind,'validation-cost',name,c['index'],F(c['index']),mm['meanCost'],'candidate index','hypothetical cost units/mass','validation',tag=exact(policy))\n   mm={**ev,**ev['confusion'],**{k:cv[k]for k in ['ROC_AUC','averagePrecision','PRTrapezoidWithInitialPrecisionOne']},**{k:cal[k]for k in ['ECE','reliability','resolution','uncertainty','withinBinCorrection','BrierIdentityResidual']}}\n   for key in ['TP','FP','FN','TN']+COUNTS+RATES+['ROC_AUC','averagePrecision','PRTrapezoidWithInitialPrecisionOne','ECE','reliability','resolution','uncertainty','withinBinCorrection','BrierIdentityResidual']:\n    unit='rows'if key in ['TP','FP','FN','TN']+COUNTS else'hypothetical cost units'if key=='totalCost'else'hypothetical cost units/mass'if key=='meanCost'else'sum squared-probability loss'if key=='BrierSum'else'dimensionless'\n    tables['test-metrics'].append(dict(kind=kind,scenario=name,metric=key,valueExact=exact(mm[key]),valueApprox=approx(mm[key]),unit=unit))\n   allg=[('overall','all',gm['overall'])]+[('known',str(g['group']),g['metrics'])for g in gm['groups']]+[('unknown','',gm['unknownGroup'])]\n   for j,(typ,token,g)in enumerate(allg):\n    tables['group-metrics'].append(dict(kind=kind,scenario=name,groupType=typ,groupToken=token,retainedRows=g.get('retainedRows',sum((r['group']==token)if typ=='known'else(r['group']is None)if typ=='unknown'else True for r in test)),**{k+'Exact':str(v)for k,v in g['confusion'].items()},**scalar_fields(g,COUNTS+RATES)))\n    if typ=='known':point(kind,'group-TPR',name,j-1,F(j-1),g['TPR'],'declared group position','TPR',tag=token)\n  studies[kind]=dict(kind=kind,rows=len(native),eligibleRows=sum(r['eligible']for r in rr),trainingIDs=fit['trainIDs'],fitMedians=fit['medians'],fitCells=[dict(cell=list(k),mass=n,positive=s,probability=fit['probabilities'][k])for k,(n,s)in fit['cells'].items()],fallback=fit['fallback'],scenarios=scenarios,testCurves=cv,testCalibration=cal,rowsScored=rr)\n files=[]\n for name,rows in tables.items():\n  p=out/('computed-'+name+'.csv')\n  with p.open('w',encoding='utf8',newline='')as f:w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows)\n  files.append(dict(file=p.name,rows=len(rows),columns=len(rows[0]),bodyFields=len(rows)*len(rows[0]),sha256=hashlib.sha256(p.read_bytes()).hexdigest()))\n (out/'study.json').write_text(json.dumps(packed(studies),ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\n sourceFiles=[source/n for n in ['actual64-country-four-indicators-original-2024.csv','actual3613-NLS-original52-fields-groups-roles.csv','actual3150-churn-original14-fields-groups-roles.csv']]\n provenance=dict(chapter='ML-14',arithmetic='Python stdlib Fraction exact finite values from original decimal strings; binary64 valueApprox is display only.',inputs=[dict(file=p.name,sha256=hashlib.sha256(p.read_bytes()).hexdigest())for p in sourceFiles],priorEngineModelsScoresOrComputedFilesRead=False,roleRule=\"SHA256('ML14-role|'+kind+'|'+ID),rankmod5=0test/1validation/others train before eligibility\",costs='Hypothetical1/1,1/5,5/1; no causal intervention returns',files=files,observations={k:dict(sourceRows=v['rows'],eligibleRows=v['eligibleRows'],trainingRows=len(v['trainingIDs']))for k,v in studies.items()})\n (out/'provenance.json').write_text(json.dumps(provenance,ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\n print(json.dumps(dict(status='PASS standalone completed',files=len(files),bodyFields=sum(f['bodyFields']for f in files),observations=provenance['observations'])))\n\n# Fixed declared examples: full web budget/option validation is not reproduced.\nfrom html import escape\nimport textwrap\ndef validated_rows(raw):\n for r in raw:\n  assert F(str(r.get('weight','1')))>=0,'negative analytical mass'\n  assert r['score']is None or 0<=F(str(r['score']))<=1,'score outside zero/one'\n  assert r['y']is None or F(str(int(r['y']))if isinstance(r['y'],bool)else str(r['y']))in [0,1],'binary target required'\n return read(raw)\ndef serial(v):\n if isinstance(v,F):return dict(exactFraction=str(v),value=float(v))\n if isinstance(v,(list,tuple)):return[serial(x)for x in v]\n if isinstance(v,dict):return{k:serial(x)for k,x in v.items()}\n return v\ndef fixed_svg(path,points,title,xlabel,ylabel,legend):\n use=[p for p in points if p['xExact']!=''and p['yExact']!=''];xs=[float(F(p['xExact']))for p in use];ys=[float(F(p['yExact']))for p in use]\n xmin=min(xs,default=0);xmax=max(xs,default=1);ymin=min([0]+ys);ymax=max([0]+ys)\n if xmin==xmax:xmin-=.5;xmax+=.5\n if ymin==ymax:ymax=ymin+1\n X=lambda v:85+(float(v)-xmin)/(xmax-xmin)*480;Y=lambda v:278-(float(v)-ymin)/(ymax-ymin)*175\n s='<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"620\" height=\"360\" viewBox=\"0 0 620 360\"><rect width=\"620\" height=\"360\" fill=\"white\"/><g font-family=\"Arial, sans-serif\" font-size=\"13\" fill=\"#17324d\">'\n for i,line in enumerate(textwrap.wrap(title,width=65)):s+='<text x=\"25\" y=\"'+str(24+i*18)+'\">'+escape(line)+'</text>'\n colors=['#176b9b','#b85e18','#437e4d']\n for i,label in enumerate(legend):s+='<circle cx=\"'+str(30+i*250)+'\" cy=\"76\" r=\"4\" fill=\"'+colors[i%3]+'\"/><text x=\"'+str(42+i*250)+'\" y=\"80\">'+escape(label)+'</text>'\n s+='<path d=\"M85 98V278H575\" fill=\"none\" stroke=\"#52677d\"/><text text-anchor=\"middle\" x=\"325\" y=\"338\">'+escape(xlabel)+'</text><text text-anchor=\"middle\" transform=\"translate(21,190) rotate(-90)\">'+escape(ylabel)+'</text>'\n for i in range(5):\n  xx=xmin+(xmax-xmin)*i/4;yy=ymin+(ymax-ymin)*i/4;s+='<text text-anchor=\"middle\" x=\"'+format(X(xx),'.9g')+'\" y=\"305\">'+format(xx,'.4g')+'</text><text text-anchor=\"end\" x=\"77\" y=\"'+format(Y(yy)+4,'.9g')+'\">'+format(yy,'.4g')+'</text>'\n for p in use:s+='<circle cx=\"'+format(X(F(p['xExact'])),'.9g')+'\" cy=\"'+format(Y(F(p['yExact'])),'.9g')+'\" r=\"3\" fill=\"'+colors[p['series']%3]+'\"/>'\n path.write_text(s+'</g></svg>',encoding='utf8')\ndef fixed_run():\n ap=argparse.ArgumentParser();ap.add_argument('--out',type=Path,default=Path('results'));ap.add_argument('--data-dir',type=Path,default=Path(__file__).resolve().parent.parent/'ml14-sources');args=ap.parse_args();args.out.mkdir(parents=True,exist_ok=True)\n api=FIXED['api'];a=FIXED['args'];summary=[];points=[];xlabel='Declared index';ylabel='Value';legend=['Declared result']\n def metric(name,v,unit='dimensionless'):\n  q=None if v is None else v if isinstance(v,F)else F(v);summary.append(dict(metric=name,value='undefined'if q is None else format(float(q),'.9g'),exactValue=''if q is None else str(q),unit=unit,defined=int(q is not None)))\n def pt(i,x,y,ident='',series=0):\n  points.append(dict(series=series,index=i,xExact=''if x is None else str(F(x)),x='undefined'if x is None else format(float(x),'.9g'),yExact=''if y is None else str(F(y)),y='undefined'if y is None else format(float(y),'.9g'),id=str(ident)))\n if api=='realdata':\n  models=load_sources(args.data_dir);model=models[a['kind']];fit=actual_model(model);rr=fit['rows'];test=scoped(rr,'test');scenarios=[]\n  for name,fp,fn in SCENARIOS:\n   c=choose(rr,{},(fp,fn));scenarios.append(dict(name=name,selection=c));metric(name+'Threshold',c['selectedPolicy']);metric(name+'TestCost',c['evaluation']['meanCost'],'hypothetical cost units/mass')\n  cv=curves(test);cal=calibrate(test,[F(0),F(1,5),F(2,5),F(3,5),F(4,5),F(1)]);metric('testAUC',cv['ROC_AUC']);metric('testAP',cv['averagePrecision']);metric('testBrier',cal['Brier']);metric('eligibleRows',sum(r['eligible']for r in rr),'rows')\n  for i,r in enumerate(test):pt(i,i+1,r['score'],r['id'],0);pt(i,i+1,r['y'],r['id'],1)\n  full=dict(kind=a['kind'],fitMedians=fit['medians'],fitCells=[dict(cell=list(k),mass=n,positive=s,probability=fit['probabilities'][k])for k,(n,s)in fit['cells'].items()],rowsScored=rr,scenarios=scenarios,testCurves=cv,testCalibration=cal);xlabel='Test row, native order';ylabel='Y or probability';legend=['Training-fitted probability','Observed Y']\n else:\n  rr=validated_rows(a['rows']);role=a.get('role','all');frame=scoped(rr,role);cc=cost(a.get('costs'));t=policy(a.get('threshold','1/2'))\n  if api=='metrics':\n   full=metrics(frame,t,cc)\n   for k in ['mass','accuracy','precision','TPR','FPR','F1','Brier','meanCost']:metric(k,full[k],'mass'if k=='mass'else'hypothetical cost units/mass'if k=='meanCost'else'dimensionless')\n   metric('BayesThreshold',full['bayesThreshold'])\n   for i,k in enumerate(['TP','FP','FN','TN']):pt(i,i,full['confusion'][k],k)\n   xlabel='TP / FP / FN / TN positions';ylabel='Analytical mass'\n  elif api=='curves':\n   full=curves(frame)\n   for k in ['ROC_AUC','averagePrecision','PRTrapezoidWithInitialPrecisionOne']:metric(k,full[k])\n   for i,p in enumerate(full['points']):pt(i,p['FPR'],p['TPR'],str(p['policy']))\n   xlabel='False positive rate';ylabel='True positive rate';legend=['Observed ROC operating points']\n  elif api=='choose':\n   full=choose(rr,a,cc);metric('selectedIndex',full['selectedIndex'],'candidate index');metric('minimumCost',None if full['selectedValidation']is None else full['selectedValidation']['meanCost'],'hypothetical cost units/mass');metric('feasible',int(full['selectedIndex']is not None),'indicator')\n   for c in full['candidates']:pt(c['index'],c['index'],c['metrics']['meanCost'],str(c['policy']))\n   xlabel='Validation candidate';ylabel='Assumed cost / mass';legend=['Validation candidate costs']\n  elif api=='calibrate':\n   full=calibrate(frame,[F(str(e))for e in a.get('binEdges',['0','1/5','2/5','3/5','4/5','1'])])\n   for k in ['ECE','Brier','uncertainty','resolution','reliability','withinBinCorrection','BrierIdentityResidual']:metric(k,full[k])\n   for b in full['bins']:pt(b['index'],b['meanPrediction'],b['eventRate'],'bin:'+str(b['index']))\n   xlabel='Bin mean forecast';ylabel='Bin event rate';legend=['Binary-event reliability']\n  elif api=='groups':\n   full=groups(frame,t,cc);metric('overallTPR',full['overall']['TPR']);metric('TPRGap',full['gaps']['TPR']['value']);metric('precisionGap',full['gaps']['precision']['value']);metric('unknownMass',full['unknownGroup']['mass'],'mass');metric('partitionResidual',full['partitionMassResidual'],'mass')\n   for i,g in enumerate(full['groups']):pt(i,i,g['metrics']['TPR'],str(g['group']))\n   xlabel='Declared group position';ylabel='True positive rate';legend=['Known-group TPR']\n  else:raise ValueError('unknown fixed API')\n def csvout(name,rows):\n  with(args.out/name).open('w',encoding='utf8',newline='')as f:w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows)\n csvout('summary.csv',summary);csvout('plot-points.csv',points);fixed_svg(args.out/'plot.svg',points,FIXED['title'],xlabel,ylabel,legend)\n (args.out/'full.json').write_text(json.dumps(dict(api=api,variant=FIXED['variant'],input=FIXED['args'],arithmetic='Python standard-library Fraction, declared fixed example; full web validator/budgets not reproduced',result=serial(full)),ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\n print(json.dumps(dict(api=api,variant=FIXED['variant'],summaryMetrics=len(summary),plotSlots=len(points))))\n\nFIXED={'api': 'curves', 'variant': 'all-tied', 'args': {'rows': [{'id': 'a', 'score': '.5', 'y': 1, 'group': 'A'}, {'id': 'b', 'score': '.5', 'y': 1, 'group': 'A'}, {'id': 'c', 'score': '.5', 'y': 0, 'group': 'A'}, {'id': 'd', 'score': '.5', 'y': 0, 'group': 'B'}, {'id': 'e', 'score': '.5', 'y': 1, 'group': 'B'}, {'id': 'f', 'score': '.5', 'y': 0, 'group': 'B'}]}, 'title': 'All scores tied: half pair credit and prevalence AP'}\nif __name__=='__main__':fixed_run()\n",
        "input": {
          "rows": [
            {
              "id": "a",
              "score": ".5",
              "y": 1,
              "group": "A"
            },
            {
              "id": "b",
              "score": ".5",
              "y": 1,
              "group": "A"
            },
            {
              "id": "c",
              "score": ".5",
              "y": 0,
              "group": "A"
            },
            {
              "id": "d",
              "score": ".5",
              "y": 0,
              "group": "B"
            },
            {
              "id": "e",
              "score": ".5",
              "y": 1,
              "group": "B"
            },
            {
              "id": "f",
              "score": ".5",
              "y": 0,
              "group": "B"
            }
          ]
        },
        "inputFiles": [],
        "returnCode": 0,
        "expectedFailure": false,
        "stdout": "{\"api\": \"curves\", \"variant\": \"all-tied\", \"summaryMetrics\": 3, \"plotSlots\": 2}\n",
        "stderr": "",
        "summary": {
          "ROC_AUC": "0.5",
          "averagePrecision": "0.5",
          "PRTrapezoidWithInitialPrecisionOne": "0.75"
        },
        "summaryRows": [
          {
            "metric": "ROC_AUC",
            "value": "0.5",
            "exactValue": "1/2",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "averagePrecision",
            "value": "0.5",
            "exactValue": "1/2",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "PRTrapezoidWithInitialPrecisionOne",
            "value": "0.75",
            "exactValue": "3/4",
            "unit": "dimensionless",
            "defined": "1"
          }
        ],
        "plotPoints": [
          {
            "series": "0",
            "index": "0",
            "xExact": "0",
            "x": "0",
            "yExact": "0",
            "y": "0",
            "id": "always-negative"
          },
          {
            "series": "0",
            "index": "1",
            "xExact": "1",
            "x": "1",
            "yExact": "1",
            "y": "1",
            "id": "1/2"
          }
        ],
        "plotFile": "ml14-fixed-results/curves-all-tied-python/plot.svg",
        "plotSHA256": "6bd15c7b1622da1c4f7de733bcc2e4fc2019ec28316e3146e04f5ff157b7d106",
        "files": [
          {
            "file": "ml14-fixed-results/curves-all-tied-python/full.json",
            "sha256": "3472b919727a6c1bb506439b2c1d49b91941c14254b876ece5970254d46d8e4e",
            "bytes": 2905
          },
          {
            "file": "ml14-fixed-results/curves-all-tied-python/plot-points.csv",
            "sha256": "750a8938cdbee7799df7b77d4a24f2d127849e9a8b0e0fa895d537b82d696664",
            "bytes": 81
          },
          {
            "file": "ml14-fixed-results/curves-all-tied-python/plot.svg",
            "sha256": "6bd15c7b1622da1c4f7de733bcc2e4fc2019ec28316e3146e04f5ff157b7d106",
            "bytes": 1213
          },
          {
            "file": "ml14-fixed-results/curves-all-tied-python/summary.csv",
            "sha256": "f5e3ca1c95b5a2ffd80cdbd13dfd2021176affc0805415c6f1b21d989d45db5f",
            "bytes": 174
          }
        ],
        "scope": "Actually executed standalone fixed example, Python exact Fraction versus base-R binary64. Approximate R residuals retained; not universal exact arithmetic/web validation/native UI. Source programs read factual3CSV only."
      }
    },
    "r": {
      "six-cards": {
        "api": "curves",
        "variant": "six-cards",
        "language": "r",
        "title": "Tied-score six-card ROC, AP and labeled PR trapezoid",
        "codeFile": "ml14-code/curves-six-cards.R",
        "codeSHA256": "68118a572f5778608e25db5ce89022c9e9328aa83eb4964aafe0d202bf65a160",
        "code": "# ML14 standalone public counterpart, base R only.\n# Inputs are only the three factual CSVs; derived columns/previous model answers unused.\n# Binary64 arithmetic, not arbitrary-precision Fraction. At numerical cost ties\n# within 1e-12 retain the earliest candidate. Exact claims belong to Python/web.\n# SHA256 infrastructure below is reused verbatim from the previous public study.\nargs<-commandArgs(trailingOnly=TRUE);filearg<-grep(\"^--file=\",commandArgs(),value=TRUE)\nhere<-if(dir.exists(\"ml14-sources\"))getwd()else if(length(filearg))dirname(normalizePath(sub(\"^--file=\",\"\",filearg[1])))else getwd()\noption<-function(key,default){i<-match(key,args);if(is.na(i))default else args[i+1]}\nsourceDir<-option(\"--source\",file.path(here,\"ml14-sources\"));outDir<-option(\"--out\",file.path(getwd(),\"ml14-r-results\"));dir.create(outDir,recursive=TRUE,showWarnings=FALSE)\nnum<-function(x){x[x%in%c(\"\",\".\")]<-NA_character_;as.numeric(x)}\nfmt<-function(x)ifelse(is.na(x),\"\",sprintf(\"%.17g\",x))\nratio<-function(a,b)if(b==0)NA_real_ else a/b\nreadnative<-function(name)read.csv(file.path(sourceDir,name),check.names=FALSE,colClasses=\"character\",na.strings=character(),stringsAsFactors=FALSE)\n# Vectorized SHA256 for the short ASCII keys used in this study.\n# Unsigned words use exact integer-valued doubles; bit operations use safe\n# 16-bit halves, avoiding R's reserved signed-INT_MIN/NA representation.\nMOD<-2^32\nxor32<-function(a,b) as.double(bitwXor(as.integer(floor(a/65536)),as.integer(floor(b/65536))))*65536+as.double(bitwXor(as.integer(a%%65536),as.integer(b%%65536)))\nand32<-function(a,b) as.double(bitwAnd(as.integer(floor(a/65536)),as.integer(floor(b/65536))))*65536+as.double(bitwAnd(as.integer(a%%65536),as.integer(b%%65536)))\nrot<-function(x,n) floor(x/2^n)+(x%%2^n)*2^(32-n)\nxor3<-function(a,b,c) xor32(xor32(a,b),c)\nK<-c(0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5,0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967,0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070,0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3,0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2)\nsha256<-function(strings) {\n n<-length(strings);bytes<-matrix(0,n,64)\n for(i in seq_len(n)) {v<-utf8ToInt(strings[i]);stopifnot(length(v)<56,all(v<128));if(length(v)) bytes[i,seq_along(v)]<-v;bytes[i,length(v)+1]<-128;bits<-length(v)*8;bytes[i,61:64]<-c(floor(bits/2^24)%%256,floor(bits/2^16)%%256,floor(bits/256)%%256,bits%%256)}\n w<-matrix(0,n,64)\n for(j in 1:16) {b<-4*(j-1)+1;w[,j]<-bytes[,b]*2^24+bytes[,b+1]*2^16+bytes[,b+2]*256+bytes[,b+3]}\n for(j in 17:64) {s0<-xor3(rot(w[,j-15],7),rot(w[,j-15],18),floor(w[,j-15]/8));s1<-xor3(rot(w[,j-2],17),rot(w[,j-2],19),floor(w[,j-2]/1024));w[,j]<-(w[,j-16]+s0+w[,j-7]+s1)%%MOD}\n init<-c(0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19)\n state<-lapply(init,function(v) rep(v,n));a<-state[[1]];b<-state[[2]];c<-state[[3]];d<-state[[4]];e<-state[[5]];f<-state[[6]];g<-state[[7]];h<-state[[8]]\n for(j in 1:64) {S1<-xor3(rot(e,6),rot(e,11),rot(e,25));ch<-xor32(and32(e,f),and32(MOD-1-e,g));t1<-(h+S1+ch+K[j]+w[,j])%%MOD;S0<-xor3(rot(a,2),rot(a,13),rot(a,22));maj<-xor3(and32(a,b),and32(a,c),and32(b,c));t2<-(S0+maj)%%MOD;h<-g;g<-f;f<-e;e<-(d+t1)%%MOD;d<-c;c<-b;b<-a;a<-(t1+t2)%%MOD}\n end<-list(a,b,c,d,e,f,g,h);hex<-lapply(1:8,function(j){v<-(end[[j]]+init[j])%%MOD;paste0(sprintf(\"%04x\",as.integer(floor(v/65536))),sprintf(\"%04x\",as.integer(v%%65536)))})\n do.call(paste0,hex)\n}\nstopifnot(identical(sha256(c(\"abc\",\"\")),c(\"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad\",\"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855\")))\n\nloadData<-function(){\n wb<-readnative(\"actual64-country-four-indicators-original-2024.csv\");codes<-c(\"NY.GDP.PCAP.KD\",\"NY.GDP.MKTP.KD.ZG\",\"FP.CPI.TOTL.ZG\",\"SP.DYN.LE00.IN\");iso<-sort(unique(wb$countryISO3));stopifnot(nrow(wb)==64,length(iso)==16)\n tokens<-t(vapply(iso,function(s)wb$originalValueToken[match(paste(s,codes),paste(wb$countryISO3,wb$indicatorID))],character(4)));vals<-matrix(num(as.vector(tokens)),nrow=nrow(tokens))\n country<-list(id=paste0(iso,\":2024\"),sourceRow=1:16,originalID=iso,x=vals[,1:3,drop=FALSE],rawX=tokens[,1:3,drop=FALSE],nativeTarget=tokens[,4],y=as.integer(vals[,4]>=80),group=ifelse(is.na(vals[,1]),NA_character_,as.character(as.integer(vals[,1]>=25000))),lineage=vapply(iso,function(s)paste(wb$sourceRow[match(paste(s,codes),paste(wb$countryISO3,wb$indicatorID))],collapse=\";\"),character(1)),cat=integer(),units=c(\"constant2015USD/person\",\"annualPercent\",\"annualPercent\"))\n nls<-readnative(\"actual3613-NLS-original52-fields-groups-roles.csv\");raw<-cbind(nls$ed76,nls$age76,nls$nearc4)\n person<-list(id=paste0(\"person:\",nls$sourceRow),sourceRow=as.integer(nls$sourceRow),originalID=nls$id,x=matrix(num(as.vector(raw)),nrow=nrow(raw)),rawX=raw,nativeTarget=nls$wage76,y=as.integer(num(nls$wage76)>=500),group=ifelse(nls$black%in%c(\"\",\".\"),NA_character_,nls$black),lineage=nls$sourceRow,cat=2L,units=c(\"years\",\"years\",\"nativeCategory\"))\n ch<-readnative(\"actual3150-churn-original14-fields-groups-roles.csv\");raw<-cbind(ch[[\"Call  Failure\"]],ch$Complains,ch[[\"Subscription  Length\"]],ch[[\"Seconds of Use\"]])\n company<-list(id=paste0(\"customer:\",ch$sourceRow),sourceRow=as.integer(ch$sourceRow),originalID=rep(\"\",nrow(ch)),x=matrix(num(as.vector(raw)),nrow=nrow(raw)),rawX=raw,nativeTarget=ch$Churn,y=as.integer(ch$Churn),group=ifelse(ch[[\"Tariff Plan\"]]%in%c(\"\",\".\"),NA_character_,ch[[\"Tariff Plan\"]]),lineage=ch$sourceRow,cat=1L,units=c(\"count\",\"nativeCategory\",\"months\",\"seconds\"))\n stopifnot(nrow(nls)==3613,nrow(ch)==3150,identical(as.integer(ch$sourceRow[ch[[\"Charge  Amount\"]]==\"10\"]),c(474L,2174L,2274L,2374L,2674L,2924L,2974L)))\n result<-list(country=country,person=person,company=company)\n for(k in names(result)){d<-result[[k]];n<-length(d$id);d$eligible<-!is.na(d$y)&rowSums(is.na(d$x))==0;hash<-sha256(paste0(\"ML14-role|\",k,\"|\",d$id));rank<-integer(n);rank[order(hash,seq_len(n))]<-seq_len(n)-1L;d$plannedRole<-ifelse(rank%%5==0,\"test\",ifelse(rank%%5==1,\"validation\",\"train\"));d$role<-ifelse(d$eligible,d$plannedRole,\"excluded\");result[[k]]<-d}\n stopifnot(sum(result$person$eligible)==3017);result\n}\nfitmodel<-function(d){\n ids<-which(d$role==\"train\");p<-ncol(d$x);m<-vapply(seq_len(p),function(j)if((j-1)%in%d$cat)NA_real_ else median(d$x[ids,j]),numeric(1));z<-d$x\n for(j in seq_len(p))if(!((j-1)%in%d$cat))z[,j]<-as.numeric(z[,j]>m[j])\n keys<-apply(z,1,function(v)paste(fmt(v),collapse=\"|\"));lev<-unique(keys[ids]);mass<-vapply(lev,function(k)sum(keys[ids]==k),integer(1));positive<-vapply(lev,function(k)sum(d$y[ids][keys[ids]==k]),integer(1));prob<-(positive+1)/(mass+2);fallback<-(sum(d$y[ids])+1)/(length(ids)+2);pred<-prob[match(keys,lev)];unseen<-is.na(pred);pred[unseen]<-fallback;pred[!d$eligible]<-NA_real_;unseen[!d$eligible]<-NA\n list(ids=ids,medians=m,z=z,keys=keys,lev=lev,mass=mass,positive=positive,prob=prob,fallback=fallback,pred=pred,unseen=unseen)\n}\nmeasure<-function(d,p,ids,t=.5,cost=c(1,1)){\n use<-ids[d$eligible[ids]&!is.na(p[ids])];y<-d$y[use];a<-if(is.character(t))rep(t==\"always-positive\",length(use))else p[use]>=t\n TP<-sum(a&y==1);FP<-sum(a&y==0);FN<-sum(!a&y==1);TN<-sum(!a&y==0);P<-TP+FN;N<-FP+TN;W<-P+N;PP<-TP+FP;PN<-TN+FN;TPR<-ratio(TP,P);TNR<-ratio(TN,N);bs<-sum((p[use]-y)^2);tc<-FP*cost[1]+FN*cost[2]\n list(TP=TP,FP=FP,FN=FN,TN=TN,mass=W,positiveTargetMass=P,negativeTargetMass=N,predictedPositiveMass=PP,predictedNegativeMass=PN,prevalence=ratio(P,W),selectionRate=ratio(PP,W),accuracy=ratio(TP+TN,W),precision=ratio(TP,PP),negativePredictiveValue=ratio(TN,PN),TPR=TPR,FPR=ratio(FP,N),TNR=TNR,FNR=ratio(FN,P),F1=ratio(2*TP,2*TP+FP+FN),balancedAccuracy=if(is.na(TPR)||is.na(TNR))NA_real_ else(TPR+TNR)/2,Brier=ratio(bs,W),BrierSum=bs,totalCost=tc,meanCost=ratio(tc,W))\n}\ncurves<-function(d,p,ids){\n use<-ids[d$eligible[ids]&!is.na(p[ids])];scores<-sort(unique(p[use]),decreasing=TRUE);policies<-c(list(\"always-negative\"),as.list(scores));points<-lapply(policies,function(t){m<-measure(d,p,ids,t);c(list(policy=t),m[c(\"TP\",\"FP\",\"FN\",\"TN\",\"TPR\",\"FPR\",\"precision\")],list(recall=m$TPR))})\n pos<-use[d$y[use]==1];neg<-use[d$y[use]==0];U<-0;for(i in pos)U<-U+sum(p[i]>p[neg])+.5*sum(p[i]==p[neg])\n AP<-0;trap<-0;lastR<-0;lastP<-1\n if(length(pos)&&length(scores))for(j in seq_along(scores)){z<-points[[j+1]];AP<-AP+(z$recall-lastR)*z$precision;trap<-trap+(z$recall-lastR)*(z$precision+lastP)/2;lastR<-z$recall;lastP<-z$precision}\n list(points=points,ROC_AUC=ratio(U,length(pos)*length(neg)),averagePrecision=if(length(pos))AP else NA_real_,PRTrapezoidWithInitialPrecisionOne=if(length(pos))trap else NA_real_)\n}\ncalibrate<-function(d,p,ids){\n use<-ids[d$eligible[ids]&!is.na(p[ids])];W<-length(use);pi<-if(W)mean(d$y[use])else NA_real_;bins<-list();ECE<-rel<-res<-correction<-0\n whichbin<-findInterval(p[use],seq(0,1,.2),rightmost.closed=TRUE,all.inside=TRUE)\n for(b in 1:5){rr<-use[whichbin==b];w<-length(rr);mp<-if(w)mean(p[rr])else NA_real_;o<-if(w)mean(d$y[rr])else NA_real_;variance<-if(w)mean((p[rr]-mp)^2)else NA_real_;covariance<-if(w)mean((p[rr]-mp)*(d$y[rr]-o))else NA_real_;bc<-variance-2*covariance;gap<-mp-o\n  bins[[b]]<-list(mass=w,meanPrediction=mp,eventRate=o,gap=gap,absoluteGap=abs(gap),scoreVariance=variance,scoreTargetCovariance=covariance,withinBinCorrection=bc,rows=w,ids=d$id[rr])\n  if(w){share<-w/W;ECE<-ECE+share*abs(gap);rel<-rel+share*gap^2;res<-res+share*(o-pi)^2;correction<-correction+share*bc}\n };bs<-if(W)mean((p[use]-d$y[use])^2)else NA_real_;unc<-pi*(1-pi)\n list(bins=bins,ECE=if(W)ECE else NA_real_,Brier=bs,reliability=if(W)rel else NA_real_,resolution=if(W)res else NA_real_,uncertainty=unc,withinBinCorrection=if(W)correction else NA_real_,BrierIdentityResidual=bs-(unc-res+rel+correction))\n}\ncounts<-c(\"mass\",\"positiveTargetMass\",\"negativeTargetMass\",\"predictedPositiveMass\",\"predictedNegativeMass\");rates<-c(\"prevalence\",\"selectionRate\",\"accuracy\",\"precision\",\"negativePredictiveValue\",\"TPR\",\"FPR\",\"TNR\",\"FNR\",\"F1\",\"balancedAccuracy\",\"Brier\",\"BrierSum\",\"totalCost\",\"meanCost\")\ntables<-setNames(lapply(1:10,function(i)list()),c(\"predictions\",\"lineage\",\"fit-medians\",\"fit-cells\",\"validation-candidates\",\"test-metrics\",\"test-curves\",\"calibration-bins\",\"group-metrics\",\"chart-points\"))\nadd<-function(name,row)tables[[name]][[length(tables[[name]])+1L]]<<-row\nscalars<-function(m,keys){out<-list();for(k in keys){out[[paste0(k,\"Exact\")]]<-\"\";out[[paste0(k,\"Approx\")]]<-fmt(m[[k]])};out}\ntagrow<-function(kind,...)c(list(kind=kind),list(...))\npoint<-function(kind,chart,series,index,x,y,xunit=\"dimensionless\",yunit=\"dimensionless\",role=\"test\",tag=\"\"){add(\"chart-points\",tagrow(kind,chart=chart,series=series,index=index,xExact=\"\",xApprox=fmt(x),yExact=\"\",yApprox=fmt(y),xUnit=xunit,yUnit=yunit,role=role,tag=tag))}\nstudy<-function(kind,d){\n f<-fitmodel(d);n<-length(d$id);train<-which(d$role==\"train\");validation<-which(d$role==\"validation\");test<-which(d$role==\"test\");p<-f$pred;cv<-curves(d,p,test);cal<-calibrate(d,p,test)\n for(i in seq_len(n)){\n  reason<-if(d$eligible[i])\"\"else\"required-X-or-Y-missing\";transformed<-if(d$eligible[i])paste(fmt(f$z[i,]),collapse=\"|\")else\"\"\n  add(\"predictions\",tagrow(kind,id=d$id[i],sourceRow=d$sourceRow[i],originalID=d$originalID[i],plannedRole=d$plannedRole[i],role=d$role[i],group=ifelse(is.na(d$group[i]),\"\",d$group[i]),eligible=as.integer(d$eligible[i]),targetExact=fmt(d$y[i]),probabilityExact=\"\",probabilityApprox=fmt(p[i]),unseenCell=ifelse(is.na(f$unseen[i]),\"\",as.character(as.integer(f$unseen[i]))),transformedX=transformed,reason=reason))\n  raw<-d$rawX[i,];raw[raw%in%c(\"\",\".\")]<-\"\";nativeY<-d$nativeTarget[i];if(nativeY%in%c(\"\",\".\"))nativeY<-\"\"\n  add(\"lineage\",tagrow(kind,id=d$id[i],sourceRow=d$sourceRow[i],originalID=d$originalID[i],nativeSourceRows=d$lineage[i],rawX=paste(raw,collapse=\"|\"),nativeTarget=nativeY,derivedTarget=fmt(d$y[i]),nativeGroup=ifelse(is.na(d$group[i]),\"\",d$group[i]),plannedRole=d$plannedRole[i],role=d$role[i],eligible=as.integer(d$eligible[i]),analyticalMass=\"1\",reason=reason))\n }\n for(j in seq_len(ncol(d$x)))add(\"fit-medians\",tagrow(kind,feature=j-1,categorical=as.integer((j-1)%in%d$cat),fitRows=length(train),medianExact=\"\",medianApprox=fmt(f$medians[j]),unit=d$units[j]))\n for(j in seq_along(f$lev))add(\"fit-cells\",tagrow(kind,cell=f$lev[j],trainingRows=f$mass[j],positiveRows=f$positive[j],probabilityExact=\"\",probabilityApprox=fmt(f$prob[j]),fallbackExact=\"\",fallbackApprox=fmt(f$fallback)))\n for(j in seq_along(cv$points)){\n  z<-cv$points[[j]];t<-z$policy;add(\"test-curves\",c(tagrow(kind,point=j-1,policy=if(is.character(t))t else\"threshold\",thresholdExact=\"\",thresholdApprox=if(is.character(t))\"\"else fmt(t)),scalars(z,c(\"TP\",\"FP\",\"FN\",\"TN\",\"TPR\",\"FPR\",\"precision\",\"recall\"))))\n  point(kind,\"roc\",\"ROC\",j-1,z$FPR,z$TPR);point(kind,\"pr\",\"PR-observed\",j-1,z$recall,z$precision)\n }\n for(b in 1:5){z<-cal$bins[[b]];add(\"calibration-bins\",c(tagrow(kind,bin=b-1,leftExact=c(\"0\",\"1/5\",\"2/5\",\"3/5\",\"4/5\")[b],rightExact=c(\"1/5\",\"2/5\",\"3/5\",\"4/5\",\"1\")[b],rightClosed=as.integer(b==5),rows=z$rows,ids=paste(z$ids,collapse=\";\")),scalars(z,c(\"mass\",\"meanPrediction\",\"eventRate\",\"gap\",\"absoluteGap\",\"scoreVariance\",\"scoreTargetCovariance\",\"withinBinCorrection\"))));point(kind,\"reliability\",\"Binary event rate\",b-1,z$meanPrediction,z$eventRate,tag=paste0(\"rows=\",z$rows))}\n for(j in seq_along(test)){i<-test[j];point(kind,\"test-scores\",\"Training-fitted probability\",j-1,j,p[i],\"test-row position\",\"probability\",tag=d$id[i]);point(kind,\"test-scores\",\"Observed Y\",j-1,j,d$y[i],\"test-row position\",\"binary target\",tag=d$id[i])}\n scenarioNames<-c(\"equal\",\"miss-five\",\"alarm-five\");costs<-list(c(1,1),c(1,5),c(5,1))\n for(s in 1:3){name<-scenarioNames[s];cost<-costs[[s]];grid<-c(list(\"always-negative\"),as.list(sort(unique(p[validation]),decreasing=TRUE)));candidates<-lapply(grid,function(t)measure(d,p,validation,t,cost));values<-vapply(candidates,function(m)m$meanCost,numeric(1));best<-which(values<=min(values)+1e-12)[1];chosen<-grid[[best]];ev<-measure(d,p,test,chosen,cost)\n  for(j in seq_along(grid)){t<-grid[[j]];m<-candidates[[j]];cell<-setNames(lapply(c(\"TP\",\"FP\",\"FN\",\"TN\"),function(k)fmt(m[[k]])),paste0(c(\"TP\",\"FP\",\"FN\",\"TN\"),\"Exact\"));add(\"validation-candidates\",c(tagrow(kind,scenario=name,candidate=j-1,selected=as.integer(j==best),policy=if(is.character(t))t else\"threshold\",thresholdExact=\"\",thresholdApprox=if(is.character(t))\"\"else fmt(t),feasible=1,reasons=\"\"),cell,scalars(m,c(counts,\"TPR\",\"FPR\",\"precision\",\"meanCost\",\"totalCost\"))));point(kind,\"validation-cost\",name,j-1,j-1,m$meanCost,\"candidate index\",\"hypothetical cost units/mass\",\"validation\",if(is.character(t))t else fmt(t))}\n  m<-c(ev,cv[c(\"ROC_AUC\",\"averagePrecision\",\"PRTrapezoidWithInitialPrecisionOne\")],cal[c(\"ECE\",\"reliability\",\"resolution\",\"uncertainty\",\"withinBinCorrection\",\"BrierIdentityResidual\")])\n  for(k in c(\"TP\",\"FP\",\"FN\",\"TN\",counts,rates,\"ROC_AUC\",\"averagePrecision\",\"PRTrapezoidWithInitialPrecisionOne\",\"ECE\",\"reliability\",\"resolution\",\"uncertainty\",\"withinBinCorrection\",\"BrierIdentityResidual\")){\n   unit<-if(k%in%c(\"TP\",\"FP\",\"FN\",\"TN\",counts))\"rows\"else if(k==\"totalCost\")\"hypothetical cost units\"else if(k==\"meanCost\")\"hypothetical cost units/mass\"else if(k==\"BrierSum\")\"sum squared-probability loss\"else\"dimensionless\"\n   add(\"test-metrics\",tagrow(kind,scenario=name,metric=k,valueExact=\"\",valueApprox=fmt(m[[k]]),unit=unit))\n  }\n  lev<-unique(d$group[test][!is.na(d$group[test])]);sets<-c(list(test),lapply(lev,function(g)test[!is.na(d$group[test])&d$group[test]==g]),list(test[is.na(d$group[test])]))\n  types<-c(\"overall\",rep(\"known\",length(lev)),\"unknown\");tokens<-c(\"all\",lev,\"\")\n  for(j in seq_along(sets)){ids<-sets[[j]];m<-measure(d,p,ids,chosen,cost);cell<-setNames(lapply(c(\"TP\",\"FP\",\"FN\",\"TN\"),function(k)fmt(m[[k]])),paste0(c(\"TP\",\"FP\",\"FN\",\"TN\"),\"Exact\"));add(\"group-metrics\",c(tagrow(kind,scenario=name,groupType=types[j],groupToken=tokens[j],retainedRows=length(ids)),cell,scalars(m,c(counts,rates))));if(types[j]==\"known\")point(kind,\"group-TPR\",name,j-2,j-2,m$TPR,\"declared group position\",\"TPR\",tag=tokens[j])}\n }\n invisible(NULL)\n}\n\n# Fixed finite inputs only; not the complete web input/budget validator.\nqnum<-function(v){if(is.null(v))return(NA_real_);if(is.logical(v))return(as.numeric(v));s<-as.character(v);if(grepl(\"/\",s,fixed=TRUE)){a<-strsplit(s,\"/\",fixed=TRUE)[[1]];return(as.numeric(a[1])/as.numeric(a[2]))};as.numeric(s)}\nrowsG<-function(raw){\n n<-length(raw);get<-function(r,k,default=NULL)if(is.null(r[[k]]))default else r[[k]]\n id<-vapply(raw,function(r)as.character(r$id),character(1));p<-vapply(raw,function(r)qnum(r$score),numeric(1));y<-vapply(raw,function(r)qnum(r$y),numeric(1));w<-vapply(raw,function(r)qnum(get(r,\"weight\",\"1\")),numeric(1));role<-vapply(raw,function(r)get(r,\"role\",\"evaluation\"),character(1));group<-vapply(raw,function(r)as.character(get(r,\"group\",NA_character_)),character(1))\n stopifnot(all(w>=0),all(is.na(p)|(p>=0&p<=1)),all(is.na(y)|y%in%c(0,1)),!anyDuplicated(id));list(id=id,p=p,y=y,w=w,role=role,group=group,eligible=!is.na(p)&!is.na(y)&w>0&role!=\"excluded\")\n}\nscopeG<-function(d,role=\"all\")if(role==\"all\")seq_along(d$id)else which(d$role==role)\nmetricsG<-function(d,ids,t=.5,cost=c(1,1)){\n use<-ids[d$eligible[ids]];p<-d$p[use];y<-d$y[use];w<-d$w[use];a<-if(is.character(t))rep(t==\"always-positive\",length(use))else p>=t\n TP<-sum(w[a&y==1]);FP<-sum(w[a&y==0]);FN<-sum(w[!a&y==1]);TN<-sum(w[!a&y==0]);P<-TP+FN;N<-FP+TN;W<-P+N;PP<-TP+FP;PN<-TN+FN;TPR<-ratio(TP,P);TNR<-ratio(TN,N);bs<-sum(w*(p-y)^2);tc<-FP*cost[1]+FN*cost[2]\n list(confusion=list(TP=TP,FP=FP,FN=FN,TN=TN),mass=W,positiveTargetMass=P,negativeTargetMass=N,predictedPositiveMass=PP,predictedNegativeMass=PN,prevalence=ratio(P,W),selectionRate=ratio(PP,W),accuracy=ratio(TP+TN,W),precision=ratio(TP,PP),negativePredictiveValue=ratio(TN,PN),TPR=TPR,FPR=ratio(FP,N),TNR=TNR,FNR=ratio(FN,P),F1=ratio(2*TP,2*TP+FP+FN),balancedAccuracy=if(is.na(TPR)||is.na(TNR))NA_real_ else(TPR+TNR)/2,Brier=ratio(bs,W),BrierSum=bs,totalCost=tc,meanCost=ratio(tc,W),bayesThreshold=ratio(cost[1],sum(cost)))\n}\ncurvesG<-function(d,ids){\n use<-ids[d$eligible[ids]];grid<-c(list(\"always-negative\"),as.list(sort(unique(d$p[use]),decreasing=TRUE)));points<-lapply(grid,function(t){m<-metricsG(d,ids,t);c(list(policy=t),m$confusion,m[c(\"TPR\",\"FPR\",\"precision\")],list(recall=m$TPR))});pos<-use[d$y[use]==1];neg<-use[d$y[use]==0];P<-sum(d$w[pos]);N<-sum(d$w[neg]);U<-0\n for(i in pos)U<-U+d$w[i]*sum(d$w[neg]*((d$p[i]>d$p[neg])+.5*(d$p[i]==d$p[neg])))\n AP<-trap<-lastR<-0;lastP<-1\n if(P&&length(grid)>1)for(j in 2:length(grid)){z<-points[[j]];AP<-AP+(z$recall-lastR)*z$precision;trap<-trap+(z$recall-lastR)*(z$precision+lastP)/2;lastR<-z$recall;lastP<-z$precision}\n list(points=points,ROC_AUC=ratio(U,P*N),averagePrecision=if(P)AP else NA_real_,PRTrapezoidWithInitialPrecisionOne=if(P)trap else NA_real_)\n}\nchooseG<-function(d,a,cost){\n role<-if(is.null(a$selectionRole))\"validation\"else a$selectionRole;er<-if(is.null(a$evaluationRole))\"test\"else a$evaluationRole;ids<-scopeG(d,role);use<-ids[d$eligible[ids]];stopifnot(length(use)>0);grid<-if(is.null(a$thresholds))c(list(\"always-negative\"),as.list(sort(unique(d$p[use]),decreasing=TRUE)))else lapply(a$thresholds,function(t)if(t%in%c(\"always-negative\",\"always-positive\"))t else qnum(t))\n candidates<-lapply(seq_along(grid),function(j){m<-metricsG(d,ids,grid[[j]],cost);feasible<-TRUE;if(!is.null(a$minTPR))feasible<-feasible&&!is.na(m$TPR)&&m$TPR>=qnum(a$minTPR);if(!is.null(a$maxFPR))feasible<-feasible&&!is.na(m$FPR)&&m$FPR<=qnum(a$maxFPR);list(index=j-1,policy=grid[[j]],metrics=m,feasible=feasible)})\n good<-which(vapply(candidates,function(c)c$feasible,logical(1)));best<-NA_integer_;if(length(good)){v<-vapply(candidates[good],function(c)c$metrics$meanCost,numeric(1));best<-good[which(v<=min(v)+1e-12)[1]]}\n list(selectedIndex=if(is.na(best))NA_integer_ else best-1,selectedPolicy=if(is.na(best))NULL else grid[[best]],selectedValidation=if(is.na(best))NULL else candidates[[best]]$metrics,candidates=candidates,evaluation=if(is.na(best)||er==\"none\")NULL else metricsG(d,scopeG(d,er),grid[[best]],cost))\n}\ncalibrateG<-function(d,ids,edges){\n use<-ids[d$eligible[ids]];W<-sum(d$w[use]);pi<-ratio(sum(d$w[use]*d$y[use]),W);bins<-list();ECE<-rel<-res<-correction<-0;assign<-findInterval(d$p[use],edges,rightmost.closed=TRUE,all.inside=TRUE)\n for(b in seq_len(length(edges)-1)){rr<-use[assign==b];w<-sum(d$w[rr]);mp<-ratio(sum(d$w[rr]*d$p[rr]),w);o<-ratio(sum(d$w[rr]*d$y[rr]),w);variance<-if(w)sum(d$w[rr]*(d$p[rr]-mp)^2)/w else NA_real_;covariance<-if(w)sum(d$w[rr]*(d$p[rr]-mp)*(d$y[rr]-o))/w else NA_real_;bc<-variance-2*covariance;gap<-mp-o;bins[[b]]<-list(index=b-1,mass=w,meanPrediction=mp,eventRate=o,scoreVariance=variance,scoreTargetCovariance=covariance,withinBinCorrection=bc,ids=d$id[rr])\n  if(w){s<-w/W;ECE<-ECE+s*abs(gap);rel<-rel+s*gap^2;res<-res+s*(o-pi)^2;correction<-correction+s*bc}\n };bs<-ratio(sum(d$w[use]*(d$p[use]-d$y[use])^2),W);unc<-pi*(1-pi);list(bins=bins,Brier=bs,ECE=if(W)ECE else NA_real_,uncertainty=unc,reliability=if(W)rel else NA_real_,resolution=if(W)res else NA_real_,withinBinCorrection=if(W)correction else NA_real_,BrierIdentityResidual=bs-(unc-res+rel+correction))\n}\ngroupsG<-function(d,ids,t,cost){\n lev<-unique(d$group[ids][!is.na(d$group[ids])]);groups<-lapply(lev,function(g)list(group=g,metrics=metricsG(d,ids[!is.na(d$group[ids])&d$group[ids]==g],t,cost)));overall<-metricsG(d,ids,t,cost);unknown<-metricsG(d,ids[is.na(d$group[ids])],t,cost);gaps<-list()\n for(k in c(\"prevalence\",\"selectionRate\",\"TPR\",\"FPR\",\"precision\",\"accuracy\",\"meanCost\")){use<-Filter(function(g)g$metrics$mass>0,groups);v<-vapply(use,function(g)g$metrics[[k]],numeric(1));gaps[[k]]<-if(length(use)<2||anyNA(v))NA_real_ else max(v)-min(v)}\n list(overall=overall,groups=groups,unknownGroup=unknown,gaps=gaps,partitionMassResidual=overall$mass-unknown$mass-sum(vapply(groups,function(g)g$metrics$mass,numeric(1))))\n}\nsvgFixed<-function(file,points,title,xlabel,ylabel,legend){\n finite<-points[points$y!=\"undefined\"&points$x!=\"undefined\",,drop=FALSE];x<-as.numeric(finite$x);y<-as.numeric(finite$y);xmin<-if(length(x))min(x)else 0;xmax<-if(length(x))max(x)else 1;ymin<-min(c(0,y));ymax<-max(c(0,y));if(xmin==xmax){xmin<-xmin-.5;xmax<-xmax+.5};if(ymin==ymax)ymax<-ymin+1;X<-function(v)85+(v-xmin)/(xmax-xmin)*480;Y<-function(v)278-(v-ymin)/(ymax-ymin)*175\n esc<-function(s){s<-gsub(\"&\",\"&amp;\",s,fixed=TRUE);s<-gsub(\"<\",\"&lt;\",s,fixed=TRUE);gsub(\">\",\"&gt;\",s,fixed=TRUE)};s<-'<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"620\" height=\"360\" viewBox=\"0 0 620 360\"><rect width=\"620\" height=\"360\" fill=\"white\"/><g font-family=\"Arial, sans-serif\" font-size=\"13\" fill=\"#17324d\">'\n lines<-strwrap(title,width=65);for(i in seq_along(lines))s<-paste0(s,'<text x=\"25\" y=\"',24+(i-1)*18,'\">',esc(lines[i]),'</text>');colors<-c(\"#176b9b\",\"#b85e18\",\"#437e4d\")\n for(i in seq_along(legend))s<-paste0(s,'<circle cx=\"',30+(i-1)*250,'\" cy=\"76\" r=\"4\" fill=\"',colors[(i-1)%%3+1],'\"/><text x=\"',42+(i-1)*250,'\" y=\"80\">',esc(legend[i]),'</text>')\n s<-paste0(s,'<path d=\"M85 98V278H575\" fill=\"none\" stroke=\"#52677d\"/><text text-anchor=\"middle\" x=\"325\" y=\"338\">',esc(xlabel),'</text><text text-anchor=\"middle\" transform=\"translate(21,190) rotate(-90)\">',esc(ylabel),'</text>')\n for(i in 0:4){xx<-xmin+(xmax-xmin)*i/4;yy<-ymin+(ymax-ymin)*i/4;s<-paste0(s,'<text text-anchor=\"middle\" x=\"',sprintf(\"%.9g\",X(xx)),'\" y=\"305\">',sprintf(\"%.4g\",xx),'</text><text text-anchor=\"end\" x=\"77\" y=\"',sprintf(\"%.9g\",Y(yy)+4),'\">',sprintf(\"%.4g\",yy),'</text>')}\n for(i in seq_len(nrow(finite)))s<-paste0(s,'<circle cx=\"',sprintf(\"%.9g\",X(x[i])),'\" cy=\"',sprintf(\"%.9g\",Y(y[i])),'\" r=\"3\" fill=\"',colors[as.integer(finite$series[i])%%3+1],'\"/>');writeLines(paste0(s,'</g></svg>'),file,useBytes=TRUE)\n}\nfixedRun<-function(){\n api<-FIXED$api;a<-FIXED$args;summary<-list();points<-list();xlabel<-\"Declared index\";ylabel<-\"Value\";legend<-\"Declared result\"\n metric<-function(name,v,unit=\"dimensionless\"){if(is.null(v))v<-NA_real_;summary[[length(summary)+1L]]<<-data.frame(metric=name,value=if(is.na(v))\"undefined\"else sprintf(\"%.9g\",v),exactValue=\"\",unit=unit,defined=as.integer(!is.na(v)),stringsAsFactors=FALSE)}\n pt<-function(i,x,y,id=\"\",series=0){points[[length(points)+1L]]<<-data.frame(series=series,index=i,xExact=\"\",x=if(is.na(x))\"undefined\"else sprintf(\"%.9g\",x),yExact=\"\",y=if(is.na(y))\"undefined\"else sprintf(\"%.9g\",y),id=as.character(id),stringsAsFactors=FALSE)}\n if(api==\"realdata\"){\n  native<-loadData()[[a$kind]];fit<-fitmodel(native);d<-list(id=native$id,p=fit$pred,y=native$y,w=rep(1,length(native$id)),role=native$role,group=native$group,eligible=native$eligible);scenarios<-list()\n  for(j in 1:3){name<-c(\"equal\",\"miss-five\",\"alarm-five\")[j];cst<-list(c(1,1),c(1,5),c(5,1))[[j]];sel<-chooseG(d,list(),cst);scenarios[[j]]<-list(name=name,selection=sel);metric(paste0(name,\"Threshold\"),sel$selectedPolicy);metric(paste0(name,\"TestCost\"),sel$evaluation$meanCost,\"hypothetical cost units/mass\")}\n  ids<-scopeG(d,\"test\");cv<-curvesG(d,ids);cal<-calibrateG(d,ids,seq(0,1,.2));metric(\"testAUC\",cv$ROC_AUC);metric(\"testAP\",cv$averagePrecision);metric(\"testBrier\",cal$Brier);metric(\"eligibleRows\",sum(d$eligible),\"rows\")\n  for(j in seq_along(ids)){i<-ids[j];pt(j-1,j,d$p[i],d$id[i],0);pt(j-1,j,d$y[i],d$id[i],1)}\n  full<-list(kind=a$kind,fit=fit,scenarios=scenarios,testCurves=cv,testCalibration=cal,rowsScored=d);xlabel<-\"Test row, native order\";ylabel<-\"Y or probability\";legend<-c(\"Training-fitted probability\",\"Observed Y\")\n }else{\n  d<-rowsG(a$rows);role<-if(is.null(a$role))\"all\"else a$role;ids<-scopeG(d,role);cost<-if(is.null(a$costs))c(1,1)else c(qnum(a$costs$falsePositive),qnum(a$costs$falseNegative));t<-if(is.null(a$threshold)).5 else if(a$threshold%in%c(\"always-positive\",\"always-negative\"))a$threshold else qnum(a$threshold)\n  if(api==\"metrics\"){\n   full<-metricsG(d,ids,t,cost);for(k in c(\"mass\",\"accuracy\",\"precision\",\"TPR\",\"FPR\",\"F1\",\"Brier\",\"meanCost\"))metric(k,full[[k]],if(k==\"mass\")\"mass\"else if(k==\"meanCost\")\"hypothetical cost units/mass\"else\"dimensionless\");metric(\"BayesThreshold\",full$bayesThreshold)\n   for(i in 1:4)pt(i-1,i-1,full$confusion[[i]],names(full$confusion)[i]);xlabel<-\"TP / FP / FN / TN positions\";ylabel<-\"Analytical mass\"\n  }else if(api==\"curves\"){\n   full<-curvesG(d,ids);for(k in c(\"ROC_AUC\",\"averagePrecision\",\"PRTrapezoidWithInitialPrecisionOne\"))metric(k,full[[k]])\n   for(j in seq_along(full$points)){p<-full$points[[j]];pt(j-1,p$FPR,p$TPR,if(is.character(p$policy))p$policy else sprintf(\"%.17g\",p$policy))};xlabel<-\"False positive rate\";ylabel<-\"True positive rate\";legend<-\"Observed ROC operating points\"\n  }else if(api==\"choose\"){\n   full<-chooseG(d,a,cost);metric(\"selectedIndex\",full$selectedIndex,\"candidate index\");metric(\"minimumCost\",if(is.null(full$selectedValidation))NULL else full$selectedValidation$meanCost,\"hypothetical cost units/mass\");metric(\"feasible\",as.integer(!is.na(full$selectedIndex)),\"indicator\")\n   for(c in full$candidates)pt(c$index,c$index,c$metrics$meanCost,if(is.character(c$policy))c$policy else sprintf(\"%.17g\",c$policy));xlabel<-\"Validation candidate\";ylabel<-\"Assumed cost / mass\";legend<-\"Validation candidate costs\"\n  }else if(api==\"calibrate\"){\n   edges<-if(is.null(a$binEdges))seq(0,1,.2)else vapply(a$binEdges,qnum,numeric(1));full<-calibrateG(d,ids,edges);for(k in c(\"ECE\",\"Brier\",\"uncertainty\",\"resolution\",\"reliability\",\"withinBinCorrection\",\"BrierIdentityResidual\"))metric(k,full[[k]])\n   for(b in full$bins)pt(b$index,b$meanPrediction,b$eventRate,paste0(\"bin:\",b$index));xlabel<-\"Bin mean forecast\";ylabel<-\"Bin event rate\";legend<-\"Binary-event reliability\"\n  }else if(api==\"groups\"){\n   full<-groupsG(d,ids,t,cost);metric(\"overallTPR\",full$overall$TPR);metric(\"TPRGap\",full$gaps$TPR);metric(\"precisionGap\",full$gaps$precision);metric(\"unknownMass\",full$unknownGroup$mass,\"mass\");metric(\"partitionResidual\",full$partitionMassResidual,\"mass\")\n   for(j in seq_along(full$groups))pt(j-1,j-1,full$groups[[j]]$metrics$TPR,full$groups[[j]]$group);xlabel<-\"Declared group position\";ylabel<-\"True positive rate\";legend<-\"Known-group TPR\"\n  }else stop(\"unknown declared fixed API\")\n }\n sm<-do.call(rbind,summary);pp<-do.call(rbind,points);write.csv(sm,file.path(outDir,\"summary.csv\"),row.names=FALSE,na=\"\");write.csv(pp,file.path(outDir,\"plot-points.csv\"),row.names=FALSE,na=\"\");svgFixed(file.path(outDir,\"plot.svg\"),pp,FIXED$title,xlabel,ylabel,legend);dput(list(api=api,variant=FIXED$variant,input=FIXED$args,arithmetic=\"Base-R binary64 fixed example; not an exact rational general validator\",result=full),file=file.path(outDir,\"full.txt\"));cat(\"PASS\",api,FIXED$variant,\"summary\",nrow(sm),\"points\",nrow(pp),\"\\n\")\n}\n\nFIXED<-list(api=\"curves\",variant=\"six-cards\",args=list(rows=list(list(id=\"a\",score=\".9\",y=1,group=\"A\"),list(id=\"b\",score=\".8\",y=1,group=\"A\"),list(id=\"c\",score=\".8\",y=0,group=\"A\"),list(id=\"d\",score=\".6\",y=0,group=\"B\"),list(id=\"e\",score=\".4\",y=1,group=\"B\"),list(id=\"f\",score=\".1\",y=0,group=\"B\"))),title=\"Tied-score six-card ROC, AP and labeled PR trapezoid\")\nfixedRun()\n",
        "codeText": "# ML14 standalone public counterpart, base R only.\n# Inputs are only the three factual CSVs; derived columns/previous model answers unused.\n# Binary64 arithmetic, not arbitrary-precision Fraction. At numerical cost ties\n# within 1e-12 retain the earliest candidate. Exact claims belong to Python/web.\n# SHA256 infrastructure below is reused verbatim from the previous public study.\nargs<-commandArgs(trailingOnly=TRUE);filearg<-grep(\"^--file=\",commandArgs(),value=TRUE)\nhere<-if(dir.exists(\"ml14-sources\"))getwd()else if(length(filearg))dirname(normalizePath(sub(\"^--file=\",\"\",filearg[1])))else getwd()\noption<-function(key,default){i<-match(key,args);if(is.na(i))default else args[i+1]}\nsourceDir<-option(\"--source\",file.path(here,\"ml14-sources\"));outDir<-option(\"--out\",file.path(getwd(),\"ml14-r-results\"));dir.create(outDir,recursive=TRUE,showWarnings=FALSE)\nnum<-function(x){x[x%in%c(\"\",\".\")]<-NA_character_;as.numeric(x)}\nfmt<-function(x)ifelse(is.na(x),\"\",sprintf(\"%.17g\",x))\nratio<-function(a,b)if(b==0)NA_real_ else a/b\nreadnative<-function(name)read.csv(file.path(sourceDir,name),check.names=FALSE,colClasses=\"character\",na.strings=character(),stringsAsFactors=FALSE)\n# Vectorized SHA256 for the short ASCII keys used in this study.\n# Unsigned words use exact integer-valued doubles; bit operations use safe\n# 16-bit halves, avoiding R's reserved signed-INT_MIN/NA representation.\nMOD<-2^32\nxor32<-function(a,b) as.double(bitwXor(as.integer(floor(a/65536)),as.integer(floor(b/65536))))*65536+as.double(bitwXor(as.integer(a%%65536),as.integer(b%%65536)))\nand32<-function(a,b) as.double(bitwAnd(as.integer(floor(a/65536)),as.integer(floor(b/65536))))*65536+as.double(bitwAnd(as.integer(a%%65536),as.integer(b%%65536)))\nrot<-function(x,n) floor(x/2^n)+(x%%2^n)*2^(32-n)\nxor3<-function(a,b,c) xor32(xor32(a,b),c)\nK<-c(0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5,0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967,0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070,0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3,0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2)\nsha256<-function(strings) {\n n<-length(strings);bytes<-matrix(0,n,64)\n for(i in seq_len(n)) {v<-utf8ToInt(strings[i]);stopifnot(length(v)<56,all(v<128));if(length(v)) bytes[i,seq_along(v)]<-v;bytes[i,length(v)+1]<-128;bits<-length(v)*8;bytes[i,61:64]<-c(floor(bits/2^24)%%256,floor(bits/2^16)%%256,floor(bits/256)%%256,bits%%256)}\n w<-matrix(0,n,64)\n for(j in 1:16) {b<-4*(j-1)+1;w[,j]<-bytes[,b]*2^24+bytes[,b+1]*2^16+bytes[,b+2]*256+bytes[,b+3]}\n for(j in 17:64) {s0<-xor3(rot(w[,j-15],7),rot(w[,j-15],18),floor(w[,j-15]/8));s1<-xor3(rot(w[,j-2],17),rot(w[,j-2],19),floor(w[,j-2]/1024));w[,j]<-(w[,j-16]+s0+w[,j-7]+s1)%%MOD}\n init<-c(0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19)\n state<-lapply(init,function(v) rep(v,n));a<-state[[1]];b<-state[[2]];c<-state[[3]];d<-state[[4]];e<-state[[5]];f<-state[[6]];g<-state[[7]];h<-state[[8]]\n for(j in 1:64) {S1<-xor3(rot(e,6),rot(e,11),rot(e,25));ch<-xor32(and32(e,f),and32(MOD-1-e,g));t1<-(h+S1+ch+K[j]+w[,j])%%MOD;S0<-xor3(rot(a,2),rot(a,13),rot(a,22));maj<-xor3(and32(a,b),and32(a,c),and32(b,c));t2<-(S0+maj)%%MOD;h<-g;g<-f;f<-e;e<-(d+t1)%%MOD;d<-c;c<-b;b<-a;a<-(t1+t2)%%MOD}\n end<-list(a,b,c,d,e,f,g,h);hex<-lapply(1:8,function(j){v<-(end[[j]]+init[j])%%MOD;paste0(sprintf(\"%04x\",as.integer(floor(v/65536))),sprintf(\"%04x\",as.integer(v%%65536)))})\n do.call(paste0,hex)\n}\nstopifnot(identical(sha256(c(\"abc\",\"\")),c(\"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad\",\"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855\")))\n\nloadData<-function(){\n wb<-readnative(\"actual64-country-four-indicators-original-2024.csv\");codes<-c(\"NY.GDP.PCAP.KD\",\"NY.GDP.MKTP.KD.ZG\",\"FP.CPI.TOTL.ZG\",\"SP.DYN.LE00.IN\");iso<-sort(unique(wb$countryISO3));stopifnot(nrow(wb)==64,length(iso)==16)\n tokens<-t(vapply(iso,function(s)wb$originalValueToken[match(paste(s,codes),paste(wb$countryISO3,wb$indicatorID))],character(4)));vals<-matrix(num(as.vector(tokens)),nrow=nrow(tokens))\n country<-list(id=paste0(iso,\":2024\"),sourceRow=1:16,originalID=iso,x=vals[,1:3,drop=FALSE],rawX=tokens[,1:3,drop=FALSE],nativeTarget=tokens[,4],y=as.integer(vals[,4]>=80),group=ifelse(is.na(vals[,1]),NA_character_,as.character(as.integer(vals[,1]>=25000))),lineage=vapply(iso,function(s)paste(wb$sourceRow[match(paste(s,codes),paste(wb$countryISO3,wb$indicatorID))],collapse=\";\"),character(1)),cat=integer(),units=c(\"constant2015USD/person\",\"annualPercent\",\"annualPercent\"))\n nls<-readnative(\"actual3613-NLS-original52-fields-groups-roles.csv\");raw<-cbind(nls$ed76,nls$age76,nls$nearc4)\n person<-list(id=paste0(\"person:\",nls$sourceRow),sourceRow=as.integer(nls$sourceRow),originalID=nls$id,x=matrix(num(as.vector(raw)),nrow=nrow(raw)),rawX=raw,nativeTarget=nls$wage76,y=as.integer(num(nls$wage76)>=500),group=ifelse(nls$black%in%c(\"\",\".\"),NA_character_,nls$black),lineage=nls$sourceRow,cat=2L,units=c(\"years\",\"years\",\"nativeCategory\"))\n ch<-readnative(\"actual3150-churn-original14-fields-groups-roles.csv\");raw<-cbind(ch[[\"Call  Failure\"]],ch$Complains,ch[[\"Subscription  Length\"]],ch[[\"Seconds of Use\"]])\n company<-list(id=paste0(\"customer:\",ch$sourceRow),sourceRow=as.integer(ch$sourceRow),originalID=rep(\"\",nrow(ch)),x=matrix(num(as.vector(raw)),nrow=nrow(raw)),rawX=raw,nativeTarget=ch$Churn,y=as.integer(ch$Churn),group=ifelse(ch[[\"Tariff Plan\"]]%in%c(\"\",\".\"),NA_character_,ch[[\"Tariff Plan\"]]),lineage=ch$sourceRow,cat=1L,units=c(\"count\",\"nativeCategory\",\"months\",\"seconds\"))\n stopifnot(nrow(nls)==3613,nrow(ch)==3150,identical(as.integer(ch$sourceRow[ch[[\"Charge  Amount\"]]==\"10\"]),c(474L,2174L,2274L,2374L,2674L,2924L,2974L)))\n result<-list(country=country,person=person,company=company)\n for(k in names(result)){d<-result[[k]];n<-length(d$id);d$eligible<-!is.na(d$y)&rowSums(is.na(d$x))==0;hash<-sha256(paste0(\"ML14-role|\",k,\"|\",d$id));rank<-integer(n);rank[order(hash,seq_len(n))]<-seq_len(n)-1L;d$plannedRole<-ifelse(rank%%5==0,\"test\",ifelse(rank%%5==1,\"validation\",\"train\"));d$role<-ifelse(d$eligible,d$plannedRole,\"excluded\");result[[k]]<-d}\n stopifnot(sum(result$person$eligible)==3017);result\n}\nfitmodel<-function(d){\n ids<-which(d$role==\"train\");p<-ncol(d$x);m<-vapply(seq_len(p),function(j)if((j-1)%in%d$cat)NA_real_ else median(d$x[ids,j]),numeric(1));z<-d$x\n for(j in seq_len(p))if(!((j-1)%in%d$cat))z[,j]<-as.numeric(z[,j]>m[j])\n keys<-apply(z,1,function(v)paste(fmt(v),collapse=\"|\"));lev<-unique(keys[ids]);mass<-vapply(lev,function(k)sum(keys[ids]==k),integer(1));positive<-vapply(lev,function(k)sum(d$y[ids][keys[ids]==k]),integer(1));prob<-(positive+1)/(mass+2);fallback<-(sum(d$y[ids])+1)/(length(ids)+2);pred<-prob[match(keys,lev)];unseen<-is.na(pred);pred[unseen]<-fallback;pred[!d$eligible]<-NA_real_;unseen[!d$eligible]<-NA\n list(ids=ids,medians=m,z=z,keys=keys,lev=lev,mass=mass,positive=positive,prob=prob,fallback=fallback,pred=pred,unseen=unseen)\n}\nmeasure<-function(d,p,ids,t=.5,cost=c(1,1)){\n use<-ids[d$eligible[ids]&!is.na(p[ids])];y<-d$y[use];a<-if(is.character(t))rep(t==\"always-positive\",length(use))else p[use]>=t\n TP<-sum(a&y==1);FP<-sum(a&y==0);FN<-sum(!a&y==1);TN<-sum(!a&y==0);P<-TP+FN;N<-FP+TN;W<-P+N;PP<-TP+FP;PN<-TN+FN;TPR<-ratio(TP,P);TNR<-ratio(TN,N);bs<-sum((p[use]-y)^2);tc<-FP*cost[1]+FN*cost[2]\n list(TP=TP,FP=FP,FN=FN,TN=TN,mass=W,positiveTargetMass=P,negativeTargetMass=N,predictedPositiveMass=PP,predictedNegativeMass=PN,prevalence=ratio(P,W),selectionRate=ratio(PP,W),accuracy=ratio(TP+TN,W),precision=ratio(TP,PP),negativePredictiveValue=ratio(TN,PN),TPR=TPR,FPR=ratio(FP,N),TNR=TNR,FNR=ratio(FN,P),F1=ratio(2*TP,2*TP+FP+FN),balancedAccuracy=if(is.na(TPR)||is.na(TNR))NA_real_ else(TPR+TNR)/2,Brier=ratio(bs,W),BrierSum=bs,totalCost=tc,meanCost=ratio(tc,W))\n}\ncurves<-function(d,p,ids){\n use<-ids[d$eligible[ids]&!is.na(p[ids])];scores<-sort(unique(p[use]),decreasing=TRUE);policies<-c(list(\"always-negative\"),as.list(scores));points<-lapply(policies,function(t){m<-measure(d,p,ids,t);c(list(policy=t),m[c(\"TP\",\"FP\",\"FN\",\"TN\",\"TPR\",\"FPR\",\"precision\")],list(recall=m$TPR))})\n pos<-use[d$y[use]==1];neg<-use[d$y[use]==0];U<-0;for(i in pos)U<-U+sum(p[i]>p[neg])+.5*sum(p[i]==p[neg])\n AP<-0;trap<-0;lastR<-0;lastP<-1\n if(length(pos)&&length(scores))for(j in seq_along(scores)){z<-points[[j+1]];AP<-AP+(z$recall-lastR)*z$precision;trap<-trap+(z$recall-lastR)*(z$precision+lastP)/2;lastR<-z$recall;lastP<-z$precision}\n list(points=points,ROC_AUC=ratio(U,length(pos)*length(neg)),averagePrecision=if(length(pos))AP else NA_real_,PRTrapezoidWithInitialPrecisionOne=if(length(pos))trap else NA_real_)\n}\ncalibrate<-function(d,p,ids){\n use<-ids[d$eligible[ids]&!is.na(p[ids])];W<-length(use);pi<-if(W)mean(d$y[use])else NA_real_;bins<-list();ECE<-rel<-res<-correction<-0\n whichbin<-findInterval(p[use],seq(0,1,.2),rightmost.closed=TRUE,all.inside=TRUE)\n for(b in 1:5){rr<-use[whichbin==b];w<-length(rr);mp<-if(w)mean(p[rr])else NA_real_;o<-if(w)mean(d$y[rr])else NA_real_;variance<-if(w)mean((p[rr]-mp)^2)else NA_real_;covariance<-if(w)mean((p[rr]-mp)*(d$y[rr]-o))else NA_real_;bc<-variance-2*covariance;gap<-mp-o\n  bins[[b]]<-list(mass=w,meanPrediction=mp,eventRate=o,gap=gap,absoluteGap=abs(gap),scoreVariance=variance,scoreTargetCovariance=covariance,withinBinCorrection=bc,rows=w,ids=d$id[rr])\n  if(w){share<-w/W;ECE<-ECE+share*abs(gap);rel<-rel+share*gap^2;res<-res+share*(o-pi)^2;correction<-correction+share*bc}\n };bs<-if(W)mean((p[use]-d$y[use])^2)else NA_real_;unc<-pi*(1-pi)\n list(bins=bins,ECE=if(W)ECE else NA_real_,Brier=bs,reliability=if(W)rel else NA_real_,resolution=if(W)res else NA_real_,uncertainty=unc,withinBinCorrection=if(W)correction else NA_real_,BrierIdentityResidual=bs-(unc-res+rel+correction))\n}\ncounts<-c(\"mass\",\"positiveTargetMass\",\"negativeTargetMass\",\"predictedPositiveMass\",\"predictedNegativeMass\");rates<-c(\"prevalence\",\"selectionRate\",\"accuracy\",\"precision\",\"negativePredictiveValue\",\"TPR\",\"FPR\",\"TNR\",\"FNR\",\"F1\",\"balancedAccuracy\",\"Brier\",\"BrierSum\",\"totalCost\",\"meanCost\")\ntables<-setNames(lapply(1:10,function(i)list()),c(\"predictions\",\"lineage\",\"fit-medians\",\"fit-cells\",\"validation-candidates\",\"test-metrics\",\"test-curves\",\"calibration-bins\",\"group-metrics\",\"chart-points\"))\nadd<-function(name,row)tables[[name]][[length(tables[[name]])+1L]]<<-row\nscalars<-function(m,keys){out<-list();for(k in keys){out[[paste0(k,\"Exact\")]]<-\"\";out[[paste0(k,\"Approx\")]]<-fmt(m[[k]])};out}\ntagrow<-function(kind,...)c(list(kind=kind),list(...))\npoint<-function(kind,chart,series,index,x,y,xunit=\"dimensionless\",yunit=\"dimensionless\",role=\"test\",tag=\"\"){add(\"chart-points\",tagrow(kind,chart=chart,series=series,index=index,xExact=\"\",xApprox=fmt(x),yExact=\"\",yApprox=fmt(y),xUnit=xunit,yUnit=yunit,role=role,tag=tag))}\nstudy<-function(kind,d){\n f<-fitmodel(d);n<-length(d$id);train<-which(d$role==\"train\");validation<-which(d$role==\"validation\");test<-which(d$role==\"test\");p<-f$pred;cv<-curves(d,p,test);cal<-calibrate(d,p,test)\n for(i in seq_len(n)){\n  reason<-if(d$eligible[i])\"\"else\"required-X-or-Y-missing\";transformed<-if(d$eligible[i])paste(fmt(f$z[i,]),collapse=\"|\")else\"\"\n  add(\"predictions\",tagrow(kind,id=d$id[i],sourceRow=d$sourceRow[i],originalID=d$originalID[i],plannedRole=d$plannedRole[i],role=d$role[i],group=ifelse(is.na(d$group[i]),\"\",d$group[i]),eligible=as.integer(d$eligible[i]),targetExact=fmt(d$y[i]),probabilityExact=\"\",probabilityApprox=fmt(p[i]),unseenCell=ifelse(is.na(f$unseen[i]),\"\",as.character(as.integer(f$unseen[i]))),transformedX=transformed,reason=reason))\n  raw<-d$rawX[i,];raw[raw%in%c(\"\",\".\")]<-\"\";nativeY<-d$nativeTarget[i];if(nativeY%in%c(\"\",\".\"))nativeY<-\"\"\n  add(\"lineage\",tagrow(kind,id=d$id[i],sourceRow=d$sourceRow[i],originalID=d$originalID[i],nativeSourceRows=d$lineage[i],rawX=paste(raw,collapse=\"|\"),nativeTarget=nativeY,derivedTarget=fmt(d$y[i]),nativeGroup=ifelse(is.na(d$group[i]),\"\",d$group[i]),plannedRole=d$plannedRole[i],role=d$role[i],eligible=as.integer(d$eligible[i]),analyticalMass=\"1\",reason=reason))\n }\n for(j in seq_len(ncol(d$x)))add(\"fit-medians\",tagrow(kind,feature=j-1,categorical=as.integer((j-1)%in%d$cat),fitRows=length(train),medianExact=\"\",medianApprox=fmt(f$medians[j]),unit=d$units[j]))\n for(j in seq_along(f$lev))add(\"fit-cells\",tagrow(kind,cell=f$lev[j],trainingRows=f$mass[j],positiveRows=f$positive[j],probabilityExact=\"\",probabilityApprox=fmt(f$prob[j]),fallbackExact=\"\",fallbackApprox=fmt(f$fallback)))\n for(j in seq_along(cv$points)){\n  z<-cv$points[[j]];t<-z$policy;add(\"test-curves\",c(tagrow(kind,point=j-1,policy=if(is.character(t))t else\"threshold\",thresholdExact=\"\",thresholdApprox=if(is.character(t))\"\"else fmt(t)),scalars(z,c(\"TP\",\"FP\",\"FN\",\"TN\",\"TPR\",\"FPR\",\"precision\",\"recall\"))))\n  point(kind,\"roc\",\"ROC\",j-1,z$FPR,z$TPR);point(kind,\"pr\",\"PR-observed\",j-1,z$recall,z$precision)\n }\n for(b in 1:5){z<-cal$bins[[b]];add(\"calibration-bins\",c(tagrow(kind,bin=b-1,leftExact=c(\"0\",\"1/5\",\"2/5\",\"3/5\",\"4/5\")[b],rightExact=c(\"1/5\",\"2/5\",\"3/5\",\"4/5\",\"1\")[b],rightClosed=as.integer(b==5),rows=z$rows,ids=paste(z$ids,collapse=\";\")),scalars(z,c(\"mass\",\"meanPrediction\",\"eventRate\",\"gap\",\"absoluteGap\",\"scoreVariance\",\"scoreTargetCovariance\",\"withinBinCorrection\"))));point(kind,\"reliability\",\"Binary event rate\",b-1,z$meanPrediction,z$eventRate,tag=paste0(\"rows=\",z$rows))}\n for(j in seq_along(test)){i<-test[j];point(kind,\"test-scores\",\"Training-fitted probability\",j-1,j,p[i],\"test-row position\",\"probability\",tag=d$id[i]);point(kind,\"test-scores\",\"Observed Y\",j-1,j,d$y[i],\"test-row position\",\"binary target\",tag=d$id[i])}\n scenarioNames<-c(\"equal\",\"miss-five\",\"alarm-five\");costs<-list(c(1,1),c(1,5),c(5,1))\n for(s in 1:3){name<-scenarioNames[s];cost<-costs[[s]];grid<-c(list(\"always-negative\"),as.list(sort(unique(p[validation]),decreasing=TRUE)));candidates<-lapply(grid,function(t)measure(d,p,validation,t,cost));values<-vapply(candidates,function(m)m$meanCost,numeric(1));best<-which(values<=min(values)+1e-12)[1];chosen<-grid[[best]];ev<-measure(d,p,test,chosen,cost)\n  for(j in seq_along(grid)){t<-grid[[j]];m<-candidates[[j]];cell<-setNames(lapply(c(\"TP\",\"FP\",\"FN\",\"TN\"),function(k)fmt(m[[k]])),paste0(c(\"TP\",\"FP\",\"FN\",\"TN\"),\"Exact\"));add(\"validation-candidates\",c(tagrow(kind,scenario=name,candidate=j-1,selected=as.integer(j==best),policy=if(is.character(t))t else\"threshold\",thresholdExact=\"\",thresholdApprox=if(is.character(t))\"\"else fmt(t),feasible=1,reasons=\"\"),cell,scalars(m,c(counts,\"TPR\",\"FPR\",\"precision\",\"meanCost\",\"totalCost\"))));point(kind,\"validation-cost\",name,j-1,j-1,m$meanCost,\"candidate index\",\"hypothetical cost units/mass\",\"validation\",if(is.character(t))t else fmt(t))}\n  m<-c(ev,cv[c(\"ROC_AUC\",\"averagePrecision\",\"PRTrapezoidWithInitialPrecisionOne\")],cal[c(\"ECE\",\"reliability\",\"resolution\",\"uncertainty\",\"withinBinCorrection\",\"BrierIdentityResidual\")])\n  for(k in c(\"TP\",\"FP\",\"FN\",\"TN\",counts,rates,\"ROC_AUC\",\"averagePrecision\",\"PRTrapezoidWithInitialPrecisionOne\",\"ECE\",\"reliability\",\"resolution\",\"uncertainty\",\"withinBinCorrection\",\"BrierIdentityResidual\")){\n   unit<-if(k%in%c(\"TP\",\"FP\",\"FN\",\"TN\",counts))\"rows\"else if(k==\"totalCost\")\"hypothetical cost units\"else if(k==\"meanCost\")\"hypothetical cost units/mass\"else if(k==\"BrierSum\")\"sum squared-probability loss\"else\"dimensionless\"\n   add(\"test-metrics\",tagrow(kind,scenario=name,metric=k,valueExact=\"\",valueApprox=fmt(m[[k]]),unit=unit))\n  }\n  lev<-unique(d$group[test][!is.na(d$group[test])]);sets<-c(list(test),lapply(lev,function(g)test[!is.na(d$group[test])&d$group[test]==g]),list(test[is.na(d$group[test])]))\n  types<-c(\"overall\",rep(\"known\",length(lev)),\"unknown\");tokens<-c(\"all\",lev,\"\")\n  for(j in seq_along(sets)){ids<-sets[[j]];m<-measure(d,p,ids,chosen,cost);cell<-setNames(lapply(c(\"TP\",\"FP\",\"FN\",\"TN\"),function(k)fmt(m[[k]])),paste0(c(\"TP\",\"FP\",\"FN\",\"TN\"),\"Exact\"));add(\"group-metrics\",c(tagrow(kind,scenario=name,groupType=types[j],groupToken=tokens[j],retainedRows=length(ids)),cell,scalars(m,c(counts,rates))));if(types[j]==\"known\")point(kind,\"group-TPR\",name,j-2,j-2,m$TPR,\"declared group position\",\"TPR\",tag=tokens[j])}\n }\n invisible(NULL)\n}\n\n# Fixed finite inputs only; not the complete web input/budget validator.\nqnum<-function(v){if(is.null(v))return(NA_real_);if(is.logical(v))return(as.numeric(v));s<-as.character(v);if(grepl(\"/\",s,fixed=TRUE)){a<-strsplit(s,\"/\",fixed=TRUE)[[1]];return(as.numeric(a[1])/as.numeric(a[2]))};as.numeric(s)}\nrowsG<-function(raw){\n n<-length(raw);get<-function(r,k,default=NULL)if(is.null(r[[k]]))default else r[[k]]\n id<-vapply(raw,function(r)as.character(r$id),character(1));p<-vapply(raw,function(r)qnum(r$score),numeric(1));y<-vapply(raw,function(r)qnum(r$y),numeric(1));w<-vapply(raw,function(r)qnum(get(r,\"weight\",\"1\")),numeric(1));role<-vapply(raw,function(r)get(r,\"role\",\"evaluation\"),character(1));group<-vapply(raw,function(r)as.character(get(r,\"group\",NA_character_)),character(1))\n stopifnot(all(w>=0),all(is.na(p)|(p>=0&p<=1)),all(is.na(y)|y%in%c(0,1)),!anyDuplicated(id));list(id=id,p=p,y=y,w=w,role=role,group=group,eligible=!is.na(p)&!is.na(y)&w>0&role!=\"excluded\")\n}\nscopeG<-function(d,role=\"all\")if(role==\"all\")seq_along(d$id)else which(d$role==role)\nmetricsG<-function(d,ids,t=.5,cost=c(1,1)){\n use<-ids[d$eligible[ids]];p<-d$p[use];y<-d$y[use];w<-d$w[use];a<-if(is.character(t))rep(t==\"always-positive\",length(use))else p>=t\n TP<-sum(w[a&y==1]);FP<-sum(w[a&y==0]);FN<-sum(w[!a&y==1]);TN<-sum(w[!a&y==0]);P<-TP+FN;N<-FP+TN;W<-P+N;PP<-TP+FP;PN<-TN+FN;TPR<-ratio(TP,P);TNR<-ratio(TN,N);bs<-sum(w*(p-y)^2);tc<-FP*cost[1]+FN*cost[2]\n list(confusion=list(TP=TP,FP=FP,FN=FN,TN=TN),mass=W,positiveTargetMass=P,negativeTargetMass=N,predictedPositiveMass=PP,predictedNegativeMass=PN,prevalence=ratio(P,W),selectionRate=ratio(PP,W),accuracy=ratio(TP+TN,W),precision=ratio(TP,PP),negativePredictiveValue=ratio(TN,PN),TPR=TPR,FPR=ratio(FP,N),TNR=TNR,FNR=ratio(FN,P),F1=ratio(2*TP,2*TP+FP+FN),balancedAccuracy=if(is.na(TPR)||is.na(TNR))NA_real_ else(TPR+TNR)/2,Brier=ratio(bs,W),BrierSum=bs,totalCost=tc,meanCost=ratio(tc,W),bayesThreshold=ratio(cost[1],sum(cost)))\n}\ncurvesG<-function(d,ids){\n use<-ids[d$eligible[ids]];grid<-c(list(\"always-negative\"),as.list(sort(unique(d$p[use]),decreasing=TRUE)));points<-lapply(grid,function(t){m<-metricsG(d,ids,t);c(list(policy=t),m$confusion,m[c(\"TPR\",\"FPR\",\"precision\")],list(recall=m$TPR))});pos<-use[d$y[use]==1];neg<-use[d$y[use]==0];P<-sum(d$w[pos]);N<-sum(d$w[neg]);U<-0\n for(i in pos)U<-U+d$w[i]*sum(d$w[neg]*((d$p[i]>d$p[neg])+.5*(d$p[i]==d$p[neg])))\n AP<-trap<-lastR<-0;lastP<-1\n if(P&&length(grid)>1)for(j in 2:length(grid)){z<-points[[j]];AP<-AP+(z$recall-lastR)*z$precision;trap<-trap+(z$recall-lastR)*(z$precision+lastP)/2;lastR<-z$recall;lastP<-z$precision}\n list(points=points,ROC_AUC=ratio(U,P*N),averagePrecision=if(P)AP else NA_real_,PRTrapezoidWithInitialPrecisionOne=if(P)trap else NA_real_)\n}\nchooseG<-function(d,a,cost){\n role<-if(is.null(a$selectionRole))\"validation\"else a$selectionRole;er<-if(is.null(a$evaluationRole))\"test\"else a$evaluationRole;ids<-scopeG(d,role);use<-ids[d$eligible[ids]];stopifnot(length(use)>0);grid<-if(is.null(a$thresholds))c(list(\"always-negative\"),as.list(sort(unique(d$p[use]),decreasing=TRUE)))else lapply(a$thresholds,function(t)if(t%in%c(\"always-negative\",\"always-positive\"))t else qnum(t))\n candidates<-lapply(seq_along(grid),function(j){m<-metricsG(d,ids,grid[[j]],cost);feasible<-TRUE;if(!is.null(a$minTPR))feasible<-feasible&&!is.na(m$TPR)&&m$TPR>=qnum(a$minTPR);if(!is.null(a$maxFPR))feasible<-feasible&&!is.na(m$FPR)&&m$FPR<=qnum(a$maxFPR);list(index=j-1,policy=grid[[j]],metrics=m,feasible=feasible)})\n good<-which(vapply(candidates,function(c)c$feasible,logical(1)));best<-NA_integer_;if(length(good)){v<-vapply(candidates[good],function(c)c$metrics$meanCost,numeric(1));best<-good[which(v<=min(v)+1e-12)[1]]}\n list(selectedIndex=if(is.na(best))NA_integer_ else best-1,selectedPolicy=if(is.na(best))NULL else grid[[best]],selectedValidation=if(is.na(best))NULL else candidates[[best]]$metrics,candidates=candidates,evaluation=if(is.na(best)||er==\"none\")NULL else metricsG(d,scopeG(d,er),grid[[best]],cost))\n}\ncalibrateG<-function(d,ids,edges){\n use<-ids[d$eligible[ids]];W<-sum(d$w[use]);pi<-ratio(sum(d$w[use]*d$y[use]),W);bins<-list();ECE<-rel<-res<-correction<-0;assign<-findInterval(d$p[use],edges,rightmost.closed=TRUE,all.inside=TRUE)\n for(b in seq_len(length(edges)-1)){rr<-use[assign==b];w<-sum(d$w[rr]);mp<-ratio(sum(d$w[rr]*d$p[rr]),w);o<-ratio(sum(d$w[rr]*d$y[rr]),w);variance<-if(w)sum(d$w[rr]*(d$p[rr]-mp)^2)/w else NA_real_;covariance<-if(w)sum(d$w[rr]*(d$p[rr]-mp)*(d$y[rr]-o))/w else NA_real_;bc<-variance-2*covariance;gap<-mp-o;bins[[b]]<-list(index=b-1,mass=w,meanPrediction=mp,eventRate=o,scoreVariance=variance,scoreTargetCovariance=covariance,withinBinCorrection=bc,ids=d$id[rr])\n  if(w){s<-w/W;ECE<-ECE+s*abs(gap);rel<-rel+s*gap^2;res<-res+s*(o-pi)^2;correction<-correction+s*bc}\n };bs<-ratio(sum(d$w[use]*(d$p[use]-d$y[use])^2),W);unc<-pi*(1-pi);list(bins=bins,Brier=bs,ECE=if(W)ECE else NA_real_,uncertainty=unc,reliability=if(W)rel else NA_real_,resolution=if(W)res else NA_real_,withinBinCorrection=if(W)correction else NA_real_,BrierIdentityResidual=bs-(unc-res+rel+correction))\n}\ngroupsG<-function(d,ids,t,cost){\n lev<-unique(d$group[ids][!is.na(d$group[ids])]);groups<-lapply(lev,function(g)list(group=g,metrics=metricsG(d,ids[!is.na(d$group[ids])&d$group[ids]==g],t,cost)));overall<-metricsG(d,ids,t,cost);unknown<-metricsG(d,ids[is.na(d$group[ids])],t,cost);gaps<-list()\n for(k in c(\"prevalence\",\"selectionRate\",\"TPR\",\"FPR\",\"precision\",\"accuracy\",\"meanCost\")){use<-Filter(function(g)g$metrics$mass>0,groups);v<-vapply(use,function(g)g$metrics[[k]],numeric(1));gaps[[k]]<-if(length(use)<2||anyNA(v))NA_real_ else max(v)-min(v)}\n list(overall=overall,groups=groups,unknownGroup=unknown,gaps=gaps,partitionMassResidual=overall$mass-unknown$mass-sum(vapply(groups,function(g)g$metrics$mass,numeric(1))))\n}\nsvgFixed<-function(file,points,title,xlabel,ylabel,legend){\n finite<-points[points$y!=\"undefined\"&points$x!=\"undefined\",,drop=FALSE];x<-as.numeric(finite$x);y<-as.numeric(finite$y);xmin<-if(length(x))min(x)else 0;xmax<-if(length(x))max(x)else 1;ymin<-min(c(0,y));ymax<-max(c(0,y));if(xmin==xmax){xmin<-xmin-.5;xmax<-xmax+.5};if(ymin==ymax)ymax<-ymin+1;X<-function(v)85+(v-xmin)/(xmax-xmin)*480;Y<-function(v)278-(v-ymin)/(ymax-ymin)*175\n esc<-function(s){s<-gsub(\"&\",\"&amp;\",s,fixed=TRUE);s<-gsub(\"<\",\"&lt;\",s,fixed=TRUE);gsub(\">\",\"&gt;\",s,fixed=TRUE)};s<-'<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"620\" height=\"360\" viewBox=\"0 0 620 360\"><rect width=\"620\" height=\"360\" fill=\"white\"/><g font-family=\"Arial, sans-serif\" font-size=\"13\" fill=\"#17324d\">'\n lines<-strwrap(title,width=65);for(i in seq_along(lines))s<-paste0(s,'<text x=\"25\" y=\"',24+(i-1)*18,'\">',esc(lines[i]),'</text>');colors<-c(\"#176b9b\",\"#b85e18\",\"#437e4d\")\n for(i in seq_along(legend))s<-paste0(s,'<circle cx=\"',30+(i-1)*250,'\" cy=\"76\" r=\"4\" fill=\"',colors[(i-1)%%3+1],'\"/><text x=\"',42+(i-1)*250,'\" y=\"80\">',esc(legend[i]),'</text>')\n s<-paste0(s,'<path d=\"M85 98V278H575\" fill=\"none\" stroke=\"#52677d\"/><text text-anchor=\"middle\" x=\"325\" y=\"338\">',esc(xlabel),'</text><text text-anchor=\"middle\" transform=\"translate(21,190) rotate(-90)\">',esc(ylabel),'</text>')\n for(i in 0:4){xx<-xmin+(xmax-xmin)*i/4;yy<-ymin+(ymax-ymin)*i/4;s<-paste0(s,'<text text-anchor=\"middle\" x=\"',sprintf(\"%.9g\",X(xx)),'\" y=\"305\">',sprintf(\"%.4g\",xx),'</text><text text-anchor=\"end\" x=\"77\" y=\"',sprintf(\"%.9g\",Y(yy)+4),'\">',sprintf(\"%.4g\",yy),'</text>')}\n for(i in seq_len(nrow(finite)))s<-paste0(s,'<circle cx=\"',sprintf(\"%.9g\",X(x[i])),'\" cy=\"',sprintf(\"%.9g\",Y(y[i])),'\" r=\"3\" fill=\"',colors[as.integer(finite$series[i])%%3+1],'\"/>');writeLines(paste0(s,'</g></svg>'),file,useBytes=TRUE)\n}\nfixedRun<-function(){\n api<-FIXED$api;a<-FIXED$args;summary<-list();points<-list();xlabel<-\"Declared index\";ylabel<-\"Value\";legend<-\"Declared result\"\n metric<-function(name,v,unit=\"dimensionless\"){if(is.null(v))v<-NA_real_;summary[[length(summary)+1L]]<<-data.frame(metric=name,value=if(is.na(v))\"undefined\"else sprintf(\"%.9g\",v),exactValue=\"\",unit=unit,defined=as.integer(!is.na(v)),stringsAsFactors=FALSE)}\n pt<-function(i,x,y,id=\"\",series=0){points[[length(points)+1L]]<<-data.frame(series=series,index=i,xExact=\"\",x=if(is.na(x))\"undefined\"else sprintf(\"%.9g\",x),yExact=\"\",y=if(is.na(y))\"undefined\"else sprintf(\"%.9g\",y),id=as.character(id),stringsAsFactors=FALSE)}\n if(api==\"realdata\"){\n  native<-loadData()[[a$kind]];fit<-fitmodel(native);d<-list(id=native$id,p=fit$pred,y=native$y,w=rep(1,length(native$id)),role=native$role,group=native$group,eligible=native$eligible);scenarios<-list()\n  for(j in 1:3){name<-c(\"equal\",\"miss-five\",\"alarm-five\")[j];cst<-list(c(1,1),c(1,5),c(5,1))[[j]];sel<-chooseG(d,list(),cst);scenarios[[j]]<-list(name=name,selection=sel);metric(paste0(name,\"Threshold\"),sel$selectedPolicy);metric(paste0(name,\"TestCost\"),sel$evaluation$meanCost,\"hypothetical cost units/mass\")}\n  ids<-scopeG(d,\"test\");cv<-curvesG(d,ids);cal<-calibrateG(d,ids,seq(0,1,.2));metric(\"testAUC\",cv$ROC_AUC);metric(\"testAP\",cv$averagePrecision);metric(\"testBrier\",cal$Brier);metric(\"eligibleRows\",sum(d$eligible),\"rows\")\n  for(j in seq_along(ids)){i<-ids[j];pt(j-1,j,d$p[i],d$id[i],0);pt(j-1,j,d$y[i],d$id[i],1)}\n  full<-list(kind=a$kind,fit=fit,scenarios=scenarios,testCurves=cv,testCalibration=cal,rowsScored=d);xlabel<-\"Test row, native order\";ylabel<-\"Y or probability\";legend<-c(\"Training-fitted probability\",\"Observed Y\")\n }else{\n  d<-rowsG(a$rows);role<-if(is.null(a$role))\"all\"else a$role;ids<-scopeG(d,role);cost<-if(is.null(a$costs))c(1,1)else c(qnum(a$costs$falsePositive),qnum(a$costs$falseNegative));t<-if(is.null(a$threshold)).5 else if(a$threshold%in%c(\"always-positive\",\"always-negative\"))a$threshold else qnum(a$threshold)\n  if(api==\"metrics\"){\n   full<-metricsG(d,ids,t,cost);for(k in c(\"mass\",\"accuracy\",\"precision\",\"TPR\",\"FPR\",\"F1\",\"Brier\",\"meanCost\"))metric(k,full[[k]],if(k==\"mass\")\"mass\"else if(k==\"meanCost\")\"hypothetical cost units/mass\"else\"dimensionless\");metric(\"BayesThreshold\",full$bayesThreshold)\n   for(i in 1:4)pt(i-1,i-1,full$confusion[[i]],names(full$confusion)[i]);xlabel<-\"TP / FP / FN / TN positions\";ylabel<-\"Analytical mass\"\n  }else if(api==\"curves\"){\n   full<-curvesG(d,ids);for(k in c(\"ROC_AUC\",\"averagePrecision\",\"PRTrapezoidWithInitialPrecisionOne\"))metric(k,full[[k]])\n   for(j in seq_along(full$points)){p<-full$points[[j]];pt(j-1,p$FPR,p$TPR,if(is.character(p$policy))p$policy else sprintf(\"%.17g\",p$policy))};xlabel<-\"False positive rate\";ylabel<-\"True positive rate\";legend<-\"Observed ROC operating points\"\n  }else if(api==\"choose\"){\n   full<-chooseG(d,a,cost);metric(\"selectedIndex\",full$selectedIndex,\"candidate index\");metric(\"minimumCost\",if(is.null(full$selectedValidation))NULL else full$selectedValidation$meanCost,\"hypothetical cost units/mass\");metric(\"feasible\",as.integer(!is.na(full$selectedIndex)),\"indicator\")\n   for(c in full$candidates)pt(c$index,c$index,c$metrics$meanCost,if(is.character(c$policy))c$policy else sprintf(\"%.17g\",c$policy));xlabel<-\"Validation candidate\";ylabel<-\"Assumed cost / mass\";legend<-\"Validation candidate costs\"\n  }else if(api==\"calibrate\"){\n   edges<-if(is.null(a$binEdges))seq(0,1,.2)else vapply(a$binEdges,qnum,numeric(1));full<-calibrateG(d,ids,edges);for(k in c(\"ECE\",\"Brier\",\"uncertainty\",\"resolution\",\"reliability\",\"withinBinCorrection\",\"BrierIdentityResidual\"))metric(k,full[[k]])\n   for(b in full$bins)pt(b$index,b$meanPrediction,b$eventRate,paste0(\"bin:\",b$index));xlabel<-\"Bin mean forecast\";ylabel<-\"Bin event rate\";legend<-\"Binary-event reliability\"\n  }else if(api==\"groups\"){\n   full<-groupsG(d,ids,t,cost);metric(\"overallTPR\",full$overall$TPR);metric(\"TPRGap\",full$gaps$TPR);metric(\"precisionGap\",full$gaps$precision);metric(\"unknownMass\",full$unknownGroup$mass,\"mass\");metric(\"partitionResidual\",full$partitionMassResidual,\"mass\")\n   for(j in seq_along(full$groups))pt(j-1,j-1,full$groups[[j]]$metrics$TPR,full$groups[[j]]$group);xlabel<-\"Declared group position\";ylabel<-\"True positive rate\";legend<-\"Known-group TPR\"\n  }else stop(\"unknown declared fixed API\")\n }\n sm<-do.call(rbind,summary);pp<-do.call(rbind,points);write.csv(sm,file.path(outDir,\"summary.csv\"),row.names=FALSE,na=\"\");write.csv(pp,file.path(outDir,\"plot-points.csv\"),row.names=FALSE,na=\"\");svgFixed(file.path(outDir,\"plot.svg\"),pp,FIXED$title,xlabel,ylabel,legend);dput(list(api=api,variant=FIXED$variant,input=FIXED$args,arithmetic=\"Base-R binary64 fixed example; not an exact rational general validator\",result=full),file=file.path(outDir,\"full.txt\"));cat(\"PASS\",api,FIXED$variant,\"summary\",nrow(sm),\"points\",nrow(pp),\"\\n\")\n}\n\nFIXED<-list(api=\"curves\",variant=\"six-cards\",args=list(rows=list(list(id=\"a\",score=\".9\",y=1,group=\"A\"),list(id=\"b\",score=\".8\",y=1,group=\"A\"),list(id=\"c\",score=\".8\",y=0,group=\"A\"),list(id=\"d\",score=\".6\",y=0,group=\"B\"),list(id=\"e\",score=\".4\",y=1,group=\"B\"),list(id=\"f\",score=\".1\",y=0,group=\"B\"))),title=\"Tied-score six-card ROC, AP and labeled PR trapezoid\")\nfixedRun()\n",
        "input": {
          "rows": [
            {
              "id": "a",
              "score": ".9",
              "y": 1,
              "group": "A"
            },
            {
              "id": "b",
              "score": ".8",
              "y": 1,
              "group": "A"
            },
            {
              "id": "c",
              "score": ".8",
              "y": 0,
              "group": "A"
            },
            {
              "id": "d",
              "score": ".6",
              "y": 0,
              "group": "B"
            },
            {
              "id": "e",
              "score": ".4",
              "y": 1,
              "group": "B"
            },
            {
              "id": "f",
              "score": ".1",
              "y": 0,
              "group": "B"
            }
          ]
        },
        "inputFiles": [],
        "returnCode": 0,
        "expectedFailure": false,
        "stdout": "PASS curves six-cards summary 3 points 6 \n",
        "stderr": "During startup - Warning messages:\n1: Setting LC_COLLATE=C.UTF-8 failed \n2: Setting LC_CTYPE=C.UTF-8 failed \n3: Setting LC_MONETARY=C.UTF-8 failed \n4: Setting LC_TIME=C.UTF-8 failed \n",
        "summary": {
          "ROC_AUC": "0.722222222",
          "averagePrecision": "0.755555556",
          "PRTrapezoidWithInitialPrecisionOne": "0.794444444"
        },
        "summaryRows": [
          {
            "metric": "ROC_AUC",
            "value": "0.722222222",
            "exactValue": "",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "averagePrecision",
            "value": "0.755555556",
            "exactValue": "",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "PRTrapezoidWithInitialPrecisionOne",
            "value": "0.794444444",
            "exactValue": "",
            "unit": "dimensionless",
            "defined": "1"
          }
        ],
        "plotPoints": [
          {
            "series": "0",
            "index": "0",
            "xExact": "",
            "x": "0",
            "yExact": "",
            "y": "0",
            "id": "always-negative"
          },
          {
            "series": "0",
            "index": "1",
            "xExact": "",
            "x": "0",
            "yExact": "",
            "y": "0.333333333",
            "id": "0.90000000000000002"
          },
          {
            "series": "0",
            "index": "2",
            "xExact": "",
            "x": "0.333333333",
            "yExact": "",
            "y": "0.666666667",
            "id": "0.80000000000000004"
          },
          {
            "series": "0",
            "index": "3",
            "xExact": "",
            "x": "0.666666667",
            "yExact": "",
            "y": "0.666666667",
            "id": "0.59999999999999998"
          },
          {
            "series": "0",
            "index": "4",
            "xExact": "",
            "x": "0.666666667",
            "yExact": "",
            "y": "1",
            "id": "0.40000000000000002"
          },
          {
            "series": "0",
            "index": "5",
            "xExact": "",
            "x": "1",
            "yExact": "",
            "y": "1",
            "id": "0.10000000000000001"
          }
        ],
        "plotFile": "ml14-fixed-results/curves-six-cards-r/plot.svg",
        "plotSHA256": "9a645573a56c6a0171e7d1406e40dfc653b2ecbf694682db150222cea075968e",
        "files": [
          {
            "file": "ml14-fixed-results/curves-six-cards-r/full.txt",
            "sha256": "9b7e6f0964d6ff208944f0075eb5cd31d5843711ecdbc31cb84fab23ffa60b51",
            "bytes": 1571
          },
          {
            "file": "ml14-fixed-results/curves-six-cards-r/plot-points.csv",
            "sha256": "0f9179e332b3a61208708a521d0ab8e05e126934b5a53ce2e0dee3cc65f748b3",
            "bytes": 351
          },
          {
            "file": "ml14-fixed-results/curves-six-cards-r/plot.svg",
            "sha256": "9a645573a56c6a0171e7d1406e40dfc653b2ecbf694682db150222cea075968e",
            "bytes": 1428
          },
          {
            "file": "ml14-fixed-results/curves-six-cards-r/summary.csv",
            "sha256": "a2ac2c7f25674091881b9b36b7c7108f2c64c50d89b77edba97b82be39978afa",
            "bytes": 222
          }
        ],
        "scope": "Actually executed standalone fixed example, Python exact Fraction versus base-R binary64. Approximate R residuals retained; not universal exact arithmetic/web validation/native UI. Source programs read factual3CSV only."
      },
      "all-tied": {
        "api": "curves",
        "variant": "all-tied",
        "language": "r",
        "title": "All scores tied: half pair credit and prevalence AP",
        "codeFile": "ml14-code/curves-all-tied.R",
        "codeSHA256": "1d8500ef7d694832ce3f51164adda1ed8c2af4f9634feebea6c625d73d8bd13f",
        "code": "# ML14 standalone public counterpart, base R only.\n# Inputs are only the three factual CSVs; derived columns/previous model answers unused.\n# Binary64 arithmetic, not arbitrary-precision Fraction. At numerical cost ties\n# within 1e-12 retain the earliest candidate. Exact claims belong to Python/web.\n# SHA256 infrastructure below is reused verbatim from the previous public study.\nargs<-commandArgs(trailingOnly=TRUE);filearg<-grep(\"^--file=\",commandArgs(),value=TRUE)\nhere<-if(dir.exists(\"ml14-sources\"))getwd()else if(length(filearg))dirname(normalizePath(sub(\"^--file=\",\"\",filearg[1])))else getwd()\noption<-function(key,default){i<-match(key,args);if(is.na(i))default else args[i+1]}\nsourceDir<-option(\"--source\",file.path(here,\"ml14-sources\"));outDir<-option(\"--out\",file.path(getwd(),\"ml14-r-results\"));dir.create(outDir,recursive=TRUE,showWarnings=FALSE)\nnum<-function(x){x[x%in%c(\"\",\".\")]<-NA_character_;as.numeric(x)}\nfmt<-function(x)ifelse(is.na(x),\"\",sprintf(\"%.17g\",x))\nratio<-function(a,b)if(b==0)NA_real_ else a/b\nreadnative<-function(name)read.csv(file.path(sourceDir,name),check.names=FALSE,colClasses=\"character\",na.strings=character(),stringsAsFactors=FALSE)\n# Vectorized SHA256 for the short ASCII keys used in this study.\n# Unsigned words use exact integer-valued doubles; bit operations use safe\n# 16-bit halves, avoiding R's reserved signed-INT_MIN/NA representation.\nMOD<-2^32\nxor32<-function(a,b) as.double(bitwXor(as.integer(floor(a/65536)),as.integer(floor(b/65536))))*65536+as.double(bitwXor(as.integer(a%%65536),as.integer(b%%65536)))\nand32<-function(a,b) as.double(bitwAnd(as.integer(floor(a/65536)),as.integer(floor(b/65536))))*65536+as.double(bitwAnd(as.integer(a%%65536),as.integer(b%%65536)))\nrot<-function(x,n) floor(x/2^n)+(x%%2^n)*2^(32-n)\nxor3<-function(a,b,c) xor32(xor32(a,b),c)\nK<-c(0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5,0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967,0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070,0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3,0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2)\nsha256<-function(strings) {\n n<-length(strings);bytes<-matrix(0,n,64)\n for(i in seq_len(n)) {v<-utf8ToInt(strings[i]);stopifnot(length(v)<56,all(v<128));if(length(v)) bytes[i,seq_along(v)]<-v;bytes[i,length(v)+1]<-128;bits<-length(v)*8;bytes[i,61:64]<-c(floor(bits/2^24)%%256,floor(bits/2^16)%%256,floor(bits/256)%%256,bits%%256)}\n w<-matrix(0,n,64)\n for(j in 1:16) {b<-4*(j-1)+1;w[,j]<-bytes[,b]*2^24+bytes[,b+1]*2^16+bytes[,b+2]*256+bytes[,b+3]}\n for(j in 17:64) {s0<-xor3(rot(w[,j-15],7),rot(w[,j-15],18),floor(w[,j-15]/8));s1<-xor3(rot(w[,j-2],17),rot(w[,j-2],19),floor(w[,j-2]/1024));w[,j]<-(w[,j-16]+s0+w[,j-7]+s1)%%MOD}\n init<-c(0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19)\n state<-lapply(init,function(v) rep(v,n));a<-state[[1]];b<-state[[2]];c<-state[[3]];d<-state[[4]];e<-state[[5]];f<-state[[6]];g<-state[[7]];h<-state[[8]]\n for(j in 1:64) {S1<-xor3(rot(e,6),rot(e,11),rot(e,25));ch<-xor32(and32(e,f),and32(MOD-1-e,g));t1<-(h+S1+ch+K[j]+w[,j])%%MOD;S0<-xor3(rot(a,2),rot(a,13),rot(a,22));maj<-xor3(and32(a,b),and32(a,c),and32(b,c));t2<-(S0+maj)%%MOD;h<-g;g<-f;f<-e;e<-(d+t1)%%MOD;d<-c;c<-b;b<-a;a<-(t1+t2)%%MOD}\n end<-list(a,b,c,d,e,f,g,h);hex<-lapply(1:8,function(j){v<-(end[[j]]+init[j])%%MOD;paste0(sprintf(\"%04x\",as.integer(floor(v/65536))),sprintf(\"%04x\",as.integer(v%%65536)))})\n do.call(paste0,hex)\n}\nstopifnot(identical(sha256(c(\"abc\",\"\")),c(\"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad\",\"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855\")))\n\nloadData<-function(){\n wb<-readnative(\"actual64-country-four-indicators-original-2024.csv\");codes<-c(\"NY.GDP.PCAP.KD\",\"NY.GDP.MKTP.KD.ZG\",\"FP.CPI.TOTL.ZG\",\"SP.DYN.LE00.IN\");iso<-sort(unique(wb$countryISO3));stopifnot(nrow(wb)==64,length(iso)==16)\n tokens<-t(vapply(iso,function(s)wb$originalValueToken[match(paste(s,codes),paste(wb$countryISO3,wb$indicatorID))],character(4)));vals<-matrix(num(as.vector(tokens)),nrow=nrow(tokens))\n country<-list(id=paste0(iso,\":2024\"),sourceRow=1:16,originalID=iso,x=vals[,1:3,drop=FALSE],rawX=tokens[,1:3,drop=FALSE],nativeTarget=tokens[,4],y=as.integer(vals[,4]>=80),group=ifelse(is.na(vals[,1]),NA_character_,as.character(as.integer(vals[,1]>=25000))),lineage=vapply(iso,function(s)paste(wb$sourceRow[match(paste(s,codes),paste(wb$countryISO3,wb$indicatorID))],collapse=\";\"),character(1)),cat=integer(),units=c(\"constant2015USD/person\",\"annualPercent\",\"annualPercent\"))\n nls<-readnative(\"actual3613-NLS-original52-fields-groups-roles.csv\");raw<-cbind(nls$ed76,nls$age76,nls$nearc4)\n person<-list(id=paste0(\"person:\",nls$sourceRow),sourceRow=as.integer(nls$sourceRow),originalID=nls$id,x=matrix(num(as.vector(raw)),nrow=nrow(raw)),rawX=raw,nativeTarget=nls$wage76,y=as.integer(num(nls$wage76)>=500),group=ifelse(nls$black%in%c(\"\",\".\"),NA_character_,nls$black),lineage=nls$sourceRow,cat=2L,units=c(\"years\",\"years\",\"nativeCategory\"))\n ch<-readnative(\"actual3150-churn-original14-fields-groups-roles.csv\");raw<-cbind(ch[[\"Call  Failure\"]],ch$Complains,ch[[\"Subscription  Length\"]],ch[[\"Seconds of Use\"]])\n company<-list(id=paste0(\"customer:\",ch$sourceRow),sourceRow=as.integer(ch$sourceRow),originalID=rep(\"\",nrow(ch)),x=matrix(num(as.vector(raw)),nrow=nrow(raw)),rawX=raw,nativeTarget=ch$Churn,y=as.integer(ch$Churn),group=ifelse(ch[[\"Tariff Plan\"]]%in%c(\"\",\".\"),NA_character_,ch[[\"Tariff Plan\"]]),lineage=ch$sourceRow,cat=1L,units=c(\"count\",\"nativeCategory\",\"months\",\"seconds\"))\n stopifnot(nrow(nls)==3613,nrow(ch)==3150,identical(as.integer(ch$sourceRow[ch[[\"Charge  Amount\"]]==\"10\"]),c(474L,2174L,2274L,2374L,2674L,2924L,2974L)))\n result<-list(country=country,person=person,company=company)\n for(k in names(result)){d<-result[[k]];n<-length(d$id);d$eligible<-!is.na(d$y)&rowSums(is.na(d$x))==0;hash<-sha256(paste0(\"ML14-role|\",k,\"|\",d$id));rank<-integer(n);rank[order(hash,seq_len(n))]<-seq_len(n)-1L;d$plannedRole<-ifelse(rank%%5==0,\"test\",ifelse(rank%%5==1,\"validation\",\"train\"));d$role<-ifelse(d$eligible,d$plannedRole,\"excluded\");result[[k]]<-d}\n stopifnot(sum(result$person$eligible)==3017);result\n}\nfitmodel<-function(d){\n ids<-which(d$role==\"train\");p<-ncol(d$x);m<-vapply(seq_len(p),function(j)if((j-1)%in%d$cat)NA_real_ else median(d$x[ids,j]),numeric(1));z<-d$x\n for(j in seq_len(p))if(!((j-1)%in%d$cat))z[,j]<-as.numeric(z[,j]>m[j])\n keys<-apply(z,1,function(v)paste(fmt(v),collapse=\"|\"));lev<-unique(keys[ids]);mass<-vapply(lev,function(k)sum(keys[ids]==k),integer(1));positive<-vapply(lev,function(k)sum(d$y[ids][keys[ids]==k]),integer(1));prob<-(positive+1)/(mass+2);fallback<-(sum(d$y[ids])+1)/(length(ids)+2);pred<-prob[match(keys,lev)];unseen<-is.na(pred);pred[unseen]<-fallback;pred[!d$eligible]<-NA_real_;unseen[!d$eligible]<-NA\n list(ids=ids,medians=m,z=z,keys=keys,lev=lev,mass=mass,positive=positive,prob=prob,fallback=fallback,pred=pred,unseen=unseen)\n}\nmeasure<-function(d,p,ids,t=.5,cost=c(1,1)){\n use<-ids[d$eligible[ids]&!is.na(p[ids])];y<-d$y[use];a<-if(is.character(t))rep(t==\"always-positive\",length(use))else p[use]>=t\n TP<-sum(a&y==1);FP<-sum(a&y==0);FN<-sum(!a&y==1);TN<-sum(!a&y==0);P<-TP+FN;N<-FP+TN;W<-P+N;PP<-TP+FP;PN<-TN+FN;TPR<-ratio(TP,P);TNR<-ratio(TN,N);bs<-sum((p[use]-y)^2);tc<-FP*cost[1]+FN*cost[2]\n list(TP=TP,FP=FP,FN=FN,TN=TN,mass=W,positiveTargetMass=P,negativeTargetMass=N,predictedPositiveMass=PP,predictedNegativeMass=PN,prevalence=ratio(P,W),selectionRate=ratio(PP,W),accuracy=ratio(TP+TN,W),precision=ratio(TP,PP),negativePredictiveValue=ratio(TN,PN),TPR=TPR,FPR=ratio(FP,N),TNR=TNR,FNR=ratio(FN,P),F1=ratio(2*TP,2*TP+FP+FN),balancedAccuracy=if(is.na(TPR)||is.na(TNR))NA_real_ else(TPR+TNR)/2,Brier=ratio(bs,W),BrierSum=bs,totalCost=tc,meanCost=ratio(tc,W))\n}\ncurves<-function(d,p,ids){\n use<-ids[d$eligible[ids]&!is.na(p[ids])];scores<-sort(unique(p[use]),decreasing=TRUE);policies<-c(list(\"always-negative\"),as.list(scores));points<-lapply(policies,function(t){m<-measure(d,p,ids,t);c(list(policy=t),m[c(\"TP\",\"FP\",\"FN\",\"TN\",\"TPR\",\"FPR\",\"precision\")],list(recall=m$TPR))})\n pos<-use[d$y[use]==1];neg<-use[d$y[use]==0];U<-0;for(i in pos)U<-U+sum(p[i]>p[neg])+.5*sum(p[i]==p[neg])\n AP<-0;trap<-0;lastR<-0;lastP<-1\n if(length(pos)&&length(scores))for(j in seq_along(scores)){z<-points[[j+1]];AP<-AP+(z$recall-lastR)*z$precision;trap<-trap+(z$recall-lastR)*(z$precision+lastP)/2;lastR<-z$recall;lastP<-z$precision}\n list(points=points,ROC_AUC=ratio(U,length(pos)*length(neg)),averagePrecision=if(length(pos))AP else NA_real_,PRTrapezoidWithInitialPrecisionOne=if(length(pos))trap else NA_real_)\n}\ncalibrate<-function(d,p,ids){\n use<-ids[d$eligible[ids]&!is.na(p[ids])];W<-length(use);pi<-if(W)mean(d$y[use])else NA_real_;bins<-list();ECE<-rel<-res<-correction<-0\n whichbin<-findInterval(p[use],seq(0,1,.2),rightmost.closed=TRUE,all.inside=TRUE)\n for(b in 1:5){rr<-use[whichbin==b];w<-length(rr);mp<-if(w)mean(p[rr])else NA_real_;o<-if(w)mean(d$y[rr])else NA_real_;variance<-if(w)mean((p[rr]-mp)^2)else NA_real_;covariance<-if(w)mean((p[rr]-mp)*(d$y[rr]-o))else NA_real_;bc<-variance-2*covariance;gap<-mp-o\n  bins[[b]]<-list(mass=w,meanPrediction=mp,eventRate=o,gap=gap,absoluteGap=abs(gap),scoreVariance=variance,scoreTargetCovariance=covariance,withinBinCorrection=bc,rows=w,ids=d$id[rr])\n  if(w){share<-w/W;ECE<-ECE+share*abs(gap);rel<-rel+share*gap^2;res<-res+share*(o-pi)^2;correction<-correction+share*bc}\n };bs<-if(W)mean((p[use]-d$y[use])^2)else NA_real_;unc<-pi*(1-pi)\n list(bins=bins,ECE=if(W)ECE else NA_real_,Brier=bs,reliability=if(W)rel else NA_real_,resolution=if(W)res else NA_real_,uncertainty=unc,withinBinCorrection=if(W)correction else NA_real_,BrierIdentityResidual=bs-(unc-res+rel+correction))\n}\ncounts<-c(\"mass\",\"positiveTargetMass\",\"negativeTargetMass\",\"predictedPositiveMass\",\"predictedNegativeMass\");rates<-c(\"prevalence\",\"selectionRate\",\"accuracy\",\"precision\",\"negativePredictiveValue\",\"TPR\",\"FPR\",\"TNR\",\"FNR\",\"F1\",\"balancedAccuracy\",\"Brier\",\"BrierSum\",\"totalCost\",\"meanCost\")\ntables<-setNames(lapply(1:10,function(i)list()),c(\"predictions\",\"lineage\",\"fit-medians\",\"fit-cells\",\"validation-candidates\",\"test-metrics\",\"test-curves\",\"calibration-bins\",\"group-metrics\",\"chart-points\"))\nadd<-function(name,row)tables[[name]][[length(tables[[name]])+1L]]<<-row\nscalars<-function(m,keys){out<-list();for(k in keys){out[[paste0(k,\"Exact\")]]<-\"\";out[[paste0(k,\"Approx\")]]<-fmt(m[[k]])};out}\ntagrow<-function(kind,...)c(list(kind=kind),list(...))\npoint<-function(kind,chart,series,index,x,y,xunit=\"dimensionless\",yunit=\"dimensionless\",role=\"test\",tag=\"\"){add(\"chart-points\",tagrow(kind,chart=chart,series=series,index=index,xExact=\"\",xApprox=fmt(x),yExact=\"\",yApprox=fmt(y),xUnit=xunit,yUnit=yunit,role=role,tag=tag))}\nstudy<-function(kind,d){\n f<-fitmodel(d);n<-length(d$id);train<-which(d$role==\"train\");validation<-which(d$role==\"validation\");test<-which(d$role==\"test\");p<-f$pred;cv<-curves(d,p,test);cal<-calibrate(d,p,test)\n for(i in seq_len(n)){\n  reason<-if(d$eligible[i])\"\"else\"required-X-or-Y-missing\";transformed<-if(d$eligible[i])paste(fmt(f$z[i,]),collapse=\"|\")else\"\"\n  add(\"predictions\",tagrow(kind,id=d$id[i],sourceRow=d$sourceRow[i],originalID=d$originalID[i],plannedRole=d$plannedRole[i],role=d$role[i],group=ifelse(is.na(d$group[i]),\"\",d$group[i]),eligible=as.integer(d$eligible[i]),targetExact=fmt(d$y[i]),probabilityExact=\"\",probabilityApprox=fmt(p[i]),unseenCell=ifelse(is.na(f$unseen[i]),\"\",as.character(as.integer(f$unseen[i]))),transformedX=transformed,reason=reason))\n  raw<-d$rawX[i,];raw[raw%in%c(\"\",\".\")]<-\"\";nativeY<-d$nativeTarget[i];if(nativeY%in%c(\"\",\".\"))nativeY<-\"\"\n  add(\"lineage\",tagrow(kind,id=d$id[i],sourceRow=d$sourceRow[i],originalID=d$originalID[i],nativeSourceRows=d$lineage[i],rawX=paste(raw,collapse=\"|\"),nativeTarget=nativeY,derivedTarget=fmt(d$y[i]),nativeGroup=ifelse(is.na(d$group[i]),\"\",d$group[i]),plannedRole=d$plannedRole[i],role=d$role[i],eligible=as.integer(d$eligible[i]),analyticalMass=\"1\",reason=reason))\n }\n for(j in seq_len(ncol(d$x)))add(\"fit-medians\",tagrow(kind,feature=j-1,categorical=as.integer((j-1)%in%d$cat),fitRows=length(train),medianExact=\"\",medianApprox=fmt(f$medians[j]),unit=d$units[j]))\n for(j in seq_along(f$lev))add(\"fit-cells\",tagrow(kind,cell=f$lev[j],trainingRows=f$mass[j],positiveRows=f$positive[j],probabilityExact=\"\",probabilityApprox=fmt(f$prob[j]),fallbackExact=\"\",fallbackApprox=fmt(f$fallback)))\n for(j in seq_along(cv$points)){\n  z<-cv$points[[j]];t<-z$policy;add(\"test-curves\",c(tagrow(kind,point=j-1,policy=if(is.character(t))t else\"threshold\",thresholdExact=\"\",thresholdApprox=if(is.character(t))\"\"else fmt(t)),scalars(z,c(\"TP\",\"FP\",\"FN\",\"TN\",\"TPR\",\"FPR\",\"precision\",\"recall\"))))\n  point(kind,\"roc\",\"ROC\",j-1,z$FPR,z$TPR);point(kind,\"pr\",\"PR-observed\",j-1,z$recall,z$precision)\n }\n for(b in 1:5){z<-cal$bins[[b]];add(\"calibration-bins\",c(tagrow(kind,bin=b-1,leftExact=c(\"0\",\"1/5\",\"2/5\",\"3/5\",\"4/5\")[b],rightExact=c(\"1/5\",\"2/5\",\"3/5\",\"4/5\",\"1\")[b],rightClosed=as.integer(b==5),rows=z$rows,ids=paste(z$ids,collapse=\";\")),scalars(z,c(\"mass\",\"meanPrediction\",\"eventRate\",\"gap\",\"absoluteGap\",\"scoreVariance\",\"scoreTargetCovariance\",\"withinBinCorrection\"))));point(kind,\"reliability\",\"Binary event rate\",b-1,z$meanPrediction,z$eventRate,tag=paste0(\"rows=\",z$rows))}\n for(j in seq_along(test)){i<-test[j];point(kind,\"test-scores\",\"Training-fitted probability\",j-1,j,p[i],\"test-row position\",\"probability\",tag=d$id[i]);point(kind,\"test-scores\",\"Observed Y\",j-1,j,d$y[i],\"test-row position\",\"binary target\",tag=d$id[i])}\n scenarioNames<-c(\"equal\",\"miss-five\",\"alarm-five\");costs<-list(c(1,1),c(1,5),c(5,1))\n for(s in 1:3){name<-scenarioNames[s];cost<-costs[[s]];grid<-c(list(\"always-negative\"),as.list(sort(unique(p[validation]),decreasing=TRUE)));candidates<-lapply(grid,function(t)measure(d,p,validation,t,cost));values<-vapply(candidates,function(m)m$meanCost,numeric(1));best<-which(values<=min(values)+1e-12)[1];chosen<-grid[[best]];ev<-measure(d,p,test,chosen,cost)\n  for(j in seq_along(grid)){t<-grid[[j]];m<-candidates[[j]];cell<-setNames(lapply(c(\"TP\",\"FP\",\"FN\",\"TN\"),function(k)fmt(m[[k]])),paste0(c(\"TP\",\"FP\",\"FN\",\"TN\"),\"Exact\"));add(\"validation-candidates\",c(tagrow(kind,scenario=name,candidate=j-1,selected=as.integer(j==best),policy=if(is.character(t))t else\"threshold\",thresholdExact=\"\",thresholdApprox=if(is.character(t))\"\"else fmt(t),feasible=1,reasons=\"\"),cell,scalars(m,c(counts,\"TPR\",\"FPR\",\"precision\",\"meanCost\",\"totalCost\"))));point(kind,\"validation-cost\",name,j-1,j-1,m$meanCost,\"candidate index\",\"hypothetical cost units/mass\",\"validation\",if(is.character(t))t else fmt(t))}\n  m<-c(ev,cv[c(\"ROC_AUC\",\"averagePrecision\",\"PRTrapezoidWithInitialPrecisionOne\")],cal[c(\"ECE\",\"reliability\",\"resolution\",\"uncertainty\",\"withinBinCorrection\",\"BrierIdentityResidual\")])\n  for(k in c(\"TP\",\"FP\",\"FN\",\"TN\",counts,rates,\"ROC_AUC\",\"averagePrecision\",\"PRTrapezoidWithInitialPrecisionOne\",\"ECE\",\"reliability\",\"resolution\",\"uncertainty\",\"withinBinCorrection\",\"BrierIdentityResidual\")){\n   unit<-if(k%in%c(\"TP\",\"FP\",\"FN\",\"TN\",counts))\"rows\"else if(k==\"totalCost\")\"hypothetical cost units\"else if(k==\"meanCost\")\"hypothetical cost units/mass\"else if(k==\"BrierSum\")\"sum squared-probability loss\"else\"dimensionless\"\n   add(\"test-metrics\",tagrow(kind,scenario=name,metric=k,valueExact=\"\",valueApprox=fmt(m[[k]]),unit=unit))\n  }\n  lev<-unique(d$group[test][!is.na(d$group[test])]);sets<-c(list(test),lapply(lev,function(g)test[!is.na(d$group[test])&d$group[test]==g]),list(test[is.na(d$group[test])]))\n  types<-c(\"overall\",rep(\"known\",length(lev)),\"unknown\");tokens<-c(\"all\",lev,\"\")\n  for(j in seq_along(sets)){ids<-sets[[j]];m<-measure(d,p,ids,chosen,cost);cell<-setNames(lapply(c(\"TP\",\"FP\",\"FN\",\"TN\"),function(k)fmt(m[[k]])),paste0(c(\"TP\",\"FP\",\"FN\",\"TN\"),\"Exact\"));add(\"group-metrics\",c(tagrow(kind,scenario=name,groupType=types[j],groupToken=tokens[j],retainedRows=length(ids)),cell,scalars(m,c(counts,rates))));if(types[j]==\"known\")point(kind,\"group-TPR\",name,j-2,j-2,m$TPR,\"declared group position\",\"TPR\",tag=tokens[j])}\n }\n invisible(NULL)\n}\n\n# Fixed finite inputs only; not the complete web input/budget validator.\nqnum<-function(v){if(is.null(v))return(NA_real_);if(is.logical(v))return(as.numeric(v));s<-as.character(v);if(grepl(\"/\",s,fixed=TRUE)){a<-strsplit(s,\"/\",fixed=TRUE)[[1]];return(as.numeric(a[1])/as.numeric(a[2]))};as.numeric(s)}\nrowsG<-function(raw){\n n<-length(raw);get<-function(r,k,default=NULL)if(is.null(r[[k]]))default else r[[k]]\n id<-vapply(raw,function(r)as.character(r$id),character(1));p<-vapply(raw,function(r)qnum(r$score),numeric(1));y<-vapply(raw,function(r)qnum(r$y),numeric(1));w<-vapply(raw,function(r)qnum(get(r,\"weight\",\"1\")),numeric(1));role<-vapply(raw,function(r)get(r,\"role\",\"evaluation\"),character(1));group<-vapply(raw,function(r)as.character(get(r,\"group\",NA_character_)),character(1))\n stopifnot(all(w>=0),all(is.na(p)|(p>=0&p<=1)),all(is.na(y)|y%in%c(0,1)),!anyDuplicated(id));list(id=id,p=p,y=y,w=w,role=role,group=group,eligible=!is.na(p)&!is.na(y)&w>0&role!=\"excluded\")\n}\nscopeG<-function(d,role=\"all\")if(role==\"all\")seq_along(d$id)else which(d$role==role)\nmetricsG<-function(d,ids,t=.5,cost=c(1,1)){\n use<-ids[d$eligible[ids]];p<-d$p[use];y<-d$y[use];w<-d$w[use];a<-if(is.character(t))rep(t==\"always-positive\",length(use))else p>=t\n TP<-sum(w[a&y==1]);FP<-sum(w[a&y==0]);FN<-sum(w[!a&y==1]);TN<-sum(w[!a&y==0]);P<-TP+FN;N<-FP+TN;W<-P+N;PP<-TP+FP;PN<-TN+FN;TPR<-ratio(TP,P);TNR<-ratio(TN,N);bs<-sum(w*(p-y)^2);tc<-FP*cost[1]+FN*cost[2]\n list(confusion=list(TP=TP,FP=FP,FN=FN,TN=TN),mass=W,positiveTargetMass=P,negativeTargetMass=N,predictedPositiveMass=PP,predictedNegativeMass=PN,prevalence=ratio(P,W),selectionRate=ratio(PP,W),accuracy=ratio(TP+TN,W),precision=ratio(TP,PP),negativePredictiveValue=ratio(TN,PN),TPR=TPR,FPR=ratio(FP,N),TNR=TNR,FNR=ratio(FN,P),F1=ratio(2*TP,2*TP+FP+FN),balancedAccuracy=if(is.na(TPR)||is.na(TNR))NA_real_ else(TPR+TNR)/2,Brier=ratio(bs,W),BrierSum=bs,totalCost=tc,meanCost=ratio(tc,W),bayesThreshold=ratio(cost[1],sum(cost)))\n}\ncurvesG<-function(d,ids){\n use<-ids[d$eligible[ids]];grid<-c(list(\"always-negative\"),as.list(sort(unique(d$p[use]),decreasing=TRUE)));points<-lapply(grid,function(t){m<-metricsG(d,ids,t);c(list(policy=t),m$confusion,m[c(\"TPR\",\"FPR\",\"precision\")],list(recall=m$TPR))});pos<-use[d$y[use]==1];neg<-use[d$y[use]==0];P<-sum(d$w[pos]);N<-sum(d$w[neg]);U<-0\n for(i in pos)U<-U+d$w[i]*sum(d$w[neg]*((d$p[i]>d$p[neg])+.5*(d$p[i]==d$p[neg])))\n AP<-trap<-lastR<-0;lastP<-1\n if(P&&length(grid)>1)for(j in 2:length(grid)){z<-points[[j]];AP<-AP+(z$recall-lastR)*z$precision;trap<-trap+(z$recall-lastR)*(z$precision+lastP)/2;lastR<-z$recall;lastP<-z$precision}\n list(points=points,ROC_AUC=ratio(U,P*N),averagePrecision=if(P)AP else NA_real_,PRTrapezoidWithInitialPrecisionOne=if(P)trap else NA_real_)\n}\nchooseG<-function(d,a,cost){\n role<-if(is.null(a$selectionRole))\"validation\"else a$selectionRole;er<-if(is.null(a$evaluationRole))\"test\"else a$evaluationRole;ids<-scopeG(d,role);use<-ids[d$eligible[ids]];stopifnot(length(use)>0);grid<-if(is.null(a$thresholds))c(list(\"always-negative\"),as.list(sort(unique(d$p[use]),decreasing=TRUE)))else lapply(a$thresholds,function(t)if(t%in%c(\"always-negative\",\"always-positive\"))t else qnum(t))\n candidates<-lapply(seq_along(grid),function(j){m<-metricsG(d,ids,grid[[j]],cost);feasible<-TRUE;if(!is.null(a$minTPR))feasible<-feasible&&!is.na(m$TPR)&&m$TPR>=qnum(a$minTPR);if(!is.null(a$maxFPR))feasible<-feasible&&!is.na(m$FPR)&&m$FPR<=qnum(a$maxFPR);list(index=j-1,policy=grid[[j]],metrics=m,feasible=feasible)})\n good<-which(vapply(candidates,function(c)c$feasible,logical(1)));best<-NA_integer_;if(length(good)){v<-vapply(candidates[good],function(c)c$metrics$meanCost,numeric(1));best<-good[which(v<=min(v)+1e-12)[1]]}\n list(selectedIndex=if(is.na(best))NA_integer_ else best-1,selectedPolicy=if(is.na(best))NULL else grid[[best]],selectedValidation=if(is.na(best))NULL else candidates[[best]]$metrics,candidates=candidates,evaluation=if(is.na(best)||er==\"none\")NULL else metricsG(d,scopeG(d,er),grid[[best]],cost))\n}\ncalibrateG<-function(d,ids,edges){\n use<-ids[d$eligible[ids]];W<-sum(d$w[use]);pi<-ratio(sum(d$w[use]*d$y[use]),W);bins<-list();ECE<-rel<-res<-correction<-0;assign<-findInterval(d$p[use],edges,rightmost.closed=TRUE,all.inside=TRUE)\n for(b in seq_len(length(edges)-1)){rr<-use[assign==b];w<-sum(d$w[rr]);mp<-ratio(sum(d$w[rr]*d$p[rr]),w);o<-ratio(sum(d$w[rr]*d$y[rr]),w);variance<-if(w)sum(d$w[rr]*(d$p[rr]-mp)^2)/w else NA_real_;covariance<-if(w)sum(d$w[rr]*(d$p[rr]-mp)*(d$y[rr]-o))/w else NA_real_;bc<-variance-2*covariance;gap<-mp-o;bins[[b]]<-list(index=b-1,mass=w,meanPrediction=mp,eventRate=o,scoreVariance=variance,scoreTargetCovariance=covariance,withinBinCorrection=bc,ids=d$id[rr])\n  if(w){s<-w/W;ECE<-ECE+s*abs(gap);rel<-rel+s*gap^2;res<-res+s*(o-pi)^2;correction<-correction+s*bc}\n };bs<-ratio(sum(d$w[use]*(d$p[use]-d$y[use])^2),W);unc<-pi*(1-pi);list(bins=bins,Brier=bs,ECE=if(W)ECE else NA_real_,uncertainty=unc,reliability=if(W)rel else NA_real_,resolution=if(W)res else NA_real_,withinBinCorrection=if(W)correction else NA_real_,BrierIdentityResidual=bs-(unc-res+rel+correction))\n}\ngroupsG<-function(d,ids,t,cost){\n lev<-unique(d$group[ids][!is.na(d$group[ids])]);groups<-lapply(lev,function(g)list(group=g,metrics=metricsG(d,ids[!is.na(d$group[ids])&d$group[ids]==g],t,cost)));overall<-metricsG(d,ids,t,cost);unknown<-metricsG(d,ids[is.na(d$group[ids])],t,cost);gaps<-list()\n for(k in c(\"prevalence\",\"selectionRate\",\"TPR\",\"FPR\",\"precision\",\"accuracy\",\"meanCost\")){use<-Filter(function(g)g$metrics$mass>0,groups);v<-vapply(use,function(g)g$metrics[[k]],numeric(1));gaps[[k]]<-if(length(use)<2||anyNA(v))NA_real_ else max(v)-min(v)}\n list(overall=overall,groups=groups,unknownGroup=unknown,gaps=gaps,partitionMassResidual=overall$mass-unknown$mass-sum(vapply(groups,function(g)g$metrics$mass,numeric(1))))\n}\nsvgFixed<-function(file,points,title,xlabel,ylabel,legend){\n finite<-points[points$y!=\"undefined\"&points$x!=\"undefined\",,drop=FALSE];x<-as.numeric(finite$x);y<-as.numeric(finite$y);xmin<-if(length(x))min(x)else 0;xmax<-if(length(x))max(x)else 1;ymin<-min(c(0,y));ymax<-max(c(0,y));if(xmin==xmax){xmin<-xmin-.5;xmax<-xmax+.5};if(ymin==ymax)ymax<-ymin+1;X<-function(v)85+(v-xmin)/(xmax-xmin)*480;Y<-function(v)278-(v-ymin)/(ymax-ymin)*175\n esc<-function(s){s<-gsub(\"&\",\"&amp;\",s,fixed=TRUE);s<-gsub(\"<\",\"&lt;\",s,fixed=TRUE);gsub(\">\",\"&gt;\",s,fixed=TRUE)};s<-'<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"620\" height=\"360\" viewBox=\"0 0 620 360\"><rect width=\"620\" height=\"360\" fill=\"white\"/><g font-family=\"Arial, sans-serif\" font-size=\"13\" fill=\"#17324d\">'\n lines<-strwrap(title,width=65);for(i in seq_along(lines))s<-paste0(s,'<text x=\"25\" y=\"',24+(i-1)*18,'\">',esc(lines[i]),'</text>');colors<-c(\"#176b9b\",\"#b85e18\",\"#437e4d\")\n for(i in seq_along(legend))s<-paste0(s,'<circle cx=\"',30+(i-1)*250,'\" cy=\"76\" r=\"4\" fill=\"',colors[(i-1)%%3+1],'\"/><text x=\"',42+(i-1)*250,'\" y=\"80\">',esc(legend[i]),'</text>')\n s<-paste0(s,'<path d=\"M85 98V278H575\" fill=\"none\" stroke=\"#52677d\"/><text text-anchor=\"middle\" x=\"325\" y=\"338\">',esc(xlabel),'</text><text text-anchor=\"middle\" transform=\"translate(21,190) rotate(-90)\">',esc(ylabel),'</text>')\n for(i in 0:4){xx<-xmin+(xmax-xmin)*i/4;yy<-ymin+(ymax-ymin)*i/4;s<-paste0(s,'<text text-anchor=\"middle\" x=\"',sprintf(\"%.9g\",X(xx)),'\" y=\"305\">',sprintf(\"%.4g\",xx),'</text><text text-anchor=\"end\" x=\"77\" y=\"',sprintf(\"%.9g\",Y(yy)+4),'\">',sprintf(\"%.4g\",yy),'</text>')}\n for(i in seq_len(nrow(finite)))s<-paste0(s,'<circle cx=\"',sprintf(\"%.9g\",X(x[i])),'\" cy=\"',sprintf(\"%.9g\",Y(y[i])),'\" r=\"3\" fill=\"',colors[as.integer(finite$series[i])%%3+1],'\"/>');writeLines(paste0(s,'</g></svg>'),file,useBytes=TRUE)\n}\nfixedRun<-function(){\n api<-FIXED$api;a<-FIXED$args;summary<-list();points<-list();xlabel<-\"Declared index\";ylabel<-\"Value\";legend<-\"Declared result\"\n metric<-function(name,v,unit=\"dimensionless\"){if(is.null(v))v<-NA_real_;summary[[length(summary)+1L]]<<-data.frame(metric=name,value=if(is.na(v))\"undefined\"else sprintf(\"%.9g\",v),exactValue=\"\",unit=unit,defined=as.integer(!is.na(v)),stringsAsFactors=FALSE)}\n pt<-function(i,x,y,id=\"\",series=0){points[[length(points)+1L]]<<-data.frame(series=series,index=i,xExact=\"\",x=if(is.na(x))\"undefined\"else sprintf(\"%.9g\",x),yExact=\"\",y=if(is.na(y))\"undefined\"else sprintf(\"%.9g\",y),id=as.character(id),stringsAsFactors=FALSE)}\n if(api==\"realdata\"){\n  native<-loadData()[[a$kind]];fit<-fitmodel(native);d<-list(id=native$id,p=fit$pred,y=native$y,w=rep(1,length(native$id)),role=native$role,group=native$group,eligible=native$eligible);scenarios<-list()\n  for(j in 1:3){name<-c(\"equal\",\"miss-five\",\"alarm-five\")[j];cst<-list(c(1,1),c(1,5),c(5,1))[[j]];sel<-chooseG(d,list(),cst);scenarios[[j]]<-list(name=name,selection=sel);metric(paste0(name,\"Threshold\"),sel$selectedPolicy);metric(paste0(name,\"TestCost\"),sel$evaluation$meanCost,\"hypothetical cost units/mass\")}\n  ids<-scopeG(d,\"test\");cv<-curvesG(d,ids);cal<-calibrateG(d,ids,seq(0,1,.2));metric(\"testAUC\",cv$ROC_AUC);metric(\"testAP\",cv$averagePrecision);metric(\"testBrier\",cal$Brier);metric(\"eligibleRows\",sum(d$eligible),\"rows\")\n  for(j in seq_along(ids)){i<-ids[j];pt(j-1,j,d$p[i],d$id[i],0);pt(j-1,j,d$y[i],d$id[i],1)}\n  full<-list(kind=a$kind,fit=fit,scenarios=scenarios,testCurves=cv,testCalibration=cal,rowsScored=d);xlabel<-\"Test row, native order\";ylabel<-\"Y or probability\";legend<-c(\"Training-fitted probability\",\"Observed Y\")\n }else{\n  d<-rowsG(a$rows);role<-if(is.null(a$role))\"all\"else a$role;ids<-scopeG(d,role);cost<-if(is.null(a$costs))c(1,1)else c(qnum(a$costs$falsePositive),qnum(a$costs$falseNegative));t<-if(is.null(a$threshold)).5 else if(a$threshold%in%c(\"always-positive\",\"always-negative\"))a$threshold else qnum(a$threshold)\n  if(api==\"metrics\"){\n   full<-metricsG(d,ids,t,cost);for(k in c(\"mass\",\"accuracy\",\"precision\",\"TPR\",\"FPR\",\"F1\",\"Brier\",\"meanCost\"))metric(k,full[[k]],if(k==\"mass\")\"mass\"else if(k==\"meanCost\")\"hypothetical cost units/mass\"else\"dimensionless\");metric(\"BayesThreshold\",full$bayesThreshold)\n   for(i in 1:4)pt(i-1,i-1,full$confusion[[i]],names(full$confusion)[i]);xlabel<-\"TP / FP / FN / TN positions\";ylabel<-\"Analytical mass\"\n  }else if(api==\"curves\"){\n   full<-curvesG(d,ids);for(k in c(\"ROC_AUC\",\"averagePrecision\",\"PRTrapezoidWithInitialPrecisionOne\"))metric(k,full[[k]])\n   for(j in seq_along(full$points)){p<-full$points[[j]];pt(j-1,p$FPR,p$TPR,if(is.character(p$policy))p$policy else sprintf(\"%.17g\",p$policy))};xlabel<-\"False positive rate\";ylabel<-\"True positive rate\";legend<-\"Observed ROC operating points\"\n  }else if(api==\"choose\"){\n   full<-chooseG(d,a,cost);metric(\"selectedIndex\",full$selectedIndex,\"candidate index\");metric(\"minimumCost\",if(is.null(full$selectedValidation))NULL else full$selectedValidation$meanCost,\"hypothetical cost units/mass\");metric(\"feasible\",as.integer(!is.na(full$selectedIndex)),\"indicator\")\n   for(c in full$candidates)pt(c$index,c$index,c$metrics$meanCost,if(is.character(c$policy))c$policy else sprintf(\"%.17g\",c$policy));xlabel<-\"Validation candidate\";ylabel<-\"Assumed cost / mass\";legend<-\"Validation candidate costs\"\n  }else if(api==\"calibrate\"){\n   edges<-if(is.null(a$binEdges))seq(0,1,.2)else vapply(a$binEdges,qnum,numeric(1));full<-calibrateG(d,ids,edges);for(k in c(\"ECE\",\"Brier\",\"uncertainty\",\"resolution\",\"reliability\",\"withinBinCorrection\",\"BrierIdentityResidual\"))metric(k,full[[k]])\n   for(b in full$bins)pt(b$index,b$meanPrediction,b$eventRate,paste0(\"bin:\",b$index));xlabel<-\"Bin mean forecast\";ylabel<-\"Bin event rate\";legend<-\"Binary-event reliability\"\n  }else if(api==\"groups\"){\n   full<-groupsG(d,ids,t,cost);metric(\"overallTPR\",full$overall$TPR);metric(\"TPRGap\",full$gaps$TPR);metric(\"precisionGap\",full$gaps$precision);metric(\"unknownMass\",full$unknownGroup$mass,\"mass\");metric(\"partitionResidual\",full$partitionMassResidual,\"mass\")\n   for(j in seq_along(full$groups))pt(j-1,j-1,full$groups[[j]]$metrics$TPR,full$groups[[j]]$group);xlabel<-\"Declared group position\";ylabel<-\"True positive rate\";legend<-\"Known-group TPR\"\n  }else stop(\"unknown declared fixed API\")\n }\n sm<-do.call(rbind,summary);pp<-do.call(rbind,points);write.csv(sm,file.path(outDir,\"summary.csv\"),row.names=FALSE,na=\"\");write.csv(pp,file.path(outDir,\"plot-points.csv\"),row.names=FALSE,na=\"\");svgFixed(file.path(outDir,\"plot.svg\"),pp,FIXED$title,xlabel,ylabel,legend);dput(list(api=api,variant=FIXED$variant,input=FIXED$args,arithmetic=\"Base-R binary64 fixed example; not an exact rational general validator\",result=full),file=file.path(outDir,\"full.txt\"));cat(\"PASS\",api,FIXED$variant,\"summary\",nrow(sm),\"points\",nrow(pp),\"\\n\")\n}\n\nFIXED<-list(api=\"curves\",variant=\"all-tied\",args=list(rows=list(list(id=\"a\",score=\".5\",y=1,group=\"A\"),list(id=\"b\",score=\".5\",y=1,group=\"A\"),list(id=\"c\",score=\".5\",y=0,group=\"A\"),list(id=\"d\",score=\".5\",y=0,group=\"B\"),list(id=\"e\",score=\".5\",y=1,group=\"B\"),list(id=\"f\",score=\".5\",y=0,group=\"B\"))),title=\"All scores tied: half pair credit and prevalence AP\")\nfixedRun()\n",
        "codeText": "# ML14 standalone public counterpart, base R only.\n# Inputs are only the three factual CSVs; derived columns/previous model answers unused.\n# Binary64 arithmetic, not arbitrary-precision Fraction. At numerical cost ties\n# within 1e-12 retain the earliest candidate. Exact claims belong to Python/web.\n# SHA256 infrastructure below is reused verbatim from the previous public study.\nargs<-commandArgs(trailingOnly=TRUE);filearg<-grep(\"^--file=\",commandArgs(),value=TRUE)\nhere<-if(dir.exists(\"ml14-sources\"))getwd()else if(length(filearg))dirname(normalizePath(sub(\"^--file=\",\"\",filearg[1])))else getwd()\noption<-function(key,default){i<-match(key,args);if(is.na(i))default else args[i+1]}\nsourceDir<-option(\"--source\",file.path(here,\"ml14-sources\"));outDir<-option(\"--out\",file.path(getwd(),\"ml14-r-results\"));dir.create(outDir,recursive=TRUE,showWarnings=FALSE)\nnum<-function(x){x[x%in%c(\"\",\".\")]<-NA_character_;as.numeric(x)}\nfmt<-function(x)ifelse(is.na(x),\"\",sprintf(\"%.17g\",x))\nratio<-function(a,b)if(b==0)NA_real_ else a/b\nreadnative<-function(name)read.csv(file.path(sourceDir,name),check.names=FALSE,colClasses=\"character\",na.strings=character(),stringsAsFactors=FALSE)\n# Vectorized SHA256 for the short ASCII keys used in this study.\n# Unsigned words use exact integer-valued doubles; bit operations use safe\n# 16-bit halves, avoiding R's reserved signed-INT_MIN/NA representation.\nMOD<-2^32\nxor32<-function(a,b) as.double(bitwXor(as.integer(floor(a/65536)),as.integer(floor(b/65536))))*65536+as.double(bitwXor(as.integer(a%%65536),as.integer(b%%65536)))\nand32<-function(a,b) as.double(bitwAnd(as.integer(floor(a/65536)),as.integer(floor(b/65536))))*65536+as.double(bitwAnd(as.integer(a%%65536),as.integer(b%%65536)))\nrot<-function(x,n) floor(x/2^n)+(x%%2^n)*2^(32-n)\nxor3<-function(a,b,c) xor32(xor32(a,b),c)\nK<-c(0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5,0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967,0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070,0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3,0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2)\nsha256<-function(strings) {\n n<-length(strings);bytes<-matrix(0,n,64)\n for(i in seq_len(n)) {v<-utf8ToInt(strings[i]);stopifnot(length(v)<56,all(v<128));if(length(v)) bytes[i,seq_along(v)]<-v;bytes[i,length(v)+1]<-128;bits<-length(v)*8;bytes[i,61:64]<-c(floor(bits/2^24)%%256,floor(bits/2^16)%%256,floor(bits/256)%%256,bits%%256)}\n w<-matrix(0,n,64)\n for(j in 1:16) {b<-4*(j-1)+1;w[,j]<-bytes[,b]*2^24+bytes[,b+1]*2^16+bytes[,b+2]*256+bytes[,b+3]}\n for(j in 17:64) {s0<-xor3(rot(w[,j-15],7),rot(w[,j-15],18),floor(w[,j-15]/8));s1<-xor3(rot(w[,j-2],17),rot(w[,j-2],19),floor(w[,j-2]/1024));w[,j]<-(w[,j-16]+s0+w[,j-7]+s1)%%MOD}\n init<-c(0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19)\n state<-lapply(init,function(v) rep(v,n));a<-state[[1]];b<-state[[2]];c<-state[[3]];d<-state[[4]];e<-state[[5]];f<-state[[6]];g<-state[[7]];h<-state[[8]]\n for(j in 1:64) {S1<-xor3(rot(e,6),rot(e,11),rot(e,25));ch<-xor32(and32(e,f),and32(MOD-1-e,g));t1<-(h+S1+ch+K[j]+w[,j])%%MOD;S0<-xor3(rot(a,2),rot(a,13),rot(a,22));maj<-xor3(and32(a,b),and32(a,c),and32(b,c));t2<-(S0+maj)%%MOD;h<-g;g<-f;f<-e;e<-(d+t1)%%MOD;d<-c;c<-b;b<-a;a<-(t1+t2)%%MOD}\n end<-list(a,b,c,d,e,f,g,h);hex<-lapply(1:8,function(j){v<-(end[[j]]+init[j])%%MOD;paste0(sprintf(\"%04x\",as.integer(floor(v/65536))),sprintf(\"%04x\",as.integer(v%%65536)))})\n do.call(paste0,hex)\n}\nstopifnot(identical(sha256(c(\"abc\",\"\")),c(\"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad\",\"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855\")))\n\nloadData<-function(){\n wb<-readnative(\"actual64-country-four-indicators-original-2024.csv\");codes<-c(\"NY.GDP.PCAP.KD\",\"NY.GDP.MKTP.KD.ZG\",\"FP.CPI.TOTL.ZG\",\"SP.DYN.LE00.IN\");iso<-sort(unique(wb$countryISO3));stopifnot(nrow(wb)==64,length(iso)==16)\n tokens<-t(vapply(iso,function(s)wb$originalValueToken[match(paste(s,codes),paste(wb$countryISO3,wb$indicatorID))],character(4)));vals<-matrix(num(as.vector(tokens)),nrow=nrow(tokens))\n country<-list(id=paste0(iso,\":2024\"),sourceRow=1:16,originalID=iso,x=vals[,1:3,drop=FALSE],rawX=tokens[,1:3,drop=FALSE],nativeTarget=tokens[,4],y=as.integer(vals[,4]>=80),group=ifelse(is.na(vals[,1]),NA_character_,as.character(as.integer(vals[,1]>=25000))),lineage=vapply(iso,function(s)paste(wb$sourceRow[match(paste(s,codes),paste(wb$countryISO3,wb$indicatorID))],collapse=\";\"),character(1)),cat=integer(),units=c(\"constant2015USD/person\",\"annualPercent\",\"annualPercent\"))\n nls<-readnative(\"actual3613-NLS-original52-fields-groups-roles.csv\");raw<-cbind(nls$ed76,nls$age76,nls$nearc4)\n person<-list(id=paste0(\"person:\",nls$sourceRow),sourceRow=as.integer(nls$sourceRow),originalID=nls$id,x=matrix(num(as.vector(raw)),nrow=nrow(raw)),rawX=raw,nativeTarget=nls$wage76,y=as.integer(num(nls$wage76)>=500),group=ifelse(nls$black%in%c(\"\",\".\"),NA_character_,nls$black),lineage=nls$sourceRow,cat=2L,units=c(\"years\",\"years\",\"nativeCategory\"))\n ch<-readnative(\"actual3150-churn-original14-fields-groups-roles.csv\");raw<-cbind(ch[[\"Call  Failure\"]],ch$Complains,ch[[\"Subscription  Length\"]],ch[[\"Seconds of Use\"]])\n company<-list(id=paste0(\"customer:\",ch$sourceRow),sourceRow=as.integer(ch$sourceRow),originalID=rep(\"\",nrow(ch)),x=matrix(num(as.vector(raw)),nrow=nrow(raw)),rawX=raw,nativeTarget=ch$Churn,y=as.integer(ch$Churn),group=ifelse(ch[[\"Tariff Plan\"]]%in%c(\"\",\".\"),NA_character_,ch[[\"Tariff Plan\"]]),lineage=ch$sourceRow,cat=1L,units=c(\"count\",\"nativeCategory\",\"months\",\"seconds\"))\n stopifnot(nrow(nls)==3613,nrow(ch)==3150,identical(as.integer(ch$sourceRow[ch[[\"Charge  Amount\"]]==\"10\"]),c(474L,2174L,2274L,2374L,2674L,2924L,2974L)))\n result<-list(country=country,person=person,company=company)\n for(k in names(result)){d<-result[[k]];n<-length(d$id);d$eligible<-!is.na(d$y)&rowSums(is.na(d$x))==0;hash<-sha256(paste0(\"ML14-role|\",k,\"|\",d$id));rank<-integer(n);rank[order(hash,seq_len(n))]<-seq_len(n)-1L;d$plannedRole<-ifelse(rank%%5==0,\"test\",ifelse(rank%%5==1,\"validation\",\"train\"));d$role<-ifelse(d$eligible,d$plannedRole,\"excluded\");result[[k]]<-d}\n stopifnot(sum(result$person$eligible)==3017);result\n}\nfitmodel<-function(d){\n ids<-which(d$role==\"train\");p<-ncol(d$x);m<-vapply(seq_len(p),function(j)if((j-1)%in%d$cat)NA_real_ else median(d$x[ids,j]),numeric(1));z<-d$x\n for(j in seq_len(p))if(!((j-1)%in%d$cat))z[,j]<-as.numeric(z[,j]>m[j])\n keys<-apply(z,1,function(v)paste(fmt(v),collapse=\"|\"));lev<-unique(keys[ids]);mass<-vapply(lev,function(k)sum(keys[ids]==k),integer(1));positive<-vapply(lev,function(k)sum(d$y[ids][keys[ids]==k]),integer(1));prob<-(positive+1)/(mass+2);fallback<-(sum(d$y[ids])+1)/(length(ids)+2);pred<-prob[match(keys,lev)];unseen<-is.na(pred);pred[unseen]<-fallback;pred[!d$eligible]<-NA_real_;unseen[!d$eligible]<-NA\n list(ids=ids,medians=m,z=z,keys=keys,lev=lev,mass=mass,positive=positive,prob=prob,fallback=fallback,pred=pred,unseen=unseen)\n}\nmeasure<-function(d,p,ids,t=.5,cost=c(1,1)){\n use<-ids[d$eligible[ids]&!is.na(p[ids])];y<-d$y[use];a<-if(is.character(t))rep(t==\"always-positive\",length(use))else p[use]>=t\n TP<-sum(a&y==1);FP<-sum(a&y==0);FN<-sum(!a&y==1);TN<-sum(!a&y==0);P<-TP+FN;N<-FP+TN;W<-P+N;PP<-TP+FP;PN<-TN+FN;TPR<-ratio(TP,P);TNR<-ratio(TN,N);bs<-sum((p[use]-y)^2);tc<-FP*cost[1]+FN*cost[2]\n list(TP=TP,FP=FP,FN=FN,TN=TN,mass=W,positiveTargetMass=P,negativeTargetMass=N,predictedPositiveMass=PP,predictedNegativeMass=PN,prevalence=ratio(P,W),selectionRate=ratio(PP,W),accuracy=ratio(TP+TN,W),precision=ratio(TP,PP),negativePredictiveValue=ratio(TN,PN),TPR=TPR,FPR=ratio(FP,N),TNR=TNR,FNR=ratio(FN,P),F1=ratio(2*TP,2*TP+FP+FN),balancedAccuracy=if(is.na(TPR)||is.na(TNR))NA_real_ else(TPR+TNR)/2,Brier=ratio(bs,W),BrierSum=bs,totalCost=tc,meanCost=ratio(tc,W))\n}\ncurves<-function(d,p,ids){\n use<-ids[d$eligible[ids]&!is.na(p[ids])];scores<-sort(unique(p[use]),decreasing=TRUE);policies<-c(list(\"always-negative\"),as.list(scores));points<-lapply(policies,function(t){m<-measure(d,p,ids,t);c(list(policy=t),m[c(\"TP\",\"FP\",\"FN\",\"TN\",\"TPR\",\"FPR\",\"precision\")],list(recall=m$TPR))})\n pos<-use[d$y[use]==1];neg<-use[d$y[use]==0];U<-0;for(i in pos)U<-U+sum(p[i]>p[neg])+.5*sum(p[i]==p[neg])\n AP<-0;trap<-0;lastR<-0;lastP<-1\n if(length(pos)&&length(scores))for(j in seq_along(scores)){z<-points[[j+1]];AP<-AP+(z$recall-lastR)*z$precision;trap<-trap+(z$recall-lastR)*(z$precision+lastP)/2;lastR<-z$recall;lastP<-z$precision}\n list(points=points,ROC_AUC=ratio(U,length(pos)*length(neg)),averagePrecision=if(length(pos))AP else NA_real_,PRTrapezoidWithInitialPrecisionOne=if(length(pos))trap else NA_real_)\n}\ncalibrate<-function(d,p,ids){\n use<-ids[d$eligible[ids]&!is.na(p[ids])];W<-length(use);pi<-if(W)mean(d$y[use])else NA_real_;bins<-list();ECE<-rel<-res<-correction<-0\n whichbin<-findInterval(p[use],seq(0,1,.2),rightmost.closed=TRUE,all.inside=TRUE)\n for(b in 1:5){rr<-use[whichbin==b];w<-length(rr);mp<-if(w)mean(p[rr])else NA_real_;o<-if(w)mean(d$y[rr])else NA_real_;variance<-if(w)mean((p[rr]-mp)^2)else NA_real_;covariance<-if(w)mean((p[rr]-mp)*(d$y[rr]-o))else NA_real_;bc<-variance-2*covariance;gap<-mp-o\n  bins[[b]]<-list(mass=w,meanPrediction=mp,eventRate=o,gap=gap,absoluteGap=abs(gap),scoreVariance=variance,scoreTargetCovariance=covariance,withinBinCorrection=bc,rows=w,ids=d$id[rr])\n  if(w){share<-w/W;ECE<-ECE+share*abs(gap);rel<-rel+share*gap^2;res<-res+share*(o-pi)^2;correction<-correction+share*bc}\n };bs<-if(W)mean((p[use]-d$y[use])^2)else NA_real_;unc<-pi*(1-pi)\n list(bins=bins,ECE=if(W)ECE else NA_real_,Brier=bs,reliability=if(W)rel else NA_real_,resolution=if(W)res else NA_real_,uncertainty=unc,withinBinCorrection=if(W)correction else NA_real_,BrierIdentityResidual=bs-(unc-res+rel+correction))\n}\ncounts<-c(\"mass\",\"positiveTargetMass\",\"negativeTargetMass\",\"predictedPositiveMass\",\"predictedNegativeMass\");rates<-c(\"prevalence\",\"selectionRate\",\"accuracy\",\"precision\",\"negativePredictiveValue\",\"TPR\",\"FPR\",\"TNR\",\"FNR\",\"F1\",\"balancedAccuracy\",\"Brier\",\"BrierSum\",\"totalCost\",\"meanCost\")\ntables<-setNames(lapply(1:10,function(i)list()),c(\"predictions\",\"lineage\",\"fit-medians\",\"fit-cells\",\"validation-candidates\",\"test-metrics\",\"test-curves\",\"calibration-bins\",\"group-metrics\",\"chart-points\"))\nadd<-function(name,row)tables[[name]][[length(tables[[name]])+1L]]<<-row\nscalars<-function(m,keys){out<-list();for(k in keys){out[[paste0(k,\"Exact\")]]<-\"\";out[[paste0(k,\"Approx\")]]<-fmt(m[[k]])};out}\ntagrow<-function(kind,...)c(list(kind=kind),list(...))\npoint<-function(kind,chart,series,index,x,y,xunit=\"dimensionless\",yunit=\"dimensionless\",role=\"test\",tag=\"\"){add(\"chart-points\",tagrow(kind,chart=chart,series=series,index=index,xExact=\"\",xApprox=fmt(x),yExact=\"\",yApprox=fmt(y),xUnit=xunit,yUnit=yunit,role=role,tag=tag))}\nstudy<-function(kind,d){\n f<-fitmodel(d);n<-length(d$id);train<-which(d$role==\"train\");validation<-which(d$role==\"validation\");test<-which(d$role==\"test\");p<-f$pred;cv<-curves(d,p,test);cal<-calibrate(d,p,test)\n for(i in seq_len(n)){\n  reason<-if(d$eligible[i])\"\"else\"required-X-or-Y-missing\";transformed<-if(d$eligible[i])paste(fmt(f$z[i,]),collapse=\"|\")else\"\"\n  add(\"predictions\",tagrow(kind,id=d$id[i],sourceRow=d$sourceRow[i],originalID=d$originalID[i],plannedRole=d$plannedRole[i],role=d$role[i],group=ifelse(is.na(d$group[i]),\"\",d$group[i]),eligible=as.integer(d$eligible[i]),targetExact=fmt(d$y[i]),probabilityExact=\"\",probabilityApprox=fmt(p[i]),unseenCell=ifelse(is.na(f$unseen[i]),\"\",as.character(as.integer(f$unseen[i]))),transformedX=transformed,reason=reason))\n  raw<-d$rawX[i,];raw[raw%in%c(\"\",\".\")]<-\"\";nativeY<-d$nativeTarget[i];if(nativeY%in%c(\"\",\".\"))nativeY<-\"\"\n  add(\"lineage\",tagrow(kind,id=d$id[i],sourceRow=d$sourceRow[i],originalID=d$originalID[i],nativeSourceRows=d$lineage[i],rawX=paste(raw,collapse=\"|\"),nativeTarget=nativeY,derivedTarget=fmt(d$y[i]),nativeGroup=ifelse(is.na(d$group[i]),\"\",d$group[i]),plannedRole=d$plannedRole[i],role=d$role[i],eligible=as.integer(d$eligible[i]),analyticalMass=\"1\",reason=reason))\n }\n for(j in seq_len(ncol(d$x)))add(\"fit-medians\",tagrow(kind,feature=j-1,categorical=as.integer((j-1)%in%d$cat),fitRows=length(train),medianExact=\"\",medianApprox=fmt(f$medians[j]),unit=d$units[j]))\n for(j in seq_along(f$lev))add(\"fit-cells\",tagrow(kind,cell=f$lev[j],trainingRows=f$mass[j],positiveRows=f$positive[j],probabilityExact=\"\",probabilityApprox=fmt(f$prob[j]),fallbackExact=\"\",fallbackApprox=fmt(f$fallback)))\n for(j in seq_along(cv$points)){\n  z<-cv$points[[j]];t<-z$policy;add(\"test-curves\",c(tagrow(kind,point=j-1,policy=if(is.character(t))t else\"threshold\",thresholdExact=\"\",thresholdApprox=if(is.character(t))\"\"else fmt(t)),scalars(z,c(\"TP\",\"FP\",\"FN\",\"TN\",\"TPR\",\"FPR\",\"precision\",\"recall\"))))\n  point(kind,\"roc\",\"ROC\",j-1,z$FPR,z$TPR);point(kind,\"pr\",\"PR-observed\",j-1,z$recall,z$precision)\n }\n for(b in 1:5){z<-cal$bins[[b]];add(\"calibration-bins\",c(tagrow(kind,bin=b-1,leftExact=c(\"0\",\"1/5\",\"2/5\",\"3/5\",\"4/5\")[b],rightExact=c(\"1/5\",\"2/5\",\"3/5\",\"4/5\",\"1\")[b],rightClosed=as.integer(b==5),rows=z$rows,ids=paste(z$ids,collapse=\";\")),scalars(z,c(\"mass\",\"meanPrediction\",\"eventRate\",\"gap\",\"absoluteGap\",\"scoreVariance\",\"scoreTargetCovariance\",\"withinBinCorrection\"))));point(kind,\"reliability\",\"Binary event rate\",b-1,z$meanPrediction,z$eventRate,tag=paste0(\"rows=\",z$rows))}\n for(j in seq_along(test)){i<-test[j];point(kind,\"test-scores\",\"Training-fitted probability\",j-1,j,p[i],\"test-row position\",\"probability\",tag=d$id[i]);point(kind,\"test-scores\",\"Observed Y\",j-1,j,d$y[i],\"test-row position\",\"binary target\",tag=d$id[i])}\n scenarioNames<-c(\"equal\",\"miss-five\",\"alarm-five\");costs<-list(c(1,1),c(1,5),c(5,1))\n for(s in 1:3){name<-scenarioNames[s];cost<-costs[[s]];grid<-c(list(\"always-negative\"),as.list(sort(unique(p[validation]),decreasing=TRUE)));candidates<-lapply(grid,function(t)measure(d,p,validation,t,cost));values<-vapply(candidates,function(m)m$meanCost,numeric(1));best<-which(values<=min(values)+1e-12)[1];chosen<-grid[[best]];ev<-measure(d,p,test,chosen,cost)\n  for(j in seq_along(grid)){t<-grid[[j]];m<-candidates[[j]];cell<-setNames(lapply(c(\"TP\",\"FP\",\"FN\",\"TN\"),function(k)fmt(m[[k]])),paste0(c(\"TP\",\"FP\",\"FN\",\"TN\"),\"Exact\"));add(\"validation-candidates\",c(tagrow(kind,scenario=name,candidate=j-1,selected=as.integer(j==best),policy=if(is.character(t))t else\"threshold\",thresholdExact=\"\",thresholdApprox=if(is.character(t))\"\"else fmt(t),feasible=1,reasons=\"\"),cell,scalars(m,c(counts,\"TPR\",\"FPR\",\"precision\",\"meanCost\",\"totalCost\"))));point(kind,\"validation-cost\",name,j-1,j-1,m$meanCost,\"candidate index\",\"hypothetical cost units/mass\",\"validation\",if(is.character(t))t else fmt(t))}\n  m<-c(ev,cv[c(\"ROC_AUC\",\"averagePrecision\",\"PRTrapezoidWithInitialPrecisionOne\")],cal[c(\"ECE\",\"reliability\",\"resolution\",\"uncertainty\",\"withinBinCorrection\",\"BrierIdentityResidual\")])\n  for(k in c(\"TP\",\"FP\",\"FN\",\"TN\",counts,rates,\"ROC_AUC\",\"averagePrecision\",\"PRTrapezoidWithInitialPrecisionOne\",\"ECE\",\"reliability\",\"resolution\",\"uncertainty\",\"withinBinCorrection\",\"BrierIdentityResidual\")){\n   unit<-if(k%in%c(\"TP\",\"FP\",\"FN\",\"TN\",counts))\"rows\"else if(k==\"totalCost\")\"hypothetical cost units\"else if(k==\"meanCost\")\"hypothetical cost units/mass\"else if(k==\"BrierSum\")\"sum squared-probability loss\"else\"dimensionless\"\n   add(\"test-metrics\",tagrow(kind,scenario=name,metric=k,valueExact=\"\",valueApprox=fmt(m[[k]]),unit=unit))\n  }\n  lev<-unique(d$group[test][!is.na(d$group[test])]);sets<-c(list(test),lapply(lev,function(g)test[!is.na(d$group[test])&d$group[test]==g]),list(test[is.na(d$group[test])]))\n  types<-c(\"overall\",rep(\"known\",length(lev)),\"unknown\");tokens<-c(\"all\",lev,\"\")\n  for(j in seq_along(sets)){ids<-sets[[j]];m<-measure(d,p,ids,chosen,cost);cell<-setNames(lapply(c(\"TP\",\"FP\",\"FN\",\"TN\"),function(k)fmt(m[[k]])),paste0(c(\"TP\",\"FP\",\"FN\",\"TN\"),\"Exact\"));add(\"group-metrics\",c(tagrow(kind,scenario=name,groupType=types[j],groupToken=tokens[j],retainedRows=length(ids)),cell,scalars(m,c(counts,rates))));if(types[j]==\"known\")point(kind,\"group-TPR\",name,j-2,j-2,m$TPR,\"declared group position\",\"TPR\",tag=tokens[j])}\n }\n invisible(NULL)\n}\n\n# Fixed finite inputs only; not the complete web input/budget validator.\nqnum<-function(v){if(is.null(v))return(NA_real_);if(is.logical(v))return(as.numeric(v));s<-as.character(v);if(grepl(\"/\",s,fixed=TRUE)){a<-strsplit(s,\"/\",fixed=TRUE)[[1]];return(as.numeric(a[1])/as.numeric(a[2]))};as.numeric(s)}\nrowsG<-function(raw){\n n<-length(raw);get<-function(r,k,default=NULL)if(is.null(r[[k]]))default else r[[k]]\n id<-vapply(raw,function(r)as.character(r$id),character(1));p<-vapply(raw,function(r)qnum(r$score),numeric(1));y<-vapply(raw,function(r)qnum(r$y),numeric(1));w<-vapply(raw,function(r)qnum(get(r,\"weight\",\"1\")),numeric(1));role<-vapply(raw,function(r)get(r,\"role\",\"evaluation\"),character(1));group<-vapply(raw,function(r)as.character(get(r,\"group\",NA_character_)),character(1))\n stopifnot(all(w>=0),all(is.na(p)|(p>=0&p<=1)),all(is.na(y)|y%in%c(0,1)),!anyDuplicated(id));list(id=id,p=p,y=y,w=w,role=role,group=group,eligible=!is.na(p)&!is.na(y)&w>0&role!=\"excluded\")\n}\nscopeG<-function(d,role=\"all\")if(role==\"all\")seq_along(d$id)else which(d$role==role)\nmetricsG<-function(d,ids,t=.5,cost=c(1,1)){\n use<-ids[d$eligible[ids]];p<-d$p[use];y<-d$y[use];w<-d$w[use];a<-if(is.character(t))rep(t==\"always-positive\",length(use))else p>=t\n TP<-sum(w[a&y==1]);FP<-sum(w[a&y==0]);FN<-sum(w[!a&y==1]);TN<-sum(w[!a&y==0]);P<-TP+FN;N<-FP+TN;W<-P+N;PP<-TP+FP;PN<-TN+FN;TPR<-ratio(TP,P);TNR<-ratio(TN,N);bs<-sum(w*(p-y)^2);tc<-FP*cost[1]+FN*cost[2]\n list(confusion=list(TP=TP,FP=FP,FN=FN,TN=TN),mass=W,positiveTargetMass=P,negativeTargetMass=N,predictedPositiveMass=PP,predictedNegativeMass=PN,prevalence=ratio(P,W),selectionRate=ratio(PP,W),accuracy=ratio(TP+TN,W),precision=ratio(TP,PP),negativePredictiveValue=ratio(TN,PN),TPR=TPR,FPR=ratio(FP,N),TNR=TNR,FNR=ratio(FN,P),F1=ratio(2*TP,2*TP+FP+FN),balancedAccuracy=if(is.na(TPR)||is.na(TNR))NA_real_ else(TPR+TNR)/2,Brier=ratio(bs,W),BrierSum=bs,totalCost=tc,meanCost=ratio(tc,W),bayesThreshold=ratio(cost[1],sum(cost)))\n}\ncurvesG<-function(d,ids){\n use<-ids[d$eligible[ids]];grid<-c(list(\"always-negative\"),as.list(sort(unique(d$p[use]),decreasing=TRUE)));points<-lapply(grid,function(t){m<-metricsG(d,ids,t);c(list(policy=t),m$confusion,m[c(\"TPR\",\"FPR\",\"precision\")],list(recall=m$TPR))});pos<-use[d$y[use]==1];neg<-use[d$y[use]==0];P<-sum(d$w[pos]);N<-sum(d$w[neg]);U<-0\n for(i in pos)U<-U+d$w[i]*sum(d$w[neg]*((d$p[i]>d$p[neg])+.5*(d$p[i]==d$p[neg])))\n AP<-trap<-lastR<-0;lastP<-1\n if(P&&length(grid)>1)for(j in 2:length(grid)){z<-points[[j]];AP<-AP+(z$recall-lastR)*z$precision;trap<-trap+(z$recall-lastR)*(z$precision+lastP)/2;lastR<-z$recall;lastP<-z$precision}\n list(points=points,ROC_AUC=ratio(U,P*N),averagePrecision=if(P)AP else NA_real_,PRTrapezoidWithInitialPrecisionOne=if(P)trap else NA_real_)\n}\nchooseG<-function(d,a,cost){\n role<-if(is.null(a$selectionRole))\"validation\"else a$selectionRole;er<-if(is.null(a$evaluationRole))\"test\"else a$evaluationRole;ids<-scopeG(d,role);use<-ids[d$eligible[ids]];stopifnot(length(use)>0);grid<-if(is.null(a$thresholds))c(list(\"always-negative\"),as.list(sort(unique(d$p[use]),decreasing=TRUE)))else lapply(a$thresholds,function(t)if(t%in%c(\"always-negative\",\"always-positive\"))t else qnum(t))\n candidates<-lapply(seq_along(grid),function(j){m<-metricsG(d,ids,grid[[j]],cost);feasible<-TRUE;if(!is.null(a$minTPR))feasible<-feasible&&!is.na(m$TPR)&&m$TPR>=qnum(a$minTPR);if(!is.null(a$maxFPR))feasible<-feasible&&!is.na(m$FPR)&&m$FPR<=qnum(a$maxFPR);list(index=j-1,policy=grid[[j]],metrics=m,feasible=feasible)})\n good<-which(vapply(candidates,function(c)c$feasible,logical(1)));best<-NA_integer_;if(length(good)){v<-vapply(candidates[good],function(c)c$metrics$meanCost,numeric(1));best<-good[which(v<=min(v)+1e-12)[1]]}\n list(selectedIndex=if(is.na(best))NA_integer_ else best-1,selectedPolicy=if(is.na(best))NULL else grid[[best]],selectedValidation=if(is.na(best))NULL else candidates[[best]]$metrics,candidates=candidates,evaluation=if(is.na(best)||er==\"none\")NULL else metricsG(d,scopeG(d,er),grid[[best]],cost))\n}\ncalibrateG<-function(d,ids,edges){\n use<-ids[d$eligible[ids]];W<-sum(d$w[use]);pi<-ratio(sum(d$w[use]*d$y[use]),W);bins<-list();ECE<-rel<-res<-correction<-0;assign<-findInterval(d$p[use],edges,rightmost.closed=TRUE,all.inside=TRUE)\n for(b in seq_len(length(edges)-1)){rr<-use[assign==b];w<-sum(d$w[rr]);mp<-ratio(sum(d$w[rr]*d$p[rr]),w);o<-ratio(sum(d$w[rr]*d$y[rr]),w);variance<-if(w)sum(d$w[rr]*(d$p[rr]-mp)^2)/w else NA_real_;covariance<-if(w)sum(d$w[rr]*(d$p[rr]-mp)*(d$y[rr]-o))/w else NA_real_;bc<-variance-2*covariance;gap<-mp-o;bins[[b]]<-list(index=b-1,mass=w,meanPrediction=mp,eventRate=o,scoreVariance=variance,scoreTargetCovariance=covariance,withinBinCorrection=bc,ids=d$id[rr])\n  if(w){s<-w/W;ECE<-ECE+s*abs(gap);rel<-rel+s*gap^2;res<-res+s*(o-pi)^2;correction<-correction+s*bc}\n };bs<-ratio(sum(d$w[use]*(d$p[use]-d$y[use])^2),W);unc<-pi*(1-pi);list(bins=bins,Brier=bs,ECE=if(W)ECE else NA_real_,uncertainty=unc,reliability=if(W)rel else NA_real_,resolution=if(W)res else NA_real_,withinBinCorrection=if(W)correction else NA_real_,BrierIdentityResidual=bs-(unc-res+rel+correction))\n}\ngroupsG<-function(d,ids,t,cost){\n lev<-unique(d$group[ids][!is.na(d$group[ids])]);groups<-lapply(lev,function(g)list(group=g,metrics=metricsG(d,ids[!is.na(d$group[ids])&d$group[ids]==g],t,cost)));overall<-metricsG(d,ids,t,cost);unknown<-metricsG(d,ids[is.na(d$group[ids])],t,cost);gaps<-list()\n for(k in c(\"prevalence\",\"selectionRate\",\"TPR\",\"FPR\",\"precision\",\"accuracy\",\"meanCost\")){use<-Filter(function(g)g$metrics$mass>0,groups);v<-vapply(use,function(g)g$metrics[[k]],numeric(1));gaps[[k]]<-if(length(use)<2||anyNA(v))NA_real_ else max(v)-min(v)}\n list(overall=overall,groups=groups,unknownGroup=unknown,gaps=gaps,partitionMassResidual=overall$mass-unknown$mass-sum(vapply(groups,function(g)g$metrics$mass,numeric(1))))\n}\nsvgFixed<-function(file,points,title,xlabel,ylabel,legend){\n finite<-points[points$y!=\"undefined\"&points$x!=\"undefined\",,drop=FALSE];x<-as.numeric(finite$x);y<-as.numeric(finite$y);xmin<-if(length(x))min(x)else 0;xmax<-if(length(x))max(x)else 1;ymin<-min(c(0,y));ymax<-max(c(0,y));if(xmin==xmax){xmin<-xmin-.5;xmax<-xmax+.5};if(ymin==ymax)ymax<-ymin+1;X<-function(v)85+(v-xmin)/(xmax-xmin)*480;Y<-function(v)278-(v-ymin)/(ymax-ymin)*175\n esc<-function(s){s<-gsub(\"&\",\"&amp;\",s,fixed=TRUE);s<-gsub(\"<\",\"&lt;\",s,fixed=TRUE);gsub(\">\",\"&gt;\",s,fixed=TRUE)};s<-'<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"620\" height=\"360\" viewBox=\"0 0 620 360\"><rect width=\"620\" height=\"360\" fill=\"white\"/><g font-family=\"Arial, sans-serif\" font-size=\"13\" fill=\"#17324d\">'\n lines<-strwrap(title,width=65);for(i in seq_along(lines))s<-paste0(s,'<text x=\"25\" y=\"',24+(i-1)*18,'\">',esc(lines[i]),'</text>');colors<-c(\"#176b9b\",\"#b85e18\",\"#437e4d\")\n for(i in seq_along(legend))s<-paste0(s,'<circle cx=\"',30+(i-1)*250,'\" cy=\"76\" r=\"4\" fill=\"',colors[(i-1)%%3+1],'\"/><text x=\"',42+(i-1)*250,'\" y=\"80\">',esc(legend[i]),'</text>')\n s<-paste0(s,'<path d=\"M85 98V278H575\" fill=\"none\" stroke=\"#52677d\"/><text text-anchor=\"middle\" x=\"325\" y=\"338\">',esc(xlabel),'</text><text text-anchor=\"middle\" transform=\"translate(21,190) rotate(-90)\">',esc(ylabel),'</text>')\n for(i in 0:4){xx<-xmin+(xmax-xmin)*i/4;yy<-ymin+(ymax-ymin)*i/4;s<-paste0(s,'<text text-anchor=\"middle\" x=\"',sprintf(\"%.9g\",X(xx)),'\" y=\"305\">',sprintf(\"%.4g\",xx),'</text><text text-anchor=\"end\" x=\"77\" y=\"',sprintf(\"%.9g\",Y(yy)+4),'\">',sprintf(\"%.4g\",yy),'</text>')}\n for(i in seq_len(nrow(finite)))s<-paste0(s,'<circle cx=\"',sprintf(\"%.9g\",X(x[i])),'\" cy=\"',sprintf(\"%.9g\",Y(y[i])),'\" r=\"3\" fill=\"',colors[as.integer(finite$series[i])%%3+1],'\"/>');writeLines(paste0(s,'</g></svg>'),file,useBytes=TRUE)\n}\nfixedRun<-function(){\n api<-FIXED$api;a<-FIXED$args;summary<-list();points<-list();xlabel<-\"Declared index\";ylabel<-\"Value\";legend<-\"Declared result\"\n metric<-function(name,v,unit=\"dimensionless\"){if(is.null(v))v<-NA_real_;summary[[length(summary)+1L]]<<-data.frame(metric=name,value=if(is.na(v))\"undefined\"else sprintf(\"%.9g\",v),exactValue=\"\",unit=unit,defined=as.integer(!is.na(v)),stringsAsFactors=FALSE)}\n pt<-function(i,x,y,id=\"\",series=0){points[[length(points)+1L]]<<-data.frame(series=series,index=i,xExact=\"\",x=if(is.na(x))\"undefined\"else sprintf(\"%.9g\",x),yExact=\"\",y=if(is.na(y))\"undefined\"else sprintf(\"%.9g\",y),id=as.character(id),stringsAsFactors=FALSE)}\n if(api==\"realdata\"){\n  native<-loadData()[[a$kind]];fit<-fitmodel(native);d<-list(id=native$id,p=fit$pred,y=native$y,w=rep(1,length(native$id)),role=native$role,group=native$group,eligible=native$eligible);scenarios<-list()\n  for(j in 1:3){name<-c(\"equal\",\"miss-five\",\"alarm-five\")[j];cst<-list(c(1,1),c(1,5),c(5,1))[[j]];sel<-chooseG(d,list(),cst);scenarios[[j]]<-list(name=name,selection=sel);metric(paste0(name,\"Threshold\"),sel$selectedPolicy);metric(paste0(name,\"TestCost\"),sel$evaluation$meanCost,\"hypothetical cost units/mass\")}\n  ids<-scopeG(d,\"test\");cv<-curvesG(d,ids);cal<-calibrateG(d,ids,seq(0,1,.2));metric(\"testAUC\",cv$ROC_AUC);metric(\"testAP\",cv$averagePrecision);metric(\"testBrier\",cal$Brier);metric(\"eligibleRows\",sum(d$eligible),\"rows\")\n  for(j in seq_along(ids)){i<-ids[j];pt(j-1,j,d$p[i],d$id[i],0);pt(j-1,j,d$y[i],d$id[i],1)}\n  full<-list(kind=a$kind,fit=fit,scenarios=scenarios,testCurves=cv,testCalibration=cal,rowsScored=d);xlabel<-\"Test row, native order\";ylabel<-\"Y or probability\";legend<-c(\"Training-fitted probability\",\"Observed Y\")\n }else{\n  d<-rowsG(a$rows);role<-if(is.null(a$role))\"all\"else a$role;ids<-scopeG(d,role);cost<-if(is.null(a$costs))c(1,1)else c(qnum(a$costs$falsePositive),qnum(a$costs$falseNegative));t<-if(is.null(a$threshold)).5 else if(a$threshold%in%c(\"always-positive\",\"always-negative\"))a$threshold else qnum(a$threshold)\n  if(api==\"metrics\"){\n   full<-metricsG(d,ids,t,cost);for(k in c(\"mass\",\"accuracy\",\"precision\",\"TPR\",\"FPR\",\"F1\",\"Brier\",\"meanCost\"))metric(k,full[[k]],if(k==\"mass\")\"mass\"else if(k==\"meanCost\")\"hypothetical cost units/mass\"else\"dimensionless\");metric(\"BayesThreshold\",full$bayesThreshold)\n   for(i in 1:4)pt(i-1,i-1,full$confusion[[i]],names(full$confusion)[i]);xlabel<-\"TP / FP / FN / TN positions\";ylabel<-\"Analytical mass\"\n  }else if(api==\"curves\"){\n   full<-curvesG(d,ids);for(k in c(\"ROC_AUC\",\"averagePrecision\",\"PRTrapezoidWithInitialPrecisionOne\"))metric(k,full[[k]])\n   for(j in seq_along(full$points)){p<-full$points[[j]];pt(j-1,p$FPR,p$TPR,if(is.character(p$policy))p$policy else sprintf(\"%.17g\",p$policy))};xlabel<-\"False positive rate\";ylabel<-\"True positive rate\";legend<-\"Observed ROC operating points\"\n  }else if(api==\"choose\"){\n   full<-chooseG(d,a,cost);metric(\"selectedIndex\",full$selectedIndex,\"candidate index\");metric(\"minimumCost\",if(is.null(full$selectedValidation))NULL else full$selectedValidation$meanCost,\"hypothetical cost units/mass\");metric(\"feasible\",as.integer(!is.na(full$selectedIndex)),\"indicator\")\n   for(c in full$candidates)pt(c$index,c$index,c$metrics$meanCost,if(is.character(c$policy))c$policy else sprintf(\"%.17g\",c$policy));xlabel<-\"Validation candidate\";ylabel<-\"Assumed cost / mass\";legend<-\"Validation candidate costs\"\n  }else if(api==\"calibrate\"){\n   edges<-if(is.null(a$binEdges))seq(0,1,.2)else vapply(a$binEdges,qnum,numeric(1));full<-calibrateG(d,ids,edges);for(k in c(\"ECE\",\"Brier\",\"uncertainty\",\"resolution\",\"reliability\",\"withinBinCorrection\",\"BrierIdentityResidual\"))metric(k,full[[k]])\n   for(b in full$bins)pt(b$index,b$meanPrediction,b$eventRate,paste0(\"bin:\",b$index));xlabel<-\"Bin mean forecast\";ylabel<-\"Bin event rate\";legend<-\"Binary-event reliability\"\n  }else if(api==\"groups\"){\n   full<-groupsG(d,ids,t,cost);metric(\"overallTPR\",full$overall$TPR);metric(\"TPRGap\",full$gaps$TPR);metric(\"precisionGap\",full$gaps$precision);metric(\"unknownMass\",full$unknownGroup$mass,\"mass\");metric(\"partitionResidual\",full$partitionMassResidual,\"mass\")\n   for(j in seq_along(full$groups))pt(j-1,j-1,full$groups[[j]]$metrics$TPR,full$groups[[j]]$group);xlabel<-\"Declared group position\";ylabel<-\"True positive rate\";legend<-\"Known-group TPR\"\n  }else stop(\"unknown declared fixed API\")\n }\n sm<-do.call(rbind,summary);pp<-do.call(rbind,points);write.csv(sm,file.path(outDir,\"summary.csv\"),row.names=FALSE,na=\"\");write.csv(pp,file.path(outDir,\"plot-points.csv\"),row.names=FALSE,na=\"\");svgFixed(file.path(outDir,\"plot.svg\"),pp,FIXED$title,xlabel,ylabel,legend);dput(list(api=api,variant=FIXED$variant,input=FIXED$args,arithmetic=\"Base-R binary64 fixed example; not an exact rational general validator\",result=full),file=file.path(outDir,\"full.txt\"));cat(\"PASS\",api,FIXED$variant,\"summary\",nrow(sm),\"points\",nrow(pp),\"\\n\")\n}\n\nFIXED<-list(api=\"curves\",variant=\"all-tied\",args=list(rows=list(list(id=\"a\",score=\".5\",y=1,group=\"A\"),list(id=\"b\",score=\".5\",y=1,group=\"A\"),list(id=\"c\",score=\".5\",y=0,group=\"A\"),list(id=\"d\",score=\".5\",y=0,group=\"B\"),list(id=\"e\",score=\".5\",y=1,group=\"B\"),list(id=\"f\",score=\".5\",y=0,group=\"B\"))),title=\"All scores tied: half pair credit and prevalence AP\")\nfixedRun()\n",
        "input": {
          "rows": [
            {
              "id": "a",
              "score": ".5",
              "y": 1,
              "group": "A"
            },
            {
              "id": "b",
              "score": ".5",
              "y": 1,
              "group": "A"
            },
            {
              "id": "c",
              "score": ".5",
              "y": 0,
              "group": "A"
            },
            {
              "id": "d",
              "score": ".5",
              "y": 0,
              "group": "B"
            },
            {
              "id": "e",
              "score": ".5",
              "y": 1,
              "group": "B"
            },
            {
              "id": "f",
              "score": ".5",
              "y": 0,
              "group": "B"
            }
          ]
        },
        "inputFiles": [],
        "returnCode": 0,
        "expectedFailure": false,
        "stdout": "PASS curves all-tied summary 3 points 2 \n",
        "stderr": "During startup - Warning messages:\n1: Setting LC_COLLATE=C.UTF-8 failed \n2: Setting LC_CTYPE=C.UTF-8 failed \n3: Setting LC_MONETARY=C.UTF-8 failed \n4: Setting LC_TIME=C.UTF-8 failed \n",
        "summary": {
          "ROC_AUC": "0.5",
          "averagePrecision": "0.5",
          "PRTrapezoidWithInitialPrecisionOne": "0.75"
        },
        "summaryRows": [
          {
            "metric": "ROC_AUC",
            "value": "0.5",
            "exactValue": "",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "averagePrecision",
            "value": "0.5",
            "exactValue": "",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "PRTrapezoidWithInitialPrecisionOne",
            "value": "0.75",
            "exactValue": "",
            "unit": "dimensionless",
            "defined": "1"
          }
        ],
        "plotPoints": [
          {
            "series": "0",
            "index": "0",
            "xExact": "",
            "x": "0",
            "yExact": "",
            "y": "0",
            "id": "always-negative"
          },
          {
            "series": "0",
            "index": "1",
            "xExact": "",
            "x": "1",
            "yExact": "",
            "y": "1",
            "id": "0.5"
          }
        ],
        "plotFile": "ml14-fixed-results/curves-all-tied-r/plot.svg",
        "plotSHA256": "96d81bdd4f71a7fc64eb43d74ec1db4b264d6d7cfdef6f0800ccf3ee14aa3c93",
        "files": [
          {
            "file": "ml14-fixed-results/curves-all-tied-r/full.txt",
            "sha256": "b08e921dd384966353f74652c1e9ba671ae98ca0ef90457e027499fa53a8edad",
            "bytes": 875
          },
          {
            "file": "ml14-fixed-results/curves-all-tied-r/plot-points.csv",
            "sha256": "23c19a75fdd7278ca1c856d2124329b98dffe3aa405a3353d3cf2e90616223c1",
            "bytes": 111
          },
          {
            "file": "ml14-fixed-results/curves-all-tied-r/plot.svg",
            "sha256": "96d81bdd4f71a7fc64eb43d74ec1db4b264d6d7cfdef6f0800ccf3ee14aa3c93",
            "bytes": 1215
          },
          {
            "file": "ml14-fixed-results/curves-all-tied-r/summary.csv",
            "sha256": "ef7e0846106432d70589982ec5f7ea78136e086ebfb5c02651765f85c6e5e65b",
            "bytes": 199
          }
        ],
        "scope": "Actually executed standalone fixed example, Python exact Fraction versus base-R binary64. Approximate R residuals retained; not universal exact arithmetic/web validation/native UI. Source programs read factual3CSV only."
      }
    }
  },
  "choose": {
    "python": {
      "miss-five": {
        "api": "choose",
        "variant": "miss-five",
        "language": "python",
        "title": "Validation-only threshold with missed-case cost five",
        "codeFile": "ml14-code/choose-miss-five.py",
        "codeSHA256": "d64df96996e613cd35d132591ee146161ba10eb165200b535a130bca0ee6ac19",
        "code": "#!/usr/bin/env python3\n\"\"\"ML14 standalone exact finite study, Python standard library only.\nInputs: only the three retained factual source CSVs below.\nDerived role/target/group/eligibility columns in those CSVs are NOT inputs.\nRebuilds SHA256 roles, train-only medians/cell scores, validation thresholds,\ntest curves, binary-event reliability and descriptive group ledgers.\nCosts 1/1,1/5,5/1 are hypothetical units, not measured intervention returns.\nThis is author public reproduction, not independent scientific review.\n\"\"\"\n\"\"\"Author Fraction reference, separate from product JavaScript; not independent peer.\"\"\"\nfrom fractions import Fraction as F\nfrom collections import Counter,defaultdict\ndef read(raw):\n rows=[]\n for i,r in enumerate(raw):\n  s=None if r['score']is None else F(str(r['score']));y=None if r['y']is None else F(int(r['y']))if isinstance(r['y'],bool)else F(str(r['y']));w=F(str(r.get('weight','1')));role=r.get('role','evaluation')\n  rows.append(dict(id=r['id'],index=i,score=s,y=y,w=w,role=role,group=r.get('group'),eligible=s is not None and y is not None and w>0 and role!='excluded'))\n return rows\ndef scoped(rows,role='all'):return rows if role=='all'else[r for r in rows if r['role']==role]\ndef divide(n,d):return None if not d else n/d\ndef policy(v):return v if v in ['always-negative','always-positive']else F(str(v))\ndef positive(p,s):return p=='always-positive'if isinstance(p,str)else s>=p\ndef cost(a=None):\n a={}if a is None else a;fp=F(str(a.get('falsePositive','1')));fn=F(str(a.get('falseNegative','1')));return fp,fn\ndef metrics(rows,threshold=F(1,2),cc=(F(1),F(1))):\n counts=dict(TP=F(0),FP=F(0),FN=F(0),TN=F(0));brier=F(0);pred=[]\n for r in rows:\n  if not r['eligible']:pred.append(dict(id=r['id'],index=r['index'],eligible=False,decision=None,probability=None,Brier=None));continue\n  yes=positive(threshold,r['score']);cell=('T'if yes==bool(r['y'])else'F')+('P'if yes else'N');counts[cell]+=r['w'];loss=(r['score']-r['y'])**2;brier+=r['w']*loss;pred.append(dict(id=r['id'],index=r['index'],eligible=True,decision=int(yes),probability=r['score'],Brier=loss))\n TP,FP,FN,TN=[counts[k]for k in ['TP','FP','FN','TN']];P=TP+FN;N=TN+FP;mass=P+N;PP=TP+FP;PN=TN+FN;TPR=divide(TP,P);TNR=divide(TN,N);total=FP*cc[0]+FN*cc[1]\n return dict(confusion=counts,mass=mass,positiveTargetMass=P,negativeTargetMass=N,predictedPositiveMass=PP,predictedNegativeMass=PN,prevalence=divide(P,mass),selectionRate=divide(PP,mass),accuracy=divide(TP+TN,mass),precision=divide(TP,PP),negativePredictiveValue=divide(TN,PN),TPR=TPR,FPR=divide(FP,N),TNR=TNR,FNR=divide(FN,P),F1=divide(2*TP,2*TP+FP+FN),balancedAccuracy=None if TPR is None or TNR is None else(TPR+TNR)/2,Brier=divide(brier,mass),BrierSum=brier,totalCost=total,meanCost=divide(total,mass),predictions=pred,bayesThreshold=divide(cc[0],sum(cc)))\ndef curves(rows):\n use=[r for r in rows if r['eligible']];pos=Counter();neg=Counter()\n for r in use:(pos if r['y']else neg)[r['score']]+=r['w']\n P=sum(pos.values(),F(0));N=sum(neg.values(),F(0));pairs=F(0)\n for a,wa in pos.items():\n  for b,wb in neg.items():pairs+=wa*wb*(F(1)if a>b else F(1,2)if a==b else F(0))\n thresholds=['always-negative']+sorted({r['score']for r in use},reverse=True);points=[];AP=F(0);trap=F(0);lastR=F(0);lastP=F(1)\n for i,p in enumerate(thresholds):\n  m=metrics(rows,p);points.append(dict(policy=p,TP=m['confusion']['TP'],FP=m['confusion']['FP'],FN=m['confusion']['FN'],TN=m['confusion']['TN'],TPR=m['TPR'],FPR=m['FPR'],precision=m['precision'],recall=m['TPR']))\n  if i and P:\n   R=m['TPR'];PP=m['precision'];AP+=(R-lastR)*PP;trap+=(R-lastR)*(PP+lastP)/2;lastR=R;lastP=PP\n return dict(positiveMass=P,negativeMass=N,ROC_AUC=divide(pairs,P*N),weightedConcordantPlusHalfTiedMass=pairs,averagePrecision=AP if P else None,PRTrapezoidWithInitialPrecisionOne=trap if P else None,points=points)\ndef choose(rows,a,cc):\n sr=a.get('selectionRole','validation');er=a.get('evaluationRole','test');rr=scoped(rows,sr);thresholds=[policy(t)for t in a['thresholds']]if'thresholds'in a else['always-negative']+sorted({r['score']for r in rr if r['eligible']},reverse=True)\n candidates=[]\n for i,p in enumerate(thresholds):\n  m=metrics(rr,p,cc);reasons=[]\n  if'minTPR'in a and(m['TPR']is None or m['TPR']<F(str(a['minTPR']))):reasons.append('TPR-undefined'if m['TPR']is None else'below-minTPR')\n  if'maxFPR'in a and(m['FPR']is None or m['FPR']>F(str(a['maxFPR']))):reasons.append('FPR-undefined'if m['FPR']is None else'above-maxFPR')\n  candidates.append(dict(index=i,policy=p,metrics=m,feasible=not reasons,reasons=reasons))\n eligible=[c for c in candidates if c['feasible']];best=min(eligible,key=lambda c:(c['metrics']['meanCost'],c['index']))if eligible else None\n return dict(selectedIndex=None if best is None else best['index'],selectedPolicy=None if best is None else best['policy'],candidates=candidates,selectedValidation=None if best is None else best['metrics'],evaluation=None if best is None or er=='none'else metrics(scoped(rows,er),best['policy'],cc),selectionIDs=[r['id']for r in rr if r['eligible']])\ndef calibrate(rows,ee):\n buckets=[[]for _ in range(len(ee)-1)]\n for r in rows:\n  if not r['eligible']:continue\n  j=next((i for i in range(len(ee)-1)if r['score']<ee[i+1]),len(ee)-2);buckets[j].append(r)\n mass=sum((r['w']for r in rows if r['eligible']),F(0));P=sum((r['w']*r['y']for r in rows if r['eligible']),F(0));pi=divide(P,mass);Brier=None if not mass else sum((r['w']*(r['score']-r['y'])**2 for r in rows if r['eligible']),F(0))/mass;ECE=F(0);reliability=F(0);resolution=F(0);correction=F(0);bins=[]\n for i,rr in enumerate(buckets):\n  w=sum((r['w']for r in rr),F(0));mp=None if not w else sum((r['w']*r['score']for r in rr),F(0))/w;o=None if not w else sum((r['w']*r['y']for r in rr),F(0))/w\n  variance=None if not w else sum((r['w']*(r['score']-mp)**2 for r in rr),F(0))/w\n  covariance=None if not w else sum((r['w']*(r['score']-mp)*(r['y']-o)for r in rr),F(0))/w\n  bc=None if not w else variance-2*covariance;gap=None if not w else mp-o\n  bins.append(dict(index=i,rows=len(rr),mass=w,meanPrediction=mp,eventRate=o,gap=gap,absoluteGap=None if gap is None else abs(gap),scoreVariance=variance,scoreTargetCovariance=covariance,withinBinCorrection=bc,ids=[r['id']for r in rr]))\n  if w:\n   share=w/mass;ECE+=share*abs(gap);reliability+=share*gap**2;resolution+=share*(o-pi)**2;correction+=share*bc\n uncertainty=None if pi is None else pi*(1-pi);residual=None if Brier is None else Brier-(uncertainty-resolution+reliability+correction)\n return dict(mass=mass,prevalence=pi,Brier=Brier,ECE=ECE if mass else None,reliability=reliability if mass else None,resolution=resolution if mass else None,uncertainty=uncertainty,withinBinCorrection=correction if mass else None,BrierIdentityResidual=residual,bins=bins)\ndef typed(v):return type(v).__name__,v\ndef groups(rows,p,cc):\n bins={}\n for r in rows:\n  if r['group']is not None:bins.setdefault(typed(r['group']),[]).append(r)\n gm=[dict(group=rr[0]['group'],metrics=metrics(rr,p,cc))for rr in bins.values()];overall=metrics(rows,p,cc);unknown=metrics([r for r in rows if r['group']is None],p,cc);gaps={}\n for key in ['prevalence','selectionRate','TPR','FPR','precision','accuracy','meanCost']:\n  positive=[g for g in gm if g['metrics']['mass']>0];undefined=[g['group']for g in positive if g['metrics'][key]is None];vals=[g['metrics'][key]for g in positive if g['metrics'][key]is not None]\n  gaps[key]=dict(value=None if len(positive)<2 or undefined else max(vals)-min(vals),undefinedGroups=undefined,comparedPositiveMassGroups=[g['group']for g in positive])\n return dict(overall=overall,groups=gm,unknownGroup=unknown,gaps=gaps,partitionMassResidual=overall['mass']-unknown['mass']-sum((g['metrics']['mass']for g in gm),F(0)))\ndef actual_model(M):\n raw=M['records'];cat=M['categoricalFeatures'];p=len(raw[0]['x']);train=[r for r in raw if r['role']=='train'];medians=[]\n for j in range(p):\n  if j in cat:medians.append(None);continue\n  values=sorted(F(r['x'][j])for r in train);n=len(values);medians.append(values[n//2]if n%2 else(values[n//2-1]+values[n//2])/2)\n def transform(r):return[F(v)if j in cat else F(int(F(v)>medians[j]))for j,v in enumerate(r['x'])]\n counts={}\n for r in train:\n  key=tuple(transform(r));n,s=counts.get(key,(0,0));counts[key]=(n+1,s+int(r['y']))\n probabilities={k:F(s+1,n+2)for k,(n,s)in counts.items()};fallback=F(sum(int(r['y'])for r in train)+1,len(train)+2);scored=[]\n for i,r in enumerate(raw):\n  eligible=r['role']!='excluded';z=transform(r)if eligible else None;key=None if z is None else tuple(z);score=None if not eligible else probabilities.get(key,fallback)\n  scored.append(dict(id=r['id'],index=i,role=r['role'],group=r['group'],y=None if r['y']is None else F(r['y']),score=score,w=F(1),eligible=eligible,transformedX=z,unseenCell=None if not eligible else key not in probabilities))\n return dict(medians=medians,cells=counts,probabilities=probabilities,fallback=fallback,rows=scored,trainIDs=[r['id']for r in train])\n\n\nimport csv,json,hashlib,argparse,datetime\nfrom pathlib import Path\ndef missing(v):return None if v in ['', '.',None]else v\ndef load_sources(folder):\n def read_csv(name):\n  with (folder/name).open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))\n wb=read_csv('actual64-country-four-indicators-original-2024.csv')\n codes=['NY.GDP.PCAP.KD','NY.GDP.MKTP.KD.ZG','FP.CPI.TOTL.ZG','SP.DYN.LE00.IN']\n lookup={(r['countryISO3'],r['indicatorID']):r for r in wb};country=[]\n for i,iso in enumerate(sorted({r['countryISO3']for r in wb}),1):\n  native=[lookup[iso,c]for c in codes];v=[missing(r['originalValueToken'])for r in native]\n  country.append(dict(id=iso+':2024',sourceRow=i,originalID=iso,x=v[:3],y=None if v[3]is None else str(int(F(v[3])>=80)),group=None if v[0]is None else str(int(F(v[0])>=25000)),nativeTarget=v[3],nativeSourceRows=';'.join(r['sourceRow']for r in native)))\n nls=read_csv('actual3613-NLS-original52-fields-groups-roles.csv');person=[]\n for r in nls:\n  y=missing(r['wage76']);person.append(dict(id='person:'+r['sourceRow'],sourceRow=int(r['sourceRow']),originalID=r['id'],x=[missing(r[k])for k in ['ed76','age76','nearc4']],y=None if y is None else str(int(F(y)>=500)),group=missing(r['black']),nativeTarget=y,nativeSourceRows=r['sourceRow']))\n ch=read_csv('actual3150-churn-original14-fields-groups-roles.csv');company=[]\n for r in ch:\n  company.append(dict(id='customer:'+r['sourceRow'],sourceRow=int(r['sourceRow']),originalID='',x=[missing(r[k])for k in ['Call  Failure','Complains','Subscription  Length','Seconds of Use']],y=missing(r['Churn']),group=missing(r['Tariff Plan']),nativeTarget=missing(r['Churn']),nativeSourceRows=r['sourceRow']))\n assert len(wb)==64 and len(country)==16 and len(nls)==3613 and len(ch)==3150\n assert [int(r['sourceRow'])for r in ch if r['Charge  Amount']=='10']==[474,2174,2274,2374,2674,2924,2974]\n models={}\n for kind,raw,cat,units in [('country',country,[],['constant2015USD/person','annualPercent','annualPercent']),('person',person,[2],['years','years','nativeCategory']),('company',company,[1],['count','nativeCategory','months','seconds'])]:\n  order=sorted(range(len(raw)),key=lambda i:(hashlib.sha256(('ML14-role|'+kind+'|'+raw[i]['id']).encode()).hexdigest(),i))\n  for rank,i in enumerate(order):\n   r=raw[i];r['plannedRole']='test'if rank%5==0 else'validation'if rank%5==1 else'train';r['eligible']=None not in r['x']+[r['y']];r['role']=r['plannedRole']if r['eligible']else'excluded';r['weight']='1'\n  models[kind]=dict(records=raw,categoricalFeatures=cat,featureUnits=units)\n assert sum(r['eligible']for r in person)==3017\n return models\n\ndef exact(v):return ''if v is None else str(v)\ndef approx(v):return ''if v is None else format(float(v),'.17g')\ndef scalar_fields(m,keys):\n out={}\n for k in keys:\n  out[k+'Exact']=exact(m[k]);out[k+'Approx']=approx(m[k])\n return out\nCOUNTS=['mass','positiveTargetMass','negativeTargetMass','predictedPositiveMass','predictedNegativeMass']\nRATES=['prevalence','selectionRate','accuracy','precision','negativePredictiveValue','TPR','FPR','TNR','FNR','F1','balancedAccuracy','Brier','BrierSum','totalCost','meanCost']\nSCENARIOS=[('equal',F(1),F(1)),('miss-five',F(1),F(5)),('alarm-five',F(5),F(1))]\ndef packed(v):\n if isinstance(v,F):return str(v)\n if isinstance(v,dict):return{str(k):packed(x)for k,x in v.items()}\n if isinstance(v,(tuple,list)):return[packed(x)for x in v]\n return v\ndef run_study(source,out):\n out.mkdir(parents=True,exist_ok=True);models=load_sources(source)\n tables={name:[]for name in ['predictions','lineage','fit-medians','fit-cells','validation-candidates','test-metrics','test-curves','calibration-bins','group-metrics','chart-points']}\n studies={};charts=[]\n def point(kind,chart,series,index,x,y,xunit='dimensionless',yunit='dimensionless',role='test',tag=''):\n  tables['chart-points'].append(dict(kind=kind,chart=chart,series=series,index=index,xExact=exact(x),xApprox=approx(x),yExact=exact(y),yApprox=approx(y),xUnit=xunit,yUnit=yunit,role=role,tag=tag))\n for kind,M in models.items():\n  fit=actual_model(M);rr=fit['rows'];native=M['records'];test=scoped(rr,'test');cv=curves(test);cal=calibrate(test,[F(0),F(1,5),F(2,5),F(3,5),F(4,5),F(1)]);scenarios=[]\n  for i,r in enumerate(rr):\n   n=native[i];reason=''if r['eligible']else'required-X-or-Y-missing'\n   tables['predictions'].append(dict(kind=kind,id=r['id'],sourceRow=n['sourceRow'],originalID=n['originalID'],plannedRole=n['plannedRole'],role=r['role'],group=''if r['group']is None else r['group'],eligible=int(r['eligible']),targetExact=exact(r['y']),probabilityExact=exact(r['score']),probabilityApprox=approx(r['score']),unseenCell=''if r['unseenCell']is None else int(r['unseenCell']),transformedX=''if r['transformedX']is None else'|'.join(map(str,r['transformedX'])),reason=reason))\n   tables['lineage'].append(dict(kind=kind,id=r['id'],sourceRow=n['sourceRow'],originalID=n['originalID'],nativeSourceRows=n['nativeSourceRows'],rawX='|'.join(''if x is None else x for x in n['x']),nativeTarget=''if n['nativeTarget']is None else n['nativeTarget'],derivedTarget=exact(r['y']),nativeGroup=''if n['group']is None else n['group'],plannedRole=n['plannedRole'],role=r['role'],eligible=int(r['eligible']),analyticalMass='1',reason=reason))\n  for j,v in enumerate(fit['medians']):tables['fit-medians'].append(dict(kind=kind,feature=j,categorical=int(j in M['categoricalFeatures']),fitRows=len(fit['trainIDs']),medianExact=exact(v),medianApprox=approx(v),unit=M['featureUnits'][j]))\n  for key,(mass,pos)in fit['cells'].items():tables['fit-cells'].append(dict(kind=kind,cell='|'.join(map(str,key)),trainingRows=mass,positiveRows=pos,probabilityExact=exact(fit['probabilities'][key]),probabilityApprox=approx(fit['probabilities'][key]),fallbackExact=exact(fit['fallback']),fallbackApprox=approx(fit['fallback'])))\n  for j,p in enumerate(cv['points']):\n   policy=p['policy'];tables['test-curves'].append(dict(kind=kind,point=j,policy=policy if isinstance(policy,str)else'threshold',thresholdExact=''if isinstance(policy,str)else exact(policy),thresholdApprox=''if isinstance(policy,str)else approx(policy),**scalar_fields(p,['TP','FP','FN','TN','TPR','FPR','precision','recall'])))\n   point(kind,'roc','ROC',j,p['FPR'],p['TPR']);point(kind,'pr','PR-observed',j,p['recall'],p['precision'])\n  for b in cal['bins']:\n   tables['calibration-bins'].append(dict(kind=kind,bin=b['index'],leftExact=str(F(b['index'],5)),rightExact=str(F(b['index']+1,5)),rightClosed=int(b['index']==4),rows=b['rows'],ids=';'.join(str(i)for i in b['ids']),**scalar_fields(b,['mass','meanPrediction','eventRate','gap','absoluteGap','scoreVariance','scoreTargetCovariance','withinBinCorrection'])))\n   point(kind,'reliability','Binary event rate',b['index'],b['meanPrediction'],b['eventRate'],tag='rows='+str(b['rows']))\n  for j,r in enumerate(test):\n   point(kind,'test-scores','Training-fitted probability',j,F(j+1),r['score'],'test-row position','probability',tag=r['id'])\n   point(kind,'test-scores','Observed Y',j,F(j+1),r['y'],'test-row position','binary target',tag=r['id'])\n  for name,fp,fn in SCENARIOS:\n   choice=choose(rr,{},(fp,fn));gm=groups(test,choice['selectedPolicy'],(fp,fn));scenarios.append(dict(name=name,costs=dict(falsePositive=fp,falseNegative=fn),selection=choice,groups=gm));ev=choice['evaluation']\n   for c in choice['candidates']:\n    policy=c['policy'];mm=c['metrics'];tables['validation-candidates'].append(dict(kind=kind,scenario=name,candidate=c['index'],selected=int(c['index']==choice['selectedIndex']),policy=policy if isinstance(policy,str)else'threshold',thresholdExact=''if isinstance(policy,str)else exact(policy),thresholdApprox=''if isinstance(policy,str)else approx(policy),feasible=int(c['feasible']),reasons=';'.join(c['reasons']),**{k+'Exact':str(v)for k,v in mm['confusion'].items()},**scalar_fields(mm,COUNTS+['TPR','FPR','precision','meanCost','totalCost'])))\n    point(kind,'validation-cost',name,c['index'],F(c['index']),mm['meanCost'],'candidate index','hypothetical cost units/mass','validation',tag=exact(policy))\n   mm={**ev,**ev['confusion'],**{k:cv[k]for k in ['ROC_AUC','averagePrecision','PRTrapezoidWithInitialPrecisionOne']},**{k:cal[k]for k in ['ECE','reliability','resolution','uncertainty','withinBinCorrection','BrierIdentityResidual']}}\n   for key in ['TP','FP','FN','TN']+COUNTS+RATES+['ROC_AUC','averagePrecision','PRTrapezoidWithInitialPrecisionOne','ECE','reliability','resolution','uncertainty','withinBinCorrection','BrierIdentityResidual']:\n    unit='rows'if key in ['TP','FP','FN','TN']+COUNTS else'hypothetical cost units'if key=='totalCost'else'hypothetical cost units/mass'if key=='meanCost'else'sum squared-probability loss'if key=='BrierSum'else'dimensionless'\n    tables['test-metrics'].append(dict(kind=kind,scenario=name,metric=key,valueExact=exact(mm[key]),valueApprox=approx(mm[key]),unit=unit))\n   allg=[('overall','all',gm['overall'])]+[('known',str(g['group']),g['metrics'])for g in gm['groups']]+[('unknown','',gm['unknownGroup'])]\n   for j,(typ,token,g)in enumerate(allg):\n    tables['group-metrics'].append(dict(kind=kind,scenario=name,groupType=typ,groupToken=token,retainedRows=g.get('retainedRows',sum((r['group']==token)if typ=='known'else(r['group']is None)if typ=='unknown'else True for r in test)),**{k+'Exact':str(v)for k,v in g['confusion'].items()},**scalar_fields(g,COUNTS+RATES)))\n    if typ=='known':point(kind,'group-TPR',name,j-1,F(j-1),g['TPR'],'declared group position','TPR',tag=token)\n  studies[kind]=dict(kind=kind,rows=len(native),eligibleRows=sum(r['eligible']for r in rr),trainingIDs=fit['trainIDs'],fitMedians=fit['medians'],fitCells=[dict(cell=list(k),mass=n,positive=s,probability=fit['probabilities'][k])for k,(n,s)in fit['cells'].items()],fallback=fit['fallback'],scenarios=scenarios,testCurves=cv,testCalibration=cal,rowsScored=rr)\n files=[]\n for name,rows in tables.items():\n  p=out/('computed-'+name+'.csv')\n  with p.open('w',encoding='utf8',newline='')as f:w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows)\n  files.append(dict(file=p.name,rows=len(rows),columns=len(rows[0]),bodyFields=len(rows)*len(rows[0]),sha256=hashlib.sha256(p.read_bytes()).hexdigest()))\n (out/'study.json').write_text(json.dumps(packed(studies),ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\n sourceFiles=[source/n for n in ['actual64-country-four-indicators-original-2024.csv','actual3613-NLS-original52-fields-groups-roles.csv','actual3150-churn-original14-fields-groups-roles.csv']]\n provenance=dict(chapter='ML-14',arithmetic='Python stdlib Fraction exact finite values from original decimal strings; binary64 valueApprox is display only.',inputs=[dict(file=p.name,sha256=hashlib.sha256(p.read_bytes()).hexdigest())for p in sourceFiles],priorEngineModelsScoresOrComputedFilesRead=False,roleRule=\"SHA256('ML14-role|'+kind+'|'+ID),rankmod5=0test/1validation/others train before eligibility\",costs='Hypothetical1/1,1/5,5/1; no causal intervention returns',files=files,observations={k:dict(sourceRows=v['rows'],eligibleRows=v['eligibleRows'],trainingRows=len(v['trainingIDs']))for k,v in studies.items()})\n (out/'provenance.json').write_text(json.dumps(provenance,ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\n print(json.dumps(dict(status='PASS standalone completed',files=len(files),bodyFields=sum(f['bodyFields']for f in files),observations=provenance['observations'])))\n\n# Fixed declared examples: full web budget/option validation is not reproduced.\nfrom html import escape\nimport textwrap\ndef validated_rows(raw):\n for r in raw:\n  assert F(str(r.get('weight','1')))>=0,'negative analytical mass'\n  assert r['score']is None or 0<=F(str(r['score']))<=1,'score outside zero/one'\n  assert r['y']is None or F(str(int(r['y']))if isinstance(r['y'],bool)else str(r['y']))in [0,1],'binary target required'\n return read(raw)\ndef serial(v):\n if isinstance(v,F):return dict(exactFraction=str(v),value=float(v))\n if isinstance(v,(list,tuple)):return[serial(x)for x in v]\n if isinstance(v,dict):return{k:serial(x)for k,x in v.items()}\n return v\ndef fixed_svg(path,points,title,xlabel,ylabel,legend):\n use=[p for p in points if p['xExact']!=''and p['yExact']!=''];xs=[float(F(p['xExact']))for p in use];ys=[float(F(p['yExact']))for p in use]\n xmin=min(xs,default=0);xmax=max(xs,default=1);ymin=min([0]+ys);ymax=max([0]+ys)\n if xmin==xmax:xmin-=.5;xmax+=.5\n if ymin==ymax:ymax=ymin+1\n X=lambda v:85+(float(v)-xmin)/(xmax-xmin)*480;Y=lambda v:278-(float(v)-ymin)/(ymax-ymin)*175\n s='<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"620\" height=\"360\" viewBox=\"0 0 620 360\"><rect width=\"620\" height=\"360\" fill=\"white\"/><g font-family=\"Arial, sans-serif\" font-size=\"13\" fill=\"#17324d\">'\n for i,line in enumerate(textwrap.wrap(title,width=65)):s+='<text x=\"25\" y=\"'+str(24+i*18)+'\">'+escape(line)+'</text>'\n colors=['#176b9b','#b85e18','#437e4d']\n for i,label in enumerate(legend):s+='<circle cx=\"'+str(30+i*250)+'\" cy=\"76\" r=\"4\" fill=\"'+colors[i%3]+'\"/><text x=\"'+str(42+i*250)+'\" y=\"80\">'+escape(label)+'</text>'\n s+='<path d=\"M85 98V278H575\" fill=\"none\" stroke=\"#52677d\"/><text text-anchor=\"middle\" x=\"325\" y=\"338\">'+escape(xlabel)+'</text><text text-anchor=\"middle\" transform=\"translate(21,190) rotate(-90)\">'+escape(ylabel)+'</text>'\n for i in range(5):\n  xx=xmin+(xmax-xmin)*i/4;yy=ymin+(ymax-ymin)*i/4;s+='<text text-anchor=\"middle\" x=\"'+format(X(xx),'.9g')+'\" y=\"305\">'+format(xx,'.4g')+'</text><text text-anchor=\"end\" x=\"77\" y=\"'+format(Y(yy)+4,'.9g')+'\">'+format(yy,'.4g')+'</text>'\n for p in use:s+='<circle cx=\"'+format(X(F(p['xExact'])),'.9g')+'\" cy=\"'+format(Y(F(p['yExact'])),'.9g')+'\" r=\"3\" fill=\"'+colors[p['series']%3]+'\"/>'\n path.write_text(s+'</g></svg>',encoding='utf8')\ndef fixed_run():\n ap=argparse.ArgumentParser();ap.add_argument('--out',type=Path,default=Path('results'));ap.add_argument('--data-dir',type=Path,default=Path(__file__).resolve().parent.parent/'ml14-sources');args=ap.parse_args();args.out.mkdir(parents=True,exist_ok=True)\n api=FIXED['api'];a=FIXED['args'];summary=[];points=[];xlabel='Declared index';ylabel='Value';legend=['Declared result']\n def metric(name,v,unit='dimensionless'):\n  q=None if v is None else v if isinstance(v,F)else F(v);summary.append(dict(metric=name,value='undefined'if q is None else format(float(q),'.9g'),exactValue=''if q is None else str(q),unit=unit,defined=int(q is not None)))\n def pt(i,x,y,ident='',series=0):\n  points.append(dict(series=series,index=i,xExact=''if x is None else str(F(x)),x='undefined'if x is None else format(float(x),'.9g'),yExact=''if y is None else str(F(y)),y='undefined'if y is None else format(float(y),'.9g'),id=str(ident)))\n if api=='realdata':\n  models=load_sources(args.data_dir);model=models[a['kind']];fit=actual_model(model);rr=fit['rows'];test=scoped(rr,'test');scenarios=[]\n  for name,fp,fn in SCENARIOS:\n   c=choose(rr,{},(fp,fn));scenarios.append(dict(name=name,selection=c));metric(name+'Threshold',c['selectedPolicy']);metric(name+'TestCost',c['evaluation']['meanCost'],'hypothetical cost units/mass')\n  cv=curves(test);cal=calibrate(test,[F(0),F(1,5),F(2,5),F(3,5),F(4,5),F(1)]);metric('testAUC',cv['ROC_AUC']);metric('testAP',cv['averagePrecision']);metric('testBrier',cal['Brier']);metric('eligibleRows',sum(r['eligible']for r in rr),'rows')\n  for i,r in enumerate(test):pt(i,i+1,r['score'],r['id'],0);pt(i,i+1,r['y'],r['id'],1)\n  full=dict(kind=a['kind'],fitMedians=fit['medians'],fitCells=[dict(cell=list(k),mass=n,positive=s,probability=fit['probabilities'][k])for k,(n,s)in fit['cells'].items()],rowsScored=rr,scenarios=scenarios,testCurves=cv,testCalibration=cal);xlabel='Test row, native order';ylabel='Y or probability';legend=['Training-fitted probability','Observed Y']\n else:\n  rr=validated_rows(a['rows']);role=a.get('role','all');frame=scoped(rr,role);cc=cost(a.get('costs'));t=policy(a.get('threshold','1/2'))\n  if api=='metrics':\n   full=metrics(frame,t,cc)\n   for k in ['mass','accuracy','precision','TPR','FPR','F1','Brier','meanCost']:metric(k,full[k],'mass'if k=='mass'else'hypothetical cost units/mass'if k=='meanCost'else'dimensionless')\n   metric('BayesThreshold',full['bayesThreshold'])\n   for i,k in enumerate(['TP','FP','FN','TN']):pt(i,i,full['confusion'][k],k)\n   xlabel='TP / FP / FN / TN positions';ylabel='Analytical mass'\n  elif api=='curves':\n   full=curves(frame)\n   for k in ['ROC_AUC','averagePrecision','PRTrapezoidWithInitialPrecisionOne']:metric(k,full[k])\n   for i,p in enumerate(full['points']):pt(i,p['FPR'],p['TPR'],str(p['policy']))\n   xlabel='False positive rate';ylabel='True positive rate';legend=['Observed ROC operating points']\n  elif api=='choose':\n   full=choose(rr,a,cc);metric('selectedIndex',full['selectedIndex'],'candidate index');metric('minimumCost',None if full['selectedValidation']is None else full['selectedValidation']['meanCost'],'hypothetical cost units/mass');metric('feasible',int(full['selectedIndex']is not None),'indicator')\n   for c in full['candidates']:pt(c['index'],c['index'],c['metrics']['meanCost'],str(c['policy']))\n   xlabel='Validation candidate';ylabel='Assumed cost / mass';legend=['Validation candidate costs']\n  elif api=='calibrate':\n   full=calibrate(frame,[F(str(e))for e in a.get('binEdges',['0','1/5','2/5','3/5','4/5','1'])])\n   for k in ['ECE','Brier','uncertainty','resolution','reliability','withinBinCorrection','BrierIdentityResidual']:metric(k,full[k])\n   for b in full['bins']:pt(b['index'],b['meanPrediction'],b['eventRate'],'bin:'+str(b['index']))\n   xlabel='Bin mean forecast';ylabel='Bin event rate';legend=['Binary-event reliability']\n  elif api=='groups':\n   full=groups(frame,t,cc);metric('overallTPR',full['overall']['TPR']);metric('TPRGap',full['gaps']['TPR']['value']);metric('precisionGap',full['gaps']['precision']['value']);metric('unknownMass',full['unknownGroup']['mass'],'mass');metric('partitionResidual',full['partitionMassResidual'],'mass')\n   for i,g in enumerate(full['groups']):pt(i,i,g['metrics']['TPR'],str(g['group']))\n   xlabel='Declared group position';ylabel='True positive rate';legend=['Known-group TPR']\n  else:raise ValueError('unknown fixed API')\n def csvout(name,rows):\n  with(args.out/name).open('w',encoding='utf8',newline='')as f:w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows)\n csvout('summary.csv',summary);csvout('plot-points.csv',points);fixed_svg(args.out/'plot.svg',points,FIXED['title'],xlabel,ylabel,legend)\n (args.out/'full.json').write_text(json.dumps(dict(api=api,variant=FIXED['variant'],input=FIXED['args'],arithmetic='Python standard-library Fraction, declared fixed example; full web validator/budgets not reproduced',result=serial(full)),ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\n print(json.dumps(dict(api=api,variant=FIXED['variant'],summaryMetrics=len(summary),plotSlots=len(points))))\n\nFIXED={'api': 'choose', 'variant': 'miss-five', 'args': {'rows': [{'id': 'a', 'score': '.9', 'y': 1, 'group': 'A', 'role': 'validation'}, {'id': 'b', 'score': '.8', 'y': 1, 'group': 'A', 'role': 'validation'}, {'id': 'c', 'score': '.8', 'y': 0, 'group': 'A', 'role': 'validation'}, {'id': 'd', 'score': '.6', 'y': 0, 'group': 'B', 'role': 'validation'}, {'id': 'e', 'score': '.4', 'y': 1, 'group': 'B', 'role': 'validation'}, {'id': 'f', 'score': '.1', 'y': 0, 'group': 'B', 'role': 'validation'}], 'costs': {'falsePositive': '1', 'falseNegative': '5'}, 'evaluationRole': 'none'}, 'title': 'Validation-only threshold with missed-case cost five'}\nif __name__=='__main__':fixed_run()\n",
        "codeText": "#!/usr/bin/env python3\n\"\"\"ML14 standalone exact finite study, Python standard library only.\nInputs: only the three retained factual source CSVs below.\nDerived role/target/group/eligibility columns in those CSVs are NOT inputs.\nRebuilds SHA256 roles, train-only medians/cell scores, validation thresholds,\ntest curves, binary-event reliability and descriptive group ledgers.\nCosts 1/1,1/5,5/1 are hypothetical units, not measured intervention returns.\nThis is author public reproduction, not independent scientific review.\n\"\"\"\n\"\"\"Author Fraction reference, separate from product JavaScript; not independent peer.\"\"\"\nfrom fractions import Fraction as F\nfrom collections import Counter,defaultdict\ndef read(raw):\n rows=[]\n for i,r in enumerate(raw):\n  s=None if r['score']is None else F(str(r['score']));y=None if r['y']is None else F(int(r['y']))if isinstance(r['y'],bool)else F(str(r['y']));w=F(str(r.get('weight','1')));role=r.get('role','evaluation')\n  rows.append(dict(id=r['id'],index=i,score=s,y=y,w=w,role=role,group=r.get('group'),eligible=s is not None and y is not None and w>0 and role!='excluded'))\n return rows\ndef scoped(rows,role='all'):return rows if role=='all'else[r for r in rows if r['role']==role]\ndef divide(n,d):return None if not d else n/d\ndef policy(v):return v if v in ['always-negative','always-positive']else F(str(v))\ndef positive(p,s):return p=='always-positive'if isinstance(p,str)else s>=p\ndef cost(a=None):\n a={}if a is None else a;fp=F(str(a.get('falsePositive','1')));fn=F(str(a.get('falseNegative','1')));return fp,fn\ndef metrics(rows,threshold=F(1,2),cc=(F(1),F(1))):\n counts=dict(TP=F(0),FP=F(0),FN=F(0),TN=F(0));brier=F(0);pred=[]\n for r in rows:\n  if not r['eligible']:pred.append(dict(id=r['id'],index=r['index'],eligible=False,decision=None,probability=None,Brier=None));continue\n  yes=positive(threshold,r['score']);cell=('T'if yes==bool(r['y'])else'F')+('P'if yes else'N');counts[cell]+=r['w'];loss=(r['score']-r['y'])**2;brier+=r['w']*loss;pred.append(dict(id=r['id'],index=r['index'],eligible=True,decision=int(yes),probability=r['score'],Brier=loss))\n TP,FP,FN,TN=[counts[k]for k in ['TP','FP','FN','TN']];P=TP+FN;N=TN+FP;mass=P+N;PP=TP+FP;PN=TN+FN;TPR=divide(TP,P);TNR=divide(TN,N);total=FP*cc[0]+FN*cc[1]\n return dict(confusion=counts,mass=mass,positiveTargetMass=P,negativeTargetMass=N,predictedPositiveMass=PP,predictedNegativeMass=PN,prevalence=divide(P,mass),selectionRate=divide(PP,mass),accuracy=divide(TP+TN,mass),precision=divide(TP,PP),negativePredictiveValue=divide(TN,PN),TPR=TPR,FPR=divide(FP,N),TNR=TNR,FNR=divide(FN,P),F1=divide(2*TP,2*TP+FP+FN),balancedAccuracy=None if TPR is None or TNR is None else(TPR+TNR)/2,Brier=divide(brier,mass),BrierSum=brier,totalCost=total,meanCost=divide(total,mass),predictions=pred,bayesThreshold=divide(cc[0],sum(cc)))\ndef curves(rows):\n use=[r for r in rows if r['eligible']];pos=Counter();neg=Counter()\n for r in use:(pos if r['y']else neg)[r['score']]+=r['w']\n P=sum(pos.values(),F(0));N=sum(neg.values(),F(0));pairs=F(0)\n for a,wa in pos.items():\n  for b,wb in neg.items():pairs+=wa*wb*(F(1)if a>b else F(1,2)if a==b else F(0))\n thresholds=['always-negative']+sorted({r['score']for r in use},reverse=True);points=[];AP=F(0);trap=F(0);lastR=F(0);lastP=F(1)\n for i,p in enumerate(thresholds):\n  m=metrics(rows,p);points.append(dict(policy=p,TP=m['confusion']['TP'],FP=m['confusion']['FP'],FN=m['confusion']['FN'],TN=m['confusion']['TN'],TPR=m['TPR'],FPR=m['FPR'],precision=m['precision'],recall=m['TPR']))\n  if i and P:\n   R=m['TPR'];PP=m['precision'];AP+=(R-lastR)*PP;trap+=(R-lastR)*(PP+lastP)/2;lastR=R;lastP=PP\n return dict(positiveMass=P,negativeMass=N,ROC_AUC=divide(pairs,P*N),weightedConcordantPlusHalfTiedMass=pairs,averagePrecision=AP if P else None,PRTrapezoidWithInitialPrecisionOne=trap if P else None,points=points)\ndef choose(rows,a,cc):\n sr=a.get('selectionRole','validation');er=a.get('evaluationRole','test');rr=scoped(rows,sr);thresholds=[policy(t)for t in a['thresholds']]if'thresholds'in a else['always-negative']+sorted({r['score']for r in rr if r['eligible']},reverse=True)\n candidates=[]\n for i,p in enumerate(thresholds):\n  m=metrics(rr,p,cc);reasons=[]\n  if'minTPR'in a and(m['TPR']is None or m['TPR']<F(str(a['minTPR']))):reasons.append('TPR-undefined'if m['TPR']is None else'below-minTPR')\n  if'maxFPR'in a and(m['FPR']is None or m['FPR']>F(str(a['maxFPR']))):reasons.append('FPR-undefined'if m['FPR']is None else'above-maxFPR')\n  candidates.append(dict(index=i,policy=p,metrics=m,feasible=not reasons,reasons=reasons))\n eligible=[c for c in candidates if c['feasible']];best=min(eligible,key=lambda c:(c['metrics']['meanCost'],c['index']))if eligible else None\n return dict(selectedIndex=None if best is None else best['index'],selectedPolicy=None if best is None else best['policy'],candidates=candidates,selectedValidation=None if best is None else best['metrics'],evaluation=None if best is None or er=='none'else metrics(scoped(rows,er),best['policy'],cc),selectionIDs=[r['id']for r in rr if r['eligible']])\ndef calibrate(rows,ee):\n buckets=[[]for _ in range(len(ee)-1)]\n for r in rows:\n  if not r['eligible']:continue\n  j=next((i for i in range(len(ee)-1)if r['score']<ee[i+1]),len(ee)-2);buckets[j].append(r)\n mass=sum((r['w']for r in rows if r['eligible']),F(0));P=sum((r['w']*r['y']for r in rows if r['eligible']),F(0));pi=divide(P,mass);Brier=None if not mass else sum((r['w']*(r['score']-r['y'])**2 for r in rows if r['eligible']),F(0))/mass;ECE=F(0);reliability=F(0);resolution=F(0);correction=F(0);bins=[]\n for i,rr in enumerate(buckets):\n  w=sum((r['w']for r in rr),F(0));mp=None if not w else sum((r['w']*r['score']for r in rr),F(0))/w;o=None if not w else sum((r['w']*r['y']for r in rr),F(0))/w\n  variance=None if not w else sum((r['w']*(r['score']-mp)**2 for r in rr),F(0))/w\n  covariance=None if not w else sum((r['w']*(r['score']-mp)*(r['y']-o)for r in rr),F(0))/w\n  bc=None if not w else variance-2*covariance;gap=None if not w else mp-o\n  bins.append(dict(index=i,rows=len(rr),mass=w,meanPrediction=mp,eventRate=o,gap=gap,absoluteGap=None if gap is None else abs(gap),scoreVariance=variance,scoreTargetCovariance=covariance,withinBinCorrection=bc,ids=[r['id']for r in rr]))\n  if w:\n   share=w/mass;ECE+=share*abs(gap);reliability+=share*gap**2;resolution+=share*(o-pi)**2;correction+=share*bc\n uncertainty=None if pi is None else pi*(1-pi);residual=None if Brier is None else Brier-(uncertainty-resolution+reliability+correction)\n return dict(mass=mass,prevalence=pi,Brier=Brier,ECE=ECE if mass else None,reliability=reliability if mass else None,resolution=resolution if mass else None,uncertainty=uncertainty,withinBinCorrection=correction if mass else None,BrierIdentityResidual=residual,bins=bins)\ndef typed(v):return type(v).__name__,v\ndef groups(rows,p,cc):\n bins={}\n for r in rows:\n  if r['group']is not None:bins.setdefault(typed(r['group']),[]).append(r)\n gm=[dict(group=rr[0]['group'],metrics=metrics(rr,p,cc))for rr in bins.values()];overall=metrics(rows,p,cc);unknown=metrics([r for r in rows if r['group']is None],p,cc);gaps={}\n for key in ['prevalence','selectionRate','TPR','FPR','precision','accuracy','meanCost']:\n  positive=[g for g in gm if g['metrics']['mass']>0];undefined=[g['group']for g in positive if g['metrics'][key]is None];vals=[g['metrics'][key]for g in positive if g['metrics'][key]is not None]\n  gaps[key]=dict(value=None if len(positive)<2 or undefined else max(vals)-min(vals),undefinedGroups=undefined,comparedPositiveMassGroups=[g['group']for g in positive])\n return dict(overall=overall,groups=gm,unknownGroup=unknown,gaps=gaps,partitionMassResidual=overall['mass']-unknown['mass']-sum((g['metrics']['mass']for g in gm),F(0)))\ndef actual_model(M):\n raw=M['records'];cat=M['categoricalFeatures'];p=len(raw[0]['x']);train=[r for r in raw if r['role']=='train'];medians=[]\n for j in range(p):\n  if j in cat:medians.append(None);continue\n  values=sorted(F(r['x'][j])for r in train);n=len(values);medians.append(values[n//2]if n%2 else(values[n//2-1]+values[n//2])/2)\n def transform(r):return[F(v)if j in cat else F(int(F(v)>medians[j]))for j,v in enumerate(r['x'])]\n counts={}\n for r in train:\n  key=tuple(transform(r));n,s=counts.get(key,(0,0));counts[key]=(n+1,s+int(r['y']))\n probabilities={k:F(s+1,n+2)for k,(n,s)in counts.items()};fallback=F(sum(int(r['y'])for r in train)+1,len(train)+2);scored=[]\n for i,r in enumerate(raw):\n  eligible=r['role']!='excluded';z=transform(r)if eligible else None;key=None if z is None else tuple(z);score=None if not eligible else probabilities.get(key,fallback)\n  scored.append(dict(id=r['id'],index=i,role=r['role'],group=r['group'],y=None if r['y']is None else F(r['y']),score=score,w=F(1),eligible=eligible,transformedX=z,unseenCell=None if not eligible else key not in probabilities))\n return dict(medians=medians,cells=counts,probabilities=probabilities,fallback=fallback,rows=scored,trainIDs=[r['id']for r in train])\n\n\nimport csv,json,hashlib,argparse,datetime\nfrom pathlib import Path\ndef missing(v):return None if v in ['', '.',None]else v\ndef load_sources(folder):\n def read_csv(name):\n  with (folder/name).open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))\n wb=read_csv('actual64-country-four-indicators-original-2024.csv')\n codes=['NY.GDP.PCAP.KD','NY.GDP.MKTP.KD.ZG','FP.CPI.TOTL.ZG','SP.DYN.LE00.IN']\n lookup={(r['countryISO3'],r['indicatorID']):r for r in wb};country=[]\n for i,iso in enumerate(sorted({r['countryISO3']for r in wb}),1):\n  native=[lookup[iso,c]for c in codes];v=[missing(r['originalValueToken'])for r in native]\n  country.append(dict(id=iso+':2024',sourceRow=i,originalID=iso,x=v[:3],y=None if v[3]is None else str(int(F(v[3])>=80)),group=None if v[0]is None else str(int(F(v[0])>=25000)),nativeTarget=v[3],nativeSourceRows=';'.join(r['sourceRow']for r in native)))\n nls=read_csv('actual3613-NLS-original52-fields-groups-roles.csv');person=[]\n for r in nls:\n  y=missing(r['wage76']);person.append(dict(id='person:'+r['sourceRow'],sourceRow=int(r['sourceRow']),originalID=r['id'],x=[missing(r[k])for k in ['ed76','age76','nearc4']],y=None if y is None else str(int(F(y)>=500)),group=missing(r['black']),nativeTarget=y,nativeSourceRows=r['sourceRow']))\n ch=read_csv('actual3150-churn-original14-fields-groups-roles.csv');company=[]\n for r in ch:\n  company.append(dict(id='customer:'+r['sourceRow'],sourceRow=int(r['sourceRow']),originalID='',x=[missing(r[k])for k in ['Call  Failure','Complains','Subscription  Length','Seconds of Use']],y=missing(r['Churn']),group=missing(r['Tariff Plan']),nativeTarget=missing(r['Churn']),nativeSourceRows=r['sourceRow']))\n assert len(wb)==64 and len(country)==16 and len(nls)==3613 and len(ch)==3150\n assert [int(r['sourceRow'])for r in ch if r['Charge  Amount']=='10']==[474,2174,2274,2374,2674,2924,2974]\n models={}\n for kind,raw,cat,units in [('country',country,[],['constant2015USD/person','annualPercent','annualPercent']),('person',person,[2],['years','years','nativeCategory']),('company',company,[1],['count','nativeCategory','months','seconds'])]:\n  order=sorted(range(len(raw)),key=lambda i:(hashlib.sha256(('ML14-role|'+kind+'|'+raw[i]['id']).encode()).hexdigest(),i))\n  for rank,i in enumerate(order):\n   r=raw[i];r['plannedRole']='test'if rank%5==0 else'validation'if rank%5==1 else'train';r['eligible']=None not in r['x']+[r['y']];r['role']=r['plannedRole']if r['eligible']else'excluded';r['weight']='1'\n  models[kind]=dict(records=raw,categoricalFeatures=cat,featureUnits=units)\n assert sum(r['eligible']for r in person)==3017\n return models\n\ndef exact(v):return ''if v is None else str(v)\ndef approx(v):return ''if v is None else format(float(v),'.17g')\ndef scalar_fields(m,keys):\n out={}\n for k in keys:\n  out[k+'Exact']=exact(m[k]);out[k+'Approx']=approx(m[k])\n return out\nCOUNTS=['mass','positiveTargetMass','negativeTargetMass','predictedPositiveMass','predictedNegativeMass']\nRATES=['prevalence','selectionRate','accuracy','precision','negativePredictiveValue','TPR','FPR','TNR','FNR','F1','balancedAccuracy','Brier','BrierSum','totalCost','meanCost']\nSCENARIOS=[('equal',F(1),F(1)),('miss-five',F(1),F(5)),('alarm-five',F(5),F(1))]\ndef packed(v):\n if isinstance(v,F):return str(v)\n if isinstance(v,dict):return{str(k):packed(x)for k,x in v.items()}\n if isinstance(v,(tuple,list)):return[packed(x)for x in v]\n return v\ndef run_study(source,out):\n out.mkdir(parents=True,exist_ok=True);models=load_sources(source)\n tables={name:[]for name in ['predictions','lineage','fit-medians','fit-cells','validation-candidates','test-metrics','test-curves','calibration-bins','group-metrics','chart-points']}\n studies={};charts=[]\n def point(kind,chart,series,index,x,y,xunit='dimensionless',yunit='dimensionless',role='test',tag=''):\n  tables['chart-points'].append(dict(kind=kind,chart=chart,series=series,index=index,xExact=exact(x),xApprox=approx(x),yExact=exact(y),yApprox=approx(y),xUnit=xunit,yUnit=yunit,role=role,tag=tag))\n for kind,M in models.items():\n  fit=actual_model(M);rr=fit['rows'];native=M['records'];test=scoped(rr,'test');cv=curves(test);cal=calibrate(test,[F(0),F(1,5),F(2,5),F(3,5),F(4,5),F(1)]);scenarios=[]\n  for i,r in enumerate(rr):\n   n=native[i];reason=''if r['eligible']else'required-X-or-Y-missing'\n   tables['predictions'].append(dict(kind=kind,id=r['id'],sourceRow=n['sourceRow'],originalID=n['originalID'],plannedRole=n['plannedRole'],role=r['role'],group=''if r['group']is None else r['group'],eligible=int(r['eligible']),targetExact=exact(r['y']),probabilityExact=exact(r['score']),probabilityApprox=approx(r['score']),unseenCell=''if r['unseenCell']is None else int(r['unseenCell']),transformedX=''if r['transformedX']is None else'|'.join(map(str,r['transformedX'])),reason=reason))\n   tables['lineage'].append(dict(kind=kind,id=r['id'],sourceRow=n['sourceRow'],originalID=n['originalID'],nativeSourceRows=n['nativeSourceRows'],rawX='|'.join(''if x is None else x for x in n['x']),nativeTarget=''if n['nativeTarget']is None else n['nativeTarget'],derivedTarget=exact(r['y']),nativeGroup=''if n['group']is None else n['group'],plannedRole=n['plannedRole'],role=r['role'],eligible=int(r['eligible']),analyticalMass='1',reason=reason))\n  for j,v in enumerate(fit['medians']):tables['fit-medians'].append(dict(kind=kind,feature=j,categorical=int(j in M['categoricalFeatures']),fitRows=len(fit['trainIDs']),medianExact=exact(v),medianApprox=approx(v),unit=M['featureUnits'][j]))\n  for key,(mass,pos)in fit['cells'].items():tables['fit-cells'].append(dict(kind=kind,cell='|'.join(map(str,key)),trainingRows=mass,positiveRows=pos,probabilityExact=exact(fit['probabilities'][key]),probabilityApprox=approx(fit['probabilities'][key]),fallbackExact=exact(fit['fallback']),fallbackApprox=approx(fit['fallback'])))\n  for j,p in enumerate(cv['points']):\n   policy=p['policy'];tables['test-curves'].append(dict(kind=kind,point=j,policy=policy if isinstance(policy,str)else'threshold',thresholdExact=''if isinstance(policy,str)else exact(policy),thresholdApprox=''if isinstance(policy,str)else approx(policy),**scalar_fields(p,['TP','FP','FN','TN','TPR','FPR','precision','recall'])))\n   point(kind,'roc','ROC',j,p['FPR'],p['TPR']);point(kind,'pr','PR-observed',j,p['recall'],p['precision'])\n  for b in cal['bins']:\n   tables['calibration-bins'].append(dict(kind=kind,bin=b['index'],leftExact=str(F(b['index'],5)),rightExact=str(F(b['index']+1,5)),rightClosed=int(b['index']==4),rows=b['rows'],ids=';'.join(str(i)for i in b['ids']),**scalar_fields(b,['mass','meanPrediction','eventRate','gap','absoluteGap','scoreVariance','scoreTargetCovariance','withinBinCorrection'])))\n   point(kind,'reliability','Binary event rate',b['index'],b['meanPrediction'],b['eventRate'],tag='rows='+str(b['rows']))\n  for j,r in enumerate(test):\n   point(kind,'test-scores','Training-fitted probability',j,F(j+1),r['score'],'test-row position','probability',tag=r['id'])\n   point(kind,'test-scores','Observed Y',j,F(j+1),r['y'],'test-row position','binary target',tag=r['id'])\n  for name,fp,fn in SCENARIOS:\n   choice=choose(rr,{},(fp,fn));gm=groups(test,choice['selectedPolicy'],(fp,fn));scenarios.append(dict(name=name,costs=dict(falsePositive=fp,falseNegative=fn),selection=choice,groups=gm));ev=choice['evaluation']\n   for c in choice['candidates']:\n    policy=c['policy'];mm=c['metrics'];tables['validation-candidates'].append(dict(kind=kind,scenario=name,candidate=c['index'],selected=int(c['index']==choice['selectedIndex']),policy=policy if isinstance(policy,str)else'threshold',thresholdExact=''if isinstance(policy,str)else exact(policy),thresholdApprox=''if isinstance(policy,str)else approx(policy),feasible=int(c['feasible']),reasons=';'.join(c['reasons']),**{k+'Exact':str(v)for k,v in mm['confusion'].items()},**scalar_fields(mm,COUNTS+['TPR','FPR','precision','meanCost','totalCost'])))\n    point(kind,'validation-cost',name,c['index'],F(c['index']),mm['meanCost'],'candidate index','hypothetical cost units/mass','validation',tag=exact(policy))\n   mm={**ev,**ev['confusion'],**{k:cv[k]for k in ['ROC_AUC','averagePrecision','PRTrapezoidWithInitialPrecisionOne']},**{k:cal[k]for k in ['ECE','reliability','resolution','uncertainty','withinBinCorrection','BrierIdentityResidual']}}\n   for key in ['TP','FP','FN','TN']+COUNTS+RATES+['ROC_AUC','averagePrecision','PRTrapezoidWithInitialPrecisionOne','ECE','reliability','resolution','uncertainty','withinBinCorrection','BrierIdentityResidual']:\n    unit='rows'if key in ['TP','FP','FN','TN']+COUNTS else'hypothetical cost units'if key=='totalCost'else'hypothetical cost units/mass'if key=='meanCost'else'sum squared-probability loss'if key=='BrierSum'else'dimensionless'\n    tables['test-metrics'].append(dict(kind=kind,scenario=name,metric=key,valueExact=exact(mm[key]),valueApprox=approx(mm[key]),unit=unit))\n   allg=[('overall','all',gm['overall'])]+[('known',str(g['group']),g['metrics'])for g in gm['groups']]+[('unknown','',gm['unknownGroup'])]\n   for j,(typ,token,g)in enumerate(allg):\n    tables['group-metrics'].append(dict(kind=kind,scenario=name,groupType=typ,groupToken=token,retainedRows=g.get('retainedRows',sum((r['group']==token)if typ=='known'else(r['group']is None)if typ=='unknown'else True for r in test)),**{k+'Exact':str(v)for k,v in g['confusion'].items()},**scalar_fields(g,COUNTS+RATES)))\n    if typ=='known':point(kind,'group-TPR',name,j-1,F(j-1),g['TPR'],'declared group position','TPR',tag=token)\n  studies[kind]=dict(kind=kind,rows=len(native),eligibleRows=sum(r['eligible']for r in rr),trainingIDs=fit['trainIDs'],fitMedians=fit['medians'],fitCells=[dict(cell=list(k),mass=n,positive=s,probability=fit['probabilities'][k])for k,(n,s)in fit['cells'].items()],fallback=fit['fallback'],scenarios=scenarios,testCurves=cv,testCalibration=cal,rowsScored=rr)\n files=[]\n for name,rows in tables.items():\n  p=out/('computed-'+name+'.csv')\n  with p.open('w',encoding='utf8',newline='')as f:w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows)\n  files.append(dict(file=p.name,rows=len(rows),columns=len(rows[0]),bodyFields=len(rows)*len(rows[0]),sha256=hashlib.sha256(p.read_bytes()).hexdigest()))\n (out/'study.json').write_text(json.dumps(packed(studies),ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\n sourceFiles=[source/n for n in ['actual64-country-four-indicators-original-2024.csv','actual3613-NLS-original52-fields-groups-roles.csv','actual3150-churn-original14-fields-groups-roles.csv']]\n provenance=dict(chapter='ML-14',arithmetic='Python stdlib Fraction exact finite values from original decimal strings; binary64 valueApprox is display only.',inputs=[dict(file=p.name,sha256=hashlib.sha256(p.read_bytes()).hexdigest())for p in sourceFiles],priorEngineModelsScoresOrComputedFilesRead=False,roleRule=\"SHA256('ML14-role|'+kind+'|'+ID),rankmod5=0test/1validation/others train before eligibility\",costs='Hypothetical1/1,1/5,5/1; no causal intervention returns',files=files,observations={k:dict(sourceRows=v['rows'],eligibleRows=v['eligibleRows'],trainingRows=len(v['trainingIDs']))for k,v in studies.items()})\n (out/'provenance.json').write_text(json.dumps(provenance,ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\n print(json.dumps(dict(status='PASS standalone completed',files=len(files),bodyFields=sum(f['bodyFields']for f in files),observations=provenance['observations'])))\n\n# Fixed declared examples: full web budget/option validation is not reproduced.\nfrom html import escape\nimport textwrap\ndef validated_rows(raw):\n for r in raw:\n  assert F(str(r.get('weight','1')))>=0,'negative analytical mass'\n  assert r['score']is None or 0<=F(str(r['score']))<=1,'score outside zero/one'\n  assert r['y']is None or F(str(int(r['y']))if isinstance(r['y'],bool)else str(r['y']))in [0,1],'binary target required'\n return read(raw)\ndef serial(v):\n if isinstance(v,F):return dict(exactFraction=str(v),value=float(v))\n if isinstance(v,(list,tuple)):return[serial(x)for x in v]\n if isinstance(v,dict):return{k:serial(x)for k,x in v.items()}\n return v\ndef fixed_svg(path,points,title,xlabel,ylabel,legend):\n use=[p for p in points if p['xExact']!=''and p['yExact']!=''];xs=[float(F(p['xExact']))for p in use];ys=[float(F(p['yExact']))for p in use]\n xmin=min(xs,default=0);xmax=max(xs,default=1);ymin=min([0]+ys);ymax=max([0]+ys)\n if xmin==xmax:xmin-=.5;xmax+=.5\n if ymin==ymax:ymax=ymin+1\n X=lambda v:85+(float(v)-xmin)/(xmax-xmin)*480;Y=lambda v:278-(float(v)-ymin)/(ymax-ymin)*175\n s='<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"620\" height=\"360\" viewBox=\"0 0 620 360\"><rect width=\"620\" height=\"360\" fill=\"white\"/><g font-family=\"Arial, sans-serif\" font-size=\"13\" fill=\"#17324d\">'\n for i,line in enumerate(textwrap.wrap(title,width=65)):s+='<text x=\"25\" y=\"'+str(24+i*18)+'\">'+escape(line)+'</text>'\n colors=['#176b9b','#b85e18','#437e4d']\n for i,label in enumerate(legend):s+='<circle cx=\"'+str(30+i*250)+'\" cy=\"76\" r=\"4\" fill=\"'+colors[i%3]+'\"/><text x=\"'+str(42+i*250)+'\" y=\"80\">'+escape(label)+'</text>'\n s+='<path d=\"M85 98V278H575\" fill=\"none\" stroke=\"#52677d\"/><text text-anchor=\"middle\" x=\"325\" y=\"338\">'+escape(xlabel)+'</text><text text-anchor=\"middle\" transform=\"translate(21,190) rotate(-90)\">'+escape(ylabel)+'</text>'\n for i in range(5):\n  xx=xmin+(xmax-xmin)*i/4;yy=ymin+(ymax-ymin)*i/4;s+='<text text-anchor=\"middle\" x=\"'+format(X(xx),'.9g')+'\" y=\"305\">'+format(xx,'.4g')+'</text><text text-anchor=\"end\" x=\"77\" y=\"'+format(Y(yy)+4,'.9g')+'\">'+format(yy,'.4g')+'</text>'\n for p in use:s+='<circle cx=\"'+format(X(F(p['xExact'])),'.9g')+'\" cy=\"'+format(Y(F(p['yExact'])),'.9g')+'\" r=\"3\" fill=\"'+colors[p['series']%3]+'\"/>'\n path.write_text(s+'</g></svg>',encoding='utf8')\ndef fixed_run():\n ap=argparse.ArgumentParser();ap.add_argument('--out',type=Path,default=Path('results'));ap.add_argument('--data-dir',type=Path,default=Path(__file__).resolve().parent.parent/'ml14-sources');args=ap.parse_args();args.out.mkdir(parents=True,exist_ok=True)\n api=FIXED['api'];a=FIXED['args'];summary=[];points=[];xlabel='Declared index';ylabel='Value';legend=['Declared result']\n def metric(name,v,unit='dimensionless'):\n  q=None if v is None else v if isinstance(v,F)else F(v);summary.append(dict(metric=name,value='undefined'if q is None else format(float(q),'.9g'),exactValue=''if q is None else str(q),unit=unit,defined=int(q is not None)))\n def pt(i,x,y,ident='',series=0):\n  points.append(dict(series=series,index=i,xExact=''if x is None else str(F(x)),x='undefined'if x is None else format(float(x),'.9g'),yExact=''if y is None else str(F(y)),y='undefined'if y is None else format(float(y),'.9g'),id=str(ident)))\n if api=='realdata':\n  models=load_sources(args.data_dir);model=models[a['kind']];fit=actual_model(model);rr=fit['rows'];test=scoped(rr,'test');scenarios=[]\n  for name,fp,fn in SCENARIOS:\n   c=choose(rr,{},(fp,fn));scenarios.append(dict(name=name,selection=c));metric(name+'Threshold',c['selectedPolicy']);metric(name+'TestCost',c['evaluation']['meanCost'],'hypothetical cost units/mass')\n  cv=curves(test);cal=calibrate(test,[F(0),F(1,5),F(2,5),F(3,5),F(4,5),F(1)]);metric('testAUC',cv['ROC_AUC']);metric('testAP',cv['averagePrecision']);metric('testBrier',cal['Brier']);metric('eligibleRows',sum(r['eligible']for r in rr),'rows')\n  for i,r in enumerate(test):pt(i,i+1,r['score'],r['id'],0);pt(i,i+1,r['y'],r['id'],1)\n  full=dict(kind=a['kind'],fitMedians=fit['medians'],fitCells=[dict(cell=list(k),mass=n,positive=s,probability=fit['probabilities'][k])for k,(n,s)in fit['cells'].items()],rowsScored=rr,scenarios=scenarios,testCurves=cv,testCalibration=cal);xlabel='Test row, native order';ylabel='Y or probability';legend=['Training-fitted probability','Observed Y']\n else:\n  rr=validated_rows(a['rows']);role=a.get('role','all');frame=scoped(rr,role);cc=cost(a.get('costs'));t=policy(a.get('threshold','1/2'))\n  if api=='metrics':\n   full=metrics(frame,t,cc)\n   for k in ['mass','accuracy','precision','TPR','FPR','F1','Brier','meanCost']:metric(k,full[k],'mass'if k=='mass'else'hypothetical cost units/mass'if k=='meanCost'else'dimensionless')\n   metric('BayesThreshold',full['bayesThreshold'])\n   for i,k in enumerate(['TP','FP','FN','TN']):pt(i,i,full['confusion'][k],k)\n   xlabel='TP / FP / FN / TN positions';ylabel='Analytical mass'\n  elif api=='curves':\n   full=curves(frame)\n   for k in ['ROC_AUC','averagePrecision','PRTrapezoidWithInitialPrecisionOne']:metric(k,full[k])\n   for i,p in enumerate(full['points']):pt(i,p['FPR'],p['TPR'],str(p['policy']))\n   xlabel='False positive rate';ylabel='True positive rate';legend=['Observed ROC operating points']\n  elif api=='choose':\n   full=choose(rr,a,cc);metric('selectedIndex',full['selectedIndex'],'candidate index');metric('minimumCost',None if full['selectedValidation']is None else full['selectedValidation']['meanCost'],'hypothetical cost units/mass');metric('feasible',int(full['selectedIndex']is not None),'indicator')\n   for c in full['candidates']:pt(c['index'],c['index'],c['metrics']['meanCost'],str(c['policy']))\n   xlabel='Validation candidate';ylabel='Assumed cost / mass';legend=['Validation candidate costs']\n  elif api=='calibrate':\n   full=calibrate(frame,[F(str(e))for e in a.get('binEdges',['0','1/5','2/5','3/5','4/5','1'])])\n   for k in ['ECE','Brier','uncertainty','resolution','reliability','withinBinCorrection','BrierIdentityResidual']:metric(k,full[k])\n   for b in full['bins']:pt(b['index'],b['meanPrediction'],b['eventRate'],'bin:'+str(b['index']))\n   xlabel='Bin mean forecast';ylabel='Bin event rate';legend=['Binary-event reliability']\n  elif api=='groups':\n   full=groups(frame,t,cc);metric('overallTPR',full['overall']['TPR']);metric('TPRGap',full['gaps']['TPR']['value']);metric('precisionGap',full['gaps']['precision']['value']);metric('unknownMass',full['unknownGroup']['mass'],'mass');metric('partitionResidual',full['partitionMassResidual'],'mass')\n   for i,g in enumerate(full['groups']):pt(i,i,g['metrics']['TPR'],str(g['group']))\n   xlabel='Declared group position';ylabel='True positive rate';legend=['Known-group TPR']\n  else:raise ValueError('unknown fixed API')\n def csvout(name,rows):\n  with(args.out/name).open('w',encoding='utf8',newline='')as f:w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows)\n csvout('summary.csv',summary);csvout('plot-points.csv',points);fixed_svg(args.out/'plot.svg',points,FIXED['title'],xlabel,ylabel,legend)\n (args.out/'full.json').write_text(json.dumps(dict(api=api,variant=FIXED['variant'],input=FIXED['args'],arithmetic='Python standard-library Fraction, declared fixed example; full web validator/budgets not reproduced',result=serial(full)),ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\n print(json.dumps(dict(api=api,variant=FIXED['variant'],summaryMetrics=len(summary),plotSlots=len(points))))\n\nFIXED={'api': 'choose', 'variant': 'miss-five', 'args': {'rows': [{'id': 'a', 'score': '.9', 'y': 1, 'group': 'A', 'role': 'validation'}, {'id': 'b', 'score': '.8', 'y': 1, 'group': 'A', 'role': 'validation'}, {'id': 'c', 'score': '.8', 'y': 0, 'group': 'A', 'role': 'validation'}, {'id': 'd', 'score': '.6', 'y': 0, 'group': 'B', 'role': 'validation'}, {'id': 'e', 'score': '.4', 'y': 1, 'group': 'B', 'role': 'validation'}, {'id': 'f', 'score': '.1', 'y': 0, 'group': 'B', 'role': 'validation'}], 'costs': {'falsePositive': '1', 'falseNegative': '5'}, 'evaluationRole': 'none'}, 'title': 'Validation-only threshold with missed-case cost five'}\nif __name__=='__main__':fixed_run()\n",
        "input": {
          "rows": [
            {
              "id": "a",
              "score": ".9",
              "y": 1,
              "group": "A",
              "role": "validation"
            },
            {
              "id": "b",
              "score": ".8",
              "y": 1,
              "group": "A",
              "role": "validation"
            },
            {
              "id": "c",
              "score": ".8",
              "y": 0,
              "group": "A",
              "role": "validation"
            },
            {
              "id": "d",
              "score": ".6",
              "y": 0,
              "group": "B",
              "role": "validation"
            },
            {
              "id": "e",
              "score": ".4",
              "y": 1,
              "group": "B",
              "role": "validation"
            },
            {
              "id": "f",
              "score": ".1",
              "y": 0,
              "group": "B",
              "role": "validation"
            }
          ],
          "costs": {
            "falsePositive": "1",
            "falseNegative": "5"
          },
          "evaluationRole": "none"
        },
        "inputFiles": [],
        "returnCode": 0,
        "expectedFailure": false,
        "stdout": "{\"api\": \"choose\", \"variant\": \"miss-five\", \"summaryMetrics\": 3, \"plotSlots\": 6}\n",
        "stderr": "",
        "summary": {
          "selectedIndex": "4",
          "minimumCost": "0.333333333",
          "feasible": "1"
        },
        "summaryRows": [
          {
            "metric": "selectedIndex",
            "value": "4",
            "exactValue": "4",
            "unit": "candidate index",
            "defined": "1"
          },
          {
            "metric": "minimumCost",
            "value": "0.333333333",
            "exactValue": "1/3",
            "unit": "hypothetical cost units/mass",
            "defined": "1"
          },
          {
            "metric": "feasible",
            "value": "1",
            "exactValue": "1",
            "unit": "indicator",
            "defined": "1"
          }
        ],
        "plotPoints": [
          {
            "series": "0",
            "index": "0",
            "xExact": "0",
            "x": "0",
            "yExact": "5/2",
            "y": "2.5",
            "id": "always-negative"
          },
          {
            "series": "0",
            "index": "1",
            "xExact": "1",
            "x": "1",
            "yExact": "5/3",
            "y": "1.66666667",
            "id": "9/10"
          },
          {
            "series": "0",
            "index": "2",
            "xExact": "2",
            "x": "2",
            "yExact": "1",
            "y": "1",
            "id": "4/5"
          },
          {
            "series": "0",
            "index": "3",
            "xExact": "3",
            "x": "3",
            "yExact": "7/6",
            "y": "1.16666667",
            "id": "3/5"
          },
          {
            "series": "0",
            "index": "4",
            "xExact": "4",
            "x": "4",
            "yExact": "1/3",
            "y": "0.333333333",
            "id": "2/5"
          },
          {
            "series": "0",
            "index": "5",
            "xExact": "5",
            "x": "5",
            "yExact": "1/2",
            "y": "0.5",
            "id": "1/10"
          }
        ],
        "plotFile": "ml14-fixed-results/choose-miss-five-python/plot.svg",
        "plotSHA256": "b0f3f0c0229082a6c14b11252163ddede691cce374219439a37075c1b49700c2",
        "files": [
          {
            "file": "ml14-fixed-results/choose-miss-five-python/full.json",
            "sha256": "eb36570acf5f6bf598ff360f5e9fbbeebf48c51aa5fd32bda0986897d885f141",
            "bytes": 37385
          },
          {
            "file": "ml14-fixed-results/choose-miss-five-python/plot-points.csv",
            "sha256": "aa4c4e70ed9d387f1c1c2a9be9810fe562573c4cc24513082f82b0d65ca75f57",
            "bytes": 193
          },
          {
            "file": "ml14-fixed-results/choose-miss-five-python/plot.svg",
            "sha256": "b0f3f0c0229082a6c14b11252163ddede691cce374219439a37075c1b49700c2",
            "bytes": 1431
          },
          {
            "file": "ml14-fixed-results/choose-miss-five-python/summary.csv",
            "sha256": "c63d77955948723ca39bc9621f340d21696c4e23cfbed905120ef4651ceb3248",
            "bytes": 161
          }
        ],
        "scope": "Actually executed standalone fixed example, Python exact Fraction versus base-R binary64. Approximate R residuals retained; not universal exact arithmetic/web validation/native UI. Source programs read factual3CSV only."
      },
      "infeasible": {
        "api": "choose",
        "variant": "infeasible",
        "language": "python",
        "title": "No threshold satisfies both declared rate constraints",
        "codeFile": "ml14-code/choose-infeasible.py",
        "codeSHA256": "a12f7e311fbc55d06adfb8340edd82eb0aab9e3deda764fd845df083b3b5978d",
        "code": "#!/usr/bin/env python3\n\"\"\"ML14 standalone exact finite study, Python standard library only.\nInputs: only the three retained factual source CSVs below.\nDerived role/target/group/eligibility columns in those CSVs are NOT inputs.\nRebuilds SHA256 roles, train-only medians/cell scores, validation thresholds,\ntest curves, binary-event reliability and descriptive group ledgers.\nCosts 1/1,1/5,5/1 are hypothetical units, not measured intervention returns.\nThis is author public reproduction, not independent scientific review.\n\"\"\"\n\"\"\"Author Fraction reference, separate from product JavaScript; not independent peer.\"\"\"\nfrom fractions import Fraction as F\nfrom collections import Counter,defaultdict\ndef read(raw):\n rows=[]\n for i,r in enumerate(raw):\n  s=None if r['score']is None else F(str(r['score']));y=None if r['y']is None else F(int(r['y']))if isinstance(r['y'],bool)else F(str(r['y']));w=F(str(r.get('weight','1')));role=r.get('role','evaluation')\n  rows.append(dict(id=r['id'],index=i,score=s,y=y,w=w,role=role,group=r.get('group'),eligible=s is not None and y is not None and w>0 and role!='excluded'))\n return rows\ndef scoped(rows,role='all'):return rows if role=='all'else[r for r in rows if r['role']==role]\ndef divide(n,d):return None if not d else n/d\ndef policy(v):return v if v in ['always-negative','always-positive']else F(str(v))\ndef positive(p,s):return p=='always-positive'if isinstance(p,str)else s>=p\ndef cost(a=None):\n a={}if a is None else a;fp=F(str(a.get('falsePositive','1')));fn=F(str(a.get('falseNegative','1')));return fp,fn\ndef metrics(rows,threshold=F(1,2),cc=(F(1),F(1))):\n counts=dict(TP=F(0),FP=F(0),FN=F(0),TN=F(0));brier=F(0);pred=[]\n for r in rows:\n  if not r['eligible']:pred.append(dict(id=r['id'],index=r['index'],eligible=False,decision=None,probability=None,Brier=None));continue\n  yes=positive(threshold,r['score']);cell=('T'if yes==bool(r['y'])else'F')+('P'if yes else'N');counts[cell]+=r['w'];loss=(r['score']-r['y'])**2;brier+=r['w']*loss;pred.append(dict(id=r['id'],index=r['index'],eligible=True,decision=int(yes),probability=r['score'],Brier=loss))\n TP,FP,FN,TN=[counts[k]for k in ['TP','FP','FN','TN']];P=TP+FN;N=TN+FP;mass=P+N;PP=TP+FP;PN=TN+FN;TPR=divide(TP,P);TNR=divide(TN,N);total=FP*cc[0]+FN*cc[1]\n return dict(confusion=counts,mass=mass,positiveTargetMass=P,negativeTargetMass=N,predictedPositiveMass=PP,predictedNegativeMass=PN,prevalence=divide(P,mass),selectionRate=divide(PP,mass),accuracy=divide(TP+TN,mass),precision=divide(TP,PP),negativePredictiveValue=divide(TN,PN),TPR=TPR,FPR=divide(FP,N),TNR=TNR,FNR=divide(FN,P),F1=divide(2*TP,2*TP+FP+FN),balancedAccuracy=None if TPR is None or TNR is None else(TPR+TNR)/2,Brier=divide(brier,mass),BrierSum=brier,totalCost=total,meanCost=divide(total,mass),predictions=pred,bayesThreshold=divide(cc[0],sum(cc)))\ndef curves(rows):\n use=[r for r in rows if r['eligible']];pos=Counter();neg=Counter()\n for r in use:(pos if r['y']else neg)[r['score']]+=r['w']\n P=sum(pos.values(),F(0));N=sum(neg.values(),F(0));pairs=F(0)\n for a,wa in pos.items():\n  for b,wb in neg.items():pairs+=wa*wb*(F(1)if a>b else F(1,2)if a==b else F(0))\n thresholds=['always-negative']+sorted({r['score']for r in use},reverse=True);points=[];AP=F(0);trap=F(0);lastR=F(0);lastP=F(1)\n for i,p in enumerate(thresholds):\n  m=metrics(rows,p);points.append(dict(policy=p,TP=m['confusion']['TP'],FP=m['confusion']['FP'],FN=m['confusion']['FN'],TN=m['confusion']['TN'],TPR=m['TPR'],FPR=m['FPR'],precision=m['precision'],recall=m['TPR']))\n  if i and P:\n   R=m['TPR'];PP=m['precision'];AP+=(R-lastR)*PP;trap+=(R-lastR)*(PP+lastP)/2;lastR=R;lastP=PP\n return dict(positiveMass=P,negativeMass=N,ROC_AUC=divide(pairs,P*N),weightedConcordantPlusHalfTiedMass=pairs,averagePrecision=AP if P else None,PRTrapezoidWithInitialPrecisionOne=trap if P else None,points=points)\ndef choose(rows,a,cc):\n sr=a.get('selectionRole','validation');er=a.get('evaluationRole','test');rr=scoped(rows,sr);thresholds=[policy(t)for t in a['thresholds']]if'thresholds'in a else['always-negative']+sorted({r['score']for r in rr if r['eligible']},reverse=True)\n candidates=[]\n for i,p in enumerate(thresholds):\n  m=metrics(rr,p,cc);reasons=[]\n  if'minTPR'in a and(m['TPR']is None or m['TPR']<F(str(a['minTPR']))):reasons.append('TPR-undefined'if m['TPR']is None else'below-minTPR')\n  if'maxFPR'in a and(m['FPR']is None or m['FPR']>F(str(a['maxFPR']))):reasons.append('FPR-undefined'if m['FPR']is None else'above-maxFPR')\n  candidates.append(dict(index=i,policy=p,metrics=m,feasible=not reasons,reasons=reasons))\n eligible=[c for c in candidates if c['feasible']];best=min(eligible,key=lambda c:(c['metrics']['meanCost'],c['index']))if eligible else None\n return dict(selectedIndex=None if best is None else best['index'],selectedPolicy=None if best is None else best['policy'],candidates=candidates,selectedValidation=None if best is None else best['metrics'],evaluation=None if best is None or er=='none'else metrics(scoped(rows,er),best['policy'],cc),selectionIDs=[r['id']for r in rr if r['eligible']])\ndef calibrate(rows,ee):\n buckets=[[]for _ in range(len(ee)-1)]\n for r in rows:\n  if not r['eligible']:continue\n  j=next((i for i in range(len(ee)-1)if r['score']<ee[i+1]),len(ee)-2);buckets[j].append(r)\n mass=sum((r['w']for r in rows if r['eligible']),F(0));P=sum((r['w']*r['y']for r in rows if r['eligible']),F(0));pi=divide(P,mass);Brier=None if not mass else sum((r['w']*(r['score']-r['y'])**2 for r in rows if r['eligible']),F(0))/mass;ECE=F(0);reliability=F(0);resolution=F(0);correction=F(0);bins=[]\n for i,rr in enumerate(buckets):\n  w=sum((r['w']for r in rr),F(0));mp=None if not w else sum((r['w']*r['score']for r in rr),F(0))/w;o=None if not w else sum((r['w']*r['y']for r in rr),F(0))/w\n  variance=None if not w else sum((r['w']*(r['score']-mp)**2 for r in rr),F(0))/w\n  covariance=None if not w else sum((r['w']*(r['score']-mp)*(r['y']-o)for r in rr),F(0))/w\n  bc=None if not w else variance-2*covariance;gap=None if not w else mp-o\n  bins.append(dict(index=i,rows=len(rr),mass=w,meanPrediction=mp,eventRate=o,gap=gap,absoluteGap=None if gap is None else abs(gap),scoreVariance=variance,scoreTargetCovariance=covariance,withinBinCorrection=bc,ids=[r['id']for r in rr]))\n  if w:\n   share=w/mass;ECE+=share*abs(gap);reliability+=share*gap**2;resolution+=share*(o-pi)**2;correction+=share*bc\n uncertainty=None if pi is None else pi*(1-pi);residual=None if Brier is None else Brier-(uncertainty-resolution+reliability+correction)\n return dict(mass=mass,prevalence=pi,Brier=Brier,ECE=ECE if mass else None,reliability=reliability if mass else None,resolution=resolution if mass else None,uncertainty=uncertainty,withinBinCorrection=correction if mass else None,BrierIdentityResidual=residual,bins=bins)\ndef typed(v):return type(v).__name__,v\ndef groups(rows,p,cc):\n bins={}\n for r in rows:\n  if r['group']is not None:bins.setdefault(typed(r['group']),[]).append(r)\n gm=[dict(group=rr[0]['group'],metrics=metrics(rr,p,cc))for rr in bins.values()];overall=metrics(rows,p,cc);unknown=metrics([r for r in rows if r['group']is None],p,cc);gaps={}\n for key in ['prevalence','selectionRate','TPR','FPR','precision','accuracy','meanCost']:\n  positive=[g for g in gm if g['metrics']['mass']>0];undefined=[g['group']for g in positive if g['metrics'][key]is None];vals=[g['metrics'][key]for g in positive if g['metrics'][key]is not None]\n  gaps[key]=dict(value=None if len(positive)<2 or undefined else max(vals)-min(vals),undefinedGroups=undefined,comparedPositiveMassGroups=[g['group']for g in positive])\n return dict(overall=overall,groups=gm,unknownGroup=unknown,gaps=gaps,partitionMassResidual=overall['mass']-unknown['mass']-sum((g['metrics']['mass']for g in gm),F(0)))\ndef actual_model(M):\n raw=M['records'];cat=M['categoricalFeatures'];p=len(raw[0]['x']);train=[r for r in raw if r['role']=='train'];medians=[]\n for j in range(p):\n  if j in cat:medians.append(None);continue\n  values=sorted(F(r['x'][j])for r in train);n=len(values);medians.append(values[n//2]if n%2 else(values[n//2-1]+values[n//2])/2)\n def transform(r):return[F(v)if j in cat else F(int(F(v)>medians[j]))for j,v in enumerate(r['x'])]\n counts={}\n for r in train:\n  key=tuple(transform(r));n,s=counts.get(key,(0,0));counts[key]=(n+1,s+int(r['y']))\n probabilities={k:F(s+1,n+2)for k,(n,s)in counts.items()};fallback=F(sum(int(r['y'])for r in train)+1,len(train)+2);scored=[]\n for i,r in enumerate(raw):\n  eligible=r['role']!='excluded';z=transform(r)if eligible else None;key=None if z is None else tuple(z);score=None if not eligible else probabilities.get(key,fallback)\n  scored.append(dict(id=r['id'],index=i,role=r['role'],group=r['group'],y=None if r['y']is None else F(r['y']),score=score,w=F(1),eligible=eligible,transformedX=z,unseenCell=None if not eligible else key not in probabilities))\n return dict(medians=medians,cells=counts,probabilities=probabilities,fallback=fallback,rows=scored,trainIDs=[r['id']for r in train])\n\n\nimport csv,json,hashlib,argparse,datetime\nfrom pathlib import Path\ndef missing(v):return None if v in ['', '.',None]else v\ndef load_sources(folder):\n def read_csv(name):\n  with (folder/name).open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))\n wb=read_csv('actual64-country-four-indicators-original-2024.csv')\n codes=['NY.GDP.PCAP.KD','NY.GDP.MKTP.KD.ZG','FP.CPI.TOTL.ZG','SP.DYN.LE00.IN']\n lookup={(r['countryISO3'],r['indicatorID']):r for r in wb};country=[]\n for i,iso in enumerate(sorted({r['countryISO3']for r in wb}),1):\n  native=[lookup[iso,c]for c in codes];v=[missing(r['originalValueToken'])for r in native]\n  country.append(dict(id=iso+':2024',sourceRow=i,originalID=iso,x=v[:3],y=None if v[3]is None else str(int(F(v[3])>=80)),group=None if v[0]is None else str(int(F(v[0])>=25000)),nativeTarget=v[3],nativeSourceRows=';'.join(r['sourceRow']for r in native)))\n nls=read_csv('actual3613-NLS-original52-fields-groups-roles.csv');person=[]\n for r in nls:\n  y=missing(r['wage76']);person.append(dict(id='person:'+r['sourceRow'],sourceRow=int(r['sourceRow']),originalID=r['id'],x=[missing(r[k])for k in ['ed76','age76','nearc4']],y=None if y is None else str(int(F(y)>=500)),group=missing(r['black']),nativeTarget=y,nativeSourceRows=r['sourceRow']))\n ch=read_csv('actual3150-churn-original14-fields-groups-roles.csv');company=[]\n for r in ch:\n  company.append(dict(id='customer:'+r['sourceRow'],sourceRow=int(r['sourceRow']),originalID='',x=[missing(r[k])for k in ['Call  Failure','Complains','Subscription  Length','Seconds of Use']],y=missing(r['Churn']),group=missing(r['Tariff Plan']),nativeTarget=missing(r['Churn']),nativeSourceRows=r['sourceRow']))\n assert len(wb)==64 and len(country)==16 and len(nls)==3613 and len(ch)==3150\n assert [int(r['sourceRow'])for r in ch if r['Charge  Amount']=='10']==[474,2174,2274,2374,2674,2924,2974]\n models={}\n for kind,raw,cat,units in [('country',country,[],['constant2015USD/person','annualPercent','annualPercent']),('person',person,[2],['years','years','nativeCategory']),('company',company,[1],['count','nativeCategory','months','seconds'])]:\n  order=sorted(range(len(raw)),key=lambda i:(hashlib.sha256(('ML14-role|'+kind+'|'+raw[i]['id']).encode()).hexdigest(),i))\n  for rank,i in enumerate(order):\n   r=raw[i];r['plannedRole']='test'if rank%5==0 else'validation'if rank%5==1 else'train';r['eligible']=None not in r['x']+[r['y']];r['role']=r['plannedRole']if r['eligible']else'excluded';r['weight']='1'\n  models[kind]=dict(records=raw,categoricalFeatures=cat,featureUnits=units)\n assert sum(r['eligible']for r in person)==3017\n return models\n\ndef exact(v):return ''if v is None else str(v)\ndef approx(v):return ''if v is None else format(float(v),'.17g')\ndef scalar_fields(m,keys):\n out={}\n for k in keys:\n  out[k+'Exact']=exact(m[k]);out[k+'Approx']=approx(m[k])\n return out\nCOUNTS=['mass','positiveTargetMass','negativeTargetMass','predictedPositiveMass','predictedNegativeMass']\nRATES=['prevalence','selectionRate','accuracy','precision','negativePredictiveValue','TPR','FPR','TNR','FNR','F1','balancedAccuracy','Brier','BrierSum','totalCost','meanCost']\nSCENARIOS=[('equal',F(1),F(1)),('miss-five',F(1),F(5)),('alarm-five',F(5),F(1))]\ndef packed(v):\n if isinstance(v,F):return str(v)\n if isinstance(v,dict):return{str(k):packed(x)for k,x in v.items()}\n if isinstance(v,(tuple,list)):return[packed(x)for x in v]\n return v\ndef run_study(source,out):\n out.mkdir(parents=True,exist_ok=True);models=load_sources(source)\n tables={name:[]for name in ['predictions','lineage','fit-medians','fit-cells','validation-candidates','test-metrics','test-curves','calibration-bins','group-metrics','chart-points']}\n studies={};charts=[]\n def point(kind,chart,series,index,x,y,xunit='dimensionless',yunit='dimensionless',role='test',tag=''):\n  tables['chart-points'].append(dict(kind=kind,chart=chart,series=series,index=index,xExact=exact(x),xApprox=approx(x),yExact=exact(y),yApprox=approx(y),xUnit=xunit,yUnit=yunit,role=role,tag=tag))\n for kind,M in models.items():\n  fit=actual_model(M);rr=fit['rows'];native=M['records'];test=scoped(rr,'test');cv=curves(test);cal=calibrate(test,[F(0),F(1,5),F(2,5),F(3,5),F(4,5),F(1)]);scenarios=[]\n  for i,r in enumerate(rr):\n   n=native[i];reason=''if r['eligible']else'required-X-or-Y-missing'\n   tables['predictions'].append(dict(kind=kind,id=r['id'],sourceRow=n['sourceRow'],originalID=n['originalID'],plannedRole=n['plannedRole'],role=r['role'],group=''if r['group']is None else r['group'],eligible=int(r['eligible']),targetExact=exact(r['y']),probabilityExact=exact(r['score']),probabilityApprox=approx(r['score']),unseenCell=''if r['unseenCell']is None else int(r['unseenCell']),transformedX=''if r['transformedX']is None else'|'.join(map(str,r['transformedX'])),reason=reason))\n   tables['lineage'].append(dict(kind=kind,id=r['id'],sourceRow=n['sourceRow'],originalID=n['originalID'],nativeSourceRows=n['nativeSourceRows'],rawX='|'.join(''if x is None else x for x in n['x']),nativeTarget=''if n['nativeTarget']is None else n['nativeTarget'],derivedTarget=exact(r['y']),nativeGroup=''if n['group']is None else n['group'],plannedRole=n['plannedRole'],role=r['role'],eligible=int(r['eligible']),analyticalMass='1',reason=reason))\n  for j,v in enumerate(fit['medians']):tables['fit-medians'].append(dict(kind=kind,feature=j,categorical=int(j in M['categoricalFeatures']),fitRows=len(fit['trainIDs']),medianExact=exact(v),medianApprox=approx(v),unit=M['featureUnits'][j]))\n  for key,(mass,pos)in fit['cells'].items():tables['fit-cells'].append(dict(kind=kind,cell='|'.join(map(str,key)),trainingRows=mass,positiveRows=pos,probabilityExact=exact(fit['probabilities'][key]),probabilityApprox=approx(fit['probabilities'][key]),fallbackExact=exact(fit['fallback']),fallbackApprox=approx(fit['fallback'])))\n  for j,p in enumerate(cv['points']):\n   policy=p['policy'];tables['test-curves'].append(dict(kind=kind,point=j,policy=policy if isinstance(policy,str)else'threshold',thresholdExact=''if isinstance(policy,str)else exact(policy),thresholdApprox=''if isinstance(policy,str)else approx(policy),**scalar_fields(p,['TP','FP','FN','TN','TPR','FPR','precision','recall'])))\n   point(kind,'roc','ROC',j,p['FPR'],p['TPR']);point(kind,'pr','PR-observed',j,p['recall'],p['precision'])\n  for b in cal['bins']:\n   tables['calibration-bins'].append(dict(kind=kind,bin=b['index'],leftExact=str(F(b['index'],5)),rightExact=str(F(b['index']+1,5)),rightClosed=int(b['index']==4),rows=b['rows'],ids=';'.join(str(i)for i in b['ids']),**scalar_fields(b,['mass','meanPrediction','eventRate','gap','absoluteGap','scoreVariance','scoreTargetCovariance','withinBinCorrection'])))\n   point(kind,'reliability','Binary event rate',b['index'],b['meanPrediction'],b['eventRate'],tag='rows='+str(b['rows']))\n  for j,r in enumerate(test):\n   point(kind,'test-scores','Training-fitted probability',j,F(j+1),r['score'],'test-row position','probability',tag=r['id'])\n   point(kind,'test-scores','Observed Y',j,F(j+1),r['y'],'test-row position','binary target',tag=r['id'])\n  for name,fp,fn in SCENARIOS:\n   choice=choose(rr,{},(fp,fn));gm=groups(test,choice['selectedPolicy'],(fp,fn));scenarios.append(dict(name=name,costs=dict(falsePositive=fp,falseNegative=fn),selection=choice,groups=gm));ev=choice['evaluation']\n   for c in choice['candidates']:\n    policy=c['policy'];mm=c['metrics'];tables['validation-candidates'].append(dict(kind=kind,scenario=name,candidate=c['index'],selected=int(c['index']==choice['selectedIndex']),policy=policy if isinstance(policy,str)else'threshold',thresholdExact=''if isinstance(policy,str)else exact(policy),thresholdApprox=''if isinstance(policy,str)else approx(policy),feasible=int(c['feasible']),reasons=';'.join(c['reasons']),**{k+'Exact':str(v)for k,v in mm['confusion'].items()},**scalar_fields(mm,COUNTS+['TPR','FPR','precision','meanCost','totalCost'])))\n    point(kind,'validation-cost',name,c['index'],F(c['index']),mm['meanCost'],'candidate index','hypothetical cost units/mass','validation',tag=exact(policy))\n   mm={**ev,**ev['confusion'],**{k:cv[k]for k in ['ROC_AUC','averagePrecision','PRTrapezoidWithInitialPrecisionOne']},**{k:cal[k]for k in ['ECE','reliability','resolution','uncertainty','withinBinCorrection','BrierIdentityResidual']}}\n   for key in ['TP','FP','FN','TN']+COUNTS+RATES+['ROC_AUC','averagePrecision','PRTrapezoidWithInitialPrecisionOne','ECE','reliability','resolution','uncertainty','withinBinCorrection','BrierIdentityResidual']:\n    unit='rows'if key in ['TP','FP','FN','TN']+COUNTS else'hypothetical cost units'if key=='totalCost'else'hypothetical cost units/mass'if key=='meanCost'else'sum squared-probability loss'if key=='BrierSum'else'dimensionless'\n    tables['test-metrics'].append(dict(kind=kind,scenario=name,metric=key,valueExact=exact(mm[key]),valueApprox=approx(mm[key]),unit=unit))\n   allg=[('overall','all',gm['overall'])]+[('known',str(g['group']),g['metrics'])for g in gm['groups']]+[('unknown','',gm['unknownGroup'])]\n   for j,(typ,token,g)in enumerate(allg):\n    tables['group-metrics'].append(dict(kind=kind,scenario=name,groupType=typ,groupToken=token,retainedRows=g.get('retainedRows',sum((r['group']==token)if typ=='known'else(r['group']is None)if typ=='unknown'else True for r in test)),**{k+'Exact':str(v)for k,v in g['confusion'].items()},**scalar_fields(g,COUNTS+RATES)))\n    if typ=='known':point(kind,'group-TPR',name,j-1,F(j-1),g['TPR'],'declared group position','TPR',tag=token)\n  studies[kind]=dict(kind=kind,rows=len(native),eligibleRows=sum(r['eligible']for r in rr),trainingIDs=fit['trainIDs'],fitMedians=fit['medians'],fitCells=[dict(cell=list(k),mass=n,positive=s,probability=fit['probabilities'][k])for k,(n,s)in fit['cells'].items()],fallback=fit['fallback'],scenarios=scenarios,testCurves=cv,testCalibration=cal,rowsScored=rr)\n files=[]\n for name,rows in tables.items():\n  p=out/('computed-'+name+'.csv')\n  with p.open('w',encoding='utf8',newline='')as f:w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows)\n  files.append(dict(file=p.name,rows=len(rows),columns=len(rows[0]),bodyFields=len(rows)*len(rows[0]),sha256=hashlib.sha256(p.read_bytes()).hexdigest()))\n (out/'study.json').write_text(json.dumps(packed(studies),ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\n sourceFiles=[source/n for n in ['actual64-country-four-indicators-original-2024.csv','actual3613-NLS-original52-fields-groups-roles.csv','actual3150-churn-original14-fields-groups-roles.csv']]\n provenance=dict(chapter='ML-14',arithmetic='Python stdlib Fraction exact finite values from original decimal strings; binary64 valueApprox is display only.',inputs=[dict(file=p.name,sha256=hashlib.sha256(p.read_bytes()).hexdigest())for p in sourceFiles],priorEngineModelsScoresOrComputedFilesRead=False,roleRule=\"SHA256('ML14-role|'+kind+'|'+ID),rankmod5=0test/1validation/others train before eligibility\",costs='Hypothetical1/1,1/5,5/1; no causal intervention returns',files=files,observations={k:dict(sourceRows=v['rows'],eligibleRows=v['eligibleRows'],trainingRows=len(v['trainingIDs']))for k,v in studies.items()})\n (out/'provenance.json').write_text(json.dumps(provenance,ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\n print(json.dumps(dict(status='PASS standalone completed',files=len(files),bodyFields=sum(f['bodyFields']for f in files),observations=provenance['observations'])))\n\n# Fixed declared examples: full web budget/option validation is not reproduced.\nfrom html import escape\nimport textwrap\ndef validated_rows(raw):\n for r in raw:\n  assert F(str(r.get('weight','1')))>=0,'negative analytical mass'\n  assert r['score']is None or 0<=F(str(r['score']))<=1,'score outside zero/one'\n  assert r['y']is None or F(str(int(r['y']))if isinstance(r['y'],bool)else str(r['y']))in [0,1],'binary target required'\n return read(raw)\ndef serial(v):\n if isinstance(v,F):return dict(exactFraction=str(v),value=float(v))\n if isinstance(v,(list,tuple)):return[serial(x)for x in v]\n if isinstance(v,dict):return{k:serial(x)for k,x in v.items()}\n return v\ndef fixed_svg(path,points,title,xlabel,ylabel,legend):\n use=[p for p in points if p['xExact']!=''and p['yExact']!=''];xs=[float(F(p['xExact']))for p in use];ys=[float(F(p['yExact']))for p in use]\n xmin=min(xs,default=0);xmax=max(xs,default=1);ymin=min([0]+ys);ymax=max([0]+ys)\n if xmin==xmax:xmin-=.5;xmax+=.5\n if ymin==ymax:ymax=ymin+1\n X=lambda v:85+(float(v)-xmin)/(xmax-xmin)*480;Y=lambda v:278-(float(v)-ymin)/(ymax-ymin)*175\n s='<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"620\" height=\"360\" viewBox=\"0 0 620 360\"><rect width=\"620\" height=\"360\" fill=\"white\"/><g font-family=\"Arial, sans-serif\" font-size=\"13\" fill=\"#17324d\">'\n for i,line in enumerate(textwrap.wrap(title,width=65)):s+='<text x=\"25\" y=\"'+str(24+i*18)+'\">'+escape(line)+'</text>'\n colors=['#176b9b','#b85e18','#437e4d']\n for i,label in enumerate(legend):s+='<circle cx=\"'+str(30+i*250)+'\" cy=\"76\" r=\"4\" fill=\"'+colors[i%3]+'\"/><text x=\"'+str(42+i*250)+'\" y=\"80\">'+escape(label)+'</text>'\n s+='<path d=\"M85 98V278H575\" fill=\"none\" stroke=\"#52677d\"/><text text-anchor=\"middle\" x=\"325\" y=\"338\">'+escape(xlabel)+'</text><text text-anchor=\"middle\" transform=\"translate(21,190) rotate(-90)\">'+escape(ylabel)+'</text>'\n for i in range(5):\n  xx=xmin+(xmax-xmin)*i/4;yy=ymin+(ymax-ymin)*i/4;s+='<text text-anchor=\"middle\" x=\"'+format(X(xx),'.9g')+'\" y=\"305\">'+format(xx,'.4g')+'</text><text text-anchor=\"end\" x=\"77\" y=\"'+format(Y(yy)+4,'.9g')+'\">'+format(yy,'.4g')+'</text>'\n for p in use:s+='<circle cx=\"'+format(X(F(p['xExact'])),'.9g')+'\" cy=\"'+format(Y(F(p['yExact'])),'.9g')+'\" r=\"3\" fill=\"'+colors[p['series']%3]+'\"/>'\n path.write_text(s+'</g></svg>',encoding='utf8')\ndef fixed_run():\n ap=argparse.ArgumentParser();ap.add_argument('--out',type=Path,default=Path('results'));ap.add_argument('--data-dir',type=Path,default=Path(__file__).resolve().parent.parent/'ml14-sources');args=ap.parse_args();args.out.mkdir(parents=True,exist_ok=True)\n api=FIXED['api'];a=FIXED['args'];summary=[];points=[];xlabel='Declared index';ylabel='Value';legend=['Declared result']\n def metric(name,v,unit='dimensionless'):\n  q=None if v is None else v if isinstance(v,F)else F(v);summary.append(dict(metric=name,value='undefined'if q is None else format(float(q),'.9g'),exactValue=''if q is None else str(q),unit=unit,defined=int(q is not None)))\n def pt(i,x,y,ident='',series=0):\n  points.append(dict(series=series,index=i,xExact=''if x is None else str(F(x)),x='undefined'if x is None else format(float(x),'.9g'),yExact=''if y is None else str(F(y)),y='undefined'if y is None else format(float(y),'.9g'),id=str(ident)))\n if api=='realdata':\n  models=load_sources(args.data_dir);model=models[a['kind']];fit=actual_model(model);rr=fit['rows'];test=scoped(rr,'test');scenarios=[]\n  for name,fp,fn in SCENARIOS:\n   c=choose(rr,{},(fp,fn));scenarios.append(dict(name=name,selection=c));metric(name+'Threshold',c['selectedPolicy']);metric(name+'TestCost',c['evaluation']['meanCost'],'hypothetical cost units/mass')\n  cv=curves(test);cal=calibrate(test,[F(0),F(1,5),F(2,5),F(3,5),F(4,5),F(1)]);metric('testAUC',cv['ROC_AUC']);metric('testAP',cv['averagePrecision']);metric('testBrier',cal['Brier']);metric('eligibleRows',sum(r['eligible']for r in rr),'rows')\n  for i,r in enumerate(test):pt(i,i+1,r['score'],r['id'],0);pt(i,i+1,r['y'],r['id'],1)\n  full=dict(kind=a['kind'],fitMedians=fit['medians'],fitCells=[dict(cell=list(k),mass=n,positive=s,probability=fit['probabilities'][k])for k,(n,s)in fit['cells'].items()],rowsScored=rr,scenarios=scenarios,testCurves=cv,testCalibration=cal);xlabel='Test row, native order';ylabel='Y or probability';legend=['Training-fitted probability','Observed Y']\n else:\n  rr=validated_rows(a['rows']);role=a.get('role','all');frame=scoped(rr,role);cc=cost(a.get('costs'));t=policy(a.get('threshold','1/2'))\n  if api=='metrics':\n   full=metrics(frame,t,cc)\n   for k in ['mass','accuracy','precision','TPR','FPR','F1','Brier','meanCost']:metric(k,full[k],'mass'if k=='mass'else'hypothetical cost units/mass'if k=='meanCost'else'dimensionless')\n   metric('BayesThreshold',full['bayesThreshold'])\n   for i,k in enumerate(['TP','FP','FN','TN']):pt(i,i,full['confusion'][k],k)\n   xlabel='TP / FP / FN / TN positions';ylabel='Analytical mass'\n  elif api=='curves':\n   full=curves(frame)\n   for k in ['ROC_AUC','averagePrecision','PRTrapezoidWithInitialPrecisionOne']:metric(k,full[k])\n   for i,p in enumerate(full['points']):pt(i,p['FPR'],p['TPR'],str(p['policy']))\n   xlabel='False positive rate';ylabel='True positive rate';legend=['Observed ROC operating points']\n  elif api=='choose':\n   full=choose(rr,a,cc);metric('selectedIndex',full['selectedIndex'],'candidate index');metric('minimumCost',None if full['selectedValidation']is None else full['selectedValidation']['meanCost'],'hypothetical cost units/mass');metric('feasible',int(full['selectedIndex']is not None),'indicator')\n   for c in full['candidates']:pt(c['index'],c['index'],c['metrics']['meanCost'],str(c['policy']))\n   xlabel='Validation candidate';ylabel='Assumed cost / mass';legend=['Validation candidate costs']\n  elif api=='calibrate':\n   full=calibrate(frame,[F(str(e))for e in a.get('binEdges',['0','1/5','2/5','3/5','4/5','1'])])\n   for k in ['ECE','Brier','uncertainty','resolution','reliability','withinBinCorrection','BrierIdentityResidual']:metric(k,full[k])\n   for b in full['bins']:pt(b['index'],b['meanPrediction'],b['eventRate'],'bin:'+str(b['index']))\n   xlabel='Bin mean forecast';ylabel='Bin event rate';legend=['Binary-event reliability']\n  elif api=='groups':\n   full=groups(frame,t,cc);metric('overallTPR',full['overall']['TPR']);metric('TPRGap',full['gaps']['TPR']['value']);metric('precisionGap',full['gaps']['precision']['value']);metric('unknownMass',full['unknownGroup']['mass'],'mass');metric('partitionResidual',full['partitionMassResidual'],'mass')\n   for i,g in enumerate(full['groups']):pt(i,i,g['metrics']['TPR'],str(g['group']))\n   xlabel='Declared group position';ylabel='True positive rate';legend=['Known-group TPR']\n  else:raise ValueError('unknown fixed API')\n def csvout(name,rows):\n  with(args.out/name).open('w',encoding='utf8',newline='')as f:w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows)\n csvout('summary.csv',summary);csvout('plot-points.csv',points);fixed_svg(args.out/'plot.svg',points,FIXED['title'],xlabel,ylabel,legend)\n (args.out/'full.json').write_text(json.dumps(dict(api=api,variant=FIXED['variant'],input=FIXED['args'],arithmetic='Python standard-library Fraction, declared fixed example; full web validator/budgets not reproduced',result=serial(full)),ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\n print(json.dumps(dict(api=api,variant=FIXED['variant'],summaryMetrics=len(summary),plotSlots=len(points))))\n\nFIXED={'api': 'choose', 'variant': 'infeasible', 'args': {'rows': [{'id': 'a', 'score': '.9', 'y': 1, 'group': 'A', 'role': 'validation'}, {'id': 'b', 'score': '.8', 'y': 1, 'group': 'A', 'role': 'validation'}, {'id': 'c', 'score': '.8', 'y': 0, 'group': 'A', 'role': 'validation'}, {'id': 'd', 'score': '.6', 'y': 0, 'group': 'B', 'role': 'validation'}, {'id': 'e', 'score': '.4', 'y': 1, 'group': 'B', 'role': 'validation'}, {'id': 'f', 'score': '.1', 'y': 0, 'group': 'B', 'role': 'validation'}], 'minTPR': '4/5', 'maxFPR': '2/5', 'evaluationRole': 'none'}, 'title': 'No threshold satisfies both declared rate constraints'}\nif __name__=='__main__':fixed_run()\n",
        "codeText": "#!/usr/bin/env python3\n\"\"\"ML14 standalone exact finite study, Python standard library only.\nInputs: only the three retained factual source CSVs below.\nDerived role/target/group/eligibility columns in those CSVs are NOT inputs.\nRebuilds SHA256 roles, train-only medians/cell scores, validation thresholds,\ntest curves, binary-event reliability and descriptive group ledgers.\nCosts 1/1,1/5,5/1 are hypothetical units, not measured intervention returns.\nThis is author public reproduction, not independent scientific review.\n\"\"\"\n\"\"\"Author Fraction reference, separate from product JavaScript; not independent peer.\"\"\"\nfrom fractions import Fraction as F\nfrom collections import Counter,defaultdict\ndef read(raw):\n rows=[]\n for i,r in enumerate(raw):\n  s=None if r['score']is None else F(str(r['score']));y=None if r['y']is None else F(int(r['y']))if isinstance(r['y'],bool)else F(str(r['y']));w=F(str(r.get('weight','1')));role=r.get('role','evaluation')\n  rows.append(dict(id=r['id'],index=i,score=s,y=y,w=w,role=role,group=r.get('group'),eligible=s is not None and y is not None and w>0 and role!='excluded'))\n return rows\ndef scoped(rows,role='all'):return rows if role=='all'else[r for r in rows if r['role']==role]\ndef divide(n,d):return None if not d else n/d\ndef policy(v):return v if v in ['always-negative','always-positive']else F(str(v))\ndef positive(p,s):return p=='always-positive'if isinstance(p,str)else s>=p\ndef cost(a=None):\n a={}if a is None else a;fp=F(str(a.get('falsePositive','1')));fn=F(str(a.get('falseNegative','1')));return fp,fn\ndef metrics(rows,threshold=F(1,2),cc=(F(1),F(1))):\n counts=dict(TP=F(0),FP=F(0),FN=F(0),TN=F(0));brier=F(0);pred=[]\n for r in rows:\n  if not r['eligible']:pred.append(dict(id=r['id'],index=r['index'],eligible=False,decision=None,probability=None,Brier=None));continue\n  yes=positive(threshold,r['score']);cell=('T'if yes==bool(r['y'])else'F')+('P'if yes else'N');counts[cell]+=r['w'];loss=(r['score']-r['y'])**2;brier+=r['w']*loss;pred.append(dict(id=r['id'],index=r['index'],eligible=True,decision=int(yes),probability=r['score'],Brier=loss))\n TP,FP,FN,TN=[counts[k]for k in ['TP','FP','FN','TN']];P=TP+FN;N=TN+FP;mass=P+N;PP=TP+FP;PN=TN+FN;TPR=divide(TP,P);TNR=divide(TN,N);total=FP*cc[0]+FN*cc[1]\n return dict(confusion=counts,mass=mass,positiveTargetMass=P,negativeTargetMass=N,predictedPositiveMass=PP,predictedNegativeMass=PN,prevalence=divide(P,mass),selectionRate=divide(PP,mass),accuracy=divide(TP+TN,mass),precision=divide(TP,PP),negativePredictiveValue=divide(TN,PN),TPR=TPR,FPR=divide(FP,N),TNR=TNR,FNR=divide(FN,P),F1=divide(2*TP,2*TP+FP+FN),balancedAccuracy=None if TPR is None or TNR is None else(TPR+TNR)/2,Brier=divide(brier,mass),BrierSum=brier,totalCost=total,meanCost=divide(total,mass),predictions=pred,bayesThreshold=divide(cc[0],sum(cc)))\ndef curves(rows):\n use=[r for r in rows if r['eligible']];pos=Counter();neg=Counter()\n for r in use:(pos if r['y']else neg)[r['score']]+=r['w']\n P=sum(pos.values(),F(0));N=sum(neg.values(),F(0));pairs=F(0)\n for a,wa in pos.items():\n  for b,wb in neg.items():pairs+=wa*wb*(F(1)if a>b else F(1,2)if a==b else F(0))\n thresholds=['always-negative']+sorted({r['score']for r in use},reverse=True);points=[];AP=F(0);trap=F(0);lastR=F(0);lastP=F(1)\n for i,p in enumerate(thresholds):\n  m=metrics(rows,p);points.append(dict(policy=p,TP=m['confusion']['TP'],FP=m['confusion']['FP'],FN=m['confusion']['FN'],TN=m['confusion']['TN'],TPR=m['TPR'],FPR=m['FPR'],precision=m['precision'],recall=m['TPR']))\n  if i and P:\n   R=m['TPR'];PP=m['precision'];AP+=(R-lastR)*PP;trap+=(R-lastR)*(PP+lastP)/2;lastR=R;lastP=PP\n return dict(positiveMass=P,negativeMass=N,ROC_AUC=divide(pairs,P*N),weightedConcordantPlusHalfTiedMass=pairs,averagePrecision=AP if P else None,PRTrapezoidWithInitialPrecisionOne=trap if P else None,points=points)\ndef choose(rows,a,cc):\n sr=a.get('selectionRole','validation');er=a.get('evaluationRole','test');rr=scoped(rows,sr);thresholds=[policy(t)for t in a['thresholds']]if'thresholds'in a else['always-negative']+sorted({r['score']for r in rr if r['eligible']},reverse=True)\n candidates=[]\n for i,p in enumerate(thresholds):\n  m=metrics(rr,p,cc);reasons=[]\n  if'minTPR'in a and(m['TPR']is None or m['TPR']<F(str(a['minTPR']))):reasons.append('TPR-undefined'if m['TPR']is None else'below-minTPR')\n  if'maxFPR'in a and(m['FPR']is None or m['FPR']>F(str(a['maxFPR']))):reasons.append('FPR-undefined'if m['FPR']is None else'above-maxFPR')\n  candidates.append(dict(index=i,policy=p,metrics=m,feasible=not reasons,reasons=reasons))\n eligible=[c for c in candidates if c['feasible']];best=min(eligible,key=lambda c:(c['metrics']['meanCost'],c['index']))if eligible else None\n return dict(selectedIndex=None if best is None else best['index'],selectedPolicy=None if best is None else best['policy'],candidates=candidates,selectedValidation=None if best is None else best['metrics'],evaluation=None if best is None or er=='none'else metrics(scoped(rows,er),best['policy'],cc),selectionIDs=[r['id']for r in rr if r['eligible']])\ndef calibrate(rows,ee):\n buckets=[[]for _ in range(len(ee)-1)]\n for r in rows:\n  if not r['eligible']:continue\n  j=next((i for i in range(len(ee)-1)if r['score']<ee[i+1]),len(ee)-2);buckets[j].append(r)\n mass=sum((r['w']for r in rows if r['eligible']),F(0));P=sum((r['w']*r['y']for r in rows if r['eligible']),F(0));pi=divide(P,mass);Brier=None if not mass else sum((r['w']*(r['score']-r['y'])**2 for r in rows if r['eligible']),F(0))/mass;ECE=F(0);reliability=F(0);resolution=F(0);correction=F(0);bins=[]\n for i,rr in enumerate(buckets):\n  w=sum((r['w']for r in rr),F(0));mp=None if not w else sum((r['w']*r['score']for r in rr),F(0))/w;o=None if not w else sum((r['w']*r['y']for r in rr),F(0))/w\n  variance=None if not w else sum((r['w']*(r['score']-mp)**2 for r in rr),F(0))/w\n  covariance=None if not w else sum((r['w']*(r['score']-mp)*(r['y']-o)for r in rr),F(0))/w\n  bc=None if not w else variance-2*covariance;gap=None if not w else mp-o\n  bins.append(dict(index=i,rows=len(rr),mass=w,meanPrediction=mp,eventRate=o,gap=gap,absoluteGap=None if gap is None else abs(gap),scoreVariance=variance,scoreTargetCovariance=covariance,withinBinCorrection=bc,ids=[r['id']for r in rr]))\n  if w:\n   share=w/mass;ECE+=share*abs(gap);reliability+=share*gap**2;resolution+=share*(o-pi)**2;correction+=share*bc\n uncertainty=None if pi is None else pi*(1-pi);residual=None if Brier is None else Brier-(uncertainty-resolution+reliability+correction)\n return dict(mass=mass,prevalence=pi,Brier=Brier,ECE=ECE if mass else None,reliability=reliability if mass else None,resolution=resolution if mass else None,uncertainty=uncertainty,withinBinCorrection=correction if mass else None,BrierIdentityResidual=residual,bins=bins)\ndef typed(v):return type(v).__name__,v\ndef groups(rows,p,cc):\n bins={}\n for r in rows:\n  if r['group']is not None:bins.setdefault(typed(r['group']),[]).append(r)\n gm=[dict(group=rr[0]['group'],metrics=metrics(rr,p,cc))for rr in bins.values()];overall=metrics(rows,p,cc);unknown=metrics([r for r in rows if r['group']is None],p,cc);gaps={}\n for key in ['prevalence','selectionRate','TPR','FPR','precision','accuracy','meanCost']:\n  positive=[g for g in gm if g['metrics']['mass']>0];undefined=[g['group']for g in positive if g['metrics'][key]is None];vals=[g['metrics'][key]for g in positive if g['metrics'][key]is not None]\n  gaps[key]=dict(value=None if len(positive)<2 or undefined else max(vals)-min(vals),undefinedGroups=undefined,comparedPositiveMassGroups=[g['group']for g in positive])\n return dict(overall=overall,groups=gm,unknownGroup=unknown,gaps=gaps,partitionMassResidual=overall['mass']-unknown['mass']-sum((g['metrics']['mass']for g in gm),F(0)))\ndef actual_model(M):\n raw=M['records'];cat=M['categoricalFeatures'];p=len(raw[0]['x']);train=[r for r in raw if r['role']=='train'];medians=[]\n for j in range(p):\n  if j in cat:medians.append(None);continue\n  values=sorted(F(r['x'][j])for r in train);n=len(values);medians.append(values[n//2]if n%2 else(values[n//2-1]+values[n//2])/2)\n def transform(r):return[F(v)if j in cat else F(int(F(v)>medians[j]))for j,v in enumerate(r['x'])]\n counts={}\n for r in train:\n  key=tuple(transform(r));n,s=counts.get(key,(0,0));counts[key]=(n+1,s+int(r['y']))\n probabilities={k:F(s+1,n+2)for k,(n,s)in counts.items()};fallback=F(sum(int(r['y'])for r in train)+1,len(train)+2);scored=[]\n for i,r in enumerate(raw):\n  eligible=r['role']!='excluded';z=transform(r)if eligible else None;key=None if z is None else tuple(z);score=None if not eligible else probabilities.get(key,fallback)\n  scored.append(dict(id=r['id'],index=i,role=r['role'],group=r['group'],y=None if r['y']is None else F(r['y']),score=score,w=F(1),eligible=eligible,transformedX=z,unseenCell=None if not eligible else key not in probabilities))\n return dict(medians=medians,cells=counts,probabilities=probabilities,fallback=fallback,rows=scored,trainIDs=[r['id']for r in train])\n\n\nimport csv,json,hashlib,argparse,datetime\nfrom pathlib import Path\ndef missing(v):return None if v in ['', '.',None]else v\ndef load_sources(folder):\n def read_csv(name):\n  with (folder/name).open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))\n wb=read_csv('actual64-country-four-indicators-original-2024.csv')\n codes=['NY.GDP.PCAP.KD','NY.GDP.MKTP.KD.ZG','FP.CPI.TOTL.ZG','SP.DYN.LE00.IN']\n lookup={(r['countryISO3'],r['indicatorID']):r for r in wb};country=[]\n for i,iso in enumerate(sorted({r['countryISO3']for r in wb}),1):\n  native=[lookup[iso,c]for c in codes];v=[missing(r['originalValueToken'])for r in native]\n  country.append(dict(id=iso+':2024',sourceRow=i,originalID=iso,x=v[:3],y=None if v[3]is None else str(int(F(v[3])>=80)),group=None if v[0]is None else str(int(F(v[0])>=25000)),nativeTarget=v[3],nativeSourceRows=';'.join(r['sourceRow']for r in native)))\n nls=read_csv('actual3613-NLS-original52-fields-groups-roles.csv');person=[]\n for r in nls:\n  y=missing(r['wage76']);person.append(dict(id='person:'+r['sourceRow'],sourceRow=int(r['sourceRow']),originalID=r['id'],x=[missing(r[k])for k in ['ed76','age76','nearc4']],y=None if y is None else str(int(F(y)>=500)),group=missing(r['black']),nativeTarget=y,nativeSourceRows=r['sourceRow']))\n ch=read_csv('actual3150-churn-original14-fields-groups-roles.csv');company=[]\n for r in ch:\n  company.append(dict(id='customer:'+r['sourceRow'],sourceRow=int(r['sourceRow']),originalID='',x=[missing(r[k])for k in ['Call  Failure','Complains','Subscription  Length','Seconds of Use']],y=missing(r['Churn']),group=missing(r['Tariff Plan']),nativeTarget=missing(r['Churn']),nativeSourceRows=r['sourceRow']))\n assert len(wb)==64 and len(country)==16 and len(nls)==3613 and len(ch)==3150\n assert [int(r['sourceRow'])for r in ch if r['Charge  Amount']=='10']==[474,2174,2274,2374,2674,2924,2974]\n models={}\n for kind,raw,cat,units in [('country',country,[],['constant2015USD/person','annualPercent','annualPercent']),('person',person,[2],['years','years','nativeCategory']),('company',company,[1],['count','nativeCategory','months','seconds'])]:\n  order=sorted(range(len(raw)),key=lambda i:(hashlib.sha256(('ML14-role|'+kind+'|'+raw[i]['id']).encode()).hexdigest(),i))\n  for rank,i in enumerate(order):\n   r=raw[i];r['plannedRole']='test'if rank%5==0 else'validation'if rank%5==1 else'train';r['eligible']=None not in r['x']+[r['y']];r['role']=r['plannedRole']if r['eligible']else'excluded';r['weight']='1'\n  models[kind]=dict(records=raw,categoricalFeatures=cat,featureUnits=units)\n assert sum(r['eligible']for r in person)==3017\n return models\n\ndef exact(v):return ''if v is None else str(v)\ndef approx(v):return ''if v is None else format(float(v),'.17g')\ndef scalar_fields(m,keys):\n out={}\n for k in keys:\n  out[k+'Exact']=exact(m[k]);out[k+'Approx']=approx(m[k])\n return out\nCOUNTS=['mass','positiveTargetMass','negativeTargetMass','predictedPositiveMass','predictedNegativeMass']\nRATES=['prevalence','selectionRate','accuracy','precision','negativePredictiveValue','TPR','FPR','TNR','FNR','F1','balancedAccuracy','Brier','BrierSum','totalCost','meanCost']\nSCENARIOS=[('equal',F(1),F(1)),('miss-five',F(1),F(5)),('alarm-five',F(5),F(1))]\ndef packed(v):\n if isinstance(v,F):return str(v)\n if isinstance(v,dict):return{str(k):packed(x)for k,x in v.items()}\n if isinstance(v,(tuple,list)):return[packed(x)for x in v]\n return v\ndef run_study(source,out):\n out.mkdir(parents=True,exist_ok=True);models=load_sources(source)\n tables={name:[]for name in ['predictions','lineage','fit-medians','fit-cells','validation-candidates','test-metrics','test-curves','calibration-bins','group-metrics','chart-points']}\n studies={};charts=[]\n def point(kind,chart,series,index,x,y,xunit='dimensionless',yunit='dimensionless',role='test',tag=''):\n  tables['chart-points'].append(dict(kind=kind,chart=chart,series=series,index=index,xExact=exact(x),xApprox=approx(x),yExact=exact(y),yApprox=approx(y),xUnit=xunit,yUnit=yunit,role=role,tag=tag))\n for kind,M in models.items():\n  fit=actual_model(M);rr=fit['rows'];native=M['records'];test=scoped(rr,'test');cv=curves(test);cal=calibrate(test,[F(0),F(1,5),F(2,5),F(3,5),F(4,5),F(1)]);scenarios=[]\n  for i,r in enumerate(rr):\n   n=native[i];reason=''if r['eligible']else'required-X-or-Y-missing'\n   tables['predictions'].append(dict(kind=kind,id=r['id'],sourceRow=n['sourceRow'],originalID=n['originalID'],plannedRole=n['plannedRole'],role=r['role'],group=''if r['group']is None else r['group'],eligible=int(r['eligible']),targetExact=exact(r['y']),probabilityExact=exact(r['score']),probabilityApprox=approx(r['score']),unseenCell=''if r['unseenCell']is None else int(r['unseenCell']),transformedX=''if r['transformedX']is None else'|'.join(map(str,r['transformedX'])),reason=reason))\n   tables['lineage'].append(dict(kind=kind,id=r['id'],sourceRow=n['sourceRow'],originalID=n['originalID'],nativeSourceRows=n['nativeSourceRows'],rawX='|'.join(''if x is None else x for x in n['x']),nativeTarget=''if n['nativeTarget']is None else n['nativeTarget'],derivedTarget=exact(r['y']),nativeGroup=''if n['group']is None else n['group'],plannedRole=n['plannedRole'],role=r['role'],eligible=int(r['eligible']),analyticalMass='1',reason=reason))\n  for j,v in enumerate(fit['medians']):tables['fit-medians'].append(dict(kind=kind,feature=j,categorical=int(j in M['categoricalFeatures']),fitRows=len(fit['trainIDs']),medianExact=exact(v),medianApprox=approx(v),unit=M['featureUnits'][j]))\n  for key,(mass,pos)in fit['cells'].items():tables['fit-cells'].append(dict(kind=kind,cell='|'.join(map(str,key)),trainingRows=mass,positiveRows=pos,probabilityExact=exact(fit['probabilities'][key]),probabilityApprox=approx(fit['probabilities'][key]),fallbackExact=exact(fit['fallback']),fallbackApprox=approx(fit['fallback'])))\n  for j,p in enumerate(cv['points']):\n   policy=p['policy'];tables['test-curves'].append(dict(kind=kind,point=j,policy=policy if isinstance(policy,str)else'threshold',thresholdExact=''if isinstance(policy,str)else exact(policy),thresholdApprox=''if isinstance(policy,str)else approx(policy),**scalar_fields(p,['TP','FP','FN','TN','TPR','FPR','precision','recall'])))\n   point(kind,'roc','ROC',j,p['FPR'],p['TPR']);point(kind,'pr','PR-observed',j,p['recall'],p['precision'])\n  for b in cal['bins']:\n   tables['calibration-bins'].append(dict(kind=kind,bin=b['index'],leftExact=str(F(b['index'],5)),rightExact=str(F(b['index']+1,5)),rightClosed=int(b['index']==4),rows=b['rows'],ids=';'.join(str(i)for i in b['ids']),**scalar_fields(b,['mass','meanPrediction','eventRate','gap','absoluteGap','scoreVariance','scoreTargetCovariance','withinBinCorrection'])))\n   point(kind,'reliability','Binary event rate',b['index'],b['meanPrediction'],b['eventRate'],tag='rows='+str(b['rows']))\n  for j,r in enumerate(test):\n   point(kind,'test-scores','Training-fitted probability',j,F(j+1),r['score'],'test-row position','probability',tag=r['id'])\n   point(kind,'test-scores','Observed Y',j,F(j+1),r['y'],'test-row position','binary target',tag=r['id'])\n  for name,fp,fn in SCENARIOS:\n   choice=choose(rr,{},(fp,fn));gm=groups(test,choice['selectedPolicy'],(fp,fn));scenarios.append(dict(name=name,costs=dict(falsePositive=fp,falseNegative=fn),selection=choice,groups=gm));ev=choice['evaluation']\n   for c in choice['candidates']:\n    policy=c['policy'];mm=c['metrics'];tables['validation-candidates'].append(dict(kind=kind,scenario=name,candidate=c['index'],selected=int(c['index']==choice['selectedIndex']),policy=policy if isinstance(policy,str)else'threshold',thresholdExact=''if isinstance(policy,str)else exact(policy),thresholdApprox=''if isinstance(policy,str)else approx(policy),feasible=int(c['feasible']),reasons=';'.join(c['reasons']),**{k+'Exact':str(v)for k,v in mm['confusion'].items()},**scalar_fields(mm,COUNTS+['TPR','FPR','precision','meanCost','totalCost'])))\n    point(kind,'validation-cost',name,c['index'],F(c['index']),mm['meanCost'],'candidate index','hypothetical cost units/mass','validation',tag=exact(policy))\n   mm={**ev,**ev['confusion'],**{k:cv[k]for k in ['ROC_AUC','averagePrecision','PRTrapezoidWithInitialPrecisionOne']},**{k:cal[k]for k in ['ECE','reliability','resolution','uncertainty','withinBinCorrection','BrierIdentityResidual']}}\n   for key in ['TP','FP','FN','TN']+COUNTS+RATES+['ROC_AUC','averagePrecision','PRTrapezoidWithInitialPrecisionOne','ECE','reliability','resolution','uncertainty','withinBinCorrection','BrierIdentityResidual']:\n    unit='rows'if key in ['TP','FP','FN','TN']+COUNTS else'hypothetical cost units'if key=='totalCost'else'hypothetical cost units/mass'if key=='meanCost'else'sum squared-probability loss'if key=='BrierSum'else'dimensionless'\n    tables['test-metrics'].append(dict(kind=kind,scenario=name,metric=key,valueExact=exact(mm[key]),valueApprox=approx(mm[key]),unit=unit))\n   allg=[('overall','all',gm['overall'])]+[('known',str(g['group']),g['metrics'])for g in gm['groups']]+[('unknown','',gm['unknownGroup'])]\n   for j,(typ,token,g)in enumerate(allg):\n    tables['group-metrics'].append(dict(kind=kind,scenario=name,groupType=typ,groupToken=token,retainedRows=g.get('retainedRows',sum((r['group']==token)if typ=='known'else(r['group']is None)if typ=='unknown'else True for r in test)),**{k+'Exact':str(v)for k,v in g['confusion'].items()},**scalar_fields(g,COUNTS+RATES)))\n    if typ=='known':point(kind,'group-TPR',name,j-1,F(j-1),g['TPR'],'declared group position','TPR',tag=token)\n  studies[kind]=dict(kind=kind,rows=len(native),eligibleRows=sum(r['eligible']for r in rr),trainingIDs=fit['trainIDs'],fitMedians=fit['medians'],fitCells=[dict(cell=list(k),mass=n,positive=s,probability=fit['probabilities'][k])for k,(n,s)in fit['cells'].items()],fallback=fit['fallback'],scenarios=scenarios,testCurves=cv,testCalibration=cal,rowsScored=rr)\n files=[]\n for name,rows in tables.items():\n  p=out/('computed-'+name+'.csv')\n  with p.open('w',encoding='utf8',newline='')as f:w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows)\n  files.append(dict(file=p.name,rows=len(rows),columns=len(rows[0]),bodyFields=len(rows)*len(rows[0]),sha256=hashlib.sha256(p.read_bytes()).hexdigest()))\n (out/'study.json').write_text(json.dumps(packed(studies),ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\n sourceFiles=[source/n for n in ['actual64-country-four-indicators-original-2024.csv','actual3613-NLS-original52-fields-groups-roles.csv','actual3150-churn-original14-fields-groups-roles.csv']]\n provenance=dict(chapter='ML-14',arithmetic='Python stdlib Fraction exact finite values from original decimal strings; binary64 valueApprox is display only.',inputs=[dict(file=p.name,sha256=hashlib.sha256(p.read_bytes()).hexdigest())for p in sourceFiles],priorEngineModelsScoresOrComputedFilesRead=False,roleRule=\"SHA256('ML14-role|'+kind+'|'+ID),rankmod5=0test/1validation/others train before eligibility\",costs='Hypothetical1/1,1/5,5/1; no causal intervention returns',files=files,observations={k:dict(sourceRows=v['rows'],eligibleRows=v['eligibleRows'],trainingRows=len(v['trainingIDs']))for k,v in studies.items()})\n (out/'provenance.json').write_text(json.dumps(provenance,ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\n print(json.dumps(dict(status='PASS standalone completed',files=len(files),bodyFields=sum(f['bodyFields']for f in files),observations=provenance['observations'])))\n\n# Fixed declared examples: full web budget/option validation is not reproduced.\nfrom html import escape\nimport textwrap\ndef validated_rows(raw):\n for r in raw:\n  assert F(str(r.get('weight','1')))>=0,'negative analytical mass'\n  assert r['score']is None or 0<=F(str(r['score']))<=1,'score outside zero/one'\n  assert r['y']is None or F(str(int(r['y']))if isinstance(r['y'],bool)else str(r['y']))in [0,1],'binary target required'\n return read(raw)\ndef serial(v):\n if isinstance(v,F):return dict(exactFraction=str(v),value=float(v))\n if isinstance(v,(list,tuple)):return[serial(x)for x in v]\n if isinstance(v,dict):return{k:serial(x)for k,x in v.items()}\n return v\ndef fixed_svg(path,points,title,xlabel,ylabel,legend):\n use=[p for p in points if p['xExact']!=''and p['yExact']!=''];xs=[float(F(p['xExact']))for p in use];ys=[float(F(p['yExact']))for p in use]\n xmin=min(xs,default=0);xmax=max(xs,default=1);ymin=min([0]+ys);ymax=max([0]+ys)\n if xmin==xmax:xmin-=.5;xmax+=.5\n if ymin==ymax:ymax=ymin+1\n X=lambda v:85+(float(v)-xmin)/(xmax-xmin)*480;Y=lambda v:278-(float(v)-ymin)/(ymax-ymin)*175\n s='<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"620\" height=\"360\" viewBox=\"0 0 620 360\"><rect width=\"620\" height=\"360\" fill=\"white\"/><g font-family=\"Arial, sans-serif\" font-size=\"13\" fill=\"#17324d\">'\n for i,line in enumerate(textwrap.wrap(title,width=65)):s+='<text x=\"25\" y=\"'+str(24+i*18)+'\">'+escape(line)+'</text>'\n colors=['#176b9b','#b85e18','#437e4d']\n for i,label in enumerate(legend):s+='<circle cx=\"'+str(30+i*250)+'\" cy=\"76\" r=\"4\" fill=\"'+colors[i%3]+'\"/><text x=\"'+str(42+i*250)+'\" y=\"80\">'+escape(label)+'</text>'\n s+='<path d=\"M85 98V278H575\" fill=\"none\" stroke=\"#52677d\"/><text text-anchor=\"middle\" x=\"325\" y=\"338\">'+escape(xlabel)+'</text><text text-anchor=\"middle\" transform=\"translate(21,190) rotate(-90)\">'+escape(ylabel)+'</text>'\n for i in range(5):\n  xx=xmin+(xmax-xmin)*i/4;yy=ymin+(ymax-ymin)*i/4;s+='<text text-anchor=\"middle\" x=\"'+format(X(xx),'.9g')+'\" y=\"305\">'+format(xx,'.4g')+'</text><text text-anchor=\"end\" x=\"77\" y=\"'+format(Y(yy)+4,'.9g')+'\">'+format(yy,'.4g')+'</text>'\n for p in use:s+='<circle cx=\"'+format(X(F(p['xExact'])),'.9g')+'\" cy=\"'+format(Y(F(p['yExact'])),'.9g')+'\" r=\"3\" fill=\"'+colors[p['series']%3]+'\"/>'\n path.write_text(s+'</g></svg>',encoding='utf8')\ndef fixed_run():\n ap=argparse.ArgumentParser();ap.add_argument('--out',type=Path,default=Path('results'));ap.add_argument('--data-dir',type=Path,default=Path(__file__).resolve().parent.parent/'ml14-sources');args=ap.parse_args();args.out.mkdir(parents=True,exist_ok=True)\n api=FIXED['api'];a=FIXED['args'];summary=[];points=[];xlabel='Declared index';ylabel='Value';legend=['Declared result']\n def metric(name,v,unit='dimensionless'):\n  q=None if v is None else v if isinstance(v,F)else F(v);summary.append(dict(metric=name,value='undefined'if q is None else format(float(q),'.9g'),exactValue=''if q is None else str(q),unit=unit,defined=int(q is not None)))\n def pt(i,x,y,ident='',series=0):\n  points.append(dict(series=series,index=i,xExact=''if x is None else str(F(x)),x='undefined'if x is None else format(float(x),'.9g'),yExact=''if y is None else str(F(y)),y='undefined'if y is None else format(float(y),'.9g'),id=str(ident)))\n if api=='realdata':\n  models=load_sources(args.data_dir);model=models[a['kind']];fit=actual_model(model);rr=fit['rows'];test=scoped(rr,'test');scenarios=[]\n  for name,fp,fn in SCENARIOS:\n   c=choose(rr,{},(fp,fn));scenarios.append(dict(name=name,selection=c));metric(name+'Threshold',c['selectedPolicy']);metric(name+'TestCost',c['evaluation']['meanCost'],'hypothetical cost units/mass')\n  cv=curves(test);cal=calibrate(test,[F(0),F(1,5),F(2,5),F(3,5),F(4,5),F(1)]);metric('testAUC',cv['ROC_AUC']);metric('testAP',cv['averagePrecision']);metric('testBrier',cal['Brier']);metric('eligibleRows',sum(r['eligible']for r in rr),'rows')\n  for i,r in enumerate(test):pt(i,i+1,r['score'],r['id'],0);pt(i,i+1,r['y'],r['id'],1)\n  full=dict(kind=a['kind'],fitMedians=fit['medians'],fitCells=[dict(cell=list(k),mass=n,positive=s,probability=fit['probabilities'][k])for k,(n,s)in fit['cells'].items()],rowsScored=rr,scenarios=scenarios,testCurves=cv,testCalibration=cal);xlabel='Test row, native order';ylabel='Y or probability';legend=['Training-fitted probability','Observed Y']\n else:\n  rr=validated_rows(a['rows']);role=a.get('role','all');frame=scoped(rr,role);cc=cost(a.get('costs'));t=policy(a.get('threshold','1/2'))\n  if api=='metrics':\n   full=metrics(frame,t,cc)\n   for k in ['mass','accuracy','precision','TPR','FPR','F1','Brier','meanCost']:metric(k,full[k],'mass'if k=='mass'else'hypothetical cost units/mass'if k=='meanCost'else'dimensionless')\n   metric('BayesThreshold',full['bayesThreshold'])\n   for i,k in enumerate(['TP','FP','FN','TN']):pt(i,i,full['confusion'][k],k)\n   xlabel='TP / FP / FN / TN positions';ylabel='Analytical mass'\n  elif api=='curves':\n   full=curves(frame)\n   for k in ['ROC_AUC','averagePrecision','PRTrapezoidWithInitialPrecisionOne']:metric(k,full[k])\n   for i,p in enumerate(full['points']):pt(i,p['FPR'],p['TPR'],str(p['policy']))\n   xlabel='False positive rate';ylabel='True positive rate';legend=['Observed ROC operating points']\n  elif api=='choose':\n   full=choose(rr,a,cc);metric('selectedIndex',full['selectedIndex'],'candidate index');metric('minimumCost',None if full['selectedValidation']is None else full['selectedValidation']['meanCost'],'hypothetical cost units/mass');metric('feasible',int(full['selectedIndex']is not None),'indicator')\n   for c in full['candidates']:pt(c['index'],c['index'],c['metrics']['meanCost'],str(c['policy']))\n   xlabel='Validation candidate';ylabel='Assumed cost / mass';legend=['Validation candidate costs']\n  elif api=='calibrate':\n   full=calibrate(frame,[F(str(e))for e in a.get('binEdges',['0','1/5','2/5','3/5','4/5','1'])])\n   for k in ['ECE','Brier','uncertainty','resolution','reliability','withinBinCorrection','BrierIdentityResidual']:metric(k,full[k])\n   for b in full['bins']:pt(b['index'],b['meanPrediction'],b['eventRate'],'bin:'+str(b['index']))\n   xlabel='Bin mean forecast';ylabel='Bin event rate';legend=['Binary-event reliability']\n  elif api=='groups':\n   full=groups(frame,t,cc);metric('overallTPR',full['overall']['TPR']);metric('TPRGap',full['gaps']['TPR']['value']);metric('precisionGap',full['gaps']['precision']['value']);metric('unknownMass',full['unknownGroup']['mass'],'mass');metric('partitionResidual',full['partitionMassResidual'],'mass')\n   for i,g in enumerate(full['groups']):pt(i,i,g['metrics']['TPR'],str(g['group']))\n   xlabel='Declared group position';ylabel='True positive rate';legend=['Known-group TPR']\n  else:raise ValueError('unknown fixed API')\n def csvout(name,rows):\n  with(args.out/name).open('w',encoding='utf8',newline='')as f:w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows)\n csvout('summary.csv',summary);csvout('plot-points.csv',points);fixed_svg(args.out/'plot.svg',points,FIXED['title'],xlabel,ylabel,legend)\n (args.out/'full.json').write_text(json.dumps(dict(api=api,variant=FIXED['variant'],input=FIXED['args'],arithmetic='Python standard-library Fraction, declared fixed example; full web validator/budgets not reproduced',result=serial(full)),ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\n print(json.dumps(dict(api=api,variant=FIXED['variant'],summaryMetrics=len(summary),plotSlots=len(points))))\n\nFIXED={'api': 'choose', 'variant': 'infeasible', 'args': {'rows': [{'id': 'a', 'score': '.9', 'y': 1, 'group': 'A', 'role': 'validation'}, {'id': 'b', 'score': '.8', 'y': 1, 'group': 'A', 'role': 'validation'}, {'id': 'c', 'score': '.8', 'y': 0, 'group': 'A', 'role': 'validation'}, {'id': 'd', 'score': '.6', 'y': 0, 'group': 'B', 'role': 'validation'}, {'id': 'e', 'score': '.4', 'y': 1, 'group': 'B', 'role': 'validation'}, {'id': 'f', 'score': '.1', 'y': 0, 'group': 'B', 'role': 'validation'}], 'minTPR': '4/5', 'maxFPR': '2/5', 'evaluationRole': 'none'}, 'title': 'No threshold satisfies both declared rate constraints'}\nif __name__=='__main__':fixed_run()\n",
        "input": {
          "rows": [
            {
              "id": "a",
              "score": ".9",
              "y": 1,
              "group": "A",
              "role": "validation"
            },
            {
              "id": "b",
              "score": ".8",
              "y": 1,
              "group": "A",
              "role": "validation"
            },
            {
              "id": "c",
              "score": ".8",
              "y": 0,
              "group": "A",
              "role": "validation"
            },
            {
              "id": "d",
              "score": ".6",
              "y": 0,
              "group": "B",
              "role": "validation"
            },
            {
              "id": "e",
              "score": ".4",
              "y": 1,
              "group": "B",
              "role": "validation"
            },
            {
              "id": "f",
              "score": ".1",
              "y": 0,
              "group": "B",
              "role": "validation"
            }
          ],
          "minTPR": "4/5",
          "maxFPR": "2/5",
          "evaluationRole": "none"
        },
        "inputFiles": [],
        "returnCode": 0,
        "expectedFailure": false,
        "stdout": "{\"api\": \"choose\", \"variant\": \"infeasible\", \"summaryMetrics\": 3, \"plotSlots\": 6}\n",
        "stderr": "",
        "summary": {
          "selectedIndex": "undefined",
          "minimumCost": "undefined",
          "feasible": "0"
        },
        "summaryRows": [
          {
            "metric": "selectedIndex",
            "value": "undefined",
            "exactValue": "",
            "unit": "candidate index",
            "defined": "0"
          },
          {
            "metric": "minimumCost",
            "value": "undefined",
            "exactValue": "",
            "unit": "hypothetical cost units/mass",
            "defined": "0"
          },
          {
            "metric": "feasible",
            "value": "0",
            "exactValue": "0",
            "unit": "indicator",
            "defined": "1"
          }
        ],
        "plotPoints": [
          {
            "series": "0",
            "index": "0",
            "xExact": "0",
            "x": "0",
            "yExact": "1/2",
            "y": "0.5",
            "id": "always-negative"
          },
          {
            "series": "0",
            "index": "1",
            "xExact": "1",
            "x": "1",
            "yExact": "1/3",
            "y": "0.333333333",
            "id": "9/10"
          },
          {
            "series": "0",
            "index": "2",
            "xExact": "2",
            "x": "2",
            "yExact": "1/3",
            "y": "0.333333333",
            "id": "4/5"
          },
          {
            "series": "0",
            "index": "3",
            "xExact": "3",
            "x": "3",
            "yExact": "1/2",
            "y": "0.5",
            "id": "3/5"
          },
          {
            "series": "0",
            "index": "4",
            "xExact": "4",
            "x": "4",
            "yExact": "1/3",
            "y": "0.333333333",
            "id": "2/5"
          },
          {
            "series": "0",
            "index": "5",
            "xExact": "5",
            "x": "5",
            "yExact": "1/2",
            "y": "0.5",
            "id": "1/10"
          }
        ],
        "plotFile": "ml14-fixed-results/choose-infeasible-python/plot.svg",
        "plotSHA256": "5fb580bd285885167668a7c3595985e5085ac7129639fc9a3cc9ae7d43e80786",
        "files": [
          {
            "file": "ml14-fixed-results/choose-infeasible-python/full.json",
            "sha256": "232cc8064a0c59b11cf0085692523c8dee144edb1005397734b3ab1d36a7a18d",
            "bytes": 33096
          },
          {
            "file": "ml14-fixed-results/choose-infeasible-python/plot-points.csv",
            "sha256": "f36765e1e6aaa2f00a7b3f6ea13499d31dabc05cc37aba47a1e6c9d6dce7a0f5",
            "bytes": 199
          },
          {
            "file": "ml14-fixed-results/choose-infeasible-python/plot.svg",
            "sha256": "5fb580bd285885167668a7c3595985e5085ac7129639fc9a3cc9ae7d43e80786",
            "bytes": 1432
          },
          {
            "file": "ml14-fixed-results/choose-infeasible-python/summary.csv",
            "sha256": "4a80cd0dc1edea14b090a88f63bbdcff1d4237276d7afdf715397fa1eb87ca04",
            "bytes": 163
          }
        ],
        "scope": "Actually executed standalone fixed example, Python exact Fraction versus base-R binary64. Approximate R residuals retained; not universal exact arithmetic/web validation/native UI. Source programs read factual3CSV only."
      }
    },
    "r": {
      "miss-five": {
        "api": "choose",
        "variant": "miss-five",
        "language": "r",
        "title": "Validation-only threshold with missed-case cost five",
        "codeFile": "ml14-code/choose-miss-five.R",
        "codeSHA256": "bf679a153592aa526b10d9b6bd1527ec12c2405ec8c2db82548f11c5d5495fbe",
        "code": "# ML14 standalone public counterpart, base R only.\n# Inputs are only the three factual CSVs; derived columns/previous model answers unused.\n# Binary64 arithmetic, not arbitrary-precision Fraction. At numerical cost ties\n# within 1e-12 retain the earliest candidate. Exact claims belong to Python/web.\n# SHA256 infrastructure below is reused verbatim from the previous public study.\nargs<-commandArgs(trailingOnly=TRUE);filearg<-grep(\"^--file=\",commandArgs(),value=TRUE)\nhere<-if(dir.exists(\"ml14-sources\"))getwd()else if(length(filearg))dirname(normalizePath(sub(\"^--file=\",\"\",filearg[1])))else getwd()\noption<-function(key,default){i<-match(key,args);if(is.na(i))default else args[i+1]}\nsourceDir<-option(\"--source\",file.path(here,\"ml14-sources\"));outDir<-option(\"--out\",file.path(getwd(),\"ml14-r-results\"));dir.create(outDir,recursive=TRUE,showWarnings=FALSE)\nnum<-function(x){x[x%in%c(\"\",\".\")]<-NA_character_;as.numeric(x)}\nfmt<-function(x)ifelse(is.na(x),\"\",sprintf(\"%.17g\",x))\nratio<-function(a,b)if(b==0)NA_real_ else a/b\nreadnative<-function(name)read.csv(file.path(sourceDir,name),check.names=FALSE,colClasses=\"character\",na.strings=character(),stringsAsFactors=FALSE)\n# Vectorized SHA256 for the short ASCII keys used in this study.\n# Unsigned words use exact integer-valued doubles; bit operations use safe\n# 16-bit halves, avoiding R's reserved signed-INT_MIN/NA representation.\nMOD<-2^32\nxor32<-function(a,b) as.double(bitwXor(as.integer(floor(a/65536)),as.integer(floor(b/65536))))*65536+as.double(bitwXor(as.integer(a%%65536),as.integer(b%%65536)))\nand32<-function(a,b) as.double(bitwAnd(as.integer(floor(a/65536)),as.integer(floor(b/65536))))*65536+as.double(bitwAnd(as.integer(a%%65536),as.integer(b%%65536)))\nrot<-function(x,n) floor(x/2^n)+(x%%2^n)*2^(32-n)\nxor3<-function(a,b,c) xor32(xor32(a,b),c)\nK<-c(0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5,0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967,0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070,0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3,0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2)\nsha256<-function(strings) {\n n<-length(strings);bytes<-matrix(0,n,64)\n for(i in seq_len(n)) {v<-utf8ToInt(strings[i]);stopifnot(length(v)<56,all(v<128));if(length(v)) bytes[i,seq_along(v)]<-v;bytes[i,length(v)+1]<-128;bits<-length(v)*8;bytes[i,61:64]<-c(floor(bits/2^24)%%256,floor(bits/2^16)%%256,floor(bits/256)%%256,bits%%256)}\n w<-matrix(0,n,64)\n for(j in 1:16) {b<-4*(j-1)+1;w[,j]<-bytes[,b]*2^24+bytes[,b+1]*2^16+bytes[,b+2]*256+bytes[,b+3]}\n for(j in 17:64) {s0<-xor3(rot(w[,j-15],7),rot(w[,j-15],18),floor(w[,j-15]/8));s1<-xor3(rot(w[,j-2],17),rot(w[,j-2],19),floor(w[,j-2]/1024));w[,j]<-(w[,j-16]+s0+w[,j-7]+s1)%%MOD}\n init<-c(0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19)\n state<-lapply(init,function(v) rep(v,n));a<-state[[1]];b<-state[[2]];c<-state[[3]];d<-state[[4]];e<-state[[5]];f<-state[[6]];g<-state[[7]];h<-state[[8]]\n for(j in 1:64) {S1<-xor3(rot(e,6),rot(e,11),rot(e,25));ch<-xor32(and32(e,f),and32(MOD-1-e,g));t1<-(h+S1+ch+K[j]+w[,j])%%MOD;S0<-xor3(rot(a,2),rot(a,13),rot(a,22));maj<-xor3(and32(a,b),and32(a,c),and32(b,c));t2<-(S0+maj)%%MOD;h<-g;g<-f;f<-e;e<-(d+t1)%%MOD;d<-c;c<-b;b<-a;a<-(t1+t2)%%MOD}\n end<-list(a,b,c,d,e,f,g,h);hex<-lapply(1:8,function(j){v<-(end[[j]]+init[j])%%MOD;paste0(sprintf(\"%04x\",as.integer(floor(v/65536))),sprintf(\"%04x\",as.integer(v%%65536)))})\n do.call(paste0,hex)\n}\nstopifnot(identical(sha256(c(\"abc\",\"\")),c(\"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad\",\"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855\")))\n\nloadData<-function(){\n wb<-readnative(\"actual64-country-four-indicators-original-2024.csv\");codes<-c(\"NY.GDP.PCAP.KD\",\"NY.GDP.MKTP.KD.ZG\",\"FP.CPI.TOTL.ZG\",\"SP.DYN.LE00.IN\");iso<-sort(unique(wb$countryISO3));stopifnot(nrow(wb)==64,length(iso)==16)\n tokens<-t(vapply(iso,function(s)wb$originalValueToken[match(paste(s,codes),paste(wb$countryISO3,wb$indicatorID))],character(4)));vals<-matrix(num(as.vector(tokens)),nrow=nrow(tokens))\n country<-list(id=paste0(iso,\":2024\"),sourceRow=1:16,originalID=iso,x=vals[,1:3,drop=FALSE],rawX=tokens[,1:3,drop=FALSE],nativeTarget=tokens[,4],y=as.integer(vals[,4]>=80),group=ifelse(is.na(vals[,1]),NA_character_,as.character(as.integer(vals[,1]>=25000))),lineage=vapply(iso,function(s)paste(wb$sourceRow[match(paste(s,codes),paste(wb$countryISO3,wb$indicatorID))],collapse=\";\"),character(1)),cat=integer(),units=c(\"constant2015USD/person\",\"annualPercent\",\"annualPercent\"))\n nls<-readnative(\"actual3613-NLS-original52-fields-groups-roles.csv\");raw<-cbind(nls$ed76,nls$age76,nls$nearc4)\n person<-list(id=paste0(\"person:\",nls$sourceRow),sourceRow=as.integer(nls$sourceRow),originalID=nls$id,x=matrix(num(as.vector(raw)),nrow=nrow(raw)),rawX=raw,nativeTarget=nls$wage76,y=as.integer(num(nls$wage76)>=500),group=ifelse(nls$black%in%c(\"\",\".\"),NA_character_,nls$black),lineage=nls$sourceRow,cat=2L,units=c(\"years\",\"years\",\"nativeCategory\"))\n ch<-readnative(\"actual3150-churn-original14-fields-groups-roles.csv\");raw<-cbind(ch[[\"Call  Failure\"]],ch$Complains,ch[[\"Subscription  Length\"]],ch[[\"Seconds of Use\"]])\n company<-list(id=paste0(\"customer:\",ch$sourceRow),sourceRow=as.integer(ch$sourceRow),originalID=rep(\"\",nrow(ch)),x=matrix(num(as.vector(raw)),nrow=nrow(raw)),rawX=raw,nativeTarget=ch$Churn,y=as.integer(ch$Churn),group=ifelse(ch[[\"Tariff Plan\"]]%in%c(\"\",\".\"),NA_character_,ch[[\"Tariff Plan\"]]),lineage=ch$sourceRow,cat=1L,units=c(\"count\",\"nativeCategory\",\"months\",\"seconds\"))\n stopifnot(nrow(nls)==3613,nrow(ch)==3150,identical(as.integer(ch$sourceRow[ch[[\"Charge  Amount\"]]==\"10\"]),c(474L,2174L,2274L,2374L,2674L,2924L,2974L)))\n result<-list(country=country,person=person,company=company)\n for(k in names(result)){d<-result[[k]];n<-length(d$id);d$eligible<-!is.na(d$y)&rowSums(is.na(d$x))==0;hash<-sha256(paste0(\"ML14-role|\",k,\"|\",d$id));rank<-integer(n);rank[order(hash,seq_len(n))]<-seq_len(n)-1L;d$plannedRole<-ifelse(rank%%5==0,\"test\",ifelse(rank%%5==1,\"validation\",\"train\"));d$role<-ifelse(d$eligible,d$plannedRole,\"excluded\");result[[k]]<-d}\n stopifnot(sum(result$person$eligible)==3017);result\n}\nfitmodel<-function(d){\n ids<-which(d$role==\"train\");p<-ncol(d$x);m<-vapply(seq_len(p),function(j)if((j-1)%in%d$cat)NA_real_ else median(d$x[ids,j]),numeric(1));z<-d$x\n for(j in seq_len(p))if(!((j-1)%in%d$cat))z[,j]<-as.numeric(z[,j]>m[j])\n keys<-apply(z,1,function(v)paste(fmt(v),collapse=\"|\"));lev<-unique(keys[ids]);mass<-vapply(lev,function(k)sum(keys[ids]==k),integer(1));positive<-vapply(lev,function(k)sum(d$y[ids][keys[ids]==k]),integer(1));prob<-(positive+1)/(mass+2);fallback<-(sum(d$y[ids])+1)/(length(ids)+2);pred<-prob[match(keys,lev)];unseen<-is.na(pred);pred[unseen]<-fallback;pred[!d$eligible]<-NA_real_;unseen[!d$eligible]<-NA\n list(ids=ids,medians=m,z=z,keys=keys,lev=lev,mass=mass,positive=positive,prob=prob,fallback=fallback,pred=pred,unseen=unseen)\n}\nmeasure<-function(d,p,ids,t=.5,cost=c(1,1)){\n use<-ids[d$eligible[ids]&!is.na(p[ids])];y<-d$y[use];a<-if(is.character(t))rep(t==\"always-positive\",length(use))else p[use]>=t\n TP<-sum(a&y==1);FP<-sum(a&y==0);FN<-sum(!a&y==1);TN<-sum(!a&y==0);P<-TP+FN;N<-FP+TN;W<-P+N;PP<-TP+FP;PN<-TN+FN;TPR<-ratio(TP,P);TNR<-ratio(TN,N);bs<-sum((p[use]-y)^2);tc<-FP*cost[1]+FN*cost[2]\n list(TP=TP,FP=FP,FN=FN,TN=TN,mass=W,positiveTargetMass=P,negativeTargetMass=N,predictedPositiveMass=PP,predictedNegativeMass=PN,prevalence=ratio(P,W),selectionRate=ratio(PP,W),accuracy=ratio(TP+TN,W),precision=ratio(TP,PP),negativePredictiveValue=ratio(TN,PN),TPR=TPR,FPR=ratio(FP,N),TNR=TNR,FNR=ratio(FN,P),F1=ratio(2*TP,2*TP+FP+FN),balancedAccuracy=if(is.na(TPR)||is.na(TNR))NA_real_ else(TPR+TNR)/2,Brier=ratio(bs,W),BrierSum=bs,totalCost=tc,meanCost=ratio(tc,W))\n}\ncurves<-function(d,p,ids){\n use<-ids[d$eligible[ids]&!is.na(p[ids])];scores<-sort(unique(p[use]),decreasing=TRUE);policies<-c(list(\"always-negative\"),as.list(scores));points<-lapply(policies,function(t){m<-measure(d,p,ids,t);c(list(policy=t),m[c(\"TP\",\"FP\",\"FN\",\"TN\",\"TPR\",\"FPR\",\"precision\")],list(recall=m$TPR))})\n pos<-use[d$y[use]==1];neg<-use[d$y[use]==0];U<-0;for(i in pos)U<-U+sum(p[i]>p[neg])+.5*sum(p[i]==p[neg])\n AP<-0;trap<-0;lastR<-0;lastP<-1\n if(length(pos)&&length(scores))for(j in seq_along(scores)){z<-points[[j+1]];AP<-AP+(z$recall-lastR)*z$precision;trap<-trap+(z$recall-lastR)*(z$precision+lastP)/2;lastR<-z$recall;lastP<-z$precision}\n list(points=points,ROC_AUC=ratio(U,length(pos)*length(neg)),averagePrecision=if(length(pos))AP else NA_real_,PRTrapezoidWithInitialPrecisionOne=if(length(pos))trap else NA_real_)\n}\ncalibrate<-function(d,p,ids){\n use<-ids[d$eligible[ids]&!is.na(p[ids])];W<-length(use);pi<-if(W)mean(d$y[use])else NA_real_;bins<-list();ECE<-rel<-res<-correction<-0\n whichbin<-findInterval(p[use],seq(0,1,.2),rightmost.closed=TRUE,all.inside=TRUE)\n for(b in 1:5){rr<-use[whichbin==b];w<-length(rr);mp<-if(w)mean(p[rr])else NA_real_;o<-if(w)mean(d$y[rr])else NA_real_;variance<-if(w)mean((p[rr]-mp)^2)else NA_real_;covariance<-if(w)mean((p[rr]-mp)*(d$y[rr]-o))else NA_real_;bc<-variance-2*covariance;gap<-mp-o\n  bins[[b]]<-list(mass=w,meanPrediction=mp,eventRate=o,gap=gap,absoluteGap=abs(gap),scoreVariance=variance,scoreTargetCovariance=covariance,withinBinCorrection=bc,rows=w,ids=d$id[rr])\n  if(w){share<-w/W;ECE<-ECE+share*abs(gap);rel<-rel+share*gap^2;res<-res+share*(o-pi)^2;correction<-correction+share*bc}\n };bs<-if(W)mean((p[use]-d$y[use])^2)else NA_real_;unc<-pi*(1-pi)\n list(bins=bins,ECE=if(W)ECE else NA_real_,Brier=bs,reliability=if(W)rel else NA_real_,resolution=if(W)res else NA_real_,uncertainty=unc,withinBinCorrection=if(W)correction else NA_real_,BrierIdentityResidual=bs-(unc-res+rel+correction))\n}\ncounts<-c(\"mass\",\"positiveTargetMass\",\"negativeTargetMass\",\"predictedPositiveMass\",\"predictedNegativeMass\");rates<-c(\"prevalence\",\"selectionRate\",\"accuracy\",\"precision\",\"negativePredictiveValue\",\"TPR\",\"FPR\",\"TNR\",\"FNR\",\"F1\",\"balancedAccuracy\",\"Brier\",\"BrierSum\",\"totalCost\",\"meanCost\")\ntables<-setNames(lapply(1:10,function(i)list()),c(\"predictions\",\"lineage\",\"fit-medians\",\"fit-cells\",\"validation-candidates\",\"test-metrics\",\"test-curves\",\"calibration-bins\",\"group-metrics\",\"chart-points\"))\nadd<-function(name,row)tables[[name]][[length(tables[[name]])+1L]]<<-row\nscalars<-function(m,keys){out<-list();for(k in keys){out[[paste0(k,\"Exact\")]]<-\"\";out[[paste0(k,\"Approx\")]]<-fmt(m[[k]])};out}\ntagrow<-function(kind,...)c(list(kind=kind),list(...))\npoint<-function(kind,chart,series,index,x,y,xunit=\"dimensionless\",yunit=\"dimensionless\",role=\"test\",tag=\"\"){add(\"chart-points\",tagrow(kind,chart=chart,series=series,index=index,xExact=\"\",xApprox=fmt(x),yExact=\"\",yApprox=fmt(y),xUnit=xunit,yUnit=yunit,role=role,tag=tag))}\nstudy<-function(kind,d){\n f<-fitmodel(d);n<-length(d$id);train<-which(d$role==\"train\");validation<-which(d$role==\"validation\");test<-which(d$role==\"test\");p<-f$pred;cv<-curves(d,p,test);cal<-calibrate(d,p,test)\n for(i in seq_len(n)){\n  reason<-if(d$eligible[i])\"\"else\"required-X-or-Y-missing\";transformed<-if(d$eligible[i])paste(fmt(f$z[i,]),collapse=\"|\")else\"\"\n  add(\"predictions\",tagrow(kind,id=d$id[i],sourceRow=d$sourceRow[i],originalID=d$originalID[i],plannedRole=d$plannedRole[i],role=d$role[i],group=ifelse(is.na(d$group[i]),\"\",d$group[i]),eligible=as.integer(d$eligible[i]),targetExact=fmt(d$y[i]),probabilityExact=\"\",probabilityApprox=fmt(p[i]),unseenCell=ifelse(is.na(f$unseen[i]),\"\",as.character(as.integer(f$unseen[i]))),transformedX=transformed,reason=reason))\n  raw<-d$rawX[i,];raw[raw%in%c(\"\",\".\")]<-\"\";nativeY<-d$nativeTarget[i];if(nativeY%in%c(\"\",\".\"))nativeY<-\"\"\n  add(\"lineage\",tagrow(kind,id=d$id[i],sourceRow=d$sourceRow[i],originalID=d$originalID[i],nativeSourceRows=d$lineage[i],rawX=paste(raw,collapse=\"|\"),nativeTarget=nativeY,derivedTarget=fmt(d$y[i]),nativeGroup=ifelse(is.na(d$group[i]),\"\",d$group[i]),plannedRole=d$plannedRole[i],role=d$role[i],eligible=as.integer(d$eligible[i]),analyticalMass=\"1\",reason=reason))\n }\n for(j in seq_len(ncol(d$x)))add(\"fit-medians\",tagrow(kind,feature=j-1,categorical=as.integer((j-1)%in%d$cat),fitRows=length(train),medianExact=\"\",medianApprox=fmt(f$medians[j]),unit=d$units[j]))\n for(j in seq_along(f$lev))add(\"fit-cells\",tagrow(kind,cell=f$lev[j],trainingRows=f$mass[j],positiveRows=f$positive[j],probabilityExact=\"\",probabilityApprox=fmt(f$prob[j]),fallbackExact=\"\",fallbackApprox=fmt(f$fallback)))\n for(j in seq_along(cv$points)){\n  z<-cv$points[[j]];t<-z$policy;add(\"test-curves\",c(tagrow(kind,point=j-1,policy=if(is.character(t))t else\"threshold\",thresholdExact=\"\",thresholdApprox=if(is.character(t))\"\"else fmt(t)),scalars(z,c(\"TP\",\"FP\",\"FN\",\"TN\",\"TPR\",\"FPR\",\"precision\",\"recall\"))))\n  point(kind,\"roc\",\"ROC\",j-1,z$FPR,z$TPR);point(kind,\"pr\",\"PR-observed\",j-1,z$recall,z$precision)\n }\n for(b in 1:5){z<-cal$bins[[b]];add(\"calibration-bins\",c(tagrow(kind,bin=b-1,leftExact=c(\"0\",\"1/5\",\"2/5\",\"3/5\",\"4/5\")[b],rightExact=c(\"1/5\",\"2/5\",\"3/5\",\"4/5\",\"1\")[b],rightClosed=as.integer(b==5),rows=z$rows,ids=paste(z$ids,collapse=\";\")),scalars(z,c(\"mass\",\"meanPrediction\",\"eventRate\",\"gap\",\"absoluteGap\",\"scoreVariance\",\"scoreTargetCovariance\",\"withinBinCorrection\"))));point(kind,\"reliability\",\"Binary event rate\",b-1,z$meanPrediction,z$eventRate,tag=paste0(\"rows=\",z$rows))}\n for(j in seq_along(test)){i<-test[j];point(kind,\"test-scores\",\"Training-fitted probability\",j-1,j,p[i],\"test-row position\",\"probability\",tag=d$id[i]);point(kind,\"test-scores\",\"Observed Y\",j-1,j,d$y[i],\"test-row position\",\"binary target\",tag=d$id[i])}\n scenarioNames<-c(\"equal\",\"miss-five\",\"alarm-five\");costs<-list(c(1,1),c(1,5),c(5,1))\n for(s in 1:3){name<-scenarioNames[s];cost<-costs[[s]];grid<-c(list(\"always-negative\"),as.list(sort(unique(p[validation]),decreasing=TRUE)));candidates<-lapply(grid,function(t)measure(d,p,validation,t,cost));values<-vapply(candidates,function(m)m$meanCost,numeric(1));best<-which(values<=min(values)+1e-12)[1];chosen<-grid[[best]];ev<-measure(d,p,test,chosen,cost)\n  for(j in seq_along(grid)){t<-grid[[j]];m<-candidates[[j]];cell<-setNames(lapply(c(\"TP\",\"FP\",\"FN\",\"TN\"),function(k)fmt(m[[k]])),paste0(c(\"TP\",\"FP\",\"FN\",\"TN\"),\"Exact\"));add(\"validation-candidates\",c(tagrow(kind,scenario=name,candidate=j-1,selected=as.integer(j==best),policy=if(is.character(t))t else\"threshold\",thresholdExact=\"\",thresholdApprox=if(is.character(t))\"\"else fmt(t),feasible=1,reasons=\"\"),cell,scalars(m,c(counts,\"TPR\",\"FPR\",\"precision\",\"meanCost\",\"totalCost\"))));point(kind,\"validation-cost\",name,j-1,j-1,m$meanCost,\"candidate index\",\"hypothetical cost units/mass\",\"validation\",if(is.character(t))t else fmt(t))}\n  m<-c(ev,cv[c(\"ROC_AUC\",\"averagePrecision\",\"PRTrapezoidWithInitialPrecisionOne\")],cal[c(\"ECE\",\"reliability\",\"resolution\",\"uncertainty\",\"withinBinCorrection\",\"BrierIdentityResidual\")])\n  for(k in c(\"TP\",\"FP\",\"FN\",\"TN\",counts,rates,\"ROC_AUC\",\"averagePrecision\",\"PRTrapezoidWithInitialPrecisionOne\",\"ECE\",\"reliability\",\"resolution\",\"uncertainty\",\"withinBinCorrection\",\"BrierIdentityResidual\")){\n   unit<-if(k%in%c(\"TP\",\"FP\",\"FN\",\"TN\",counts))\"rows\"else if(k==\"totalCost\")\"hypothetical cost units\"else if(k==\"meanCost\")\"hypothetical cost units/mass\"else if(k==\"BrierSum\")\"sum squared-probability loss\"else\"dimensionless\"\n   add(\"test-metrics\",tagrow(kind,scenario=name,metric=k,valueExact=\"\",valueApprox=fmt(m[[k]]),unit=unit))\n  }\n  lev<-unique(d$group[test][!is.na(d$group[test])]);sets<-c(list(test),lapply(lev,function(g)test[!is.na(d$group[test])&d$group[test]==g]),list(test[is.na(d$group[test])]))\n  types<-c(\"overall\",rep(\"known\",length(lev)),\"unknown\");tokens<-c(\"all\",lev,\"\")\n  for(j in seq_along(sets)){ids<-sets[[j]];m<-measure(d,p,ids,chosen,cost);cell<-setNames(lapply(c(\"TP\",\"FP\",\"FN\",\"TN\"),function(k)fmt(m[[k]])),paste0(c(\"TP\",\"FP\",\"FN\",\"TN\"),\"Exact\"));add(\"group-metrics\",c(tagrow(kind,scenario=name,groupType=types[j],groupToken=tokens[j],retainedRows=length(ids)),cell,scalars(m,c(counts,rates))));if(types[j]==\"known\")point(kind,\"group-TPR\",name,j-2,j-2,m$TPR,\"declared group position\",\"TPR\",tag=tokens[j])}\n }\n invisible(NULL)\n}\n\n# Fixed finite inputs only; not the complete web input/budget validator.\nqnum<-function(v){if(is.null(v))return(NA_real_);if(is.logical(v))return(as.numeric(v));s<-as.character(v);if(grepl(\"/\",s,fixed=TRUE)){a<-strsplit(s,\"/\",fixed=TRUE)[[1]];return(as.numeric(a[1])/as.numeric(a[2]))};as.numeric(s)}\nrowsG<-function(raw){\n n<-length(raw);get<-function(r,k,default=NULL)if(is.null(r[[k]]))default else r[[k]]\n id<-vapply(raw,function(r)as.character(r$id),character(1));p<-vapply(raw,function(r)qnum(r$score),numeric(1));y<-vapply(raw,function(r)qnum(r$y),numeric(1));w<-vapply(raw,function(r)qnum(get(r,\"weight\",\"1\")),numeric(1));role<-vapply(raw,function(r)get(r,\"role\",\"evaluation\"),character(1));group<-vapply(raw,function(r)as.character(get(r,\"group\",NA_character_)),character(1))\n stopifnot(all(w>=0),all(is.na(p)|(p>=0&p<=1)),all(is.na(y)|y%in%c(0,1)),!anyDuplicated(id));list(id=id,p=p,y=y,w=w,role=role,group=group,eligible=!is.na(p)&!is.na(y)&w>0&role!=\"excluded\")\n}\nscopeG<-function(d,role=\"all\")if(role==\"all\")seq_along(d$id)else which(d$role==role)\nmetricsG<-function(d,ids,t=.5,cost=c(1,1)){\n use<-ids[d$eligible[ids]];p<-d$p[use];y<-d$y[use];w<-d$w[use];a<-if(is.character(t))rep(t==\"always-positive\",length(use))else p>=t\n TP<-sum(w[a&y==1]);FP<-sum(w[a&y==0]);FN<-sum(w[!a&y==1]);TN<-sum(w[!a&y==0]);P<-TP+FN;N<-FP+TN;W<-P+N;PP<-TP+FP;PN<-TN+FN;TPR<-ratio(TP,P);TNR<-ratio(TN,N);bs<-sum(w*(p-y)^2);tc<-FP*cost[1]+FN*cost[2]\n list(confusion=list(TP=TP,FP=FP,FN=FN,TN=TN),mass=W,positiveTargetMass=P,negativeTargetMass=N,predictedPositiveMass=PP,predictedNegativeMass=PN,prevalence=ratio(P,W),selectionRate=ratio(PP,W),accuracy=ratio(TP+TN,W),precision=ratio(TP,PP),negativePredictiveValue=ratio(TN,PN),TPR=TPR,FPR=ratio(FP,N),TNR=TNR,FNR=ratio(FN,P),F1=ratio(2*TP,2*TP+FP+FN),balancedAccuracy=if(is.na(TPR)||is.na(TNR))NA_real_ else(TPR+TNR)/2,Brier=ratio(bs,W),BrierSum=bs,totalCost=tc,meanCost=ratio(tc,W),bayesThreshold=ratio(cost[1],sum(cost)))\n}\ncurvesG<-function(d,ids){\n use<-ids[d$eligible[ids]];grid<-c(list(\"always-negative\"),as.list(sort(unique(d$p[use]),decreasing=TRUE)));points<-lapply(grid,function(t){m<-metricsG(d,ids,t);c(list(policy=t),m$confusion,m[c(\"TPR\",\"FPR\",\"precision\")],list(recall=m$TPR))});pos<-use[d$y[use]==1];neg<-use[d$y[use]==0];P<-sum(d$w[pos]);N<-sum(d$w[neg]);U<-0\n for(i in pos)U<-U+d$w[i]*sum(d$w[neg]*((d$p[i]>d$p[neg])+.5*(d$p[i]==d$p[neg])))\n AP<-trap<-lastR<-0;lastP<-1\n if(P&&length(grid)>1)for(j in 2:length(grid)){z<-points[[j]];AP<-AP+(z$recall-lastR)*z$precision;trap<-trap+(z$recall-lastR)*(z$precision+lastP)/2;lastR<-z$recall;lastP<-z$precision}\n list(points=points,ROC_AUC=ratio(U,P*N),averagePrecision=if(P)AP else NA_real_,PRTrapezoidWithInitialPrecisionOne=if(P)trap else NA_real_)\n}\nchooseG<-function(d,a,cost){\n role<-if(is.null(a$selectionRole))\"validation\"else a$selectionRole;er<-if(is.null(a$evaluationRole))\"test\"else a$evaluationRole;ids<-scopeG(d,role);use<-ids[d$eligible[ids]];stopifnot(length(use)>0);grid<-if(is.null(a$thresholds))c(list(\"always-negative\"),as.list(sort(unique(d$p[use]),decreasing=TRUE)))else lapply(a$thresholds,function(t)if(t%in%c(\"always-negative\",\"always-positive\"))t else qnum(t))\n candidates<-lapply(seq_along(grid),function(j){m<-metricsG(d,ids,grid[[j]],cost);feasible<-TRUE;if(!is.null(a$minTPR))feasible<-feasible&&!is.na(m$TPR)&&m$TPR>=qnum(a$minTPR);if(!is.null(a$maxFPR))feasible<-feasible&&!is.na(m$FPR)&&m$FPR<=qnum(a$maxFPR);list(index=j-1,policy=grid[[j]],metrics=m,feasible=feasible)})\n good<-which(vapply(candidates,function(c)c$feasible,logical(1)));best<-NA_integer_;if(length(good)){v<-vapply(candidates[good],function(c)c$metrics$meanCost,numeric(1));best<-good[which(v<=min(v)+1e-12)[1]]}\n list(selectedIndex=if(is.na(best))NA_integer_ else best-1,selectedPolicy=if(is.na(best))NULL else grid[[best]],selectedValidation=if(is.na(best))NULL else candidates[[best]]$metrics,candidates=candidates,evaluation=if(is.na(best)||er==\"none\")NULL else metricsG(d,scopeG(d,er),grid[[best]],cost))\n}\ncalibrateG<-function(d,ids,edges){\n use<-ids[d$eligible[ids]];W<-sum(d$w[use]);pi<-ratio(sum(d$w[use]*d$y[use]),W);bins<-list();ECE<-rel<-res<-correction<-0;assign<-findInterval(d$p[use],edges,rightmost.closed=TRUE,all.inside=TRUE)\n for(b in seq_len(length(edges)-1)){rr<-use[assign==b];w<-sum(d$w[rr]);mp<-ratio(sum(d$w[rr]*d$p[rr]),w);o<-ratio(sum(d$w[rr]*d$y[rr]),w);variance<-if(w)sum(d$w[rr]*(d$p[rr]-mp)^2)/w else NA_real_;covariance<-if(w)sum(d$w[rr]*(d$p[rr]-mp)*(d$y[rr]-o))/w else NA_real_;bc<-variance-2*covariance;gap<-mp-o;bins[[b]]<-list(index=b-1,mass=w,meanPrediction=mp,eventRate=o,scoreVariance=variance,scoreTargetCovariance=covariance,withinBinCorrection=bc,ids=d$id[rr])\n  if(w){s<-w/W;ECE<-ECE+s*abs(gap);rel<-rel+s*gap^2;res<-res+s*(o-pi)^2;correction<-correction+s*bc}\n };bs<-ratio(sum(d$w[use]*(d$p[use]-d$y[use])^2),W);unc<-pi*(1-pi);list(bins=bins,Brier=bs,ECE=if(W)ECE else NA_real_,uncertainty=unc,reliability=if(W)rel else NA_real_,resolution=if(W)res else NA_real_,withinBinCorrection=if(W)correction else NA_real_,BrierIdentityResidual=bs-(unc-res+rel+correction))\n}\ngroupsG<-function(d,ids,t,cost){\n lev<-unique(d$group[ids][!is.na(d$group[ids])]);groups<-lapply(lev,function(g)list(group=g,metrics=metricsG(d,ids[!is.na(d$group[ids])&d$group[ids]==g],t,cost)));overall<-metricsG(d,ids,t,cost);unknown<-metricsG(d,ids[is.na(d$group[ids])],t,cost);gaps<-list()\n for(k in c(\"prevalence\",\"selectionRate\",\"TPR\",\"FPR\",\"precision\",\"accuracy\",\"meanCost\")){use<-Filter(function(g)g$metrics$mass>0,groups);v<-vapply(use,function(g)g$metrics[[k]],numeric(1));gaps[[k]]<-if(length(use)<2||anyNA(v))NA_real_ else max(v)-min(v)}\n list(overall=overall,groups=groups,unknownGroup=unknown,gaps=gaps,partitionMassResidual=overall$mass-unknown$mass-sum(vapply(groups,function(g)g$metrics$mass,numeric(1))))\n}\nsvgFixed<-function(file,points,title,xlabel,ylabel,legend){\n finite<-points[points$y!=\"undefined\"&points$x!=\"undefined\",,drop=FALSE];x<-as.numeric(finite$x);y<-as.numeric(finite$y);xmin<-if(length(x))min(x)else 0;xmax<-if(length(x))max(x)else 1;ymin<-min(c(0,y));ymax<-max(c(0,y));if(xmin==xmax){xmin<-xmin-.5;xmax<-xmax+.5};if(ymin==ymax)ymax<-ymin+1;X<-function(v)85+(v-xmin)/(xmax-xmin)*480;Y<-function(v)278-(v-ymin)/(ymax-ymin)*175\n esc<-function(s){s<-gsub(\"&\",\"&amp;\",s,fixed=TRUE);s<-gsub(\"<\",\"&lt;\",s,fixed=TRUE);gsub(\">\",\"&gt;\",s,fixed=TRUE)};s<-'<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"620\" height=\"360\" viewBox=\"0 0 620 360\"><rect width=\"620\" height=\"360\" fill=\"white\"/><g font-family=\"Arial, sans-serif\" font-size=\"13\" fill=\"#17324d\">'\n lines<-strwrap(title,width=65);for(i in seq_along(lines))s<-paste0(s,'<text x=\"25\" y=\"',24+(i-1)*18,'\">',esc(lines[i]),'</text>');colors<-c(\"#176b9b\",\"#b85e18\",\"#437e4d\")\n for(i in seq_along(legend))s<-paste0(s,'<circle cx=\"',30+(i-1)*250,'\" cy=\"76\" r=\"4\" fill=\"',colors[(i-1)%%3+1],'\"/><text x=\"',42+(i-1)*250,'\" y=\"80\">',esc(legend[i]),'</text>')\n s<-paste0(s,'<path d=\"M85 98V278H575\" fill=\"none\" stroke=\"#52677d\"/><text text-anchor=\"middle\" x=\"325\" y=\"338\">',esc(xlabel),'</text><text text-anchor=\"middle\" transform=\"translate(21,190) rotate(-90)\">',esc(ylabel),'</text>')\n for(i in 0:4){xx<-xmin+(xmax-xmin)*i/4;yy<-ymin+(ymax-ymin)*i/4;s<-paste0(s,'<text text-anchor=\"middle\" x=\"',sprintf(\"%.9g\",X(xx)),'\" y=\"305\">',sprintf(\"%.4g\",xx),'</text><text text-anchor=\"end\" x=\"77\" y=\"',sprintf(\"%.9g\",Y(yy)+4),'\">',sprintf(\"%.4g\",yy),'</text>')}\n for(i in seq_len(nrow(finite)))s<-paste0(s,'<circle cx=\"',sprintf(\"%.9g\",X(x[i])),'\" cy=\"',sprintf(\"%.9g\",Y(y[i])),'\" r=\"3\" fill=\"',colors[as.integer(finite$series[i])%%3+1],'\"/>');writeLines(paste0(s,'</g></svg>'),file,useBytes=TRUE)\n}\nfixedRun<-function(){\n api<-FIXED$api;a<-FIXED$args;summary<-list();points<-list();xlabel<-\"Declared index\";ylabel<-\"Value\";legend<-\"Declared result\"\n metric<-function(name,v,unit=\"dimensionless\"){if(is.null(v))v<-NA_real_;summary[[length(summary)+1L]]<<-data.frame(metric=name,value=if(is.na(v))\"undefined\"else sprintf(\"%.9g\",v),exactValue=\"\",unit=unit,defined=as.integer(!is.na(v)),stringsAsFactors=FALSE)}\n pt<-function(i,x,y,id=\"\",series=0){points[[length(points)+1L]]<<-data.frame(series=series,index=i,xExact=\"\",x=if(is.na(x))\"undefined\"else sprintf(\"%.9g\",x),yExact=\"\",y=if(is.na(y))\"undefined\"else sprintf(\"%.9g\",y),id=as.character(id),stringsAsFactors=FALSE)}\n if(api==\"realdata\"){\n  native<-loadData()[[a$kind]];fit<-fitmodel(native);d<-list(id=native$id,p=fit$pred,y=native$y,w=rep(1,length(native$id)),role=native$role,group=native$group,eligible=native$eligible);scenarios<-list()\n  for(j in 1:3){name<-c(\"equal\",\"miss-five\",\"alarm-five\")[j];cst<-list(c(1,1),c(1,5),c(5,1))[[j]];sel<-chooseG(d,list(),cst);scenarios[[j]]<-list(name=name,selection=sel);metric(paste0(name,\"Threshold\"),sel$selectedPolicy);metric(paste0(name,\"TestCost\"),sel$evaluation$meanCost,\"hypothetical cost units/mass\")}\n  ids<-scopeG(d,\"test\");cv<-curvesG(d,ids);cal<-calibrateG(d,ids,seq(0,1,.2));metric(\"testAUC\",cv$ROC_AUC);metric(\"testAP\",cv$averagePrecision);metric(\"testBrier\",cal$Brier);metric(\"eligibleRows\",sum(d$eligible),\"rows\")\n  for(j in seq_along(ids)){i<-ids[j];pt(j-1,j,d$p[i],d$id[i],0);pt(j-1,j,d$y[i],d$id[i],1)}\n  full<-list(kind=a$kind,fit=fit,scenarios=scenarios,testCurves=cv,testCalibration=cal,rowsScored=d);xlabel<-\"Test row, native order\";ylabel<-\"Y or probability\";legend<-c(\"Training-fitted probability\",\"Observed Y\")\n }else{\n  d<-rowsG(a$rows);role<-if(is.null(a$role))\"all\"else a$role;ids<-scopeG(d,role);cost<-if(is.null(a$costs))c(1,1)else c(qnum(a$costs$falsePositive),qnum(a$costs$falseNegative));t<-if(is.null(a$threshold)).5 else if(a$threshold%in%c(\"always-positive\",\"always-negative\"))a$threshold else qnum(a$threshold)\n  if(api==\"metrics\"){\n   full<-metricsG(d,ids,t,cost);for(k in c(\"mass\",\"accuracy\",\"precision\",\"TPR\",\"FPR\",\"F1\",\"Brier\",\"meanCost\"))metric(k,full[[k]],if(k==\"mass\")\"mass\"else if(k==\"meanCost\")\"hypothetical cost units/mass\"else\"dimensionless\");metric(\"BayesThreshold\",full$bayesThreshold)\n   for(i in 1:4)pt(i-1,i-1,full$confusion[[i]],names(full$confusion)[i]);xlabel<-\"TP / FP / FN / TN positions\";ylabel<-\"Analytical mass\"\n  }else if(api==\"curves\"){\n   full<-curvesG(d,ids);for(k in c(\"ROC_AUC\",\"averagePrecision\",\"PRTrapezoidWithInitialPrecisionOne\"))metric(k,full[[k]])\n   for(j in seq_along(full$points)){p<-full$points[[j]];pt(j-1,p$FPR,p$TPR,if(is.character(p$policy))p$policy else sprintf(\"%.17g\",p$policy))};xlabel<-\"False positive rate\";ylabel<-\"True positive rate\";legend<-\"Observed ROC operating points\"\n  }else if(api==\"choose\"){\n   full<-chooseG(d,a,cost);metric(\"selectedIndex\",full$selectedIndex,\"candidate index\");metric(\"minimumCost\",if(is.null(full$selectedValidation))NULL else full$selectedValidation$meanCost,\"hypothetical cost units/mass\");metric(\"feasible\",as.integer(!is.na(full$selectedIndex)),\"indicator\")\n   for(c in full$candidates)pt(c$index,c$index,c$metrics$meanCost,if(is.character(c$policy))c$policy else sprintf(\"%.17g\",c$policy));xlabel<-\"Validation candidate\";ylabel<-\"Assumed cost / mass\";legend<-\"Validation candidate costs\"\n  }else if(api==\"calibrate\"){\n   edges<-if(is.null(a$binEdges))seq(0,1,.2)else vapply(a$binEdges,qnum,numeric(1));full<-calibrateG(d,ids,edges);for(k in c(\"ECE\",\"Brier\",\"uncertainty\",\"resolution\",\"reliability\",\"withinBinCorrection\",\"BrierIdentityResidual\"))metric(k,full[[k]])\n   for(b in full$bins)pt(b$index,b$meanPrediction,b$eventRate,paste0(\"bin:\",b$index));xlabel<-\"Bin mean forecast\";ylabel<-\"Bin event rate\";legend<-\"Binary-event reliability\"\n  }else if(api==\"groups\"){\n   full<-groupsG(d,ids,t,cost);metric(\"overallTPR\",full$overall$TPR);metric(\"TPRGap\",full$gaps$TPR);metric(\"precisionGap\",full$gaps$precision);metric(\"unknownMass\",full$unknownGroup$mass,\"mass\");metric(\"partitionResidual\",full$partitionMassResidual,\"mass\")\n   for(j in seq_along(full$groups))pt(j-1,j-1,full$groups[[j]]$metrics$TPR,full$groups[[j]]$group);xlabel<-\"Declared group position\";ylabel<-\"True positive rate\";legend<-\"Known-group TPR\"\n  }else stop(\"unknown declared fixed API\")\n }\n sm<-do.call(rbind,summary);pp<-do.call(rbind,points);write.csv(sm,file.path(outDir,\"summary.csv\"),row.names=FALSE,na=\"\");write.csv(pp,file.path(outDir,\"plot-points.csv\"),row.names=FALSE,na=\"\");svgFixed(file.path(outDir,\"plot.svg\"),pp,FIXED$title,xlabel,ylabel,legend);dput(list(api=api,variant=FIXED$variant,input=FIXED$args,arithmetic=\"Base-R binary64 fixed example; not an exact rational general validator\",result=full),file=file.path(outDir,\"full.txt\"));cat(\"PASS\",api,FIXED$variant,\"summary\",nrow(sm),\"points\",nrow(pp),\"\\n\")\n}\n\nFIXED<-list(api=\"choose\",variant=\"miss-five\",args=list(rows=list(list(id=\"a\",score=\".9\",y=1,group=\"A\",role=\"validation\"),list(id=\"b\",score=\".8\",y=1,group=\"A\",role=\"validation\"),list(id=\"c\",score=\".8\",y=0,group=\"A\",role=\"validation\"),list(id=\"d\",score=\".6\",y=0,group=\"B\",role=\"validation\"),list(id=\"e\",score=\".4\",y=1,group=\"B\",role=\"validation\"),list(id=\"f\",score=\".1\",y=0,group=\"B\",role=\"validation\")),costs=list(falsePositive=\"1\",falseNegative=\"5\"),evaluationRole=\"none\"),title=\"Validation-only threshold with missed-case cost five\")\nfixedRun()\n",
        "codeText": "# ML14 standalone public counterpart, base R only.\n# Inputs are only the three factual CSVs; derived columns/previous model answers unused.\n# Binary64 arithmetic, not arbitrary-precision Fraction. At numerical cost ties\n# within 1e-12 retain the earliest candidate. Exact claims belong to Python/web.\n# SHA256 infrastructure below is reused verbatim from the previous public study.\nargs<-commandArgs(trailingOnly=TRUE);filearg<-grep(\"^--file=\",commandArgs(),value=TRUE)\nhere<-if(dir.exists(\"ml14-sources\"))getwd()else if(length(filearg))dirname(normalizePath(sub(\"^--file=\",\"\",filearg[1])))else getwd()\noption<-function(key,default){i<-match(key,args);if(is.na(i))default else args[i+1]}\nsourceDir<-option(\"--source\",file.path(here,\"ml14-sources\"));outDir<-option(\"--out\",file.path(getwd(),\"ml14-r-results\"));dir.create(outDir,recursive=TRUE,showWarnings=FALSE)\nnum<-function(x){x[x%in%c(\"\",\".\")]<-NA_character_;as.numeric(x)}\nfmt<-function(x)ifelse(is.na(x),\"\",sprintf(\"%.17g\",x))\nratio<-function(a,b)if(b==0)NA_real_ else a/b\nreadnative<-function(name)read.csv(file.path(sourceDir,name),check.names=FALSE,colClasses=\"character\",na.strings=character(),stringsAsFactors=FALSE)\n# Vectorized SHA256 for the short ASCII keys used in this study.\n# Unsigned words use exact integer-valued doubles; bit operations use safe\n# 16-bit halves, avoiding R's reserved signed-INT_MIN/NA representation.\nMOD<-2^32\nxor32<-function(a,b) as.double(bitwXor(as.integer(floor(a/65536)),as.integer(floor(b/65536))))*65536+as.double(bitwXor(as.integer(a%%65536),as.integer(b%%65536)))\nand32<-function(a,b) as.double(bitwAnd(as.integer(floor(a/65536)),as.integer(floor(b/65536))))*65536+as.double(bitwAnd(as.integer(a%%65536),as.integer(b%%65536)))\nrot<-function(x,n) floor(x/2^n)+(x%%2^n)*2^(32-n)\nxor3<-function(a,b,c) xor32(xor32(a,b),c)\nK<-c(0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5,0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967,0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070,0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3,0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2)\nsha256<-function(strings) {\n n<-length(strings);bytes<-matrix(0,n,64)\n for(i in seq_len(n)) {v<-utf8ToInt(strings[i]);stopifnot(length(v)<56,all(v<128));if(length(v)) bytes[i,seq_along(v)]<-v;bytes[i,length(v)+1]<-128;bits<-length(v)*8;bytes[i,61:64]<-c(floor(bits/2^24)%%256,floor(bits/2^16)%%256,floor(bits/256)%%256,bits%%256)}\n w<-matrix(0,n,64)\n for(j in 1:16) {b<-4*(j-1)+1;w[,j]<-bytes[,b]*2^24+bytes[,b+1]*2^16+bytes[,b+2]*256+bytes[,b+3]}\n for(j in 17:64) {s0<-xor3(rot(w[,j-15],7),rot(w[,j-15],18),floor(w[,j-15]/8));s1<-xor3(rot(w[,j-2],17),rot(w[,j-2],19),floor(w[,j-2]/1024));w[,j]<-(w[,j-16]+s0+w[,j-7]+s1)%%MOD}\n init<-c(0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19)\n state<-lapply(init,function(v) rep(v,n));a<-state[[1]];b<-state[[2]];c<-state[[3]];d<-state[[4]];e<-state[[5]];f<-state[[6]];g<-state[[7]];h<-state[[8]]\n for(j in 1:64) {S1<-xor3(rot(e,6),rot(e,11),rot(e,25));ch<-xor32(and32(e,f),and32(MOD-1-e,g));t1<-(h+S1+ch+K[j]+w[,j])%%MOD;S0<-xor3(rot(a,2),rot(a,13),rot(a,22));maj<-xor3(and32(a,b),and32(a,c),and32(b,c));t2<-(S0+maj)%%MOD;h<-g;g<-f;f<-e;e<-(d+t1)%%MOD;d<-c;c<-b;b<-a;a<-(t1+t2)%%MOD}\n end<-list(a,b,c,d,e,f,g,h);hex<-lapply(1:8,function(j){v<-(end[[j]]+init[j])%%MOD;paste0(sprintf(\"%04x\",as.integer(floor(v/65536))),sprintf(\"%04x\",as.integer(v%%65536)))})\n do.call(paste0,hex)\n}\nstopifnot(identical(sha256(c(\"abc\",\"\")),c(\"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad\",\"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855\")))\n\nloadData<-function(){\n wb<-readnative(\"actual64-country-four-indicators-original-2024.csv\");codes<-c(\"NY.GDP.PCAP.KD\",\"NY.GDP.MKTP.KD.ZG\",\"FP.CPI.TOTL.ZG\",\"SP.DYN.LE00.IN\");iso<-sort(unique(wb$countryISO3));stopifnot(nrow(wb)==64,length(iso)==16)\n tokens<-t(vapply(iso,function(s)wb$originalValueToken[match(paste(s,codes),paste(wb$countryISO3,wb$indicatorID))],character(4)));vals<-matrix(num(as.vector(tokens)),nrow=nrow(tokens))\n country<-list(id=paste0(iso,\":2024\"),sourceRow=1:16,originalID=iso,x=vals[,1:3,drop=FALSE],rawX=tokens[,1:3,drop=FALSE],nativeTarget=tokens[,4],y=as.integer(vals[,4]>=80),group=ifelse(is.na(vals[,1]),NA_character_,as.character(as.integer(vals[,1]>=25000))),lineage=vapply(iso,function(s)paste(wb$sourceRow[match(paste(s,codes),paste(wb$countryISO3,wb$indicatorID))],collapse=\";\"),character(1)),cat=integer(),units=c(\"constant2015USD/person\",\"annualPercent\",\"annualPercent\"))\n nls<-readnative(\"actual3613-NLS-original52-fields-groups-roles.csv\");raw<-cbind(nls$ed76,nls$age76,nls$nearc4)\n person<-list(id=paste0(\"person:\",nls$sourceRow),sourceRow=as.integer(nls$sourceRow),originalID=nls$id,x=matrix(num(as.vector(raw)),nrow=nrow(raw)),rawX=raw,nativeTarget=nls$wage76,y=as.integer(num(nls$wage76)>=500),group=ifelse(nls$black%in%c(\"\",\".\"),NA_character_,nls$black),lineage=nls$sourceRow,cat=2L,units=c(\"years\",\"years\",\"nativeCategory\"))\n ch<-readnative(\"actual3150-churn-original14-fields-groups-roles.csv\");raw<-cbind(ch[[\"Call  Failure\"]],ch$Complains,ch[[\"Subscription  Length\"]],ch[[\"Seconds of Use\"]])\n company<-list(id=paste0(\"customer:\",ch$sourceRow),sourceRow=as.integer(ch$sourceRow),originalID=rep(\"\",nrow(ch)),x=matrix(num(as.vector(raw)),nrow=nrow(raw)),rawX=raw,nativeTarget=ch$Churn,y=as.integer(ch$Churn),group=ifelse(ch[[\"Tariff Plan\"]]%in%c(\"\",\".\"),NA_character_,ch[[\"Tariff Plan\"]]),lineage=ch$sourceRow,cat=1L,units=c(\"count\",\"nativeCategory\",\"months\",\"seconds\"))\n stopifnot(nrow(nls)==3613,nrow(ch)==3150,identical(as.integer(ch$sourceRow[ch[[\"Charge  Amount\"]]==\"10\"]),c(474L,2174L,2274L,2374L,2674L,2924L,2974L)))\n result<-list(country=country,person=person,company=company)\n for(k in names(result)){d<-result[[k]];n<-length(d$id);d$eligible<-!is.na(d$y)&rowSums(is.na(d$x))==0;hash<-sha256(paste0(\"ML14-role|\",k,\"|\",d$id));rank<-integer(n);rank[order(hash,seq_len(n))]<-seq_len(n)-1L;d$plannedRole<-ifelse(rank%%5==0,\"test\",ifelse(rank%%5==1,\"validation\",\"train\"));d$role<-ifelse(d$eligible,d$plannedRole,\"excluded\");result[[k]]<-d}\n stopifnot(sum(result$person$eligible)==3017);result\n}\nfitmodel<-function(d){\n ids<-which(d$role==\"train\");p<-ncol(d$x);m<-vapply(seq_len(p),function(j)if((j-1)%in%d$cat)NA_real_ else median(d$x[ids,j]),numeric(1));z<-d$x\n for(j in seq_len(p))if(!((j-1)%in%d$cat))z[,j]<-as.numeric(z[,j]>m[j])\n keys<-apply(z,1,function(v)paste(fmt(v),collapse=\"|\"));lev<-unique(keys[ids]);mass<-vapply(lev,function(k)sum(keys[ids]==k),integer(1));positive<-vapply(lev,function(k)sum(d$y[ids][keys[ids]==k]),integer(1));prob<-(positive+1)/(mass+2);fallback<-(sum(d$y[ids])+1)/(length(ids)+2);pred<-prob[match(keys,lev)];unseen<-is.na(pred);pred[unseen]<-fallback;pred[!d$eligible]<-NA_real_;unseen[!d$eligible]<-NA\n list(ids=ids,medians=m,z=z,keys=keys,lev=lev,mass=mass,positive=positive,prob=prob,fallback=fallback,pred=pred,unseen=unseen)\n}\nmeasure<-function(d,p,ids,t=.5,cost=c(1,1)){\n use<-ids[d$eligible[ids]&!is.na(p[ids])];y<-d$y[use];a<-if(is.character(t))rep(t==\"always-positive\",length(use))else p[use]>=t\n TP<-sum(a&y==1);FP<-sum(a&y==0);FN<-sum(!a&y==1);TN<-sum(!a&y==0);P<-TP+FN;N<-FP+TN;W<-P+N;PP<-TP+FP;PN<-TN+FN;TPR<-ratio(TP,P);TNR<-ratio(TN,N);bs<-sum((p[use]-y)^2);tc<-FP*cost[1]+FN*cost[2]\n list(TP=TP,FP=FP,FN=FN,TN=TN,mass=W,positiveTargetMass=P,negativeTargetMass=N,predictedPositiveMass=PP,predictedNegativeMass=PN,prevalence=ratio(P,W),selectionRate=ratio(PP,W),accuracy=ratio(TP+TN,W),precision=ratio(TP,PP),negativePredictiveValue=ratio(TN,PN),TPR=TPR,FPR=ratio(FP,N),TNR=TNR,FNR=ratio(FN,P),F1=ratio(2*TP,2*TP+FP+FN),balancedAccuracy=if(is.na(TPR)||is.na(TNR))NA_real_ else(TPR+TNR)/2,Brier=ratio(bs,W),BrierSum=bs,totalCost=tc,meanCost=ratio(tc,W))\n}\ncurves<-function(d,p,ids){\n use<-ids[d$eligible[ids]&!is.na(p[ids])];scores<-sort(unique(p[use]),decreasing=TRUE);policies<-c(list(\"always-negative\"),as.list(scores));points<-lapply(policies,function(t){m<-measure(d,p,ids,t);c(list(policy=t),m[c(\"TP\",\"FP\",\"FN\",\"TN\",\"TPR\",\"FPR\",\"precision\")],list(recall=m$TPR))})\n pos<-use[d$y[use]==1];neg<-use[d$y[use]==0];U<-0;for(i in pos)U<-U+sum(p[i]>p[neg])+.5*sum(p[i]==p[neg])\n AP<-0;trap<-0;lastR<-0;lastP<-1\n if(length(pos)&&length(scores))for(j in seq_along(scores)){z<-points[[j+1]];AP<-AP+(z$recall-lastR)*z$precision;trap<-trap+(z$recall-lastR)*(z$precision+lastP)/2;lastR<-z$recall;lastP<-z$precision}\n list(points=points,ROC_AUC=ratio(U,length(pos)*length(neg)),averagePrecision=if(length(pos))AP else NA_real_,PRTrapezoidWithInitialPrecisionOne=if(length(pos))trap else NA_real_)\n}\ncalibrate<-function(d,p,ids){\n use<-ids[d$eligible[ids]&!is.na(p[ids])];W<-length(use);pi<-if(W)mean(d$y[use])else NA_real_;bins<-list();ECE<-rel<-res<-correction<-0\n whichbin<-findInterval(p[use],seq(0,1,.2),rightmost.closed=TRUE,all.inside=TRUE)\n for(b in 1:5){rr<-use[whichbin==b];w<-length(rr);mp<-if(w)mean(p[rr])else NA_real_;o<-if(w)mean(d$y[rr])else NA_real_;variance<-if(w)mean((p[rr]-mp)^2)else NA_real_;covariance<-if(w)mean((p[rr]-mp)*(d$y[rr]-o))else NA_real_;bc<-variance-2*covariance;gap<-mp-o\n  bins[[b]]<-list(mass=w,meanPrediction=mp,eventRate=o,gap=gap,absoluteGap=abs(gap),scoreVariance=variance,scoreTargetCovariance=covariance,withinBinCorrection=bc,rows=w,ids=d$id[rr])\n  if(w){share<-w/W;ECE<-ECE+share*abs(gap);rel<-rel+share*gap^2;res<-res+share*(o-pi)^2;correction<-correction+share*bc}\n };bs<-if(W)mean((p[use]-d$y[use])^2)else NA_real_;unc<-pi*(1-pi)\n list(bins=bins,ECE=if(W)ECE else NA_real_,Brier=bs,reliability=if(W)rel else NA_real_,resolution=if(W)res else NA_real_,uncertainty=unc,withinBinCorrection=if(W)correction else NA_real_,BrierIdentityResidual=bs-(unc-res+rel+correction))\n}\ncounts<-c(\"mass\",\"positiveTargetMass\",\"negativeTargetMass\",\"predictedPositiveMass\",\"predictedNegativeMass\");rates<-c(\"prevalence\",\"selectionRate\",\"accuracy\",\"precision\",\"negativePredictiveValue\",\"TPR\",\"FPR\",\"TNR\",\"FNR\",\"F1\",\"balancedAccuracy\",\"Brier\",\"BrierSum\",\"totalCost\",\"meanCost\")\ntables<-setNames(lapply(1:10,function(i)list()),c(\"predictions\",\"lineage\",\"fit-medians\",\"fit-cells\",\"validation-candidates\",\"test-metrics\",\"test-curves\",\"calibration-bins\",\"group-metrics\",\"chart-points\"))\nadd<-function(name,row)tables[[name]][[length(tables[[name]])+1L]]<<-row\nscalars<-function(m,keys){out<-list();for(k in keys){out[[paste0(k,\"Exact\")]]<-\"\";out[[paste0(k,\"Approx\")]]<-fmt(m[[k]])};out}\ntagrow<-function(kind,...)c(list(kind=kind),list(...))\npoint<-function(kind,chart,series,index,x,y,xunit=\"dimensionless\",yunit=\"dimensionless\",role=\"test\",tag=\"\"){add(\"chart-points\",tagrow(kind,chart=chart,series=series,index=index,xExact=\"\",xApprox=fmt(x),yExact=\"\",yApprox=fmt(y),xUnit=xunit,yUnit=yunit,role=role,tag=tag))}\nstudy<-function(kind,d){\n f<-fitmodel(d);n<-length(d$id);train<-which(d$role==\"train\");validation<-which(d$role==\"validation\");test<-which(d$role==\"test\");p<-f$pred;cv<-curves(d,p,test);cal<-calibrate(d,p,test)\n for(i in seq_len(n)){\n  reason<-if(d$eligible[i])\"\"else\"required-X-or-Y-missing\";transformed<-if(d$eligible[i])paste(fmt(f$z[i,]),collapse=\"|\")else\"\"\n  add(\"predictions\",tagrow(kind,id=d$id[i],sourceRow=d$sourceRow[i],originalID=d$originalID[i],plannedRole=d$plannedRole[i],role=d$role[i],group=ifelse(is.na(d$group[i]),\"\",d$group[i]),eligible=as.integer(d$eligible[i]),targetExact=fmt(d$y[i]),probabilityExact=\"\",probabilityApprox=fmt(p[i]),unseenCell=ifelse(is.na(f$unseen[i]),\"\",as.character(as.integer(f$unseen[i]))),transformedX=transformed,reason=reason))\n  raw<-d$rawX[i,];raw[raw%in%c(\"\",\".\")]<-\"\";nativeY<-d$nativeTarget[i];if(nativeY%in%c(\"\",\".\"))nativeY<-\"\"\n  add(\"lineage\",tagrow(kind,id=d$id[i],sourceRow=d$sourceRow[i],originalID=d$originalID[i],nativeSourceRows=d$lineage[i],rawX=paste(raw,collapse=\"|\"),nativeTarget=nativeY,derivedTarget=fmt(d$y[i]),nativeGroup=ifelse(is.na(d$group[i]),\"\",d$group[i]),plannedRole=d$plannedRole[i],role=d$role[i],eligible=as.integer(d$eligible[i]),analyticalMass=\"1\",reason=reason))\n }\n for(j in seq_len(ncol(d$x)))add(\"fit-medians\",tagrow(kind,feature=j-1,categorical=as.integer((j-1)%in%d$cat),fitRows=length(train),medianExact=\"\",medianApprox=fmt(f$medians[j]),unit=d$units[j]))\n for(j in seq_along(f$lev))add(\"fit-cells\",tagrow(kind,cell=f$lev[j],trainingRows=f$mass[j],positiveRows=f$positive[j],probabilityExact=\"\",probabilityApprox=fmt(f$prob[j]),fallbackExact=\"\",fallbackApprox=fmt(f$fallback)))\n for(j in seq_along(cv$points)){\n  z<-cv$points[[j]];t<-z$policy;add(\"test-curves\",c(tagrow(kind,point=j-1,policy=if(is.character(t))t else\"threshold\",thresholdExact=\"\",thresholdApprox=if(is.character(t))\"\"else fmt(t)),scalars(z,c(\"TP\",\"FP\",\"FN\",\"TN\",\"TPR\",\"FPR\",\"precision\",\"recall\"))))\n  point(kind,\"roc\",\"ROC\",j-1,z$FPR,z$TPR);point(kind,\"pr\",\"PR-observed\",j-1,z$recall,z$precision)\n }\n for(b in 1:5){z<-cal$bins[[b]];add(\"calibration-bins\",c(tagrow(kind,bin=b-1,leftExact=c(\"0\",\"1/5\",\"2/5\",\"3/5\",\"4/5\")[b],rightExact=c(\"1/5\",\"2/5\",\"3/5\",\"4/5\",\"1\")[b],rightClosed=as.integer(b==5),rows=z$rows,ids=paste(z$ids,collapse=\";\")),scalars(z,c(\"mass\",\"meanPrediction\",\"eventRate\",\"gap\",\"absoluteGap\",\"scoreVariance\",\"scoreTargetCovariance\",\"withinBinCorrection\"))));point(kind,\"reliability\",\"Binary event rate\",b-1,z$meanPrediction,z$eventRate,tag=paste0(\"rows=\",z$rows))}\n for(j in seq_along(test)){i<-test[j];point(kind,\"test-scores\",\"Training-fitted probability\",j-1,j,p[i],\"test-row position\",\"probability\",tag=d$id[i]);point(kind,\"test-scores\",\"Observed Y\",j-1,j,d$y[i],\"test-row position\",\"binary target\",tag=d$id[i])}\n scenarioNames<-c(\"equal\",\"miss-five\",\"alarm-five\");costs<-list(c(1,1),c(1,5),c(5,1))\n for(s in 1:3){name<-scenarioNames[s];cost<-costs[[s]];grid<-c(list(\"always-negative\"),as.list(sort(unique(p[validation]),decreasing=TRUE)));candidates<-lapply(grid,function(t)measure(d,p,validation,t,cost));values<-vapply(candidates,function(m)m$meanCost,numeric(1));best<-which(values<=min(values)+1e-12)[1];chosen<-grid[[best]];ev<-measure(d,p,test,chosen,cost)\n  for(j in seq_along(grid)){t<-grid[[j]];m<-candidates[[j]];cell<-setNames(lapply(c(\"TP\",\"FP\",\"FN\",\"TN\"),function(k)fmt(m[[k]])),paste0(c(\"TP\",\"FP\",\"FN\",\"TN\"),\"Exact\"));add(\"validation-candidates\",c(tagrow(kind,scenario=name,candidate=j-1,selected=as.integer(j==best),policy=if(is.character(t))t else\"threshold\",thresholdExact=\"\",thresholdApprox=if(is.character(t))\"\"else fmt(t),feasible=1,reasons=\"\"),cell,scalars(m,c(counts,\"TPR\",\"FPR\",\"precision\",\"meanCost\",\"totalCost\"))));point(kind,\"validation-cost\",name,j-1,j-1,m$meanCost,\"candidate index\",\"hypothetical cost units/mass\",\"validation\",if(is.character(t))t else fmt(t))}\n  m<-c(ev,cv[c(\"ROC_AUC\",\"averagePrecision\",\"PRTrapezoidWithInitialPrecisionOne\")],cal[c(\"ECE\",\"reliability\",\"resolution\",\"uncertainty\",\"withinBinCorrection\",\"BrierIdentityResidual\")])\n  for(k in c(\"TP\",\"FP\",\"FN\",\"TN\",counts,rates,\"ROC_AUC\",\"averagePrecision\",\"PRTrapezoidWithInitialPrecisionOne\",\"ECE\",\"reliability\",\"resolution\",\"uncertainty\",\"withinBinCorrection\",\"BrierIdentityResidual\")){\n   unit<-if(k%in%c(\"TP\",\"FP\",\"FN\",\"TN\",counts))\"rows\"else if(k==\"totalCost\")\"hypothetical cost units\"else if(k==\"meanCost\")\"hypothetical cost units/mass\"else if(k==\"BrierSum\")\"sum squared-probability loss\"else\"dimensionless\"\n   add(\"test-metrics\",tagrow(kind,scenario=name,metric=k,valueExact=\"\",valueApprox=fmt(m[[k]]),unit=unit))\n  }\n  lev<-unique(d$group[test][!is.na(d$group[test])]);sets<-c(list(test),lapply(lev,function(g)test[!is.na(d$group[test])&d$group[test]==g]),list(test[is.na(d$group[test])]))\n  types<-c(\"overall\",rep(\"known\",length(lev)),\"unknown\");tokens<-c(\"all\",lev,\"\")\n  for(j in seq_along(sets)){ids<-sets[[j]];m<-measure(d,p,ids,chosen,cost);cell<-setNames(lapply(c(\"TP\",\"FP\",\"FN\",\"TN\"),function(k)fmt(m[[k]])),paste0(c(\"TP\",\"FP\",\"FN\",\"TN\"),\"Exact\"));add(\"group-metrics\",c(tagrow(kind,scenario=name,groupType=types[j],groupToken=tokens[j],retainedRows=length(ids)),cell,scalars(m,c(counts,rates))));if(types[j]==\"known\")point(kind,\"group-TPR\",name,j-2,j-2,m$TPR,\"declared group position\",\"TPR\",tag=tokens[j])}\n }\n invisible(NULL)\n}\n\n# Fixed finite inputs only; not the complete web input/budget validator.\nqnum<-function(v){if(is.null(v))return(NA_real_);if(is.logical(v))return(as.numeric(v));s<-as.character(v);if(grepl(\"/\",s,fixed=TRUE)){a<-strsplit(s,\"/\",fixed=TRUE)[[1]];return(as.numeric(a[1])/as.numeric(a[2]))};as.numeric(s)}\nrowsG<-function(raw){\n n<-length(raw);get<-function(r,k,default=NULL)if(is.null(r[[k]]))default else r[[k]]\n id<-vapply(raw,function(r)as.character(r$id),character(1));p<-vapply(raw,function(r)qnum(r$score),numeric(1));y<-vapply(raw,function(r)qnum(r$y),numeric(1));w<-vapply(raw,function(r)qnum(get(r,\"weight\",\"1\")),numeric(1));role<-vapply(raw,function(r)get(r,\"role\",\"evaluation\"),character(1));group<-vapply(raw,function(r)as.character(get(r,\"group\",NA_character_)),character(1))\n stopifnot(all(w>=0),all(is.na(p)|(p>=0&p<=1)),all(is.na(y)|y%in%c(0,1)),!anyDuplicated(id));list(id=id,p=p,y=y,w=w,role=role,group=group,eligible=!is.na(p)&!is.na(y)&w>0&role!=\"excluded\")\n}\nscopeG<-function(d,role=\"all\")if(role==\"all\")seq_along(d$id)else which(d$role==role)\nmetricsG<-function(d,ids,t=.5,cost=c(1,1)){\n use<-ids[d$eligible[ids]];p<-d$p[use];y<-d$y[use];w<-d$w[use];a<-if(is.character(t))rep(t==\"always-positive\",length(use))else p>=t\n TP<-sum(w[a&y==1]);FP<-sum(w[a&y==0]);FN<-sum(w[!a&y==1]);TN<-sum(w[!a&y==0]);P<-TP+FN;N<-FP+TN;W<-P+N;PP<-TP+FP;PN<-TN+FN;TPR<-ratio(TP,P);TNR<-ratio(TN,N);bs<-sum(w*(p-y)^2);tc<-FP*cost[1]+FN*cost[2]\n list(confusion=list(TP=TP,FP=FP,FN=FN,TN=TN),mass=W,positiveTargetMass=P,negativeTargetMass=N,predictedPositiveMass=PP,predictedNegativeMass=PN,prevalence=ratio(P,W),selectionRate=ratio(PP,W),accuracy=ratio(TP+TN,W),precision=ratio(TP,PP),negativePredictiveValue=ratio(TN,PN),TPR=TPR,FPR=ratio(FP,N),TNR=TNR,FNR=ratio(FN,P),F1=ratio(2*TP,2*TP+FP+FN),balancedAccuracy=if(is.na(TPR)||is.na(TNR))NA_real_ else(TPR+TNR)/2,Brier=ratio(bs,W),BrierSum=bs,totalCost=tc,meanCost=ratio(tc,W),bayesThreshold=ratio(cost[1],sum(cost)))\n}\ncurvesG<-function(d,ids){\n use<-ids[d$eligible[ids]];grid<-c(list(\"always-negative\"),as.list(sort(unique(d$p[use]),decreasing=TRUE)));points<-lapply(grid,function(t){m<-metricsG(d,ids,t);c(list(policy=t),m$confusion,m[c(\"TPR\",\"FPR\",\"precision\")],list(recall=m$TPR))});pos<-use[d$y[use]==1];neg<-use[d$y[use]==0];P<-sum(d$w[pos]);N<-sum(d$w[neg]);U<-0\n for(i in pos)U<-U+d$w[i]*sum(d$w[neg]*((d$p[i]>d$p[neg])+.5*(d$p[i]==d$p[neg])))\n AP<-trap<-lastR<-0;lastP<-1\n if(P&&length(grid)>1)for(j in 2:length(grid)){z<-points[[j]];AP<-AP+(z$recall-lastR)*z$precision;trap<-trap+(z$recall-lastR)*(z$precision+lastP)/2;lastR<-z$recall;lastP<-z$precision}\n list(points=points,ROC_AUC=ratio(U,P*N),averagePrecision=if(P)AP else NA_real_,PRTrapezoidWithInitialPrecisionOne=if(P)trap else NA_real_)\n}\nchooseG<-function(d,a,cost){\n role<-if(is.null(a$selectionRole))\"validation\"else a$selectionRole;er<-if(is.null(a$evaluationRole))\"test\"else a$evaluationRole;ids<-scopeG(d,role);use<-ids[d$eligible[ids]];stopifnot(length(use)>0);grid<-if(is.null(a$thresholds))c(list(\"always-negative\"),as.list(sort(unique(d$p[use]),decreasing=TRUE)))else lapply(a$thresholds,function(t)if(t%in%c(\"always-negative\",\"always-positive\"))t else qnum(t))\n candidates<-lapply(seq_along(grid),function(j){m<-metricsG(d,ids,grid[[j]],cost);feasible<-TRUE;if(!is.null(a$minTPR))feasible<-feasible&&!is.na(m$TPR)&&m$TPR>=qnum(a$minTPR);if(!is.null(a$maxFPR))feasible<-feasible&&!is.na(m$FPR)&&m$FPR<=qnum(a$maxFPR);list(index=j-1,policy=grid[[j]],metrics=m,feasible=feasible)})\n good<-which(vapply(candidates,function(c)c$feasible,logical(1)));best<-NA_integer_;if(length(good)){v<-vapply(candidates[good],function(c)c$metrics$meanCost,numeric(1));best<-good[which(v<=min(v)+1e-12)[1]]}\n list(selectedIndex=if(is.na(best))NA_integer_ else best-1,selectedPolicy=if(is.na(best))NULL else grid[[best]],selectedValidation=if(is.na(best))NULL else candidates[[best]]$metrics,candidates=candidates,evaluation=if(is.na(best)||er==\"none\")NULL else metricsG(d,scopeG(d,er),grid[[best]],cost))\n}\ncalibrateG<-function(d,ids,edges){\n use<-ids[d$eligible[ids]];W<-sum(d$w[use]);pi<-ratio(sum(d$w[use]*d$y[use]),W);bins<-list();ECE<-rel<-res<-correction<-0;assign<-findInterval(d$p[use],edges,rightmost.closed=TRUE,all.inside=TRUE)\n for(b in seq_len(length(edges)-1)){rr<-use[assign==b];w<-sum(d$w[rr]);mp<-ratio(sum(d$w[rr]*d$p[rr]),w);o<-ratio(sum(d$w[rr]*d$y[rr]),w);variance<-if(w)sum(d$w[rr]*(d$p[rr]-mp)^2)/w else NA_real_;covariance<-if(w)sum(d$w[rr]*(d$p[rr]-mp)*(d$y[rr]-o))/w else NA_real_;bc<-variance-2*covariance;gap<-mp-o;bins[[b]]<-list(index=b-1,mass=w,meanPrediction=mp,eventRate=o,scoreVariance=variance,scoreTargetCovariance=covariance,withinBinCorrection=bc,ids=d$id[rr])\n  if(w){s<-w/W;ECE<-ECE+s*abs(gap);rel<-rel+s*gap^2;res<-res+s*(o-pi)^2;correction<-correction+s*bc}\n };bs<-ratio(sum(d$w[use]*(d$p[use]-d$y[use])^2),W);unc<-pi*(1-pi);list(bins=bins,Brier=bs,ECE=if(W)ECE else NA_real_,uncertainty=unc,reliability=if(W)rel else NA_real_,resolution=if(W)res else NA_real_,withinBinCorrection=if(W)correction else NA_real_,BrierIdentityResidual=bs-(unc-res+rel+correction))\n}\ngroupsG<-function(d,ids,t,cost){\n lev<-unique(d$group[ids][!is.na(d$group[ids])]);groups<-lapply(lev,function(g)list(group=g,metrics=metricsG(d,ids[!is.na(d$group[ids])&d$group[ids]==g],t,cost)));overall<-metricsG(d,ids,t,cost);unknown<-metricsG(d,ids[is.na(d$group[ids])],t,cost);gaps<-list()\n for(k in c(\"prevalence\",\"selectionRate\",\"TPR\",\"FPR\",\"precision\",\"accuracy\",\"meanCost\")){use<-Filter(function(g)g$metrics$mass>0,groups);v<-vapply(use,function(g)g$metrics[[k]],numeric(1));gaps[[k]]<-if(length(use)<2||anyNA(v))NA_real_ else max(v)-min(v)}\n list(overall=overall,groups=groups,unknownGroup=unknown,gaps=gaps,partitionMassResidual=overall$mass-unknown$mass-sum(vapply(groups,function(g)g$metrics$mass,numeric(1))))\n}\nsvgFixed<-function(file,points,title,xlabel,ylabel,legend){\n finite<-points[points$y!=\"undefined\"&points$x!=\"undefined\",,drop=FALSE];x<-as.numeric(finite$x);y<-as.numeric(finite$y);xmin<-if(length(x))min(x)else 0;xmax<-if(length(x))max(x)else 1;ymin<-min(c(0,y));ymax<-max(c(0,y));if(xmin==xmax){xmin<-xmin-.5;xmax<-xmax+.5};if(ymin==ymax)ymax<-ymin+1;X<-function(v)85+(v-xmin)/(xmax-xmin)*480;Y<-function(v)278-(v-ymin)/(ymax-ymin)*175\n esc<-function(s){s<-gsub(\"&\",\"&amp;\",s,fixed=TRUE);s<-gsub(\"<\",\"&lt;\",s,fixed=TRUE);gsub(\">\",\"&gt;\",s,fixed=TRUE)};s<-'<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"620\" height=\"360\" viewBox=\"0 0 620 360\"><rect width=\"620\" height=\"360\" fill=\"white\"/><g font-family=\"Arial, sans-serif\" font-size=\"13\" fill=\"#17324d\">'\n lines<-strwrap(title,width=65);for(i in seq_along(lines))s<-paste0(s,'<text x=\"25\" y=\"',24+(i-1)*18,'\">',esc(lines[i]),'</text>');colors<-c(\"#176b9b\",\"#b85e18\",\"#437e4d\")\n for(i in seq_along(legend))s<-paste0(s,'<circle cx=\"',30+(i-1)*250,'\" cy=\"76\" r=\"4\" fill=\"',colors[(i-1)%%3+1],'\"/><text x=\"',42+(i-1)*250,'\" y=\"80\">',esc(legend[i]),'</text>')\n s<-paste0(s,'<path d=\"M85 98V278H575\" fill=\"none\" stroke=\"#52677d\"/><text text-anchor=\"middle\" x=\"325\" y=\"338\">',esc(xlabel),'</text><text text-anchor=\"middle\" transform=\"translate(21,190) rotate(-90)\">',esc(ylabel),'</text>')\n for(i in 0:4){xx<-xmin+(xmax-xmin)*i/4;yy<-ymin+(ymax-ymin)*i/4;s<-paste0(s,'<text text-anchor=\"middle\" x=\"',sprintf(\"%.9g\",X(xx)),'\" y=\"305\">',sprintf(\"%.4g\",xx),'</text><text text-anchor=\"end\" x=\"77\" y=\"',sprintf(\"%.9g\",Y(yy)+4),'\">',sprintf(\"%.4g\",yy),'</text>')}\n for(i in seq_len(nrow(finite)))s<-paste0(s,'<circle cx=\"',sprintf(\"%.9g\",X(x[i])),'\" cy=\"',sprintf(\"%.9g\",Y(y[i])),'\" r=\"3\" fill=\"',colors[as.integer(finite$series[i])%%3+1],'\"/>');writeLines(paste0(s,'</g></svg>'),file,useBytes=TRUE)\n}\nfixedRun<-function(){\n api<-FIXED$api;a<-FIXED$args;summary<-list();points<-list();xlabel<-\"Declared index\";ylabel<-\"Value\";legend<-\"Declared result\"\n metric<-function(name,v,unit=\"dimensionless\"){if(is.null(v))v<-NA_real_;summary[[length(summary)+1L]]<<-data.frame(metric=name,value=if(is.na(v))\"undefined\"else sprintf(\"%.9g\",v),exactValue=\"\",unit=unit,defined=as.integer(!is.na(v)),stringsAsFactors=FALSE)}\n pt<-function(i,x,y,id=\"\",series=0){points[[length(points)+1L]]<<-data.frame(series=series,index=i,xExact=\"\",x=if(is.na(x))\"undefined\"else sprintf(\"%.9g\",x),yExact=\"\",y=if(is.na(y))\"undefined\"else sprintf(\"%.9g\",y),id=as.character(id),stringsAsFactors=FALSE)}\n if(api==\"realdata\"){\n  native<-loadData()[[a$kind]];fit<-fitmodel(native);d<-list(id=native$id,p=fit$pred,y=native$y,w=rep(1,length(native$id)),role=native$role,group=native$group,eligible=native$eligible);scenarios<-list()\n  for(j in 1:3){name<-c(\"equal\",\"miss-five\",\"alarm-five\")[j];cst<-list(c(1,1),c(1,5),c(5,1))[[j]];sel<-chooseG(d,list(),cst);scenarios[[j]]<-list(name=name,selection=sel);metric(paste0(name,\"Threshold\"),sel$selectedPolicy);metric(paste0(name,\"TestCost\"),sel$evaluation$meanCost,\"hypothetical cost units/mass\")}\n  ids<-scopeG(d,\"test\");cv<-curvesG(d,ids);cal<-calibrateG(d,ids,seq(0,1,.2));metric(\"testAUC\",cv$ROC_AUC);metric(\"testAP\",cv$averagePrecision);metric(\"testBrier\",cal$Brier);metric(\"eligibleRows\",sum(d$eligible),\"rows\")\n  for(j in seq_along(ids)){i<-ids[j];pt(j-1,j,d$p[i],d$id[i],0);pt(j-1,j,d$y[i],d$id[i],1)}\n  full<-list(kind=a$kind,fit=fit,scenarios=scenarios,testCurves=cv,testCalibration=cal,rowsScored=d);xlabel<-\"Test row, native order\";ylabel<-\"Y or probability\";legend<-c(\"Training-fitted probability\",\"Observed Y\")\n }else{\n  d<-rowsG(a$rows);role<-if(is.null(a$role))\"all\"else a$role;ids<-scopeG(d,role);cost<-if(is.null(a$costs))c(1,1)else c(qnum(a$costs$falsePositive),qnum(a$costs$falseNegative));t<-if(is.null(a$threshold)).5 else if(a$threshold%in%c(\"always-positive\",\"always-negative\"))a$threshold else qnum(a$threshold)\n  if(api==\"metrics\"){\n   full<-metricsG(d,ids,t,cost);for(k in c(\"mass\",\"accuracy\",\"precision\",\"TPR\",\"FPR\",\"F1\",\"Brier\",\"meanCost\"))metric(k,full[[k]],if(k==\"mass\")\"mass\"else if(k==\"meanCost\")\"hypothetical cost units/mass\"else\"dimensionless\");metric(\"BayesThreshold\",full$bayesThreshold)\n   for(i in 1:4)pt(i-1,i-1,full$confusion[[i]],names(full$confusion)[i]);xlabel<-\"TP / FP / FN / TN positions\";ylabel<-\"Analytical mass\"\n  }else if(api==\"curves\"){\n   full<-curvesG(d,ids);for(k in c(\"ROC_AUC\",\"averagePrecision\",\"PRTrapezoidWithInitialPrecisionOne\"))metric(k,full[[k]])\n   for(j in seq_along(full$points)){p<-full$points[[j]];pt(j-1,p$FPR,p$TPR,if(is.character(p$policy))p$policy else sprintf(\"%.17g\",p$policy))};xlabel<-\"False positive rate\";ylabel<-\"True positive rate\";legend<-\"Observed ROC operating points\"\n  }else if(api==\"choose\"){\n   full<-chooseG(d,a,cost);metric(\"selectedIndex\",full$selectedIndex,\"candidate index\");metric(\"minimumCost\",if(is.null(full$selectedValidation))NULL else full$selectedValidation$meanCost,\"hypothetical cost units/mass\");metric(\"feasible\",as.integer(!is.na(full$selectedIndex)),\"indicator\")\n   for(c in full$candidates)pt(c$index,c$index,c$metrics$meanCost,if(is.character(c$policy))c$policy else sprintf(\"%.17g\",c$policy));xlabel<-\"Validation candidate\";ylabel<-\"Assumed cost / mass\";legend<-\"Validation candidate costs\"\n  }else if(api==\"calibrate\"){\n   edges<-if(is.null(a$binEdges))seq(0,1,.2)else vapply(a$binEdges,qnum,numeric(1));full<-calibrateG(d,ids,edges);for(k in c(\"ECE\",\"Brier\",\"uncertainty\",\"resolution\",\"reliability\",\"withinBinCorrection\",\"BrierIdentityResidual\"))metric(k,full[[k]])\n   for(b in full$bins)pt(b$index,b$meanPrediction,b$eventRate,paste0(\"bin:\",b$index));xlabel<-\"Bin mean forecast\";ylabel<-\"Bin event rate\";legend<-\"Binary-event reliability\"\n  }else if(api==\"groups\"){\n   full<-groupsG(d,ids,t,cost);metric(\"overallTPR\",full$overall$TPR);metric(\"TPRGap\",full$gaps$TPR);metric(\"precisionGap\",full$gaps$precision);metric(\"unknownMass\",full$unknownGroup$mass,\"mass\");metric(\"partitionResidual\",full$partitionMassResidual,\"mass\")\n   for(j in seq_along(full$groups))pt(j-1,j-1,full$groups[[j]]$metrics$TPR,full$groups[[j]]$group);xlabel<-\"Declared group position\";ylabel<-\"True positive rate\";legend<-\"Known-group TPR\"\n  }else stop(\"unknown declared fixed API\")\n }\n sm<-do.call(rbind,summary);pp<-do.call(rbind,points);write.csv(sm,file.path(outDir,\"summary.csv\"),row.names=FALSE,na=\"\");write.csv(pp,file.path(outDir,\"plot-points.csv\"),row.names=FALSE,na=\"\");svgFixed(file.path(outDir,\"plot.svg\"),pp,FIXED$title,xlabel,ylabel,legend);dput(list(api=api,variant=FIXED$variant,input=FIXED$args,arithmetic=\"Base-R binary64 fixed example; not an exact rational general validator\",result=full),file=file.path(outDir,\"full.txt\"));cat(\"PASS\",api,FIXED$variant,\"summary\",nrow(sm),\"points\",nrow(pp),\"\\n\")\n}\n\nFIXED<-list(api=\"choose\",variant=\"miss-five\",args=list(rows=list(list(id=\"a\",score=\".9\",y=1,group=\"A\",role=\"validation\"),list(id=\"b\",score=\".8\",y=1,group=\"A\",role=\"validation\"),list(id=\"c\",score=\".8\",y=0,group=\"A\",role=\"validation\"),list(id=\"d\",score=\".6\",y=0,group=\"B\",role=\"validation\"),list(id=\"e\",score=\".4\",y=1,group=\"B\",role=\"validation\"),list(id=\"f\",score=\".1\",y=0,group=\"B\",role=\"validation\")),costs=list(falsePositive=\"1\",falseNegative=\"5\"),evaluationRole=\"none\"),title=\"Validation-only threshold with missed-case cost five\")\nfixedRun()\n",
        "input": {
          "rows": [
            {
              "id": "a",
              "score": ".9",
              "y": 1,
              "group": "A",
              "role": "validation"
            },
            {
              "id": "b",
              "score": ".8",
              "y": 1,
              "group": "A",
              "role": "validation"
            },
            {
              "id": "c",
              "score": ".8",
              "y": 0,
              "group": "A",
              "role": "validation"
            },
            {
              "id": "d",
              "score": ".6",
              "y": 0,
              "group": "B",
              "role": "validation"
            },
            {
              "id": "e",
              "score": ".4",
              "y": 1,
              "group": "B",
              "role": "validation"
            },
            {
              "id": "f",
              "score": ".1",
              "y": 0,
              "group": "B",
              "role": "validation"
            }
          ],
          "costs": {
            "falsePositive": "1",
            "falseNegative": "5"
          },
          "evaluationRole": "none"
        },
        "inputFiles": [],
        "returnCode": 0,
        "expectedFailure": false,
        "stdout": "PASS choose miss-five summary 3 points 6 \n",
        "stderr": "During startup - Warning messages:\n1: Setting LC_COLLATE=C.UTF-8 failed \n2: Setting LC_CTYPE=C.UTF-8 failed \n3: Setting LC_MONETARY=C.UTF-8 failed \n4: Setting LC_TIME=C.UTF-8 failed \n",
        "summary": {
          "selectedIndex": "4",
          "minimumCost": "0.333333333",
          "feasible": "1"
        },
        "summaryRows": [
          {
            "metric": "selectedIndex",
            "value": "4",
            "exactValue": "",
            "unit": "candidate index",
            "defined": "1"
          },
          {
            "metric": "minimumCost",
            "value": "0.333333333",
            "exactValue": "",
            "unit": "hypothetical cost units/mass",
            "defined": "1"
          },
          {
            "metric": "feasible",
            "value": "1",
            "exactValue": "",
            "unit": "indicator",
            "defined": "1"
          }
        ],
        "plotPoints": [
          {
            "series": "0",
            "index": "0",
            "xExact": "",
            "x": "0",
            "yExact": "",
            "y": "2.5",
            "id": "always-negative"
          },
          {
            "series": "0",
            "index": "1",
            "xExact": "",
            "x": "1",
            "yExact": "",
            "y": "1.66666667",
            "id": "0.90000000000000002"
          },
          {
            "series": "0",
            "index": "2",
            "xExact": "",
            "x": "2",
            "yExact": "",
            "y": "1",
            "id": "0.80000000000000004"
          },
          {
            "series": "0",
            "index": "3",
            "xExact": "",
            "x": "3",
            "yExact": "",
            "y": "1.16666667",
            "id": "0.59999999999999998"
          },
          {
            "series": "0",
            "index": "4",
            "xExact": "",
            "x": "4",
            "yExact": "",
            "y": "0.333333333",
            "id": "0.40000000000000002"
          },
          {
            "series": "0",
            "index": "5",
            "xExact": "",
            "x": "5",
            "yExact": "",
            "y": "0.5",
            "id": "0.10000000000000001"
          }
        ],
        "plotFile": "ml14-fixed-results/choose-miss-five-r/plot.svg",
        "plotSHA256": "0eb1836322c7f73f4c3285703cd6ee0648c14c3be8fb19be8e55a04f2755c3ef",
        "files": [
          {
            "file": "ml14-fixed-results/choose-miss-five-r/full.txt",
            "sha256": "0a209168a8292fb1f7b698773a27948c492f55d5f079e9d7570fc61430fbf2ec",
            "bytes": 6099
          },
          {
            "file": "ml14-fixed-results/choose-miss-five-r/plot-points.csv",
            "sha256": "f197a5f466eb51fadc52ba8fa035537af7c1f58d15b15e157caba6f9b92255f8",
            "bytes": 323
          },
          {
            "file": "ml14-fixed-results/choose-miss-five-r/plot.svg",
            "sha256": "0eb1836322c7f73f4c3285703cd6ee0648c14c3be8fb19be8e55a04f2755c3ef",
            "bytes": 1433
          },
          {
            "file": "ml14-fixed-results/choose-miss-five-r/summary.csv",
            "sha256": "cc503e2d3f4986fff217ac42b633a4996a100b71fc73f3ddd73627470adfe14b",
            "bytes": 190
          }
        ],
        "scope": "Actually executed standalone fixed example, Python exact Fraction versus base-R binary64. Approximate R residuals retained; not universal exact arithmetic/web validation/native UI. Source programs read factual3CSV only."
      },
      "infeasible": {
        "api": "choose",
        "variant": "infeasible",
        "language": "r",
        "title": "No threshold satisfies both declared rate constraints",
        "codeFile": "ml14-code/choose-infeasible.R",
        "codeSHA256": "420ec5983e1c95d4104f2bcd3db2eac86baf2b687f634b2efb5b2439c33f50b8",
        "code": "# ML14 standalone public counterpart, base R only.\n# Inputs are only the three factual CSVs; derived columns/previous model answers unused.\n# Binary64 arithmetic, not arbitrary-precision Fraction. At numerical cost ties\n# within 1e-12 retain the earliest candidate. Exact claims belong to Python/web.\n# SHA256 infrastructure below is reused verbatim from the previous public study.\nargs<-commandArgs(trailingOnly=TRUE);filearg<-grep(\"^--file=\",commandArgs(),value=TRUE)\nhere<-if(dir.exists(\"ml14-sources\"))getwd()else if(length(filearg))dirname(normalizePath(sub(\"^--file=\",\"\",filearg[1])))else getwd()\noption<-function(key,default){i<-match(key,args);if(is.na(i))default else args[i+1]}\nsourceDir<-option(\"--source\",file.path(here,\"ml14-sources\"));outDir<-option(\"--out\",file.path(getwd(),\"ml14-r-results\"));dir.create(outDir,recursive=TRUE,showWarnings=FALSE)\nnum<-function(x){x[x%in%c(\"\",\".\")]<-NA_character_;as.numeric(x)}\nfmt<-function(x)ifelse(is.na(x),\"\",sprintf(\"%.17g\",x))\nratio<-function(a,b)if(b==0)NA_real_ else a/b\nreadnative<-function(name)read.csv(file.path(sourceDir,name),check.names=FALSE,colClasses=\"character\",na.strings=character(),stringsAsFactors=FALSE)\n# Vectorized SHA256 for the short ASCII keys used in this study.\n# Unsigned words use exact integer-valued doubles; bit operations use safe\n# 16-bit halves, avoiding R's reserved signed-INT_MIN/NA representation.\nMOD<-2^32\nxor32<-function(a,b) as.double(bitwXor(as.integer(floor(a/65536)),as.integer(floor(b/65536))))*65536+as.double(bitwXor(as.integer(a%%65536),as.integer(b%%65536)))\nand32<-function(a,b) as.double(bitwAnd(as.integer(floor(a/65536)),as.integer(floor(b/65536))))*65536+as.double(bitwAnd(as.integer(a%%65536),as.integer(b%%65536)))\nrot<-function(x,n) floor(x/2^n)+(x%%2^n)*2^(32-n)\nxor3<-function(a,b,c) xor32(xor32(a,b),c)\nK<-c(0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5,0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967,0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070,0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3,0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2)\nsha256<-function(strings) {\n n<-length(strings);bytes<-matrix(0,n,64)\n for(i in seq_len(n)) {v<-utf8ToInt(strings[i]);stopifnot(length(v)<56,all(v<128));if(length(v)) bytes[i,seq_along(v)]<-v;bytes[i,length(v)+1]<-128;bits<-length(v)*8;bytes[i,61:64]<-c(floor(bits/2^24)%%256,floor(bits/2^16)%%256,floor(bits/256)%%256,bits%%256)}\n w<-matrix(0,n,64)\n for(j in 1:16) {b<-4*(j-1)+1;w[,j]<-bytes[,b]*2^24+bytes[,b+1]*2^16+bytes[,b+2]*256+bytes[,b+3]}\n for(j in 17:64) {s0<-xor3(rot(w[,j-15],7),rot(w[,j-15],18),floor(w[,j-15]/8));s1<-xor3(rot(w[,j-2],17),rot(w[,j-2],19),floor(w[,j-2]/1024));w[,j]<-(w[,j-16]+s0+w[,j-7]+s1)%%MOD}\n init<-c(0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19)\n state<-lapply(init,function(v) rep(v,n));a<-state[[1]];b<-state[[2]];c<-state[[3]];d<-state[[4]];e<-state[[5]];f<-state[[6]];g<-state[[7]];h<-state[[8]]\n for(j in 1:64) {S1<-xor3(rot(e,6),rot(e,11),rot(e,25));ch<-xor32(and32(e,f),and32(MOD-1-e,g));t1<-(h+S1+ch+K[j]+w[,j])%%MOD;S0<-xor3(rot(a,2),rot(a,13),rot(a,22));maj<-xor3(and32(a,b),and32(a,c),and32(b,c));t2<-(S0+maj)%%MOD;h<-g;g<-f;f<-e;e<-(d+t1)%%MOD;d<-c;c<-b;b<-a;a<-(t1+t2)%%MOD}\n end<-list(a,b,c,d,e,f,g,h);hex<-lapply(1:8,function(j){v<-(end[[j]]+init[j])%%MOD;paste0(sprintf(\"%04x\",as.integer(floor(v/65536))),sprintf(\"%04x\",as.integer(v%%65536)))})\n do.call(paste0,hex)\n}\nstopifnot(identical(sha256(c(\"abc\",\"\")),c(\"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad\",\"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855\")))\n\nloadData<-function(){\n wb<-readnative(\"actual64-country-four-indicators-original-2024.csv\");codes<-c(\"NY.GDP.PCAP.KD\",\"NY.GDP.MKTP.KD.ZG\",\"FP.CPI.TOTL.ZG\",\"SP.DYN.LE00.IN\");iso<-sort(unique(wb$countryISO3));stopifnot(nrow(wb)==64,length(iso)==16)\n tokens<-t(vapply(iso,function(s)wb$originalValueToken[match(paste(s,codes),paste(wb$countryISO3,wb$indicatorID))],character(4)));vals<-matrix(num(as.vector(tokens)),nrow=nrow(tokens))\n country<-list(id=paste0(iso,\":2024\"),sourceRow=1:16,originalID=iso,x=vals[,1:3,drop=FALSE],rawX=tokens[,1:3,drop=FALSE],nativeTarget=tokens[,4],y=as.integer(vals[,4]>=80),group=ifelse(is.na(vals[,1]),NA_character_,as.character(as.integer(vals[,1]>=25000))),lineage=vapply(iso,function(s)paste(wb$sourceRow[match(paste(s,codes),paste(wb$countryISO3,wb$indicatorID))],collapse=\";\"),character(1)),cat=integer(),units=c(\"constant2015USD/person\",\"annualPercent\",\"annualPercent\"))\n nls<-readnative(\"actual3613-NLS-original52-fields-groups-roles.csv\");raw<-cbind(nls$ed76,nls$age76,nls$nearc4)\n person<-list(id=paste0(\"person:\",nls$sourceRow),sourceRow=as.integer(nls$sourceRow),originalID=nls$id,x=matrix(num(as.vector(raw)),nrow=nrow(raw)),rawX=raw,nativeTarget=nls$wage76,y=as.integer(num(nls$wage76)>=500),group=ifelse(nls$black%in%c(\"\",\".\"),NA_character_,nls$black),lineage=nls$sourceRow,cat=2L,units=c(\"years\",\"years\",\"nativeCategory\"))\n ch<-readnative(\"actual3150-churn-original14-fields-groups-roles.csv\");raw<-cbind(ch[[\"Call  Failure\"]],ch$Complains,ch[[\"Subscription  Length\"]],ch[[\"Seconds of Use\"]])\n company<-list(id=paste0(\"customer:\",ch$sourceRow),sourceRow=as.integer(ch$sourceRow),originalID=rep(\"\",nrow(ch)),x=matrix(num(as.vector(raw)),nrow=nrow(raw)),rawX=raw,nativeTarget=ch$Churn,y=as.integer(ch$Churn),group=ifelse(ch[[\"Tariff Plan\"]]%in%c(\"\",\".\"),NA_character_,ch[[\"Tariff Plan\"]]),lineage=ch$sourceRow,cat=1L,units=c(\"count\",\"nativeCategory\",\"months\",\"seconds\"))\n stopifnot(nrow(nls)==3613,nrow(ch)==3150,identical(as.integer(ch$sourceRow[ch[[\"Charge  Amount\"]]==\"10\"]),c(474L,2174L,2274L,2374L,2674L,2924L,2974L)))\n result<-list(country=country,person=person,company=company)\n for(k in names(result)){d<-result[[k]];n<-length(d$id);d$eligible<-!is.na(d$y)&rowSums(is.na(d$x))==0;hash<-sha256(paste0(\"ML14-role|\",k,\"|\",d$id));rank<-integer(n);rank[order(hash,seq_len(n))]<-seq_len(n)-1L;d$plannedRole<-ifelse(rank%%5==0,\"test\",ifelse(rank%%5==1,\"validation\",\"train\"));d$role<-ifelse(d$eligible,d$plannedRole,\"excluded\");result[[k]]<-d}\n stopifnot(sum(result$person$eligible)==3017);result\n}\nfitmodel<-function(d){\n ids<-which(d$role==\"train\");p<-ncol(d$x);m<-vapply(seq_len(p),function(j)if((j-1)%in%d$cat)NA_real_ else median(d$x[ids,j]),numeric(1));z<-d$x\n for(j in seq_len(p))if(!((j-1)%in%d$cat))z[,j]<-as.numeric(z[,j]>m[j])\n keys<-apply(z,1,function(v)paste(fmt(v),collapse=\"|\"));lev<-unique(keys[ids]);mass<-vapply(lev,function(k)sum(keys[ids]==k),integer(1));positive<-vapply(lev,function(k)sum(d$y[ids][keys[ids]==k]),integer(1));prob<-(positive+1)/(mass+2);fallback<-(sum(d$y[ids])+1)/(length(ids)+2);pred<-prob[match(keys,lev)];unseen<-is.na(pred);pred[unseen]<-fallback;pred[!d$eligible]<-NA_real_;unseen[!d$eligible]<-NA\n list(ids=ids,medians=m,z=z,keys=keys,lev=lev,mass=mass,positive=positive,prob=prob,fallback=fallback,pred=pred,unseen=unseen)\n}\nmeasure<-function(d,p,ids,t=.5,cost=c(1,1)){\n use<-ids[d$eligible[ids]&!is.na(p[ids])];y<-d$y[use];a<-if(is.character(t))rep(t==\"always-positive\",length(use))else p[use]>=t\n TP<-sum(a&y==1);FP<-sum(a&y==0);FN<-sum(!a&y==1);TN<-sum(!a&y==0);P<-TP+FN;N<-FP+TN;W<-P+N;PP<-TP+FP;PN<-TN+FN;TPR<-ratio(TP,P);TNR<-ratio(TN,N);bs<-sum((p[use]-y)^2);tc<-FP*cost[1]+FN*cost[2]\n list(TP=TP,FP=FP,FN=FN,TN=TN,mass=W,positiveTargetMass=P,negativeTargetMass=N,predictedPositiveMass=PP,predictedNegativeMass=PN,prevalence=ratio(P,W),selectionRate=ratio(PP,W),accuracy=ratio(TP+TN,W),precision=ratio(TP,PP),negativePredictiveValue=ratio(TN,PN),TPR=TPR,FPR=ratio(FP,N),TNR=TNR,FNR=ratio(FN,P),F1=ratio(2*TP,2*TP+FP+FN),balancedAccuracy=if(is.na(TPR)||is.na(TNR))NA_real_ else(TPR+TNR)/2,Brier=ratio(bs,W),BrierSum=bs,totalCost=tc,meanCost=ratio(tc,W))\n}\ncurves<-function(d,p,ids){\n use<-ids[d$eligible[ids]&!is.na(p[ids])];scores<-sort(unique(p[use]),decreasing=TRUE);policies<-c(list(\"always-negative\"),as.list(scores));points<-lapply(policies,function(t){m<-measure(d,p,ids,t);c(list(policy=t),m[c(\"TP\",\"FP\",\"FN\",\"TN\",\"TPR\",\"FPR\",\"precision\")],list(recall=m$TPR))})\n pos<-use[d$y[use]==1];neg<-use[d$y[use]==0];U<-0;for(i in pos)U<-U+sum(p[i]>p[neg])+.5*sum(p[i]==p[neg])\n AP<-0;trap<-0;lastR<-0;lastP<-1\n if(length(pos)&&length(scores))for(j in seq_along(scores)){z<-points[[j+1]];AP<-AP+(z$recall-lastR)*z$precision;trap<-trap+(z$recall-lastR)*(z$precision+lastP)/2;lastR<-z$recall;lastP<-z$precision}\n list(points=points,ROC_AUC=ratio(U,length(pos)*length(neg)),averagePrecision=if(length(pos))AP else NA_real_,PRTrapezoidWithInitialPrecisionOne=if(length(pos))trap else NA_real_)\n}\ncalibrate<-function(d,p,ids){\n use<-ids[d$eligible[ids]&!is.na(p[ids])];W<-length(use);pi<-if(W)mean(d$y[use])else NA_real_;bins<-list();ECE<-rel<-res<-correction<-0\n whichbin<-findInterval(p[use],seq(0,1,.2),rightmost.closed=TRUE,all.inside=TRUE)\n for(b in 1:5){rr<-use[whichbin==b];w<-length(rr);mp<-if(w)mean(p[rr])else NA_real_;o<-if(w)mean(d$y[rr])else NA_real_;variance<-if(w)mean((p[rr]-mp)^2)else NA_real_;covariance<-if(w)mean((p[rr]-mp)*(d$y[rr]-o))else NA_real_;bc<-variance-2*covariance;gap<-mp-o\n  bins[[b]]<-list(mass=w,meanPrediction=mp,eventRate=o,gap=gap,absoluteGap=abs(gap),scoreVariance=variance,scoreTargetCovariance=covariance,withinBinCorrection=bc,rows=w,ids=d$id[rr])\n  if(w){share<-w/W;ECE<-ECE+share*abs(gap);rel<-rel+share*gap^2;res<-res+share*(o-pi)^2;correction<-correction+share*bc}\n };bs<-if(W)mean((p[use]-d$y[use])^2)else NA_real_;unc<-pi*(1-pi)\n list(bins=bins,ECE=if(W)ECE else NA_real_,Brier=bs,reliability=if(W)rel else NA_real_,resolution=if(W)res else NA_real_,uncertainty=unc,withinBinCorrection=if(W)correction else NA_real_,BrierIdentityResidual=bs-(unc-res+rel+correction))\n}\ncounts<-c(\"mass\",\"positiveTargetMass\",\"negativeTargetMass\",\"predictedPositiveMass\",\"predictedNegativeMass\");rates<-c(\"prevalence\",\"selectionRate\",\"accuracy\",\"precision\",\"negativePredictiveValue\",\"TPR\",\"FPR\",\"TNR\",\"FNR\",\"F1\",\"balancedAccuracy\",\"Brier\",\"BrierSum\",\"totalCost\",\"meanCost\")\ntables<-setNames(lapply(1:10,function(i)list()),c(\"predictions\",\"lineage\",\"fit-medians\",\"fit-cells\",\"validation-candidates\",\"test-metrics\",\"test-curves\",\"calibration-bins\",\"group-metrics\",\"chart-points\"))\nadd<-function(name,row)tables[[name]][[length(tables[[name]])+1L]]<<-row\nscalars<-function(m,keys){out<-list();for(k in keys){out[[paste0(k,\"Exact\")]]<-\"\";out[[paste0(k,\"Approx\")]]<-fmt(m[[k]])};out}\ntagrow<-function(kind,...)c(list(kind=kind),list(...))\npoint<-function(kind,chart,series,index,x,y,xunit=\"dimensionless\",yunit=\"dimensionless\",role=\"test\",tag=\"\"){add(\"chart-points\",tagrow(kind,chart=chart,series=series,index=index,xExact=\"\",xApprox=fmt(x),yExact=\"\",yApprox=fmt(y),xUnit=xunit,yUnit=yunit,role=role,tag=tag))}\nstudy<-function(kind,d){\n f<-fitmodel(d);n<-length(d$id);train<-which(d$role==\"train\");validation<-which(d$role==\"validation\");test<-which(d$role==\"test\");p<-f$pred;cv<-curves(d,p,test);cal<-calibrate(d,p,test)\n for(i in seq_len(n)){\n  reason<-if(d$eligible[i])\"\"else\"required-X-or-Y-missing\";transformed<-if(d$eligible[i])paste(fmt(f$z[i,]),collapse=\"|\")else\"\"\n  add(\"predictions\",tagrow(kind,id=d$id[i],sourceRow=d$sourceRow[i],originalID=d$originalID[i],plannedRole=d$plannedRole[i],role=d$role[i],group=ifelse(is.na(d$group[i]),\"\",d$group[i]),eligible=as.integer(d$eligible[i]),targetExact=fmt(d$y[i]),probabilityExact=\"\",probabilityApprox=fmt(p[i]),unseenCell=ifelse(is.na(f$unseen[i]),\"\",as.character(as.integer(f$unseen[i]))),transformedX=transformed,reason=reason))\n  raw<-d$rawX[i,];raw[raw%in%c(\"\",\".\")]<-\"\";nativeY<-d$nativeTarget[i];if(nativeY%in%c(\"\",\".\"))nativeY<-\"\"\n  add(\"lineage\",tagrow(kind,id=d$id[i],sourceRow=d$sourceRow[i],originalID=d$originalID[i],nativeSourceRows=d$lineage[i],rawX=paste(raw,collapse=\"|\"),nativeTarget=nativeY,derivedTarget=fmt(d$y[i]),nativeGroup=ifelse(is.na(d$group[i]),\"\",d$group[i]),plannedRole=d$plannedRole[i],role=d$role[i],eligible=as.integer(d$eligible[i]),analyticalMass=\"1\",reason=reason))\n }\n for(j in seq_len(ncol(d$x)))add(\"fit-medians\",tagrow(kind,feature=j-1,categorical=as.integer((j-1)%in%d$cat),fitRows=length(train),medianExact=\"\",medianApprox=fmt(f$medians[j]),unit=d$units[j]))\n for(j in seq_along(f$lev))add(\"fit-cells\",tagrow(kind,cell=f$lev[j],trainingRows=f$mass[j],positiveRows=f$positive[j],probabilityExact=\"\",probabilityApprox=fmt(f$prob[j]),fallbackExact=\"\",fallbackApprox=fmt(f$fallback)))\n for(j in seq_along(cv$points)){\n  z<-cv$points[[j]];t<-z$policy;add(\"test-curves\",c(tagrow(kind,point=j-1,policy=if(is.character(t))t else\"threshold\",thresholdExact=\"\",thresholdApprox=if(is.character(t))\"\"else fmt(t)),scalars(z,c(\"TP\",\"FP\",\"FN\",\"TN\",\"TPR\",\"FPR\",\"precision\",\"recall\"))))\n  point(kind,\"roc\",\"ROC\",j-1,z$FPR,z$TPR);point(kind,\"pr\",\"PR-observed\",j-1,z$recall,z$precision)\n }\n for(b in 1:5){z<-cal$bins[[b]];add(\"calibration-bins\",c(tagrow(kind,bin=b-1,leftExact=c(\"0\",\"1/5\",\"2/5\",\"3/5\",\"4/5\")[b],rightExact=c(\"1/5\",\"2/5\",\"3/5\",\"4/5\",\"1\")[b],rightClosed=as.integer(b==5),rows=z$rows,ids=paste(z$ids,collapse=\";\")),scalars(z,c(\"mass\",\"meanPrediction\",\"eventRate\",\"gap\",\"absoluteGap\",\"scoreVariance\",\"scoreTargetCovariance\",\"withinBinCorrection\"))));point(kind,\"reliability\",\"Binary event rate\",b-1,z$meanPrediction,z$eventRate,tag=paste0(\"rows=\",z$rows))}\n for(j in seq_along(test)){i<-test[j];point(kind,\"test-scores\",\"Training-fitted probability\",j-1,j,p[i],\"test-row position\",\"probability\",tag=d$id[i]);point(kind,\"test-scores\",\"Observed Y\",j-1,j,d$y[i],\"test-row position\",\"binary target\",tag=d$id[i])}\n scenarioNames<-c(\"equal\",\"miss-five\",\"alarm-five\");costs<-list(c(1,1),c(1,5),c(5,1))\n for(s in 1:3){name<-scenarioNames[s];cost<-costs[[s]];grid<-c(list(\"always-negative\"),as.list(sort(unique(p[validation]),decreasing=TRUE)));candidates<-lapply(grid,function(t)measure(d,p,validation,t,cost));values<-vapply(candidates,function(m)m$meanCost,numeric(1));best<-which(values<=min(values)+1e-12)[1];chosen<-grid[[best]];ev<-measure(d,p,test,chosen,cost)\n  for(j in seq_along(grid)){t<-grid[[j]];m<-candidates[[j]];cell<-setNames(lapply(c(\"TP\",\"FP\",\"FN\",\"TN\"),function(k)fmt(m[[k]])),paste0(c(\"TP\",\"FP\",\"FN\",\"TN\"),\"Exact\"));add(\"validation-candidates\",c(tagrow(kind,scenario=name,candidate=j-1,selected=as.integer(j==best),policy=if(is.character(t))t else\"threshold\",thresholdExact=\"\",thresholdApprox=if(is.character(t))\"\"else fmt(t),feasible=1,reasons=\"\"),cell,scalars(m,c(counts,\"TPR\",\"FPR\",\"precision\",\"meanCost\",\"totalCost\"))));point(kind,\"validation-cost\",name,j-1,j-1,m$meanCost,\"candidate index\",\"hypothetical cost units/mass\",\"validation\",if(is.character(t))t else fmt(t))}\n  m<-c(ev,cv[c(\"ROC_AUC\",\"averagePrecision\",\"PRTrapezoidWithInitialPrecisionOne\")],cal[c(\"ECE\",\"reliability\",\"resolution\",\"uncertainty\",\"withinBinCorrection\",\"BrierIdentityResidual\")])\n  for(k in c(\"TP\",\"FP\",\"FN\",\"TN\",counts,rates,\"ROC_AUC\",\"averagePrecision\",\"PRTrapezoidWithInitialPrecisionOne\",\"ECE\",\"reliability\",\"resolution\",\"uncertainty\",\"withinBinCorrection\",\"BrierIdentityResidual\")){\n   unit<-if(k%in%c(\"TP\",\"FP\",\"FN\",\"TN\",counts))\"rows\"else if(k==\"totalCost\")\"hypothetical cost units\"else if(k==\"meanCost\")\"hypothetical cost units/mass\"else if(k==\"BrierSum\")\"sum squared-probability loss\"else\"dimensionless\"\n   add(\"test-metrics\",tagrow(kind,scenario=name,metric=k,valueExact=\"\",valueApprox=fmt(m[[k]]),unit=unit))\n  }\n  lev<-unique(d$group[test][!is.na(d$group[test])]);sets<-c(list(test),lapply(lev,function(g)test[!is.na(d$group[test])&d$group[test]==g]),list(test[is.na(d$group[test])]))\n  types<-c(\"overall\",rep(\"known\",length(lev)),\"unknown\");tokens<-c(\"all\",lev,\"\")\n  for(j in seq_along(sets)){ids<-sets[[j]];m<-measure(d,p,ids,chosen,cost);cell<-setNames(lapply(c(\"TP\",\"FP\",\"FN\",\"TN\"),function(k)fmt(m[[k]])),paste0(c(\"TP\",\"FP\",\"FN\",\"TN\"),\"Exact\"));add(\"group-metrics\",c(tagrow(kind,scenario=name,groupType=types[j],groupToken=tokens[j],retainedRows=length(ids)),cell,scalars(m,c(counts,rates))));if(types[j]==\"known\")point(kind,\"group-TPR\",name,j-2,j-2,m$TPR,\"declared group position\",\"TPR\",tag=tokens[j])}\n }\n invisible(NULL)\n}\n\n# Fixed finite inputs only; not the complete web input/budget validator.\nqnum<-function(v){if(is.null(v))return(NA_real_);if(is.logical(v))return(as.numeric(v));s<-as.character(v);if(grepl(\"/\",s,fixed=TRUE)){a<-strsplit(s,\"/\",fixed=TRUE)[[1]];return(as.numeric(a[1])/as.numeric(a[2]))};as.numeric(s)}\nrowsG<-function(raw){\n n<-length(raw);get<-function(r,k,default=NULL)if(is.null(r[[k]]))default else r[[k]]\n id<-vapply(raw,function(r)as.character(r$id),character(1));p<-vapply(raw,function(r)qnum(r$score),numeric(1));y<-vapply(raw,function(r)qnum(r$y),numeric(1));w<-vapply(raw,function(r)qnum(get(r,\"weight\",\"1\")),numeric(1));role<-vapply(raw,function(r)get(r,\"role\",\"evaluation\"),character(1));group<-vapply(raw,function(r)as.character(get(r,\"group\",NA_character_)),character(1))\n stopifnot(all(w>=0),all(is.na(p)|(p>=0&p<=1)),all(is.na(y)|y%in%c(0,1)),!anyDuplicated(id));list(id=id,p=p,y=y,w=w,role=role,group=group,eligible=!is.na(p)&!is.na(y)&w>0&role!=\"excluded\")\n}\nscopeG<-function(d,role=\"all\")if(role==\"all\")seq_along(d$id)else which(d$role==role)\nmetricsG<-function(d,ids,t=.5,cost=c(1,1)){\n use<-ids[d$eligible[ids]];p<-d$p[use];y<-d$y[use];w<-d$w[use];a<-if(is.character(t))rep(t==\"always-positive\",length(use))else p>=t\n TP<-sum(w[a&y==1]);FP<-sum(w[a&y==0]);FN<-sum(w[!a&y==1]);TN<-sum(w[!a&y==0]);P<-TP+FN;N<-FP+TN;W<-P+N;PP<-TP+FP;PN<-TN+FN;TPR<-ratio(TP,P);TNR<-ratio(TN,N);bs<-sum(w*(p-y)^2);tc<-FP*cost[1]+FN*cost[2]\n list(confusion=list(TP=TP,FP=FP,FN=FN,TN=TN),mass=W,positiveTargetMass=P,negativeTargetMass=N,predictedPositiveMass=PP,predictedNegativeMass=PN,prevalence=ratio(P,W),selectionRate=ratio(PP,W),accuracy=ratio(TP+TN,W),precision=ratio(TP,PP),negativePredictiveValue=ratio(TN,PN),TPR=TPR,FPR=ratio(FP,N),TNR=TNR,FNR=ratio(FN,P),F1=ratio(2*TP,2*TP+FP+FN),balancedAccuracy=if(is.na(TPR)||is.na(TNR))NA_real_ else(TPR+TNR)/2,Brier=ratio(bs,W),BrierSum=bs,totalCost=tc,meanCost=ratio(tc,W),bayesThreshold=ratio(cost[1],sum(cost)))\n}\ncurvesG<-function(d,ids){\n use<-ids[d$eligible[ids]];grid<-c(list(\"always-negative\"),as.list(sort(unique(d$p[use]),decreasing=TRUE)));points<-lapply(grid,function(t){m<-metricsG(d,ids,t);c(list(policy=t),m$confusion,m[c(\"TPR\",\"FPR\",\"precision\")],list(recall=m$TPR))});pos<-use[d$y[use]==1];neg<-use[d$y[use]==0];P<-sum(d$w[pos]);N<-sum(d$w[neg]);U<-0\n for(i in pos)U<-U+d$w[i]*sum(d$w[neg]*((d$p[i]>d$p[neg])+.5*(d$p[i]==d$p[neg])))\n AP<-trap<-lastR<-0;lastP<-1\n if(P&&length(grid)>1)for(j in 2:length(grid)){z<-points[[j]];AP<-AP+(z$recall-lastR)*z$precision;trap<-trap+(z$recall-lastR)*(z$precision+lastP)/2;lastR<-z$recall;lastP<-z$precision}\n list(points=points,ROC_AUC=ratio(U,P*N),averagePrecision=if(P)AP else NA_real_,PRTrapezoidWithInitialPrecisionOne=if(P)trap else NA_real_)\n}\nchooseG<-function(d,a,cost){\n role<-if(is.null(a$selectionRole))\"validation\"else a$selectionRole;er<-if(is.null(a$evaluationRole))\"test\"else a$evaluationRole;ids<-scopeG(d,role);use<-ids[d$eligible[ids]];stopifnot(length(use)>0);grid<-if(is.null(a$thresholds))c(list(\"always-negative\"),as.list(sort(unique(d$p[use]),decreasing=TRUE)))else lapply(a$thresholds,function(t)if(t%in%c(\"always-negative\",\"always-positive\"))t else qnum(t))\n candidates<-lapply(seq_along(grid),function(j){m<-metricsG(d,ids,grid[[j]],cost);feasible<-TRUE;if(!is.null(a$minTPR))feasible<-feasible&&!is.na(m$TPR)&&m$TPR>=qnum(a$minTPR);if(!is.null(a$maxFPR))feasible<-feasible&&!is.na(m$FPR)&&m$FPR<=qnum(a$maxFPR);list(index=j-1,policy=grid[[j]],metrics=m,feasible=feasible)})\n good<-which(vapply(candidates,function(c)c$feasible,logical(1)));best<-NA_integer_;if(length(good)){v<-vapply(candidates[good],function(c)c$metrics$meanCost,numeric(1));best<-good[which(v<=min(v)+1e-12)[1]]}\n list(selectedIndex=if(is.na(best))NA_integer_ else best-1,selectedPolicy=if(is.na(best))NULL else grid[[best]],selectedValidation=if(is.na(best))NULL else candidates[[best]]$metrics,candidates=candidates,evaluation=if(is.na(best)||er==\"none\")NULL else metricsG(d,scopeG(d,er),grid[[best]],cost))\n}\ncalibrateG<-function(d,ids,edges){\n use<-ids[d$eligible[ids]];W<-sum(d$w[use]);pi<-ratio(sum(d$w[use]*d$y[use]),W);bins<-list();ECE<-rel<-res<-correction<-0;assign<-findInterval(d$p[use],edges,rightmost.closed=TRUE,all.inside=TRUE)\n for(b in seq_len(length(edges)-1)){rr<-use[assign==b];w<-sum(d$w[rr]);mp<-ratio(sum(d$w[rr]*d$p[rr]),w);o<-ratio(sum(d$w[rr]*d$y[rr]),w);variance<-if(w)sum(d$w[rr]*(d$p[rr]-mp)^2)/w else NA_real_;covariance<-if(w)sum(d$w[rr]*(d$p[rr]-mp)*(d$y[rr]-o))/w else NA_real_;bc<-variance-2*covariance;gap<-mp-o;bins[[b]]<-list(index=b-1,mass=w,meanPrediction=mp,eventRate=o,scoreVariance=variance,scoreTargetCovariance=covariance,withinBinCorrection=bc,ids=d$id[rr])\n  if(w){s<-w/W;ECE<-ECE+s*abs(gap);rel<-rel+s*gap^2;res<-res+s*(o-pi)^2;correction<-correction+s*bc}\n };bs<-ratio(sum(d$w[use]*(d$p[use]-d$y[use])^2),W);unc<-pi*(1-pi);list(bins=bins,Brier=bs,ECE=if(W)ECE else NA_real_,uncertainty=unc,reliability=if(W)rel else NA_real_,resolution=if(W)res else NA_real_,withinBinCorrection=if(W)correction else NA_real_,BrierIdentityResidual=bs-(unc-res+rel+correction))\n}\ngroupsG<-function(d,ids,t,cost){\n lev<-unique(d$group[ids][!is.na(d$group[ids])]);groups<-lapply(lev,function(g)list(group=g,metrics=metricsG(d,ids[!is.na(d$group[ids])&d$group[ids]==g],t,cost)));overall<-metricsG(d,ids,t,cost);unknown<-metricsG(d,ids[is.na(d$group[ids])],t,cost);gaps<-list()\n for(k in c(\"prevalence\",\"selectionRate\",\"TPR\",\"FPR\",\"precision\",\"accuracy\",\"meanCost\")){use<-Filter(function(g)g$metrics$mass>0,groups);v<-vapply(use,function(g)g$metrics[[k]],numeric(1));gaps[[k]]<-if(length(use)<2||anyNA(v))NA_real_ else max(v)-min(v)}\n list(overall=overall,groups=groups,unknownGroup=unknown,gaps=gaps,partitionMassResidual=overall$mass-unknown$mass-sum(vapply(groups,function(g)g$metrics$mass,numeric(1))))\n}\nsvgFixed<-function(file,points,title,xlabel,ylabel,legend){\n finite<-points[points$y!=\"undefined\"&points$x!=\"undefined\",,drop=FALSE];x<-as.numeric(finite$x);y<-as.numeric(finite$y);xmin<-if(length(x))min(x)else 0;xmax<-if(length(x))max(x)else 1;ymin<-min(c(0,y));ymax<-max(c(0,y));if(xmin==xmax){xmin<-xmin-.5;xmax<-xmax+.5};if(ymin==ymax)ymax<-ymin+1;X<-function(v)85+(v-xmin)/(xmax-xmin)*480;Y<-function(v)278-(v-ymin)/(ymax-ymin)*175\n esc<-function(s){s<-gsub(\"&\",\"&amp;\",s,fixed=TRUE);s<-gsub(\"<\",\"&lt;\",s,fixed=TRUE);gsub(\">\",\"&gt;\",s,fixed=TRUE)};s<-'<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"620\" height=\"360\" viewBox=\"0 0 620 360\"><rect width=\"620\" height=\"360\" fill=\"white\"/><g font-family=\"Arial, sans-serif\" font-size=\"13\" fill=\"#17324d\">'\n lines<-strwrap(title,width=65);for(i in seq_along(lines))s<-paste0(s,'<text x=\"25\" y=\"',24+(i-1)*18,'\">',esc(lines[i]),'</text>');colors<-c(\"#176b9b\",\"#b85e18\",\"#437e4d\")\n for(i in seq_along(legend))s<-paste0(s,'<circle cx=\"',30+(i-1)*250,'\" cy=\"76\" r=\"4\" fill=\"',colors[(i-1)%%3+1],'\"/><text x=\"',42+(i-1)*250,'\" y=\"80\">',esc(legend[i]),'</text>')\n s<-paste0(s,'<path d=\"M85 98V278H575\" fill=\"none\" stroke=\"#52677d\"/><text text-anchor=\"middle\" x=\"325\" y=\"338\">',esc(xlabel),'</text><text text-anchor=\"middle\" transform=\"translate(21,190) rotate(-90)\">',esc(ylabel),'</text>')\n for(i in 0:4){xx<-xmin+(xmax-xmin)*i/4;yy<-ymin+(ymax-ymin)*i/4;s<-paste0(s,'<text text-anchor=\"middle\" x=\"',sprintf(\"%.9g\",X(xx)),'\" y=\"305\">',sprintf(\"%.4g\",xx),'</text><text text-anchor=\"end\" x=\"77\" y=\"',sprintf(\"%.9g\",Y(yy)+4),'\">',sprintf(\"%.4g\",yy),'</text>')}\n for(i in seq_len(nrow(finite)))s<-paste0(s,'<circle cx=\"',sprintf(\"%.9g\",X(x[i])),'\" cy=\"',sprintf(\"%.9g\",Y(y[i])),'\" r=\"3\" fill=\"',colors[as.integer(finite$series[i])%%3+1],'\"/>');writeLines(paste0(s,'</g></svg>'),file,useBytes=TRUE)\n}\nfixedRun<-function(){\n api<-FIXED$api;a<-FIXED$args;summary<-list();points<-list();xlabel<-\"Declared index\";ylabel<-\"Value\";legend<-\"Declared result\"\n metric<-function(name,v,unit=\"dimensionless\"){if(is.null(v))v<-NA_real_;summary[[length(summary)+1L]]<<-data.frame(metric=name,value=if(is.na(v))\"undefined\"else sprintf(\"%.9g\",v),exactValue=\"\",unit=unit,defined=as.integer(!is.na(v)),stringsAsFactors=FALSE)}\n pt<-function(i,x,y,id=\"\",series=0){points[[length(points)+1L]]<<-data.frame(series=series,index=i,xExact=\"\",x=if(is.na(x))\"undefined\"else sprintf(\"%.9g\",x),yExact=\"\",y=if(is.na(y))\"undefined\"else sprintf(\"%.9g\",y),id=as.character(id),stringsAsFactors=FALSE)}\n if(api==\"realdata\"){\n  native<-loadData()[[a$kind]];fit<-fitmodel(native);d<-list(id=native$id,p=fit$pred,y=native$y,w=rep(1,length(native$id)),role=native$role,group=native$group,eligible=native$eligible);scenarios<-list()\n  for(j in 1:3){name<-c(\"equal\",\"miss-five\",\"alarm-five\")[j];cst<-list(c(1,1),c(1,5),c(5,1))[[j]];sel<-chooseG(d,list(),cst);scenarios[[j]]<-list(name=name,selection=sel);metric(paste0(name,\"Threshold\"),sel$selectedPolicy);metric(paste0(name,\"TestCost\"),sel$evaluation$meanCost,\"hypothetical cost units/mass\")}\n  ids<-scopeG(d,\"test\");cv<-curvesG(d,ids);cal<-calibrateG(d,ids,seq(0,1,.2));metric(\"testAUC\",cv$ROC_AUC);metric(\"testAP\",cv$averagePrecision);metric(\"testBrier\",cal$Brier);metric(\"eligibleRows\",sum(d$eligible),\"rows\")\n  for(j in seq_along(ids)){i<-ids[j];pt(j-1,j,d$p[i],d$id[i],0);pt(j-1,j,d$y[i],d$id[i],1)}\n  full<-list(kind=a$kind,fit=fit,scenarios=scenarios,testCurves=cv,testCalibration=cal,rowsScored=d);xlabel<-\"Test row, native order\";ylabel<-\"Y or probability\";legend<-c(\"Training-fitted probability\",\"Observed Y\")\n }else{\n  d<-rowsG(a$rows);role<-if(is.null(a$role))\"all\"else a$role;ids<-scopeG(d,role);cost<-if(is.null(a$costs))c(1,1)else c(qnum(a$costs$falsePositive),qnum(a$costs$falseNegative));t<-if(is.null(a$threshold)).5 else if(a$threshold%in%c(\"always-positive\",\"always-negative\"))a$threshold else qnum(a$threshold)\n  if(api==\"metrics\"){\n   full<-metricsG(d,ids,t,cost);for(k in c(\"mass\",\"accuracy\",\"precision\",\"TPR\",\"FPR\",\"F1\",\"Brier\",\"meanCost\"))metric(k,full[[k]],if(k==\"mass\")\"mass\"else if(k==\"meanCost\")\"hypothetical cost units/mass\"else\"dimensionless\");metric(\"BayesThreshold\",full$bayesThreshold)\n   for(i in 1:4)pt(i-1,i-1,full$confusion[[i]],names(full$confusion)[i]);xlabel<-\"TP / FP / FN / TN positions\";ylabel<-\"Analytical mass\"\n  }else if(api==\"curves\"){\n   full<-curvesG(d,ids);for(k in c(\"ROC_AUC\",\"averagePrecision\",\"PRTrapezoidWithInitialPrecisionOne\"))metric(k,full[[k]])\n   for(j in seq_along(full$points)){p<-full$points[[j]];pt(j-1,p$FPR,p$TPR,if(is.character(p$policy))p$policy else sprintf(\"%.17g\",p$policy))};xlabel<-\"False positive rate\";ylabel<-\"True positive rate\";legend<-\"Observed ROC operating points\"\n  }else if(api==\"choose\"){\n   full<-chooseG(d,a,cost);metric(\"selectedIndex\",full$selectedIndex,\"candidate index\");metric(\"minimumCost\",if(is.null(full$selectedValidation))NULL else full$selectedValidation$meanCost,\"hypothetical cost units/mass\");metric(\"feasible\",as.integer(!is.na(full$selectedIndex)),\"indicator\")\n   for(c in full$candidates)pt(c$index,c$index,c$metrics$meanCost,if(is.character(c$policy))c$policy else sprintf(\"%.17g\",c$policy));xlabel<-\"Validation candidate\";ylabel<-\"Assumed cost / mass\";legend<-\"Validation candidate costs\"\n  }else if(api==\"calibrate\"){\n   edges<-if(is.null(a$binEdges))seq(0,1,.2)else vapply(a$binEdges,qnum,numeric(1));full<-calibrateG(d,ids,edges);for(k in c(\"ECE\",\"Brier\",\"uncertainty\",\"resolution\",\"reliability\",\"withinBinCorrection\",\"BrierIdentityResidual\"))metric(k,full[[k]])\n   for(b in full$bins)pt(b$index,b$meanPrediction,b$eventRate,paste0(\"bin:\",b$index));xlabel<-\"Bin mean forecast\";ylabel<-\"Bin event rate\";legend<-\"Binary-event reliability\"\n  }else if(api==\"groups\"){\n   full<-groupsG(d,ids,t,cost);metric(\"overallTPR\",full$overall$TPR);metric(\"TPRGap\",full$gaps$TPR);metric(\"precisionGap\",full$gaps$precision);metric(\"unknownMass\",full$unknownGroup$mass,\"mass\");metric(\"partitionResidual\",full$partitionMassResidual,\"mass\")\n   for(j in seq_along(full$groups))pt(j-1,j-1,full$groups[[j]]$metrics$TPR,full$groups[[j]]$group);xlabel<-\"Declared group position\";ylabel<-\"True positive rate\";legend<-\"Known-group TPR\"\n  }else stop(\"unknown declared fixed API\")\n }\n sm<-do.call(rbind,summary);pp<-do.call(rbind,points);write.csv(sm,file.path(outDir,\"summary.csv\"),row.names=FALSE,na=\"\");write.csv(pp,file.path(outDir,\"plot-points.csv\"),row.names=FALSE,na=\"\");svgFixed(file.path(outDir,\"plot.svg\"),pp,FIXED$title,xlabel,ylabel,legend);dput(list(api=api,variant=FIXED$variant,input=FIXED$args,arithmetic=\"Base-R binary64 fixed example; not an exact rational general validator\",result=full),file=file.path(outDir,\"full.txt\"));cat(\"PASS\",api,FIXED$variant,\"summary\",nrow(sm),\"points\",nrow(pp),\"\\n\")\n}\n\nFIXED<-list(api=\"choose\",variant=\"infeasible\",args=list(rows=list(list(id=\"a\",score=\".9\",y=1,group=\"A\",role=\"validation\"),list(id=\"b\",score=\".8\",y=1,group=\"A\",role=\"validation\"),list(id=\"c\",score=\".8\",y=0,group=\"A\",role=\"validation\"),list(id=\"d\",score=\".6\",y=0,group=\"B\",role=\"validation\"),list(id=\"e\",score=\".4\",y=1,group=\"B\",role=\"validation\"),list(id=\"f\",score=\".1\",y=0,group=\"B\",role=\"validation\")),minTPR=\"4/5\",maxFPR=\"2/5\",evaluationRole=\"none\"),title=\"No threshold satisfies both declared rate constraints\")\nfixedRun()\n",
        "codeText": "# ML14 standalone public counterpart, base R only.\n# Inputs are only the three factual CSVs; derived columns/previous model answers unused.\n# Binary64 arithmetic, not arbitrary-precision Fraction. At numerical cost ties\n# within 1e-12 retain the earliest candidate. Exact claims belong to Python/web.\n# SHA256 infrastructure below is reused verbatim from the previous public study.\nargs<-commandArgs(trailingOnly=TRUE);filearg<-grep(\"^--file=\",commandArgs(),value=TRUE)\nhere<-if(dir.exists(\"ml14-sources\"))getwd()else if(length(filearg))dirname(normalizePath(sub(\"^--file=\",\"\",filearg[1])))else getwd()\noption<-function(key,default){i<-match(key,args);if(is.na(i))default else args[i+1]}\nsourceDir<-option(\"--source\",file.path(here,\"ml14-sources\"));outDir<-option(\"--out\",file.path(getwd(),\"ml14-r-results\"));dir.create(outDir,recursive=TRUE,showWarnings=FALSE)\nnum<-function(x){x[x%in%c(\"\",\".\")]<-NA_character_;as.numeric(x)}\nfmt<-function(x)ifelse(is.na(x),\"\",sprintf(\"%.17g\",x))\nratio<-function(a,b)if(b==0)NA_real_ else a/b\nreadnative<-function(name)read.csv(file.path(sourceDir,name),check.names=FALSE,colClasses=\"character\",na.strings=character(),stringsAsFactors=FALSE)\n# Vectorized SHA256 for the short ASCII keys used in this study.\n# Unsigned words use exact integer-valued doubles; bit operations use safe\n# 16-bit halves, avoiding R's reserved signed-INT_MIN/NA representation.\nMOD<-2^32\nxor32<-function(a,b) as.double(bitwXor(as.integer(floor(a/65536)),as.integer(floor(b/65536))))*65536+as.double(bitwXor(as.integer(a%%65536),as.integer(b%%65536)))\nand32<-function(a,b) as.double(bitwAnd(as.integer(floor(a/65536)),as.integer(floor(b/65536))))*65536+as.double(bitwAnd(as.integer(a%%65536),as.integer(b%%65536)))\nrot<-function(x,n) floor(x/2^n)+(x%%2^n)*2^(32-n)\nxor3<-function(a,b,c) xor32(xor32(a,b),c)\nK<-c(0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5,0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967,0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070,0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3,0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2)\nsha256<-function(strings) {\n n<-length(strings);bytes<-matrix(0,n,64)\n for(i in seq_len(n)) {v<-utf8ToInt(strings[i]);stopifnot(length(v)<56,all(v<128));if(length(v)) bytes[i,seq_along(v)]<-v;bytes[i,length(v)+1]<-128;bits<-length(v)*8;bytes[i,61:64]<-c(floor(bits/2^24)%%256,floor(bits/2^16)%%256,floor(bits/256)%%256,bits%%256)}\n w<-matrix(0,n,64)\n for(j in 1:16) {b<-4*(j-1)+1;w[,j]<-bytes[,b]*2^24+bytes[,b+1]*2^16+bytes[,b+2]*256+bytes[,b+3]}\n for(j in 17:64) {s0<-xor3(rot(w[,j-15],7),rot(w[,j-15],18),floor(w[,j-15]/8));s1<-xor3(rot(w[,j-2],17),rot(w[,j-2],19),floor(w[,j-2]/1024));w[,j]<-(w[,j-16]+s0+w[,j-7]+s1)%%MOD}\n init<-c(0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19)\n state<-lapply(init,function(v) rep(v,n));a<-state[[1]];b<-state[[2]];c<-state[[3]];d<-state[[4]];e<-state[[5]];f<-state[[6]];g<-state[[7]];h<-state[[8]]\n for(j in 1:64) {S1<-xor3(rot(e,6),rot(e,11),rot(e,25));ch<-xor32(and32(e,f),and32(MOD-1-e,g));t1<-(h+S1+ch+K[j]+w[,j])%%MOD;S0<-xor3(rot(a,2),rot(a,13),rot(a,22));maj<-xor3(and32(a,b),and32(a,c),and32(b,c));t2<-(S0+maj)%%MOD;h<-g;g<-f;f<-e;e<-(d+t1)%%MOD;d<-c;c<-b;b<-a;a<-(t1+t2)%%MOD}\n end<-list(a,b,c,d,e,f,g,h);hex<-lapply(1:8,function(j){v<-(end[[j]]+init[j])%%MOD;paste0(sprintf(\"%04x\",as.integer(floor(v/65536))),sprintf(\"%04x\",as.integer(v%%65536)))})\n do.call(paste0,hex)\n}\nstopifnot(identical(sha256(c(\"abc\",\"\")),c(\"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad\",\"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855\")))\n\nloadData<-function(){\n wb<-readnative(\"actual64-country-four-indicators-original-2024.csv\");codes<-c(\"NY.GDP.PCAP.KD\",\"NY.GDP.MKTP.KD.ZG\",\"FP.CPI.TOTL.ZG\",\"SP.DYN.LE00.IN\");iso<-sort(unique(wb$countryISO3));stopifnot(nrow(wb)==64,length(iso)==16)\n tokens<-t(vapply(iso,function(s)wb$originalValueToken[match(paste(s,codes),paste(wb$countryISO3,wb$indicatorID))],character(4)));vals<-matrix(num(as.vector(tokens)),nrow=nrow(tokens))\n country<-list(id=paste0(iso,\":2024\"),sourceRow=1:16,originalID=iso,x=vals[,1:3,drop=FALSE],rawX=tokens[,1:3,drop=FALSE],nativeTarget=tokens[,4],y=as.integer(vals[,4]>=80),group=ifelse(is.na(vals[,1]),NA_character_,as.character(as.integer(vals[,1]>=25000))),lineage=vapply(iso,function(s)paste(wb$sourceRow[match(paste(s,codes),paste(wb$countryISO3,wb$indicatorID))],collapse=\";\"),character(1)),cat=integer(),units=c(\"constant2015USD/person\",\"annualPercent\",\"annualPercent\"))\n nls<-readnative(\"actual3613-NLS-original52-fields-groups-roles.csv\");raw<-cbind(nls$ed76,nls$age76,nls$nearc4)\n person<-list(id=paste0(\"person:\",nls$sourceRow),sourceRow=as.integer(nls$sourceRow),originalID=nls$id,x=matrix(num(as.vector(raw)),nrow=nrow(raw)),rawX=raw,nativeTarget=nls$wage76,y=as.integer(num(nls$wage76)>=500),group=ifelse(nls$black%in%c(\"\",\".\"),NA_character_,nls$black),lineage=nls$sourceRow,cat=2L,units=c(\"years\",\"years\",\"nativeCategory\"))\n ch<-readnative(\"actual3150-churn-original14-fields-groups-roles.csv\");raw<-cbind(ch[[\"Call  Failure\"]],ch$Complains,ch[[\"Subscription  Length\"]],ch[[\"Seconds of Use\"]])\n company<-list(id=paste0(\"customer:\",ch$sourceRow),sourceRow=as.integer(ch$sourceRow),originalID=rep(\"\",nrow(ch)),x=matrix(num(as.vector(raw)),nrow=nrow(raw)),rawX=raw,nativeTarget=ch$Churn,y=as.integer(ch$Churn),group=ifelse(ch[[\"Tariff Plan\"]]%in%c(\"\",\".\"),NA_character_,ch[[\"Tariff Plan\"]]),lineage=ch$sourceRow,cat=1L,units=c(\"count\",\"nativeCategory\",\"months\",\"seconds\"))\n stopifnot(nrow(nls)==3613,nrow(ch)==3150,identical(as.integer(ch$sourceRow[ch[[\"Charge  Amount\"]]==\"10\"]),c(474L,2174L,2274L,2374L,2674L,2924L,2974L)))\n result<-list(country=country,person=person,company=company)\n for(k in names(result)){d<-result[[k]];n<-length(d$id);d$eligible<-!is.na(d$y)&rowSums(is.na(d$x))==0;hash<-sha256(paste0(\"ML14-role|\",k,\"|\",d$id));rank<-integer(n);rank[order(hash,seq_len(n))]<-seq_len(n)-1L;d$plannedRole<-ifelse(rank%%5==0,\"test\",ifelse(rank%%5==1,\"validation\",\"train\"));d$role<-ifelse(d$eligible,d$plannedRole,\"excluded\");result[[k]]<-d}\n stopifnot(sum(result$person$eligible)==3017);result\n}\nfitmodel<-function(d){\n ids<-which(d$role==\"train\");p<-ncol(d$x);m<-vapply(seq_len(p),function(j)if((j-1)%in%d$cat)NA_real_ else median(d$x[ids,j]),numeric(1));z<-d$x\n for(j in seq_len(p))if(!((j-1)%in%d$cat))z[,j]<-as.numeric(z[,j]>m[j])\n keys<-apply(z,1,function(v)paste(fmt(v),collapse=\"|\"));lev<-unique(keys[ids]);mass<-vapply(lev,function(k)sum(keys[ids]==k),integer(1));positive<-vapply(lev,function(k)sum(d$y[ids][keys[ids]==k]),integer(1));prob<-(positive+1)/(mass+2);fallback<-(sum(d$y[ids])+1)/(length(ids)+2);pred<-prob[match(keys,lev)];unseen<-is.na(pred);pred[unseen]<-fallback;pred[!d$eligible]<-NA_real_;unseen[!d$eligible]<-NA\n list(ids=ids,medians=m,z=z,keys=keys,lev=lev,mass=mass,positive=positive,prob=prob,fallback=fallback,pred=pred,unseen=unseen)\n}\nmeasure<-function(d,p,ids,t=.5,cost=c(1,1)){\n use<-ids[d$eligible[ids]&!is.na(p[ids])];y<-d$y[use];a<-if(is.character(t))rep(t==\"always-positive\",length(use))else p[use]>=t\n TP<-sum(a&y==1);FP<-sum(a&y==0);FN<-sum(!a&y==1);TN<-sum(!a&y==0);P<-TP+FN;N<-FP+TN;W<-P+N;PP<-TP+FP;PN<-TN+FN;TPR<-ratio(TP,P);TNR<-ratio(TN,N);bs<-sum((p[use]-y)^2);tc<-FP*cost[1]+FN*cost[2]\n list(TP=TP,FP=FP,FN=FN,TN=TN,mass=W,positiveTargetMass=P,negativeTargetMass=N,predictedPositiveMass=PP,predictedNegativeMass=PN,prevalence=ratio(P,W),selectionRate=ratio(PP,W),accuracy=ratio(TP+TN,W),precision=ratio(TP,PP),negativePredictiveValue=ratio(TN,PN),TPR=TPR,FPR=ratio(FP,N),TNR=TNR,FNR=ratio(FN,P),F1=ratio(2*TP,2*TP+FP+FN),balancedAccuracy=if(is.na(TPR)||is.na(TNR))NA_real_ else(TPR+TNR)/2,Brier=ratio(bs,W),BrierSum=bs,totalCost=tc,meanCost=ratio(tc,W))\n}\ncurves<-function(d,p,ids){\n use<-ids[d$eligible[ids]&!is.na(p[ids])];scores<-sort(unique(p[use]),decreasing=TRUE);policies<-c(list(\"always-negative\"),as.list(scores));points<-lapply(policies,function(t){m<-measure(d,p,ids,t);c(list(policy=t),m[c(\"TP\",\"FP\",\"FN\",\"TN\",\"TPR\",\"FPR\",\"precision\")],list(recall=m$TPR))})\n pos<-use[d$y[use]==1];neg<-use[d$y[use]==0];U<-0;for(i in pos)U<-U+sum(p[i]>p[neg])+.5*sum(p[i]==p[neg])\n AP<-0;trap<-0;lastR<-0;lastP<-1\n if(length(pos)&&length(scores))for(j in seq_along(scores)){z<-points[[j+1]];AP<-AP+(z$recall-lastR)*z$precision;trap<-trap+(z$recall-lastR)*(z$precision+lastP)/2;lastR<-z$recall;lastP<-z$precision}\n list(points=points,ROC_AUC=ratio(U,length(pos)*length(neg)),averagePrecision=if(length(pos))AP else NA_real_,PRTrapezoidWithInitialPrecisionOne=if(length(pos))trap else NA_real_)\n}\ncalibrate<-function(d,p,ids){\n use<-ids[d$eligible[ids]&!is.na(p[ids])];W<-length(use);pi<-if(W)mean(d$y[use])else NA_real_;bins<-list();ECE<-rel<-res<-correction<-0\n whichbin<-findInterval(p[use],seq(0,1,.2),rightmost.closed=TRUE,all.inside=TRUE)\n for(b in 1:5){rr<-use[whichbin==b];w<-length(rr);mp<-if(w)mean(p[rr])else NA_real_;o<-if(w)mean(d$y[rr])else NA_real_;variance<-if(w)mean((p[rr]-mp)^2)else NA_real_;covariance<-if(w)mean((p[rr]-mp)*(d$y[rr]-o))else NA_real_;bc<-variance-2*covariance;gap<-mp-o\n  bins[[b]]<-list(mass=w,meanPrediction=mp,eventRate=o,gap=gap,absoluteGap=abs(gap),scoreVariance=variance,scoreTargetCovariance=covariance,withinBinCorrection=bc,rows=w,ids=d$id[rr])\n  if(w){share<-w/W;ECE<-ECE+share*abs(gap);rel<-rel+share*gap^2;res<-res+share*(o-pi)^2;correction<-correction+share*bc}\n };bs<-if(W)mean((p[use]-d$y[use])^2)else NA_real_;unc<-pi*(1-pi)\n list(bins=bins,ECE=if(W)ECE else NA_real_,Brier=bs,reliability=if(W)rel else NA_real_,resolution=if(W)res else NA_real_,uncertainty=unc,withinBinCorrection=if(W)correction else NA_real_,BrierIdentityResidual=bs-(unc-res+rel+correction))\n}\ncounts<-c(\"mass\",\"positiveTargetMass\",\"negativeTargetMass\",\"predictedPositiveMass\",\"predictedNegativeMass\");rates<-c(\"prevalence\",\"selectionRate\",\"accuracy\",\"precision\",\"negativePredictiveValue\",\"TPR\",\"FPR\",\"TNR\",\"FNR\",\"F1\",\"balancedAccuracy\",\"Brier\",\"BrierSum\",\"totalCost\",\"meanCost\")\ntables<-setNames(lapply(1:10,function(i)list()),c(\"predictions\",\"lineage\",\"fit-medians\",\"fit-cells\",\"validation-candidates\",\"test-metrics\",\"test-curves\",\"calibration-bins\",\"group-metrics\",\"chart-points\"))\nadd<-function(name,row)tables[[name]][[length(tables[[name]])+1L]]<<-row\nscalars<-function(m,keys){out<-list();for(k in keys){out[[paste0(k,\"Exact\")]]<-\"\";out[[paste0(k,\"Approx\")]]<-fmt(m[[k]])};out}\ntagrow<-function(kind,...)c(list(kind=kind),list(...))\npoint<-function(kind,chart,series,index,x,y,xunit=\"dimensionless\",yunit=\"dimensionless\",role=\"test\",tag=\"\"){add(\"chart-points\",tagrow(kind,chart=chart,series=series,index=index,xExact=\"\",xApprox=fmt(x),yExact=\"\",yApprox=fmt(y),xUnit=xunit,yUnit=yunit,role=role,tag=tag))}\nstudy<-function(kind,d){\n f<-fitmodel(d);n<-length(d$id);train<-which(d$role==\"train\");validation<-which(d$role==\"validation\");test<-which(d$role==\"test\");p<-f$pred;cv<-curves(d,p,test);cal<-calibrate(d,p,test)\n for(i in seq_len(n)){\n  reason<-if(d$eligible[i])\"\"else\"required-X-or-Y-missing\";transformed<-if(d$eligible[i])paste(fmt(f$z[i,]),collapse=\"|\")else\"\"\n  add(\"predictions\",tagrow(kind,id=d$id[i],sourceRow=d$sourceRow[i],originalID=d$originalID[i],plannedRole=d$plannedRole[i],role=d$role[i],group=ifelse(is.na(d$group[i]),\"\",d$group[i]),eligible=as.integer(d$eligible[i]),targetExact=fmt(d$y[i]),probabilityExact=\"\",probabilityApprox=fmt(p[i]),unseenCell=ifelse(is.na(f$unseen[i]),\"\",as.character(as.integer(f$unseen[i]))),transformedX=transformed,reason=reason))\n  raw<-d$rawX[i,];raw[raw%in%c(\"\",\".\")]<-\"\";nativeY<-d$nativeTarget[i];if(nativeY%in%c(\"\",\".\"))nativeY<-\"\"\n  add(\"lineage\",tagrow(kind,id=d$id[i],sourceRow=d$sourceRow[i],originalID=d$originalID[i],nativeSourceRows=d$lineage[i],rawX=paste(raw,collapse=\"|\"),nativeTarget=nativeY,derivedTarget=fmt(d$y[i]),nativeGroup=ifelse(is.na(d$group[i]),\"\",d$group[i]),plannedRole=d$plannedRole[i],role=d$role[i],eligible=as.integer(d$eligible[i]),analyticalMass=\"1\",reason=reason))\n }\n for(j in seq_len(ncol(d$x)))add(\"fit-medians\",tagrow(kind,feature=j-1,categorical=as.integer((j-1)%in%d$cat),fitRows=length(train),medianExact=\"\",medianApprox=fmt(f$medians[j]),unit=d$units[j]))\n for(j in seq_along(f$lev))add(\"fit-cells\",tagrow(kind,cell=f$lev[j],trainingRows=f$mass[j],positiveRows=f$positive[j],probabilityExact=\"\",probabilityApprox=fmt(f$prob[j]),fallbackExact=\"\",fallbackApprox=fmt(f$fallback)))\n for(j in seq_along(cv$points)){\n  z<-cv$points[[j]];t<-z$policy;add(\"test-curves\",c(tagrow(kind,point=j-1,policy=if(is.character(t))t else\"threshold\",thresholdExact=\"\",thresholdApprox=if(is.character(t))\"\"else fmt(t)),scalars(z,c(\"TP\",\"FP\",\"FN\",\"TN\",\"TPR\",\"FPR\",\"precision\",\"recall\"))))\n  point(kind,\"roc\",\"ROC\",j-1,z$FPR,z$TPR);point(kind,\"pr\",\"PR-observed\",j-1,z$recall,z$precision)\n }\n for(b in 1:5){z<-cal$bins[[b]];add(\"calibration-bins\",c(tagrow(kind,bin=b-1,leftExact=c(\"0\",\"1/5\",\"2/5\",\"3/5\",\"4/5\")[b],rightExact=c(\"1/5\",\"2/5\",\"3/5\",\"4/5\",\"1\")[b],rightClosed=as.integer(b==5),rows=z$rows,ids=paste(z$ids,collapse=\";\")),scalars(z,c(\"mass\",\"meanPrediction\",\"eventRate\",\"gap\",\"absoluteGap\",\"scoreVariance\",\"scoreTargetCovariance\",\"withinBinCorrection\"))));point(kind,\"reliability\",\"Binary event rate\",b-1,z$meanPrediction,z$eventRate,tag=paste0(\"rows=\",z$rows))}\n for(j in seq_along(test)){i<-test[j];point(kind,\"test-scores\",\"Training-fitted probability\",j-1,j,p[i],\"test-row position\",\"probability\",tag=d$id[i]);point(kind,\"test-scores\",\"Observed Y\",j-1,j,d$y[i],\"test-row position\",\"binary target\",tag=d$id[i])}\n scenarioNames<-c(\"equal\",\"miss-five\",\"alarm-five\");costs<-list(c(1,1),c(1,5),c(5,1))\n for(s in 1:3){name<-scenarioNames[s];cost<-costs[[s]];grid<-c(list(\"always-negative\"),as.list(sort(unique(p[validation]),decreasing=TRUE)));candidates<-lapply(grid,function(t)measure(d,p,validation,t,cost));values<-vapply(candidates,function(m)m$meanCost,numeric(1));best<-which(values<=min(values)+1e-12)[1];chosen<-grid[[best]];ev<-measure(d,p,test,chosen,cost)\n  for(j in seq_along(grid)){t<-grid[[j]];m<-candidates[[j]];cell<-setNames(lapply(c(\"TP\",\"FP\",\"FN\",\"TN\"),function(k)fmt(m[[k]])),paste0(c(\"TP\",\"FP\",\"FN\",\"TN\"),\"Exact\"));add(\"validation-candidates\",c(tagrow(kind,scenario=name,candidate=j-1,selected=as.integer(j==best),policy=if(is.character(t))t else\"threshold\",thresholdExact=\"\",thresholdApprox=if(is.character(t))\"\"else fmt(t),feasible=1,reasons=\"\"),cell,scalars(m,c(counts,\"TPR\",\"FPR\",\"precision\",\"meanCost\",\"totalCost\"))));point(kind,\"validation-cost\",name,j-1,j-1,m$meanCost,\"candidate index\",\"hypothetical cost units/mass\",\"validation\",if(is.character(t))t else fmt(t))}\n  m<-c(ev,cv[c(\"ROC_AUC\",\"averagePrecision\",\"PRTrapezoidWithInitialPrecisionOne\")],cal[c(\"ECE\",\"reliability\",\"resolution\",\"uncertainty\",\"withinBinCorrection\",\"BrierIdentityResidual\")])\n  for(k in c(\"TP\",\"FP\",\"FN\",\"TN\",counts,rates,\"ROC_AUC\",\"averagePrecision\",\"PRTrapezoidWithInitialPrecisionOne\",\"ECE\",\"reliability\",\"resolution\",\"uncertainty\",\"withinBinCorrection\",\"BrierIdentityResidual\")){\n   unit<-if(k%in%c(\"TP\",\"FP\",\"FN\",\"TN\",counts))\"rows\"else if(k==\"totalCost\")\"hypothetical cost units\"else if(k==\"meanCost\")\"hypothetical cost units/mass\"else if(k==\"BrierSum\")\"sum squared-probability loss\"else\"dimensionless\"\n   add(\"test-metrics\",tagrow(kind,scenario=name,metric=k,valueExact=\"\",valueApprox=fmt(m[[k]]),unit=unit))\n  }\n  lev<-unique(d$group[test][!is.na(d$group[test])]);sets<-c(list(test),lapply(lev,function(g)test[!is.na(d$group[test])&d$group[test]==g]),list(test[is.na(d$group[test])]))\n  types<-c(\"overall\",rep(\"known\",length(lev)),\"unknown\");tokens<-c(\"all\",lev,\"\")\n  for(j in seq_along(sets)){ids<-sets[[j]];m<-measure(d,p,ids,chosen,cost);cell<-setNames(lapply(c(\"TP\",\"FP\",\"FN\",\"TN\"),function(k)fmt(m[[k]])),paste0(c(\"TP\",\"FP\",\"FN\",\"TN\"),\"Exact\"));add(\"group-metrics\",c(tagrow(kind,scenario=name,groupType=types[j],groupToken=tokens[j],retainedRows=length(ids)),cell,scalars(m,c(counts,rates))));if(types[j]==\"known\")point(kind,\"group-TPR\",name,j-2,j-2,m$TPR,\"declared group position\",\"TPR\",tag=tokens[j])}\n }\n invisible(NULL)\n}\n\n# Fixed finite inputs only; not the complete web input/budget validator.\nqnum<-function(v){if(is.null(v))return(NA_real_);if(is.logical(v))return(as.numeric(v));s<-as.character(v);if(grepl(\"/\",s,fixed=TRUE)){a<-strsplit(s,\"/\",fixed=TRUE)[[1]];return(as.numeric(a[1])/as.numeric(a[2]))};as.numeric(s)}\nrowsG<-function(raw){\n n<-length(raw);get<-function(r,k,default=NULL)if(is.null(r[[k]]))default else r[[k]]\n id<-vapply(raw,function(r)as.character(r$id),character(1));p<-vapply(raw,function(r)qnum(r$score),numeric(1));y<-vapply(raw,function(r)qnum(r$y),numeric(1));w<-vapply(raw,function(r)qnum(get(r,\"weight\",\"1\")),numeric(1));role<-vapply(raw,function(r)get(r,\"role\",\"evaluation\"),character(1));group<-vapply(raw,function(r)as.character(get(r,\"group\",NA_character_)),character(1))\n stopifnot(all(w>=0),all(is.na(p)|(p>=0&p<=1)),all(is.na(y)|y%in%c(0,1)),!anyDuplicated(id));list(id=id,p=p,y=y,w=w,role=role,group=group,eligible=!is.na(p)&!is.na(y)&w>0&role!=\"excluded\")\n}\nscopeG<-function(d,role=\"all\")if(role==\"all\")seq_along(d$id)else which(d$role==role)\nmetricsG<-function(d,ids,t=.5,cost=c(1,1)){\n use<-ids[d$eligible[ids]];p<-d$p[use];y<-d$y[use];w<-d$w[use];a<-if(is.character(t))rep(t==\"always-positive\",length(use))else p>=t\n TP<-sum(w[a&y==1]);FP<-sum(w[a&y==0]);FN<-sum(w[!a&y==1]);TN<-sum(w[!a&y==0]);P<-TP+FN;N<-FP+TN;W<-P+N;PP<-TP+FP;PN<-TN+FN;TPR<-ratio(TP,P);TNR<-ratio(TN,N);bs<-sum(w*(p-y)^2);tc<-FP*cost[1]+FN*cost[2]\n list(confusion=list(TP=TP,FP=FP,FN=FN,TN=TN),mass=W,positiveTargetMass=P,negativeTargetMass=N,predictedPositiveMass=PP,predictedNegativeMass=PN,prevalence=ratio(P,W),selectionRate=ratio(PP,W),accuracy=ratio(TP+TN,W),precision=ratio(TP,PP),negativePredictiveValue=ratio(TN,PN),TPR=TPR,FPR=ratio(FP,N),TNR=TNR,FNR=ratio(FN,P),F1=ratio(2*TP,2*TP+FP+FN),balancedAccuracy=if(is.na(TPR)||is.na(TNR))NA_real_ else(TPR+TNR)/2,Brier=ratio(bs,W),BrierSum=bs,totalCost=tc,meanCost=ratio(tc,W),bayesThreshold=ratio(cost[1],sum(cost)))\n}\ncurvesG<-function(d,ids){\n use<-ids[d$eligible[ids]];grid<-c(list(\"always-negative\"),as.list(sort(unique(d$p[use]),decreasing=TRUE)));points<-lapply(grid,function(t){m<-metricsG(d,ids,t);c(list(policy=t),m$confusion,m[c(\"TPR\",\"FPR\",\"precision\")],list(recall=m$TPR))});pos<-use[d$y[use]==1];neg<-use[d$y[use]==0];P<-sum(d$w[pos]);N<-sum(d$w[neg]);U<-0\n for(i in pos)U<-U+d$w[i]*sum(d$w[neg]*((d$p[i]>d$p[neg])+.5*(d$p[i]==d$p[neg])))\n AP<-trap<-lastR<-0;lastP<-1\n if(P&&length(grid)>1)for(j in 2:length(grid)){z<-points[[j]];AP<-AP+(z$recall-lastR)*z$precision;trap<-trap+(z$recall-lastR)*(z$precision+lastP)/2;lastR<-z$recall;lastP<-z$precision}\n list(points=points,ROC_AUC=ratio(U,P*N),averagePrecision=if(P)AP else NA_real_,PRTrapezoidWithInitialPrecisionOne=if(P)trap else NA_real_)\n}\nchooseG<-function(d,a,cost){\n role<-if(is.null(a$selectionRole))\"validation\"else a$selectionRole;er<-if(is.null(a$evaluationRole))\"test\"else a$evaluationRole;ids<-scopeG(d,role);use<-ids[d$eligible[ids]];stopifnot(length(use)>0);grid<-if(is.null(a$thresholds))c(list(\"always-negative\"),as.list(sort(unique(d$p[use]),decreasing=TRUE)))else lapply(a$thresholds,function(t)if(t%in%c(\"always-negative\",\"always-positive\"))t else qnum(t))\n candidates<-lapply(seq_along(grid),function(j){m<-metricsG(d,ids,grid[[j]],cost);feasible<-TRUE;if(!is.null(a$minTPR))feasible<-feasible&&!is.na(m$TPR)&&m$TPR>=qnum(a$minTPR);if(!is.null(a$maxFPR))feasible<-feasible&&!is.na(m$FPR)&&m$FPR<=qnum(a$maxFPR);list(index=j-1,policy=grid[[j]],metrics=m,feasible=feasible)})\n good<-which(vapply(candidates,function(c)c$feasible,logical(1)));best<-NA_integer_;if(length(good)){v<-vapply(candidates[good],function(c)c$metrics$meanCost,numeric(1));best<-good[which(v<=min(v)+1e-12)[1]]}\n list(selectedIndex=if(is.na(best))NA_integer_ else best-1,selectedPolicy=if(is.na(best))NULL else grid[[best]],selectedValidation=if(is.na(best))NULL else candidates[[best]]$metrics,candidates=candidates,evaluation=if(is.na(best)||er==\"none\")NULL else metricsG(d,scopeG(d,er),grid[[best]],cost))\n}\ncalibrateG<-function(d,ids,edges){\n use<-ids[d$eligible[ids]];W<-sum(d$w[use]);pi<-ratio(sum(d$w[use]*d$y[use]),W);bins<-list();ECE<-rel<-res<-correction<-0;assign<-findInterval(d$p[use],edges,rightmost.closed=TRUE,all.inside=TRUE)\n for(b in seq_len(length(edges)-1)){rr<-use[assign==b];w<-sum(d$w[rr]);mp<-ratio(sum(d$w[rr]*d$p[rr]),w);o<-ratio(sum(d$w[rr]*d$y[rr]),w);variance<-if(w)sum(d$w[rr]*(d$p[rr]-mp)^2)/w else NA_real_;covariance<-if(w)sum(d$w[rr]*(d$p[rr]-mp)*(d$y[rr]-o))/w else NA_real_;bc<-variance-2*covariance;gap<-mp-o;bins[[b]]<-list(index=b-1,mass=w,meanPrediction=mp,eventRate=o,scoreVariance=variance,scoreTargetCovariance=covariance,withinBinCorrection=bc,ids=d$id[rr])\n  if(w){s<-w/W;ECE<-ECE+s*abs(gap);rel<-rel+s*gap^2;res<-res+s*(o-pi)^2;correction<-correction+s*bc}\n };bs<-ratio(sum(d$w[use]*(d$p[use]-d$y[use])^2),W);unc<-pi*(1-pi);list(bins=bins,Brier=bs,ECE=if(W)ECE else NA_real_,uncertainty=unc,reliability=if(W)rel else NA_real_,resolution=if(W)res else NA_real_,withinBinCorrection=if(W)correction else NA_real_,BrierIdentityResidual=bs-(unc-res+rel+correction))\n}\ngroupsG<-function(d,ids,t,cost){\n lev<-unique(d$group[ids][!is.na(d$group[ids])]);groups<-lapply(lev,function(g)list(group=g,metrics=metricsG(d,ids[!is.na(d$group[ids])&d$group[ids]==g],t,cost)));overall<-metricsG(d,ids,t,cost);unknown<-metricsG(d,ids[is.na(d$group[ids])],t,cost);gaps<-list()\n for(k in c(\"prevalence\",\"selectionRate\",\"TPR\",\"FPR\",\"precision\",\"accuracy\",\"meanCost\")){use<-Filter(function(g)g$metrics$mass>0,groups);v<-vapply(use,function(g)g$metrics[[k]],numeric(1));gaps[[k]]<-if(length(use)<2||anyNA(v))NA_real_ else max(v)-min(v)}\n list(overall=overall,groups=groups,unknownGroup=unknown,gaps=gaps,partitionMassResidual=overall$mass-unknown$mass-sum(vapply(groups,function(g)g$metrics$mass,numeric(1))))\n}\nsvgFixed<-function(file,points,title,xlabel,ylabel,legend){\n finite<-points[points$y!=\"undefined\"&points$x!=\"undefined\",,drop=FALSE];x<-as.numeric(finite$x);y<-as.numeric(finite$y);xmin<-if(length(x))min(x)else 0;xmax<-if(length(x))max(x)else 1;ymin<-min(c(0,y));ymax<-max(c(0,y));if(xmin==xmax){xmin<-xmin-.5;xmax<-xmax+.5};if(ymin==ymax)ymax<-ymin+1;X<-function(v)85+(v-xmin)/(xmax-xmin)*480;Y<-function(v)278-(v-ymin)/(ymax-ymin)*175\n esc<-function(s){s<-gsub(\"&\",\"&amp;\",s,fixed=TRUE);s<-gsub(\"<\",\"&lt;\",s,fixed=TRUE);gsub(\">\",\"&gt;\",s,fixed=TRUE)};s<-'<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"620\" height=\"360\" viewBox=\"0 0 620 360\"><rect width=\"620\" height=\"360\" fill=\"white\"/><g font-family=\"Arial, sans-serif\" font-size=\"13\" fill=\"#17324d\">'\n lines<-strwrap(title,width=65);for(i in seq_along(lines))s<-paste0(s,'<text x=\"25\" y=\"',24+(i-1)*18,'\">',esc(lines[i]),'</text>');colors<-c(\"#176b9b\",\"#b85e18\",\"#437e4d\")\n for(i in seq_along(legend))s<-paste0(s,'<circle cx=\"',30+(i-1)*250,'\" cy=\"76\" r=\"4\" fill=\"',colors[(i-1)%%3+1],'\"/><text x=\"',42+(i-1)*250,'\" y=\"80\">',esc(legend[i]),'</text>')\n s<-paste0(s,'<path d=\"M85 98V278H575\" fill=\"none\" stroke=\"#52677d\"/><text text-anchor=\"middle\" x=\"325\" y=\"338\">',esc(xlabel),'</text><text text-anchor=\"middle\" transform=\"translate(21,190) rotate(-90)\">',esc(ylabel),'</text>')\n for(i in 0:4){xx<-xmin+(xmax-xmin)*i/4;yy<-ymin+(ymax-ymin)*i/4;s<-paste0(s,'<text text-anchor=\"middle\" x=\"',sprintf(\"%.9g\",X(xx)),'\" y=\"305\">',sprintf(\"%.4g\",xx),'</text><text text-anchor=\"end\" x=\"77\" y=\"',sprintf(\"%.9g\",Y(yy)+4),'\">',sprintf(\"%.4g\",yy),'</text>')}\n for(i in seq_len(nrow(finite)))s<-paste0(s,'<circle cx=\"',sprintf(\"%.9g\",X(x[i])),'\" cy=\"',sprintf(\"%.9g\",Y(y[i])),'\" r=\"3\" fill=\"',colors[as.integer(finite$series[i])%%3+1],'\"/>');writeLines(paste0(s,'</g></svg>'),file,useBytes=TRUE)\n}\nfixedRun<-function(){\n api<-FIXED$api;a<-FIXED$args;summary<-list();points<-list();xlabel<-\"Declared index\";ylabel<-\"Value\";legend<-\"Declared result\"\n metric<-function(name,v,unit=\"dimensionless\"){if(is.null(v))v<-NA_real_;summary[[length(summary)+1L]]<<-data.frame(metric=name,value=if(is.na(v))\"undefined\"else sprintf(\"%.9g\",v),exactValue=\"\",unit=unit,defined=as.integer(!is.na(v)),stringsAsFactors=FALSE)}\n pt<-function(i,x,y,id=\"\",series=0){points[[length(points)+1L]]<<-data.frame(series=series,index=i,xExact=\"\",x=if(is.na(x))\"undefined\"else sprintf(\"%.9g\",x),yExact=\"\",y=if(is.na(y))\"undefined\"else sprintf(\"%.9g\",y),id=as.character(id),stringsAsFactors=FALSE)}\n if(api==\"realdata\"){\n  native<-loadData()[[a$kind]];fit<-fitmodel(native);d<-list(id=native$id,p=fit$pred,y=native$y,w=rep(1,length(native$id)),role=native$role,group=native$group,eligible=native$eligible);scenarios<-list()\n  for(j in 1:3){name<-c(\"equal\",\"miss-five\",\"alarm-five\")[j];cst<-list(c(1,1),c(1,5),c(5,1))[[j]];sel<-chooseG(d,list(),cst);scenarios[[j]]<-list(name=name,selection=sel);metric(paste0(name,\"Threshold\"),sel$selectedPolicy);metric(paste0(name,\"TestCost\"),sel$evaluation$meanCost,\"hypothetical cost units/mass\")}\n  ids<-scopeG(d,\"test\");cv<-curvesG(d,ids);cal<-calibrateG(d,ids,seq(0,1,.2));metric(\"testAUC\",cv$ROC_AUC);metric(\"testAP\",cv$averagePrecision);metric(\"testBrier\",cal$Brier);metric(\"eligibleRows\",sum(d$eligible),\"rows\")\n  for(j in seq_along(ids)){i<-ids[j];pt(j-1,j,d$p[i],d$id[i],0);pt(j-1,j,d$y[i],d$id[i],1)}\n  full<-list(kind=a$kind,fit=fit,scenarios=scenarios,testCurves=cv,testCalibration=cal,rowsScored=d);xlabel<-\"Test row, native order\";ylabel<-\"Y or probability\";legend<-c(\"Training-fitted probability\",\"Observed Y\")\n }else{\n  d<-rowsG(a$rows);role<-if(is.null(a$role))\"all\"else a$role;ids<-scopeG(d,role);cost<-if(is.null(a$costs))c(1,1)else c(qnum(a$costs$falsePositive),qnum(a$costs$falseNegative));t<-if(is.null(a$threshold)).5 else if(a$threshold%in%c(\"always-positive\",\"always-negative\"))a$threshold else qnum(a$threshold)\n  if(api==\"metrics\"){\n   full<-metricsG(d,ids,t,cost);for(k in c(\"mass\",\"accuracy\",\"precision\",\"TPR\",\"FPR\",\"F1\",\"Brier\",\"meanCost\"))metric(k,full[[k]],if(k==\"mass\")\"mass\"else if(k==\"meanCost\")\"hypothetical cost units/mass\"else\"dimensionless\");metric(\"BayesThreshold\",full$bayesThreshold)\n   for(i in 1:4)pt(i-1,i-1,full$confusion[[i]],names(full$confusion)[i]);xlabel<-\"TP / FP / FN / TN positions\";ylabel<-\"Analytical mass\"\n  }else if(api==\"curves\"){\n   full<-curvesG(d,ids);for(k in c(\"ROC_AUC\",\"averagePrecision\",\"PRTrapezoidWithInitialPrecisionOne\"))metric(k,full[[k]])\n   for(j in seq_along(full$points)){p<-full$points[[j]];pt(j-1,p$FPR,p$TPR,if(is.character(p$policy))p$policy else sprintf(\"%.17g\",p$policy))};xlabel<-\"False positive rate\";ylabel<-\"True positive rate\";legend<-\"Observed ROC operating points\"\n  }else if(api==\"choose\"){\n   full<-chooseG(d,a,cost);metric(\"selectedIndex\",full$selectedIndex,\"candidate index\");metric(\"minimumCost\",if(is.null(full$selectedValidation))NULL else full$selectedValidation$meanCost,\"hypothetical cost units/mass\");metric(\"feasible\",as.integer(!is.na(full$selectedIndex)),\"indicator\")\n   for(c in full$candidates)pt(c$index,c$index,c$metrics$meanCost,if(is.character(c$policy))c$policy else sprintf(\"%.17g\",c$policy));xlabel<-\"Validation candidate\";ylabel<-\"Assumed cost / mass\";legend<-\"Validation candidate costs\"\n  }else if(api==\"calibrate\"){\n   edges<-if(is.null(a$binEdges))seq(0,1,.2)else vapply(a$binEdges,qnum,numeric(1));full<-calibrateG(d,ids,edges);for(k in c(\"ECE\",\"Brier\",\"uncertainty\",\"resolution\",\"reliability\",\"withinBinCorrection\",\"BrierIdentityResidual\"))metric(k,full[[k]])\n   for(b in full$bins)pt(b$index,b$meanPrediction,b$eventRate,paste0(\"bin:\",b$index));xlabel<-\"Bin mean forecast\";ylabel<-\"Bin event rate\";legend<-\"Binary-event reliability\"\n  }else if(api==\"groups\"){\n   full<-groupsG(d,ids,t,cost);metric(\"overallTPR\",full$overall$TPR);metric(\"TPRGap\",full$gaps$TPR);metric(\"precisionGap\",full$gaps$precision);metric(\"unknownMass\",full$unknownGroup$mass,\"mass\");metric(\"partitionResidual\",full$partitionMassResidual,\"mass\")\n   for(j in seq_along(full$groups))pt(j-1,j-1,full$groups[[j]]$metrics$TPR,full$groups[[j]]$group);xlabel<-\"Declared group position\";ylabel<-\"True positive rate\";legend<-\"Known-group TPR\"\n  }else stop(\"unknown declared fixed API\")\n }\n sm<-do.call(rbind,summary);pp<-do.call(rbind,points);write.csv(sm,file.path(outDir,\"summary.csv\"),row.names=FALSE,na=\"\");write.csv(pp,file.path(outDir,\"plot-points.csv\"),row.names=FALSE,na=\"\");svgFixed(file.path(outDir,\"plot.svg\"),pp,FIXED$title,xlabel,ylabel,legend);dput(list(api=api,variant=FIXED$variant,input=FIXED$args,arithmetic=\"Base-R binary64 fixed example; not an exact rational general validator\",result=full),file=file.path(outDir,\"full.txt\"));cat(\"PASS\",api,FIXED$variant,\"summary\",nrow(sm),\"points\",nrow(pp),\"\\n\")\n}\n\nFIXED<-list(api=\"choose\",variant=\"infeasible\",args=list(rows=list(list(id=\"a\",score=\".9\",y=1,group=\"A\",role=\"validation\"),list(id=\"b\",score=\".8\",y=1,group=\"A\",role=\"validation\"),list(id=\"c\",score=\".8\",y=0,group=\"A\",role=\"validation\"),list(id=\"d\",score=\".6\",y=0,group=\"B\",role=\"validation\"),list(id=\"e\",score=\".4\",y=1,group=\"B\",role=\"validation\"),list(id=\"f\",score=\".1\",y=0,group=\"B\",role=\"validation\")),minTPR=\"4/5\",maxFPR=\"2/5\",evaluationRole=\"none\"),title=\"No threshold satisfies both declared rate constraints\")\nfixedRun()\n",
        "input": {
          "rows": [
            {
              "id": "a",
              "score": ".9",
              "y": 1,
              "group": "A",
              "role": "validation"
            },
            {
              "id": "b",
              "score": ".8",
              "y": 1,
              "group": "A",
              "role": "validation"
            },
            {
              "id": "c",
              "score": ".8",
              "y": 0,
              "group": "A",
              "role": "validation"
            },
            {
              "id": "d",
              "score": ".6",
              "y": 0,
              "group": "B",
              "role": "validation"
            },
            {
              "id": "e",
              "score": ".4",
              "y": 1,
              "group": "B",
              "role": "validation"
            },
            {
              "id": "f",
              "score": ".1",
              "y": 0,
              "group": "B",
              "role": "validation"
            }
          ],
          "minTPR": "4/5",
          "maxFPR": "2/5",
          "evaluationRole": "none"
        },
        "inputFiles": [],
        "returnCode": 0,
        "expectedFailure": false,
        "stdout": "PASS choose infeasible summary 3 points 6 \n",
        "stderr": "During startup - Warning messages:\n1: Setting LC_COLLATE=C.UTF-8 failed \n2: Setting LC_CTYPE=C.UTF-8 failed \n3: Setting LC_MONETARY=C.UTF-8 failed \n4: Setting LC_TIME=C.UTF-8 failed \n",
        "summary": {
          "selectedIndex": "undefined",
          "minimumCost": "undefined",
          "feasible": "0"
        },
        "summaryRows": [
          {
            "metric": "selectedIndex",
            "value": "undefined",
            "exactValue": "",
            "unit": "candidate index",
            "defined": "0"
          },
          {
            "metric": "minimumCost",
            "value": "undefined",
            "exactValue": "",
            "unit": "hypothetical cost units/mass",
            "defined": "0"
          },
          {
            "metric": "feasible",
            "value": "0",
            "exactValue": "",
            "unit": "indicator",
            "defined": "1"
          }
        ],
        "plotPoints": [
          {
            "series": "0",
            "index": "0",
            "xExact": "",
            "x": "0",
            "yExact": "",
            "y": "0.5",
            "id": "always-negative"
          },
          {
            "series": "0",
            "index": "1",
            "xExact": "",
            "x": "1",
            "yExact": "",
            "y": "0.333333333",
            "id": "0.90000000000000002"
          },
          {
            "series": "0",
            "index": "2",
            "xExact": "",
            "x": "2",
            "yExact": "",
            "y": "0.333333333",
            "id": "0.80000000000000004"
          },
          {
            "series": "0",
            "index": "3",
            "xExact": "",
            "x": "3",
            "yExact": "",
            "y": "0.5",
            "id": "0.59999999999999998"
          },
          {
            "series": "0",
            "index": "4",
            "xExact": "",
            "x": "4",
            "yExact": "",
            "y": "0.333333333",
            "id": "0.40000000000000002"
          },
          {
            "series": "0",
            "index": "5",
            "xExact": "",
            "x": "5",
            "yExact": "",
            "y": "0.5",
            "id": "0.10000000000000001"
          }
        ],
        "plotFile": "ml14-fixed-results/choose-infeasible-r/plot.svg",
        "plotSHA256": "bc6fe93d3fd1b3fc2c9aaa611696914a0a84551157a5734b324126079e8d412a",
        "files": [
          {
            "file": "ml14-fixed-results/choose-infeasible-r/full.txt",
            "sha256": "b839545df7e918beaea9fddfbbea0b993a775fe296b748c63ad572d4cbfe834d",
            "bytes": 5518
          },
          {
            "file": "ml14-fixed-results/choose-infeasible-r/plot-points.csv",
            "sha256": "592424a72ec29d6bef6ad1e71b31600bb3d7935251ef3130377a35dfa25e365d",
            "bytes": 327
          },
          {
            "file": "ml14-fixed-results/choose-infeasible-r/plot.svg",
            "sha256": "bc6fe93d3fd1b3fc2c9aaa611696914a0a84551157a5734b324126079e8d412a",
            "bytes": 1434
          },
          {
            "file": "ml14-fixed-results/choose-infeasible-r/summary.csv",
            "sha256": "8785ec80989c2d8fec9ca9c78db12e09eb020e69f34a817b41301cb0fe635018",
            "bytes": 196
          }
        ],
        "scope": "Actually executed standalone fixed example, Python exact Fraction versus base-R binary64. Approximate R residuals retained; not universal exact arithmetic/web validation/native UI. Source programs read factual3CSV only."
      }
    }
  },
  "calibrate": {
    "python": {
      "two-bins": {
        "api": "calibrate",
        "variant": "two-bins",
        "language": "python",
        "title": "Six-card binary-event bins and full Brier identity",
        "codeFile": "ml14-code/calibrate-two-bins.py",
        "codeSHA256": "72ac98dfdde15a5845572a67f42ac61e14c397587d24e5c6d37c6e672436c61e",
        "code": "#!/usr/bin/env python3\n\"\"\"ML14 standalone exact finite study, Python standard library only.\nInputs: only the three retained factual source CSVs below.\nDerived role/target/group/eligibility columns in those CSVs are NOT inputs.\nRebuilds SHA256 roles, train-only medians/cell scores, validation thresholds,\ntest curves, binary-event reliability and descriptive group ledgers.\nCosts 1/1,1/5,5/1 are hypothetical units, not measured intervention returns.\nThis is author public reproduction, not independent scientific review.\n\"\"\"\n\"\"\"Author Fraction reference, separate from product JavaScript; not independent peer.\"\"\"\nfrom fractions import Fraction as F\nfrom collections import Counter,defaultdict\ndef read(raw):\n rows=[]\n for i,r in enumerate(raw):\n  s=None if r['score']is None else F(str(r['score']));y=None if r['y']is None else F(int(r['y']))if isinstance(r['y'],bool)else F(str(r['y']));w=F(str(r.get('weight','1')));role=r.get('role','evaluation')\n  rows.append(dict(id=r['id'],index=i,score=s,y=y,w=w,role=role,group=r.get('group'),eligible=s is not None and y is not None and w>0 and role!='excluded'))\n return rows\ndef scoped(rows,role='all'):return rows if role=='all'else[r for r in rows if r['role']==role]\ndef divide(n,d):return None if not d else n/d\ndef policy(v):return v if v in ['always-negative','always-positive']else F(str(v))\ndef positive(p,s):return p=='always-positive'if isinstance(p,str)else s>=p\ndef cost(a=None):\n a={}if a is None else a;fp=F(str(a.get('falsePositive','1')));fn=F(str(a.get('falseNegative','1')));return fp,fn\ndef metrics(rows,threshold=F(1,2),cc=(F(1),F(1))):\n counts=dict(TP=F(0),FP=F(0),FN=F(0),TN=F(0));brier=F(0);pred=[]\n for r in rows:\n  if not r['eligible']:pred.append(dict(id=r['id'],index=r['index'],eligible=False,decision=None,probability=None,Brier=None));continue\n  yes=positive(threshold,r['score']);cell=('T'if yes==bool(r['y'])else'F')+('P'if yes else'N');counts[cell]+=r['w'];loss=(r['score']-r['y'])**2;brier+=r['w']*loss;pred.append(dict(id=r['id'],index=r['index'],eligible=True,decision=int(yes),probability=r['score'],Brier=loss))\n TP,FP,FN,TN=[counts[k]for k in ['TP','FP','FN','TN']];P=TP+FN;N=TN+FP;mass=P+N;PP=TP+FP;PN=TN+FN;TPR=divide(TP,P);TNR=divide(TN,N);total=FP*cc[0]+FN*cc[1]\n return dict(confusion=counts,mass=mass,positiveTargetMass=P,negativeTargetMass=N,predictedPositiveMass=PP,predictedNegativeMass=PN,prevalence=divide(P,mass),selectionRate=divide(PP,mass),accuracy=divide(TP+TN,mass),precision=divide(TP,PP),negativePredictiveValue=divide(TN,PN),TPR=TPR,FPR=divide(FP,N),TNR=TNR,FNR=divide(FN,P),F1=divide(2*TP,2*TP+FP+FN),balancedAccuracy=None if TPR is None or TNR is None else(TPR+TNR)/2,Brier=divide(brier,mass),BrierSum=brier,totalCost=total,meanCost=divide(total,mass),predictions=pred,bayesThreshold=divide(cc[0],sum(cc)))\ndef curves(rows):\n use=[r for r in rows if r['eligible']];pos=Counter();neg=Counter()\n for r in use:(pos if r['y']else neg)[r['score']]+=r['w']\n P=sum(pos.values(),F(0));N=sum(neg.values(),F(0));pairs=F(0)\n for a,wa in pos.items():\n  for b,wb in neg.items():pairs+=wa*wb*(F(1)if a>b else F(1,2)if a==b else F(0))\n thresholds=['always-negative']+sorted({r['score']for r in use},reverse=True);points=[];AP=F(0);trap=F(0);lastR=F(0);lastP=F(1)\n for i,p in enumerate(thresholds):\n  m=metrics(rows,p);points.append(dict(policy=p,TP=m['confusion']['TP'],FP=m['confusion']['FP'],FN=m['confusion']['FN'],TN=m['confusion']['TN'],TPR=m['TPR'],FPR=m['FPR'],precision=m['precision'],recall=m['TPR']))\n  if i and P:\n   R=m['TPR'];PP=m['precision'];AP+=(R-lastR)*PP;trap+=(R-lastR)*(PP+lastP)/2;lastR=R;lastP=PP\n return dict(positiveMass=P,negativeMass=N,ROC_AUC=divide(pairs,P*N),weightedConcordantPlusHalfTiedMass=pairs,averagePrecision=AP if P else None,PRTrapezoidWithInitialPrecisionOne=trap if P else None,points=points)\ndef choose(rows,a,cc):\n sr=a.get('selectionRole','validation');er=a.get('evaluationRole','test');rr=scoped(rows,sr);thresholds=[policy(t)for t in a['thresholds']]if'thresholds'in a else['always-negative']+sorted({r['score']for r in rr if r['eligible']},reverse=True)\n candidates=[]\n for i,p in enumerate(thresholds):\n  m=metrics(rr,p,cc);reasons=[]\n  if'minTPR'in a and(m['TPR']is None or m['TPR']<F(str(a['minTPR']))):reasons.append('TPR-undefined'if m['TPR']is None else'below-minTPR')\n  if'maxFPR'in a and(m['FPR']is None or m['FPR']>F(str(a['maxFPR']))):reasons.append('FPR-undefined'if m['FPR']is None else'above-maxFPR')\n  candidates.append(dict(index=i,policy=p,metrics=m,feasible=not reasons,reasons=reasons))\n eligible=[c for c in candidates if c['feasible']];best=min(eligible,key=lambda c:(c['metrics']['meanCost'],c['index']))if eligible else None\n return dict(selectedIndex=None if best is None else best['index'],selectedPolicy=None if best is None else best['policy'],candidates=candidates,selectedValidation=None if best is None else best['metrics'],evaluation=None if best is None or er=='none'else metrics(scoped(rows,er),best['policy'],cc),selectionIDs=[r['id']for r in rr if r['eligible']])\ndef calibrate(rows,ee):\n buckets=[[]for _ in range(len(ee)-1)]\n for r in rows:\n  if not r['eligible']:continue\n  j=next((i for i in range(len(ee)-1)if r['score']<ee[i+1]),len(ee)-2);buckets[j].append(r)\n mass=sum((r['w']for r in rows if r['eligible']),F(0));P=sum((r['w']*r['y']for r in rows if r['eligible']),F(0));pi=divide(P,mass);Brier=None if not mass else sum((r['w']*(r['score']-r['y'])**2 for r in rows if r['eligible']),F(0))/mass;ECE=F(0);reliability=F(0);resolution=F(0);correction=F(0);bins=[]\n for i,rr in enumerate(buckets):\n  w=sum((r['w']for r in rr),F(0));mp=None if not w else sum((r['w']*r['score']for r in rr),F(0))/w;o=None if not w else sum((r['w']*r['y']for r in rr),F(0))/w\n  variance=None if not w else sum((r['w']*(r['score']-mp)**2 for r in rr),F(0))/w\n  covariance=None if not w else sum((r['w']*(r['score']-mp)*(r['y']-o)for r in rr),F(0))/w\n  bc=None if not w else variance-2*covariance;gap=None if not w else mp-o\n  bins.append(dict(index=i,rows=len(rr),mass=w,meanPrediction=mp,eventRate=o,gap=gap,absoluteGap=None if gap is None else abs(gap),scoreVariance=variance,scoreTargetCovariance=covariance,withinBinCorrection=bc,ids=[r['id']for r in rr]))\n  if w:\n   share=w/mass;ECE+=share*abs(gap);reliability+=share*gap**2;resolution+=share*(o-pi)**2;correction+=share*bc\n uncertainty=None if pi is None else pi*(1-pi);residual=None if Brier is None else Brier-(uncertainty-resolution+reliability+correction)\n return dict(mass=mass,prevalence=pi,Brier=Brier,ECE=ECE if mass else None,reliability=reliability if mass else None,resolution=resolution if mass else None,uncertainty=uncertainty,withinBinCorrection=correction if mass else None,BrierIdentityResidual=residual,bins=bins)\ndef typed(v):return type(v).__name__,v\ndef groups(rows,p,cc):\n bins={}\n for r in rows:\n  if r['group']is not None:bins.setdefault(typed(r['group']),[]).append(r)\n gm=[dict(group=rr[0]['group'],metrics=metrics(rr,p,cc))for rr in bins.values()];overall=metrics(rows,p,cc);unknown=metrics([r for r in rows if r['group']is None],p,cc);gaps={}\n for key in ['prevalence','selectionRate','TPR','FPR','precision','accuracy','meanCost']:\n  positive=[g for g in gm if g['metrics']['mass']>0];undefined=[g['group']for g in positive if g['metrics'][key]is None];vals=[g['metrics'][key]for g in positive if g['metrics'][key]is not None]\n  gaps[key]=dict(value=None if len(positive)<2 or undefined else max(vals)-min(vals),undefinedGroups=undefined,comparedPositiveMassGroups=[g['group']for g in positive])\n return dict(overall=overall,groups=gm,unknownGroup=unknown,gaps=gaps,partitionMassResidual=overall['mass']-unknown['mass']-sum((g['metrics']['mass']for g in gm),F(0)))\ndef actual_model(M):\n raw=M['records'];cat=M['categoricalFeatures'];p=len(raw[0]['x']);train=[r for r in raw if r['role']=='train'];medians=[]\n for j in range(p):\n  if j in cat:medians.append(None);continue\n  values=sorted(F(r['x'][j])for r in train);n=len(values);medians.append(values[n//2]if n%2 else(values[n//2-1]+values[n//2])/2)\n def transform(r):return[F(v)if j in cat else F(int(F(v)>medians[j]))for j,v in enumerate(r['x'])]\n counts={}\n for r in train:\n  key=tuple(transform(r));n,s=counts.get(key,(0,0));counts[key]=(n+1,s+int(r['y']))\n probabilities={k:F(s+1,n+2)for k,(n,s)in counts.items()};fallback=F(sum(int(r['y'])for r in train)+1,len(train)+2);scored=[]\n for i,r in enumerate(raw):\n  eligible=r['role']!='excluded';z=transform(r)if eligible else None;key=None if z is None else tuple(z);score=None if not eligible else probabilities.get(key,fallback)\n  scored.append(dict(id=r['id'],index=i,role=r['role'],group=r['group'],y=None if r['y']is None else F(r['y']),score=score,w=F(1),eligible=eligible,transformedX=z,unseenCell=None if not eligible else key not in probabilities))\n return dict(medians=medians,cells=counts,probabilities=probabilities,fallback=fallback,rows=scored,trainIDs=[r['id']for r in train])\n\n\nimport csv,json,hashlib,argparse,datetime\nfrom pathlib import Path\ndef missing(v):return None if v in ['', '.',None]else v\ndef load_sources(folder):\n def read_csv(name):\n  with (folder/name).open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))\n wb=read_csv('actual64-country-four-indicators-original-2024.csv')\n codes=['NY.GDP.PCAP.KD','NY.GDP.MKTP.KD.ZG','FP.CPI.TOTL.ZG','SP.DYN.LE00.IN']\n lookup={(r['countryISO3'],r['indicatorID']):r for r in wb};country=[]\n for i,iso in enumerate(sorted({r['countryISO3']for r in wb}),1):\n  native=[lookup[iso,c]for c in codes];v=[missing(r['originalValueToken'])for r in native]\n  country.append(dict(id=iso+':2024',sourceRow=i,originalID=iso,x=v[:3],y=None if v[3]is None else str(int(F(v[3])>=80)),group=None if v[0]is None else str(int(F(v[0])>=25000)),nativeTarget=v[3],nativeSourceRows=';'.join(r['sourceRow']for r in native)))\n nls=read_csv('actual3613-NLS-original52-fields-groups-roles.csv');person=[]\n for r in nls:\n  y=missing(r['wage76']);person.append(dict(id='person:'+r['sourceRow'],sourceRow=int(r['sourceRow']),originalID=r['id'],x=[missing(r[k])for k in ['ed76','age76','nearc4']],y=None if y is None else str(int(F(y)>=500)),group=missing(r['black']),nativeTarget=y,nativeSourceRows=r['sourceRow']))\n ch=read_csv('actual3150-churn-original14-fields-groups-roles.csv');company=[]\n for r in ch:\n  company.append(dict(id='customer:'+r['sourceRow'],sourceRow=int(r['sourceRow']),originalID='',x=[missing(r[k])for k in ['Call  Failure','Complains','Subscription  Length','Seconds of Use']],y=missing(r['Churn']),group=missing(r['Tariff Plan']),nativeTarget=missing(r['Churn']),nativeSourceRows=r['sourceRow']))\n assert len(wb)==64 and len(country)==16 and len(nls)==3613 and len(ch)==3150\n assert [int(r['sourceRow'])for r in ch if r['Charge  Amount']=='10']==[474,2174,2274,2374,2674,2924,2974]\n models={}\n for kind,raw,cat,units in [('country',country,[],['constant2015USD/person','annualPercent','annualPercent']),('person',person,[2],['years','years','nativeCategory']),('company',company,[1],['count','nativeCategory','months','seconds'])]:\n  order=sorted(range(len(raw)),key=lambda i:(hashlib.sha256(('ML14-role|'+kind+'|'+raw[i]['id']).encode()).hexdigest(),i))\n  for rank,i in enumerate(order):\n   r=raw[i];r['plannedRole']='test'if rank%5==0 else'validation'if rank%5==1 else'train';r['eligible']=None not in r['x']+[r['y']];r['role']=r['plannedRole']if r['eligible']else'excluded';r['weight']='1'\n  models[kind]=dict(records=raw,categoricalFeatures=cat,featureUnits=units)\n assert sum(r['eligible']for r in person)==3017\n return models\n\ndef exact(v):return ''if v is None else str(v)\ndef approx(v):return ''if v is None else format(float(v),'.17g')\ndef scalar_fields(m,keys):\n out={}\n for k in keys:\n  out[k+'Exact']=exact(m[k]);out[k+'Approx']=approx(m[k])\n return out\nCOUNTS=['mass','positiveTargetMass','negativeTargetMass','predictedPositiveMass','predictedNegativeMass']\nRATES=['prevalence','selectionRate','accuracy','precision','negativePredictiveValue','TPR','FPR','TNR','FNR','F1','balancedAccuracy','Brier','BrierSum','totalCost','meanCost']\nSCENARIOS=[('equal',F(1),F(1)),('miss-five',F(1),F(5)),('alarm-five',F(5),F(1))]\ndef packed(v):\n if isinstance(v,F):return str(v)\n if isinstance(v,dict):return{str(k):packed(x)for k,x in v.items()}\n if isinstance(v,(tuple,list)):return[packed(x)for x in v]\n return v\ndef run_study(source,out):\n out.mkdir(parents=True,exist_ok=True);models=load_sources(source)\n tables={name:[]for name in ['predictions','lineage','fit-medians','fit-cells','validation-candidates','test-metrics','test-curves','calibration-bins','group-metrics','chart-points']}\n studies={};charts=[]\n def point(kind,chart,series,index,x,y,xunit='dimensionless',yunit='dimensionless',role='test',tag=''):\n  tables['chart-points'].append(dict(kind=kind,chart=chart,series=series,index=index,xExact=exact(x),xApprox=approx(x),yExact=exact(y),yApprox=approx(y),xUnit=xunit,yUnit=yunit,role=role,tag=tag))\n for kind,M in models.items():\n  fit=actual_model(M);rr=fit['rows'];native=M['records'];test=scoped(rr,'test');cv=curves(test);cal=calibrate(test,[F(0),F(1,5),F(2,5),F(3,5),F(4,5),F(1)]);scenarios=[]\n  for i,r in enumerate(rr):\n   n=native[i];reason=''if r['eligible']else'required-X-or-Y-missing'\n   tables['predictions'].append(dict(kind=kind,id=r['id'],sourceRow=n['sourceRow'],originalID=n['originalID'],plannedRole=n['plannedRole'],role=r['role'],group=''if r['group']is None else r['group'],eligible=int(r['eligible']),targetExact=exact(r['y']),probabilityExact=exact(r['score']),probabilityApprox=approx(r['score']),unseenCell=''if r['unseenCell']is None else int(r['unseenCell']),transformedX=''if r['transformedX']is None else'|'.join(map(str,r['transformedX'])),reason=reason))\n   tables['lineage'].append(dict(kind=kind,id=r['id'],sourceRow=n['sourceRow'],originalID=n['originalID'],nativeSourceRows=n['nativeSourceRows'],rawX='|'.join(''if x is None else x for x in n['x']),nativeTarget=''if n['nativeTarget']is None else n['nativeTarget'],derivedTarget=exact(r['y']),nativeGroup=''if n['group']is None else n['group'],plannedRole=n['plannedRole'],role=r['role'],eligible=int(r['eligible']),analyticalMass='1',reason=reason))\n  for j,v in enumerate(fit['medians']):tables['fit-medians'].append(dict(kind=kind,feature=j,categorical=int(j in M['categoricalFeatures']),fitRows=len(fit['trainIDs']),medianExact=exact(v),medianApprox=approx(v),unit=M['featureUnits'][j]))\n  for key,(mass,pos)in fit['cells'].items():tables['fit-cells'].append(dict(kind=kind,cell='|'.join(map(str,key)),trainingRows=mass,positiveRows=pos,probabilityExact=exact(fit['probabilities'][key]),probabilityApprox=approx(fit['probabilities'][key]),fallbackExact=exact(fit['fallback']),fallbackApprox=approx(fit['fallback'])))\n  for j,p in enumerate(cv['points']):\n   policy=p['policy'];tables['test-curves'].append(dict(kind=kind,point=j,policy=policy if isinstance(policy,str)else'threshold',thresholdExact=''if isinstance(policy,str)else exact(policy),thresholdApprox=''if isinstance(policy,str)else approx(policy),**scalar_fields(p,['TP','FP','FN','TN','TPR','FPR','precision','recall'])))\n   point(kind,'roc','ROC',j,p['FPR'],p['TPR']);point(kind,'pr','PR-observed',j,p['recall'],p['precision'])\n  for b in cal['bins']:\n   tables['calibration-bins'].append(dict(kind=kind,bin=b['index'],leftExact=str(F(b['index'],5)),rightExact=str(F(b['index']+1,5)),rightClosed=int(b['index']==4),rows=b['rows'],ids=';'.join(str(i)for i in b['ids']),**scalar_fields(b,['mass','meanPrediction','eventRate','gap','absoluteGap','scoreVariance','scoreTargetCovariance','withinBinCorrection'])))\n   point(kind,'reliability','Binary event rate',b['index'],b['meanPrediction'],b['eventRate'],tag='rows='+str(b['rows']))\n  for j,r in enumerate(test):\n   point(kind,'test-scores','Training-fitted probability',j,F(j+1),r['score'],'test-row position','probability',tag=r['id'])\n   point(kind,'test-scores','Observed Y',j,F(j+1),r['y'],'test-row position','binary target',tag=r['id'])\n  for name,fp,fn in SCENARIOS:\n   choice=choose(rr,{},(fp,fn));gm=groups(test,choice['selectedPolicy'],(fp,fn));scenarios.append(dict(name=name,costs=dict(falsePositive=fp,falseNegative=fn),selection=choice,groups=gm));ev=choice['evaluation']\n   for c in choice['candidates']:\n    policy=c['policy'];mm=c['metrics'];tables['validation-candidates'].append(dict(kind=kind,scenario=name,candidate=c['index'],selected=int(c['index']==choice['selectedIndex']),policy=policy if isinstance(policy,str)else'threshold',thresholdExact=''if isinstance(policy,str)else exact(policy),thresholdApprox=''if isinstance(policy,str)else approx(policy),feasible=int(c['feasible']),reasons=';'.join(c['reasons']),**{k+'Exact':str(v)for k,v in mm['confusion'].items()},**scalar_fields(mm,COUNTS+['TPR','FPR','precision','meanCost','totalCost'])))\n    point(kind,'validation-cost',name,c['index'],F(c['index']),mm['meanCost'],'candidate index','hypothetical cost units/mass','validation',tag=exact(policy))\n   mm={**ev,**ev['confusion'],**{k:cv[k]for k in ['ROC_AUC','averagePrecision','PRTrapezoidWithInitialPrecisionOne']},**{k:cal[k]for k in ['ECE','reliability','resolution','uncertainty','withinBinCorrection','BrierIdentityResidual']}}\n   for key in ['TP','FP','FN','TN']+COUNTS+RATES+['ROC_AUC','averagePrecision','PRTrapezoidWithInitialPrecisionOne','ECE','reliability','resolution','uncertainty','withinBinCorrection','BrierIdentityResidual']:\n    unit='rows'if key in ['TP','FP','FN','TN']+COUNTS else'hypothetical cost units'if key=='totalCost'else'hypothetical cost units/mass'if key=='meanCost'else'sum squared-probability loss'if key=='BrierSum'else'dimensionless'\n    tables['test-metrics'].append(dict(kind=kind,scenario=name,metric=key,valueExact=exact(mm[key]),valueApprox=approx(mm[key]),unit=unit))\n   allg=[('overall','all',gm['overall'])]+[('known',str(g['group']),g['metrics'])for g in gm['groups']]+[('unknown','',gm['unknownGroup'])]\n   for j,(typ,token,g)in enumerate(allg):\n    tables['group-metrics'].append(dict(kind=kind,scenario=name,groupType=typ,groupToken=token,retainedRows=g.get('retainedRows',sum((r['group']==token)if typ=='known'else(r['group']is None)if typ=='unknown'else True for r in test)),**{k+'Exact':str(v)for k,v in g['confusion'].items()},**scalar_fields(g,COUNTS+RATES)))\n    if typ=='known':point(kind,'group-TPR',name,j-1,F(j-1),g['TPR'],'declared group position','TPR',tag=token)\n  studies[kind]=dict(kind=kind,rows=len(native),eligibleRows=sum(r['eligible']for r in rr),trainingIDs=fit['trainIDs'],fitMedians=fit['medians'],fitCells=[dict(cell=list(k),mass=n,positive=s,probability=fit['probabilities'][k])for k,(n,s)in fit['cells'].items()],fallback=fit['fallback'],scenarios=scenarios,testCurves=cv,testCalibration=cal,rowsScored=rr)\n files=[]\n for name,rows in tables.items():\n  p=out/('computed-'+name+'.csv')\n  with p.open('w',encoding='utf8',newline='')as f:w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows)\n  files.append(dict(file=p.name,rows=len(rows),columns=len(rows[0]),bodyFields=len(rows)*len(rows[0]),sha256=hashlib.sha256(p.read_bytes()).hexdigest()))\n (out/'study.json').write_text(json.dumps(packed(studies),ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\n sourceFiles=[source/n for n in ['actual64-country-four-indicators-original-2024.csv','actual3613-NLS-original52-fields-groups-roles.csv','actual3150-churn-original14-fields-groups-roles.csv']]\n provenance=dict(chapter='ML-14',arithmetic='Python stdlib Fraction exact finite values from original decimal strings; binary64 valueApprox is display only.',inputs=[dict(file=p.name,sha256=hashlib.sha256(p.read_bytes()).hexdigest())for p in sourceFiles],priorEngineModelsScoresOrComputedFilesRead=False,roleRule=\"SHA256('ML14-role|'+kind+'|'+ID),rankmod5=0test/1validation/others train before eligibility\",costs='Hypothetical1/1,1/5,5/1; no causal intervention returns',files=files,observations={k:dict(sourceRows=v['rows'],eligibleRows=v['eligibleRows'],trainingRows=len(v['trainingIDs']))for k,v in studies.items()})\n (out/'provenance.json').write_text(json.dumps(provenance,ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\n print(json.dumps(dict(status='PASS standalone completed',files=len(files),bodyFields=sum(f['bodyFields']for f in files),observations=provenance['observations'])))\n\n# Fixed declared examples: full web budget/option validation is not reproduced.\nfrom html import escape\nimport textwrap\ndef validated_rows(raw):\n for r in raw:\n  assert F(str(r.get('weight','1')))>=0,'negative analytical mass'\n  assert r['score']is None or 0<=F(str(r['score']))<=1,'score outside zero/one'\n  assert r['y']is None or F(str(int(r['y']))if isinstance(r['y'],bool)else str(r['y']))in [0,1],'binary target required'\n return read(raw)\ndef serial(v):\n if isinstance(v,F):return dict(exactFraction=str(v),value=float(v))\n if isinstance(v,(list,tuple)):return[serial(x)for x in v]\n if isinstance(v,dict):return{k:serial(x)for k,x in v.items()}\n return v\ndef fixed_svg(path,points,title,xlabel,ylabel,legend):\n use=[p for p in points if p['xExact']!=''and p['yExact']!=''];xs=[float(F(p['xExact']))for p in use];ys=[float(F(p['yExact']))for p in use]\n xmin=min(xs,default=0);xmax=max(xs,default=1);ymin=min([0]+ys);ymax=max([0]+ys)\n if xmin==xmax:xmin-=.5;xmax+=.5\n if ymin==ymax:ymax=ymin+1\n X=lambda v:85+(float(v)-xmin)/(xmax-xmin)*480;Y=lambda v:278-(float(v)-ymin)/(ymax-ymin)*175\n s='<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"620\" height=\"360\" viewBox=\"0 0 620 360\"><rect width=\"620\" height=\"360\" fill=\"white\"/><g font-family=\"Arial, sans-serif\" font-size=\"13\" fill=\"#17324d\">'\n for i,line in enumerate(textwrap.wrap(title,width=65)):s+='<text x=\"25\" y=\"'+str(24+i*18)+'\">'+escape(line)+'</text>'\n colors=['#176b9b','#b85e18','#437e4d']\n for i,label in enumerate(legend):s+='<circle cx=\"'+str(30+i*250)+'\" cy=\"76\" r=\"4\" fill=\"'+colors[i%3]+'\"/><text x=\"'+str(42+i*250)+'\" y=\"80\">'+escape(label)+'</text>'\n s+='<path d=\"M85 98V278H575\" fill=\"none\" stroke=\"#52677d\"/><text text-anchor=\"middle\" x=\"325\" y=\"338\">'+escape(xlabel)+'</text><text text-anchor=\"middle\" transform=\"translate(21,190) rotate(-90)\">'+escape(ylabel)+'</text>'\n for i in range(5):\n  xx=xmin+(xmax-xmin)*i/4;yy=ymin+(ymax-ymin)*i/4;s+='<text text-anchor=\"middle\" x=\"'+format(X(xx),'.9g')+'\" y=\"305\">'+format(xx,'.4g')+'</text><text text-anchor=\"end\" x=\"77\" y=\"'+format(Y(yy)+4,'.9g')+'\">'+format(yy,'.4g')+'</text>'\n for p in use:s+='<circle cx=\"'+format(X(F(p['xExact'])),'.9g')+'\" cy=\"'+format(Y(F(p['yExact'])),'.9g')+'\" r=\"3\" fill=\"'+colors[p['series']%3]+'\"/>'\n path.write_text(s+'</g></svg>',encoding='utf8')\ndef fixed_run():\n ap=argparse.ArgumentParser();ap.add_argument('--out',type=Path,default=Path('results'));ap.add_argument('--data-dir',type=Path,default=Path(__file__).resolve().parent.parent/'ml14-sources');args=ap.parse_args();args.out.mkdir(parents=True,exist_ok=True)\n api=FIXED['api'];a=FIXED['args'];summary=[];points=[];xlabel='Declared index';ylabel='Value';legend=['Declared result']\n def metric(name,v,unit='dimensionless'):\n  q=None if v is None else v if isinstance(v,F)else F(v);summary.append(dict(metric=name,value='undefined'if q is None else format(float(q),'.9g'),exactValue=''if q is None else str(q),unit=unit,defined=int(q is not None)))\n def pt(i,x,y,ident='',series=0):\n  points.append(dict(series=series,index=i,xExact=''if x is None else str(F(x)),x='undefined'if x is None else format(float(x),'.9g'),yExact=''if y is None else str(F(y)),y='undefined'if y is None else format(float(y),'.9g'),id=str(ident)))\n if api=='realdata':\n  models=load_sources(args.data_dir);model=models[a['kind']];fit=actual_model(model);rr=fit['rows'];test=scoped(rr,'test');scenarios=[]\n  for name,fp,fn in SCENARIOS:\n   c=choose(rr,{},(fp,fn));scenarios.append(dict(name=name,selection=c));metric(name+'Threshold',c['selectedPolicy']);metric(name+'TestCost',c['evaluation']['meanCost'],'hypothetical cost units/mass')\n  cv=curves(test);cal=calibrate(test,[F(0),F(1,5),F(2,5),F(3,5),F(4,5),F(1)]);metric('testAUC',cv['ROC_AUC']);metric('testAP',cv['averagePrecision']);metric('testBrier',cal['Brier']);metric('eligibleRows',sum(r['eligible']for r in rr),'rows')\n  for i,r in enumerate(test):pt(i,i+1,r['score'],r['id'],0);pt(i,i+1,r['y'],r['id'],1)\n  full=dict(kind=a['kind'],fitMedians=fit['medians'],fitCells=[dict(cell=list(k),mass=n,positive=s,probability=fit['probabilities'][k])for k,(n,s)in fit['cells'].items()],rowsScored=rr,scenarios=scenarios,testCurves=cv,testCalibration=cal);xlabel='Test row, native order';ylabel='Y or probability';legend=['Training-fitted probability','Observed Y']\n else:\n  rr=validated_rows(a['rows']);role=a.get('role','all');frame=scoped(rr,role);cc=cost(a.get('costs'));t=policy(a.get('threshold','1/2'))\n  if api=='metrics':\n   full=metrics(frame,t,cc)\n   for k in ['mass','accuracy','precision','TPR','FPR','F1','Brier','meanCost']:metric(k,full[k],'mass'if k=='mass'else'hypothetical cost units/mass'if k=='meanCost'else'dimensionless')\n   metric('BayesThreshold',full['bayesThreshold'])\n   for i,k in enumerate(['TP','FP','FN','TN']):pt(i,i,full['confusion'][k],k)\n   xlabel='TP / FP / FN / TN positions';ylabel='Analytical mass'\n  elif api=='curves':\n   full=curves(frame)\n   for k in ['ROC_AUC','averagePrecision','PRTrapezoidWithInitialPrecisionOne']:metric(k,full[k])\n   for i,p in enumerate(full['points']):pt(i,p['FPR'],p['TPR'],str(p['policy']))\n   xlabel='False positive rate';ylabel='True positive rate';legend=['Observed ROC operating points']\n  elif api=='choose':\n   full=choose(rr,a,cc);metric('selectedIndex',full['selectedIndex'],'candidate index');metric('minimumCost',None if full['selectedValidation']is None else full['selectedValidation']['meanCost'],'hypothetical cost units/mass');metric('feasible',int(full['selectedIndex']is not None),'indicator')\n   for c in full['candidates']:pt(c['index'],c['index'],c['metrics']['meanCost'],str(c['policy']))\n   xlabel='Validation candidate';ylabel='Assumed cost / mass';legend=['Validation candidate costs']\n  elif api=='calibrate':\n   full=calibrate(frame,[F(str(e))for e in a.get('binEdges',['0','1/5','2/5','3/5','4/5','1'])])\n   for k in ['ECE','Brier','uncertainty','resolution','reliability','withinBinCorrection','BrierIdentityResidual']:metric(k,full[k])\n   for b in full['bins']:pt(b['index'],b['meanPrediction'],b['eventRate'],'bin:'+str(b['index']))\n   xlabel='Bin mean forecast';ylabel='Bin event rate';legend=['Binary-event reliability']\n  elif api=='groups':\n   full=groups(frame,t,cc);metric('overallTPR',full['overall']['TPR']);metric('TPRGap',full['gaps']['TPR']['value']);metric('precisionGap',full['gaps']['precision']['value']);metric('unknownMass',full['unknownGroup']['mass'],'mass');metric('partitionResidual',full['partitionMassResidual'],'mass')\n   for i,g in enumerate(full['groups']):pt(i,i,g['metrics']['TPR'],str(g['group']))\n   xlabel='Declared group position';ylabel='True positive rate';legend=['Known-group TPR']\n  else:raise ValueError('unknown fixed API')\n def csvout(name,rows):\n  with(args.out/name).open('w',encoding='utf8',newline='')as f:w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows)\n csvout('summary.csv',summary);csvout('plot-points.csv',points);fixed_svg(args.out/'plot.svg',points,FIXED['title'],xlabel,ylabel,legend)\n (args.out/'full.json').write_text(json.dumps(dict(api=api,variant=FIXED['variant'],input=FIXED['args'],arithmetic='Python standard-library Fraction, declared fixed example; full web validator/budgets not reproduced',result=serial(full)),ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\n print(json.dumps(dict(api=api,variant=FIXED['variant'],summaryMetrics=len(summary),plotSlots=len(points))))\n\nFIXED={'api': 'calibrate', 'variant': 'two-bins', 'args': {'rows': [{'id': 'a', 'score': '.9', 'y': 1, 'group': 'A'}, {'id': 'b', 'score': '.8', 'y': 1, 'group': 'A'}, {'id': 'c', 'score': '.8', 'y': 0, 'group': 'A'}, {'id': 'd', 'score': '.6', 'y': 0, 'group': 'B'}, {'id': 'e', 'score': '.4', 'y': 1, 'group': 'B'}, {'id': 'f', 'score': '.1', 'y': 0, 'group': 'B'}], 'binEdges': ['0', '1/2', '1']}, 'title': 'Six-card binary-event bins and full Brier identity'}\nif __name__=='__main__':fixed_run()\n",
        "codeText": "#!/usr/bin/env python3\n\"\"\"ML14 standalone exact finite study, Python standard library only.\nInputs: only the three retained factual source CSVs below.\nDerived role/target/group/eligibility columns in those CSVs are NOT inputs.\nRebuilds SHA256 roles, train-only medians/cell scores, validation thresholds,\ntest curves, binary-event reliability and descriptive group ledgers.\nCosts 1/1,1/5,5/1 are hypothetical units, not measured intervention returns.\nThis is author public reproduction, not independent scientific review.\n\"\"\"\n\"\"\"Author Fraction reference, separate from product JavaScript; not independent peer.\"\"\"\nfrom fractions import Fraction as F\nfrom collections import Counter,defaultdict\ndef read(raw):\n rows=[]\n for i,r in enumerate(raw):\n  s=None if r['score']is None else F(str(r['score']));y=None if r['y']is None else F(int(r['y']))if isinstance(r['y'],bool)else F(str(r['y']));w=F(str(r.get('weight','1')));role=r.get('role','evaluation')\n  rows.append(dict(id=r['id'],index=i,score=s,y=y,w=w,role=role,group=r.get('group'),eligible=s is not None and y is not None and w>0 and role!='excluded'))\n return rows\ndef scoped(rows,role='all'):return rows if role=='all'else[r for r in rows if r['role']==role]\ndef divide(n,d):return None if not d else n/d\ndef policy(v):return v if v in ['always-negative','always-positive']else F(str(v))\ndef positive(p,s):return p=='always-positive'if isinstance(p,str)else s>=p\ndef cost(a=None):\n a={}if a is None else a;fp=F(str(a.get('falsePositive','1')));fn=F(str(a.get('falseNegative','1')));return fp,fn\ndef metrics(rows,threshold=F(1,2),cc=(F(1),F(1))):\n counts=dict(TP=F(0),FP=F(0),FN=F(0),TN=F(0));brier=F(0);pred=[]\n for r in rows:\n  if not r['eligible']:pred.append(dict(id=r['id'],index=r['index'],eligible=False,decision=None,probability=None,Brier=None));continue\n  yes=positive(threshold,r['score']);cell=('T'if yes==bool(r['y'])else'F')+('P'if yes else'N');counts[cell]+=r['w'];loss=(r['score']-r['y'])**2;brier+=r['w']*loss;pred.append(dict(id=r['id'],index=r['index'],eligible=True,decision=int(yes),probability=r['score'],Brier=loss))\n TP,FP,FN,TN=[counts[k]for k in ['TP','FP','FN','TN']];P=TP+FN;N=TN+FP;mass=P+N;PP=TP+FP;PN=TN+FN;TPR=divide(TP,P);TNR=divide(TN,N);total=FP*cc[0]+FN*cc[1]\n return dict(confusion=counts,mass=mass,positiveTargetMass=P,negativeTargetMass=N,predictedPositiveMass=PP,predictedNegativeMass=PN,prevalence=divide(P,mass),selectionRate=divide(PP,mass),accuracy=divide(TP+TN,mass),precision=divide(TP,PP),negativePredictiveValue=divide(TN,PN),TPR=TPR,FPR=divide(FP,N),TNR=TNR,FNR=divide(FN,P),F1=divide(2*TP,2*TP+FP+FN),balancedAccuracy=None if TPR is None or TNR is None else(TPR+TNR)/2,Brier=divide(brier,mass),BrierSum=brier,totalCost=total,meanCost=divide(total,mass),predictions=pred,bayesThreshold=divide(cc[0],sum(cc)))\ndef curves(rows):\n use=[r for r in rows if r['eligible']];pos=Counter();neg=Counter()\n for r in use:(pos if r['y']else neg)[r['score']]+=r['w']\n P=sum(pos.values(),F(0));N=sum(neg.values(),F(0));pairs=F(0)\n for a,wa in pos.items():\n  for b,wb in neg.items():pairs+=wa*wb*(F(1)if a>b else F(1,2)if a==b else F(0))\n thresholds=['always-negative']+sorted({r['score']for r in use},reverse=True);points=[];AP=F(0);trap=F(0);lastR=F(0);lastP=F(1)\n for i,p in enumerate(thresholds):\n  m=metrics(rows,p);points.append(dict(policy=p,TP=m['confusion']['TP'],FP=m['confusion']['FP'],FN=m['confusion']['FN'],TN=m['confusion']['TN'],TPR=m['TPR'],FPR=m['FPR'],precision=m['precision'],recall=m['TPR']))\n  if i and P:\n   R=m['TPR'];PP=m['precision'];AP+=(R-lastR)*PP;trap+=(R-lastR)*(PP+lastP)/2;lastR=R;lastP=PP\n return dict(positiveMass=P,negativeMass=N,ROC_AUC=divide(pairs,P*N),weightedConcordantPlusHalfTiedMass=pairs,averagePrecision=AP if P else None,PRTrapezoidWithInitialPrecisionOne=trap if P else None,points=points)\ndef choose(rows,a,cc):\n sr=a.get('selectionRole','validation');er=a.get('evaluationRole','test');rr=scoped(rows,sr);thresholds=[policy(t)for t in a['thresholds']]if'thresholds'in a else['always-negative']+sorted({r['score']for r in rr if r['eligible']},reverse=True)\n candidates=[]\n for i,p in enumerate(thresholds):\n  m=metrics(rr,p,cc);reasons=[]\n  if'minTPR'in a and(m['TPR']is None or m['TPR']<F(str(a['minTPR']))):reasons.append('TPR-undefined'if m['TPR']is None else'below-minTPR')\n  if'maxFPR'in a and(m['FPR']is None or m['FPR']>F(str(a['maxFPR']))):reasons.append('FPR-undefined'if m['FPR']is None else'above-maxFPR')\n  candidates.append(dict(index=i,policy=p,metrics=m,feasible=not reasons,reasons=reasons))\n eligible=[c for c in candidates if c['feasible']];best=min(eligible,key=lambda c:(c['metrics']['meanCost'],c['index']))if eligible else None\n return dict(selectedIndex=None if best is None else best['index'],selectedPolicy=None if best is None else best['policy'],candidates=candidates,selectedValidation=None if best is None else best['metrics'],evaluation=None if best is None or er=='none'else metrics(scoped(rows,er),best['policy'],cc),selectionIDs=[r['id']for r in rr if r['eligible']])\ndef calibrate(rows,ee):\n buckets=[[]for _ in range(len(ee)-1)]\n for r in rows:\n  if not r['eligible']:continue\n  j=next((i for i in range(len(ee)-1)if r['score']<ee[i+1]),len(ee)-2);buckets[j].append(r)\n mass=sum((r['w']for r in rows if r['eligible']),F(0));P=sum((r['w']*r['y']for r in rows if r['eligible']),F(0));pi=divide(P,mass);Brier=None if not mass else sum((r['w']*(r['score']-r['y'])**2 for r in rows if r['eligible']),F(0))/mass;ECE=F(0);reliability=F(0);resolution=F(0);correction=F(0);bins=[]\n for i,rr in enumerate(buckets):\n  w=sum((r['w']for r in rr),F(0));mp=None if not w else sum((r['w']*r['score']for r in rr),F(0))/w;o=None if not w else sum((r['w']*r['y']for r in rr),F(0))/w\n  variance=None if not w else sum((r['w']*(r['score']-mp)**2 for r in rr),F(0))/w\n  covariance=None if not w else sum((r['w']*(r['score']-mp)*(r['y']-o)for r in rr),F(0))/w\n  bc=None if not w else variance-2*covariance;gap=None if not w else mp-o\n  bins.append(dict(index=i,rows=len(rr),mass=w,meanPrediction=mp,eventRate=o,gap=gap,absoluteGap=None if gap is None else abs(gap),scoreVariance=variance,scoreTargetCovariance=covariance,withinBinCorrection=bc,ids=[r['id']for r in rr]))\n  if w:\n   share=w/mass;ECE+=share*abs(gap);reliability+=share*gap**2;resolution+=share*(o-pi)**2;correction+=share*bc\n uncertainty=None if pi is None else pi*(1-pi);residual=None if Brier is None else Brier-(uncertainty-resolution+reliability+correction)\n return dict(mass=mass,prevalence=pi,Brier=Brier,ECE=ECE if mass else None,reliability=reliability if mass else None,resolution=resolution if mass else None,uncertainty=uncertainty,withinBinCorrection=correction if mass else None,BrierIdentityResidual=residual,bins=bins)\ndef typed(v):return type(v).__name__,v\ndef groups(rows,p,cc):\n bins={}\n for r in rows:\n  if r['group']is not None:bins.setdefault(typed(r['group']),[]).append(r)\n gm=[dict(group=rr[0]['group'],metrics=metrics(rr,p,cc))for rr in bins.values()];overall=metrics(rows,p,cc);unknown=metrics([r for r in rows if r['group']is None],p,cc);gaps={}\n for key in ['prevalence','selectionRate','TPR','FPR','precision','accuracy','meanCost']:\n  positive=[g for g in gm if g['metrics']['mass']>0];undefined=[g['group']for g in positive if g['metrics'][key]is None];vals=[g['metrics'][key]for g in positive if g['metrics'][key]is not None]\n  gaps[key]=dict(value=None if len(positive)<2 or undefined else max(vals)-min(vals),undefinedGroups=undefined,comparedPositiveMassGroups=[g['group']for g in positive])\n return dict(overall=overall,groups=gm,unknownGroup=unknown,gaps=gaps,partitionMassResidual=overall['mass']-unknown['mass']-sum((g['metrics']['mass']for g in gm),F(0)))\ndef actual_model(M):\n raw=M['records'];cat=M['categoricalFeatures'];p=len(raw[0]['x']);train=[r for r in raw if r['role']=='train'];medians=[]\n for j in range(p):\n  if j in cat:medians.append(None);continue\n  values=sorted(F(r['x'][j])for r in train);n=len(values);medians.append(values[n//2]if n%2 else(values[n//2-1]+values[n//2])/2)\n def transform(r):return[F(v)if j in cat else F(int(F(v)>medians[j]))for j,v in enumerate(r['x'])]\n counts={}\n for r in train:\n  key=tuple(transform(r));n,s=counts.get(key,(0,0));counts[key]=(n+1,s+int(r['y']))\n probabilities={k:F(s+1,n+2)for k,(n,s)in counts.items()};fallback=F(sum(int(r['y'])for r in train)+1,len(train)+2);scored=[]\n for i,r in enumerate(raw):\n  eligible=r['role']!='excluded';z=transform(r)if eligible else None;key=None if z is None else tuple(z);score=None if not eligible else probabilities.get(key,fallback)\n  scored.append(dict(id=r['id'],index=i,role=r['role'],group=r['group'],y=None if r['y']is None else F(r['y']),score=score,w=F(1),eligible=eligible,transformedX=z,unseenCell=None if not eligible else key not in probabilities))\n return dict(medians=medians,cells=counts,probabilities=probabilities,fallback=fallback,rows=scored,trainIDs=[r['id']for r in train])\n\n\nimport csv,json,hashlib,argparse,datetime\nfrom pathlib import Path\ndef missing(v):return None if v in ['', '.',None]else v\ndef load_sources(folder):\n def read_csv(name):\n  with (folder/name).open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))\n wb=read_csv('actual64-country-four-indicators-original-2024.csv')\n codes=['NY.GDP.PCAP.KD','NY.GDP.MKTP.KD.ZG','FP.CPI.TOTL.ZG','SP.DYN.LE00.IN']\n lookup={(r['countryISO3'],r['indicatorID']):r for r in wb};country=[]\n for i,iso in enumerate(sorted({r['countryISO3']for r in wb}),1):\n  native=[lookup[iso,c]for c in codes];v=[missing(r['originalValueToken'])for r in native]\n  country.append(dict(id=iso+':2024',sourceRow=i,originalID=iso,x=v[:3],y=None if v[3]is None else str(int(F(v[3])>=80)),group=None if v[0]is None else str(int(F(v[0])>=25000)),nativeTarget=v[3],nativeSourceRows=';'.join(r['sourceRow']for r in native)))\n nls=read_csv('actual3613-NLS-original52-fields-groups-roles.csv');person=[]\n for r in nls:\n  y=missing(r['wage76']);person.append(dict(id='person:'+r['sourceRow'],sourceRow=int(r['sourceRow']),originalID=r['id'],x=[missing(r[k])for k in ['ed76','age76','nearc4']],y=None if y is None else str(int(F(y)>=500)),group=missing(r['black']),nativeTarget=y,nativeSourceRows=r['sourceRow']))\n ch=read_csv('actual3150-churn-original14-fields-groups-roles.csv');company=[]\n for r in ch:\n  company.append(dict(id='customer:'+r['sourceRow'],sourceRow=int(r['sourceRow']),originalID='',x=[missing(r[k])for k in ['Call  Failure','Complains','Subscription  Length','Seconds of Use']],y=missing(r['Churn']),group=missing(r['Tariff Plan']),nativeTarget=missing(r['Churn']),nativeSourceRows=r['sourceRow']))\n assert len(wb)==64 and len(country)==16 and len(nls)==3613 and len(ch)==3150\n assert [int(r['sourceRow'])for r in ch if r['Charge  Amount']=='10']==[474,2174,2274,2374,2674,2924,2974]\n models={}\n for kind,raw,cat,units in [('country',country,[],['constant2015USD/person','annualPercent','annualPercent']),('person',person,[2],['years','years','nativeCategory']),('company',company,[1],['count','nativeCategory','months','seconds'])]:\n  order=sorted(range(len(raw)),key=lambda i:(hashlib.sha256(('ML14-role|'+kind+'|'+raw[i]['id']).encode()).hexdigest(),i))\n  for rank,i in enumerate(order):\n   r=raw[i];r['plannedRole']='test'if rank%5==0 else'validation'if rank%5==1 else'train';r['eligible']=None not in r['x']+[r['y']];r['role']=r['plannedRole']if r['eligible']else'excluded';r['weight']='1'\n  models[kind]=dict(records=raw,categoricalFeatures=cat,featureUnits=units)\n assert sum(r['eligible']for r in person)==3017\n return models\n\ndef exact(v):return ''if v is None else str(v)\ndef approx(v):return ''if v is None else format(float(v),'.17g')\ndef scalar_fields(m,keys):\n out={}\n for k in keys:\n  out[k+'Exact']=exact(m[k]);out[k+'Approx']=approx(m[k])\n return out\nCOUNTS=['mass','positiveTargetMass','negativeTargetMass','predictedPositiveMass','predictedNegativeMass']\nRATES=['prevalence','selectionRate','accuracy','precision','negativePredictiveValue','TPR','FPR','TNR','FNR','F1','balancedAccuracy','Brier','BrierSum','totalCost','meanCost']\nSCENARIOS=[('equal',F(1),F(1)),('miss-five',F(1),F(5)),('alarm-five',F(5),F(1))]\ndef packed(v):\n if isinstance(v,F):return str(v)\n if isinstance(v,dict):return{str(k):packed(x)for k,x in v.items()}\n if isinstance(v,(tuple,list)):return[packed(x)for x in v]\n return v\ndef run_study(source,out):\n out.mkdir(parents=True,exist_ok=True);models=load_sources(source)\n tables={name:[]for name in ['predictions','lineage','fit-medians','fit-cells','validation-candidates','test-metrics','test-curves','calibration-bins','group-metrics','chart-points']}\n studies={};charts=[]\n def point(kind,chart,series,index,x,y,xunit='dimensionless',yunit='dimensionless',role='test',tag=''):\n  tables['chart-points'].append(dict(kind=kind,chart=chart,series=series,index=index,xExact=exact(x),xApprox=approx(x),yExact=exact(y),yApprox=approx(y),xUnit=xunit,yUnit=yunit,role=role,tag=tag))\n for kind,M in models.items():\n  fit=actual_model(M);rr=fit['rows'];native=M['records'];test=scoped(rr,'test');cv=curves(test);cal=calibrate(test,[F(0),F(1,5),F(2,5),F(3,5),F(4,5),F(1)]);scenarios=[]\n  for i,r in enumerate(rr):\n   n=native[i];reason=''if r['eligible']else'required-X-or-Y-missing'\n   tables['predictions'].append(dict(kind=kind,id=r['id'],sourceRow=n['sourceRow'],originalID=n['originalID'],plannedRole=n['plannedRole'],role=r['role'],group=''if r['group']is None else r['group'],eligible=int(r['eligible']),targetExact=exact(r['y']),probabilityExact=exact(r['score']),probabilityApprox=approx(r['score']),unseenCell=''if r['unseenCell']is None else int(r['unseenCell']),transformedX=''if r['transformedX']is None else'|'.join(map(str,r['transformedX'])),reason=reason))\n   tables['lineage'].append(dict(kind=kind,id=r['id'],sourceRow=n['sourceRow'],originalID=n['originalID'],nativeSourceRows=n['nativeSourceRows'],rawX='|'.join(''if x is None else x for x in n['x']),nativeTarget=''if n['nativeTarget']is None else n['nativeTarget'],derivedTarget=exact(r['y']),nativeGroup=''if n['group']is None else n['group'],plannedRole=n['plannedRole'],role=r['role'],eligible=int(r['eligible']),analyticalMass='1',reason=reason))\n  for j,v in enumerate(fit['medians']):tables['fit-medians'].append(dict(kind=kind,feature=j,categorical=int(j in M['categoricalFeatures']),fitRows=len(fit['trainIDs']),medianExact=exact(v),medianApprox=approx(v),unit=M['featureUnits'][j]))\n  for key,(mass,pos)in fit['cells'].items():tables['fit-cells'].append(dict(kind=kind,cell='|'.join(map(str,key)),trainingRows=mass,positiveRows=pos,probabilityExact=exact(fit['probabilities'][key]),probabilityApprox=approx(fit['probabilities'][key]),fallbackExact=exact(fit['fallback']),fallbackApprox=approx(fit['fallback'])))\n  for j,p in enumerate(cv['points']):\n   policy=p['policy'];tables['test-curves'].append(dict(kind=kind,point=j,policy=policy if isinstance(policy,str)else'threshold',thresholdExact=''if isinstance(policy,str)else exact(policy),thresholdApprox=''if isinstance(policy,str)else approx(policy),**scalar_fields(p,['TP','FP','FN','TN','TPR','FPR','precision','recall'])))\n   point(kind,'roc','ROC',j,p['FPR'],p['TPR']);point(kind,'pr','PR-observed',j,p['recall'],p['precision'])\n  for b in cal['bins']:\n   tables['calibration-bins'].append(dict(kind=kind,bin=b['index'],leftExact=str(F(b['index'],5)),rightExact=str(F(b['index']+1,5)),rightClosed=int(b['index']==4),rows=b['rows'],ids=';'.join(str(i)for i in b['ids']),**scalar_fields(b,['mass','meanPrediction','eventRate','gap','absoluteGap','scoreVariance','scoreTargetCovariance','withinBinCorrection'])))\n   point(kind,'reliability','Binary event rate',b['index'],b['meanPrediction'],b['eventRate'],tag='rows='+str(b['rows']))\n  for j,r in enumerate(test):\n   point(kind,'test-scores','Training-fitted probability',j,F(j+1),r['score'],'test-row position','probability',tag=r['id'])\n   point(kind,'test-scores','Observed Y',j,F(j+1),r['y'],'test-row position','binary target',tag=r['id'])\n  for name,fp,fn in SCENARIOS:\n   choice=choose(rr,{},(fp,fn));gm=groups(test,choice['selectedPolicy'],(fp,fn));scenarios.append(dict(name=name,costs=dict(falsePositive=fp,falseNegative=fn),selection=choice,groups=gm));ev=choice['evaluation']\n   for c in choice['candidates']:\n    policy=c['policy'];mm=c['metrics'];tables['validation-candidates'].append(dict(kind=kind,scenario=name,candidate=c['index'],selected=int(c['index']==choice['selectedIndex']),policy=policy if isinstance(policy,str)else'threshold',thresholdExact=''if isinstance(policy,str)else exact(policy),thresholdApprox=''if isinstance(policy,str)else approx(policy),feasible=int(c['feasible']),reasons=';'.join(c['reasons']),**{k+'Exact':str(v)for k,v in mm['confusion'].items()},**scalar_fields(mm,COUNTS+['TPR','FPR','precision','meanCost','totalCost'])))\n    point(kind,'validation-cost',name,c['index'],F(c['index']),mm['meanCost'],'candidate index','hypothetical cost units/mass','validation',tag=exact(policy))\n   mm={**ev,**ev['confusion'],**{k:cv[k]for k in ['ROC_AUC','averagePrecision','PRTrapezoidWithInitialPrecisionOne']},**{k:cal[k]for k in ['ECE','reliability','resolution','uncertainty','withinBinCorrection','BrierIdentityResidual']}}\n   for key in ['TP','FP','FN','TN']+COUNTS+RATES+['ROC_AUC','averagePrecision','PRTrapezoidWithInitialPrecisionOne','ECE','reliability','resolution','uncertainty','withinBinCorrection','BrierIdentityResidual']:\n    unit='rows'if key in ['TP','FP','FN','TN']+COUNTS else'hypothetical cost units'if key=='totalCost'else'hypothetical cost units/mass'if key=='meanCost'else'sum squared-probability loss'if key=='BrierSum'else'dimensionless'\n    tables['test-metrics'].append(dict(kind=kind,scenario=name,metric=key,valueExact=exact(mm[key]),valueApprox=approx(mm[key]),unit=unit))\n   allg=[('overall','all',gm['overall'])]+[('known',str(g['group']),g['metrics'])for g in gm['groups']]+[('unknown','',gm['unknownGroup'])]\n   for j,(typ,token,g)in enumerate(allg):\n    tables['group-metrics'].append(dict(kind=kind,scenario=name,groupType=typ,groupToken=token,retainedRows=g.get('retainedRows',sum((r['group']==token)if typ=='known'else(r['group']is None)if typ=='unknown'else True for r in test)),**{k+'Exact':str(v)for k,v in g['confusion'].items()},**scalar_fields(g,COUNTS+RATES)))\n    if typ=='known':point(kind,'group-TPR',name,j-1,F(j-1),g['TPR'],'declared group position','TPR',tag=token)\n  studies[kind]=dict(kind=kind,rows=len(native),eligibleRows=sum(r['eligible']for r in rr),trainingIDs=fit['trainIDs'],fitMedians=fit['medians'],fitCells=[dict(cell=list(k),mass=n,positive=s,probability=fit['probabilities'][k])for k,(n,s)in fit['cells'].items()],fallback=fit['fallback'],scenarios=scenarios,testCurves=cv,testCalibration=cal,rowsScored=rr)\n files=[]\n for name,rows in tables.items():\n  p=out/('computed-'+name+'.csv')\n  with p.open('w',encoding='utf8',newline='')as f:w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows)\n  files.append(dict(file=p.name,rows=len(rows),columns=len(rows[0]),bodyFields=len(rows)*len(rows[0]),sha256=hashlib.sha256(p.read_bytes()).hexdigest()))\n (out/'study.json').write_text(json.dumps(packed(studies),ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\n sourceFiles=[source/n for n in ['actual64-country-four-indicators-original-2024.csv','actual3613-NLS-original52-fields-groups-roles.csv','actual3150-churn-original14-fields-groups-roles.csv']]\n provenance=dict(chapter='ML-14',arithmetic='Python stdlib Fraction exact finite values from original decimal strings; binary64 valueApprox is display only.',inputs=[dict(file=p.name,sha256=hashlib.sha256(p.read_bytes()).hexdigest())for p in sourceFiles],priorEngineModelsScoresOrComputedFilesRead=False,roleRule=\"SHA256('ML14-role|'+kind+'|'+ID),rankmod5=0test/1validation/others train before eligibility\",costs='Hypothetical1/1,1/5,5/1; no causal intervention returns',files=files,observations={k:dict(sourceRows=v['rows'],eligibleRows=v['eligibleRows'],trainingRows=len(v['trainingIDs']))for k,v in studies.items()})\n (out/'provenance.json').write_text(json.dumps(provenance,ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\n print(json.dumps(dict(status='PASS standalone completed',files=len(files),bodyFields=sum(f['bodyFields']for f in files),observations=provenance['observations'])))\n\n# Fixed declared examples: full web budget/option validation is not reproduced.\nfrom html import escape\nimport textwrap\ndef validated_rows(raw):\n for r in raw:\n  assert F(str(r.get('weight','1')))>=0,'negative analytical mass'\n  assert r['score']is None or 0<=F(str(r['score']))<=1,'score outside zero/one'\n  assert r['y']is None or F(str(int(r['y']))if isinstance(r['y'],bool)else str(r['y']))in [0,1],'binary target required'\n return read(raw)\ndef serial(v):\n if isinstance(v,F):return dict(exactFraction=str(v),value=float(v))\n if isinstance(v,(list,tuple)):return[serial(x)for x in v]\n if isinstance(v,dict):return{k:serial(x)for k,x in v.items()}\n return v\ndef fixed_svg(path,points,title,xlabel,ylabel,legend):\n use=[p for p in points if p['xExact']!=''and p['yExact']!=''];xs=[float(F(p['xExact']))for p in use];ys=[float(F(p['yExact']))for p in use]\n xmin=min(xs,default=0);xmax=max(xs,default=1);ymin=min([0]+ys);ymax=max([0]+ys)\n if xmin==xmax:xmin-=.5;xmax+=.5\n if ymin==ymax:ymax=ymin+1\n X=lambda v:85+(float(v)-xmin)/(xmax-xmin)*480;Y=lambda v:278-(float(v)-ymin)/(ymax-ymin)*175\n s='<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"620\" height=\"360\" viewBox=\"0 0 620 360\"><rect width=\"620\" height=\"360\" fill=\"white\"/><g font-family=\"Arial, sans-serif\" font-size=\"13\" fill=\"#17324d\">'\n for i,line in enumerate(textwrap.wrap(title,width=65)):s+='<text x=\"25\" y=\"'+str(24+i*18)+'\">'+escape(line)+'</text>'\n colors=['#176b9b','#b85e18','#437e4d']\n for i,label in enumerate(legend):s+='<circle cx=\"'+str(30+i*250)+'\" cy=\"76\" r=\"4\" fill=\"'+colors[i%3]+'\"/><text x=\"'+str(42+i*250)+'\" y=\"80\">'+escape(label)+'</text>'\n s+='<path d=\"M85 98V278H575\" fill=\"none\" stroke=\"#52677d\"/><text text-anchor=\"middle\" x=\"325\" y=\"338\">'+escape(xlabel)+'</text><text text-anchor=\"middle\" transform=\"translate(21,190) rotate(-90)\">'+escape(ylabel)+'</text>'\n for i in range(5):\n  xx=xmin+(xmax-xmin)*i/4;yy=ymin+(ymax-ymin)*i/4;s+='<text text-anchor=\"middle\" x=\"'+format(X(xx),'.9g')+'\" y=\"305\">'+format(xx,'.4g')+'</text><text text-anchor=\"end\" x=\"77\" y=\"'+format(Y(yy)+4,'.9g')+'\">'+format(yy,'.4g')+'</text>'\n for p in use:s+='<circle cx=\"'+format(X(F(p['xExact'])),'.9g')+'\" cy=\"'+format(Y(F(p['yExact'])),'.9g')+'\" r=\"3\" fill=\"'+colors[p['series']%3]+'\"/>'\n path.write_text(s+'</g></svg>',encoding='utf8')\ndef fixed_run():\n ap=argparse.ArgumentParser();ap.add_argument('--out',type=Path,default=Path('results'));ap.add_argument('--data-dir',type=Path,default=Path(__file__).resolve().parent.parent/'ml14-sources');args=ap.parse_args();args.out.mkdir(parents=True,exist_ok=True)\n api=FIXED['api'];a=FIXED['args'];summary=[];points=[];xlabel='Declared index';ylabel='Value';legend=['Declared result']\n def metric(name,v,unit='dimensionless'):\n  q=None if v is None else v if isinstance(v,F)else F(v);summary.append(dict(metric=name,value='undefined'if q is None else format(float(q),'.9g'),exactValue=''if q is None else str(q),unit=unit,defined=int(q is not None)))\n def pt(i,x,y,ident='',series=0):\n  points.append(dict(series=series,index=i,xExact=''if x is None else str(F(x)),x='undefined'if x is None else format(float(x),'.9g'),yExact=''if y is None else str(F(y)),y='undefined'if y is None else format(float(y),'.9g'),id=str(ident)))\n if api=='realdata':\n  models=load_sources(args.data_dir);model=models[a['kind']];fit=actual_model(model);rr=fit['rows'];test=scoped(rr,'test');scenarios=[]\n  for name,fp,fn in SCENARIOS:\n   c=choose(rr,{},(fp,fn));scenarios.append(dict(name=name,selection=c));metric(name+'Threshold',c['selectedPolicy']);metric(name+'TestCost',c['evaluation']['meanCost'],'hypothetical cost units/mass')\n  cv=curves(test);cal=calibrate(test,[F(0),F(1,5),F(2,5),F(3,5),F(4,5),F(1)]);metric('testAUC',cv['ROC_AUC']);metric('testAP',cv['averagePrecision']);metric('testBrier',cal['Brier']);metric('eligibleRows',sum(r['eligible']for r in rr),'rows')\n  for i,r in enumerate(test):pt(i,i+1,r['score'],r['id'],0);pt(i,i+1,r['y'],r['id'],1)\n  full=dict(kind=a['kind'],fitMedians=fit['medians'],fitCells=[dict(cell=list(k),mass=n,positive=s,probability=fit['probabilities'][k])for k,(n,s)in fit['cells'].items()],rowsScored=rr,scenarios=scenarios,testCurves=cv,testCalibration=cal);xlabel='Test row, native order';ylabel='Y or probability';legend=['Training-fitted probability','Observed Y']\n else:\n  rr=validated_rows(a['rows']);role=a.get('role','all');frame=scoped(rr,role);cc=cost(a.get('costs'));t=policy(a.get('threshold','1/2'))\n  if api=='metrics':\n   full=metrics(frame,t,cc)\n   for k in ['mass','accuracy','precision','TPR','FPR','F1','Brier','meanCost']:metric(k,full[k],'mass'if k=='mass'else'hypothetical cost units/mass'if k=='meanCost'else'dimensionless')\n   metric('BayesThreshold',full['bayesThreshold'])\n   for i,k in enumerate(['TP','FP','FN','TN']):pt(i,i,full['confusion'][k],k)\n   xlabel='TP / FP / FN / TN positions';ylabel='Analytical mass'\n  elif api=='curves':\n   full=curves(frame)\n   for k in ['ROC_AUC','averagePrecision','PRTrapezoidWithInitialPrecisionOne']:metric(k,full[k])\n   for i,p in enumerate(full['points']):pt(i,p['FPR'],p['TPR'],str(p['policy']))\n   xlabel='False positive rate';ylabel='True positive rate';legend=['Observed ROC operating points']\n  elif api=='choose':\n   full=choose(rr,a,cc);metric('selectedIndex',full['selectedIndex'],'candidate index');metric('minimumCost',None if full['selectedValidation']is None else full['selectedValidation']['meanCost'],'hypothetical cost units/mass');metric('feasible',int(full['selectedIndex']is not None),'indicator')\n   for c in full['candidates']:pt(c['index'],c['index'],c['metrics']['meanCost'],str(c['policy']))\n   xlabel='Validation candidate';ylabel='Assumed cost / mass';legend=['Validation candidate costs']\n  elif api=='calibrate':\n   full=calibrate(frame,[F(str(e))for e in a.get('binEdges',['0','1/5','2/5','3/5','4/5','1'])])\n   for k in ['ECE','Brier','uncertainty','resolution','reliability','withinBinCorrection','BrierIdentityResidual']:metric(k,full[k])\n   for b in full['bins']:pt(b['index'],b['meanPrediction'],b['eventRate'],'bin:'+str(b['index']))\n   xlabel='Bin mean forecast';ylabel='Bin event rate';legend=['Binary-event reliability']\n  elif api=='groups':\n   full=groups(frame,t,cc);metric('overallTPR',full['overall']['TPR']);metric('TPRGap',full['gaps']['TPR']['value']);metric('precisionGap',full['gaps']['precision']['value']);metric('unknownMass',full['unknownGroup']['mass'],'mass');metric('partitionResidual',full['partitionMassResidual'],'mass')\n   for i,g in enumerate(full['groups']):pt(i,i,g['metrics']['TPR'],str(g['group']))\n   xlabel='Declared group position';ylabel='True positive rate';legend=['Known-group TPR']\n  else:raise ValueError('unknown fixed API')\n def csvout(name,rows):\n  with(args.out/name).open('w',encoding='utf8',newline='')as f:w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows)\n csvout('summary.csv',summary);csvout('plot-points.csv',points);fixed_svg(args.out/'plot.svg',points,FIXED['title'],xlabel,ylabel,legend)\n (args.out/'full.json').write_text(json.dumps(dict(api=api,variant=FIXED['variant'],input=FIXED['args'],arithmetic='Python standard-library Fraction, declared fixed example; full web validator/budgets not reproduced',result=serial(full)),ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\n print(json.dumps(dict(api=api,variant=FIXED['variant'],summaryMetrics=len(summary),plotSlots=len(points))))\n\nFIXED={'api': 'calibrate', 'variant': 'two-bins', 'args': {'rows': [{'id': 'a', 'score': '.9', 'y': 1, 'group': 'A'}, {'id': 'b', 'score': '.8', 'y': 1, 'group': 'A'}, {'id': 'c', 'score': '.8', 'y': 0, 'group': 'A'}, {'id': 'd', 'score': '.6', 'y': 0, 'group': 'B'}, {'id': 'e', 'score': '.4', 'y': 1, 'group': 'B'}, {'id': 'f', 'score': '.1', 'y': 0, 'group': 'B'}], 'binEdges': ['0', '1/2', '1']}, 'title': 'Six-card binary-event bins and full Brier identity'}\nif __name__=='__main__':fixed_run()\n",
        "input": {
          "rows": [
            {
              "id": "a",
              "score": ".9",
              "y": 1,
              "group": "A"
            },
            {
              "id": "b",
              "score": ".8",
              "y": 1,
              "group": "A"
            },
            {
              "id": "c",
              "score": ".8",
              "y": 0,
              "group": "A"
            },
            {
              "id": "d",
              "score": ".6",
              "y": 0,
              "group": "B"
            },
            {
              "id": "e",
              "score": ".4",
              "y": 1,
              "group": "B"
            },
            {
              "id": "f",
              "score": ".1",
              "y": 0,
              "group": "B"
            }
          ],
          "binEdges": [
            "0",
            "1/2",
            "1"
          ]
        },
        "inputFiles": [],
        "returnCode": 0,
        "expectedFailure": false,
        "stdout": "{\"api\": \"calibrate\", \"variant\": \"two-bins\", \"summaryMetrics\": 7, \"plotSlots\": 2}\n",
        "stderr": "",
        "summary": {
          "ECE": "0.266666667",
          "Brier": "0.236666667",
          "uncertainty": "0.25",
          "resolution": "0",
          "reliability": "0.07125",
          "withinBinCorrection": "-0.0845833333",
          "BrierIdentityResidual": "0"
        },
        "summaryRows": [
          {
            "metric": "ECE",
            "value": "0.266666667",
            "exactValue": "4/15",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "Brier",
            "value": "0.236666667",
            "exactValue": "71/300",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "uncertainty",
            "value": "0.25",
            "exactValue": "1/4",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "resolution",
            "value": "0",
            "exactValue": "0",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "reliability",
            "value": "0.07125",
            "exactValue": "57/800",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "withinBinCorrection",
            "value": "-0.0845833333",
            "exactValue": "-203/2400",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "BrierIdentityResidual",
            "value": "0",
            "exactValue": "0",
            "unit": "dimensionless",
            "defined": "1"
          }
        ],
        "plotPoints": [
          {
            "series": "0",
            "index": "0",
            "xExact": "1/4",
            "x": "0.25",
            "yExact": "1/2",
            "y": "0.5",
            "id": "bin:0"
          },
          {
            "series": "0",
            "index": "1",
            "xExact": "31/40",
            "x": "0.775",
            "yExact": "1/2",
            "y": "0.5",
            "id": "bin:1"
          }
        ],
        "plotFile": "ml14-fixed-results/calibrate-two-bins-python/plot.svg",
        "plotSHA256": "98c8d49be5a018b308267051cb172bebad5c3b1fe810ae8a1d1bc96a96302f0b",
        "files": [
          {
            "file": "ml14-fixed-results/calibrate-two-bins-python/full.json",
            "sha256": "2589276044d481e22deed3c8f423f955e7c967fede04a381a5bfcd5066738ecb",
            "bytes": 3608
          },
          {
            "file": "ml14-fixed-results/calibrate-two-bins-python/plot-points.csv",
            "sha256": "eec96231c57e5fcc013200645c0728dbc8e400f39427bc1fddf51c0d3ed962ec",
            "bytes": 94
          },
          {
            "file": "ml14-fixed-results/calibrate-two-bins-python/plot.svg",
            "sha256": "98c8d49be5a018b308267051cb172bebad5c3b1fe810ae8a1d1bc96a96302f0b",
            "bytes": 1220
          },
          {
            "file": "ml14-fixed-results/calibrate-two-bins-python/summary.csv",
            "sha256": "91ab725fc06d30e33a25e3b0a7820a9f91be72fb7bd0343c4d2af32098fbf47b",
            "bytes": 336
          }
        ],
        "scope": "Actually executed standalone fixed example, Python exact Fraction versus base-R binary64. Approximate R residuals retained; not universal exact arithmetic/web validation/native UI. Source programs read factual3CSV only."
      },
      "reversed-one-bin": {
        "api": "calibrate",
        "variant": "reversed-one-bin",
        "language": "python",
        "title": "ECE zero while reversed forecasts have Brier0.81",
        "codeFile": "ml14-code/calibrate-reversed-one-bin.py",
        "codeSHA256": "f98b7c2f5962c8a0fdc5447d7d39f0e3568d96c64890637d8e8e4dd41ba123fc",
        "code": "#!/usr/bin/env python3\n\"\"\"ML14 standalone exact finite study, Python standard library only.\nInputs: only the three retained factual source CSVs below.\nDerived role/target/group/eligibility columns in those CSVs are NOT inputs.\nRebuilds SHA256 roles, train-only medians/cell scores, validation thresholds,\ntest curves, binary-event reliability and descriptive group ledgers.\nCosts 1/1,1/5,5/1 are hypothetical units, not measured intervention returns.\nThis is author public reproduction, not independent scientific review.\n\"\"\"\n\"\"\"Author Fraction reference, separate from product JavaScript; not independent peer.\"\"\"\nfrom fractions import Fraction as F\nfrom collections import Counter,defaultdict\ndef read(raw):\n rows=[]\n for i,r in enumerate(raw):\n  s=None if r['score']is None else F(str(r['score']));y=None if r['y']is None else F(int(r['y']))if isinstance(r['y'],bool)else F(str(r['y']));w=F(str(r.get('weight','1')));role=r.get('role','evaluation')\n  rows.append(dict(id=r['id'],index=i,score=s,y=y,w=w,role=role,group=r.get('group'),eligible=s is not None and y is not None and w>0 and role!='excluded'))\n return rows\ndef scoped(rows,role='all'):return rows if role=='all'else[r for r in rows if r['role']==role]\ndef divide(n,d):return None if not d else n/d\ndef policy(v):return v if v in ['always-negative','always-positive']else F(str(v))\ndef positive(p,s):return p=='always-positive'if isinstance(p,str)else s>=p\ndef cost(a=None):\n a={}if a is None else a;fp=F(str(a.get('falsePositive','1')));fn=F(str(a.get('falseNegative','1')));return fp,fn\ndef metrics(rows,threshold=F(1,2),cc=(F(1),F(1))):\n counts=dict(TP=F(0),FP=F(0),FN=F(0),TN=F(0));brier=F(0);pred=[]\n for r in rows:\n  if not r['eligible']:pred.append(dict(id=r['id'],index=r['index'],eligible=False,decision=None,probability=None,Brier=None));continue\n  yes=positive(threshold,r['score']);cell=('T'if yes==bool(r['y'])else'F')+('P'if yes else'N');counts[cell]+=r['w'];loss=(r['score']-r['y'])**2;brier+=r['w']*loss;pred.append(dict(id=r['id'],index=r['index'],eligible=True,decision=int(yes),probability=r['score'],Brier=loss))\n TP,FP,FN,TN=[counts[k]for k in ['TP','FP','FN','TN']];P=TP+FN;N=TN+FP;mass=P+N;PP=TP+FP;PN=TN+FN;TPR=divide(TP,P);TNR=divide(TN,N);total=FP*cc[0]+FN*cc[1]\n return dict(confusion=counts,mass=mass,positiveTargetMass=P,negativeTargetMass=N,predictedPositiveMass=PP,predictedNegativeMass=PN,prevalence=divide(P,mass),selectionRate=divide(PP,mass),accuracy=divide(TP+TN,mass),precision=divide(TP,PP),negativePredictiveValue=divide(TN,PN),TPR=TPR,FPR=divide(FP,N),TNR=TNR,FNR=divide(FN,P),F1=divide(2*TP,2*TP+FP+FN),balancedAccuracy=None if TPR is None or TNR is None else(TPR+TNR)/2,Brier=divide(brier,mass),BrierSum=brier,totalCost=total,meanCost=divide(total,mass),predictions=pred,bayesThreshold=divide(cc[0],sum(cc)))\ndef curves(rows):\n use=[r for r in rows if r['eligible']];pos=Counter();neg=Counter()\n for r in use:(pos if r['y']else neg)[r['score']]+=r['w']\n P=sum(pos.values(),F(0));N=sum(neg.values(),F(0));pairs=F(0)\n for a,wa in pos.items():\n  for b,wb in neg.items():pairs+=wa*wb*(F(1)if a>b else F(1,2)if a==b else F(0))\n thresholds=['always-negative']+sorted({r['score']for r in use},reverse=True);points=[];AP=F(0);trap=F(0);lastR=F(0);lastP=F(1)\n for i,p in enumerate(thresholds):\n  m=metrics(rows,p);points.append(dict(policy=p,TP=m['confusion']['TP'],FP=m['confusion']['FP'],FN=m['confusion']['FN'],TN=m['confusion']['TN'],TPR=m['TPR'],FPR=m['FPR'],precision=m['precision'],recall=m['TPR']))\n  if i and P:\n   R=m['TPR'];PP=m['precision'];AP+=(R-lastR)*PP;trap+=(R-lastR)*(PP+lastP)/2;lastR=R;lastP=PP\n return dict(positiveMass=P,negativeMass=N,ROC_AUC=divide(pairs,P*N),weightedConcordantPlusHalfTiedMass=pairs,averagePrecision=AP if P else None,PRTrapezoidWithInitialPrecisionOne=trap if P else None,points=points)\ndef choose(rows,a,cc):\n sr=a.get('selectionRole','validation');er=a.get('evaluationRole','test');rr=scoped(rows,sr);thresholds=[policy(t)for t in a['thresholds']]if'thresholds'in a else['always-negative']+sorted({r['score']for r in rr if r['eligible']},reverse=True)\n candidates=[]\n for i,p in enumerate(thresholds):\n  m=metrics(rr,p,cc);reasons=[]\n  if'minTPR'in a and(m['TPR']is None or m['TPR']<F(str(a['minTPR']))):reasons.append('TPR-undefined'if m['TPR']is None else'below-minTPR')\n  if'maxFPR'in a and(m['FPR']is None or m['FPR']>F(str(a['maxFPR']))):reasons.append('FPR-undefined'if m['FPR']is None else'above-maxFPR')\n  candidates.append(dict(index=i,policy=p,metrics=m,feasible=not reasons,reasons=reasons))\n eligible=[c for c in candidates if c['feasible']];best=min(eligible,key=lambda c:(c['metrics']['meanCost'],c['index']))if eligible else None\n return dict(selectedIndex=None if best is None else best['index'],selectedPolicy=None if best is None else best['policy'],candidates=candidates,selectedValidation=None if best is None else best['metrics'],evaluation=None if best is None or er=='none'else metrics(scoped(rows,er),best['policy'],cc),selectionIDs=[r['id']for r in rr if r['eligible']])\ndef calibrate(rows,ee):\n buckets=[[]for _ in range(len(ee)-1)]\n for r in rows:\n  if not r['eligible']:continue\n  j=next((i for i in range(len(ee)-1)if r['score']<ee[i+1]),len(ee)-2);buckets[j].append(r)\n mass=sum((r['w']for r in rows if r['eligible']),F(0));P=sum((r['w']*r['y']for r in rows if r['eligible']),F(0));pi=divide(P,mass);Brier=None if not mass else sum((r['w']*(r['score']-r['y'])**2 for r in rows if r['eligible']),F(0))/mass;ECE=F(0);reliability=F(0);resolution=F(0);correction=F(0);bins=[]\n for i,rr in enumerate(buckets):\n  w=sum((r['w']for r in rr),F(0));mp=None if not w else sum((r['w']*r['score']for r in rr),F(0))/w;o=None if not w else sum((r['w']*r['y']for r in rr),F(0))/w\n  variance=None if not w else sum((r['w']*(r['score']-mp)**2 for r in rr),F(0))/w\n  covariance=None if not w else sum((r['w']*(r['score']-mp)*(r['y']-o)for r in rr),F(0))/w\n  bc=None if not w else variance-2*covariance;gap=None if not w else mp-o\n  bins.append(dict(index=i,rows=len(rr),mass=w,meanPrediction=mp,eventRate=o,gap=gap,absoluteGap=None if gap is None else abs(gap),scoreVariance=variance,scoreTargetCovariance=covariance,withinBinCorrection=bc,ids=[r['id']for r in rr]))\n  if w:\n   share=w/mass;ECE+=share*abs(gap);reliability+=share*gap**2;resolution+=share*(o-pi)**2;correction+=share*bc\n uncertainty=None if pi is None else pi*(1-pi);residual=None if Brier is None else Brier-(uncertainty-resolution+reliability+correction)\n return dict(mass=mass,prevalence=pi,Brier=Brier,ECE=ECE if mass else None,reliability=reliability if mass else None,resolution=resolution if mass else None,uncertainty=uncertainty,withinBinCorrection=correction if mass else None,BrierIdentityResidual=residual,bins=bins)\ndef typed(v):return type(v).__name__,v\ndef groups(rows,p,cc):\n bins={}\n for r in rows:\n  if r['group']is not None:bins.setdefault(typed(r['group']),[]).append(r)\n gm=[dict(group=rr[0]['group'],metrics=metrics(rr,p,cc))for rr in bins.values()];overall=metrics(rows,p,cc);unknown=metrics([r for r in rows if r['group']is None],p,cc);gaps={}\n for key in ['prevalence','selectionRate','TPR','FPR','precision','accuracy','meanCost']:\n  positive=[g for g in gm if g['metrics']['mass']>0];undefined=[g['group']for g in positive if g['metrics'][key]is None];vals=[g['metrics'][key]for g in positive if g['metrics'][key]is not None]\n  gaps[key]=dict(value=None if len(positive)<2 or undefined else max(vals)-min(vals),undefinedGroups=undefined,comparedPositiveMassGroups=[g['group']for g in positive])\n return dict(overall=overall,groups=gm,unknownGroup=unknown,gaps=gaps,partitionMassResidual=overall['mass']-unknown['mass']-sum((g['metrics']['mass']for g in gm),F(0)))\ndef actual_model(M):\n raw=M['records'];cat=M['categoricalFeatures'];p=len(raw[0]['x']);train=[r for r in raw if r['role']=='train'];medians=[]\n for j in range(p):\n  if j in cat:medians.append(None);continue\n  values=sorted(F(r['x'][j])for r in train);n=len(values);medians.append(values[n//2]if n%2 else(values[n//2-1]+values[n//2])/2)\n def transform(r):return[F(v)if j in cat else F(int(F(v)>medians[j]))for j,v in enumerate(r['x'])]\n counts={}\n for r in train:\n  key=tuple(transform(r));n,s=counts.get(key,(0,0));counts[key]=(n+1,s+int(r['y']))\n probabilities={k:F(s+1,n+2)for k,(n,s)in counts.items()};fallback=F(sum(int(r['y'])for r in train)+1,len(train)+2);scored=[]\n for i,r in enumerate(raw):\n  eligible=r['role']!='excluded';z=transform(r)if eligible else None;key=None if z is None else tuple(z);score=None if not eligible else probabilities.get(key,fallback)\n  scored.append(dict(id=r['id'],index=i,role=r['role'],group=r['group'],y=None if r['y']is None else F(r['y']),score=score,w=F(1),eligible=eligible,transformedX=z,unseenCell=None if not eligible else key not in probabilities))\n return dict(medians=medians,cells=counts,probabilities=probabilities,fallback=fallback,rows=scored,trainIDs=[r['id']for r in train])\n\n\nimport csv,json,hashlib,argparse,datetime\nfrom pathlib import Path\ndef missing(v):return None if v in ['', '.',None]else v\ndef load_sources(folder):\n def read_csv(name):\n  with (folder/name).open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))\n wb=read_csv('actual64-country-four-indicators-original-2024.csv')\n codes=['NY.GDP.PCAP.KD','NY.GDP.MKTP.KD.ZG','FP.CPI.TOTL.ZG','SP.DYN.LE00.IN']\n lookup={(r['countryISO3'],r['indicatorID']):r for r in wb};country=[]\n for i,iso in enumerate(sorted({r['countryISO3']for r in wb}),1):\n  native=[lookup[iso,c]for c in codes];v=[missing(r['originalValueToken'])for r in native]\n  country.append(dict(id=iso+':2024',sourceRow=i,originalID=iso,x=v[:3],y=None if v[3]is None else str(int(F(v[3])>=80)),group=None if v[0]is None else str(int(F(v[0])>=25000)),nativeTarget=v[3],nativeSourceRows=';'.join(r['sourceRow']for r in native)))\n nls=read_csv('actual3613-NLS-original52-fields-groups-roles.csv');person=[]\n for r in nls:\n  y=missing(r['wage76']);person.append(dict(id='person:'+r['sourceRow'],sourceRow=int(r['sourceRow']),originalID=r['id'],x=[missing(r[k])for k in ['ed76','age76','nearc4']],y=None if y is None else str(int(F(y)>=500)),group=missing(r['black']),nativeTarget=y,nativeSourceRows=r['sourceRow']))\n ch=read_csv('actual3150-churn-original14-fields-groups-roles.csv');company=[]\n for r in ch:\n  company.append(dict(id='customer:'+r['sourceRow'],sourceRow=int(r['sourceRow']),originalID='',x=[missing(r[k])for k in ['Call  Failure','Complains','Subscription  Length','Seconds of Use']],y=missing(r['Churn']),group=missing(r['Tariff Plan']),nativeTarget=missing(r['Churn']),nativeSourceRows=r['sourceRow']))\n assert len(wb)==64 and len(country)==16 and len(nls)==3613 and len(ch)==3150\n assert [int(r['sourceRow'])for r in ch if r['Charge  Amount']=='10']==[474,2174,2274,2374,2674,2924,2974]\n models={}\n for kind,raw,cat,units in [('country',country,[],['constant2015USD/person','annualPercent','annualPercent']),('person',person,[2],['years','years','nativeCategory']),('company',company,[1],['count','nativeCategory','months','seconds'])]:\n  order=sorted(range(len(raw)),key=lambda i:(hashlib.sha256(('ML14-role|'+kind+'|'+raw[i]['id']).encode()).hexdigest(),i))\n  for rank,i in enumerate(order):\n   r=raw[i];r['plannedRole']='test'if rank%5==0 else'validation'if rank%5==1 else'train';r['eligible']=None not in r['x']+[r['y']];r['role']=r['plannedRole']if r['eligible']else'excluded';r['weight']='1'\n  models[kind]=dict(records=raw,categoricalFeatures=cat,featureUnits=units)\n assert sum(r['eligible']for r in person)==3017\n return models\n\ndef exact(v):return ''if v is None else str(v)\ndef approx(v):return ''if v is None else format(float(v),'.17g')\ndef scalar_fields(m,keys):\n out={}\n for k in keys:\n  out[k+'Exact']=exact(m[k]);out[k+'Approx']=approx(m[k])\n return out\nCOUNTS=['mass','positiveTargetMass','negativeTargetMass','predictedPositiveMass','predictedNegativeMass']\nRATES=['prevalence','selectionRate','accuracy','precision','negativePredictiveValue','TPR','FPR','TNR','FNR','F1','balancedAccuracy','Brier','BrierSum','totalCost','meanCost']\nSCENARIOS=[('equal',F(1),F(1)),('miss-five',F(1),F(5)),('alarm-five',F(5),F(1))]\ndef packed(v):\n if isinstance(v,F):return str(v)\n if isinstance(v,dict):return{str(k):packed(x)for k,x in v.items()}\n if isinstance(v,(tuple,list)):return[packed(x)for x in v]\n return v\ndef run_study(source,out):\n out.mkdir(parents=True,exist_ok=True);models=load_sources(source)\n tables={name:[]for name in ['predictions','lineage','fit-medians','fit-cells','validation-candidates','test-metrics','test-curves','calibration-bins','group-metrics','chart-points']}\n studies={};charts=[]\n def point(kind,chart,series,index,x,y,xunit='dimensionless',yunit='dimensionless',role='test',tag=''):\n  tables['chart-points'].append(dict(kind=kind,chart=chart,series=series,index=index,xExact=exact(x),xApprox=approx(x),yExact=exact(y),yApprox=approx(y),xUnit=xunit,yUnit=yunit,role=role,tag=tag))\n for kind,M in models.items():\n  fit=actual_model(M);rr=fit['rows'];native=M['records'];test=scoped(rr,'test');cv=curves(test);cal=calibrate(test,[F(0),F(1,5),F(2,5),F(3,5),F(4,5),F(1)]);scenarios=[]\n  for i,r in enumerate(rr):\n   n=native[i];reason=''if r['eligible']else'required-X-or-Y-missing'\n   tables['predictions'].append(dict(kind=kind,id=r['id'],sourceRow=n['sourceRow'],originalID=n['originalID'],plannedRole=n['plannedRole'],role=r['role'],group=''if r['group']is None else r['group'],eligible=int(r['eligible']),targetExact=exact(r['y']),probabilityExact=exact(r['score']),probabilityApprox=approx(r['score']),unseenCell=''if r['unseenCell']is None else int(r['unseenCell']),transformedX=''if r['transformedX']is None else'|'.join(map(str,r['transformedX'])),reason=reason))\n   tables['lineage'].append(dict(kind=kind,id=r['id'],sourceRow=n['sourceRow'],originalID=n['originalID'],nativeSourceRows=n['nativeSourceRows'],rawX='|'.join(''if x is None else x for x in n['x']),nativeTarget=''if n['nativeTarget']is None else n['nativeTarget'],derivedTarget=exact(r['y']),nativeGroup=''if n['group']is None else n['group'],plannedRole=n['plannedRole'],role=r['role'],eligible=int(r['eligible']),analyticalMass='1',reason=reason))\n  for j,v in enumerate(fit['medians']):tables['fit-medians'].append(dict(kind=kind,feature=j,categorical=int(j in M['categoricalFeatures']),fitRows=len(fit['trainIDs']),medianExact=exact(v),medianApprox=approx(v),unit=M['featureUnits'][j]))\n  for key,(mass,pos)in fit['cells'].items():tables['fit-cells'].append(dict(kind=kind,cell='|'.join(map(str,key)),trainingRows=mass,positiveRows=pos,probabilityExact=exact(fit['probabilities'][key]),probabilityApprox=approx(fit['probabilities'][key]),fallbackExact=exact(fit['fallback']),fallbackApprox=approx(fit['fallback'])))\n  for j,p in enumerate(cv['points']):\n   policy=p['policy'];tables['test-curves'].append(dict(kind=kind,point=j,policy=policy if isinstance(policy,str)else'threshold',thresholdExact=''if isinstance(policy,str)else exact(policy),thresholdApprox=''if isinstance(policy,str)else approx(policy),**scalar_fields(p,['TP','FP','FN','TN','TPR','FPR','precision','recall'])))\n   point(kind,'roc','ROC',j,p['FPR'],p['TPR']);point(kind,'pr','PR-observed',j,p['recall'],p['precision'])\n  for b in cal['bins']:\n   tables['calibration-bins'].append(dict(kind=kind,bin=b['index'],leftExact=str(F(b['index'],5)),rightExact=str(F(b['index']+1,5)),rightClosed=int(b['index']==4),rows=b['rows'],ids=';'.join(str(i)for i in b['ids']),**scalar_fields(b,['mass','meanPrediction','eventRate','gap','absoluteGap','scoreVariance','scoreTargetCovariance','withinBinCorrection'])))\n   point(kind,'reliability','Binary event rate',b['index'],b['meanPrediction'],b['eventRate'],tag='rows='+str(b['rows']))\n  for j,r in enumerate(test):\n   point(kind,'test-scores','Training-fitted probability',j,F(j+1),r['score'],'test-row position','probability',tag=r['id'])\n   point(kind,'test-scores','Observed Y',j,F(j+1),r['y'],'test-row position','binary target',tag=r['id'])\n  for name,fp,fn in SCENARIOS:\n   choice=choose(rr,{},(fp,fn));gm=groups(test,choice['selectedPolicy'],(fp,fn));scenarios.append(dict(name=name,costs=dict(falsePositive=fp,falseNegative=fn),selection=choice,groups=gm));ev=choice['evaluation']\n   for c in choice['candidates']:\n    policy=c['policy'];mm=c['metrics'];tables['validation-candidates'].append(dict(kind=kind,scenario=name,candidate=c['index'],selected=int(c['index']==choice['selectedIndex']),policy=policy if isinstance(policy,str)else'threshold',thresholdExact=''if isinstance(policy,str)else exact(policy),thresholdApprox=''if isinstance(policy,str)else approx(policy),feasible=int(c['feasible']),reasons=';'.join(c['reasons']),**{k+'Exact':str(v)for k,v in mm['confusion'].items()},**scalar_fields(mm,COUNTS+['TPR','FPR','precision','meanCost','totalCost'])))\n    point(kind,'validation-cost',name,c['index'],F(c['index']),mm['meanCost'],'candidate index','hypothetical cost units/mass','validation',tag=exact(policy))\n   mm={**ev,**ev['confusion'],**{k:cv[k]for k in ['ROC_AUC','averagePrecision','PRTrapezoidWithInitialPrecisionOne']},**{k:cal[k]for k in ['ECE','reliability','resolution','uncertainty','withinBinCorrection','BrierIdentityResidual']}}\n   for key in ['TP','FP','FN','TN']+COUNTS+RATES+['ROC_AUC','averagePrecision','PRTrapezoidWithInitialPrecisionOne','ECE','reliability','resolution','uncertainty','withinBinCorrection','BrierIdentityResidual']:\n    unit='rows'if key in ['TP','FP','FN','TN']+COUNTS else'hypothetical cost units'if key=='totalCost'else'hypothetical cost units/mass'if key=='meanCost'else'sum squared-probability loss'if key=='BrierSum'else'dimensionless'\n    tables['test-metrics'].append(dict(kind=kind,scenario=name,metric=key,valueExact=exact(mm[key]),valueApprox=approx(mm[key]),unit=unit))\n   allg=[('overall','all',gm['overall'])]+[('known',str(g['group']),g['metrics'])for g in gm['groups']]+[('unknown','',gm['unknownGroup'])]\n   for j,(typ,token,g)in enumerate(allg):\n    tables['group-metrics'].append(dict(kind=kind,scenario=name,groupType=typ,groupToken=token,retainedRows=g.get('retainedRows',sum((r['group']==token)if typ=='known'else(r['group']is None)if typ=='unknown'else True for r in test)),**{k+'Exact':str(v)for k,v in g['confusion'].items()},**scalar_fields(g,COUNTS+RATES)))\n    if typ=='known':point(kind,'group-TPR',name,j-1,F(j-1),g['TPR'],'declared group position','TPR',tag=token)\n  studies[kind]=dict(kind=kind,rows=len(native),eligibleRows=sum(r['eligible']for r in rr),trainingIDs=fit['trainIDs'],fitMedians=fit['medians'],fitCells=[dict(cell=list(k),mass=n,positive=s,probability=fit['probabilities'][k])for k,(n,s)in fit['cells'].items()],fallback=fit['fallback'],scenarios=scenarios,testCurves=cv,testCalibration=cal,rowsScored=rr)\n files=[]\n for name,rows in tables.items():\n  p=out/('computed-'+name+'.csv')\n  with p.open('w',encoding='utf8',newline='')as f:w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows)\n  files.append(dict(file=p.name,rows=len(rows),columns=len(rows[0]),bodyFields=len(rows)*len(rows[0]),sha256=hashlib.sha256(p.read_bytes()).hexdigest()))\n (out/'study.json').write_text(json.dumps(packed(studies),ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\n sourceFiles=[source/n for n in ['actual64-country-four-indicators-original-2024.csv','actual3613-NLS-original52-fields-groups-roles.csv','actual3150-churn-original14-fields-groups-roles.csv']]\n provenance=dict(chapter='ML-14',arithmetic='Python stdlib Fraction exact finite values from original decimal strings; binary64 valueApprox is display only.',inputs=[dict(file=p.name,sha256=hashlib.sha256(p.read_bytes()).hexdigest())for p in sourceFiles],priorEngineModelsScoresOrComputedFilesRead=False,roleRule=\"SHA256('ML14-role|'+kind+'|'+ID),rankmod5=0test/1validation/others train before eligibility\",costs='Hypothetical1/1,1/5,5/1; no causal intervention returns',files=files,observations={k:dict(sourceRows=v['rows'],eligibleRows=v['eligibleRows'],trainingRows=len(v['trainingIDs']))for k,v in studies.items()})\n (out/'provenance.json').write_text(json.dumps(provenance,ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\n print(json.dumps(dict(status='PASS standalone completed',files=len(files),bodyFields=sum(f['bodyFields']for f in files),observations=provenance['observations'])))\n\n# Fixed declared examples: full web budget/option validation is not reproduced.\nfrom html import escape\nimport textwrap\ndef validated_rows(raw):\n for r in raw:\n  assert F(str(r.get('weight','1')))>=0,'negative analytical mass'\n  assert r['score']is None or 0<=F(str(r['score']))<=1,'score outside zero/one'\n  assert r['y']is None or F(str(int(r['y']))if isinstance(r['y'],bool)else str(r['y']))in [0,1],'binary target required'\n return read(raw)\ndef serial(v):\n if isinstance(v,F):return dict(exactFraction=str(v),value=float(v))\n if isinstance(v,(list,tuple)):return[serial(x)for x in v]\n if isinstance(v,dict):return{k:serial(x)for k,x in v.items()}\n return v\ndef fixed_svg(path,points,title,xlabel,ylabel,legend):\n use=[p for p in points if p['xExact']!=''and p['yExact']!=''];xs=[float(F(p['xExact']))for p in use];ys=[float(F(p['yExact']))for p in use]\n xmin=min(xs,default=0);xmax=max(xs,default=1);ymin=min([0]+ys);ymax=max([0]+ys)\n if xmin==xmax:xmin-=.5;xmax+=.5\n if ymin==ymax:ymax=ymin+1\n X=lambda v:85+(float(v)-xmin)/(xmax-xmin)*480;Y=lambda v:278-(float(v)-ymin)/(ymax-ymin)*175\n s='<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"620\" height=\"360\" viewBox=\"0 0 620 360\"><rect width=\"620\" height=\"360\" fill=\"white\"/><g font-family=\"Arial, sans-serif\" font-size=\"13\" fill=\"#17324d\">'\n for i,line in enumerate(textwrap.wrap(title,width=65)):s+='<text x=\"25\" y=\"'+str(24+i*18)+'\">'+escape(line)+'</text>'\n colors=['#176b9b','#b85e18','#437e4d']\n for i,label in enumerate(legend):s+='<circle cx=\"'+str(30+i*250)+'\" cy=\"76\" r=\"4\" fill=\"'+colors[i%3]+'\"/><text x=\"'+str(42+i*250)+'\" y=\"80\">'+escape(label)+'</text>'\n s+='<path d=\"M85 98V278H575\" fill=\"none\" stroke=\"#52677d\"/><text text-anchor=\"middle\" x=\"325\" y=\"338\">'+escape(xlabel)+'</text><text text-anchor=\"middle\" transform=\"translate(21,190) rotate(-90)\">'+escape(ylabel)+'</text>'\n for i in range(5):\n  xx=xmin+(xmax-xmin)*i/4;yy=ymin+(ymax-ymin)*i/4;s+='<text text-anchor=\"middle\" x=\"'+format(X(xx),'.9g')+'\" y=\"305\">'+format(xx,'.4g')+'</text><text text-anchor=\"end\" x=\"77\" y=\"'+format(Y(yy)+4,'.9g')+'\">'+format(yy,'.4g')+'</text>'\n for p in use:s+='<circle cx=\"'+format(X(F(p['xExact'])),'.9g')+'\" cy=\"'+format(Y(F(p['yExact'])),'.9g')+'\" r=\"3\" fill=\"'+colors[p['series']%3]+'\"/>'\n path.write_text(s+'</g></svg>',encoding='utf8')\ndef fixed_run():\n ap=argparse.ArgumentParser();ap.add_argument('--out',type=Path,default=Path('results'));ap.add_argument('--data-dir',type=Path,default=Path(__file__).resolve().parent.parent/'ml14-sources');args=ap.parse_args();args.out.mkdir(parents=True,exist_ok=True)\n api=FIXED['api'];a=FIXED['args'];summary=[];points=[];xlabel='Declared index';ylabel='Value';legend=['Declared result']\n def metric(name,v,unit='dimensionless'):\n  q=None if v is None else v if isinstance(v,F)else F(v);summary.append(dict(metric=name,value='undefined'if q is None else format(float(q),'.9g'),exactValue=''if q is None else str(q),unit=unit,defined=int(q is not None)))\n def pt(i,x,y,ident='',series=0):\n  points.append(dict(series=series,index=i,xExact=''if x is None else str(F(x)),x='undefined'if x is None else format(float(x),'.9g'),yExact=''if y is None else str(F(y)),y='undefined'if y is None else format(float(y),'.9g'),id=str(ident)))\n if api=='realdata':\n  models=load_sources(args.data_dir);model=models[a['kind']];fit=actual_model(model);rr=fit['rows'];test=scoped(rr,'test');scenarios=[]\n  for name,fp,fn in SCENARIOS:\n   c=choose(rr,{},(fp,fn));scenarios.append(dict(name=name,selection=c));metric(name+'Threshold',c['selectedPolicy']);metric(name+'TestCost',c['evaluation']['meanCost'],'hypothetical cost units/mass')\n  cv=curves(test);cal=calibrate(test,[F(0),F(1,5),F(2,5),F(3,5),F(4,5),F(1)]);metric('testAUC',cv['ROC_AUC']);metric('testAP',cv['averagePrecision']);metric('testBrier',cal['Brier']);metric('eligibleRows',sum(r['eligible']for r in rr),'rows')\n  for i,r in enumerate(test):pt(i,i+1,r['score'],r['id'],0);pt(i,i+1,r['y'],r['id'],1)\n  full=dict(kind=a['kind'],fitMedians=fit['medians'],fitCells=[dict(cell=list(k),mass=n,positive=s,probability=fit['probabilities'][k])for k,(n,s)in fit['cells'].items()],rowsScored=rr,scenarios=scenarios,testCurves=cv,testCalibration=cal);xlabel='Test row, native order';ylabel='Y or probability';legend=['Training-fitted probability','Observed Y']\n else:\n  rr=validated_rows(a['rows']);role=a.get('role','all');frame=scoped(rr,role);cc=cost(a.get('costs'));t=policy(a.get('threshold','1/2'))\n  if api=='metrics':\n   full=metrics(frame,t,cc)\n   for k in ['mass','accuracy','precision','TPR','FPR','F1','Brier','meanCost']:metric(k,full[k],'mass'if k=='mass'else'hypothetical cost units/mass'if k=='meanCost'else'dimensionless')\n   metric('BayesThreshold',full['bayesThreshold'])\n   for i,k in enumerate(['TP','FP','FN','TN']):pt(i,i,full['confusion'][k],k)\n   xlabel='TP / FP / FN / TN positions';ylabel='Analytical mass'\n  elif api=='curves':\n   full=curves(frame)\n   for k in ['ROC_AUC','averagePrecision','PRTrapezoidWithInitialPrecisionOne']:metric(k,full[k])\n   for i,p in enumerate(full['points']):pt(i,p['FPR'],p['TPR'],str(p['policy']))\n   xlabel='False positive rate';ylabel='True positive rate';legend=['Observed ROC operating points']\n  elif api=='choose':\n   full=choose(rr,a,cc);metric('selectedIndex',full['selectedIndex'],'candidate index');metric('minimumCost',None if full['selectedValidation']is None else full['selectedValidation']['meanCost'],'hypothetical cost units/mass');metric('feasible',int(full['selectedIndex']is not None),'indicator')\n   for c in full['candidates']:pt(c['index'],c['index'],c['metrics']['meanCost'],str(c['policy']))\n   xlabel='Validation candidate';ylabel='Assumed cost / mass';legend=['Validation candidate costs']\n  elif api=='calibrate':\n   full=calibrate(frame,[F(str(e))for e in a.get('binEdges',['0','1/5','2/5','3/5','4/5','1'])])\n   for k in ['ECE','Brier','uncertainty','resolution','reliability','withinBinCorrection','BrierIdentityResidual']:metric(k,full[k])\n   for b in full['bins']:pt(b['index'],b['meanPrediction'],b['eventRate'],'bin:'+str(b['index']))\n   xlabel='Bin mean forecast';ylabel='Bin event rate';legend=['Binary-event reliability']\n  elif api=='groups':\n   full=groups(frame,t,cc);metric('overallTPR',full['overall']['TPR']);metric('TPRGap',full['gaps']['TPR']['value']);metric('precisionGap',full['gaps']['precision']['value']);metric('unknownMass',full['unknownGroup']['mass'],'mass');metric('partitionResidual',full['partitionMassResidual'],'mass')\n   for i,g in enumerate(full['groups']):pt(i,i,g['metrics']['TPR'],str(g['group']))\n   xlabel='Declared group position';ylabel='True positive rate';legend=['Known-group TPR']\n  else:raise ValueError('unknown fixed API')\n def csvout(name,rows):\n  with(args.out/name).open('w',encoding='utf8',newline='')as f:w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows)\n csvout('summary.csv',summary);csvout('plot-points.csv',points);fixed_svg(args.out/'plot.svg',points,FIXED['title'],xlabel,ylabel,legend)\n (args.out/'full.json').write_text(json.dumps(dict(api=api,variant=FIXED['variant'],input=FIXED['args'],arithmetic='Python standard-library Fraction, declared fixed example; full web validator/budgets not reproduced',result=serial(full)),ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\n print(json.dumps(dict(api=api,variant=FIXED['variant'],summaryMetrics=len(summary),plotSlots=len(points))))\n\nFIXED={'api': 'calibrate', 'variant': 'reversed-one-bin', 'args': {'rows': [{'id': 'r1', 'score': '.1', 'y': 1}, {'id': 'r2', 'score': '.9', 'y': 0}], 'binEdges': ['0', '1']}, 'title': 'ECE zero while reversed forecasts have Brier0.81'}\nif __name__=='__main__':fixed_run()\n",
        "codeText": "#!/usr/bin/env python3\n\"\"\"ML14 standalone exact finite study, Python standard library only.\nInputs: only the three retained factual source CSVs below.\nDerived role/target/group/eligibility columns in those CSVs are NOT inputs.\nRebuilds SHA256 roles, train-only medians/cell scores, validation thresholds,\ntest curves, binary-event reliability and descriptive group ledgers.\nCosts 1/1,1/5,5/1 are hypothetical units, not measured intervention returns.\nThis is author public reproduction, not independent scientific review.\n\"\"\"\n\"\"\"Author Fraction reference, separate from product JavaScript; not independent peer.\"\"\"\nfrom fractions import Fraction as F\nfrom collections import Counter,defaultdict\ndef read(raw):\n rows=[]\n for i,r in enumerate(raw):\n  s=None if r['score']is None else F(str(r['score']));y=None if r['y']is None else F(int(r['y']))if isinstance(r['y'],bool)else F(str(r['y']));w=F(str(r.get('weight','1')));role=r.get('role','evaluation')\n  rows.append(dict(id=r['id'],index=i,score=s,y=y,w=w,role=role,group=r.get('group'),eligible=s is not None and y is not None and w>0 and role!='excluded'))\n return rows\ndef scoped(rows,role='all'):return rows if role=='all'else[r for r in rows if r['role']==role]\ndef divide(n,d):return None if not d else n/d\ndef policy(v):return v if v in ['always-negative','always-positive']else F(str(v))\ndef positive(p,s):return p=='always-positive'if isinstance(p,str)else s>=p\ndef cost(a=None):\n a={}if a is None else a;fp=F(str(a.get('falsePositive','1')));fn=F(str(a.get('falseNegative','1')));return fp,fn\ndef metrics(rows,threshold=F(1,2),cc=(F(1),F(1))):\n counts=dict(TP=F(0),FP=F(0),FN=F(0),TN=F(0));brier=F(0);pred=[]\n for r in rows:\n  if not r['eligible']:pred.append(dict(id=r['id'],index=r['index'],eligible=False,decision=None,probability=None,Brier=None));continue\n  yes=positive(threshold,r['score']);cell=('T'if yes==bool(r['y'])else'F')+('P'if yes else'N');counts[cell]+=r['w'];loss=(r['score']-r['y'])**2;brier+=r['w']*loss;pred.append(dict(id=r['id'],index=r['index'],eligible=True,decision=int(yes),probability=r['score'],Brier=loss))\n TP,FP,FN,TN=[counts[k]for k in ['TP','FP','FN','TN']];P=TP+FN;N=TN+FP;mass=P+N;PP=TP+FP;PN=TN+FN;TPR=divide(TP,P);TNR=divide(TN,N);total=FP*cc[0]+FN*cc[1]\n return dict(confusion=counts,mass=mass,positiveTargetMass=P,negativeTargetMass=N,predictedPositiveMass=PP,predictedNegativeMass=PN,prevalence=divide(P,mass),selectionRate=divide(PP,mass),accuracy=divide(TP+TN,mass),precision=divide(TP,PP),negativePredictiveValue=divide(TN,PN),TPR=TPR,FPR=divide(FP,N),TNR=TNR,FNR=divide(FN,P),F1=divide(2*TP,2*TP+FP+FN),balancedAccuracy=None if TPR is None or TNR is None else(TPR+TNR)/2,Brier=divide(brier,mass),BrierSum=brier,totalCost=total,meanCost=divide(total,mass),predictions=pred,bayesThreshold=divide(cc[0],sum(cc)))\ndef curves(rows):\n use=[r for r in rows if r['eligible']];pos=Counter();neg=Counter()\n for r in use:(pos if r['y']else neg)[r['score']]+=r['w']\n P=sum(pos.values(),F(0));N=sum(neg.values(),F(0));pairs=F(0)\n for a,wa in pos.items():\n  for b,wb in neg.items():pairs+=wa*wb*(F(1)if a>b else F(1,2)if a==b else F(0))\n thresholds=['always-negative']+sorted({r['score']for r in use},reverse=True);points=[];AP=F(0);trap=F(0);lastR=F(0);lastP=F(1)\n for i,p in enumerate(thresholds):\n  m=metrics(rows,p);points.append(dict(policy=p,TP=m['confusion']['TP'],FP=m['confusion']['FP'],FN=m['confusion']['FN'],TN=m['confusion']['TN'],TPR=m['TPR'],FPR=m['FPR'],precision=m['precision'],recall=m['TPR']))\n  if i and P:\n   R=m['TPR'];PP=m['precision'];AP+=(R-lastR)*PP;trap+=(R-lastR)*(PP+lastP)/2;lastR=R;lastP=PP\n return dict(positiveMass=P,negativeMass=N,ROC_AUC=divide(pairs,P*N),weightedConcordantPlusHalfTiedMass=pairs,averagePrecision=AP if P else None,PRTrapezoidWithInitialPrecisionOne=trap if P else None,points=points)\ndef choose(rows,a,cc):\n sr=a.get('selectionRole','validation');er=a.get('evaluationRole','test');rr=scoped(rows,sr);thresholds=[policy(t)for t in a['thresholds']]if'thresholds'in a else['always-negative']+sorted({r['score']for r in rr if r['eligible']},reverse=True)\n candidates=[]\n for i,p in enumerate(thresholds):\n  m=metrics(rr,p,cc);reasons=[]\n  if'minTPR'in a and(m['TPR']is None or m['TPR']<F(str(a['minTPR']))):reasons.append('TPR-undefined'if m['TPR']is None else'below-minTPR')\n  if'maxFPR'in a and(m['FPR']is None or m['FPR']>F(str(a['maxFPR']))):reasons.append('FPR-undefined'if m['FPR']is None else'above-maxFPR')\n  candidates.append(dict(index=i,policy=p,metrics=m,feasible=not reasons,reasons=reasons))\n eligible=[c for c in candidates if c['feasible']];best=min(eligible,key=lambda c:(c['metrics']['meanCost'],c['index']))if eligible else None\n return dict(selectedIndex=None if best is None else best['index'],selectedPolicy=None if best is None else best['policy'],candidates=candidates,selectedValidation=None if best is None else best['metrics'],evaluation=None if best is None or er=='none'else metrics(scoped(rows,er),best['policy'],cc),selectionIDs=[r['id']for r in rr if r['eligible']])\ndef calibrate(rows,ee):\n buckets=[[]for _ in range(len(ee)-1)]\n for r in rows:\n  if not r['eligible']:continue\n  j=next((i for i in range(len(ee)-1)if r['score']<ee[i+1]),len(ee)-2);buckets[j].append(r)\n mass=sum((r['w']for r in rows if r['eligible']),F(0));P=sum((r['w']*r['y']for r in rows if r['eligible']),F(0));pi=divide(P,mass);Brier=None if not mass else sum((r['w']*(r['score']-r['y'])**2 for r in rows if r['eligible']),F(0))/mass;ECE=F(0);reliability=F(0);resolution=F(0);correction=F(0);bins=[]\n for i,rr in enumerate(buckets):\n  w=sum((r['w']for r in rr),F(0));mp=None if not w else sum((r['w']*r['score']for r in rr),F(0))/w;o=None if not w else sum((r['w']*r['y']for r in rr),F(0))/w\n  variance=None if not w else sum((r['w']*(r['score']-mp)**2 for r in rr),F(0))/w\n  covariance=None if not w else sum((r['w']*(r['score']-mp)*(r['y']-o)for r in rr),F(0))/w\n  bc=None if not w else variance-2*covariance;gap=None if not w else mp-o\n  bins.append(dict(index=i,rows=len(rr),mass=w,meanPrediction=mp,eventRate=o,gap=gap,absoluteGap=None if gap is None else abs(gap),scoreVariance=variance,scoreTargetCovariance=covariance,withinBinCorrection=bc,ids=[r['id']for r in rr]))\n  if w:\n   share=w/mass;ECE+=share*abs(gap);reliability+=share*gap**2;resolution+=share*(o-pi)**2;correction+=share*bc\n uncertainty=None if pi is None else pi*(1-pi);residual=None if Brier is None else Brier-(uncertainty-resolution+reliability+correction)\n return dict(mass=mass,prevalence=pi,Brier=Brier,ECE=ECE if mass else None,reliability=reliability if mass else None,resolution=resolution if mass else None,uncertainty=uncertainty,withinBinCorrection=correction if mass else None,BrierIdentityResidual=residual,bins=bins)\ndef typed(v):return type(v).__name__,v\ndef groups(rows,p,cc):\n bins={}\n for r in rows:\n  if r['group']is not None:bins.setdefault(typed(r['group']),[]).append(r)\n gm=[dict(group=rr[0]['group'],metrics=metrics(rr,p,cc))for rr in bins.values()];overall=metrics(rows,p,cc);unknown=metrics([r for r in rows if r['group']is None],p,cc);gaps={}\n for key in ['prevalence','selectionRate','TPR','FPR','precision','accuracy','meanCost']:\n  positive=[g for g in gm if g['metrics']['mass']>0];undefined=[g['group']for g in positive if g['metrics'][key]is None];vals=[g['metrics'][key]for g in positive if g['metrics'][key]is not None]\n  gaps[key]=dict(value=None if len(positive)<2 or undefined else max(vals)-min(vals),undefinedGroups=undefined,comparedPositiveMassGroups=[g['group']for g in positive])\n return dict(overall=overall,groups=gm,unknownGroup=unknown,gaps=gaps,partitionMassResidual=overall['mass']-unknown['mass']-sum((g['metrics']['mass']for g in gm),F(0)))\ndef actual_model(M):\n raw=M['records'];cat=M['categoricalFeatures'];p=len(raw[0]['x']);train=[r for r in raw if r['role']=='train'];medians=[]\n for j in range(p):\n  if j in cat:medians.append(None);continue\n  values=sorted(F(r['x'][j])for r in train);n=len(values);medians.append(values[n//2]if n%2 else(values[n//2-1]+values[n//2])/2)\n def transform(r):return[F(v)if j in cat else F(int(F(v)>medians[j]))for j,v in enumerate(r['x'])]\n counts={}\n for r in train:\n  key=tuple(transform(r));n,s=counts.get(key,(0,0));counts[key]=(n+1,s+int(r['y']))\n probabilities={k:F(s+1,n+2)for k,(n,s)in counts.items()};fallback=F(sum(int(r['y'])for r in train)+1,len(train)+2);scored=[]\n for i,r in enumerate(raw):\n  eligible=r['role']!='excluded';z=transform(r)if eligible else None;key=None if z is None else tuple(z);score=None if not eligible else probabilities.get(key,fallback)\n  scored.append(dict(id=r['id'],index=i,role=r['role'],group=r['group'],y=None if r['y']is None else F(r['y']),score=score,w=F(1),eligible=eligible,transformedX=z,unseenCell=None if not eligible else key not in probabilities))\n return dict(medians=medians,cells=counts,probabilities=probabilities,fallback=fallback,rows=scored,trainIDs=[r['id']for r in train])\n\n\nimport csv,json,hashlib,argparse,datetime\nfrom pathlib import Path\ndef missing(v):return None if v in ['', '.',None]else v\ndef load_sources(folder):\n def read_csv(name):\n  with (folder/name).open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))\n wb=read_csv('actual64-country-four-indicators-original-2024.csv')\n codes=['NY.GDP.PCAP.KD','NY.GDP.MKTP.KD.ZG','FP.CPI.TOTL.ZG','SP.DYN.LE00.IN']\n lookup={(r['countryISO3'],r['indicatorID']):r for r in wb};country=[]\n for i,iso in enumerate(sorted({r['countryISO3']for r in wb}),1):\n  native=[lookup[iso,c]for c in codes];v=[missing(r['originalValueToken'])for r in native]\n  country.append(dict(id=iso+':2024',sourceRow=i,originalID=iso,x=v[:3],y=None if v[3]is None else str(int(F(v[3])>=80)),group=None if v[0]is None else str(int(F(v[0])>=25000)),nativeTarget=v[3],nativeSourceRows=';'.join(r['sourceRow']for r in native)))\n nls=read_csv('actual3613-NLS-original52-fields-groups-roles.csv');person=[]\n for r in nls:\n  y=missing(r['wage76']);person.append(dict(id='person:'+r['sourceRow'],sourceRow=int(r['sourceRow']),originalID=r['id'],x=[missing(r[k])for k in ['ed76','age76','nearc4']],y=None if y is None else str(int(F(y)>=500)),group=missing(r['black']),nativeTarget=y,nativeSourceRows=r['sourceRow']))\n ch=read_csv('actual3150-churn-original14-fields-groups-roles.csv');company=[]\n for r in ch:\n  company.append(dict(id='customer:'+r['sourceRow'],sourceRow=int(r['sourceRow']),originalID='',x=[missing(r[k])for k in ['Call  Failure','Complains','Subscription  Length','Seconds of Use']],y=missing(r['Churn']),group=missing(r['Tariff Plan']),nativeTarget=missing(r['Churn']),nativeSourceRows=r['sourceRow']))\n assert len(wb)==64 and len(country)==16 and len(nls)==3613 and len(ch)==3150\n assert [int(r['sourceRow'])for r in ch if r['Charge  Amount']=='10']==[474,2174,2274,2374,2674,2924,2974]\n models={}\n for kind,raw,cat,units in [('country',country,[],['constant2015USD/person','annualPercent','annualPercent']),('person',person,[2],['years','years','nativeCategory']),('company',company,[1],['count','nativeCategory','months','seconds'])]:\n  order=sorted(range(len(raw)),key=lambda i:(hashlib.sha256(('ML14-role|'+kind+'|'+raw[i]['id']).encode()).hexdigest(),i))\n  for rank,i in enumerate(order):\n   r=raw[i];r['plannedRole']='test'if rank%5==0 else'validation'if rank%5==1 else'train';r['eligible']=None not in r['x']+[r['y']];r['role']=r['plannedRole']if r['eligible']else'excluded';r['weight']='1'\n  models[kind]=dict(records=raw,categoricalFeatures=cat,featureUnits=units)\n assert sum(r['eligible']for r in person)==3017\n return models\n\ndef exact(v):return ''if v is None else str(v)\ndef approx(v):return ''if v is None else format(float(v),'.17g')\ndef scalar_fields(m,keys):\n out={}\n for k in keys:\n  out[k+'Exact']=exact(m[k]);out[k+'Approx']=approx(m[k])\n return out\nCOUNTS=['mass','positiveTargetMass','negativeTargetMass','predictedPositiveMass','predictedNegativeMass']\nRATES=['prevalence','selectionRate','accuracy','precision','negativePredictiveValue','TPR','FPR','TNR','FNR','F1','balancedAccuracy','Brier','BrierSum','totalCost','meanCost']\nSCENARIOS=[('equal',F(1),F(1)),('miss-five',F(1),F(5)),('alarm-five',F(5),F(1))]\ndef packed(v):\n if isinstance(v,F):return str(v)\n if isinstance(v,dict):return{str(k):packed(x)for k,x in v.items()}\n if isinstance(v,(tuple,list)):return[packed(x)for x in v]\n return v\ndef run_study(source,out):\n out.mkdir(parents=True,exist_ok=True);models=load_sources(source)\n tables={name:[]for name in ['predictions','lineage','fit-medians','fit-cells','validation-candidates','test-metrics','test-curves','calibration-bins','group-metrics','chart-points']}\n studies={};charts=[]\n def point(kind,chart,series,index,x,y,xunit='dimensionless',yunit='dimensionless',role='test',tag=''):\n  tables['chart-points'].append(dict(kind=kind,chart=chart,series=series,index=index,xExact=exact(x),xApprox=approx(x),yExact=exact(y),yApprox=approx(y),xUnit=xunit,yUnit=yunit,role=role,tag=tag))\n for kind,M in models.items():\n  fit=actual_model(M);rr=fit['rows'];native=M['records'];test=scoped(rr,'test');cv=curves(test);cal=calibrate(test,[F(0),F(1,5),F(2,5),F(3,5),F(4,5),F(1)]);scenarios=[]\n  for i,r in enumerate(rr):\n   n=native[i];reason=''if r['eligible']else'required-X-or-Y-missing'\n   tables['predictions'].append(dict(kind=kind,id=r['id'],sourceRow=n['sourceRow'],originalID=n['originalID'],plannedRole=n['plannedRole'],role=r['role'],group=''if r['group']is None else r['group'],eligible=int(r['eligible']),targetExact=exact(r['y']),probabilityExact=exact(r['score']),probabilityApprox=approx(r['score']),unseenCell=''if r['unseenCell']is None else int(r['unseenCell']),transformedX=''if r['transformedX']is None else'|'.join(map(str,r['transformedX'])),reason=reason))\n   tables['lineage'].append(dict(kind=kind,id=r['id'],sourceRow=n['sourceRow'],originalID=n['originalID'],nativeSourceRows=n['nativeSourceRows'],rawX='|'.join(''if x is None else x for x in n['x']),nativeTarget=''if n['nativeTarget']is None else n['nativeTarget'],derivedTarget=exact(r['y']),nativeGroup=''if n['group']is None else n['group'],plannedRole=n['plannedRole'],role=r['role'],eligible=int(r['eligible']),analyticalMass='1',reason=reason))\n  for j,v in enumerate(fit['medians']):tables['fit-medians'].append(dict(kind=kind,feature=j,categorical=int(j in M['categoricalFeatures']),fitRows=len(fit['trainIDs']),medianExact=exact(v),medianApprox=approx(v),unit=M['featureUnits'][j]))\n  for key,(mass,pos)in fit['cells'].items():tables['fit-cells'].append(dict(kind=kind,cell='|'.join(map(str,key)),trainingRows=mass,positiveRows=pos,probabilityExact=exact(fit['probabilities'][key]),probabilityApprox=approx(fit['probabilities'][key]),fallbackExact=exact(fit['fallback']),fallbackApprox=approx(fit['fallback'])))\n  for j,p in enumerate(cv['points']):\n   policy=p['policy'];tables['test-curves'].append(dict(kind=kind,point=j,policy=policy if isinstance(policy,str)else'threshold',thresholdExact=''if isinstance(policy,str)else exact(policy),thresholdApprox=''if isinstance(policy,str)else approx(policy),**scalar_fields(p,['TP','FP','FN','TN','TPR','FPR','precision','recall'])))\n   point(kind,'roc','ROC',j,p['FPR'],p['TPR']);point(kind,'pr','PR-observed',j,p['recall'],p['precision'])\n  for b in cal['bins']:\n   tables['calibration-bins'].append(dict(kind=kind,bin=b['index'],leftExact=str(F(b['index'],5)),rightExact=str(F(b['index']+1,5)),rightClosed=int(b['index']==4),rows=b['rows'],ids=';'.join(str(i)for i in b['ids']),**scalar_fields(b,['mass','meanPrediction','eventRate','gap','absoluteGap','scoreVariance','scoreTargetCovariance','withinBinCorrection'])))\n   point(kind,'reliability','Binary event rate',b['index'],b['meanPrediction'],b['eventRate'],tag='rows='+str(b['rows']))\n  for j,r in enumerate(test):\n   point(kind,'test-scores','Training-fitted probability',j,F(j+1),r['score'],'test-row position','probability',tag=r['id'])\n   point(kind,'test-scores','Observed Y',j,F(j+1),r['y'],'test-row position','binary target',tag=r['id'])\n  for name,fp,fn in SCENARIOS:\n   choice=choose(rr,{},(fp,fn));gm=groups(test,choice['selectedPolicy'],(fp,fn));scenarios.append(dict(name=name,costs=dict(falsePositive=fp,falseNegative=fn),selection=choice,groups=gm));ev=choice['evaluation']\n   for c in choice['candidates']:\n    policy=c['policy'];mm=c['metrics'];tables['validation-candidates'].append(dict(kind=kind,scenario=name,candidate=c['index'],selected=int(c['index']==choice['selectedIndex']),policy=policy if isinstance(policy,str)else'threshold',thresholdExact=''if isinstance(policy,str)else exact(policy),thresholdApprox=''if isinstance(policy,str)else approx(policy),feasible=int(c['feasible']),reasons=';'.join(c['reasons']),**{k+'Exact':str(v)for k,v in mm['confusion'].items()},**scalar_fields(mm,COUNTS+['TPR','FPR','precision','meanCost','totalCost'])))\n    point(kind,'validation-cost',name,c['index'],F(c['index']),mm['meanCost'],'candidate index','hypothetical cost units/mass','validation',tag=exact(policy))\n   mm={**ev,**ev['confusion'],**{k:cv[k]for k in ['ROC_AUC','averagePrecision','PRTrapezoidWithInitialPrecisionOne']},**{k:cal[k]for k in ['ECE','reliability','resolution','uncertainty','withinBinCorrection','BrierIdentityResidual']}}\n   for key in ['TP','FP','FN','TN']+COUNTS+RATES+['ROC_AUC','averagePrecision','PRTrapezoidWithInitialPrecisionOne','ECE','reliability','resolution','uncertainty','withinBinCorrection','BrierIdentityResidual']:\n    unit='rows'if key in ['TP','FP','FN','TN']+COUNTS else'hypothetical cost units'if key=='totalCost'else'hypothetical cost units/mass'if key=='meanCost'else'sum squared-probability loss'if key=='BrierSum'else'dimensionless'\n    tables['test-metrics'].append(dict(kind=kind,scenario=name,metric=key,valueExact=exact(mm[key]),valueApprox=approx(mm[key]),unit=unit))\n   allg=[('overall','all',gm['overall'])]+[('known',str(g['group']),g['metrics'])for g in gm['groups']]+[('unknown','',gm['unknownGroup'])]\n   for j,(typ,token,g)in enumerate(allg):\n    tables['group-metrics'].append(dict(kind=kind,scenario=name,groupType=typ,groupToken=token,retainedRows=g.get('retainedRows',sum((r['group']==token)if typ=='known'else(r['group']is None)if typ=='unknown'else True for r in test)),**{k+'Exact':str(v)for k,v in g['confusion'].items()},**scalar_fields(g,COUNTS+RATES)))\n    if typ=='known':point(kind,'group-TPR',name,j-1,F(j-1),g['TPR'],'declared group position','TPR',tag=token)\n  studies[kind]=dict(kind=kind,rows=len(native),eligibleRows=sum(r['eligible']for r in rr),trainingIDs=fit['trainIDs'],fitMedians=fit['medians'],fitCells=[dict(cell=list(k),mass=n,positive=s,probability=fit['probabilities'][k])for k,(n,s)in fit['cells'].items()],fallback=fit['fallback'],scenarios=scenarios,testCurves=cv,testCalibration=cal,rowsScored=rr)\n files=[]\n for name,rows in tables.items():\n  p=out/('computed-'+name+'.csv')\n  with p.open('w',encoding='utf8',newline='')as f:w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows)\n  files.append(dict(file=p.name,rows=len(rows),columns=len(rows[0]),bodyFields=len(rows)*len(rows[0]),sha256=hashlib.sha256(p.read_bytes()).hexdigest()))\n (out/'study.json').write_text(json.dumps(packed(studies),ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\n sourceFiles=[source/n for n in ['actual64-country-four-indicators-original-2024.csv','actual3613-NLS-original52-fields-groups-roles.csv','actual3150-churn-original14-fields-groups-roles.csv']]\n provenance=dict(chapter='ML-14',arithmetic='Python stdlib Fraction exact finite values from original decimal strings; binary64 valueApprox is display only.',inputs=[dict(file=p.name,sha256=hashlib.sha256(p.read_bytes()).hexdigest())for p in sourceFiles],priorEngineModelsScoresOrComputedFilesRead=False,roleRule=\"SHA256('ML14-role|'+kind+'|'+ID),rankmod5=0test/1validation/others train before eligibility\",costs='Hypothetical1/1,1/5,5/1; no causal intervention returns',files=files,observations={k:dict(sourceRows=v['rows'],eligibleRows=v['eligibleRows'],trainingRows=len(v['trainingIDs']))for k,v in studies.items()})\n (out/'provenance.json').write_text(json.dumps(provenance,ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\n print(json.dumps(dict(status='PASS standalone completed',files=len(files),bodyFields=sum(f['bodyFields']for f in files),observations=provenance['observations'])))\n\n# Fixed declared examples: full web budget/option validation is not reproduced.\nfrom html import escape\nimport textwrap\ndef validated_rows(raw):\n for r in raw:\n  assert F(str(r.get('weight','1')))>=0,'negative analytical mass'\n  assert r['score']is None or 0<=F(str(r['score']))<=1,'score outside zero/one'\n  assert r['y']is None or F(str(int(r['y']))if isinstance(r['y'],bool)else str(r['y']))in [0,1],'binary target required'\n return read(raw)\ndef serial(v):\n if isinstance(v,F):return dict(exactFraction=str(v),value=float(v))\n if isinstance(v,(list,tuple)):return[serial(x)for x in v]\n if isinstance(v,dict):return{k:serial(x)for k,x in v.items()}\n return v\ndef fixed_svg(path,points,title,xlabel,ylabel,legend):\n use=[p for p in points if p['xExact']!=''and p['yExact']!=''];xs=[float(F(p['xExact']))for p in use];ys=[float(F(p['yExact']))for p in use]\n xmin=min(xs,default=0);xmax=max(xs,default=1);ymin=min([0]+ys);ymax=max([0]+ys)\n if xmin==xmax:xmin-=.5;xmax+=.5\n if ymin==ymax:ymax=ymin+1\n X=lambda v:85+(float(v)-xmin)/(xmax-xmin)*480;Y=lambda v:278-(float(v)-ymin)/(ymax-ymin)*175\n s='<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"620\" height=\"360\" viewBox=\"0 0 620 360\"><rect width=\"620\" height=\"360\" fill=\"white\"/><g font-family=\"Arial, sans-serif\" font-size=\"13\" fill=\"#17324d\">'\n for i,line in enumerate(textwrap.wrap(title,width=65)):s+='<text x=\"25\" y=\"'+str(24+i*18)+'\">'+escape(line)+'</text>'\n colors=['#176b9b','#b85e18','#437e4d']\n for i,label in enumerate(legend):s+='<circle cx=\"'+str(30+i*250)+'\" cy=\"76\" r=\"4\" fill=\"'+colors[i%3]+'\"/><text x=\"'+str(42+i*250)+'\" y=\"80\">'+escape(label)+'</text>'\n s+='<path d=\"M85 98V278H575\" fill=\"none\" stroke=\"#52677d\"/><text text-anchor=\"middle\" x=\"325\" y=\"338\">'+escape(xlabel)+'</text><text text-anchor=\"middle\" transform=\"translate(21,190) rotate(-90)\">'+escape(ylabel)+'</text>'\n for i in range(5):\n  xx=xmin+(xmax-xmin)*i/4;yy=ymin+(ymax-ymin)*i/4;s+='<text text-anchor=\"middle\" x=\"'+format(X(xx),'.9g')+'\" y=\"305\">'+format(xx,'.4g')+'</text><text text-anchor=\"end\" x=\"77\" y=\"'+format(Y(yy)+4,'.9g')+'\">'+format(yy,'.4g')+'</text>'\n for p in use:s+='<circle cx=\"'+format(X(F(p['xExact'])),'.9g')+'\" cy=\"'+format(Y(F(p['yExact'])),'.9g')+'\" r=\"3\" fill=\"'+colors[p['series']%3]+'\"/>'\n path.write_text(s+'</g></svg>',encoding='utf8')\ndef fixed_run():\n ap=argparse.ArgumentParser();ap.add_argument('--out',type=Path,default=Path('results'));ap.add_argument('--data-dir',type=Path,default=Path(__file__).resolve().parent.parent/'ml14-sources');args=ap.parse_args();args.out.mkdir(parents=True,exist_ok=True)\n api=FIXED['api'];a=FIXED['args'];summary=[];points=[];xlabel='Declared index';ylabel='Value';legend=['Declared result']\n def metric(name,v,unit='dimensionless'):\n  q=None if v is None else v if isinstance(v,F)else F(v);summary.append(dict(metric=name,value='undefined'if q is None else format(float(q),'.9g'),exactValue=''if q is None else str(q),unit=unit,defined=int(q is not None)))\n def pt(i,x,y,ident='',series=0):\n  points.append(dict(series=series,index=i,xExact=''if x is None else str(F(x)),x='undefined'if x is None else format(float(x),'.9g'),yExact=''if y is None else str(F(y)),y='undefined'if y is None else format(float(y),'.9g'),id=str(ident)))\n if api=='realdata':\n  models=load_sources(args.data_dir);model=models[a['kind']];fit=actual_model(model);rr=fit['rows'];test=scoped(rr,'test');scenarios=[]\n  for name,fp,fn in SCENARIOS:\n   c=choose(rr,{},(fp,fn));scenarios.append(dict(name=name,selection=c));metric(name+'Threshold',c['selectedPolicy']);metric(name+'TestCost',c['evaluation']['meanCost'],'hypothetical cost units/mass')\n  cv=curves(test);cal=calibrate(test,[F(0),F(1,5),F(2,5),F(3,5),F(4,5),F(1)]);metric('testAUC',cv['ROC_AUC']);metric('testAP',cv['averagePrecision']);metric('testBrier',cal['Brier']);metric('eligibleRows',sum(r['eligible']for r in rr),'rows')\n  for i,r in enumerate(test):pt(i,i+1,r['score'],r['id'],0);pt(i,i+1,r['y'],r['id'],1)\n  full=dict(kind=a['kind'],fitMedians=fit['medians'],fitCells=[dict(cell=list(k),mass=n,positive=s,probability=fit['probabilities'][k])for k,(n,s)in fit['cells'].items()],rowsScored=rr,scenarios=scenarios,testCurves=cv,testCalibration=cal);xlabel='Test row, native order';ylabel='Y or probability';legend=['Training-fitted probability','Observed Y']\n else:\n  rr=validated_rows(a['rows']);role=a.get('role','all');frame=scoped(rr,role);cc=cost(a.get('costs'));t=policy(a.get('threshold','1/2'))\n  if api=='metrics':\n   full=metrics(frame,t,cc)\n   for k in ['mass','accuracy','precision','TPR','FPR','F1','Brier','meanCost']:metric(k,full[k],'mass'if k=='mass'else'hypothetical cost units/mass'if k=='meanCost'else'dimensionless')\n   metric('BayesThreshold',full['bayesThreshold'])\n   for i,k in enumerate(['TP','FP','FN','TN']):pt(i,i,full['confusion'][k],k)\n   xlabel='TP / FP / FN / TN positions';ylabel='Analytical mass'\n  elif api=='curves':\n   full=curves(frame)\n   for k in ['ROC_AUC','averagePrecision','PRTrapezoidWithInitialPrecisionOne']:metric(k,full[k])\n   for i,p in enumerate(full['points']):pt(i,p['FPR'],p['TPR'],str(p['policy']))\n   xlabel='False positive rate';ylabel='True positive rate';legend=['Observed ROC operating points']\n  elif api=='choose':\n   full=choose(rr,a,cc);metric('selectedIndex',full['selectedIndex'],'candidate index');metric('minimumCost',None if full['selectedValidation']is None else full['selectedValidation']['meanCost'],'hypothetical cost units/mass');metric('feasible',int(full['selectedIndex']is not None),'indicator')\n   for c in full['candidates']:pt(c['index'],c['index'],c['metrics']['meanCost'],str(c['policy']))\n   xlabel='Validation candidate';ylabel='Assumed cost / mass';legend=['Validation candidate costs']\n  elif api=='calibrate':\n   full=calibrate(frame,[F(str(e))for e in a.get('binEdges',['0','1/5','2/5','3/5','4/5','1'])])\n   for k in ['ECE','Brier','uncertainty','resolution','reliability','withinBinCorrection','BrierIdentityResidual']:metric(k,full[k])\n   for b in full['bins']:pt(b['index'],b['meanPrediction'],b['eventRate'],'bin:'+str(b['index']))\n   xlabel='Bin mean forecast';ylabel='Bin event rate';legend=['Binary-event reliability']\n  elif api=='groups':\n   full=groups(frame,t,cc);metric('overallTPR',full['overall']['TPR']);metric('TPRGap',full['gaps']['TPR']['value']);metric('precisionGap',full['gaps']['precision']['value']);metric('unknownMass',full['unknownGroup']['mass'],'mass');metric('partitionResidual',full['partitionMassResidual'],'mass')\n   for i,g in enumerate(full['groups']):pt(i,i,g['metrics']['TPR'],str(g['group']))\n   xlabel='Declared group position';ylabel='True positive rate';legend=['Known-group TPR']\n  else:raise ValueError('unknown fixed API')\n def csvout(name,rows):\n  with(args.out/name).open('w',encoding='utf8',newline='')as f:w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows)\n csvout('summary.csv',summary);csvout('plot-points.csv',points);fixed_svg(args.out/'plot.svg',points,FIXED['title'],xlabel,ylabel,legend)\n (args.out/'full.json').write_text(json.dumps(dict(api=api,variant=FIXED['variant'],input=FIXED['args'],arithmetic='Python standard-library Fraction, declared fixed example; full web validator/budgets not reproduced',result=serial(full)),ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\n print(json.dumps(dict(api=api,variant=FIXED['variant'],summaryMetrics=len(summary),plotSlots=len(points))))\n\nFIXED={'api': 'calibrate', 'variant': 'reversed-one-bin', 'args': {'rows': [{'id': 'r1', 'score': '.1', 'y': 1}, {'id': 'r2', 'score': '.9', 'y': 0}], 'binEdges': ['0', '1']}, 'title': 'ECE zero while reversed forecasts have Brier0.81'}\nif __name__=='__main__':fixed_run()\n",
        "input": {
          "rows": [
            {
              "id": "r1",
              "score": ".1",
              "y": 1
            },
            {
              "id": "r2",
              "score": ".9",
              "y": 0
            }
          ],
          "binEdges": [
            "0",
            "1"
          ]
        },
        "inputFiles": [],
        "returnCode": 0,
        "expectedFailure": false,
        "stdout": "{\"api\": \"calibrate\", \"variant\": \"reversed-one-bin\", \"summaryMetrics\": 7, \"plotSlots\": 1}\n",
        "stderr": "",
        "summary": {
          "ECE": "0",
          "Brier": "0.81",
          "uncertainty": "0.25",
          "resolution": "0",
          "reliability": "0",
          "withinBinCorrection": "0.56",
          "BrierIdentityResidual": "0"
        },
        "summaryRows": [
          {
            "metric": "ECE",
            "value": "0",
            "exactValue": "0",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "Brier",
            "value": "0.81",
            "exactValue": "81/100",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "uncertainty",
            "value": "0.25",
            "exactValue": "1/4",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "resolution",
            "value": "0",
            "exactValue": "0",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "reliability",
            "value": "0",
            "exactValue": "0",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "withinBinCorrection",
            "value": "0.56",
            "exactValue": "14/25",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "BrierIdentityResidual",
            "value": "0",
            "exactValue": "0",
            "unit": "dimensionless",
            "defined": "1"
          }
        ],
        "plotPoints": [
          {
            "series": "0",
            "index": "0",
            "xExact": "1/2",
            "x": "0.5",
            "yExact": "1/2",
            "y": "0.5",
            "id": "bin:0"
          }
        ],
        "plotFile": "ml14-fixed-results/calibrate-reversed-one-bin-python/plot.svg",
        "plotSHA256": "f6073dae32427573bc5edf7e878462b1458f8351137f28bb25cbd09d7271fcbf",
        "files": [
          {
            "file": "ml14-fixed-results/calibrate-reversed-one-bin-python/full.json",
            "sha256": "5bb920fe1cc13d5acba7f6e647f3d85c7a5caad42de1de0d90eb6f66815093c1",
            "bytes": 2102
          },
          {
            "file": "ml14-fixed-results/calibrate-reversed-one-bin-python/plot-points.csv",
            "sha256": "58419e919878a190c95a8ffb61fb40cb0fe888480ea5531381b9edfcf6c76706",
            "bytes": 62
          },
          {
            "file": "ml14-fixed-results/calibrate-reversed-one-bin-python/plot.svg",
            "sha256": "f6073dae32427573bc5edf7e878462b1458f8351137f28bb25cbd09d7271fcbf",
            "bytes": 1157
          },
          {
            "file": "ml14-fixed-results/calibrate-reversed-one-bin-python/summary.csv",
            "sha256": "fca29931bbbd9f487bfbd31b5d3a85b50541876d9a909c00b36edb74d2ee2835",
            "bytes": 292
          }
        ],
        "scope": "Actually executed standalone fixed example, Python exact Fraction versus base-R binary64. Approximate R residuals retained; not universal exact arithmetic/web validation/native UI. Source programs read factual3CSV only."
      }
    },
    "r": {
      "two-bins": {
        "api": "calibrate",
        "variant": "two-bins",
        "language": "r",
        "title": "Six-card binary-event bins and full Brier identity",
        "codeFile": "ml14-code/calibrate-two-bins.R",
        "codeSHA256": "60ebe8e4642fa0795e3752998857bdded614ed0452eb8da62fc03ddc28185401",
        "code": "# ML14 standalone public counterpart, base R only.\n# Inputs are only the three factual CSVs; derived columns/previous model answers unused.\n# Binary64 arithmetic, not arbitrary-precision Fraction. At numerical cost ties\n# within 1e-12 retain the earliest candidate. Exact claims belong to Python/web.\n# SHA256 infrastructure below is reused verbatim from the previous public study.\nargs<-commandArgs(trailingOnly=TRUE);filearg<-grep(\"^--file=\",commandArgs(),value=TRUE)\nhere<-if(dir.exists(\"ml14-sources\"))getwd()else if(length(filearg))dirname(normalizePath(sub(\"^--file=\",\"\",filearg[1])))else getwd()\noption<-function(key,default){i<-match(key,args);if(is.na(i))default else args[i+1]}\nsourceDir<-option(\"--source\",file.path(here,\"ml14-sources\"));outDir<-option(\"--out\",file.path(getwd(),\"ml14-r-results\"));dir.create(outDir,recursive=TRUE,showWarnings=FALSE)\nnum<-function(x){x[x%in%c(\"\",\".\")]<-NA_character_;as.numeric(x)}\nfmt<-function(x)ifelse(is.na(x),\"\",sprintf(\"%.17g\",x))\nratio<-function(a,b)if(b==0)NA_real_ else a/b\nreadnative<-function(name)read.csv(file.path(sourceDir,name),check.names=FALSE,colClasses=\"character\",na.strings=character(),stringsAsFactors=FALSE)\n# Vectorized SHA256 for the short ASCII keys used in this study.\n# Unsigned words use exact integer-valued doubles; bit operations use safe\n# 16-bit halves, avoiding R's reserved signed-INT_MIN/NA representation.\nMOD<-2^32\nxor32<-function(a,b) as.double(bitwXor(as.integer(floor(a/65536)),as.integer(floor(b/65536))))*65536+as.double(bitwXor(as.integer(a%%65536),as.integer(b%%65536)))\nand32<-function(a,b) as.double(bitwAnd(as.integer(floor(a/65536)),as.integer(floor(b/65536))))*65536+as.double(bitwAnd(as.integer(a%%65536),as.integer(b%%65536)))\nrot<-function(x,n) floor(x/2^n)+(x%%2^n)*2^(32-n)\nxor3<-function(a,b,c) xor32(xor32(a,b),c)\nK<-c(0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5,0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967,0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070,0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3,0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2)\nsha256<-function(strings) {\n n<-length(strings);bytes<-matrix(0,n,64)\n for(i in seq_len(n)) {v<-utf8ToInt(strings[i]);stopifnot(length(v)<56,all(v<128));if(length(v)) bytes[i,seq_along(v)]<-v;bytes[i,length(v)+1]<-128;bits<-length(v)*8;bytes[i,61:64]<-c(floor(bits/2^24)%%256,floor(bits/2^16)%%256,floor(bits/256)%%256,bits%%256)}\n w<-matrix(0,n,64)\n for(j in 1:16) {b<-4*(j-1)+1;w[,j]<-bytes[,b]*2^24+bytes[,b+1]*2^16+bytes[,b+2]*256+bytes[,b+3]}\n for(j in 17:64) {s0<-xor3(rot(w[,j-15],7),rot(w[,j-15],18),floor(w[,j-15]/8));s1<-xor3(rot(w[,j-2],17),rot(w[,j-2],19),floor(w[,j-2]/1024));w[,j]<-(w[,j-16]+s0+w[,j-7]+s1)%%MOD}\n init<-c(0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19)\n state<-lapply(init,function(v) rep(v,n));a<-state[[1]];b<-state[[2]];c<-state[[3]];d<-state[[4]];e<-state[[5]];f<-state[[6]];g<-state[[7]];h<-state[[8]]\n for(j in 1:64) {S1<-xor3(rot(e,6),rot(e,11),rot(e,25));ch<-xor32(and32(e,f),and32(MOD-1-e,g));t1<-(h+S1+ch+K[j]+w[,j])%%MOD;S0<-xor3(rot(a,2),rot(a,13),rot(a,22));maj<-xor3(and32(a,b),and32(a,c),and32(b,c));t2<-(S0+maj)%%MOD;h<-g;g<-f;f<-e;e<-(d+t1)%%MOD;d<-c;c<-b;b<-a;a<-(t1+t2)%%MOD}\n end<-list(a,b,c,d,e,f,g,h);hex<-lapply(1:8,function(j){v<-(end[[j]]+init[j])%%MOD;paste0(sprintf(\"%04x\",as.integer(floor(v/65536))),sprintf(\"%04x\",as.integer(v%%65536)))})\n do.call(paste0,hex)\n}\nstopifnot(identical(sha256(c(\"abc\",\"\")),c(\"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad\",\"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855\")))\n\nloadData<-function(){\n wb<-readnative(\"actual64-country-four-indicators-original-2024.csv\");codes<-c(\"NY.GDP.PCAP.KD\",\"NY.GDP.MKTP.KD.ZG\",\"FP.CPI.TOTL.ZG\",\"SP.DYN.LE00.IN\");iso<-sort(unique(wb$countryISO3));stopifnot(nrow(wb)==64,length(iso)==16)\n tokens<-t(vapply(iso,function(s)wb$originalValueToken[match(paste(s,codes),paste(wb$countryISO3,wb$indicatorID))],character(4)));vals<-matrix(num(as.vector(tokens)),nrow=nrow(tokens))\n country<-list(id=paste0(iso,\":2024\"),sourceRow=1:16,originalID=iso,x=vals[,1:3,drop=FALSE],rawX=tokens[,1:3,drop=FALSE],nativeTarget=tokens[,4],y=as.integer(vals[,4]>=80),group=ifelse(is.na(vals[,1]),NA_character_,as.character(as.integer(vals[,1]>=25000))),lineage=vapply(iso,function(s)paste(wb$sourceRow[match(paste(s,codes),paste(wb$countryISO3,wb$indicatorID))],collapse=\";\"),character(1)),cat=integer(),units=c(\"constant2015USD/person\",\"annualPercent\",\"annualPercent\"))\n nls<-readnative(\"actual3613-NLS-original52-fields-groups-roles.csv\");raw<-cbind(nls$ed76,nls$age76,nls$nearc4)\n person<-list(id=paste0(\"person:\",nls$sourceRow),sourceRow=as.integer(nls$sourceRow),originalID=nls$id,x=matrix(num(as.vector(raw)),nrow=nrow(raw)),rawX=raw,nativeTarget=nls$wage76,y=as.integer(num(nls$wage76)>=500),group=ifelse(nls$black%in%c(\"\",\".\"),NA_character_,nls$black),lineage=nls$sourceRow,cat=2L,units=c(\"years\",\"years\",\"nativeCategory\"))\n ch<-readnative(\"actual3150-churn-original14-fields-groups-roles.csv\");raw<-cbind(ch[[\"Call  Failure\"]],ch$Complains,ch[[\"Subscription  Length\"]],ch[[\"Seconds of Use\"]])\n company<-list(id=paste0(\"customer:\",ch$sourceRow),sourceRow=as.integer(ch$sourceRow),originalID=rep(\"\",nrow(ch)),x=matrix(num(as.vector(raw)),nrow=nrow(raw)),rawX=raw,nativeTarget=ch$Churn,y=as.integer(ch$Churn),group=ifelse(ch[[\"Tariff Plan\"]]%in%c(\"\",\".\"),NA_character_,ch[[\"Tariff Plan\"]]),lineage=ch$sourceRow,cat=1L,units=c(\"count\",\"nativeCategory\",\"months\",\"seconds\"))\n stopifnot(nrow(nls)==3613,nrow(ch)==3150,identical(as.integer(ch$sourceRow[ch[[\"Charge  Amount\"]]==\"10\"]),c(474L,2174L,2274L,2374L,2674L,2924L,2974L)))\n result<-list(country=country,person=person,company=company)\n for(k in names(result)){d<-result[[k]];n<-length(d$id);d$eligible<-!is.na(d$y)&rowSums(is.na(d$x))==0;hash<-sha256(paste0(\"ML14-role|\",k,\"|\",d$id));rank<-integer(n);rank[order(hash,seq_len(n))]<-seq_len(n)-1L;d$plannedRole<-ifelse(rank%%5==0,\"test\",ifelse(rank%%5==1,\"validation\",\"train\"));d$role<-ifelse(d$eligible,d$plannedRole,\"excluded\");result[[k]]<-d}\n stopifnot(sum(result$person$eligible)==3017);result\n}\nfitmodel<-function(d){\n ids<-which(d$role==\"train\");p<-ncol(d$x);m<-vapply(seq_len(p),function(j)if((j-1)%in%d$cat)NA_real_ else median(d$x[ids,j]),numeric(1));z<-d$x\n for(j in seq_len(p))if(!((j-1)%in%d$cat))z[,j]<-as.numeric(z[,j]>m[j])\n keys<-apply(z,1,function(v)paste(fmt(v),collapse=\"|\"));lev<-unique(keys[ids]);mass<-vapply(lev,function(k)sum(keys[ids]==k),integer(1));positive<-vapply(lev,function(k)sum(d$y[ids][keys[ids]==k]),integer(1));prob<-(positive+1)/(mass+2);fallback<-(sum(d$y[ids])+1)/(length(ids)+2);pred<-prob[match(keys,lev)];unseen<-is.na(pred);pred[unseen]<-fallback;pred[!d$eligible]<-NA_real_;unseen[!d$eligible]<-NA\n list(ids=ids,medians=m,z=z,keys=keys,lev=lev,mass=mass,positive=positive,prob=prob,fallback=fallback,pred=pred,unseen=unseen)\n}\nmeasure<-function(d,p,ids,t=.5,cost=c(1,1)){\n use<-ids[d$eligible[ids]&!is.na(p[ids])];y<-d$y[use];a<-if(is.character(t))rep(t==\"always-positive\",length(use))else p[use]>=t\n TP<-sum(a&y==1);FP<-sum(a&y==0);FN<-sum(!a&y==1);TN<-sum(!a&y==0);P<-TP+FN;N<-FP+TN;W<-P+N;PP<-TP+FP;PN<-TN+FN;TPR<-ratio(TP,P);TNR<-ratio(TN,N);bs<-sum((p[use]-y)^2);tc<-FP*cost[1]+FN*cost[2]\n list(TP=TP,FP=FP,FN=FN,TN=TN,mass=W,positiveTargetMass=P,negativeTargetMass=N,predictedPositiveMass=PP,predictedNegativeMass=PN,prevalence=ratio(P,W),selectionRate=ratio(PP,W),accuracy=ratio(TP+TN,W),precision=ratio(TP,PP),negativePredictiveValue=ratio(TN,PN),TPR=TPR,FPR=ratio(FP,N),TNR=TNR,FNR=ratio(FN,P),F1=ratio(2*TP,2*TP+FP+FN),balancedAccuracy=if(is.na(TPR)||is.na(TNR))NA_real_ else(TPR+TNR)/2,Brier=ratio(bs,W),BrierSum=bs,totalCost=tc,meanCost=ratio(tc,W))\n}\ncurves<-function(d,p,ids){\n use<-ids[d$eligible[ids]&!is.na(p[ids])];scores<-sort(unique(p[use]),decreasing=TRUE);policies<-c(list(\"always-negative\"),as.list(scores));points<-lapply(policies,function(t){m<-measure(d,p,ids,t);c(list(policy=t),m[c(\"TP\",\"FP\",\"FN\",\"TN\",\"TPR\",\"FPR\",\"precision\")],list(recall=m$TPR))})\n pos<-use[d$y[use]==1];neg<-use[d$y[use]==0];U<-0;for(i in pos)U<-U+sum(p[i]>p[neg])+.5*sum(p[i]==p[neg])\n AP<-0;trap<-0;lastR<-0;lastP<-1\n if(length(pos)&&length(scores))for(j in seq_along(scores)){z<-points[[j+1]];AP<-AP+(z$recall-lastR)*z$precision;trap<-trap+(z$recall-lastR)*(z$precision+lastP)/2;lastR<-z$recall;lastP<-z$precision}\n list(points=points,ROC_AUC=ratio(U,length(pos)*length(neg)),averagePrecision=if(length(pos))AP else NA_real_,PRTrapezoidWithInitialPrecisionOne=if(length(pos))trap else NA_real_)\n}\ncalibrate<-function(d,p,ids){\n use<-ids[d$eligible[ids]&!is.na(p[ids])];W<-length(use);pi<-if(W)mean(d$y[use])else NA_real_;bins<-list();ECE<-rel<-res<-correction<-0\n whichbin<-findInterval(p[use],seq(0,1,.2),rightmost.closed=TRUE,all.inside=TRUE)\n for(b in 1:5){rr<-use[whichbin==b];w<-length(rr);mp<-if(w)mean(p[rr])else NA_real_;o<-if(w)mean(d$y[rr])else NA_real_;variance<-if(w)mean((p[rr]-mp)^2)else NA_real_;covariance<-if(w)mean((p[rr]-mp)*(d$y[rr]-o))else NA_real_;bc<-variance-2*covariance;gap<-mp-o\n  bins[[b]]<-list(mass=w,meanPrediction=mp,eventRate=o,gap=gap,absoluteGap=abs(gap),scoreVariance=variance,scoreTargetCovariance=covariance,withinBinCorrection=bc,rows=w,ids=d$id[rr])\n  if(w){share<-w/W;ECE<-ECE+share*abs(gap);rel<-rel+share*gap^2;res<-res+share*(o-pi)^2;correction<-correction+share*bc}\n };bs<-if(W)mean((p[use]-d$y[use])^2)else NA_real_;unc<-pi*(1-pi)\n list(bins=bins,ECE=if(W)ECE else NA_real_,Brier=bs,reliability=if(W)rel else NA_real_,resolution=if(W)res else NA_real_,uncertainty=unc,withinBinCorrection=if(W)correction else NA_real_,BrierIdentityResidual=bs-(unc-res+rel+correction))\n}\ncounts<-c(\"mass\",\"positiveTargetMass\",\"negativeTargetMass\",\"predictedPositiveMass\",\"predictedNegativeMass\");rates<-c(\"prevalence\",\"selectionRate\",\"accuracy\",\"precision\",\"negativePredictiveValue\",\"TPR\",\"FPR\",\"TNR\",\"FNR\",\"F1\",\"balancedAccuracy\",\"Brier\",\"BrierSum\",\"totalCost\",\"meanCost\")\ntables<-setNames(lapply(1:10,function(i)list()),c(\"predictions\",\"lineage\",\"fit-medians\",\"fit-cells\",\"validation-candidates\",\"test-metrics\",\"test-curves\",\"calibration-bins\",\"group-metrics\",\"chart-points\"))\nadd<-function(name,row)tables[[name]][[length(tables[[name]])+1L]]<<-row\nscalars<-function(m,keys){out<-list();for(k in keys){out[[paste0(k,\"Exact\")]]<-\"\";out[[paste0(k,\"Approx\")]]<-fmt(m[[k]])};out}\ntagrow<-function(kind,...)c(list(kind=kind),list(...))\npoint<-function(kind,chart,series,index,x,y,xunit=\"dimensionless\",yunit=\"dimensionless\",role=\"test\",tag=\"\"){add(\"chart-points\",tagrow(kind,chart=chart,series=series,index=index,xExact=\"\",xApprox=fmt(x),yExact=\"\",yApprox=fmt(y),xUnit=xunit,yUnit=yunit,role=role,tag=tag))}\nstudy<-function(kind,d){\n f<-fitmodel(d);n<-length(d$id);train<-which(d$role==\"train\");validation<-which(d$role==\"validation\");test<-which(d$role==\"test\");p<-f$pred;cv<-curves(d,p,test);cal<-calibrate(d,p,test)\n for(i in seq_len(n)){\n  reason<-if(d$eligible[i])\"\"else\"required-X-or-Y-missing\";transformed<-if(d$eligible[i])paste(fmt(f$z[i,]),collapse=\"|\")else\"\"\n  add(\"predictions\",tagrow(kind,id=d$id[i],sourceRow=d$sourceRow[i],originalID=d$originalID[i],plannedRole=d$plannedRole[i],role=d$role[i],group=ifelse(is.na(d$group[i]),\"\",d$group[i]),eligible=as.integer(d$eligible[i]),targetExact=fmt(d$y[i]),probabilityExact=\"\",probabilityApprox=fmt(p[i]),unseenCell=ifelse(is.na(f$unseen[i]),\"\",as.character(as.integer(f$unseen[i]))),transformedX=transformed,reason=reason))\n  raw<-d$rawX[i,];raw[raw%in%c(\"\",\".\")]<-\"\";nativeY<-d$nativeTarget[i];if(nativeY%in%c(\"\",\".\"))nativeY<-\"\"\n  add(\"lineage\",tagrow(kind,id=d$id[i],sourceRow=d$sourceRow[i],originalID=d$originalID[i],nativeSourceRows=d$lineage[i],rawX=paste(raw,collapse=\"|\"),nativeTarget=nativeY,derivedTarget=fmt(d$y[i]),nativeGroup=ifelse(is.na(d$group[i]),\"\",d$group[i]),plannedRole=d$plannedRole[i],role=d$role[i],eligible=as.integer(d$eligible[i]),analyticalMass=\"1\",reason=reason))\n }\n for(j in seq_len(ncol(d$x)))add(\"fit-medians\",tagrow(kind,feature=j-1,categorical=as.integer((j-1)%in%d$cat),fitRows=length(train),medianExact=\"\",medianApprox=fmt(f$medians[j]),unit=d$units[j]))\n for(j in seq_along(f$lev))add(\"fit-cells\",tagrow(kind,cell=f$lev[j],trainingRows=f$mass[j],positiveRows=f$positive[j],probabilityExact=\"\",probabilityApprox=fmt(f$prob[j]),fallbackExact=\"\",fallbackApprox=fmt(f$fallback)))\n for(j in seq_along(cv$points)){\n  z<-cv$points[[j]];t<-z$policy;add(\"test-curves\",c(tagrow(kind,point=j-1,policy=if(is.character(t))t else\"threshold\",thresholdExact=\"\",thresholdApprox=if(is.character(t))\"\"else fmt(t)),scalars(z,c(\"TP\",\"FP\",\"FN\",\"TN\",\"TPR\",\"FPR\",\"precision\",\"recall\"))))\n  point(kind,\"roc\",\"ROC\",j-1,z$FPR,z$TPR);point(kind,\"pr\",\"PR-observed\",j-1,z$recall,z$precision)\n }\n for(b in 1:5){z<-cal$bins[[b]];add(\"calibration-bins\",c(tagrow(kind,bin=b-1,leftExact=c(\"0\",\"1/5\",\"2/5\",\"3/5\",\"4/5\")[b],rightExact=c(\"1/5\",\"2/5\",\"3/5\",\"4/5\",\"1\")[b],rightClosed=as.integer(b==5),rows=z$rows,ids=paste(z$ids,collapse=\";\")),scalars(z,c(\"mass\",\"meanPrediction\",\"eventRate\",\"gap\",\"absoluteGap\",\"scoreVariance\",\"scoreTargetCovariance\",\"withinBinCorrection\"))));point(kind,\"reliability\",\"Binary event rate\",b-1,z$meanPrediction,z$eventRate,tag=paste0(\"rows=\",z$rows))}\n for(j in seq_along(test)){i<-test[j];point(kind,\"test-scores\",\"Training-fitted probability\",j-1,j,p[i],\"test-row position\",\"probability\",tag=d$id[i]);point(kind,\"test-scores\",\"Observed Y\",j-1,j,d$y[i],\"test-row position\",\"binary target\",tag=d$id[i])}\n scenarioNames<-c(\"equal\",\"miss-five\",\"alarm-five\");costs<-list(c(1,1),c(1,5),c(5,1))\n for(s in 1:3){name<-scenarioNames[s];cost<-costs[[s]];grid<-c(list(\"always-negative\"),as.list(sort(unique(p[validation]),decreasing=TRUE)));candidates<-lapply(grid,function(t)measure(d,p,validation,t,cost));values<-vapply(candidates,function(m)m$meanCost,numeric(1));best<-which(values<=min(values)+1e-12)[1];chosen<-grid[[best]];ev<-measure(d,p,test,chosen,cost)\n  for(j in seq_along(grid)){t<-grid[[j]];m<-candidates[[j]];cell<-setNames(lapply(c(\"TP\",\"FP\",\"FN\",\"TN\"),function(k)fmt(m[[k]])),paste0(c(\"TP\",\"FP\",\"FN\",\"TN\"),\"Exact\"));add(\"validation-candidates\",c(tagrow(kind,scenario=name,candidate=j-1,selected=as.integer(j==best),policy=if(is.character(t))t else\"threshold\",thresholdExact=\"\",thresholdApprox=if(is.character(t))\"\"else fmt(t),feasible=1,reasons=\"\"),cell,scalars(m,c(counts,\"TPR\",\"FPR\",\"precision\",\"meanCost\",\"totalCost\"))));point(kind,\"validation-cost\",name,j-1,j-1,m$meanCost,\"candidate index\",\"hypothetical cost units/mass\",\"validation\",if(is.character(t))t else fmt(t))}\n  m<-c(ev,cv[c(\"ROC_AUC\",\"averagePrecision\",\"PRTrapezoidWithInitialPrecisionOne\")],cal[c(\"ECE\",\"reliability\",\"resolution\",\"uncertainty\",\"withinBinCorrection\",\"BrierIdentityResidual\")])\n  for(k in c(\"TP\",\"FP\",\"FN\",\"TN\",counts,rates,\"ROC_AUC\",\"averagePrecision\",\"PRTrapezoidWithInitialPrecisionOne\",\"ECE\",\"reliability\",\"resolution\",\"uncertainty\",\"withinBinCorrection\",\"BrierIdentityResidual\")){\n   unit<-if(k%in%c(\"TP\",\"FP\",\"FN\",\"TN\",counts))\"rows\"else if(k==\"totalCost\")\"hypothetical cost units\"else if(k==\"meanCost\")\"hypothetical cost units/mass\"else if(k==\"BrierSum\")\"sum squared-probability loss\"else\"dimensionless\"\n   add(\"test-metrics\",tagrow(kind,scenario=name,metric=k,valueExact=\"\",valueApprox=fmt(m[[k]]),unit=unit))\n  }\n  lev<-unique(d$group[test][!is.na(d$group[test])]);sets<-c(list(test),lapply(lev,function(g)test[!is.na(d$group[test])&d$group[test]==g]),list(test[is.na(d$group[test])]))\n  types<-c(\"overall\",rep(\"known\",length(lev)),\"unknown\");tokens<-c(\"all\",lev,\"\")\n  for(j in seq_along(sets)){ids<-sets[[j]];m<-measure(d,p,ids,chosen,cost);cell<-setNames(lapply(c(\"TP\",\"FP\",\"FN\",\"TN\"),function(k)fmt(m[[k]])),paste0(c(\"TP\",\"FP\",\"FN\",\"TN\"),\"Exact\"));add(\"group-metrics\",c(tagrow(kind,scenario=name,groupType=types[j],groupToken=tokens[j],retainedRows=length(ids)),cell,scalars(m,c(counts,rates))));if(types[j]==\"known\")point(kind,\"group-TPR\",name,j-2,j-2,m$TPR,\"declared group position\",\"TPR\",tag=tokens[j])}\n }\n invisible(NULL)\n}\n\n# Fixed finite inputs only; not the complete web input/budget validator.\nqnum<-function(v){if(is.null(v))return(NA_real_);if(is.logical(v))return(as.numeric(v));s<-as.character(v);if(grepl(\"/\",s,fixed=TRUE)){a<-strsplit(s,\"/\",fixed=TRUE)[[1]];return(as.numeric(a[1])/as.numeric(a[2]))};as.numeric(s)}\nrowsG<-function(raw){\n n<-length(raw);get<-function(r,k,default=NULL)if(is.null(r[[k]]))default else r[[k]]\n id<-vapply(raw,function(r)as.character(r$id),character(1));p<-vapply(raw,function(r)qnum(r$score),numeric(1));y<-vapply(raw,function(r)qnum(r$y),numeric(1));w<-vapply(raw,function(r)qnum(get(r,\"weight\",\"1\")),numeric(1));role<-vapply(raw,function(r)get(r,\"role\",\"evaluation\"),character(1));group<-vapply(raw,function(r)as.character(get(r,\"group\",NA_character_)),character(1))\n stopifnot(all(w>=0),all(is.na(p)|(p>=0&p<=1)),all(is.na(y)|y%in%c(0,1)),!anyDuplicated(id));list(id=id,p=p,y=y,w=w,role=role,group=group,eligible=!is.na(p)&!is.na(y)&w>0&role!=\"excluded\")\n}\nscopeG<-function(d,role=\"all\")if(role==\"all\")seq_along(d$id)else which(d$role==role)\nmetricsG<-function(d,ids,t=.5,cost=c(1,1)){\n use<-ids[d$eligible[ids]];p<-d$p[use];y<-d$y[use];w<-d$w[use];a<-if(is.character(t))rep(t==\"always-positive\",length(use))else p>=t\n TP<-sum(w[a&y==1]);FP<-sum(w[a&y==0]);FN<-sum(w[!a&y==1]);TN<-sum(w[!a&y==0]);P<-TP+FN;N<-FP+TN;W<-P+N;PP<-TP+FP;PN<-TN+FN;TPR<-ratio(TP,P);TNR<-ratio(TN,N);bs<-sum(w*(p-y)^2);tc<-FP*cost[1]+FN*cost[2]\n list(confusion=list(TP=TP,FP=FP,FN=FN,TN=TN),mass=W,positiveTargetMass=P,negativeTargetMass=N,predictedPositiveMass=PP,predictedNegativeMass=PN,prevalence=ratio(P,W),selectionRate=ratio(PP,W),accuracy=ratio(TP+TN,W),precision=ratio(TP,PP),negativePredictiveValue=ratio(TN,PN),TPR=TPR,FPR=ratio(FP,N),TNR=TNR,FNR=ratio(FN,P),F1=ratio(2*TP,2*TP+FP+FN),balancedAccuracy=if(is.na(TPR)||is.na(TNR))NA_real_ else(TPR+TNR)/2,Brier=ratio(bs,W),BrierSum=bs,totalCost=tc,meanCost=ratio(tc,W),bayesThreshold=ratio(cost[1],sum(cost)))\n}\ncurvesG<-function(d,ids){\n use<-ids[d$eligible[ids]];grid<-c(list(\"always-negative\"),as.list(sort(unique(d$p[use]),decreasing=TRUE)));points<-lapply(grid,function(t){m<-metricsG(d,ids,t);c(list(policy=t),m$confusion,m[c(\"TPR\",\"FPR\",\"precision\")],list(recall=m$TPR))});pos<-use[d$y[use]==1];neg<-use[d$y[use]==0];P<-sum(d$w[pos]);N<-sum(d$w[neg]);U<-0\n for(i in pos)U<-U+d$w[i]*sum(d$w[neg]*((d$p[i]>d$p[neg])+.5*(d$p[i]==d$p[neg])))\n AP<-trap<-lastR<-0;lastP<-1\n if(P&&length(grid)>1)for(j in 2:length(grid)){z<-points[[j]];AP<-AP+(z$recall-lastR)*z$precision;trap<-trap+(z$recall-lastR)*(z$precision+lastP)/2;lastR<-z$recall;lastP<-z$precision}\n list(points=points,ROC_AUC=ratio(U,P*N),averagePrecision=if(P)AP else NA_real_,PRTrapezoidWithInitialPrecisionOne=if(P)trap else NA_real_)\n}\nchooseG<-function(d,a,cost){\n role<-if(is.null(a$selectionRole))\"validation\"else a$selectionRole;er<-if(is.null(a$evaluationRole))\"test\"else a$evaluationRole;ids<-scopeG(d,role);use<-ids[d$eligible[ids]];stopifnot(length(use)>0);grid<-if(is.null(a$thresholds))c(list(\"always-negative\"),as.list(sort(unique(d$p[use]),decreasing=TRUE)))else lapply(a$thresholds,function(t)if(t%in%c(\"always-negative\",\"always-positive\"))t else qnum(t))\n candidates<-lapply(seq_along(grid),function(j){m<-metricsG(d,ids,grid[[j]],cost);feasible<-TRUE;if(!is.null(a$minTPR))feasible<-feasible&&!is.na(m$TPR)&&m$TPR>=qnum(a$minTPR);if(!is.null(a$maxFPR))feasible<-feasible&&!is.na(m$FPR)&&m$FPR<=qnum(a$maxFPR);list(index=j-1,policy=grid[[j]],metrics=m,feasible=feasible)})\n good<-which(vapply(candidates,function(c)c$feasible,logical(1)));best<-NA_integer_;if(length(good)){v<-vapply(candidates[good],function(c)c$metrics$meanCost,numeric(1));best<-good[which(v<=min(v)+1e-12)[1]]}\n list(selectedIndex=if(is.na(best))NA_integer_ else best-1,selectedPolicy=if(is.na(best))NULL else grid[[best]],selectedValidation=if(is.na(best))NULL else candidates[[best]]$metrics,candidates=candidates,evaluation=if(is.na(best)||er==\"none\")NULL else metricsG(d,scopeG(d,er),grid[[best]],cost))\n}\ncalibrateG<-function(d,ids,edges){\n use<-ids[d$eligible[ids]];W<-sum(d$w[use]);pi<-ratio(sum(d$w[use]*d$y[use]),W);bins<-list();ECE<-rel<-res<-correction<-0;assign<-findInterval(d$p[use],edges,rightmost.closed=TRUE,all.inside=TRUE)\n for(b in seq_len(length(edges)-1)){rr<-use[assign==b];w<-sum(d$w[rr]);mp<-ratio(sum(d$w[rr]*d$p[rr]),w);o<-ratio(sum(d$w[rr]*d$y[rr]),w);variance<-if(w)sum(d$w[rr]*(d$p[rr]-mp)^2)/w else NA_real_;covariance<-if(w)sum(d$w[rr]*(d$p[rr]-mp)*(d$y[rr]-o))/w else NA_real_;bc<-variance-2*covariance;gap<-mp-o;bins[[b]]<-list(index=b-1,mass=w,meanPrediction=mp,eventRate=o,scoreVariance=variance,scoreTargetCovariance=covariance,withinBinCorrection=bc,ids=d$id[rr])\n  if(w){s<-w/W;ECE<-ECE+s*abs(gap);rel<-rel+s*gap^2;res<-res+s*(o-pi)^2;correction<-correction+s*bc}\n };bs<-ratio(sum(d$w[use]*(d$p[use]-d$y[use])^2),W);unc<-pi*(1-pi);list(bins=bins,Brier=bs,ECE=if(W)ECE else NA_real_,uncertainty=unc,reliability=if(W)rel else NA_real_,resolution=if(W)res else NA_real_,withinBinCorrection=if(W)correction else NA_real_,BrierIdentityResidual=bs-(unc-res+rel+correction))\n}\ngroupsG<-function(d,ids,t,cost){\n lev<-unique(d$group[ids][!is.na(d$group[ids])]);groups<-lapply(lev,function(g)list(group=g,metrics=metricsG(d,ids[!is.na(d$group[ids])&d$group[ids]==g],t,cost)));overall<-metricsG(d,ids,t,cost);unknown<-metricsG(d,ids[is.na(d$group[ids])],t,cost);gaps<-list()\n for(k in c(\"prevalence\",\"selectionRate\",\"TPR\",\"FPR\",\"precision\",\"accuracy\",\"meanCost\")){use<-Filter(function(g)g$metrics$mass>0,groups);v<-vapply(use,function(g)g$metrics[[k]],numeric(1));gaps[[k]]<-if(length(use)<2||anyNA(v))NA_real_ else max(v)-min(v)}\n list(overall=overall,groups=groups,unknownGroup=unknown,gaps=gaps,partitionMassResidual=overall$mass-unknown$mass-sum(vapply(groups,function(g)g$metrics$mass,numeric(1))))\n}\nsvgFixed<-function(file,points,title,xlabel,ylabel,legend){\n finite<-points[points$y!=\"undefined\"&points$x!=\"undefined\",,drop=FALSE];x<-as.numeric(finite$x);y<-as.numeric(finite$y);xmin<-if(length(x))min(x)else 0;xmax<-if(length(x))max(x)else 1;ymin<-min(c(0,y));ymax<-max(c(0,y));if(xmin==xmax){xmin<-xmin-.5;xmax<-xmax+.5};if(ymin==ymax)ymax<-ymin+1;X<-function(v)85+(v-xmin)/(xmax-xmin)*480;Y<-function(v)278-(v-ymin)/(ymax-ymin)*175\n esc<-function(s){s<-gsub(\"&\",\"&amp;\",s,fixed=TRUE);s<-gsub(\"<\",\"&lt;\",s,fixed=TRUE);gsub(\">\",\"&gt;\",s,fixed=TRUE)};s<-'<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"620\" height=\"360\" viewBox=\"0 0 620 360\"><rect width=\"620\" height=\"360\" fill=\"white\"/><g font-family=\"Arial, sans-serif\" font-size=\"13\" fill=\"#17324d\">'\n lines<-strwrap(title,width=65);for(i in seq_along(lines))s<-paste0(s,'<text x=\"25\" y=\"',24+(i-1)*18,'\">',esc(lines[i]),'</text>');colors<-c(\"#176b9b\",\"#b85e18\",\"#437e4d\")\n for(i in seq_along(legend))s<-paste0(s,'<circle cx=\"',30+(i-1)*250,'\" cy=\"76\" r=\"4\" fill=\"',colors[(i-1)%%3+1],'\"/><text x=\"',42+(i-1)*250,'\" y=\"80\">',esc(legend[i]),'</text>')\n s<-paste0(s,'<path d=\"M85 98V278H575\" fill=\"none\" stroke=\"#52677d\"/><text text-anchor=\"middle\" x=\"325\" y=\"338\">',esc(xlabel),'</text><text text-anchor=\"middle\" transform=\"translate(21,190) rotate(-90)\">',esc(ylabel),'</text>')\n for(i in 0:4){xx<-xmin+(xmax-xmin)*i/4;yy<-ymin+(ymax-ymin)*i/4;s<-paste0(s,'<text text-anchor=\"middle\" x=\"',sprintf(\"%.9g\",X(xx)),'\" y=\"305\">',sprintf(\"%.4g\",xx),'</text><text text-anchor=\"end\" x=\"77\" y=\"',sprintf(\"%.9g\",Y(yy)+4),'\">',sprintf(\"%.4g\",yy),'</text>')}\n for(i in seq_len(nrow(finite)))s<-paste0(s,'<circle cx=\"',sprintf(\"%.9g\",X(x[i])),'\" cy=\"',sprintf(\"%.9g\",Y(y[i])),'\" r=\"3\" fill=\"',colors[as.integer(finite$series[i])%%3+1],'\"/>');writeLines(paste0(s,'</g></svg>'),file,useBytes=TRUE)\n}\nfixedRun<-function(){\n api<-FIXED$api;a<-FIXED$args;summary<-list();points<-list();xlabel<-\"Declared index\";ylabel<-\"Value\";legend<-\"Declared result\"\n metric<-function(name,v,unit=\"dimensionless\"){if(is.null(v))v<-NA_real_;summary[[length(summary)+1L]]<<-data.frame(metric=name,value=if(is.na(v))\"undefined\"else sprintf(\"%.9g\",v),exactValue=\"\",unit=unit,defined=as.integer(!is.na(v)),stringsAsFactors=FALSE)}\n pt<-function(i,x,y,id=\"\",series=0){points[[length(points)+1L]]<<-data.frame(series=series,index=i,xExact=\"\",x=if(is.na(x))\"undefined\"else sprintf(\"%.9g\",x),yExact=\"\",y=if(is.na(y))\"undefined\"else sprintf(\"%.9g\",y),id=as.character(id),stringsAsFactors=FALSE)}\n if(api==\"realdata\"){\n  native<-loadData()[[a$kind]];fit<-fitmodel(native);d<-list(id=native$id,p=fit$pred,y=native$y,w=rep(1,length(native$id)),role=native$role,group=native$group,eligible=native$eligible);scenarios<-list()\n  for(j in 1:3){name<-c(\"equal\",\"miss-five\",\"alarm-five\")[j];cst<-list(c(1,1),c(1,5),c(5,1))[[j]];sel<-chooseG(d,list(),cst);scenarios[[j]]<-list(name=name,selection=sel);metric(paste0(name,\"Threshold\"),sel$selectedPolicy);metric(paste0(name,\"TestCost\"),sel$evaluation$meanCost,\"hypothetical cost units/mass\")}\n  ids<-scopeG(d,\"test\");cv<-curvesG(d,ids);cal<-calibrateG(d,ids,seq(0,1,.2));metric(\"testAUC\",cv$ROC_AUC);metric(\"testAP\",cv$averagePrecision);metric(\"testBrier\",cal$Brier);metric(\"eligibleRows\",sum(d$eligible),\"rows\")\n  for(j in seq_along(ids)){i<-ids[j];pt(j-1,j,d$p[i],d$id[i],0);pt(j-1,j,d$y[i],d$id[i],1)}\n  full<-list(kind=a$kind,fit=fit,scenarios=scenarios,testCurves=cv,testCalibration=cal,rowsScored=d);xlabel<-\"Test row, native order\";ylabel<-\"Y or probability\";legend<-c(\"Training-fitted probability\",\"Observed Y\")\n }else{\n  d<-rowsG(a$rows);role<-if(is.null(a$role))\"all\"else a$role;ids<-scopeG(d,role);cost<-if(is.null(a$costs))c(1,1)else c(qnum(a$costs$falsePositive),qnum(a$costs$falseNegative));t<-if(is.null(a$threshold)).5 else if(a$threshold%in%c(\"always-positive\",\"always-negative\"))a$threshold else qnum(a$threshold)\n  if(api==\"metrics\"){\n   full<-metricsG(d,ids,t,cost);for(k in c(\"mass\",\"accuracy\",\"precision\",\"TPR\",\"FPR\",\"F1\",\"Brier\",\"meanCost\"))metric(k,full[[k]],if(k==\"mass\")\"mass\"else if(k==\"meanCost\")\"hypothetical cost units/mass\"else\"dimensionless\");metric(\"BayesThreshold\",full$bayesThreshold)\n   for(i in 1:4)pt(i-1,i-1,full$confusion[[i]],names(full$confusion)[i]);xlabel<-\"TP / FP / FN / TN positions\";ylabel<-\"Analytical mass\"\n  }else if(api==\"curves\"){\n   full<-curvesG(d,ids);for(k in c(\"ROC_AUC\",\"averagePrecision\",\"PRTrapezoidWithInitialPrecisionOne\"))metric(k,full[[k]])\n   for(j in seq_along(full$points)){p<-full$points[[j]];pt(j-1,p$FPR,p$TPR,if(is.character(p$policy))p$policy else sprintf(\"%.17g\",p$policy))};xlabel<-\"False positive rate\";ylabel<-\"True positive rate\";legend<-\"Observed ROC operating points\"\n  }else if(api==\"choose\"){\n   full<-chooseG(d,a,cost);metric(\"selectedIndex\",full$selectedIndex,\"candidate index\");metric(\"minimumCost\",if(is.null(full$selectedValidation))NULL else full$selectedValidation$meanCost,\"hypothetical cost units/mass\");metric(\"feasible\",as.integer(!is.na(full$selectedIndex)),\"indicator\")\n   for(c in full$candidates)pt(c$index,c$index,c$metrics$meanCost,if(is.character(c$policy))c$policy else sprintf(\"%.17g\",c$policy));xlabel<-\"Validation candidate\";ylabel<-\"Assumed cost / mass\";legend<-\"Validation candidate costs\"\n  }else if(api==\"calibrate\"){\n   edges<-if(is.null(a$binEdges))seq(0,1,.2)else vapply(a$binEdges,qnum,numeric(1));full<-calibrateG(d,ids,edges);for(k in c(\"ECE\",\"Brier\",\"uncertainty\",\"resolution\",\"reliability\",\"withinBinCorrection\",\"BrierIdentityResidual\"))metric(k,full[[k]])\n   for(b in full$bins)pt(b$index,b$meanPrediction,b$eventRate,paste0(\"bin:\",b$index));xlabel<-\"Bin mean forecast\";ylabel<-\"Bin event rate\";legend<-\"Binary-event reliability\"\n  }else if(api==\"groups\"){\n   full<-groupsG(d,ids,t,cost);metric(\"overallTPR\",full$overall$TPR);metric(\"TPRGap\",full$gaps$TPR);metric(\"precisionGap\",full$gaps$precision);metric(\"unknownMass\",full$unknownGroup$mass,\"mass\");metric(\"partitionResidual\",full$partitionMassResidual,\"mass\")\n   for(j in seq_along(full$groups))pt(j-1,j-1,full$groups[[j]]$metrics$TPR,full$groups[[j]]$group);xlabel<-\"Declared group position\";ylabel<-\"True positive rate\";legend<-\"Known-group TPR\"\n  }else stop(\"unknown declared fixed API\")\n }\n sm<-do.call(rbind,summary);pp<-do.call(rbind,points);write.csv(sm,file.path(outDir,\"summary.csv\"),row.names=FALSE,na=\"\");write.csv(pp,file.path(outDir,\"plot-points.csv\"),row.names=FALSE,na=\"\");svgFixed(file.path(outDir,\"plot.svg\"),pp,FIXED$title,xlabel,ylabel,legend);dput(list(api=api,variant=FIXED$variant,input=FIXED$args,arithmetic=\"Base-R binary64 fixed example; not an exact rational general validator\",result=full),file=file.path(outDir,\"full.txt\"));cat(\"PASS\",api,FIXED$variant,\"summary\",nrow(sm),\"points\",nrow(pp),\"\\n\")\n}\n\nFIXED<-list(api=\"calibrate\",variant=\"two-bins\",args=list(rows=list(list(id=\"a\",score=\".9\",y=1,group=\"A\"),list(id=\"b\",score=\".8\",y=1,group=\"A\"),list(id=\"c\",score=\".8\",y=0,group=\"A\"),list(id=\"d\",score=\".6\",y=0,group=\"B\"),list(id=\"e\",score=\".4\",y=1,group=\"B\"),list(id=\"f\",score=\".1\",y=0,group=\"B\")),binEdges=list(\"0\",\"1/2\",\"1\")),title=\"Six-card binary-event bins and full Brier identity\")\nfixedRun()\n",
        "codeText": "# ML14 standalone public counterpart, base R only.\n# Inputs are only the three factual CSVs; derived columns/previous model answers unused.\n# Binary64 arithmetic, not arbitrary-precision Fraction. At numerical cost ties\n# within 1e-12 retain the earliest candidate. Exact claims belong to Python/web.\n# SHA256 infrastructure below is reused verbatim from the previous public study.\nargs<-commandArgs(trailingOnly=TRUE);filearg<-grep(\"^--file=\",commandArgs(),value=TRUE)\nhere<-if(dir.exists(\"ml14-sources\"))getwd()else if(length(filearg))dirname(normalizePath(sub(\"^--file=\",\"\",filearg[1])))else getwd()\noption<-function(key,default){i<-match(key,args);if(is.na(i))default else args[i+1]}\nsourceDir<-option(\"--source\",file.path(here,\"ml14-sources\"));outDir<-option(\"--out\",file.path(getwd(),\"ml14-r-results\"));dir.create(outDir,recursive=TRUE,showWarnings=FALSE)\nnum<-function(x){x[x%in%c(\"\",\".\")]<-NA_character_;as.numeric(x)}\nfmt<-function(x)ifelse(is.na(x),\"\",sprintf(\"%.17g\",x))\nratio<-function(a,b)if(b==0)NA_real_ else a/b\nreadnative<-function(name)read.csv(file.path(sourceDir,name),check.names=FALSE,colClasses=\"character\",na.strings=character(),stringsAsFactors=FALSE)\n# Vectorized SHA256 for the short ASCII keys used in this study.\n# Unsigned words use exact integer-valued doubles; bit operations use safe\n# 16-bit halves, avoiding R's reserved signed-INT_MIN/NA representation.\nMOD<-2^32\nxor32<-function(a,b) as.double(bitwXor(as.integer(floor(a/65536)),as.integer(floor(b/65536))))*65536+as.double(bitwXor(as.integer(a%%65536),as.integer(b%%65536)))\nand32<-function(a,b) as.double(bitwAnd(as.integer(floor(a/65536)),as.integer(floor(b/65536))))*65536+as.double(bitwAnd(as.integer(a%%65536),as.integer(b%%65536)))\nrot<-function(x,n) floor(x/2^n)+(x%%2^n)*2^(32-n)\nxor3<-function(a,b,c) xor32(xor32(a,b),c)\nK<-c(0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5,0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967,0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070,0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3,0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2)\nsha256<-function(strings) {\n n<-length(strings);bytes<-matrix(0,n,64)\n for(i in seq_len(n)) {v<-utf8ToInt(strings[i]);stopifnot(length(v)<56,all(v<128));if(length(v)) bytes[i,seq_along(v)]<-v;bytes[i,length(v)+1]<-128;bits<-length(v)*8;bytes[i,61:64]<-c(floor(bits/2^24)%%256,floor(bits/2^16)%%256,floor(bits/256)%%256,bits%%256)}\n w<-matrix(0,n,64)\n for(j in 1:16) {b<-4*(j-1)+1;w[,j]<-bytes[,b]*2^24+bytes[,b+1]*2^16+bytes[,b+2]*256+bytes[,b+3]}\n for(j in 17:64) {s0<-xor3(rot(w[,j-15],7),rot(w[,j-15],18),floor(w[,j-15]/8));s1<-xor3(rot(w[,j-2],17),rot(w[,j-2],19),floor(w[,j-2]/1024));w[,j]<-(w[,j-16]+s0+w[,j-7]+s1)%%MOD}\n init<-c(0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19)\n state<-lapply(init,function(v) rep(v,n));a<-state[[1]];b<-state[[2]];c<-state[[3]];d<-state[[4]];e<-state[[5]];f<-state[[6]];g<-state[[7]];h<-state[[8]]\n for(j in 1:64) {S1<-xor3(rot(e,6),rot(e,11),rot(e,25));ch<-xor32(and32(e,f),and32(MOD-1-e,g));t1<-(h+S1+ch+K[j]+w[,j])%%MOD;S0<-xor3(rot(a,2),rot(a,13),rot(a,22));maj<-xor3(and32(a,b),and32(a,c),and32(b,c));t2<-(S0+maj)%%MOD;h<-g;g<-f;f<-e;e<-(d+t1)%%MOD;d<-c;c<-b;b<-a;a<-(t1+t2)%%MOD}\n end<-list(a,b,c,d,e,f,g,h);hex<-lapply(1:8,function(j){v<-(end[[j]]+init[j])%%MOD;paste0(sprintf(\"%04x\",as.integer(floor(v/65536))),sprintf(\"%04x\",as.integer(v%%65536)))})\n do.call(paste0,hex)\n}\nstopifnot(identical(sha256(c(\"abc\",\"\")),c(\"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad\",\"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855\")))\n\nloadData<-function(){\n wb<-readnative(\"actual64-country-four-indicators-original-2024.csv\");codes<-c(\"NY.GDP.PCAP.KD\",\"NY.GDP.MKTP.KD.ZG\",\"FP.CPI.TOTL.ZG\",\"SP.DYN.LE00.IN\");iso<-sort(unique(wb$countryISO3));stopifnot(nrow(wb)==64,length(iso)==16)\n tokens<-t(vapply(iso,function(s)wb$originalValueToken[match(paste(s,codes),paste(wb$countryISO3,wb$indicatorID))],character(4)));vals<-matrix(num(as.vector(tokens)),nrow=nrow(tokens))\n country<-list(id=paste0(iso,\":2024\"),sourceRow=1:16,originalID=iso,x=vals[,1:3,drop=FALSE],rawX=tokens[,1:3,drop=FALSE],nativeTarget=tokens[,4],y=as.integer(vals[,4]>=80),group=ifelse(is.na(vals[,1]),NA_character_,as.character(as.integer(vals[,1]>=25000))),lineage=vapply(iso,function(s)paste(wb$sourceRow[match(paste(s,codes),paste(wb$countryISO3,wb$indicatorID))],collapse=\";\"),character(1)),cat=integer(),units=c(\"constant2015USD/person\",\"annualPercent\",\"annualPercent\"))\n nls<-readnative(\"actual3613-NLS-original52-fields-groups-roles.csv\");raw<-cbind(nls$ed76,nls$age76,nls$nearc4)\n person<-list(id=paste0(\"person:\",nls$sourceRow),sourceRow=as.integer(nls$sourceRow),originalID=nls$id,x=matrix(num(as.vector(raw)),nrow=nrow(raw)),rawX=raw,nativeTarget=nls$wage76,y=as.integer(num(nls$wage76)>=500),group=ifelse(nls$black%in%c(\"\",\".\"),NA_character_,nls$black),lineage=nls$sourceRow,cat=2L,units=c(\"years\",\"years\",\"nativeCategory\"))\n ch<-readnative(\"actual3150-churn-original14-fields-groups-roles.csv\");raw<-cbind(ch[[\"Call  Failure\"]],ch$Complains,ch[[\"Subscription  Length\"]],ch[[\"Seconds of Use\"]])\n company<-list(id=paste0(\"customer:\",ch$sourceRow),sourceRow=as.integer(ch$sourceRow),originalID=rep(\"\",nrow(ch)),x=matrix(num(as.vector(raw)),nrow=nrow(raw)),rawX=raw,nativeTarget=ch$Churn,y=as.integer(ch$Churn),group=ifelse(ch[[\"Tariff Plan\"]]%in%c(\"\",\".\"),NA_character_,ch[[\"Tariff Plan\"]]),lineage=ch$sourceRow,cat=1L,units=c(\"count\",\"nativeCategory\",\"months\",\"seconds\"))\n stopifnot(nrow(nls)==3613,nrow(ch)==3150,identical(as.integer(ch$sourceRow[ch[[\"Charge  Amount\"]]==\"10\"]),c(474L,2174L,2274L,2374L,2674L,2924L,2974L)))\n result<-list(country=country,person=person,company=company)\n for(k in names(result)){d<-result[[k]];n<-length(d$id);d$eligible<-!is.na(d$y)&rowSums(is.na(d$x))==0;hash<-sha256(paste0(\"ML14-role|\",k,\"|\",d$id));rank<-integer(n);rank[order(hash,seq_len(n))]<-seq_len(n)-1L;d$plannedRole<-ifelse(rank%%5==0,\"test\",ifelse(rank%%5==1,\"validation\",\"train\"));d$role<-ifelse(d$eligible,d$plannedRole,\"excluded\");result[[k]]<-d}\n stopifnot(sum(result$person$eligible)==3017);result\n}\nfitmodel<-function(d){\n ids<-which(d$role==\"train\");p<-ncol(d$x);m<-vapply(seq_len(p),function(j)if((j-1)%in%d$cat)NA_real_ else median(d$x[ids,j]),numeric(1));z<-d$x\n for(j in seq_len(p))if(!((j-1)%in%d$cat))z[,j]<-as.numeric(z[,j]>m[j])\n keys<-apply(z,1,function(v)paste(fmt(v),collapse=\"|\"));lev<-unique(keys[ids]);mass<-vapply(lev,function(k)sum(keys[ids]==k),integer(1));positive<-vapply(lev,function(k)sum(d$y[ids][keys[ids]==k]),integer(1));prob<-(positive+1)/(mass+2);fallback<-(sum(d$y[ids])+1)/(length(ids)+2);pred<-prob[match(keys,lev)];unseen<-is.na(pred);pred[unseen]<-fallback;pred[!d$eligible]<-NA_real_;unseen[!d$eligible]<-NA\n list(ids=ids,medians=m,z=z,keys=keys,lev=lev,mass=mass,positive=positive,prob=prob,fallback=fallback,pred=pred,unseen=unseen)\n}\nmeasure<-function(d,p,ids,t=.5,cost=c(1,1)){\n use<-ids[d$eligible[ids]&!is.na(p[ids])];y<-d$y[use];a<-if(is.character(t))rep(t==\"always-positive\",length(use))else p[use]>=t\n TP<-sum(a&y==1);FP<-sum(a&y==0);FN<-sum(!a&y==1);TN<-sum(!a&y==0);P<-TP+FN;N<-FP+TN;W<-P+N;PP<-TP+FP;PN<-TN+FN;TPR<-ratio(TP,P);TNR<-ratio(TN,N);bs<-sum((p[use]-y)^2);tc<-FP*cost[1]+FN*cost[2]\n list(TP=TP,FP=FP,FN=FN,TN=TN,mass=W,positiveTargetMass=P,negativeTargetMass=N,predictedPositiveMass=PP,predictedNegativeMass=PN,prevalence=ratio(P,W),selectionRate=ratio(PP,W),accuracy=ratio(TP+TN,W),precision=ratio(TP,PP),negativePredictiveValue=ratio(TN,PN),TPR=TPR,FPR=ratio(FP,N),TNR=TNR,FNR=ratio(FN,P),F1=ratio(2*TP,2*TP+FP+FN),balancedAccuracy=if(is.na(TPR)||is.na(TNR))NA_real_ else(TPR+TNR)/2,Brier=ratio(bs,W),BrierSum=bs,totalCost=tc,meanCost=ratio(tc,W))\n}\ncurves<-function(d,p,ids){\n use<-ids[d$eligible[ids]&!is.na(p[ids])];scores<-sort(unique(p[use]),decreasing=TRUE);policies<-c(list(\"always-negative\"),as.list(scores));points<-lapply(policies,function(t){m<-measure(d,p,ids,t);c(list(policy=t),m[c(\"TP\",\"FP\",\"FN\",\"TN\",\"TPR\",\"FPR\",\"precision\")],list(recall=m$TPR))})\n pos<-use[d$y[use]==1];neg<-use[d$y[use]==0];U<-0;for(i in pos)U<-U+sum(p[i]>p[neg])+.5*sum(p[i]==p[neg])\n AP<-0;trap<-0;lastR<-0;lastP<-1\n if(length(pos)&&length(scores))for(j in seq_along(scores)){z<-points[[j+1]];AP<-AP+(z$recall-lastR)*z$precision;trap<-trap+(z$recall-lastR)*(z$precision+lastP)/2;lastR<-z$recall;lastP<-z$precision}\n list(points=points,ROC_AUC=ratio(U,length(pos)*length(neg)),averagePrecision=if(length(pos))AP else NA_real_,PRTrapezoidWithInitialPrecisionOne=if(length(pos))trap else NA_real_)\n}\ncalibrate<-function(d,p,ids){\n use<-ids[d$eligible[ids]&!is.na(p[ids])];W<-length(use);pi<-if(W)mean(d$y[use])else NA_real_;bins<-list();ECE<-rel<-res<-correction<-0\n whichbin<-findInterval(p[use],seq(0,1,.2),rightmost.closed=TRUE,all.inside=TRUE)\n for(b in 1:5){rr<-use[whichbin==b];w<-length(rr);mp<-if(w)mean(p[rr])else NA_real_;o<-if(w)mean(d$y[rr])else NA_real_;variance<-if(w)mean((p[rr]-mp)^2)else NA_real_;covariance<-if(w)mean((p[rr]-mp)*(d$y[rr]-o))else NA_real_;bc<-variance-2*covariance;gap<-mp-o\n  bins[[b]]<-list(mass=w,meanPrediction=mp,eventRate=o,gap=gap,absoluteGap=abs(gap),scoreVariance=variance,scoreTargetCovariance=covariance,withinBinCorrection=bc,rows=w,ids=d$id[rr])\n  if(w){share<-w/W;ECE<-ECE+share*abs(gap);rel<-rel+share*gap^2;res<-res+share*(o-pi)^2;correction<-correction+share*bc}\n };bs<-if(W)mean((p[use]-d$y[use])^2)else NA_real_;unc<-pi*(1-pi)\n list(bins=bins,ECE=if(W)ECE else NA_real_,Brier=bs,reliability=if(W)rel else NA_real_,resolution=if(W)res else NA_real_,uncertainty=unc,withinBinCorrection=if(W)correction else NA_real_,BrierIdentityResidual=bs-(unc-res+rel+correction))\n}\ncounts<-c(\"mass\",\"positiveTargetMass\",\"negativeTargetMass\",\"predictedPositiveMass\",\"predictedNegativeMass\");rates<-c(\"prevalence\",\"selectionRate\",\"accuracy\",\"precision\",\"negativePredictiveValue\",\"TPR\",\"FPR\",\"TNR\",\"FNR\",\"F1\",\"balancedAccuracy\",\"Brier\",\"BrierSum\",\"totalCost\",\"meanCost\")\ntables<-setNames(lapply(1:10,function(i)list()),c(\"predictions\",\"lineage\",\"fit-medians\",\"fit-cells\",\"validation-candidates\",\"test-metrics\",\"test-curves\",\"calibration-bins\",\"group-metrics\",\"chart-points\"))\nadd<-function(name,row)tables[[name]][[length(tables[[name]])+1L]]<<-row\nscalars<-function(m,keys){out<-list();for(k in keys){out[[paste0(k,\"Exact\")]]<-\"\";out[[paste0(k,\"Approx\")]]<-fmt(m[[k]])};out}\ntagrow<-function(kind,...)c(list(kind=kind),list(...))\npoint<-function(kind,chart,series,index,x,y,xunit=\"dimensionless\",yunit=\"dimensionless\",role=\"test\",tag=\"\"){add(\"chart-points\",tagrow(kind,chart=chart,series=series,index=index,xExact=\"\",xApprox=fmt(x),yExact=\"\",yApprox=fmt(y),xUnit=xunit,yUnit=yunit,role=role,tag=tag))}\nstudy<-function(kind,d){\n f<-fitmodel(d);n<-length(d$id);train<-which(d$role==\"train\");validation<-which(d$role==\"validation\");test<-which(d$role==\"test\");p<-f$pred;cv<-curves(d,p,test);cal<-calibrate(d,p,test)\n for(i in seq_len(n)){\n  reason<-if(d$eligible[i])\"\"else\"required-X-or-Y-missing\";transformed<-if(d$eligible[i])paste(fmt(f$z[i,]),collapse=\"|\")else\"\"\n  add(\"predictions\",tagrow(kind,id=d$id[i],sourceRow=d$sourceRow[i],originalID=d$originalID[i],plannedRole=d$plannedRole[i],role=d$role[i],group=ifelse(is.na(d$group[i]),\"\",d$group[i]),eligible=as.integer(d$eligible[i]),targetExact=fmt(d$y[i]),probabilityExact=\"\",probabilityApprox=fmt(p[i]),unseenCell=ifelse(is.na(f$unseen[i]),\"\",as.character(as.integer(f$unseen[i]))),transformedX=transformed,reason=reason))\n  raw<-d$rawX[i,];raw[raw%in%c(\"\",\".\")]<-\"\";nativeY<-d$nativeTarget[i];if(nativeY%in%c(\"\",\".\"))nativeY<-\"\"\n  add(\"lineage\",tagrow(kind,id=d$id[i],sourceRow=d$sourceRow[i],originalID=d$originalID[i],nativeSourceRows=d$lineage[i],rawX=paste(raw,collapse=\"|\"),nativeTarget=nativeY,derivedTarget=fmt(d$y[i]),nativeGroup=ifelse(is.na(d$group[i]),\"\",d$group[i]),plannedRole=d$plannedRole[i],role=d$role[i],eligible=as.integer(d$eligible[i]),analyticalMass=\"1\",reason=reason))\n }\n for(j in seq_len(ncol(d$x)))add(\"fit-medians\",tagrow(kind,feature=j-1,categorical=as.integer((j-1)%in%d$cat),fitRows=length(train),medianExact=\"\",medianApprox=fmt(f$medians[j]),unit=d$units[j]))\n for(j in seq_along(f$lev))add(\"fit-cells\",tagrow(kind,cell=f$lev[j],trainingRows=f$mass[j],positiveRows=f$positive[j],probabilityExact=\"\",probabilityApprox=fmt(f$prob[j]),fallbackExact=\"\",fallbackApprox=fmt(f$fallback)))\n for(j in seq_along(cv$points)){\n  z<-cv$points[[j]];t<-z$policy;add(\"test-curves\",c(tagrow(kind,point=j-1,policy=if(is.character(t))t else\"threshold\",thresholdExact=\"\",thresholdApprox=if(is.character(t))\"\"else fmt(t)),scalars(z,c(\"TP\",\"FP\",\"FN\",\"TN\",\"TPR\",\"FPR\",\"precision\",\"recall\"))))\n  point(kind,\"roc\",\"ROC\",j-1,z$FPR,z$TPR);point(kind,\"pr\",\"PR-observed\",j-1,z$recall,z$precision)\n }\n for(b in 1:5){z<-cal$bins[[b]];add(\"calibration-bins\",c(tagrow(kind,bin=b-1,leftExact=c(\"0\",\"1/5\",\"2/5\",\"3/5\",\"4/5\")[b],rightExact=c(\"1/5\",\"2/5\",\"3/5\",\"4/5\",\"1\")[b],rightClosed=as.integer(b==5),rows=z$rows,ids=paste(z$ids,collapse=\";\")),scalars(z,c(\"mass\",\"meanPrediction\",\"eventRate\",\"gap\",\"absoluteGap\",\"scoreVariance\",\"scoreTargetCovariance\",\"withinBinCorrection\"))));point(kind,\"reliability\",\"Binary event rate\",b-1,z$meanPrediction,z$eventRate,tag=paste0(\"rows=\",z$rows))}\n for(j in seq_along(test)){i<-test[j];point(kind,\"test-scores\",\"Training-fitted probability\",j-1,j,p[i],\"test-row position\",\"probability\",tag=d$id[i]);point(kind,\"test-scores\",\"Observed Y\",j-1,j,d$y[i],\"test-row position\",\"binary target\",tag=d$id[i])}\n scenarioNames<-c(\"equal\",\"miss-five\",\"alarm-five\");costs<-list(c(1,1),c(1,5),c(5,1))\n for(s in 1:3){name<-scenarioNames[s];cost<-costs[[s]];grid<-c(list(\"always-negative\"),as.list(sort(unique(p[validation]),decreasing=TRUE)));candidates<-lapply(grid,function(t)measure(d,p,validation,t,cost));values<-vapply(candidates,function(m)m$meanCost,numeric(1));best<-which(values<=min(values)+1e-12)[1];chosen<-grid[[best]];ev<-measure(d,p,test,chosen,cost)\n  for(j in seq_along(grid)){t<-grid[[j]];m<-candidates[[j]];cell<-setNames(lapply(c(\"TP\",\"FP\",\"FN\",\"TN\"),function(k)fmt(m[[k]])),paste0(c(\"TP\",\"FP\",\"FN\",\"TN\"),\"Exact\"));add(\"validation-candidates\",c(tagrow(kind,scenario=name,candidate=j-1,selected=as.integer(j==best),policy=if(is.character(t))t else\"threshold\",thresholdExact=\"\",thresholdApprox=if(is.character(t))\"\"else fmt(t),feasible=1,reasons=\"\"),cell,scalars(m,c(counts,\"TPR\",\"FPR\",\"precision\",\"meanCost\",\"totalCost\"))));point(kind,\"validation-cost\",name,j-1,j-1,m$meanCost,\"candidate index\",\"hypothetical cost units/mass\",\"validation\",if(is.character(t))t else fmt(t))}\n  m<-c(ev,cv[c(\"ROC_AUC\",\"averagePrecision\",\"PRTrapezoidWithInitialPrecisionOne\")],cal[c(\"ECE\",\"reliability\",\"resolution\",\"uncertainty\",\"withinBinCorrection\",\"BrierIdentityResidual\")])\n  for(k in c(\"TP\",\"FP\",\"FN\",\"TN\",counts,rates,\"ROC_AUC\",\"averagePrecision\",\"PRTrapezoidWithInitialPrecisionOne\",\"ECE\",\"reliability\",\"resolution\",\"uncertainty\",\"withinBinCorrection\",\"BrierIdentityResidual\")){\n   unit<-if(k%in%c(\"TP\",\"FP\",\"FN\",\"TN\",counts))\"rows\"else if(k==\"totalCost\")\"hypothetical cost units\"else if(k==\"meanCost\")\"hypothetical cost units/mass\"else if(k==\"BrierSum\")\"sum squared-probability loss\"else\"dimensionless\"\n   add(\"test-metrics\",tagrow(kind,scenario=name,metric=k,valueExact=\"\",valueApprox=fmt(m[[k]]),unit=unit))\n  }\n  lev<-unique(d$group[test][!is.na(d$group[test])]);sets<-c(list(test),lapply(lev,function(g)test[!is.na(d$group[test])&d$group[test]==g]),list(test[is.na(d$group[test])]))\n  types<-c(\"overall\",rep(\"known\",length(lev)),\"unknown\");tokens<-c(\"all\",lev,\"\")\n  for(j in seq_along(sets)){ids<-sets[[j]];m<-measure(d,p,ids,chosen,cost);cell<-setNames(lapply(c(\"TP\",\"FP\",\"FN\",\"TN\"),function(k)fmt(m[[k]])),paste0(c(\"TP\",\"FP\",\"FN\",\"TN\"),\"Exact\"));add(\"group-metrics\",c(tagrow(kind,scenario=name,groupType=types[j],groupToken=tokens[j],retainedRows=length(ids)),cell,scalars(m,c(counts,rates))));if(types[j]==\"known\")point(kind,\"group-TPR\",name,j-2,j-2,m$TPR,\"declared group position\",\"TPR\",tag=tokens[j])}\n }\n invisible(NULL)\n}\n\n# Fixed finite inputs only; not the complete web input/budget validator.\nqnum<-function(v){if(is.null(v))return(NA_real_);if(is.logical(v))return(as.numeric(v));s<-as.character(v);if(grepl(\"/\",s,fixed=TRUE)){a<-strsplit(s,\"/\",fixed=TRUE)[[1]];return(as.numeric(a[1])/as.numeric(a[2]))};as.numeric(s)}\nrowsG<-function(raw){\n n<-length(raw);get<-function(r,k,default=NULL)if(is.null(r[[k]]))default else r[[k]]\n id<-vapply(raw,function(r)as.character(r$id),character(1));p<-vapply(raw,function(r)qnum(r$score),numeric(1));y<-vapply(raw,function(r)qnum(r$y),numeric(1));w<-vapply(raw,function(r)qnum(get(r,\"weight\",\"1\")),numeric(1));role<-vapply(raw,function(r)get(r,\"role\",\"evaluation\"),character(1));group<-vapply(raw,function(r)as.character(get(r,\"group\",NA_character_)),character(1))\n stopifnot(all(w>=0),all(is.na(p)|(p>=0&p<=1)),all(is.na(y)|y%in%c(0,1)),!anyDuplicated(id));list(id=id,p=p,y=y,w=w,role=role,group=group,eligible=!is.na(p)&!is.na(y)&w>0&role!=\"excluded\")\n}\nscopeG<-function(d,role=\"all\")if(role==\"all\")seq_along(d$id)else which(d$role==role)\nmetricsG<-function(d,ids,t=.5,cost=c(1,1)){\n use<-ids[d$eligible[ids]];p<-d$p[use];y<-d$y[use];w<-d$w[use];a<-if(is.character(t))rep(t==\"always-positive\",length(use))else p>=t\n TP<-sum(w[a&y==1]);FP<-sum(w[a&y==0]);FN<-sum(w[!a&y==1]);TN<-sum(w[!a&y==0]);P<-TP+FN;N<-FP+TN;W<-P+N;PP<-TP+FP;PN<-TN+FN;TPR<-ratio(TP,P);TNR<-ratio(TN,N);bs<-sum(w*(p-y)^2);tc<-FP*cost[1]+FN*cost[2]\n list(confusion=list(TP=TP,FP=FP,FN=FN,TN=TN),mass=W,positiveTargetMass=P,negativeTargetMass=N,predictedPositiveMass=PP,predictedNegativeMass=PN,prevalence=ratio(P,W),selectionRate=ratio(PP,W),accuracy=ratio(TP+TN,W),precision=ratio(TP,PP),negativePredictiveValue=ratio(TN,PN),TPR=TPR,FPR=ratio(FP,N),TNR=TNR,FNR=ratio(FN,P),F1=ratio(2*TP,2*TP+FP+FN),balancedAccuracy=if(is.na(TPR)||is.na(TNR))NA_real_ else(TPR+TNR)/2,Brier=ratio(bs,W),BrierSum=bs,totalCost=tc,meanCost=ratio(tc,W),bayesThreshold=ratio(cost[1],sum(cost)))\n}\ncurvesG<-function(d,ids){\n use<-ids[d$eligible[ids]];grid<-c(list(\"always-negative\"),as.list(sort(unique(d$p[use]),decreasing=TRUE)));points<-lapply(grid,function(t){m<-metricsG(d,ids,t);c(list(policy=t),m$confusion,m[c(\"TPR\",\"FPR\",\"precision\")],list(recall=m$TPR))});pos<-use[d$y[use]==1];neg<-use[d$y[use]==0];P<-sum(d$w[pos]);N<-sum(d$w[neg]);U<-0\n for(i in pos)U<-U+d$w[i]*sum(d$w[neg]*((d$p[i]>d$p[neg])+.5*(d$p[i]==d$p[neg])))\n AP<-trap<-lastR<-0;lastP<-1\n if(P&&length(grid)>1)for(j in 2:length(grid)){z<-points[[j]];AP<-AP+(z$recall-lastR)*z$precision;trap<-trap+(z$recall-lastR)*(z$precision+lastP)/2;lastR<-z$recall;lastP<-z$precision}\n list(points=points,ROC_AUC=ratio(U,P*N),averagePrecision=if(P)AP else NA_real_,PRTrapezoidWithInitialPrecisionOne=if(P)trap else NA_real_)\n}\nchooseG<-function(d,a,cost){\n role<-if(is.null(a$selectionRole))\"validation\"else a$selectionRole;er<-if(is.null(a$evaluationRole))\"test\"else a$evaluationRole;ids<-scopeG(d,role);use<-ids[d$eligible[ids]];stopifnot(length(use)>0);grid<-if(is.null(a$thresholds))c(list(\"always-negative\"),as.list(sort(unique(d$p[use]),decreasing=TRUE)))else lapply(a$thresholds,function(t)if(t%in%c(\"always-negative\",\"always-positive\"))t else qnum(t))\n candidates<-lapply(seq_along(grid),function(j){m<-metricsG(d,ids,grid[[j]],cost);feasible<-TRUE;if(!is.null(a$minTPR))feasible<-feasible&&!is.na(m$TPR)&&m$TPR>=qnum(a$minTPR);if(!is.null(a$maxFPR))feasible<-feasible&&!is.na(m$FPR)&&m$FPR<=qnum(a$maxFPR);list(index=j-1,policy=grid[[j]],metrics=m,feasible=feasible)})\n good<-which(vapply(candidates,function(c)c$feasible,logical(1)));best<-NA_integer_;if(length(good)){v<-vapply(candidates[good],function(c)c$metrics$meanCost,numeric(1));best<-good[which(v<=min(v)+1e-12)[1]]}\n list(selectedIndex=if(is.na(best))NA_integer_ else best-1,selectedPolicy=if(is.na(best))NULL else grid[[best]],selectedValidation=if(is.na(best))NULL else candidates[[best]]$metrics,candidates=candidates,evaluation=if(is.na(best)||er==\"none\")NULL else metricsG(d,scopeG(d,er),grid[[best]],cost))\n}\ncalibrateG<-function(d,ids,edges){\n use<-ids[d$eligible[ids]];W<-sum(d$w[use]);pi<-ratio(sum(d$w[use]*d$y[use]),W);bins<-list();ECE<-rel<-res<-correction<-0;assign<-findInterval(d$p[use],edges,rightmost.closed=TRUE,all.inside=TRUE)\n for(b in seq_len(length(edges)-1)){rr<-use[assign==b];w<-sum(d$w[rr]);mp<-ratio(sum(d$w[rr]*d$p[rr]),w);o<-ratio(sum(d$w[rr]*d$y[rr]),w);variance<-if(w)sum(d$w[rr]*(d$p[rr]-mp)^2)/w else NA_real_;covariance<-if(w)sum(d$w[rr]*(d$p[rr]-mp)*(d$y[rr]-o))/w else NA_real_;bc<-variance-2*covariance;gap<-mp-o;bins[[b]]<-list(index=b-1,mass=w,meanPrediction=mp,eventRate=o,scoreVariance=variance,scoreTargetCovariance=covariance,withinBinCorrection=bc,ids=d$id[rr])\n  if(w){s<-w/W;ECE<-ECE+s*abs(gap);rel<-rel+s*gap^2;res<-res+s*(o-pi)^2;correction<-correction+s*bc}\n };bs<-ratio(sum(d$w[use]*(d$p[use]-d$y[use])^2),W);unc<-pi*(1-pi);list(bins=bins,Brier=bs,ECE=if(W)ECE else NA_real_,uncertainty=unc,reliability=if(W)rel else NA_real_,resolution=if(W)res else NA_real_,withinBinCorrection=if(W)correction else NA_real_,BrierIdentityResidual=bs-(unc-res+rel+correction))\n}\ngroupsG<-function(d,ids,t,cost){\n lev<-unique(d$group[ids][!is.na(d$group[ids])]);groups<-lapply(lev,function(g)list(group=g,metrics=metricsG(d,ids[!is.na(d$group[ids])&d$group[ids]==g],t,cost)));overall<-metricsG(d,ids,t,cost);unknown<-metricsG(d,ids[is.na(d$group[ids])],t,cost);gaps<-list()\n for(k in c(\"prevalence\",\"selectionRate\",\"TPR\",\"FPR\",\"precision\",\"accuracy\",\"meanCost\")){use<-Filter(function(g)g$metrics$mass>0,groups);v<-vapply(use,function(g)g$metrics[[k]],numeric(1));gaps[[k]]<-if(length(use)<2||anyNA(v))NA_real_ else max(v)-min(v)}\n list(overall=overall,groups=groups,unknownGroup=unknown,gaps=gaps,partitionMassResidual=overall$mass-unknown$mass-sum(vapply(groups,function(g)g$metrics$mass,numeric(1))))\n}\nsvgFixed<-function(file,points,title,xlabel,ylabel,legend){\n finite<-points[points$y!=\"undefined\"&points$x!=\"undefined\",,drop=FALSE];x<-as.numeric(finite$x);y<-as.numeric(finite$y);xmin<-if(length(x))min(x)else 0;xmax<-if(length(x))max(x)else 1;ymin<-min(c(0,y));ymax<-max(c(0,y));if(xmin==xmax){xmin<-xmin-.5;xmax<-xmax+.5};if(ymin==ymax)ymax<-ymin+1;X<-function(v)85+(v-xmin)/(xmax-xmin)*480;Y<-function(v)278-(v-ymin)/(ymax-ymin)*175\n esc<-function(s){s<-gsub(\"&\",\"&amp;\",s,fixed=TRUE);s<-gsub(\"<\",\"&lt;\",s,fixed=TRUE);gsub(\">\",\"&gt;\",s,fixed=TRUE)};s<-'<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"620\" height=\"360\" viewBox=\"0 0 620 360\"><rect width=\"620\" height=\"360\" fill=\"white\"/><g font-family=\"Arial, sans-serif\" font-size=\"13\" fill=\"#17324d\">'\n lines<-strwrap(title,width=65);for(i in seq_along(lines))s<-paste0(s,'<text x=\"25\" y=\"',24+(i-1)*18,'\">',esc(lines[i]),'</text>');colors<-c(\"#176b9b\",\"#b85e18\",\"#437e4d\")\n for(i in seq_along(legend))s<-paste0(s,'<circle cx=\"',30+(i-1)*250,'\" cy=\"76\" r=\"4\" fill=\"',colors[(i-1)%%3+1],'\"/><text x=\"',42+(i-1)*250,'\" y=\"80\">',esc(legend[i]),'</text>')\n s<-paste0(s,'<path d=\"M85 98V278H575\" fill=\"none\" stroke=\"#52677d\"/><text text-anchor=\"middle\" x=\"325\" y=\"338\">',esc(xlabel),'</text><text text-anchor=\"middle\" transform=\"translate(21,190) rotate(-90)\">',esc(ylabel),'</text>')\n for(i in 0:4){xx<-xmin+(xmax-xmin)*i/4;yy<-ymin+(ymax-ymin)*i/4;s<-paste0(s,'<text text-anchor=\"middle\" x=\"',sprintf(\"%.9g\",X(xx)),'\" y=\"305\">',sprintf(\"%.4g\",xx),'</text><text text-anchor=\"end\" x=\"77\" y=\"',sprintf(\"%.9g\",Y(yy)+4),'\">',sprintf(\"%.4g\",yy),'</text>')}\n for(i in seq_len(nrow(finite)))s<-paste0(s,'<circle cx=\"',sprintf(\"%.9g\",X(x[i])),'\" cy=\"',sprintf(\"%.9g\",Y(y[i])),'\" r=\"3\" fill=\"',colors[as.integer(finite$series[i])%%3+1],'\"/>');writeLines(paste0(s,'</g></svg>'),file,useBytes=TRUE)\n}\nfixedRun<-function(){\n api<-FIXED$api;a<-FIXED$args;summary<-list();points<-list();xlabel<-\"Declared index\";ylabel<-\"Value\";legend<-\"Declared result\"\n metric<-function(name,v,unit=\"dimensionless\"){if(is.null(v))v<-NA_real_;summary[[length(summary)+1L]]<<-data.frame(metric=name,value=if(is.na(v))\"undefined\"else sprintf(\"%.9g\",v),exactValue=\"\",unit=unit,defined=as.integer(!is.na(v)),stringsAsFactors=FALSE)}\n pt<-function(i,x,y,id=\"\",series=0){points[[length(points)+1L]]<<-data.frame(series=series,index=i,xExact=\"\",x=if(is.na(x))\"undefined\"else sprintf(\"%.9g\",x),yExact=\"\",y=if(is.na(y))\"undefined\"else sprintf(\"%.9g\",y),id=as.character(id),stringsAsFactors=FALSE)}\n if(api==\"realdata\"){\n  native<-loadData()[[a$kind]];fit<-fitmodel(native);d<-list(id=native$id,p=fit$pred,y=native$y,w=rep(1,length(native$id)),role=native$role,group=native$group,eligible=native$eligible);scenarios<-list()\n  for(j in 1:3){name<-c(\"equal\",\"miss-five\",\"alarm-five\")[j];cst<-list(c(1,1),c(1,5),c(5,1))[[j]];sel<-chooseG(d,list(),cst);scenarios[[j]]<-list(name=name,selection=sel);metric(paste0(name,\"Threshold\"),sel$selectedPolicy);metric(paste0(name,\"TestCost\"),sel$evaluation$meanCost,\"hypothetical cost units/mass\")}\n  ids<-scopeG(d,\"test\");cv<-curvesG(d,ids);cal<-calibrateG(d,ids,seq(0,1,.2));metric(\"testAUC\",cv$ROC_AUC);metric(\"testAP\",cv$averagePrecision);metric(\"testBrier\",cal$Brier);metric(\"eligibleRows\",sum(d$eligible),\"rows\")\n  for(j in seq_along(ids)){i<-ids[j];pt(j-1,j,d$p[i],d$id[i],0);pt(j-1,j,d$y[i],d$id[i],1)}\n  full<-list(kind=a$kind,fit=fit,scenarios=scenarios,testCurves=cv,testCalibration=cal,rowsScored=d);xlabel<-\"Test row, native order\";ylabel<-\"Y or probability\";legend<-c(\"Training-fitted probability\",\"Observed Y\")\n }else{\n  d<-rowsG(a$rows);role<-if(is.null(a$role))\"all\"else a$role;ids<-scopeG(d,role);cost<-if(is.null(a$costs))c(1,1)else c(qnum(a$costs$falsePositive),qnum(a$costs$falseNegative));t<-if(is.null(a$threshold)).5 else if(a$threshold%in%c(\"always-positive\",\"always-negative\"))a$threshold else qnum(a$threshold)\n  if(api==\"metrics\"){\n   full<-metricsG(d,ids,t,cost);for(k in c(\"mass\",\"accuracy\",\"precision\",\"TPR\",\"FPR\",\"F1\",\"Brier\",\"meanCost\"))metric(k,full[[k]],if(k==\"mass\")\"mass\"else if(k==\"meanCost\")\"hypothetical cost units/mass\"else\"dimensionless\");metric(\"BayesThreshold\",full$bayesThreshold)\n   for(i in 1:4)pt(i-1,i-1,full$confusion[[i]],names(full$confusion)[i]);xlabel<-\"TP / FP / FN / TN positions\";ylabel<-\"Analytical mass\"\n  }else if(api==\"curves\"){\n   full<-curvesG(d,ids);for(k in c(\"ROC_AUC\",\"averagePrecision\",\"PRTrapezoidWithInitialPrecisionOne\"))metric(k,full[[k]])\n   for(j in seq_along(full$points)){p<-full$points[[j]];pt(j-1,p$FPR,p$TPR,if(is.character(p$policy))p$policy else sprintf(\"%.17g\",p$policy))};xlabel<-\"False positive rate\";ylabel<-\"True positive rate\";legend<-\"Observed ROC operating points\"\n  }else if(api==\"choose\"){\n   full<-chooseG(d,a,cost);metric(\"selectedIndex\",full$selectedIndex,\"candidate index\");metric(\"minimumCost\",if(is.null(full$selectedValidation))NULL else full$selectedValidation$meanCost,\"hypothetical cost units/mass\");metric(\"feasible\",as.integer(!is.na(full$selectedIndex)),\"indicator\")\n   for(c in full$candidates)pt(c$index,c$index,c$metrics$meanCost,if(is.character(c$policy))c$policy else sprintf(\"%.17g\",c$policy));xlabel<-\"Validation candidate\";ylabel<-\"Assumed cost / mass\";legend<-\"Validation candidate costs\"\n  }else if(api==\"calibrate\"){\n   edges<-if(is.null(a$binEdges))seq(0,1,.2)else vapply(a$binEdges,qnum,numeric(1));full<-calibrateG(d,ids,edges);for(k in c(\"ECE\",\"Brier\",\"uncertainty\",\"resolution\",\"reliability\",\"withinBinCorrection\",\"BrierIdentityResidual\"))metric(k,full[[k]])\n   for(b in full$bins)pt(b$index,b$meanPrediction,b$eventRate,paste0(\"bin:\",b$index));xlabel<-\"Bin mean forecast\";ylabel<-\"Bin event rate\";legend<-\"Binary-event reliability\"\n  }else if(api==\"groups\"){\n   full<-groupsG(d,ids,t,cost);metric(\"overallTPR\",full$overall$TPR);metric(\"TPRGap\",full$gaps$TPR);metric(\"precisionGap\",full$gaps$precision);metric(\"unknownMass\",full$unknownGroup$mass,\"mass\");metric(\"partitionResidual\",full$partitionMassResidual,\"mass\")\n   for(j in seq_along(full$groups))pt(j-1,j-1,full$groups[[j]]$metrics$TPR,full$groups[[j]]$group);xlabel<-\"Declared group position\";ylabel<-\"True positive rate\";legend<-\"Known-group TPR\"\n  }else stop(\"unknown declared fixed API\")\n }\n sm<-do.call(rbind,summary);pp<-do.call(rbind,points);write.csv(sm,file.path(outDir,\"summary.csv\"),row.names=FALSE,na=\"\");write.csv(pp,file.path(outDir,\"plot-points.csv\"),row.names=FALSE,na=\"\");svgFixed(file.path(outDir,\"plot.svg\"),pp,FIXED$title,xlabel,ylabel,legend);dput(list(api=api,variant=FIXED$variant,input=FIXED$args,arithmetic=\"Base-R binary64 fixed example; not an exact rational general validator\",result=full),file=file.path(outDir,\"full.txt\"));cat(\"PASS\",api,FIXED$variant,\"summary\",nrow(sm),\"points\",nrow(pp),\"\\n\")\n}\n\nFIXED<-list(api=\"calibrate\",variant=\"two-bins\",args=list(rows=list(list(id=\"a\",score=\".9\",y=1,group=\"A\"),list(id=\"b\",score=\".8\",y=1,group=\"A\"),list(id=\"c\",score=\".8\",y=0,group=\"A\"),list(id=\"d\",score=\".6\",y=0,group=\"B\"),list(id=\"e\",score=\".4\",y=1,group=\"B\"),list(id=\"f\",score=\".1\",y=0,group=\"B\")),binEdges=list(\"0\",\"1/2\",\"1\")),title=\"Six-card binary-event bins and full Brier identity\")\nfixedRun()\n",
        "input": {
          "rows": [
            {
              "id": "a",
              "score": ".9",
              "y": 1,
              "group": "A"
            },
            {
              "id": "b",
              "score": ".8",
              "y": 1,
              "group": "A"
            },
            {
              "id": "c",
              "score": ".8",
              "y": 0,
              "group": "A"
            },
            {
              "id": "d",
              "score": ".6",
              "y": 0,
              "group": "B"
            },
            {
              "id": "e",
              "score": ".4",
              "y": 1,
              "group": "B"
            },
            {
              "id": "f",
              "score": ".1",
              "y": 0,
              "group": "B"
            }
          ],
          "binEdges": [
            "0",
            "1/2",
            "1"
          ]
        },
        "inputFiles": [],
        "returnCode": 0,
        "expectedFailure": false,
        "stdout": "PASS calibrate two-bins summary 7 points 2 \n",
        "stderr": "During startup - Warning messages:\n1: Setting LC_COLLATE=C.UTF-8 failed \n2: Setting LC_CTYPE=C.UTF-8 failed \n3: Setting LC_MONETARY=C.UTF-8 failed \n4: Setting LC_TIME=C.UTF-8 failed \n",
        "summary": {
          "ECE": "0.266666667",
          "Brier": "0.236666667",
          "uncertainty": "0.25",
          "resolution": "0",
          "reliability": "0.07125",
          "withinBinCorrection": "-0.0845833333",
          "BrierIdentityResidual": "0"
        },
        "summaryRows": [
          {
            "metric": "ECE",
            "value": "0.266666667",
            "exactValue": "",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "Brier",
            "value": "0.236666667",
            "exactValue": "",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "uncertainty",
            "value": "0.25",
            "exactValue": "",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "resolution",
            "value": "0",
            "exactValue": "",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "reliability",
            "value": "0.07125",
            "exactValue": "",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "withinBinCorrection",
            "value": "-0.0845833333",
            "exactValue": "",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "BrierIdentityResidual",
            "value": "0",
            "exactValue": "",
            "unit": "dimensionless",
            "defined": "1"
          }
        ],
        "plotPoints": [
          {
            "series": "0",
            "index": "0",
            "xExact": "",
            "x": "0.25",
            "yExact": "",
            "y": "0.5",
            "id": "bin:0"
          },
          {
            "series": "0",
            "index": "1",
            "xExact": "",
            "x": "0.775",
            "yExact": "",
            "y": "0.5",
            "id": "bin:1"
          }
        ],
        "plotFile": "ml14-fixed-results/calibrate-two-bins-r/plot.svg",
        "plotSHA256": "83c11d02add103fe9257609bafabeef5e703e5f3b85c09dfdc66a0dd90d0b9f1",
        "files": [
          {
            "file": "ml14-fixed-results/calibrate-two-bins-r/full.txt",
            "sha256": "139f8df15c58dd9013acb6a5e46ab5d8d6d1f645ef932bf34141bfc03360d55c",
            "bytes": 1198
          },
          {
            "file": "ml14-fixed-results/calibrate-two-bins-r/plot-points.csv",
            "sha256": "6b92f8652edde43569a845e5eb981cbabc3b83b8e782a3f0e25b5dc83d4c0773",
            "bytes": 114
          },
          {
            "file": "ml14-fixed-results/calibrate-two-bins-r/plot.svg",
            "sha256": "83c11d02add103fe9257609bafabeef5e703e5f3b85c09dfdc66a0dd90d0b9f1",
            "bytes": 1222
          },
          {
            "file": "ml14-fixed-results/calibrate-two-bins-r/summary.csv",
            "sha256": "013f5520480aea98c99f88f1ee4b94d57d2101248c8048b6ff2e7cbdfc363215",
            "bytes": 372
          }
        ],
        "scope": "Actually executed standalone fixed example, Python exact Fraction versus base-R binary64. Approximate R residuals retained; not universal exact arithmetic/web validation/native UI. Source programs read factual3CSV only."
      },
      "reversed-one-bin": {
        "api": "calibrate",
        "variant": "reversed-one-bin",
        "language": "r",
        "title": "ECE zero while reversed forecasts have Brier0.81",
        "codeFile": "ml14-code/calibrate-reversed-one-bin.R",
        "codeSHA256": "476ec6cae3fba840e98e2108cf944b001a8ae830c3c788fadb640fbcba25216d",
        "code": "# ML14 standalone public counterpart, base R only.\n# Inputs are only the three factual CSVs; derived columns/previous model answers unused.\n# Binary64 arithmetic, not arbitrary-precision Fraction. At numerical cost ties\n# within 1e-12 retain the earliest candidate. Exact claims belong to Python/web.\n# SHA256 infrastructure below is reused verbatim from the previous public study.\nargs<-commandArgs(trailingOnly=TRUE);filearg<-grep(\"^--file=\",commandArgs(),value=TRUE)\nhere<-if(dir.exists(\"ml14-sources\"))getwd()else if(length(filearg))dirname(normalizePath(sub(\"^--file=\",\"\",filearg[1])))else getwd()\noption<-function(key,default){i<-match(key,args);if(is.na(i))default else args[i+1]}\nsourceDir<-option(\"--source\",file.path(here,\"ml14-sources\"));outDir<-option(\"--out\",file.path(getwd(),\"ml14-r-results\"));dir.create(outDir,recursive=TRUE,showWarnings=FALSE)\nnum<-function(x){x[x%in%c(\"\",\".\")]<-NA_character_;as.numeric(x)}\nfmt<-function(x)ifelse(is.na(x),\"\",sprintf(\"%.17g\",x))\nratio<-function(a,b)if(b==0)NA_real_ else a/b\nreadnative<-function(name)read.csv(file.path(sourceDir,name),check.names=FALSE,colClasses=\"character\",na.strings=character(),stringsAsFactors=FALSE)\n# Vectorized SHA256 for the short ASCII keys used in this study.\n# Unsigned words use exact integer-valued doubles; bit operations use safe\n# 16-bit halves, avoiding R's reserved signed-INT_MIN/NA representation.\nMOD<-2^32\nxor32<-function(a,b) as.double(bitwXor(as.integer(floor(a/65536)),as.integer(floor(b/65536))))*65536+as.double(bitwXor(as.integer(a%%65536),as.integer(b%%65536)))\nand32<-function(a,b) as.double(bitwAnd(as.integer(floor(a/65536)),as.integer(floor(b/65536))))*65536+as.double(bitwAnd(as.integer(a%%65536),as.integer(b%%65536)))\nrot<-function(x,n) floor(x/2^n)+(x%%2^n)*2^(32-n)\nxor3<-function(a,b,c) xor32(xor32(a,b),c)\nK<-c(0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5,0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967,0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070,0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3,0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2)\nsha256<-function(strings) {\n n<-length(strings);bytes<-matrix(0,n,64)\n for(i in seq_len(n)) {v<-utf8ToInt(strings[i]);stopifnot(length(v)<56,all(v<128));if(length(v)) bytes[i,seq_along(v)]<-v;bytes[i,length(v)+1]<-128;bits<-length(v)*8;bytes[i,61:64]<-c(floor(bits/2^24)%%256,floor(bits/2^16)%%256,floor(bits/256)%%256,bits%%256)}\n w<-matrix(0,n,64)\n for(j in 1:16) {b<-4*(j-1)+1;w[,j]<-bytes[,b]*2^24+bytes[,b+1]*2^16+bytes[,b+2]*256+bytes[,b+3]}\n for(j in 17:64) {s0<-xor3(rot(w[,j-15],7),rot(w[,j-15],18),floor(w[,j-15]/8));s1<-xor3(rot(w[,j-2],17),rot(w[,j-2],19),floor(w[,j-2]/1024));w[,j]<-(w[,j-16]+s0+w[,j-7]+s1)%%MOD}\n init<-c(0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19)\n state<-lapply(init,function(v) rep(v,n));a<-state[[1]];b<-state[[2]];c<-state[[3]];d<-state[[4]];e<-state[[5]];f<-state[[6]];g<-state[[7]];h<-state[[8]]\n for(j in 1:64) {S1<-xor3(rot(e,6),rot(e,11),rot(e,25));ch<-xor32(and32(e,f),and32(MOD-1-e,g));t1<-(h+S1+ch+K[j]+w[,j])%%MOD;S0<-xor3(rot(a,2),rot(a,13),rot(a,22));maj<-xor3(and32(a,b),and32(a,c),and32(b,c));t2<-(S0+maj)%%MOD;h<-g;g<-f;f<-e;e<-(d+t1)%%MOD;d<-c;c<-b;b<-a;a<-(t1+t2)%%MOD}\n end<-list(a,b,c,d,e,f,g,h);hex<-lapply(1:8,function(j){v<-(end[[j]]+init[j])%%MOD;paste0(sprintf(\"%04x\",as.integer(floor(v/65536))),sprintf(\"%04x\",as.integer(v%%65536)))})\n do.call(paste0,hex)\n}\nstopifnot(identical(sha256(c(\"abc\",\"\")),c(\"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad\",\"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855\")))\n\nloadData<-function(){\n wb<-readnative(\"actual64-country-four-indicators-original-2024.csv\");codes<-c(\"NY.GDP.PCAP.KD\",\"NY.GDP.MKTP.KD.ZG\",\"FP.CPI.TOTL.ZG\",\"SP.DYN.LE00.IN\");iso<-sort(unique(wb$countryISO3));stopifnot(nrow(wb)==64,length(iso)==16)\n tokens<-t(vapply(iso,function(s)wb$originalValueToken[match(paste(s,codes),paste(wb$countryISO3,wb$indicatorID))],character(4)));vals<-matrix(num(as.vector(tokens)),nrow=nrow(tokens))\n country<-list(id=paste0(iso,\":2024\"),sourceRow=1:16,originalID=iso,x=vals[,1:3,drop=FALSE],rawX=tokens[,1:3,drop=FALSE],nativeTarget=tokens[,4],y=as.integer(vals[,4]>=80),group=ifelse(is.na(vals[,1]),NA_character_,as.character(as.integer(vals[,1]>=25000))),lineage=vapply(iso,function(s)paste(wb$sourceRow[match(paste(s,codes),paste(wb$countryISO3,wb$indicatorID))],collapse=\";\"),character(1)),cat=integer(),units=c(\"constant2015USD/person\",\"annualPercent\",\"annualPercent\"))\n nls<-readnative(\"actual3613-NLS-original52-fields-groups-roles.csv\");raw<-cbind(nls$ed76,nls$age76,nls$nearc4)\n person<-list(id=paste0(\"person:\",nls$sourceRow),sourceRow=as.integer(nls$sourceRow),originalID=nls$id,x=matrix(num(as.vector(raw)),nrow=nrow(raw)),rawX=raw,nativeTarget=nls$wage76,y=as.integer(num(nls$wage76)>=500),group=ifelse(nls$black%in%c(\"\",\".\"),NA_character_,nls$black),lineage=nls$sourceRow,cat=2L,units=c(\"years\",\"years\",\"nativeCategory\"))\n ch<-readnative(\"actual3150-churn-original14-fields-groups-roles.csv\");raw<-cbind(ch[[\"Call  Failure\"]],ch$Complains,ch[[\"Subscription  Length\"]],ch[[\"Seconds of Use\"]])\n company<-list(id=paste0(\"customer:\",ch$sourceRow),sourceRow=as.integer(ch$sourceRow),originalID=rep(\"\",nrow(ch)),x=matrix(num(as.vector(raw)),nrow=nrow(raw)),rawX=raw,nativeTarget=ch$Churn,y=as.integer(ch$Churn),group=ifelse(ch[[\"Tariff Plan\"]]%in%c(\"\",\".\"),NA_character_,ch[[\"Tariff Plan\"]]),lineage=ch$sourceRow,cat=1L,units=c(\"count\",\"nativeCategory\",\"months\",\"seconds\"))\n stopifnot(nrow(nls)==3613,nrow(ch)==3150,identical(as.integer(ch$sourceRow[ch[[\"Charge  Amount\"]]==\"10\"]),c(474L,2174L,2274L,2374L,2674L,2924L,2974L)))\n result<-list(country=country,person=person,company=company)\n for(k in names(result)){d<-result[[k]];n<-length(d$id);d$eligible<-!is.na(d$y)&rowSums(is.na(d$x))==0;hash<-sha256(paste0(\"ML14-role|\",k,\"|\",d$id));rank<-integer(n);rank[order(hash,seq_len(n))]<-seq_len(n)-1L;d$plannedRole<-ifelse(rank%%5==0,\"test\",ifelse(rank%%5==1,\"validation\",\"train\"));d$role<-ifelse(d$eligible,d$plannedRole,\"excluded\");result[[k]]<-d}\n stopifnot(sum(result$person$eligible)==3017);result\n}\nfitmodel<-function(d){\n ids<-which(d$role==\"train\");p<-ncol(d$x);m<-vapply(seq_len(p),function(j)if((j-1)%in%d$cat)NA_real_ else median(d$x[ids,j]),numeric(1));z<-d$x\n for(j in seq_len(p))if(!((j-1)%in%d$cat))z[,j]<-as.numeric(z[,j]>m[j])\n keys<-apply(z,1,function(v)paste(fmt(v),collapse=\"|\"));lev<-unique(keys[ids]);mass<-vapply(lev,function(k)sum(keys[ids]==k),integer(1));positive<-vapply(lev,function(k)sum(d$y[ids][keys[ids]==k]),integer(1));prob<-(positive+1)/(mass+2);fallback<-(sum(d$y[ids])+1)/(length(ids)+2);pred<-prob[match(keys,lev)];unseen<-is.na(pred);pred[unseen]<-fallback;pred[!d$eligible]<-NA_real_;unseen[!d$eligible]<-NA\n list(ids=ids,medians=m,z=z,keys=keys,lev=lev,mass=mass,positive=positive,prob=prob,fallback=fallback,pred=pred,unseen=unseen)\n}\nmeasure<-function(d,p,ids,t=.5,cost=c(1,1)){\n use<-ids[d$eligible[ids]&!is.na(p[ids])];y<-d$y[use];a<-if(is.character(t))rep(t==\"always-positive\",length(use))else p[use]>=t\n TP<-sum(a&y==1);FP<-sum(a&y==0);FN<-sum(!a&y==1);TN<-sum(!a&y==0);P<-TP+FN;N<-FP+TN;W<-P+N;PP<-TP+FP;PN<-TN+FN;TPR<-ratio(TP,P);TNR<-ratio(TN,N);bs<-sum((p[use]-y)^2);tc<-FP*cost[1]+FN*cost[2]\n list(TP=TP,FP=FP,FN=FN,TN=TN,mass=W,positiveTargetMass=P,negativeTargetMass=N,predictedPositiveMass=PP,predictedNegativeMass=PN,prevalence=ratio(P,W),selectionRate=ratio(PP,W),accuracy=ratio(TP+TN,W),precision=ratio(TP,PP),negativePredictiveValue=ratio(TN,PN),TPR=TPR,FPR=ratio(FP,N),TNR=TNR,FNR=ratio(FN,P),F1=ratio(2*TP,2*TP+FP+FN),balancedAccuracy=if(is.na(TPR)||is.na(TNR))NA_real_ else(TPR+TNR)/2,Brier=ratio(bs,W),BrierSum=bs,totalCost=tc,meanCost=ratio(tc,W))\n}\ncurves<-function(d,p,ids){\n use<-ids[d$eligible[ids]&!is.na(p[ids])];scores<-sort(unique(p[use]),decreasing=TRUE);policies<-c(list(\"always-negative\"),as.list(scores));points<-lapply(policies,function(t){m<-measure(d,p,ids,t);c(list(policy=t),m[c(\"TP\",\"FP\",\"FN\",\"TN\",\"TPR\",\"FPR\",\"precision\")],list(recall=m$TPR))})\n pos<-use[d$y[use]==1];neg<-use[d$y[use]==0];U<-0;for(i in pos)U<-U+sum(p[i]>p[neg])+.5*sum(p[i]==p[neg])\n AP<-0;trap<-0;lastR<-0;lastP<-1\n if(length(pos)&&length(scores))for(j in seq_along(scores)){z<-points[[j+1]];AP<-AP+(z$recall-lastR)*z$precision;trap<-trap+(z$recall-lastR)*(z$precision+lastP)/2;lastR<-z$recall;lastP<-z$precision}\n list(points=points,ROC_AUC=ratio(U,length(pos)*length(neg)),averagePrecision=if(length(pos))AP else NA_real_,PRTrapezoidWithInitialPrecisionOne=if(length(pos))trap else NA_real_)\n}\ncalibrate<-function(d,p,ids){\n use<-ids[d$eligible[ids]&!is.na(p[ids])];W<-length(use);pi<-if(W)mean(d$y[use])else NA_real_;bins<-list();ECE<-rel<-res<-correction<-0\n whichbin<-findInterval(p[use],seq(0,1,.2),rightmost.closed=TRUE,all.inside=TRUE)\n for(b in 1:5){rr<-use[whichbin==b];w<-length(rr);mp<-if(w)mean(p[rr])else NA_real_;o<-if(w)mean(d$y[rr])else NA_real_;variance<-if(w)mean((p[rr]-mp)^2)else NA_real_;covariance<-if(w)mean((p[rr]-mp)*(d$y[rr]-o))else NA_real_;bc<-variance-2*covariance;gap<-mp-o\n  bins[[b]]<-list(mass=w,meanPrediction=mp,eventRate=o,gap=gap,absoluteGap=abs(gap),scoreVariance=variance,scoreTargetCovariance=covariance,withinBinCorrection=bc,rows=w,ids=d$id[rr])\n  if(w){share<-w/W;ECE<-ECE+share*abs(gap);rel<-rel+share*gap^2;res<-res+share*(o-pi)^2;correction<-correction+share*bc}\n };bs<-if(W)mean((p[use]-d$y[use])^2)else NA_real_;unc<-pi*(1-pi)\n list(bins=bins,ECE=if(W)ECE else NA_real_,Brier=bs,reliability=if(W)rel else NA_real_,resolution=if(W)res else NA_real_,uncertainty=unc,withinBinCorrection=if(W)correction else NA_real_,BrierIdentityResidual=bs-(unc-res+rel+correction))\n}\ncounts<-c(\"mass\",\"positiveTargetMass\",\"negativeTargetMass\",\"predictedPositiveMass\",\"predictedNegativeMass\");rates<-c(\"prevalence\",\"selectionRate\",\"accuracy\",\"precision\",\"negativePredictiveValue\",\"TPR\",\"FPR\",\"TNR\",\"FNR\",\"F1\",\"balancedAccuracy\",\"Brier\",\"BrierSum\",\"totalCost\",\"meanCost\")\ntables<-setNames(lapply(1:10,function(i)list()),c(\"predictions\",\"lineage\",\"fit-medians\",\"fit-cells\",\"validation-candidates\",\"test-metrics\",\"test-curves\",\"calibration-bins\",\"group-metrics\",\"chart-points\"))\nadd<-function(name,row)tables[[name]][[length(tables[[name]])+1L]]<<-row\nscalars<-function(m,keys){out<-list();for(k in keys){out[[paste0(k,\"Exact\")]]<-\"\";out[[paste0(k,\"Approx\")]]<-fmt(m[[k]])};out}\ntagrow<-function(kind,...)c(list(kind=kind),list(...))\npoint<-function(kind,chart,series,index,x,y,xunit=\"dimensionless\",yunit=\"dimensionless\",role=\"test\",tag=\"\"){add(\"chart-points\",tagrow(kind,chart=chart,series=series,index=index,xExact=\"\",xApprox=fmt(x),yExact=\"\",yApprox=fmt(y),xUnit=xunit,yUnit=yunit,role=role,tag=tag))}\nstudy<-function(kind,d){\n f<-fitmodel(d);n<-length(d$id);train<-which(d$role==\"train\");validation<-which(d$role==\"validation\");test<-which(d$role==\"test\");p<-f$pred;cv<-curves(d,p,test);cal<-calibrate(d,p,test)\n for(i in seq_len(n)){\n  reason<-if(d$eligible[i])\"\"else\"required-X-or-Y-missing\";transformed<-if(d$eligible[i])paste(fmt(f$z[i,]),collapse=\"|\")else\"\"\n  add(\"predictions\",tagrow(kind,id=d$id[i],sourceRow=d$sourceRow[i],originalID=d$originalID[i],plannedRole=d$plannedRole[i],role=d$role[i],group=ifelse(is.na(d$group[i]),\"\",d$group[i]),eligible=as.integer(d$eligible[i]),targetExact=fmt(d$y[i]),probabilityExact=\"\",probabilityApprox=fmt(p[i]),unseenCell=ifelse(is.na(f$unseen[i]),\"\",as.character(as.integer(f$unseen[i]))),transformedX=transformed,reason=reason))\n  raw<-d$rawX[i,];raw[raw%in%c(\"\",\".\")]<-\"\";nativeY<-d$nativeTarget[i];if(nativeY%in%c(\"\",\".\"))nativeY<-\"\"\n  add(\"lineage\",tagrow(kind,id=d$id[i],sourceRow=d$sourceRow[i],originalID=d$originalID[i],nativeSourceRows=d$lineage[i],rawX=paste(raw,collapse=\"|\"),nativeTarget=nativeY,derivedTarget=fmt(d$y[i]),nativeGroup=ifelse(is.na(d$group[i]),\"\",d$group[i]),plannedRole=d$plannedRole[i],role=d$role[i],eligible=as.integer(d$eligible[i]),analyticalMass=\"1\",reason=reason))\n }\n for(j in seq_len(ncol(d$x)))add(\"fit-medians\",tagrow(kind,feature=j-1,categorical=as.integer((j-1)%in%d$cat),fitRows=length(train),medianExact=\"\",medianApprox=fmt(f$medians[j]),unit=d$units[j]))\n for(j in seq_along(f$lev))add(\"fit-cells\",tagrow(kind,cell=f$lev[j],trainingRows=f$mass[j],positiveRows=f$positive[j],probabilityExact=\"\",probabilityApprox=fmt(f$prob[j]),fallbackExact=\"\",fallbackApprox=fmt(f$fallback)))\n for(j in seq_along(cv$points)){\n  z<-cv$points[[j]];t<-z$policy;add(\"test-curves\",c(tagrow(kind,point=j-1,policy=if(is.character(t))t else\"threshold\",thresholdExact=\"\",thresholdApprox=if(is.character(t))\"\"else fmt(t)),scalars(z,c(\"TP\",\"FP\",\"FN\",\"TN\",\"TPR\",\"FPR\",\"precision\",\"recall\"))))\n  point(kind,\"roc\",\"ROC\",j-1,z$FPR,z$TPR);point(kind,\"pr\",\"PR-observed\",j-1,z$recall,z$precision)\n }\n for(b in 1:5){z<-cal$bins[[b]];add(\"calibration-bins\",c(tagrow(kind,bin=b-1,leftExact=c(\"0\",\"1/5\",\"2/5\",\"3/5\",\"4/5\")[b],rightExact=c(\"1/5\",\"2/5\",\"3/5\",\"4/5\",\"1\")[b],rightClosed=as.integer(b==5),rows=z$rows,ids=paste(z$ids,collapse=\";\")),scalars(z,c(\"mass\",\"meanPrediction\",\"eventRate\",\"gap\",\"absoluteGap\",\"scoreVariance\",\"scoreTargetCovariance\",\"withinBinCorrection\"))));point(kind,\"reliability\",\"Binary event rate\",b-1,z$meanPrediction,z$eventRate,tag=paste0(\"rows=\",z$rows))}\n for(j in seq_along(test)){i<-test[j];point(kind,\"test-scores\",\"Training-fitted probability\",j-1,j,p[i],\"test-row position\",\"probability\",tag=d$id[i]);point(kind,\"test-scores\",\"Observed Y\",j-1,j,d$y[i],\"test-row position\",\"binary target\",tag=d$id[i])}\n scenarioNames<-c(\"equal\",\"miss-five\",\"alarm-five\");costs<-list(c(1,1),c(1,5),c(5,1))\n for(s in 1:3){name<-scenarioNames[s];cost<-costs[[s]];grid<-c(list(\"always-negative\"),as.list(sort(unique(p[validation]),decreasing=TRUE)));candidates<-lapply(grid,function(t)measure(d,p,validation,t,cost));values<-vapply(candidates,function(m)m$meanCost,numeric(1));best<-which(values<=min(values)+1e-12)[1];chosen<-grid[[best]];ev<-measure(d,p,test,chosen,cost)\n  for(j in seq_along(grid)){t<-grid[[j]];m<-candidates[[j]];cell<-setNames(lapply(c(\"TP\",\"FP\",\"FN\",\"TN\"),function(k)fmt(m[[k]])),paste0(c(\"TP\",\"FP\",\"FN\",\"TN\"),\"Exact\"));add(\"validation-candidates\",c(tagrow(kind,scenario=name,candidate=j-1,selected=as.integer(j==best),policy=if(is.character(t))t else\"threshold\",thresholdExact=\"\",thresholdApprox=if(is.character(t))\"\"else fmt(t),feasible=1,reasons=\"\"),cell,scalars(m,c(counts,\"TPR\",\"FPR\",\"precision\",\"meanCost\",\"totalCost\"))));point(kind,\"validation-cost\",name,j-1,j-1,m$meanCost,\"candidate index\",\"hypothetical cost units/mass\",\"validation\",if(is.character(t))t else fmt(t))}\n  m<-c(ev,cv[c(\"ROC_AUC\",\"averagePrecision\",\"PRTrapezoidWithInitialPrecisionOne\")],cal[c(\"ECE\",\"reliability\",\"resolution\",\"uncertainty\",\"withinBinCorrection\",\"BrierIdentityResidual\")])\n  for(k in c(\"TP\",\"FP\",\"FN\",\"TN\",counts,rates,\"ROC_AUC\",\"averagePrecision\",\"PRTrapezoidWithInitialPrecisionOne\",\"ECE\",\"reliability\",\"resolution\",\"uncertainty\",\"withinBinCorrection\",\"BrierIdentityResidual\")){\n   unit<-if(k%in%c(\"TP\",\"FP\",\"FN\",\"TN\",counts))\"rows\"else if(k==\"totalCost\")\"hypothetical cost units\"else if(k==\"meanCost\")\"hypothetical cost units/mass\"else if(k==\"BrierSum\")\"sum squared-probability loss\"else\"dimensionless\"\n   add(\"test-metrics\",tagrow(kind,scenario=name,metric=k,valueExact=\"\",valueApprox=fmt(m[[k]]),unit=unit))\n  }\n  lev<-unique(d$group[test][!is.na(d$group[test])]);sets<-c(list(test),lapply(lev,function(g)test[!is.na(d$group[test])&d$group[test]==g]),list(test[is.na(d$group[test])]))\n  types<-c(\"overall\",rep(\"known\",length(lev)),\"unknown\");tokens<-c(\"all\",lev,\"\")\n  for(j in seq_along(sets)){ids<-sets[[j]];m<-measure(d,p,ids,chosen,cost);cell<-setNames(lapply(c(\"TP\",\"FP\",\"FN\",\"TN\"),function(k)fmt(m[[k]])),paste0(c(\"TP\",\"FP\",\"FN\",\"TN\"),\"Exact\"));add(\"group-metrics\",c(tagrow(kind,scenario=name,groupType=types[j],groupToken=tokens[j],retainedRows=length(ids)),cell,scalars(m,c(counts,rates))));if(types[j]==\"known\")point(kind,\"group-TPR\",name,j-2,j-2,m$TPR,\"declared group position\",\"TPR\",tag=tokens[j])}\n }\n invisible(NULL)\n}\n\n# Fixed finite inputs only; not the complete web input/budget validator.\nqnum<-function(v){if(is.null(v))return(NA_real_);if(is.logical(v))return(as.numeric(v));s<-as.character(v);if(grepl(\"/\",s,fixed=TRUE)){a<-strsplit(s,\"/\",fixed=TRUE)[[1]];return(as.numeric(a[1])/as.numeric(a[2]))};as.numeric(s)}\nrowsG<-function(raw){\n n<-length(raw);get<-function(r,k,default=NULL)if(is.null(r[[k]]))default else r[[k]]\n id<-vapply(raw,function(r)as.character(r$id),character(1));p<-vapply(raw,function(r)qnum(r$score),numeric(1));y<-vapply(raw,function(r)qnum(r$y),numeric(1));w<-vapply(raw,function(r)qnum(get(r,\"weight\",\"1\")),numeric(1));role<-vapply(raw,function(r)get(r,\"role\",\"evaluation\"),character(1));group<-vapply(raw,function(r)as.character(get(r,\"group\",NA_character_)),character(1))\n stopifnot(all(w>=0),all(is.na(p)|(p>=0&p<=1)),all(is.na(y)|y%in%c(0,1)),!anyDuplicated(id));list(id=id,p=p,y=y,w=w,role=role,group=group,eligible=!is.na(p)&!is.na(y)&w>0&role!=\"excluded\")\n}\nscopeG<-function(d,role=\"all\")if(role==\"all\")seq_along(d$id)else which(d$role==role)\nmetricsG<-function(d,ids,t=.5,cost=c(1,1)){\n use<-ids[d$eligible[ids]];p<-d$p[use];y<-d$y[use];w<-d$w[use];a<-if(is.character(t))rep(t==\"always-positive\",length(use))else p>=t\n TP<-sum(w[a&y==1]);FP<-sum(w[a&y==0]);FN<-sum(w[!a&y==1]);TN<-sum(w[!a&y==0]);P<-TP+FN;N<-FP+TN;W<-P+N;PP<-TP+FP;PN<-TN+FN;TPR<-ratio(TP,P);TNR<-ratio(TN,N);bs<-sum(w*(p-y)^2);tc<-FP*cost[1]+FN*cost[2]\n list(confusion=list(TP=TP,FP=FP,FN=FN,TN=TN),mass=W,positiveTargetMass=P,negativeTargetMass=N,predictedPositiveMass=PP,predictedNegativeMass=PN,prevalence=ratio(P,W),selectionRate=ratio(PP,W),accuracy=ratio(TP+TN,W),precision=ratio(TP,PP),negativePredictiveValue=ratio(TN,PN),TPR=TPR,FPR=ratio(FP,N),TNR=TNR,FNR=ratio(FN,P),F1=ratio(2*TP,2*TP+FP+FN),balancedAccuracy=if(is.na(TPR)||is.na(TNR))NA_real_ else(TPR+TNR)/2,Brier=ratio(bs,W),BrierSum=bs,totalCost=tc,meanCost=ratio(tc,W),bayesThreshold=ratio(cost[1],sum(cost)))\n}\ncurvesG<-function(d,ids){\n use<-ids[d$eligible[ids]];grid<-c(list(\"always-negative\"),as.list(sort(unique(d$p[use]),decreasing=TRUE)));points<-lapply(grid,function(t){m<-metricsG(d,ids,t);c(list(policy=t),m$confusion,m[c(\"TPR\",\"FPR\",\"precision\")],list(recall=m$TPR))});pos<-use[d$y[use]==1];neg<-use[d$y[use]==0];P<-sum(d$w[pos]);N<-sum(d$w[neg]);U<-0\n for(i in pos)U<-U+d$w[i]*sum(d$w[neg]*((d$p[i]>d$p[neg])+.5*(d$p[i]==d$p[neg])))\n AP<-trap<-lastR<-0;lastP<-1\n if(P&&length(grid)>1)for(j in 2:length(grid)){z<-points[[j]];AP<-AP+(z$recall-lastR)*z$precision;trap<-trap+(z$recall-lastR)*(z$precision+lastP)/2;lastR<-z$recall;lastP<-z$precision}\n list(points=points,ROC_AUC=ratio(U,P*N),averagePrecision=if(P)AP else NA_real_,PRTrapezoidWithInitialPrecisionOne=if(P)trap else NA_real_)\n}\nchooseG<-function(d,a,cost){\n role<-if(is.null(a$selectionRole))\"validation\"else a$selectionRole;er<-if(is.null(a$evaluationRole))\"test\"else a$evaluationRole;ids<-scopeG(d,role);use<-ids[d$eligible[ids]];stopifnot(length(use)>0);grid<-if(is.null(a$thresholds))c(list(\"always-negative\"),as.list(sort(unique(d$p[use]),decreasing=TRUE)))else lapply(a$thresholds,function(t)if(t%in%c(\"always-negative\",\"always-positive\"))t else qnum(t))\n candidates<-lapply(seq_along(grid),function(j){m<-metricsG(d,ids,grid[[j]],cost);feasible<-TRUE;if(!is.null(a$minTPR))feasible<-feasible&&!is.na(m$TPR)&&m$TPR>=qnum(a$minTPR);if(!is.null(a$maxFPR))feasible<-feasible&&!is.na(m$FPR)&&m$FPR<=qnum(a$maxFPR);list(index=j-1,policy=grid[[j]],metrics=m,feasible=feasible)})\n good<-which(vapply(candidates,function(c)c$feasible,logical(1)));best<-NA_integer_;if(length(good)){v<-vapply(candidates[good],function(c)c$metrics$meanCost,numeric(1));best<-good[which(v<=min(v)+1e-12)[1]]}\n list(selectedIndex=if(is.na(best))NA_integer_ else best-1,selectedPolicy=if(is.na(best))NULL else grid[[best]],selectedValidation=if(is.na(best))NULL else candidates[[best]]$metrics,candidates=candidates,evaluation=if(is.na(best)||er==\"none\")NULL else metricsG(d,scopeG(d,er),grid[[best]],cost))\n}\ncalibrateG<-function(d,ids,edges){\n use<-ids[d$eligible[ids]];W<-sum(d$w[use]);pi<-ratio(sum(d$w[use]*d$y[use]),W);bins<-list();ECE<-rel<-res<-correction<-0;assign<-findInterval(d$p[use],edges,rightmost.closed=TRUE,all.inside=TRUE)\n for(b in seq_len(length(edges)-1)){rr<-use[assign==b];w<-sum(d$w[rr]);mp<-ratio(sum(d$w[rr]*d$p[rr]),w);o<-ratio(sum(d$w[rr]*d$y[rr]),w);variance<-if(w)sum(d$w[rr]*(d$p[rr]-mp)^2)/w else NA_real_;covariance<-if(w)sum(d$w[rr]*(d$p[rr]-mp)*(d$y[rr]-o))/w else NA_real_;bc<-variance-2*covariance;gap<-mp-o;bins[[b]]<-list(index=b-1,mass=w,meanPrediction=mp,eventRate=o,scoreVariance=variance,scoreTargetCovariance=covariance,withinBinCorrection=bc,ids=d$id[rr])\n  if(w){s<-w/W;ECE<-ECE+s*abs(gap);rel<-rel+s*gap^2;res<-res+s*(o-pi)^2;correction<-correction+s*bc}\n };bs<-ratio(sum(d$w[use]*(d$p[use]-d$y[use])^2),W);unc<-pi*(1-pi);list(bins=bins,Brier=bs,ECE=if(W)ECE else NA_real_,uncertainty=unc,reliability=if(W)rel else NA_real_,resolution=if(W)res else NA_real_,withinBinCorrection=if(W)correction else NA_real_,BrierIdentityResidual=bs-(unc-res+rel+correction))\n}\ngroupsG<-function(d,ids,t,cost){\n lev<-unique(d$group[ids][!is.na(d$group[ids])]);groups<-lapply(lev,function(g)list(group=g,metrics=metricsG(d,ids[!is.na(d$group[ids])&d$group[ids]==g],t,cost)));overall<-metricsG(d,ids,t,cost);unknown<-metricsG(d,ids[is.na(d$group[ids])],t,cost);gaps<-list()\n for(k in c(\"prevalence\",\"selectionRate\",\"TPR\",\"FPR\",\"precision\",\"accuracy\",\"meanCost\")){use<-Filter(function(g)g$metrics$mass>0,groups);v<-vapply(use,function(g)g$metrics[[k]],numeric(1));gaps[[k]]<-if(length(use)<2||anyNA(v))NA_real_ else max(v)-min(v)}\n list(overall=overall,groups=groups,unknownGroup=unknown,gaps=gaps,partitionMassResidual=overall$mass-unknown$mass-sum(vapply(groups,function(g)g$metrics$mass,numeric(1))))\n}\nsvgFixed<-function(file,points,title,xlabel,ylabel,legend){\n finite<-points[points$y!=\"undefined\"&points$x!=\"undefined\",,drop=FALSE];x<-as.numeric(finite$x);y<-as.numeric(finite$y);xmin<-if(length(x))min(x)else 0;xmax<-if(length(x))max(x)else 1;ymin<-min(c(0,y));ymax<-max(c(0,y));if(xmin==xmax){xmin<-xmin-.5;xmax<-xmax+.5};if(ymin==ymax)ymax<-ymin+1;X<-function(v)85+(v-xmin)/(xmax-xmin)*480;Y<-function(v)278-(v-ymin)/(ymax-ymin)*175\n esc<-function(s){s<-gsub(\"&\",\"&amp;\",s,fixed=TRUE);s<-gsub(\"<\",\"&lt;\",s,fixed=TRUE);gsub(\">\",\"&gt;\",s,fixed=TRUE)};s<-'<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"620\" height=\"360\" viewBox=\"0 0 620 360\"><rect width=\"620\" height=\"360\" fill=\"white\"/><g font-family=\"Arial, sans-serif\" font-size=\"13\" fill=\"#17324d\">'\n lines<-strwrap(title,width=65);for(i in seq_along(lines))s<-paste0(s,'<text x=\"25\" y=\"',24+(i-1)*18,'\">',esc(lines[i]),'</text>');colors<-c(\"#176b9b\",\"#b85e18\",\"#437e4d\")\n for(i in seq_along(legend))s<-paste0(s,'<circle cx=\"',30+(i-1)*250,'\" cy=\"76\" r=\"4\" fill=\"',colors[(i-1)%%3+1],'\"/><text x=\"',42+(i-1)*250,'\" y=\"80\">',esc(legend[i]),'</text>')\n s<-paste0(s,'<path d=\"M85 98V278H575\" fill=\"none\" stroke=\"#52677d\"/><text text-anchor=\"middle\" x=\"325\" y=\"338\">',esc(xlabel),'</text><text text-anchor=\"middle\" transform=\"translate(21,190) rotate(-90)\">',esc(ylabel),'</text>')\n for(i in 0:4){xx<-xmin+(xmax-xmin)*i/4;yy<-ymin+(ymax-ymin)*i/4;s<-paste0(s,'<text text-anchor=\"middle\" x=\"',sprintf(\"%.9g\",X(xx)),'\" y=\"305\">',sprintf(\"%.4g\",xx),'</text><text text-anchor=\"end\" x=\"77\" y=\"',sprintf(\"%.9g\",Y(yy)+4),'\">',sprintf(\"%.4g\",yy),'</text>')}\n for(i in seq_len(nrow(finite)))s<-paste0(s,'<circle cx=\"',sprintf(\"%.9g\",X(x[i])),'\" cy=\"',sprintf(\"%.9g\",Y(y[i])),'\" r=\"3\" fill=\"',colors[as.integer(finite$series[i])%%3+1],'\"/>');writeLines(paste0(s,'</g></svg>'),file,useBytes=TRUE)\n}\nfixedRun<-function(){\n api<-FIXED$api;a<-FIXED$args;summary<-list();points<-list();xlabel<-\"Declared index\";ylabel<-\"Value\";legend<-\"Declared result\"\n metric<-function(name,v,unit=\"dimensionless\"){if(is.null(v))v<-NA_real_;summary[[length(summary)+1L]]<<-data.frame(metric=name,value=if(is.na(v))\"undefined\"else sprintf(\"%.9g\",v),exactValue=\"\",unit=unit,defined=as.integer(!is.na(v)),stringsAsFactors=FALSE)}\n pt<-function(i,x,y,id=\"\",series=0){points[[length(points)+1L]]<<-data.frame(series=series,index=i,xExact=\"\",x=if(is.na(x))\"undefined\"else sprintf(\"%.9g\",x),yExact=\"\",y=if(is.na(y))\"undefined\"else sprintf(\"%.9g\",y),id=as.character(id),stringsAsFactors=FALSE)}\n if(api==\"realdata\"){\n  native<-loadData()[[a$kind]];fit<-fitmodel(native);d<-list(id=native$id,p=fit$pred,y=native$y,w=rep(1,length(native$id)),role=native$role,group=native$group,eligible=native$eligible);scenarios<-list()\n  for(j in 1:3){name<-c(\"equal\",\"miss-five\",\"alarm-five\")[j];cst<-list(c(1,1),c(1,5),c(5,1))[[j]];sel<-chooseG(d,list(),cst);scenarios[[j]]<-list(name=name,selection=sel);metric(paste0(name,\"Threshold\"),sel$selectedPolicy);metric(paste0(name,\"TestCost\"),sel$evaluation$meanCost,\"hypothetical cost units/mass\")}\n  ids<-scopeG(d,\"test\");cv<-curvesG(d,ids);cal<-calibrateG(d,ids,seq(0,1,.2));metric(\"testAUC\",cv$ROC_AUC);metric(\"testAP\",cv$averagePrecision);metric(\"testBrier\",cal$Brier);metric(\"eligibleRows\",sum(d$eligible),\"rows\")\n  for(j in seq_along(ids)){i<-ids[j];pt(j-1,j,d$p[i],d$id[i],0);pt(j-1,j,d$y[i],d$id[i],1)}\n  full<-list(kind=a$kind,fit=fit,scenarios=scenarios,testCurves=cv,testCalibration=cal,rowsScored=d);xlabel<-\"Test row, native order\";ylabel<-\"Y or probability\";legend<-c(\"Training-fitted probability\",\"Observed Y\")\n }else{\n  d<-rowsG(a$rows);role<-if(is.null(a$role))\"all\"else a$role;ids<-scopeG(d,role);cost<-if(is.null(a$costs))c(1,1)else c(qnum(a$costs$falsePositive),qnum(a$costs$falseNegative));t<-if(is.null(a$threshold)).5 else if(a$threshold%in%c(\"always-positive\",\"always-negative\"))a$threshold else qnum(a$threshold)\n  if(api==\"metrics\"){\n   full<-metricsG(d,ids,t,cost);for(k in c(\"mass\",\"accuracy\",\"precision\",\"TPR\",\"FPR\",\"F1\",\"Brier\",\"meanCost\"))metric(k,full[[k]],if(k==\"mass\")\"mass\"else if(k==\"meanCost\")\"hypothetical cost units/mass\"else\"dimensionless\");metric(\"BayesThreshold\",full$bayesThreshold)\n   for(i in 1:4)pt(i-1,i-1,full$confusion[[i]],names(full$confusion)[i]);xlabel<-\"TP / FP / FN / TN positions\";ylabel<-\"Analytical mass\"\n  }else if(api==\"curves\"){\n   full<-curvesG(d,ids);for(k in c(\"ROC_AUC\",\"averagePrecision\",\"PRTrapezoidWithInitialPrecisionOne\"))metric(k,full[[k]])\n   for(j in seq_along(full$points)){p<-full$points[[j]];pt(j-1,p$FPR,p$TPR,if(is.character(p$policy))p$policy else sprintf(\"%.17g\",p$policy))};xlabel<-\"False positive rate\";ylabel<-\"True positive rate\";legend<-\"Observed ROC operating points\"\n  }else if(api==\"choose\"){\n   full<-chooseG(d,a,cost);metric(\"selectedIndex\",full$selectedIndex,\"candidate index\");metric(\"minimumCost\",if(is.null(full$selectedValidation))NULL else full$selectedValidation$meanCost,\"hypothetical cost units/mass\");metric(\"feasible\",as.integer(!is.na(full$selectedIndex)),\"indicator\")\n   for(c in full$candidates)pt(c$index,c$index,c$metrics$meanCost,if(is.character(c$policy))c$policy else sprintf(\"%.17g\",c$policy));xlabel<-\"Validation candidate\";ylabel<-\"Assumed cost / mass\";legend<-\"Validation candidate costs\"\n  }else if(api==\"calibrate\"){\n   edges<-if(is.null(a$binEdges))seq(0,1,.2)else vapply(a$binEdges,qnum,numeric(1));full<-calibrateG(d,ids,edges);for(k in c(\"ECE\",\"Brier\",\"uncertainty\",\"resolution\",\"reliability\",\"withinBinCorrection\",\"BrierIdentityResidual\"))metric(k,full[[k]])\n   for(b in full$bins)pt(b$index,b$meanPrediction,b$eventRate,paste0(\"bin:\",b$index));xlabel<-\"Bin mean forecast\";ylabel<-\"Bin event rate\";legend<-\"Binary-event reliability\"\n  }else if(api==\"groups\"){\n   full<-groupsG(d,ids,t,cost);metric(\"overallTPR\",full$overall$TPR);metric(\"TPRGap\",full$gaps$TPR);metric(\"precisionGap\",full$gaps$precision);metric(\"unknownMass\",full$unknownGroup$mass,\"mass\");metric(\"partitionResidual\",full$partitionMassResidual,\"mass\")\n   for(j in seq_along(full$groups))pt(j-1,j-1,full$groups[[j]]$metrics$TPR,full$groups[[j]]$group);xlabel<-\"Declared group position\";ylabel<-\"True positive rate\";legend<-\"Known-group TPR\"\n  }else stop(\"unknown declared fixed API\")\n }\n sm<-do.call(rbind,summary);pp<-do.call(rbind,points);write.csv(sm,file.path(outDir,\"summary.csv\"),row.names=FALSE,na=\"\");write.csv(pp,file.path(outDir,\"plot-points.csv\"),row.names=FALSE,na=\"\");svgFixed(file.path(outDir,\"plot.svg\"),pp,FIXED$title,xlabel,ylabel,legend);dput(list(api=api,variant=FIXED$variant,input=FIXED$args,arithmetic=\"Base-R binary64 fixed example; not an exact rational general validator\",result=full),file=file.path(outDir,\"full.txt\"));cat(\"PASS\",api,FIXED$variant,\"summary\",nrow(sm),\"points\",nrow(pp),\"\\n\")\n}\n\nFIXED<-list(api=\"calibrate\",variant=\"reversed-one-bin\",args=list(rows=list(list(id=\"r1\",score=\".1\",y=1),list(id=\"r2\",score=\".9\",y=0)),binEdges=list(\"0\",\"1\")),title=\"ECE zero while reversed forecasts have Brier0.81\")\nfixedRun()\n",
        "codeText": "# ML14 standalone public counterpart, base R only.\n# Inputs are only the three factual CSVs; derived columns/previous model answers unused.\n# Binary64 arithmetic, not arbitrary-precision Fraction. At numerical cost ties\n# within 1e-12 retain the earliest candidate. Exact claims belong to Python/web.\n# SHA256 infrastructure below is reused verbatim from the previous public study.\nargs<-commandArgs(trailingOnly=TRUE);filearg<-grep(\"^--file=\",commandArgs(),value=TRUE)\nhere<-if(dir.exists(\"ml14-sources\"))getwd()else if(length(filearg))dirname(normalizePath(sub(\"^--file=\",\"\",filearg[1])))else getwd()\noption<-function(key,default){i<-match(key,args);if(is.na(i))default else args[i+1]}\nsourceDir<-option(\"--source\",file.path(here,\"ml14-sources\"));outDir<-option(\"--out\",file.path(getwd(),\"ml14-r-results\"));dir.create(outDir,recursive=TRUE,showWarnings=FALSE)\nnum<-function(x){x[x%in%c(\"\",\".\")]<-NA_character_;as.numeric(x)}\nfmt<-function(x)ifelse(is.na(x),\"\",sprintf(\"%.17g\",x))\nratio<-function(a,b)if(b==0)NA_real_ else a/b\nreadnative<-function(name)read.csv(file.path(sourceDir,name),check.names=FALSE,colClasses=\"character\",na.strings=character(),stringsAsFactors=FALSE)\n# Vectorized SHA256 for the short ASCII keys used in this study.\n# Unsigned words use exact integer-valued doubles; bit operations use safe\n# 16-bit halves, avoiding R's reserved signed-INT_MIN/NA representation.\nMOD<-2^32\nxor32<-function(a,b) as.double(bitwXor(as.integer(floor(a/65536)),as.integer(floor(b/65536))))*65536+as.double(bitwXor(as.integer(a%%65536),as.integer(b%%65536)))\nand32<-function(a,b) as.double(bitwAnd(as.integer(floor(a/65536)),as.integer(floor(b/65536))))*65536+as.double(bitwAnd(as.integer(a%%65536),as.integer(b%%65536)))\nrot<-function(x,n) floor(x/2^n)+(x%%2^n)*2^(32-n)\nxor3<-function(a,b,c) xor32(xor32(a,b),c)\nK<-c(0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5,0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967,0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070,0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3,0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2)\nsha256<-function(strings) {\n n<-length(strings);bytes<-matrix(0,n,64)\n for(i in seq_len(n)) {v<-utf8ToInt(strings[i]);stopifnot(length(v)<56,all(v<128));if(length(v)) bytes[i,seq_along(v)]<-v;bytes[i,length(v)+1]<-128;bits<-length(v)*8;bytes[i,61:64]<-c(floor(bits/2^24)%%256,floor(bits/2^16)%%256,floor(bits/256)%%256,bits%%256)}\n w<-matrix(0,n,64)\n for(j in 1:16) {b<-4*(j-1)+1;w[,j]<-bytes[,b]*2^24+bytes[,b+1]*2^16+bytes[,b+2]*256+bytes[,b+3]}\n for(j in 17:64) {s0<-xor3(rot(w[,j-15],7),rot(w[,j-15],18),floor(w[,j-15]/8));s1<-xor3(rot(w[,j-2],17),rot(w[,j-2],19),floor(w[,j-2]/1024));w[,j]<-(w[,j-16]+s0+w[,j-7]+s1)%%MOD}\n init<-c(0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19)\n state<-lapply(init,function(v) rep(v,n));a<-state[[1]];b<-state[[2]];c<-state[[3]];d<-state[[4]];e<-state[[5]];f<-state[[6]];g<-state[[7]];h<-state[[8]]\n for(j in 1:64) {S1<-xor3(rot(e,6),rot(e,11),rot(e,25));ch<-xor32(and32(e,f),and32(MOD-1-e,g));t1<-(h+S1+ch+K[j]+w[,j])%%MOD;S0<-xor3(rot(a,2),rot(a,13),rot(a,22));maj<-xor3(and32(a,b),and32(a,c),and32(b,c));t2<-(S0+maj)%%MOD;h<-g;g<-f;f<-e;e<-(d+t1)%%MOD;d<-c;c<-b;b<-a;a<-(t1+t2)%%MOD}\n end<-list(a,b,c,d,e,f,g,h);hex<-lapply(1:8,function(j){v<-(end[[j]]+init[j])%%MOD;paste0(sprintf(\"%04x\",as.integer(floor(v/65536))),sprintf(\"%04x\",as.integer(v%%65536)))})\n do.call(paste0,hex)\n}\nstopifnot(identical(sha256(c(\"abc\",\"\")),c(\"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad\",\"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855\")))\n\nloadData<-function(){\n wb<-readnative(\"actual64-country-four-indicators-original-2024.csv\");codes<-c(\"NY.GDP.PCAP.KD\",\"NY.GDP.MKTP.KD.ZG\",\"FP.CPI.TOTL.ZG\",\"SP.DYN.LE00.IN\");iso<-sort(unique(wb$countryISO3));stopifnot(nrow(wb)==64,length(iso)==16)\n tokens<-t(vapply(iso,function(s)wb$originalValueToken[match(paste(s,codes),paste(wb$countryISO3,wb$indicatorID))],character(4)));vals<-matrix(num(as.vector(tokens)),nrow=nrow(tokens))\n country<-list(id=paste0(iso,\":2024\"),sourceRow=1:16,originalID=iso,x=vals[,1:3,drop=FALSE],rawX=tokens[,1:3,drop=FALSE],nativeTarget=tokens[,4],y=as.integer(vals[,4]>=80),group=ifelse(is.na(vals[,1]),NA_character_,as.character(as.integer(vals[,1]>=25000))),lineage=vapply(iso,function(s)paste(wb$sourceRow[match(paste(s,codes),paste(wb$countryISO3,wb$indicatorID))],collapse=\";\"),character(1)),cat=integer(),units=c(\"constant2015USD/person\",\"annualPercent\",\"annualPercent\"))\n nls<-readnative(\"actual3613-NLS-original52-fields-groups-roles.csv\");raw<-cbind(nls$ed76,nls$age76,nls$nearc4)\n person<-list(id=paste0(\"person:\",nls$sourceRow),sourceRow=as.integer(nls$sourceRow),originalID=nls$id,x=matrix(num(as.vector(raw)),nrow=nrow(raw)),rawX=raw,nativeTarget=nls$wage76,y=as.integer(num(nls$wage76)>=500),group=ifelse(nls$black%in%c(\"\",\".\"),NA_character_,nls$black),lineage=nls$sourceRow,cat=2L,units=c(\"years\",\"years\",\"nativeCategory\"))\n ch<-readnative(\"actual3150-churn-original14-fields-groups-roles.csv\");raw<-cbind(ch[[\"Call  Failure\"]],ch$Complains,ch[[\"Subscription  Length\"]],ch[[\"Seconds of Use\"]])\n company<-list(id=paste0(\"customer:\",ch$sourceRow),sourceRow=as.integer(ch$sourceRow),originalID=rep(\"\",nrow(ch)),x=matrix(num(as.vector(raw)),nrow=nrow(raw)),rawX=raw,nativeTarget=ch$Churn,y=as.integer(ch$Churn),group=ifelse(ch[[\"Tariff Plan\"]]%in%c(\"\",\".\"),NA_character_,ch[[\"Tariff Plan\"]]),lineage=ch$sourceRow,cat=1L,units=c(\"count\",\"nativeCategory\",\"months\",\"seconds\"))\n stopifnot(nrow(nls)==3613,nrow(ch)==3150,identical(as.integer(ch$sourceRow[ch[[\"Charge  Amount\"]]==\"10\"]),c(474L,2174L,2274L,2374L,2674L,2924L,2974L)))\n result<-list(country=country,person=person,company=company)\n for(k in names(result)){d<-result[[k]];n<-length(d$id);d$eligible<-!is.na(d$y)&rowSums(is.na(d$x))==0;hash<-sha256(paste0(\"ML14-role|\",k,\"|\",d$id));rank<-integer(n);rank[order(hash,seq_len(n))]<-seq_len(n)-1L;d$plannedRole<-ifelse(rank%%5==0,\"test\",ifelse(rank%%5==1,\"validation\",\"train\"));d$role<-ifelse(d$eligible,d$plannedRole,\"excluded\");result[[k]]<-d}\n stopifnot(sum(result$person$eligible)==3017);result\n}\nfitmodel<-function(d){\n ids<-which(d$role==\"train\");p<-ncol(d$x);m<-vapply(seq_len(p),function(j)if((j-1)%in%d$cat)NA_real_ else median(d$x[ids,j]),numeric(1));z<-d$x\n for(j in seq_len(p))if(!((j-1)%in%d$cat))z[,j]<-as.numeric(z[,j]>m[j])\n keys<-apply(z,1,function(v)paste(fmt(v),collapse=\"|\"));lev<-unique(keys[ids]);mass<-vapply(lev,function(k)sum(keys[ids]==k),integer(1));positive<-vapply(lev,function(k)sum(d$y[ids][keys[ids]==k]),integer(1));prob<-(positive+1)/(mass+2);fallback<-(sum(d$y[ids])+1)/(length(ids)+2);pred<-prob[match(keys,lev)];unseen<-is.na(pred);pred[unseen]<-fallback;pred[!d$eligible]<-NA_real_;unseen[!d$eligible]<-NA\n list(ids=ids,medians=m,z=z,keys=keys,lev=lev,mass=mass,positive=positive,prob=prob,fallback=fallback,pred=pred,unseen=unseen)\n}\nmeasure<-function(d,p,ids,t=.5,cost=c(1,1)){\n use<-ids[d$eligible[ids]&!is.na(p[ids])];y<-d$y[use];a<-if(is.character(t))rep(t==\"always-positive\",length(use))else p[use]>=t\n TP<-sum(a&y==1);FP<-sum(a&y==0);FN<-sum(!a&y==1);TN<-sum(!a&y==0);P<-TP+FN;N<-FP+TN;W<-P+N;PP<-TP+FP;PN<-TN+FN;TPR<-ratio(TP,P);TNR<-ratio(TN,N);bs<-sum((p[use]-y)^2);tc<-FP*cost[1]+FN*cost[2]\n list(TP=TP,FP=FP,FN=FN,TN=TN,mass=W,positiveTargetMass=P,negativeTargetMass=N,predictedPositiveMass=PP,predictedNegativeMass=PN,prevalence=ratio(P,W),selectionRate=ratio(PP,W),accuracy=ratio(TP+TN,W),precision=ratio(TP,PP),negativePredictiveValue=ratio(TN,PN),TPR=TPR,FPR=ratio(FP,N),TNR=TNR,FNR=ratio(FN,P),F1=ratio(2*TP,2*TP+FP+FN),balancedAccuracy=if(is.na(TPR)||is.na(TNR))NA_real_ else(TPR+TNR)/2,Brier=ratio(bs,W),BrierSum=bs,totalCost=tc,meanCost=ratio(tc,W))\n}\ncurves<-function(d,p,ids){\n use<-ids[d$eligible[ids]&!is.na(p[ids])];scores<-sort(unique(p[use]),decreasing=TRUE);policies<-c(list(\"always-negative\"),as.list(scores));points<-lapply(policies,function(t){m<-measure(d,p,ids,t);c(list(policy=t),m[c(\"TP\",\"FP\",\"FN\",\"TN\",\"TPR\",\"FPR\",\"precision\")],list(recall=m$TPR))})\n pos<-use[d$y[use]==1];neg<-use[d$y[use]==0];U<-0;for(i in pos)U<-U+sum(p[i]>p[neg])+.5*sum(p[i]==p[neg])\n AP<-0;trap<-0;lastR<-0;lastP<-1\n if(length(pos)&&length(scores))for(j in seq_along(scores)){z<-points[[j+1]];AP<-AP+(z$recall-lastR)*z$precision;trap<-trap+(z$recall-lastR)*(z$precision+lastP)/2;lastR<-z$recall;lastP<-z$precision}\n list(points=points,ROC_AUC=ratio(U,length(pos)*length(neg)),averagePrecision=if(length(pos))AP else NA_real_,PRTrapezoidWithInitialPrecisionOne=if(length(pos))trap else NA_real_)\n}\ncalibrate<-function(d,p,ids){\n use<-ids[d$eligible[ids]&!is.na(p[ids])];W<-length(use);pi<-if(W)mean(d$y[use])else NA_real_;bins<-list();ECE<-rel<-res<-correction<-0\n whichbin<-findInterval(p[use],seq(0,1,.2),rightmost.closed=TRUE,all.inside=TRUE)\n for(b in 1:5){rr<-use[whichbin==b];w<-length(rr);mp<-if(w)mean(p[rr])else NA_real_;o<-if(w)mean(d$y[rr])else NA_real_;variance<-if(w)mean((p[rr]-mp)^2)else NA_real_;covariance<-if(w)mean((p[rr]-mp)*(d$y[rr]-o))else NA_real_;bc<-variance-2*covariance;gap<-mp-o\n  bins[[b]]<-list(mass=w,meanPrediction=mp,eventRate=o,gap=gap,absoluteGap=abs(gap),scoreVariance=variance,scoreTargetCovariance=covariance,withinBinCorrection=bc,rows=w,ids=d$id[rr])\n  if(w){share<-w/W;ECE<-ECE+share*abs(gap);rel<-rel+share*gap^2;res<-res+share*(o-pi)^2;correction<-correction+share*bc}\n };bs<-if(W)mean((p[use]-d$y[use])^2)else NA_real_;unc<-pi*(1-pi)\n list(bins=bins,ECE=if(W)ECE else NA_real_,Brier=bs,reliability=if(W)rel else NA_real_,resolution=if(W)res else NA_real_,uncertainty=unc,withinBinCorrection=if(W)correction else NA_real_,BrierIdentityResidual=bs-(unc-res+rel+correction))\n}\ncounts<-c(\"mass\",\"positiveTargetMass\",\"negativeTargetMass\",\"predictedPositiveMass\",\"predictedNegativeMass\");rates<-c(\"prevalence\",\"selectionRate\",\"accuracy\",\"precision\",\"negativePredictiveValue\",\"TPR\",\"FPR\",\"TNR\",\"FNR\",\"F1\",\"balancedAccuracy\",\"Brier\",\"BrierSum\",\"totalCost\",\"meanCost\")\ntables<-setNames(lapply(1:10,function(i)list()),c(\"predictions\",\"lineage\",\"fit-medians\",\"fit-cells\",\"validation-candidates\",\"test-metrics\",\"test-curves\",\"calibration-bins\",\"group-metrics\",\"chart-points\"))\nadd<-function(name,row)tables[[name]][[length(tables[[name]])+1L]]<<-row\nscalars<-function(m,keys){out<-list();for(k in keys){out[[paste0(k,\"Exact\")]]<-\"\";out[[paste0(k,\"Approx\")]]<-fmt(m[[k]])};out}\ntagrow<-function(kind,...)c(list(kind=kind),list(...))\npoint<-function(kind,chart,series,index,x,y,xunit=\"dimensionless\",yunit=\"dimensionless\",role=\"test\",tag=\"\"){add(\"chart-points\",tagrow(kind,chart=chart,series=series,index=index,xExact=\"\",xApprox=fmt(x),yExact=\"\",yApprox=fmt(y),xUnit=xunit,yUnit=yunit,role=role,tag=tag))}\nstudy<-function(kind,d){\n f<-fitmodel(d);n<-length(d$id);train<-which(d$role==\"train\");validation<-which(d$role==\"validation\");test<-which(d$role==\"test\");p<-f$pred;cv<-curves(d,p,test);cal<-calibrate(d,p,test)\n for(i in seq_len(n)){\n  reason<-if(d$eligible[i])\"\"else\"required-X-or-Y-missing\";transformed<-if(d$eligible[i])paste(fmt(f$z[i,]),collapse=\"|\")else\"\"\n  add(\"predictions\",tagrow(kind,id=d$id[i],sourceRow=d$sourceRow[i],originalID=d$originalID[i],plannedRole=d$plannedRole[i],role=d$role[i],group=ifelse(is.na(d$group[i]),\"\",d$group[i]),eligible=as.integer(d$eligible[i]),targetExact=fmt(d$y[i]),probabilityExact=\"\",probabilityApprox=fmt(p[i]),unseenCell=ifelse(is.na(f$unseen[i]),\"\",as.character(as.integer(f$unseen[i]))),transformedX=transformed,reason=reason))\n  raw<-d$rawX[i,];raw[raw%in%c(\"\",\".\")]<-\"\";nativeY<-d$nativeTarget[i];if(nativeY%in%c(\"\",\".\"))nativeY<-\"\"\n  add(\"lineage\",tagrow(kind,id=d$id[i],sourceRow=d$sourceRow[i],originalID=d$originalID[i],nativeSourceRows=d$lineage[i],rawX=paste(raw,collapse=\"|\"),nativeTarget=nativeY,derivedTarget=fmt(d$y[i]),nativeGroup=ifelse(is.na(d$group[i]),\"\",d$group[i]),plannedRole=d$plannedRole[i],role=d$role[i],eligible=as.integer(d$eligible[i]),analyticalMass=\"1\",reason=reason))\n }\n for(j in seq_len(ncol(d$x)))add(\"fit-medians\",tagrow(kind,feature=j-1,categorical=as.integer((j-1)%in%d$cat),fitRows=length(train),medianExact=\"\",medianApprox=fmt(f$medians[j]),unit=d$units[j]))\n for(j in seq_along(f$lev))add(\"fit-cells\",tagrow(kind,cell=f$lev[j],trainingRows=f$mass[j],positiveRows=f$positive[j],probabilityExact=\"\",probabilityApprox=fmt(f$prob[j]),fallbackExact=\"\",fallbackApprox=fmt(f$fallback)))\n for(j in seq_along(cv$points)){\n  z<-cv$points[[j]];t<-z$policy;add(\"test-curves\",c(tagrow(kind,point=j-1,policy=if(is.character(t))t else\"threshold\",thresholdExact=\"\",thresholdApprox=if(is.character(t))\"\"else fmt(t)),scalars(z,c(\"TP\",\"FP\",\"FN\",\"TN\",\"TPR\",\"FPR\",\"precision\",\"recall\"))))\n  point(kind,\"roc\",\"ROC\",j-1,z$FPR,z$TPR);point(kind,\"pr\",\"PR-observed\",j-1,z$recall,z$precision)\n }\n for(b in 1:5){z<-cal$bins[[b]];add(\"calibration-bins\",c(tagrow(kind,bin=b-1,leftExact=c(\"0\",\"1/5\",\"2/5\",\"3/5\",\"4/5\")[b],rightExact=c(\"1/5\",\"2/5\",\"3/5\",\"4/5\",\"1\")[b],rightClosed=as.integer(b==5),rows=z$rows,ids=paste(z$ids,collapse=\";\")),scalars(z,c(\"mass\",\"meanPrediction\",\"eventRate\",\"gap\",\"absoluteGap\",\"scoreVariance\",\"scoreTargetCovariance\",\"withinBinCorrection\"))));point(kind,\"reliability\",\"Binary event rate\",b-1,z$meanPrediction,z$eventRate,tag=paste0(\"rows=\",z$rows))}\n for(j in seq_along(test)){i<-test[j];point(kind,\"test-scores\",\"Training-fitted probability\",j-1,j,p[i],\"test-row position\",\"probability\",tag=d$id[i]);point(kind,\"test-scores\",\"Observed Y\",j-1,j,d$y[i],\"test-row position\",\"binary target\",tag=d$id[i])}\n scenarioNames<-c(\"equal\",\"miss-five\",\"alarm-five\");costs<-list(c(1,1),c(1,5),c(5,1))\n for(s in 1:3){name<-scenarioNames[s];cost<-costs[[s]];grid<-c(list(\"always-negative\"),as.list(sort(unique(p[validation]),decreasing=TRUE)));candidates<-lapply(grid,function(t)measure(d,p,validation,t,cost));values<-vapply(candidates,function(m)m$meanCost,numeric(1));best<-which(values<=min(values)+1e-12)[1];chosen<-grid[[best]];ev<-measure(d,p,test,chosen,cost)\n  for(j in seq_along(grid)){t<-grid[[j]];m<-candidates[[j]];cell<-setNames(lapply(c(\"TP\",\"FP\",\"FN\",\"TN\"),function(k)fmt(m[[k]])),paste0(c(\"TP\",\"FP\",\"FN\",\"TN\"),\"Exact\"));add(\"validation-candidates\",c(tagrow(kind,scenario=name,candidate=j-1,selected=as.integer(j==best),policy=if(is.character(t))t else\"threshold\",thresholdExact=\"\",thresholdApprox=if(is.character(t))\"\"else fmt(t),feasible=1,reasons=\"\"),cell,scalars(m,c(counts,\"TPR\",\"FPR\",\"precision\",\"meanCost\",\"totalCost\"))));point(kind,\"validation-cost\",name,j-1,j-1,m$meanCost,\"candidate index\",\"hypothetical cost units/mass\",\"validation\",if(is.character(t))t else fmt(t))}\n  m<-c(ev,cv[c(\"ROC_AUC\",\"averagePrecision\",\"PRTrapezoidWithInitialPrecisionOne\")],cal[c(\"ECE\",\"reliability\",\"resolution\",\"uncertainty\",\"withinBinCorrection\",\"BrierIdentityResidual\")])\n  for(k in c(\"TP\",\"FP\",\"FN\",\"TN\",counts,rates,\"ROC_AUC\",\"averagePrecision\",\"PRTrapezoidWithInitialPrecisionOne\",\"ECE\",\"reliability\",\"resolution\",\"uncertainty\",\"withinBinCorrection\",\"BrierIdentityResidual\")){\n   unit<-if(k%in%c(\"TP\",\"FP\",\"FN\",\"TN\",counts))\"rows\"else if(k==\"totalCost\")\"hypothetical cost units\"else if(k==\"meanCost\")\"hypothetical cost units/mass\"else if(k==\"BrierSum\")\"sum squared-probability loss\"else\"dimensionless\"\n   add(\"test-metrics\",tagrow(kind,scenario=name,metric=k,valueExact=\"\",valueApprox=fmt(m[[k]]),unit=unit))\n  }\n  lev<-unique(d$group[test][!is.na(d$group[test])]);sets<-c(list(test),lapply(lev,function(g)test[!is.na(d$group[test])&d$group[test]==g]),list(test[is.na(d$group[test])]))\n  types<-c(\"overall\",rep(\"known\",length(lev)),\"unknown\");tokens<-c(\"all\",lev,\"\")\n  for(j in seq_along(sets)){ids<-sets[[j]];m<-measure(d,p,ids,chosen,cost);cell<-setNames(lapply(c(\"TP\",\"FP\",\"FN\",\"TN\"),function(k)fmt(m[[k]])),paste0(c(\"TP\",\"FP\",\"FN\",\"TN\"),\"Exact\"));add(\"group-metrics\",c(tagrow(kind,scenario=name,groupType=types[j],groupToken=tokens[j],retainedRows=length(ids)),cell,scalars(m,c(counts,rates))));if(types[j]==\"known\")point(kind,\"group-TPR\",name,j-2,j-2,m$TPR,\"declared group position\",\"TPR\",tag=tokens[j])}\n }\n invisible(NULL)\n}\n\n# Fixed finite inputs only; not the complete web input/budget validator.\nqnum<-function(v){if(is.null(v))return(NA_real_);if(is.logical(v))return(as.numeric(v));s<-as.character(v);if(grepl(\"/\",s,fixed=TRUE)){a<-strsplit(s,\"/\",fixed=TRUE)[[1]];return(as.numeric(a[1])/as.numeric(a[2]))};as.numeric(s)}\nrowsG<-function(raw){\n n<-length(raw);get<-function(r,k,default=NULL)if(is.null(r[[k]]))default else r[[k]]\n id<-vapply(raw,function(r)as.character(r$id),character(1));p<-vapply(raw,function(r)qnum(r$score),numeric(1));y<-vapply(raw,function(r)qnum(r$y),numeric(1));w<-vapply(raw,function(r)qnum(get(r,\"weight\",\"1\")),numeric(1));role<-vapply(raw,function(r)get(r,\"role\",\"evaluation\"),character(1));group<-vapply(raw,function(r)as.character(get(r,\"group\",NA_character_)),character(1))\n stopifnot(all(w>=0),all(is.na(p)|(p>=0&p<=1)),all(is.na(y)|y%in%c(0,1)),!anyDuplicated(id));list(id=id,p=p,y=y,w=w,role=role,group=group,eligible=!is.na(p)&!is.na(y)&w>0&role!=\"excluded\")\n}\nscopeG<-function(d,role=\"all\")if(role==\"all\")seq_along(d$id)else which(d$role==role)\nmetricsG<-function(d,ids,t=.5,cost=c(1,1)){\n use<-ids[d$eligible[ids]];p<-d$p[use];y<-d$y[use];w<-d$w[use];a<-if(is.character(t))rep(t==\"always-positive\",length(use))else p>=t\n TP<-sum(w[a&y==1]);FP<-sum(w[a&y==0]);FN<-sum(w[!a&y==1]);TN<-sum(w[!a&y==0]);P<-TP+FN;N<-FP+TN;W<-P+N;PP<-TP+FP;PN<-TN+FN;TPR<-ratio(TP,P);TNR<-ratio(TN,N);bs<-sum(w*(p-y)^2);tc<-FP*cost[1]+FN*cost[2]\n list(confusion=list(TP=TP,FP=FP,FN=FN,TN=TN),mass=W,positiveTargetMass=P,negativeTargetMass=N,predictedPositiveMass=PP,predictedNegativeMass=PN,prevalence=ratio(P,W),selectionRate=ratio(PP,W),accuracy=ratio(TP+TN,W),precision=ratio(TP,PP),negativePredictiveValue=ratio(TN,PN),TPR=TPR,FPR=ratio(FP,N),TNR=TNR,FNR=ratio(FN,P),F1=ratio(2*TP,2*TP+FP+FN),balancedAccuracy=if(is.na(TPR)||is.na(TNR))NA_real_ else(TPR+TNR)/2,Brier=ratio(bs,W),BrierSum=bs,totalCost=tc,meanCost=ratio(tc,W),bayesThreshold=ratio(cost[1],sum(cost)))\n}\ncurvesG<-function(d,ids){\n use<-ids[d$eligible[ids]];grid<-c(list(\"always-negative\"),as.list(sort(unique(d$p[use]),decreasing=TRUE)));points<-lapply(grid,function(t){m<-metricsG(d,ids,t);c(list(policy=t),m$confusion,m[c(\"TPR\",\"FPR\",\"precision\")],list(recall=m$TPR))});pos<-use[d$y[use]==1];neg<-use[d$y[use]==0];P<-sum(d$w[pos]);N<-sum(d$w[neg]);U<-0\n for(i in pos)U<-U+d$w[i]*sum(d$w[neg]*((d$p[i]>d$p[neg])+.5*(d$p[i]==d$p[neg])))\n AP<-trap<-lastR<-0;lastP<-1\n if(P&&length(grid)>1)for(j in 2:length(grid)){z<-points[[j]];AP<-AP+(z$recall-lastR)*z$precision;trap<-trap+(z$recall-lastR)*(z$precision+lastP)/2;lastR<-z$recall;lastP<-z$precision}\n list(points=points,ROC_AUC=ratio(U,P*N),averagePrecision=if(P)AP else NA_real_,PRTrapezoidWithInitialPrecisionOne=if(P)trap else NA_real_)\n}\nchooseG<-function(d,a,cost){\n role<-if(is.null(a$selectionRole))\"validation\"else a$selectionRole;er<-if(is.null(a$evaluationRole))\"test\"else a$evaluationRole;ids<-scopeG(d,role);use<-ids[d$eligible[ids]];stopifnot(length(use)>0);grid<-if(is.null(a$thresholds))c(list(\"always-negative\"),as.list(sort(unique(d$p[use]),decreasing=TRUE)))else lapply(a$thresholds,function(t)if(t%in%c(\"always-negative\",\"always-positive\"))t else qnum(t))\n candidates<-lapply(seq_along(grid),function(j){m<-metricsG(d,ids,grid[[j]],cost);feasible<-TRUE;if(!is.null(a$minTPR))feasible<-feasible&&!is.na(m$TPR)&&m$TPR>=qnum(a$minTPR);if(!is.null(a$maxFPR))feasible<-feasible&&!is.na(m$FPR)&&m$FPR<=qnum(a$maxFPR);list(index=j-1,policy=grid[[j]],metrics=m,feasible=feasible)})\n good<-which(vapply(candidates,function(c)c$feasible,logical(1)));best<-NA_integer_;if(length(good)){v<-vapply(candidates[good],function(c)c$metrics$meanCost,numeric(1));best<-good[which(v<=min(v)+1e-12)[1]]}\n list(selectedIndex=if(is.na(best))NA_integer_ else best-1,selectedPolicy=if(is.na(best))NULL else grid[[best]],selectedValidation=if(is.na(best))NULL else candidates[[best]]$metrics,candidates=candidates,evaluation=if(is.na(best)||er==\"none\")NULL else metricsG(d,scopeG(d,er),grid[[best]],cost))\n}\ncalibrateG<-function(d,ids,edges){\n use<-ids[d$eligible[ids]];W<-sum(d$w[use]);pi<-ratio(sum(d$w[use]*d$y[use]),W);bins<-list();ECE<-rel<-res<-correction<-0;assign<-findInterval(d$p[use],edges,rightmost.closed=TRUE,all.inside=TRUE)\n for(b in seq_len(length(edges)-1)){rr<-use[assign==b];w<-sum(d$w[rr]);mp<-ratio(sum(d$w[rr]*d$p[rr]),w);o<-ratio(sum(d$w[rr]*d$y[rr]),w);variance<-if(w)sum(d$w[rr]*(d$p[rr]-mp)^2)/w else NA_real_;covariance<-if(w)sum(d$w[rr]*(d$p[rr]-mp)*(d$y[rr]-o))/w else NA_real_;bc<-variance-2*covariance;gap<-mp-o;bins[[b]]<-list(index=b-1,mass=w,meanPrediction=mp,eventRate=o,scoreVariance=variance,scoreTargetCovariance=covariance,withinBinCorrection=bc,ids=d$id[rr])\n  if(w){s<-w/W;ECE<-ECE+s*abs(gap);rel<-rel+s*gap^2;res<-res+s*(o-pi)^2;correction<-correction+s*bc}\n };bs<-ratio(sum(d$w[use]*(d$p[use]-d$y[use])^2),W);unc<-pi*(1-pi);list(bins=bins,Brier=bs,ECE=if(W)ECE else NA_real_,uncertainty=unc,reliability=if(W)rel else NA_real_,resolution=if(W)res else NA_real_,withinBinCorrection=if(W)correction else NA_real_,BrierIdentityResidual=bs-(unc-res+rel+correction))\n}\ngroupsG<-function(d,ids,t,cost){\n lev<-unique(d$group[ids][!is.na(d$group[ids])]);groups<-lapply(lev,function(g)list(group=g,metrics=metricsG(d,ids[!is.na(d$group[ids])&d$group[ids]==g],t,cost)));overall<-metricsG(d,ids,t,cost);unknown<-metricsG(d,ids[is.na(d$group[ids])],t,cost);gaps<-list()\n for(k in c(\"prevalence\",\"selectionRate\",\"TPR\",\"FPR\",\"precision\",\"accuracy\",\"meanCost\")){use<-Filter(function(g)g$metrics$mass>0,groups);v<-vapply(use,function(g)g$metrics[[k]],numeric(1));gaps[[k]]<-if(length(use)<2||anyNA(v))NA_real_ else max(v)-min(v)}\n list(overall=overall,groups=groups,unknownGroup=unknown,gaps=gaps,partitionMassResidual=overall$mass-unknown$mass-sum(vapply(groups,function(g)g$metrics$mass,numeric(1))))\n}\nsvgFixed<-function(file,points,title,xlabel,ylabel,legend){\n finite<-points[points$y!=\"undefined\"&points$x!=\"undefined\",,drop=FALSE];x<-as.numeric(finite$x);y<-as.numeric(finite$y);xmin<-if(length(x))min(x)else 0;xmax<-if(length(x))max(x)else 1;ymin<-min(c(0,y));ymax<-max(c(0,y));if(xmin==xmax){xmin<-xmin-.5;xmax<-xmax+.5};if(ymin==ymax)ymax<-ymin+1;X<-function(v)85+(v-xmin)/(xmax-xmin)*480;Y<-function(v)278-(v-ymin)/(ymax-ymin)*175\n esc<-function(s){s<-gsub(\"&\",\"&amp;\",s,fixed=TRUE);s<-gsub(\"<\",\"&lt;\",s,fixed=TRUE);gsub(\">\",\"&gt;\",s,fixed=TRUE)};s<-'<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"620\" height=\"360\" viewBox=\"0 0 620 360\"><rect width=\"620\" height=\"360\" fill=\"white\"/><g font-family=\"Arial, sans-serif\" font-size=\"13\" fill=\"#17324d\">'\n lines<-strwrap(title,width=65);for(i in seq_along(lines))s<-paste0(s,'<text x=\"25\" y=\"',24+(i-1)*18,'\">',esc(lines[i]),'</text>');colors<-c(\"#176b9b\",\"#b85e18\",\"#437e4d\")\n for(i in seq_along(legend))s<-paste0(s,'<circle cx=\"',30+(i-1)*250,'\" cy=\"76\" r=\"4\" fill=\"',colors[(i-1)%%3+1],'\"/><text x=\"',42+(i-1)*250,'\" y=\"80\">',esc(legend[i]),'</text>')\n s<-paste0(s,'<path d=\"M85 98V278H575\" fill=\"none\" stroke=\"#52677d\"/><text text-anchor=\"middle\" x=\"325\" y=\"338\">',esc(xlabel),'</text><text text-anchor=\"middle\" transform=\"translate(21,190) rotate(-90)\">',esc(ylabel),'</text>')\n for(i in 0:4){xx<-xmin+(xmax-xmin)*i/4;yy<-ymin+(ymax-ymin)*i/4;s<-paste0(s,'<text text-anchor=\"middle\" x=\"',sprintf(\"%.9g\",X(xx)),'\" y=\"305\">',sprintf(\"%.4g\",xx),'</text><text text-anchor=\"end\" x=\"77\" y=\"',sprintf(\"%.9g\",Y(yy)+4),'\">',sprintf(\"%.4g\",yy),'</text>')}\n for(i in seq_len(nrow(finite)))s<-paste0(s,'<circle cx=\"',sprintf(\"%.9g\",X(x[i])),'\" cy=\"',sprintf(\"%.9g\",Y(y[i])),'\" r=\"3\" fill=\"',colors[as.integer(finite$series[i])%%3+1],'\"/>');writeLines(paste0(s,'</g></svg>'),file,useBytes=TRUE)\n}\nfixedRun<-function(){\n api<-FIXED$api;a<-FIXED$args;summary<-list();points<-list();xlabel<-\"Declared index\";ylabel<-\"Value\";legend<-\"Declared result\"\n metric<-function(name,v,unit=\"dimensionless\"){if(is.null(v))v<-NA_real_;summary[[length(summary)+1L]]<<-data.frame(metric=name,value=if(is.na(v))\"undefined\"else sprintf(\"%.9g\",v),exactValue=\"\",unit=unit,defined=as.integer(!is.na(v)),stringsAsFactors=FALSE)}\n pt<-function(i,x,y,id=\"\",series=0){points[[length(points)+1L]]<<-data.frame(series=series,index=i,xExact=\"\",x=if(is.na(x))\"undefined\"else sprintf(\"%.9g\",x),yExact=\"\",y=if(is.na(y))\"undefined\"else sprintf(\"%.9g\",y),id=as.character(id),stringsAsFactors=FALSE)}\n if(api==\"realdata\"){\n  native<-loadData()[[a$kind]];fit<-fitmodel(native);d<-list(id=native$id,p=fit$pred,y=native$y,w=rep(1,length(native$id)),role=native$role,group=native$group,eligible=native$eligible);scenarios<-list()\n  for(j in 1:3){name<-c(\"equal\",\"miss-five\",\"alarm-five\")[j];cst<-list(c(1,1),c(1,5),c(5,1))[[j]];sel<-chooseG(d,list(),cst);scenarios[[j]]<-list(name=name,selection=sel);metric(paste0(name,\"Threshold\"),sel$selectedPolicy);metric(paste0(name,\"TestCost\"),sel$evaluation$meanCost,\"hypothetical cost units/mass\")}\n  ids<-scopeG(d,\"test\");cv<-curvesG(d,ids);cal<-calibrateG(d,ids,seq(0,1,.2));metric(\"testAUC\",cv$ROC_AUC);metric(\"testAP\",cv$averagePrecision);metric(\"testBrier\",cal$Brier);metric(\"eligibleRows\",sum(d$eligible),\"rows\")\n  for(j in seq_along(ids)){i<-ids[j];pt(j-1,j,d$p[i],d$id[i],0);pt(j-1,j,d$y[i],d$id[i],1)}\n  full<-list(kind=a$kind,fit=fit,scenarios=scenarios,testCurves=cv,testCalibration=cal,rowsScored=d);xlabel<-\"Test row, native order\";ylabel<-\"Y or probability\";legend<-c(\"Training-fitted probability\",\"Observed Y\")\n }else{\n  d<-rowsG(a$rows);role<-if(is.null(a$role))\"all\"else a$role;ids<-scopeG(d,role);cost<-if(is.null(a$costs))c(1,1)else c(qnum(a$costs$falsePositive),qnum(a$costs$falseNegative));t<-if(is.null(a$threshold)).5 else if(a$threshold%in%c(\"always-positive\",\"always-negative\"))a$threshold else qnum(a$threshold)\n  if(api==\"metrics\"){\n   full<-metricsG(d,ids,t,cost);for(k in c(\"mass\",\"accuracy\",\"precision\",\"TPR\",\"FPR\",\"F1\",\"Brier\",\"meanCost\"))metric(k,full[[k]],if(k==\"mass\")\"mass\"else if(k==\"meanCost\")\"hypothetical cost units/mass\"else\"dimensionless\");metric(\"BayesThreshold\",full$bayesThreshold)\n   for(i in 1:4)pt(i-1,i-1,full$confusion[[i]],names(full$confusion)[i]);xlabel<-\"TP / FP / FN / TN positions\";ylabel<-\"Analytical mass\"\n  }else if(api==\"curves\"){\n   full<-curvesG(d,ids);for(k in c(\"ROC_AUC\",\"averagePrecision\",\"PRTrapezoidWithInitialPrecisionOne\"))metric(k,full[[k]])\n   for(j in seq_along(full$points)){p<-full$points[[j]];pt(j-1,p$FPR,p$TPR,if(is.character(p$policy))p$policy else sprintf(\"%.17g\",p$policy))};xlabel<-\"False positive rate\";ylabel<-\"True positive rate\";legend<-\"Observed ROC operating points\"\n  }else if(api==\"choose\"){\n   full<-chooseG(d,a,cost);metric(\"selectedIndex\",full$selectedIndex,\"candidate index\");metric(\"minimumCost\",if(is.null(full$selectedValidation))NULL else full$selectedValidation$meanCost,\"hypothetical cost units/mass\");metric(\"feasible\",as.integer(!is.na(full$selectedIndex)),\"indicator\")\n   for(c in full$candidates)pt(c$index,c$index,c$metrics$meanCost,if(is.character(c$policy))c$policy else sprintf(\"%.17g\",c$policy));xlabel<-\"Validation candidate\";ylabel<-\"Assumed cost / mass\";legend<-\"Validation candidate costs\"\n  }else if(api==\"calibrate\"){\n   edges<-if(is.null(a$binEdges))seq(0,1,.2)else vapply(a$binEdges,qnum,numeric(1));full<-calibrateG(d,ids,edges);for(k in c(\"ECE\",\"Brier\",\"uncertainty\",\"resolution\",\"reliability\",\"withinBinCorrection\",\"BrierIdentityResidual\"))metric(k,full[[k]])\n   for(b in full$bins)pt(b$index,b$meanPrediction,b$eventRate,paste0(\"bin:\",b$index));xlabel<-\"Bin mean forecast\";ylabel<-\"Bin event rate\";legend<-\"Binary-event reliability\"\n  }else if(api==\"groups\"){\n   full<-groupsG(d,ids,t,cost);metric(\"overallTPR\",full$overall$TPR);metric(\"TPRGap\",full$gaps$TPR);metric(\"precisionGap\",full$gaps$precision);metric(\"unknownMass\",full$unknownGroup$mass,\"mass\");metric(\"partitionResidual\",full$partitionMassResidual,\"mass\")\n   for(j in seq_along(full$groups))pt(j-1,j-1,full$groups[[j]]$metrics$TPR,full$groups[[j]]$group);xlabel<-\"Declared group position\";ylabel<-\"True positive rate\";legend<-\"Known-group TPR\"\n  }else stop(\"unknown declared fixed API\")\n }\n sm<-do.call(rbind,summary);pp<-do.call(rbind,points);write.csv(sm,file.path(outDir,\"summary.csv\"),row.names=FALSE,na=\"\");write.csv(pp,file.path(outDir,\"plot-points.csv\"),row.names=FALSE,na=\"\");svgFixed(file.path(outDir,\"plot.svg\"),pp,FIXED$title,xlabel,ylabel,legend);dput(list(api=api,variant=FIXED$variant,input=FIXED$args,arithmetic=\"Base-R binary64 fixed example; not an exact rational general validator\",result=full),file=file.path(outDir,\"full.txt\"));cat(\"PASS\",api,FIXED$variant,\"summary\",nrow(sm),\"points\",nrow(pp),\"\\n\")\n}\n\nFIXED<-list(api=\"calibrate\",variant=\"reversed-one-bin\",args=list(rows=list(list(id=\"r1\",score=\".1\",y=1),list(id=\"r2\",score=\".9\",y=0)),binEdges=list(\"0\",\"1\")),title=\"ECE zero while reversed forecasts have Brier0.81\")\nfixedRun()\n",
        "input": {
          "rows": [
            {
              "id": "r1",
              "score": ".1",
              "y": 1
            },
            {
              "id": "r2",
              "score": ".9",
              "y": 0
            }
          ],
          "binEdges": [
            "0",
            "1"
          ]
        },
        "inputFiles": [],
        "returnCode": 0,
        "expectedFailure": false,
        "stdout": "PASS calibrate reversed-one-bin summary 7 points 1 \n",
        "stderr": "During startup - Warning messages:\n1: Setting LC_COLLATE=C.UTF-8 failed \n2: Setting LC_CTYPE=C.UTF-8 failed \n3: Setting LC_MONETARY=C.UTF-8 failed \n4: Setting LC_TIME=C.UTF-8 failed \n",
        "summary": {
          "ECE": "0",
          "Brier": "0.81",
          "uncertainty": "0.25",
          "resolution": "0",
          "reliability": "0",
          "withinBinCorrection": "0.56",
          "BrierIdentityResidual": "0"
        },
        "summaryRows": [
          {
            "metric": "ECE",
            "value": "0",
            "exactValue": "",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "Brier",
            "value": "0.81",
            "exactValue": "",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "uncertainty",
            "value": "0.25",
            "exactValue": "",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "resolution",
            "value": "0",
            "exactValue": "",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "reliability",
            "value": "0",
            "exactValue": "",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "withinBinCorrection",
            "value": "0.56",
            "exactValue": "",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "BrierIdentityResidual",
            "value": "0",
            "exactValue": "",
            "unit": "dimensionless",
            "defined": "1"
          }
        ],
        "plotPoints": [
          {
            "series": "0",
            "index": "0",
            "xExact": "",
            "x": "0.5",
            "yExact": "",
            "y": "0.5",
            "id": "bin:0"
          }
        ],
        "plotFile": "ml14-fixed-results/calibrate-reversed-one-bin-r/plot.svg",
        "plotSHA256": "c766c07d0c81aaa1706ed29ea0c9bc61f946d6fbfbebb90a5c0f8b2db7689c7e",
        "files": [
          {
            "file": "ml14-fixed-results/calibrate-reversed-one-bin-r/full.txt",
            "sha256": "6ea935eb6bc90524f73931af54384cf95f445d3b8ea213ab41dbc9942a53870f",
            "bytes": 660
          },
          {
            "file": "ml14-fixed-results/calibrate-reversed-one-bin-r/plot-points.csv",
            "sha256": "ba1881442a16cb0ea710bf4791f27b9719098beb38c4f61f803bdc97ee797dc5",
            "bytes": 80
          },
          {
            "file": "ml14-fixed-results/calibrate-reversed-one-bin-r/plot.svg",
            "sha256": "c766c07d0c81aaa1706ed29ea0c9bc61f946d6fbfbebb90a5c0f8b2db7689c7e",
            "bytes": 1159
          },
          {
            "file": "ml14-fixed-results/calibrate-reversed-one-bin-r/summary.csv",
            "sha256": "203baf27bcfe4cd8c60288d75d4d521b51db25178bd950fa21773e0abf39729c",
            "bytes": 340
          }
        ],
        "scope": "Actually executed standalone fixed example, Python exact Fraction versus base-R binary64. Approximate R residuals retained; not universal exact arithmetic/web validation/native UI. Source programs read factual3CSV only."
      }
    }
  },
  "groups": {
    "python": {
      "six-cards": {
        "api": "groups",
        "variant": "six-cards",
        "language": "python",
        "title": "Group TPR gaps and undefined precision comparison",
        "codeFile": "ml14-code/groups-six-cards.py",
        "codeSHA256": "801576b2055c4a6dbdb894387ba6d4dd21a0e19303a3fcc360380bc5c3eb4f7c",
        "code": "#!/usr/bin/env python3\n\"\"\"ML14 standalone exact finite study, Python standard library only.\nInputs: only the three retained factual source CSVs below.\nDerived role/target/group/eligibility columns in those CSVs are NOT inputs.\nRebuilds SHA256 roles, train-only medians/cell scores, validation thresholds,\ntest curves, binary-event reliability and descriptive group ledgers.\nCosts 1/1,1/5,5/1 are hypothetical units, not measured intervention returns.\nThis is author public reproduction, not independent scientific review.\n\"\"\"\n\"\"\"Author Fraction reference, separate from product JavaScript; not independent peer.\"\"\"\nfrom fractions import Fraction as F\nfrom collections import Counter,defaultdict\ndef read(raw):\n rows=[]\n for i,r in enumerate(raw):\n  s=None if r['score']is None else F(str(r['score']));y=None if r['y']is None else F(int(r['y']))if isinstance(r['y'],bool)else F(str(r['y']));w=F(str(r.get('weight','1')));role=r.get('role','evaluation')\n  rows.append(dict(id=r['id'],index=i,score=s,y=y,w=w,role=role,group=r.get('group'),eligible=s is not None and y is not None and w>0 and role!='excluded'))\n return rows\ndef scoped(rows,role='all'):return rows if role=='all'else[r for r in rows if r['role']==role]\ndef divide(n,d):return None if not d else n/d\ndef policy(v):return v if v in ['always-negative','always-positive']else F(str(v))\ndef positive(p,s):return p=='always-positive'if isinstance(p,str)else s>=p\ndef cost(a=None):\n a={}if a is None else a;fp=F(str(a.get('falsePositive','1')));fn=F(str(a.get('falseNegative','1')));return fp,fn\ndef metrics(rows,threshold=F(1,2),cc=(F(1),F(1))):\n counts=dict(TP=F(0),FP=F(0),FN=F(0),TN=F(0));brier=F(0);pred=[]\n for r in rows:\n  if not r['eligible']:pred.append(dict(id=r['id'],index=r['index'],eligible=False,decision=None,probability=None,Brier=None));continue\n  yes=positive(threshold,r['score']);cell=('T'if yes==bool(r['y'])else'F')+('P'if yes else'N');counts[cell]+=r['w'];loss=(r['score']-r['y'])**2;brier+=r['w']*loss;pred.append(dict(id=r['id'],index=r['index'],eligible=True,decision=int(yes),probability=r['score'],Brier=loss))\n TP,FP,FN,TN=[counts[k]for k in ['TP','FP','FN','TN']];P=TP+FN;N=TN+FP;mass=P+N;PP=TP+FP;PN=TN+FN;TPR=divide(TP,P);TNR=divide(TN,N);total=FP*cc[0]+FN*cc[1]\n return dict(confusion=counts,mass=mass,positiveTargetMass=P,negativeTargetMass=N,predictedPositiveMass=PP,predictedNegativeMass=PN,prevalence=divide(P,mass),selectionRate=divide(PP,mass),accuracy=divide(TP+TN,mass),precision=divide(TP,PP),negativePredictiveValue=divide(TN,PN),TPR=TPR,FPR=divide(FP,N),TNR=TNR,FNR=divide(FN,P),F1=divide(2*TP,2*TP+FP+FN),balancedAccuracy=None if TPR is None or TNR is None else(TPR+TNR)/2,Brier=divide(brier,mass),BrierSum=brier,totalCost=total,meanCost=divide(total,mass),predictions=pred,bayesThreshold=divide(cc[0],sum(cc)))\ndef curves(rows):\n use=[r for r in rows if r['eligible']];pos=Counter();neg=Counter()\n for r in use:(pos if r['y']else neg)[r['score']]+=r['w']\n P=sum(pos.values(),F(0));N=sum(neg.values(),F(0));pairs=F(0)\n for a,wa in pos.items():\n  for b,wb in neg.items():pairs+=wa*wb*(F(1)if a>b else F(1,2)if a==b else F(0))\n thresholds=['always-negative']+sorted({r['score']for r in use},reverse=True);points=[];AP=F(0);trap=F(0);lastR=F(0);lastP=F(1)\n for i,p in enumerate(thresholds):\n  m=metrics(rows,p);points.append(dict(policy=p,TP=m['confusion']['TP'],FP=m['confusion']['FP'],FN=m['confusion']['FN'],TN=m['confusion']['TN'],TPR=m['TPR'],FPR=m['FPR'],precision=m['precision'],recall=m['TPR']))\n  if i and P:\n   R=m['TPR'];PP=m['precision'];AP+=(R-lastR)*PP;trap+=(R-lastR)*(PP+lastP)/2;lastR=R;lastP=PP\n return dict(positiveMass=P,negativeMass=N,ROC_AUC=divide(pairs,P*N),weightedConcordantPlusHalfTiedMass=pairs,averagePrecision=AP if P else None,PRTrapezoidWithInitialPrecisionOne=trap if P else None,points=points)\ndef choose(rows,a,cc):\n sr=a.get('selectionRole','validation');er=a.get('evaluationRole','test');rr=scoped(rows,sr);thresholds=[policy(t)for t in a['thresholds']]if'thresholds'in a else['always-negative']+sorted({r['score']for r in rr if r['eligible']},reverse=True)\n candidates=[]\n for i,p in enumerate(thresholds):\n  m=metrics(rr,p,cc);reasons=[]\n  if'minTPR'in a and(m['TPR']is None or m['TPR']<F(str(a['minTPR']))):reasons.append('TPR-undefined'if m['TPR']is None else'below-minTPR')\n  if'maxFPR'in a and(m['FPR']is None or m['FPR']>F(str(a['maxFPR']))):reasons.append('FPR-undefined'if m['FPR']is None else'above-maxFPR')\n  candidates.append(dict(index=i,policy=p,metrics=m,feasible=not reasons,reasons=reasons))\n eligible=[c for c in candidates if c['feasible']];best=min(eligible,key=lambda c:(c['metrics']['meanCost'],c['index']))if eligible else None\n return dict(selectedIndex=None if best is None else best['index'],selectedPolicy=None if best is None else best['policy'],candidates=candidates,selectedValidation=None if best is None else best['metrics'],evaluation=None if best is None or er=='none'else metrics(scoped(rows,er),best['policy'],cc),selectionIDs=[r['id']for r in rr if r['eligible']])\ndef calibrate(rows,ee):\n buckets=[[]for _ in range(len(ee)-1)]\n for r in rows:\n  if not r['eligible']:continue\n  j=next((i for i in range(len(ee)-1)if r['score']<ee[i+1]),len(ee)-2);buckets[j].append(r)\n mass=sum((r['w']for r in rows if r['eligible']),F(0));P=sum((r['w']*r['y']for r in rows if r['eligible']),F(0));pi=divide(P,mass);Brier=None if not mass else sum((r['w']*(r['score']-r['y'])**2 for r in rows if r['eligible']),F(0))/mass;ECE=F(0);reliability=F(0);resolution=F(0);correction=F(0);bins=[]\n for i,rr in enumerate(buckets):\n  w=sum((r['w']for r in rr),F(0));mp=None if not w else sum((r['w']*r['score']for r in rr),F(0))/w;o=None if not w else sum((r['w']*r['y']for r in rr),F(0))/w\n  variance=None if not w else sum((r['w']*(r['score']-mp)**2 for r in rr),F(0))/w\n  covariance=None if not w else sum((r['w']*(r['score']-mp)*(r['y']-o)for r in rr),F(0))/w\n  bc=None if not w else variance-2*covariance;gap=None if not w else mp-o\n  bins.append(dict(index=i,rows=len(rr),mass=w,meanPrediction=mp,eventRate=o,gap=gap,absoluteGap=None if gap is None else abs(gap),scoreVariance=variance,scoreTargetCovariance=covariance,withinBinCorrection=bc,ids=[r['id']for r in rr]))\n  if w:\n   share=w/mass;ECE+=share*abs(gap);reliability+=share*gap**2;resolution+=share*(o-pi)**2;correction+=share*bc\n uncertainty=None if pi is None else pi*(1-pi);residual=None if Brier is None else Brier-(uncertainty-resolution+reliability+correction)\n return dict(mass=mass,prevalence=pi,Brier=Brier,ECE=ECE if mass else None,reliability=reliability if mass else None,resolution=resolution if mass else None,uncertainty=uncertainty,withinBinCorrection=correction if mass else None,BrierIdentityResidual=residual,bins=bins)\ndef typed(v):return type(v).__name__,v\ndef groups(rows,p,cc):\n bins={}\n for r in rows:\n  if r['group']is not None:bins.setdefault(typed(r['group']),[]).append(r)\n gm=[dict(group=rr[0]['group'],metrics=metrics(rr,p,cc))for rr in bins.values()];overall=metrics(rows,p,cc);unknown=metrics([r for r in rows if r['group']is None],p,cc);gaps={}\n for key in ['prevalence','selectionRate','TPR','FPR','precision','accuracy','meanCost']:\n  positive=[g for g in gm if g['metrics']['mass']>0];undefined=[g['group']for g in positive if g['metrics'][key]is None];vals=[g['metrics'][key]for g in positive if g['metrics'][key]is not None]\n  gaps[key]=dict(value=None if len(positive)<2 or undefined else max(vals)-min(vals),undefinedGroups=undefined,comparedPositiveMassGroups=[g['group']for g in positive])\n return dict(overall=overall,groups=gm,unknownGroup=unknown,gaps=gaps,partitionMassResidual=overall['mass']-unknown['mass']-sum((g['metrics']['mass']for g in gm),F(0)))\ndef actual_model(M):\n raw=M['records'];cat=M['categoricalFeatures'];p=len(raw[0]['x']);train=[r for r in raw if r['role']=='train'];medians=[]\n for j in range(p):\n  if j in cat:medians.append(None);continue\n  values=sorted(F(r['x'][j])for r in train);n=len(values);medians.append(values[n//2]if n%2 else(values[n//2-1]+values[n//2])/2)\n def transform(r):return[F(v)if j in cat else F(int(F(v)>medians[j]))for j,v in enumerate(r['x'])]\n counts={}\n for r in train:\n  key=tuple(transform(r));n,s=counts.get(key,(0,0));counts[key]=(n+1,s+int(r['y']))\n probabilities={k:F(s+1,n+2)for k,(n,s)in counts.items()};fallback=F(sum(int(r['y'])for r in train)+1,len(train)+2);scored=[]\n for i,r in enumerate(raw):\n  eligible=r['role']!='excluded';z=transform(r)if eligible else None;key=None if z is None else tuple(z);score=None if not eligible else probabilities.get(key,fallback)\n  scored.append(dict(id=r['id'],index=i,role=r['role'],group=r['group'],y=None if r['y']is None else F(r['y']),score=score,w=F(1),eligible=eligible,transformedX=z,unseenCell=None if not eligible else key not in probabilities))\n return dict(medians=medians,cells=counts,probabilities=probabilities,fallback=fallback,rows=scored,trainIDs=[r['id']for r in train])\n\n\nimport csv,json,hashlib,argparse,datetime\nfrom pathlib import Path\ndef missing(v):return None if v in ['', '.',None]else v\ndef load_sources(folder):\n def read_csv(name):\n  with (folder/name).open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))\n wb=read_csv('actual64-country-four-indicators-original-2024.csv')\n codes=['NY.GDP.PCAP.KD','NY.GDP.MKTP.KD.ZG','FP.CPI.TOTL.ZG','SP.DYN.LE00.IN']\n lookup={(r['countryISO3'],r['indicatorID']):r for r in wb};country=[]\n for i,iso in enumerate(sorted({r['countryISO3']for r in wb}),1):\n  native=[lookup[iso,c]for c in codes];v=[missing(r['originalValueToken'])for r in native]\n  country.append(dict(id=iso+':2024',sourceRow=i,originalID=iso,x=v[:3],y=None if v[3]is None else str(int(F(v[3])>=80)),group=None if v[0]is None else str(int(F(v[0])>=25000)),nativeTarget=v[3],nativeSourceRows=';'.join(r['sourceRow']for r in native)))\n nls=read_csv('actual3613-NLS-original52-fields-groups-roles.csv');person=[]\n for r in nls:\n  y=missing(r['wage76']);person.append(dict(id='person:'+r['sourceRow'],sourceRow=int(r['sourceRow']),originalID=r['id'],x=[missing(r[k])for k in ['ed76','age76','nearc4']],y=None if y is None else str(int(F(y)>=500)),group=missing(r['black']),nativeTarget=y,nativeSourceRows=r['sourceRow']))\n ch=read_csv('actual3150-churn-original14-fields-groups-roles.csv');company=[]\n for r in ch:\n  company.append(dict(id='customer:'+r['sourceRow'],sourceRow=int(r['sourceRow']),originalID='',x=[missing(r[k])for k in ['Call  Failure','Complains','Subscription  Length','Seconds of Use']],y=missing(r['Churn']),group=missing(r['Tariff Plan']),nativeTarget=missing(r['Churn']),nativeSourceRows=r['sourceRow']))\n assert len(wb)==64 and len(country)==16 and len(nls)==3613 and len(ch)==3150\n assert [int(r['sourceRow'])for r in ch if r['Charge  Amount']=='10']==[474,2174,2274,2374,2674,2924,2974]\n models={}\n for kind,raw,cat,units in [('country',country,[],['constant2015USD/person','annualPercent','annualPercent']),('person',person,[2],['years','years','nativeCategory']),('company',company,[1],['count','nativeCategory','months','seconds'])]:\n  order=sorted(range(len(raw)),key=lambda i:(hashlib.sha256(('ML14-role|'+kind+'|'+raw[i]['id']).encode()).hexdigest(),i))\n  for rank,i in enumerate(order):\n   r=raw[i];r['plannedRole']='test'if rank%5==0 else'validation'if rank%5==1 else'train';r['eligible']=None not in r['x']+[r['y']];r['role']=r['plannedRole']if r['eligible']else'excluded';r['weight']='1'\n  models[kind]=dict(records=raw,categoricalFeatures=cat,featureUnits=units)\n assert sum(r['eligible']for r in person)==3017\n return models\n\ndef exact(v):return ''if v is None else str(v)\ndef approx(v):return ''if v is None else format(float(v),'.17g')\ndef scalar_fields(m,keys):\n out={}\n for k in keys:\n  out[k+'Exact']=exact(m[k]);out[k+'Approx']=approx(m[k])\n return out\nCOUNTS=['mass','positiveTargetMass','negativeTargetMass','predictedPositiveMass','predictedNegativeMass']\nRATES=['prevalence','selectionRate','accuracy','precision','negativePredictiveValue','TPR','FPR','TNR','FNR','F1','balancedAccuracy','Brier','BrierSum','totalCost','meanCost']\nSCENARIOS=[('equal',F(1),F(1)),('miss-five',F(1),F(5)),('alarm-five',F(5),F(1))]\ndef packed(v):\n if isinstance(v,F):return str(v)\n if isinstance(v,dict):return{str(k):packed(x)for k,x in v.items()}\n if isinstance(v,(tuple,list)):return[packed(x)for x in v]\n return v\ndef run_study(source,out):\n out.mkdir(parents=True,exist_ok=True);models=load_sources(source)\n tables={name:[]for name in ['predictions','lineage','fit-medians','fit-cells','validation-candidates','test-metrics','test-curves','calibration-bins','group-metrics','chart-points']}\n studies={};charts=[]\n def point(kind,chart,series,index,x,y,xunit='dimensionless',yunit='dimensionless',role='test',tag=''):\n  tables['chart-points'].append(dict(kind=kind,chart=chart,series=series,index=index,xExact=exact(x),xApprox=approx(x),yExact=exact(y),yApprox=approx(y),xUnit=xunit,yUnit=yunit,role=role,tag=tag))\n for kind,M in models.items():\n  fit=actual_model(M);rr=fit['rows'];native=M['records'];test=scoped(rr,'test');cv=curves(test);cal=calibrate(test,[F(0),F(1,5),F(2,5),F(3,5),F(4,5),F(1)]);scenarios=[]\n  for i,r in enumerate(rr):\n   n=native[i];reason=''if r['eligible']else'required-X-or-Y-missing'\n   tables['predictions'].append(dict(kind=kind,id=r['id'],sourceRow=n['sourceRow'],originalID=n['originalID'],plannedRole=n['plannedRole'],role=r['role'],group=''if r['group']is None else r['group'],eligible=int(r['eligible']),targetExact=exact(r['y']),probabilityExact=exact(r['score']),probabilityApprox=approx(r['score']),unseenCell=''if r['unseenCell']is None else int(r['unseenCell']),transformedX=''if r['transformedX']is None else'|'.join(map(str,r['transformedX'])),reason=reason))\n   tables['lineage'].append(dict(kind=kind,id=r['id'],sourceRow=n['sourceRow'],originalID=n['originalID'],nativeSourceRows=n['nativeSourceRows'],rawX='|'.join(''if x is None else x for x in n['x']),nativeTarget=''if n['nativeTarget']is None else n['nativeTarget'],derivedTarget=exact(r['y']),nativeGroup=''if n['group']is None else n['group'],plannedRole=n['plannedRole'],role=r['role'],eligible=int(r['eligible']),analyticalMass='1',reason=reason))\n  for j,v in enumerate(fit['medians']):tables['fit-medians'].append(dict(kind=kind,feature=j,categorical=int(j in M['categoricalFeatures']),fitRows=len(fit['trainIDs']),medianExact=exact(v),medianApprox=approx(v),unit=M['featureUnits'][j]))\n  for key,(mass,pos)in fit['cells'].items():tables['fit-cells'].append(dict(kind=kind,cell='|'.join(map(str,key)),trainingRows=mass,positiveRows=pos,probabilityExact=exact(fit['probabilities'][key]),probabilityApprox=approx(fit['probabilities'][key]),fallbackExact=exact(fit['fallback']),fallbackApprox=approx(fit['fallback'])))\n  for j,p in enumerate(cv['points']):\n   policy=p['policy'];tables['test-curves'].append(dict(kind=kind,point=j,policy=policy if isinstance(policy,str)else'threshold',thresholdExact=''if isinstance(policy,str)else exact(policy),thresholdApprox=''if isinstance(policy,str)else approx(policy),**scalar_fields(p,['TP','FP','FN','TN','TPR','FPR','precision','recall'])))\n   point(kind,'roc','ROC',j,p['FPR'],p['TPR']);point(kind,'pr','PR-observed',j,p['recall'],p['precision'])\n  for b in cal['bins']:\n   tables['calibration-bins'].append(dict(kind=kind,bin=b['index'],leftExact=str(F(b['index'],5)),rightExact=str(F(b['index']+1,5)),rightClosed=int(b['index']==4),rows=b['rows'],ids=';'.join(str(i)for i in b['ids']),**scalar_fields(b,['mass','meanPrediction','eventRate','gap','absoluteGap','scoreVariance','scoreTargetCovariance','withinBinCorrection'])))\n   point(kind,'reliability','Binary event rate',b['index'],b['meanPrediction'],b['eventRate'],tag='rows='+str(b['rows']))\n  for j,r in enumerate(test):\n   point(kind,'test-scores','Training-fitted probability',j,F(j+1),r['score'],'test-row position','probability',tag=r['id'])\n   point(kind,'test-scores','Observed Y',j,F(j+1),r['y'],'test-row position','binary target',tag=r['id'])\n  for name,fp,fn in SCENARIOS:\n   choice=choose(rr,{},(fp,fn));gm=groups(test,choice['selectedPolicy'],(fp,fn));scenarios.append(dict(name=name,costs=dict(falsePositive=fp,falseNegative=fn),selection=choice,groups=gm));ev=choice['evaluation']\n   for c in choice['candidates']:\n    policy=c['policy'];mm=c['metrics'];tables['validation-candidates'].append(dict(kind=kind,scenario=name,candidate=c['index'],selected=int(c['index']==choice['selectedIndex']),policy=policy if isinstance(policy,str)else'threshold',thresholdExact=''if isinstance(policy,str)else exact(policy),thresholdApprox=''if isinstance(policy,str)else approx(policy),feasible=int(c['feasible']),reasons=';'.join(c['reasons']),**{k+'Exact':str(v)for k,v in mm['confusion'].items()},**scalar_fields(mm,COUNTS+['TPR','FPR','precision','meanCost','totalCost'])))\n    point(kind,'validation-cost',name,c['index'],F(c['index']),mm['meanCost'],'candidate index','hypothetical cost units/mass','validation',tag=exact(policy))\n   mm={**ev,**ev['confusion'],**{k:cv[k]for k in ['ROC_AUC','averagePrecision','PRTrapezoidWithInitialPrecisionOne']},**{k:cal[k]for k in ['ECE','reliability','resolution','uncertainty','withinBinCorrection','BrierIdentityResidual']}}\n   for key in ['TP','FP','FN','TN']+COUNTS+RATES+['ROC_AUC','averagePrecision','PRTrapezoidWithInitialPrecisionOne','ECE','reliability','resolution','uncertainty','withinBinCorrection','BrierIdentityResidual']:\n    unit='rows'if key in ['TP','FP','FN','TN']+COUNTS else'hypothetical cost units'if key=='totalCost'else'hypothetical cost units/mass'if key=='meanCost'else'sum squared-probability loss'if key=='BrierSum'else'dimensionless'\n    tables['test-metrics'].append(dict(kind=kind,scenario=name,metric=key,valueExact=exact(mm[key]),valueApprox=approx(mm[key]),unit=unit))\n   allg=[('overall','all',gm['overall'])]+[('known',str(g['group']),g['metrics'])for g in gm['groups']]+[('unknown','',gm['unknownGroup'])]\n   for j,(typ,token,g)in enumerate(allg):\n    tables['group-metrics'].append(dict(kind=kind,scenario=name,groupType=typ,groupToken=token,retainedRows=g.get('retainedRows',sum((r['group']==token)if typ=='known'else(r['group']is None)if typ=='unknown'else True for r in test)),**{k+'Exact':str(v)for k,v in g['confusion'].items()},**scalar_fields(g,COUNTS+RATES)))\n    if typ=='known':point(kind,'group-TPR',name,j-1,F(j-1),g['TPR'],'declared group position','TPR',tag=token)\n  studies[kind]=dict(kind=kind,rows=len(native),eligibleRows=sum(r['eligible']for r in rr),trainingIDs=fit['trainIDs'],fitMedians=fit['medians'],fitCells=[dict(cell=list(k),mass=n,positive=s,probability=fit['probabilities'][k])for k,(n,s)in fit['cells'].items()],fallback=fit['fallback'],scenarios=scenarios,testCurves=cv,testCalibration=cal,rowsScored=rr)\n files=[]\n for name,rows in tables.items():\n  p=out/('computed-'+name+'.csv')\n  with p.open('w',encoding='utf8',newline='')as f:w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows)\n  files.append(dict(file=p.name,rows=len(rows),columns=len(rows[0]),bodyFields=len(rows)*len(rows[0]),sha256=hashlib.sha256(p.read_bytes()).hexdigest()))\n (out/'study.json').write_text(json.dumps(packed(studies),ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\n sourceFiles=[source/n for n in ['actual64-country-four-indicators-original-2024.csv','actual3613-NLS-original52-fields-groups-roles.csv','actual3150-churn-original14-fields-groups-roles.csv']]\n provenance=dict(chapter='ML-14',arithmetic='Python stdlib Fraction exact finite values from original decimal strings; binary64 valueApprox is display only.',inputs=[dict(file=p.name,sha256=hashlib.sha256(p.read_bytes()).hexdigest())for p in sourceFiles],priorEngineModelsScoresOrComputedFilesRead=False,roleRule=\"SHA256('ML14-role|'+kind+'|'+ID),rankmod5=0test/1validation/others train before eligibility\",costs='Hypothetical1/1,1/5,5/1; no causal intervention returns',files=files,observations={k:dict(sourceRows=v['rows'],eligibleRows=v['eligibleRows'],trainingRows=len(v['trainingIDs']))for k,v in studies.items()})\n (out/'provenance.json').write_text(json.dumps(provenance,ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\n print(json.dumps(dict(status='PASS standalone completed',files=len(files),bodyFields=sum(f['bodyFields']for f in files),observations=provenance['observations'])))\n\n# Fixed declared examples: full web budget/option validation is not reproduced.\nfrom html import escape\nimport textwrap\ndef validated_rows(raw):\n for r in raw:\n  assert F(str(r.get('weight','1')))>=0,'negative analytical mass'\n  assert r['score']is None or 0<=F(str(r['score']))<=1,'score outside zero/one'\n  assert r['y']is None or F(str(int(r['y']))if isinstance(r['y'],bool)else str(r['y']))in [0,1],'binary target required'\n return read(raw)\ndef serial(v):\n if isinstance(v,F):return dict(exactFraction=str(v),value=float(v))\n if isinstance(v,(list,tuple)):return[serial(x)for x in v]\n if isinstance(v,dict):return{k:serial(x)for k,x in v.items()}\n return v\ndef fixed_svg(path,points,title,xlabel,ylabel,legend):\n use=[p for p in points if p['xExact']!=''and p['yExact']!=''];xs=[float(F(p['xExact']))for p in use];ys=[float(F(p['yExact']))for p in use]\n xmin=min(xs,default=0);xmax=max(xs,default=1);ymin=min([0]+ys);ymax=max([0]+ys)\n if xmin==xmax:xmin-=.5;xmax+=.5\n if ymin==ymax:ymax=ymin+1\n X=lambda v:85+(float(v)-xmin)/(xmax-xmin)*480;Y=lambda v:278-(float(v)-ymin)/(ymax-ymin)*175\n s='<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"620\" height=\"360\" viewBox=\"0 0 620 360\"><rect width=\"620\" height=\"360\" fill=\"white\"/><g font-family=\"Arial, sans-serif\" font-size=\"13\" fill=\"#17324d\">'\n for i,line in enumerate(textwrap.wrap(title,width=65)):s+='<text x=\"25\" y=\"'+str(24+i*18)+'\">'+escape(line)+'</text>'\n colors=['#176b9b','#b85e18','#437e4d']\n for i,label in enumerate(legend):s+='<circle cx=\"'+str(30+i*250)+'\" cy=\"76\" r=\"4\" fill=\"'+colors[i%3]+'\"/><text x=\"'+str(42+i*250)+'\" y=\"80\">'+escape(label)+'</text>'\n s+='<path d=\"M85 98V278H575\" fill=\"none\" stroke=\"#52677d\"/><text text-anchor=\"middle\" x=\"325\" y=\"338\">'+escape(xlabel)+'</text><text text-anchor=\"middle\" transform=\"translate(21,190) rotate(-90)\">'+escape(ylabel)+'</text>'\n for i in range(5):\n  xx=xmin+(xmax-xmin)*i/4;yy=ymin+(ymax-ymin)*i/4;s+='<text text-anchor=\"middle\" x=\"'+format(X(xx),'.9g')+'\" y=\"305\">'+format(xx,'.4g')+'</text><text text-anchor=\"end\" x=\"77\" y=\"'+format(Y(yy)+4,'.9g')+'\">'+format(yy,'.4g')+'</text>'\n for p in use:s+='<circle cx=\"'+format(X(F(p['xExact'])),'.9g')+'\" cy=\"'+format(Y(F(p['yExact'])),'.9g')+'\" r=\"3\" fill=\"'+colors[p['series']%3]+'\"/>'\n path.write_text(s+'</g></svg>',encoding='utf8')\ndef fixed_run():\n ap=argparse.ArgumentParser();ap.add_argument('--out',type=Path,default=Path('results'));ap.add_argument('--data-dir',type=Path,default=Path(__file__).resolve().parent.parent/'ml14-sources');args=ap.parse_args();args.out.mkdir(parents=True,exist_ok=True)\n api=FIXED['api'];a=FIXED['args'];summary=[];points=[];xlabel='Declared index';ylabel='Value';legend=['Declared result']\n def metric(name,v,unit='dimensionless'):\n  q=None if v is None else v if isinstance(v,F)else F(v);summary.append(dict(metric=name,value='undefined'if q is None else format(float(q),'.9g'),exactValue=''if q is None else str(q),unit=unit,defined=int(q is not None)))\n def pt(i,x,y,ident='',series=0):\n  points.append(dict(series=series,index=i,xExact=''if x is None else str(F(x)),x='undefined'if x is None else format(float(x),'.9g'),yExact=''if y is None else str(F(y)),y='undefined'if y is None else format(float(y),'.9g'),id=str(ident)))\n if api=='realdata':\n  models=load_sources(args.data_dir);model=models[a['kind']];fit=actual_model(model);rr=fit['rows'];test=scoped(rr,'test');scenarios=[]\n  for name,fp,fn in SCENARIOS:\n   c=choose(rr,{},(fp,fn));scenarios.append(dict(name=name,selection=c));metric(name+'Threshold',c['selectedPolicy']);metric(name+'TestCost',c['evaluation']['meanCost'],'hypothetical cost units/mass')\n  cv=curves(test);cal=calibrate(test,[F(0),F(1,5),F(2,5),F(3,5),F(4,5),F(1)]);metric('testAUC',cv['ROC_AUC']);metric('testAP',cv['averagePrecision']);metric('testBrier',cal['Brier']);metric('eligibleRows',sum(r['eligible']for r in rr),'rows')\n  for i,r in enumerate(test):pt(i,i+1,r['score'],r['id'],0);pt(i,i+1,r['y'],r['id'],1)\n  full=dict(kind=a['kind'],fitMedians=fit['medians'],fitCells=[dict(cell=list(k),mass=n,positive=s,probability=fit['probabilities'][k])for k,(n,s)in fit['cells'].items()],rowsScored=rr,scenarios=scenarios,testCurves=cv,testCalibration=cal);xlabel='Test row, native order';ylabel='Y or probability';legend=['Training-fitted probability','Observed Y']\n else:\n  rr=validated_rows(a['rows']);role=a.get('role','all');frame=scoped(rr,role);cc=cost(a.get('costs'));t=policy(a.get('threshold','1/2'))\n  if api=='metrics':\n   full=metrics(frame,t,cc)\n   for k in ['mass','accuracy','precision','TPR','FPR','F1','Brier','meanCost']:metric(k,full[k],'mass'if k=='mass'else'hypothetical cost units/mass'if k=='meanCost'else'dimensionless')\n   metric('BayesThreshold',full['bayesThreshold'])\n   for i,k in enumerate(['TP','FP','FN','TN']):pt(i,i,full['confusion'][k],k)\n   xlabel='TP / FP / FN / TN positions';ylabel='Analytical mass'\n  elif api=='curves':\n   full=curves(frame)\n   for k in ['ROC_AUC','averagePrecision','PRTrapezoidWithInitialPrecisionOne']:metric(k,full[k])\n   for i,p in enumerate(full['points']):pt(i,p['FPR'],p['TPR'],str(p['policy']))\n   xlabel='False positive rate';ylabel='True positive rate';legend=['Observed ROC operating points']\n  elif api=='choose':\n   full=choose(rr,a,cc);metric('selectedIndex',full['selectedIndex'],'candidate index');metric('minimumCost',None if full['selectedValidation']is None else full['selectedValidation']['meanCost'],'hypothetical cost units/mass');metric('feasible',int(full['selectedIndex']is not None),'indicator')\n   for c in full['candidates']:pt(c['index'],c['index'],c['metrics']['meanCost'],str(c['policy']))\n   xlabel='Validation candidate';ylabel='Assumed cost / mass';legend=['Validation candidate costs']\n  elif api=='calibrate':\n   full=calibrate(frame,[F(str(e))for e in a.get('binEdges',['0','1/5','2/5','3/5','4/5','1'])])\n   for k in ['ECE','Brier','uncertainty','resolution','reliability','withinBinCorrection','BrierIdentityResidual']:metric(k,full[k])\n   for b in full['bins']:pt(b['index'],b['meanPrediction'],b['eventRate'],'bin:'+str(b['index']))\n   xlabel='Bin mean forecast';ylabel='Bin event rate';legend=['Binary-event reliability']\n  elif api=='groups':\n   full=groups(frame,t,cc);metric('overallTPR',full['overall']['TPR']);metric('TPRGap',full['gaps']['TPR']['value']);metric('precisionGap',full['gaps']['precision']['value']);metric('unknownMass',full['unknownGroup']['mass'],'mass');metric('partitionResidual',full['partitionMassResidual'],'mass')\n   for i,g in enumerate(full['groups']):pt(i,i,g['metrics']['TPR'],str(g['group']))\n   xlabel='Declared group position';ylabel='True positive rate';legend=['Known-group TPR']\n  else:raise ValueError('unknown fixed API')\n def csvout(name,rows):\n  with(args.out/name).open('w',encoding='utf8',newline='')as f:w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows)\n csvout('summary.csv',summary);csvout('plot-points.csv',points);fixed_svg(args.out/'plot.svg',points,FIXED['title'],xlabel,ylabel,legend)\n (args.out/'full.json').write_text(json.dumps(dict(api=api,variant=FIXED['variant'],input=FIXED['args'],arithmetic='Python standard-library Fraction, declared fixed example; full web validator/budgets not reproduced',result=serial(full)),ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\n print(json.dumps(dict(api=api,variant=FIXED['variant'],summaryMetrics=len(summary),plotSlots=len(points))))\n\nFIXED={'api': 'groups', 'variant': 'six-cards', 'args': {'rows': [{'id': 'a', 'score': '.9', 'y': 1, 'group': 'A'}, {'id': 'b', 'score': '.8', 'y': 1, 'group': 'A'}, {'id': 'c', 'score': '.8', 'y': 0, 'group': 'A'}, {'id': 'd', 'score': '.6', 'y': 0, 'group': 'B'}, {'id': 'e', 'score': '.4', 'y': 1, 'group': 'B'}, {'id': 'f', 'score': '.1', 'y': 0, 'group': 'B'}], 'threshold': '.8'}, 'title': 'Group TPR gaps and undefined precision comparison'}\nif __name__=='__main__':fixed_run()\n",
        "codeText": "#!/usr/bin/env python3\n\"\"\"ML14 standalone exact finite study, Python standard library only.\nInputs: only the three retained factual source CSVs below.\nDerived role/target/group/eligibility columns in those CSVs are NOT inputs.\nRebuilds SHA256 roles, train-only medians/cell scores, validation thresholds,\ntest curves, binary-event reliability and descriptive group ledgers.\nCosts 1/1,1/5,5/1 are hypothetical units, not measured intervention returns.\nThis is author public reproduction, not independent scientific review.\n\"\"\"\n\"\"\"Author Fraction reference, separate from product JavaScript; not independent peer.\"\"\"\nfrom fractions import Fraction as F\nfrom collections import Counter,defaultdict\ndef read(raw):\n rows=[]\n for i,r in enumerate(raw):\n  s=None if r['score']is None else F(str(r['score']));y=None if r['y']is None else F(int(r['y']))if isinstance(r['y'],bool)else F(str(r['y']));w=F(str(r.get('weight','1')));role=r.get('role','evaluation')\n  rows.append(dict(id=r['id'],index=i,score=s,y=y,w=w,role=role,group=r.get('group'),eligible=s is not None and y is not None and w>0 and role!='excluded'))\n return rows\ndef scoped(rows,role='all'):return rows if role=='all'else[r for r in rows if r['role']==role]\ndef divide(n,d):return None if not d else n/d\ndef policy(v):return v if v in ['always-negative','always-positive']else F(str(v))\ndef positive(p,s):return p=='always-positive'if isinstance(p,str)else s>=p\ndef cost(a=None):\n a={}if a is None else a;fp=F(str(a.get('falsePositive','1')));fn=F(str(a.get('falseNegative','1')));return fp,fn\ndef metrics(rows,threshold=F(1,2),cc=(F(1),F(1))):\n counts=dict(TP=F(0),FP=F(0),FN=F(0),TN=F(0));brier=F(0);pred=[]\n for r in rows:\n  if not r['eligible']:pred.append(dict(id=r['id'],index=r['index'],eligible=False,decision=None,probability=None,Brier=None));continue\n  yes=positive(threshold,r['score']);cell=('T'if yes==bool(r['y'])else'F')+('P'if yes else'N');counts[cell]+=r['w'];loss=(r['score']-r['y'])**2;brier+=r['w']*loss;pred.append(dict(id=r['id'],index=r['index'],eligible=True,decision=int(yes),probability=r['score'],Brier=loss))\n TP,FP,FN,TN=[counts[k]for k in ['TP','FP','FN','TN']];P=TP+FN;N=TN+FP;mass=P+N;PP=TP+FP;PN=TN+FN;TPR=divide(TP,P);TNR=divide(TN,N);total=FP*cc[0]+FN*cc[1]\n return dict(confusion=counts,mass=mass,positiveTargetMass=P,negativeTargetMass=N,predictedPositiveMass=PP,predictedNegativeMass=PN,prevalence=divide(P,mass),selectionRate=divide(PP,mass),accuracy=divide(TP+TN,mass),precision=divide(TP,PP),negativePredictiveValue=divide(TN,PN),TPR=TPR,FPR=divide(FP,N),TNR=TNR,FNR=divide(FN,P),F1=divide(2*TP,2*TP+FP+FN),balancedAccuracy=None if TPR is None or TNR is None else(TPR+TNR)/2,Brier=divide(brier,mass),BrierSum=brier,totalCost=total,meanCost=divide(total,mass),predictions=pred,bayesThreshold=divide(cc[0],sum(cc)))\ndef curves(rows):\n use=[r for r in rows if r['eligible']];pos=Counter();neg=Counter()\n for r in use:(pos if r['y']else neg)[r['score']]+=r['w']\n P=sum(pos.values(),F(0));N=sum(neg.values(),F(0));pairs=F(0)\n for a,wa in pos.items():\n  for b,wb in neg.items():pairs+=wa*wb*(F(1)if a>b else F(1,2)if a==b else F(0))\n thresholds=['always-negative']+sorted({r['score']for r in use},reverse=True);points=[];AP=F(0);trap=F(0);lastR=F(0);lastP=F(1)\n for i,p in enumerate(thresholds):\n  m=metrics(rows,p);points.append(dict(policy=p,TP=m['confusion']['TP'],FP=m['confusion']['FP'],FN=m['confusion']['FN'],TN=m['confusion']['TN'],TPR=m['TPR'],FPR=m['FPR'],precision=m['precision'],recall=m['TPR']))\n  if i and P:\n   R=m['TPR'];PP=m['precision'];AP+=(R-lastR)*PP;trap+=(R-lastR)*(PP+lastP)/2;lastR=R;lastP=PP\n return dict(positiveMass=P,negativeMass=N,ROC_AUC=divide(pairs,P*N),weightedConcordantPlusHalfTiedMass=pairs,averagePrecision=AP if P else None,PRTrapezoidWithInitialPrecisionOne=trap if P else None,points=points)\ndef choose(rows,a,cc):\n sr=a.get('selectionRole','validation');er=a.get('evaluationRole','test');rr=scoped(rows,sr);thresholds=[policy(t)for t in a['thresholds']]if'thresholds'in a else['always-negative']+sorted({r['score']for r in rr if r['eligible']},reverse=True)\n candidates=[]\n for i,p in enumerate(thresholds):\n  m=metrics(rr,p,cc);reasons=[]\n  if'minTPR'in a and(m['TPR']is None or m['TPR']<F(str(a['minTPR']))):reasons.append('TPR-undefined'if m['TPR']is None else'below-minTPR')\n  if'maxFPR'in a and(m['FPR']is None or m['FPR']>F(str(a['maxFPR']))):reasons.append('FPR-undefined'if m['FPR']is None else'above-maxFPR')\n  candidates.append(dict(index=i,policy=p,metrics=m,feasible=not reasons,reasons=reasons))\n eligible=[c for c in candidates if c['feasible']];best=min(eligible,key=lambda c:(c['metrics']['meanCost'],c['index']))if eligible else None\n return dict(selectedIndex=None if best is None else best['index'],selectedPolicy=None if best is None else best['policy'],candidates=candidates,selectedValidation=None if best is None else best['metrics'],evaluation=None if best is None or er=='none'else metrics(scoped(rows,er),best['policy'],cc),selectionIDs=[r['id']for r in rr if r['eligible']])\ndef calibrate(rows,ee):\n buckets=[[]for _ in range(len(ee)-1)]\n for r in rows:\n  if not r['eligible']:continue\n  j=next((i for i in range(len(ee)-1)if r['score']<ee[i+1]),len(ee)-2);buckets[j].append(r)\n mass=sum((r['w']for r in rows if r['eligible']),F(0));P=sum((r['w']*r['y']for r in rows if r['eligible']),F(0));pi=divide(P,mass);Brier=None if not mass else sum((r['w']*(r['score']-r['y'])**2 for r in rows if r['eligible']),F(0))/mass;ECE=F(0);reliability=F(0);resolution=F(0);correction=F(0);bins=[]\n for i,rr in enumerate(buckets):\n  w=sum((r['w']for r in rr),F(0));mp=None if not w else sum((r['w']*r['score']for r in rr),F(0))/w;o=None if not w else sum((r['w']*r['y']for r in rr),F(0))/w\n  variance=None if not w else sum((r['w']*(r['score']-mp)**2 for r in rr),F(0))/w\n  covariance=None if not w else sum((r['w']*(r['score']-mp)*(r['y']-o)for r in rr),F(0))/w\n  bc=None if not w else variance-2*covariance;gap=None if not w else mp-o\n  bins.append(dict(index=i,rows=len(rr),mass=w,meanPrediction=mp,eventRate=o,gap=gap,absoluteGap=None if gap is None else abs(gap),scoreVariance=variance,scoreTargetCovariance=covariance,withinBinCorrection=bc,ids=[r['id']for r in rr]))\n  if w:\n   share=w/mass;ECE+=share*abs(gap);reliability+=share*gap**2;resolution+=share*(o-pi)**2;correction+=share*bc\n uncertainty=None if pi is None else pi*(1-pi);residual=None if Brier is None else Brier-(uncertainty-resolution+reliability+correction)\n return dict(mass=mass,prevalence=pi,Brier=Brier,ECE=ECE if mass else None,reliability=reliability if mass else None,resolution=resolution if mass else None,uncertainty=uncertainty,withinBinCorrection=correction if mass else None,BrierIdentityResidual=residual,bins=bins)\ndef typed(v):return type(v).__name__,v\ndef groups(rows,p,cc):\n bins={}\n for r in rows:\n  if r['group']is not None:bins.setdefault(typed(r['group']),[]).append(r)\n gm=[dict(group=rr[0]['group'],metrics=metrics(rr,p,cc))for rr in bins.values()];overall=metrics(rows,p,cc);unknown=metrics([r for r in rows if r['group']is None],p,cc);gaps={}\n for key in ['prevalence','selectionRate','TPR','FPR','precision','accuracy','meanCost']:\n  positive=[g for g in gm if g['metrics']['mass']>0];undefined=[g['group']for g in positive if g['metrics'][key]is None];vals=[g['metrics'][key]for g in positive if g['metrics'][key]is not None]\n  gaps[key]=dict(value=None if len(positive)<2 or undefined else max(vals)-min(vals),undefinedGroups=undefined,comparedPositiveMassGroups=[g['group']for g in positive])\n return dict(overall=overall,groups=gm,unknownGroup=unknown,gaps=gaps,partitionMassResidual=overall['mass']-unknown['mass']-sum((g['metrics']['mass']for g in gm),F(0)))\ndef actual_model(M):\n raw=M['records'];cat=M['categoricalFeatures'];p=len(raw[0]['x']);train=[r for r in raw if r['role']=='train'];medians=[]\n for j in range(p):\n  if j in cat:medians.append(None);continue\n  values=sorted(F(r['x'][j])for r in train);n=len(values);medians.append(values[n//2]if n%2 else(values[n//2-1]+values[n//2])/2)\n def transform(r):return[F(v)if j in cat else F(int(F(v)>medians[j]))for j,v in enumerate(r['x'])]\n counts={}\n for r in train:\n  key=tuple(transform(r));n,s=counts.get(key,(0,0));counts[key]=(n+1,s+int(r['y']))\n probabilities={k:F(s+1,n+2)for k,(n,s)in counts.items()};fallback=F(sum(int(r['y'])for r in train)+1,len(train)+2);scored=[]\n for i,r in enumerate(raw):\n  eligible=r['role']!='excluded';z=transform(r)if eligible else None;key=None if z is None else tuple(z);score=None if not eligible else probabilities.get(key,fallback)\n  scored.append(dict(id=r['id'],index=i,role=r['role'],group=r['group'],y=None if r['y']is None else F(r['y']),score=score,w=F(1),eligible=eligible,transformedX=z,unseenCell=None if not eligible else key not in probabilities))\n return dict(medians=medians,cells=counts,probabilities=probabilities,fallback=fallback,rows=scored,trainIDs=[r['id']for r in train])\n\n\nimport csv,json,hashlib,argparse,datetime\nfrom pathlib import Path\ndef missing(v):return None if v in ['', '.',None]else v\ndef load_sources(folder):\n def read_csv(name):\n  with (folder/name).open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))\n wb=read_csv('actual64-country-four-indicators-original-2024.csv')\n codes=['NY.GDP.PCAP.KD','NY.GDP.MKTP.KD.ZG','FP.CPI.TOTL.ZG','SP.DYN.LE00.IN']\n lookup={(r['countryISO3'],r['indicatorID']):r for r in wb};country=[]\n for i,iso in enumerate(sorted({r['countryISO3']for r in wb}),1):\n  native=[lookup[iso,c]for c in codes];v=[missing(r['originalValueToken'])for r in native]\n  country.append(dict(id=iso+':2024',sourceRow=i,originalID=iso,x=v[:3],y=None if v[3]is None else str(int(F(v[3])>=80)),group=None if v[0]is None else str(int(F(v[0])>=25000)),nativeTarget=v[3],nativeSourceRows=';'.join(r['sourceRow']for r in native)))\n nls=read_csv('actual3613-NLS-original52-fields-groups-roles.csv');person=[]\n for r in nls:\n  y=missing(r['wage76']);person.append(dict(id='person:'+r['sourceRow'],sourceRow=int(r['sourceRow']),originalID=r['id'],x=[missing(r[k])for k in ['ed76','age76','nearc4']],y=None if y is None else str(int(F(y)>=500)),group=missing(r['black']),nativeTarget=y,nativeSourceRows=r['sourceRow']))\n ch=read_csv('actual3150-churn-original14-fields-groups-roles.csv');company=[]\n for r in ch:\n  company.append(dict(id='customer:'+r['sourceRow'],sourceRow=int(r['sourceRow']),originalID='',x=[missing(r[k])for k in ['Call  Failure','Complains','Subscription  Length','Seconds of Use']],y=missing(r['Churn']),group=missing(r['Tariff Plan']),nativeTarget=missing(r['Churn']),nativeSourceRows=r['sourceRow']))\n assert len(wb)==64 and len(country)==16 and len(nls)==3613 and len(ch)==3150\n assert [int(r['sourceRow'])for r in ch if r['Charge  Amount']=='10']==[474,2174,2274,2374,2674,2924,2974]\n models={}\n for kind,raw,cat,units in [('country',country,[],['constant2015USD/person','annualPercent','annualPercent']),('person',person,[2],['years','years','nativeCategory']),('company',company,[1],['count','nativeCategory','months','seconds'])]:\n  order=sorted(range(len(raw)),key=lambda i:(hashlib.sha256(('ML14-role|'+kind+'|'+raw[i]['id']).encode()).hexdigest(),i))\n  for rank,i in enumerate(order):\n   r=raw[i];r['plannedRole']='test'if rank%5==0 else'validation'if rank%5==1 else'train';r['eligible']=None not in r['x']+[r['y']];r['role']=r['plannedRole']if r['eligible']else'excluded';r['weight']='1'\n  models[kind]=dict(records=raw,categoricalFeatures=cat,featureUnits=units)\n assert sum(r['eligible']for r in person)==3017\n return models\n\ndef exact(v):return ''if v is None else str(v)\ndef approx(v):return ''if v is None else format(float(v),'.17g')\ndef scalar_fields(m,keys):\n out={}\n for k in keys:\n  out[k+'Exact']=exact(m[k]);out[k+'Approx']=approx(m[k])\n return out\nCOUNTS=['mass','positiveTargetMass','negativeTargetMass','predictedPositiveMass','predictedNegativeMass']\nRATES=['prevalence','selectionRate','accuracy','precision','negativePredictiveValue','TPR','FPR','TNR','FNR','F1','balancedAccuracy','Brier','BrierSum','totalCost','meanCost']\nSCENARIOS=[('equal',F(1),F(1)),('miss-five',F(1),F(5)),('alarm-five',F(5),F(1))]\ndef packed(v):\n if isinstance(v,F):return str(v)\n if isinstance(v,dict):return{str(k):packed(x)for k,x in v.items()}\n if isinstance(v,(tuple,list)):return[packed(x)for x in v]\n return v\ndef run_study(source,out):\n out.mkdir(parents=True,exist_ok=True);models=load_sources(source)\n tables={name:[]for name in ['predictions','lineage','fit-medians','fit-cells','validation-candidates','test-metrics','test-curves','calibration-bins','group-metrics','chart-points']}\n studies={};charts=[]\n def point(kind,chart,series,index,x,y,xunit='dimensionless',yunit='dimensionless',role='test',tag=''):\n  tables['chart-points'].append(dict(kind=kind,chart=chart,series=series,index=index,xExact=exact(x),xApprox=approx(x),yExact=exact(y),yApprox=approx(y),xUnit=xunit,yUnit=yunit,role=role,tag=tag))\n for kind,M in models.items():\n  fit=actual_model(M);rr=fit['rows'];native=M['records'];test=scoped(rr,'test');cv=curves(test);cal=calibrate(test,[F(0),F(1,5),F(2,5),F(3,5),F(4,5),F(1)]);scenarios=[]\n  for i,r in enumerate(rr):\n   n=native[i];reason=''if r['eligible']else'required-X-or-Y-missing'\n   tables['predictions'].append(dict(kind=kind,id=r['id'],sourceRow=n['sourceRow'],originalID=n['originalID'],plannedRole=n['plannedRole'],role=r['role'],group=''if r['group']is None else r['group'],eligible=int(r['eligible']),targetExact=exact(r['y']),probabilityExact=exact(r['score']),probabilityApprox=approx(r['score']),unseenCell=''if r['unseenCell']is None else int(r['unseenCell']),transformedX=''if r['transformedX']is None else'|'.join(map(str,r['transformedX'])),reason=reason))\n   tables['lineage'].append(dict(kind=kind,id=r['id'],sourceRow=n['sourceRow'],originalID=n['originalID'],nativeSourceRows=n['nativeSourceRows'],rawX='|'.join(''if x is None else x for x in n['x']),nativeTarget=''if n['nativeTarget']is None else n['nativeTarget'],derivedTarget=exact(r['y']),nativeGroup=''if n['group']is None else n['group'],plannedRole=n['plannedRole'],role=r['role'],eligible=int(r['eligible']),analyticalMass='1',reason=reason))\n  for j,v in enumerate(fit['medians']):tables['fit-medians'].append(dict(kind=kind,feature=j,categorical=int(j in M['categoricalFeatures']),fitRows=len(fit['trainIDs']),medianExact=exact(v),medianApprox=approx(v),unit=M['featureUnits'][j]))\n  for key,(mass,pos)in fit['cells'].items():tables['fit-cells'].append(dict(kind=kind,cell='|'.join(map(str,key)),trainingRows=mass,positiveRows=pos,probabilityExact=exact(fit['probabilities'][key]),probabilityApprox=approx(fit['probabilities'][key]),fallbackExact=exact(fit['fallback']),fallbackApprox=approx(fit['fallback'])))\n  for j,p in enumerate(cv['points']):\n   policy=p['policy'];tables['test-curves'].append(dict(kind=kind,point=j,policy=policy if isinstance(policy,str)else'threshold',thresholdExact=''if isinstance(policy,str)else exact(policy),thresholdApprox=''if isinstance(policy,str)else approx(policy),**scalar_fields(p,['TP','FP','FN','TN','TPR','FPR','precision','recall'])))\n   point(kind,'roc','ROC',j,p['FPR'],p['TPR']);point(kind,'pr','PR-observed',j,p['recall'],p['precision'])\n  for b in cal['bins']:\n   tables['calibration-bins'].append(dict(kind=kind,bin=b['index'],leftExact=str(F(b['index'],5)),rightExact=str(F(b['index']+1,5)),rightClosed=int(b['index']==4),rows=b['rows'],ids=';'.join(str(i)for i in b['ids']),**scalar_fields(b,['mass','meanPrediction','eventRate','gap','absoluteGap','scoreVariance','scoreTargetCovariance','withinBinCorrection'])))\n   point(kind,'reliability','Binary event rate',b['index'],b['meanPrediction'],b['eventRate'],tag='rows='+str(b['rows']))\n  for j,r in enumerate(test):\n   point(kind,'test-scores','Training-fitted probability',j,F(j+1),r['score'],'test-row position','probability',tag=r['id'])\n   point(kind,'test-scores','Observed Y',j,F(j+1),r['y'],'test-row position','binary target',tag=r['id'])\n  for name,fp,fn in SCENARIOS:\n   choice=choose(rr,{},(fp,fn));gm=groups(test,choice['selectedPolicy'],(fp,fn));scenarios.append(dict(name=name,costs=dict(falsePositive=fp,falseNegative=fn),selection=choice,groups=gm));ev=choice['evaluation']\n   for c in choice['candidates']:\n    policy=c['policy'];mm=c['metrics'];tables['validation-candidates'].append(dict(kind=kind,scenario=name,candidate=c['index'],selected=int(c['index']==choice['selectedIndex']),policy=policy if isinstance(policy,str)else'threshold',thresholdExact=''if isinstance(policy,str)else exact(policy),thresholdApprox=''if isinstance(policy,str)else approx(policy),feasible=int(c['feasible']),reasons=';'.join(c['reasons']),**{k+'Exact':str(v)for k,v in mm['confusion'].items()},**scalar_fields(mm,COUNTS+['TPR','FPR','precision','meanCost','totalCost'])))\n    point(kind,'validation-cost',name,c['index'],F(c['index']),mm['meanCost'],'candidate index','hypothetical cost units/mass','validation',tag=exact(policy))\n   mm={**ev,**ev['confusion'],**{k:cv[k]for k in ['ROC_AUC','averagePrecision','PRTrapezoidWithInitialPrecisionOne']},**{k:cal[k]for k in ['ECE','reliability','resolution','uncertainty','withinBinCorrection','BrierIdentityResidual']}}\n   for key in ['TP','FP','FN','TN']+COUNTS+RATES+['ROC_AUC','averagePrecision','PRTrapezoidWithInitialPrecisionOne','ECE','reliability','resolution','uncertainty','withinBinCorrection','BrierIdentityResidual']:\n    unit='rows'if key in ['TP','FP','FN','TN']+COUNTS else'hypothetical cost units'if key=='totalCost'else'hypothetical cost units/mass'if key=='meanCost'else'sum squared-probability loss'if key=='BrierSum'else'dimensionless'\n    tables['test-metrics'].append(dict(kind=kind,scenario=name,metric=key,valueExact=exact(mm[key]),valueApprox=approx(mm[key]),unit=unit))\n   allg=[('overall','all',gm['overall'])]+[('known',str(g['group']),g['metrics'])for g in gm['groups']]+[('unknown','',gm['unknownGroup'])]\n   for j,(typ,token,g)in enumerate(allg):\n    tables['group-metrics'].append(dict(kind=kind,scenario=name,groupType=typ,groupToken=token,retainedRows=g.get('retainedRows',sum((r['group']==token)if typ=='known'else(r['group']is None)if typ=='unknown'else True for r in test)),**{k+'Exact':str(v)for k,v in g['confusion'].items()},**scalar_fields(g,COUNTS+RATES)))\n    if typ=='known':point(kind,'group-TPR',name,j-1,F(j-1),g['TPR'],'declared group position','TPR',tag=token)\n  studies[kind]=dict(kind=kind,rows=len(native),eligibleRows=sum(r['eligible']for r in rr),trainingIDs=fit['trainIDs'],fitMedians=fit['medians'],fitCells=[dict(cell=list(k),mass=n,positive=s,probability=fit['probabilities'][k])for k,(n,s)in fit['cells'].items()],fallback=fit['fallback'],scenarios=scenarios,testCurves=cv,testCalibration=cal,rowsScored=rr)\n files=[]\n for name,rows in tables.items():\n  p=out/('computed-'+name+'.csv')\n  with p.open('w',encoding='utf8',newline='')as f:w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows)\n  files.append(dict(file=p.name,rows=len(rows),columns=len(rows[0]),bodyFields=len(rows)*len(rows[0]),sha256=hashlib.sha256(p.read_bytes()).hexdigest()))\n (out/'study.json').write_text(json.dumps(packed(studies),ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\n sourceFiles=[source/n for n in ['actual64-country-four-indicators-original-2024.csv','actual3613-NLS-original52-fields-groups-roles.csv','actual3150-churn-original14-fields-groups-roles.csv']]\n provenance=dict(chapter='ML-14',arithmetic='Python stdlib Fraction exact finite values from original decimal strings; binary64 valueApprox is display only.',inputs=[dict(file=p.name,sha256=hashlib.sha256(p.read_bytes()).hexdigest())for p in sourceFiles],priorEngineModelsScoresOrComputedFilesRead=False,roleRule=\"SHA256('ML14-role|'+kind+'|'+ID),rankmod5=0test/1validation/others train before eligibility\",costs='Hypothetical1/1,1/5,5/1; no causal intervention returns',files=files,observations={k:dict(sourceRows=v['rows'],eligibleRows=v['eligibleRows'],trainingRows=len(v['trainingIDs']))for k,v in studies.items()})\n (out/'provenance.json').write_text(json.dumps(provenance,ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\n print(json.dumps(dict(status='PASS standalone completed',files=len(files),bodyFields=sum(f['bodyFields']for f in files),observations=provenance['observations'])))\n\n# Fixed declared examples: full web budget/option validation is not reproduced.\nfrom html import escape\nimport textwrap\ndef validated_rows(raw):\n for r in raw:\n  assert F(str(r.get('weight','1')))>=0,'negative analytical mass'\n  assert r['score']is None or 0<=F(str(r['score']))<=1,'score outside zero/one'\n  assert r['y']is None or F(str(int(r['y']))if isinstance(r['y'],bool)else str(r['y']))in [0,1],'binary target required'\n return read(raw)\ndef serial(v):\n if isinstance(v,F):return dict(exactFraction=str(v),value=float(v))\n if isinstance(v,(list,tuple)):return[serial(x)for x in v]\n if isinstance(v,dict):return{k:serial(x)for k,x in v.items()}\n return v\ndef fixed_svg(path,points,title,xlabel,ylabel,legend):\n use=[p for p in points if p['xExact']!=''and p['yExact']!=''];xs=[float(F(p['xExact']))for p in use];ys=[float(F(p['yExact']))for p in use]\n xmin=min(xs,default=0);xmax=max(xs,default=1);ymin=min([0]+ys);ymax=max([0]+ys)\n if xmin==xmax:xmin-=.5;xmax+=.5\n if ymin==ymax:ymax=ymin+1\n X=lambda v:85+(float(v)-xmin)/(xmax-xmin)*480;Y=lambda v:278-(float(v)-ymin)/(ymax-ymin)*175\n s='<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"620\" height=\"360\" viewBox=\"0 0 620 360\"><rect width=\"620\" height=\"360\" fill=\"white\"/><g font-family=\"Arial, sans-serif\" font-size=\"13\" fill=\"#17324d\">'\n for i,line in enumerate(textwrap.wrap(title,width=65)):s+='<text x=\"25\" y=\"'+str(24+i*18)+'\">'+escape(line)+'</text>'\n colors=['#176b9b','#b85e18','#437e4d']\n for i,label in enumerate(legend):s+='<circle cx=\"'+str(30+i*250)+'\" cy=\"76\" r=\"4\" fill=\"'+colors[i%3]+'\"/><text x=\"'+str(42+i*250)+'\" y=\"80\">'+escape(label)+'</text>'\n s+='<path d=\"M85 98V278H575\" fill=\"none\" stroke=\"#52677d\"/><text text-anchor=\"middle\" x=\"325\" y=\"338\">'+escape(xlabel)+'</text><text text-anchor=\"middle\" transform=\"translate(21,190) rotate(-90)\">'+escape(ylabel)+'</text>'\n for i in range(5):\n  xx=xmin+(xmax-xmin)*i/4;yy=ymin+(ymax-ymin)*i/4;s+='<text text-anchor=\"middle\" x=\"'+format(X(xx),'.9g')+'\" y=\"305\">'+format(xx,'.4g')+'</text><text text-anchor=\"end\" x=\"77\" y=\"'+format(Y(yy)+4,'.9g')+'\">'+format(yy,'.4g')+'</text>'\n for p in use:s+='<circle cx=\"'+format(X(F(p['xExact'])),'.9g')+'\" cy=\"'+format(Y(F(p['yExact'])),'.9g')+'\" r=\"3\" fill=\"'+colors[p['series']%3]+'\"/>'\n path.write_text(s+'</g></svg>',encoding='utf8')\ndef fixed_run():\n ap=argparse.ArgumentParser();ap.add_argument('--out',type=Path,default=Path('results'));ap.add_argument('--data-dir',type=Path,default=Path(__file__).resolve().parent.parent/'ml14-sources');args=ap.parse_args();args.out.mkdir(parents=True,exist_ok=True)\n api=FIXED['api'];a=FIXED['args'];summary=[];points=[];xlabel='Declared index';ylabel='Value';legend=['Declared result']\n def metric(name,v,unit='dimensionless'):\n  q=None if v is None else v if isinstance(v,F)else F(v);summary.append(dict(metric=name,value='undefined'if q is None else format(float(q),'.9g'),exactValue=''if q is None else str(q),unit=unit,defined=int(q is not None)))\n def pt(i,x,y,ident='',series=0):\n  points.append(dict(series=series,index=i,xExact=''if x is None else str(F(x)),x='undefined'if x is None else format(float(x),'.9g'),yExact=''if y is None else str(F(y)),y='undefined'if y is None else format(float(y),'.9g'),id=str(ident)))\n if api=='realdata':\n  models=load_sources(args.data_dir);model=models[a['kind']];fit=actual_model(model);rr=fit['rows'];test=scoped(rr,'test');scenarios=[]\n  for name,fp,fn in SCENARIOS:\n   c=choose(rr,{},(fp,fn));scenarios.append(dict(name=name,selection=c));metric(name+'Threshold',c['selectedPolicy']);metric(name+'TestCost',c['evaluation']['meanCost'],'hypothetical cost units/mass')\n  cv=curves(test);cal=calibrate(test,[F(0),F(1,5),F(2,5),F(3,5),F(4,5),F(1)]);metric('testAUC',cv['ROC_AUC']);metric('testAP',cv['averagePrecision']);metric('testBrier',cal['Brier']);metric('eligibleRows',sum(r['eligible']for r in rr),'rows')\n  for i,r in enumerate(test):pt(i,i+1,r['score'],r['id'],0);pt(i,i+1,r['y'],r['id'],1)\n  full=dict(kind=a['kind'],fitMedians=fit['medians'],fitCells=[dict(cell=list(k),mass=n,positive=s,probability=fit['probabilities'][k])for k,(n,s)in fit['cells'].items()],rowsScored=rr,scenarios=scenarios,testCurves=cv,testCalibration=cal);xlabel='Test row, native order';ylabel='Y or probability';legend=['Training-fitted probability','Observed Y']\n else:\n  rr=validated_rows(a['rows']);role=a.get('role','all');frame=scoped(rr,role);cc=cost(a.get('costs'));t=policy(a.get('threshold','1/2'))\n  if api=='metrics':\n   full=metrics(frame,t,cc)\n   for k in ['mass','accuracy','precision','TPR','FPR','F1','Brier','meanCost']:metric(k,full[k],'mass'if k=='mass'else'hypothetical cost units/mass'if k=='meanCost'else'dimensionless')\n   metric('BayesThreshold',full['bayesThreshold'])\n   for i,k in enumerate(['TP','FP','FN','TN']):pt(i,i,full['confusion'][k],k)\n   xlabel='TP / FP / FN / TN positions';ylabel='Analytical mass'\n  elif api=='curves':\n   full=curves(frame)\n   for k in ['ROC_AUC','averagePrecision','PRTrapezoidWithInitialPrecisionOne']:metric(k,full[k])\n   for i,p in enumerate(full['points']):pt(i,p['FPR'],p['TPR'],str(p['policy']))\n   xlabel='False positive rate';ylabel='True positive rate';legend=['Observed ROC operating points']\n  elif api=='choose':\n   full=choose(rr,a,cc);metric('selectedIndex',full['selectedIndex'],'candidate index');metric('minimumCost',None if full['selectedValidation']is None else full['selectedValidation']['meanCost'],'hypothetical cost units/mass');metric('feasible',int(full['selectedIndex']is not None),'indicator')\n   for c in full['candidates']:pt(c['index'],c['index'],c['metrics']['meanCost'],str(c['policy']))\n   xlabel='Validation candidate';ylabel='Assumed cost / mass';legend=['Validation candidate costs']\n  elif api=='calibrate':\n   full=calibrate(frame,[F(str(e))for e in a.get('binEdges',['0','1/5','2/5','3/5','4/5','1'])])\n   for k in ['ECE','Brier','uncertainty','resolution','reliability','withinBinCorrection','BrierIdentityResidual']:metric(k,full[k])\n   for b in full['bins']:pt(b['index'],b['meanPrediction'],b['eventRate'],'bin:'+str(b['index']))\n   xlabel='Bin mean forecast';ylabel='Bin event rate';legend=['Binary-event reliability']\n  elif api=='groups':\n   full=groups(frame,t,cc);metric('overallTPR',full['overall']['TPR']);metric('TPRGap',full['gaps']['TPR']['value']);metric('precisionGap',full['gaps']['precision']['value']);metric('unknownMass',full['unknownGroup']['mass'],'mass');metric('partitionResidual',full['partitionMassResidual'],'mass')\n   for i,g in enumerate(full['groups']):pt(i,i,g['metrics']['TPR'],str(g['group']))\n   xlabel='Declared group position';ylabel='True positive rate';legend=['Known-group TPR']\n  else:raise ValueError('unknown fixed API')\n def csvout(name,rows):\n  with(args.out/name).open('w',encoding='utf8',newline='')as f:w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows)\n csvout('summary.csv',summary);csvout('plot-points.csv',points);fixed_svg(args.out/'plot.svg',points,FIXED['title'],xlabel,ylabel,legend)\n (args.out/'full.json').write_text(json.dumps(dict(api=api,variant=FIXED['variant'],input=FIXED['args'],arithmetic='Python standard-library Fraction, declared fixed example; full web validator/budgets not reproduced',result=serial(full)),ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\n print(json.dumps(dict(api=api,variant=FIXED['variant'],summaryMetrics=len(summary),plotSlots=len(points))))\n\nFIXED={'api': 'groups', 'variant': 'six-cards', 'args': {'rows': [{'id': 'a', 'score': '.9', 'y': 1, 'group': 'A'}, {'id': 'b', 'score': '.8', 'y': 1, 'group': 'A'}, {'id': 'c', 'score': '.8', 'y': 0, 'group': 'A'}, {'id': 'd', 'score': '.6', 'y': 0, 'group': 'B'}, {'id': 'e', 'score': '.4', 'y': 1, 'group': 'B'}, {'id': 'f', 'score': '.1', 'y': 0, 'group': 'B'}], 'threshold': '.8'}, 'title': 'Group TPR gaps and undefined precision comparison'}\nif __name__=='__main__':fixed_run()\n",
        "input": {
          "rows": [
            {
              "id": "a",
              "score": ".9",
              "y": 1,
              "group": "A"
            },
            {
              "id": "b",
              "score": ".8",
              "y": 1,
              "group": "A"
            },
            {
              "id": "c",
              "score": ".8",
              "y": 0,
              "group": "A"
            },
            {
              "id": "d",
              "score": ".6",
              "y": 0,
              "group": "B"
            },
            {
              "id": "e",
              "score": ".4",
              "y": 1,
              "group": "B"
            },
            {
              "id": "f",
              "score": ".1",
              "y": 0,
              "group": "B"
            }
          ],
          "threshold": ".8"
        },
        "inputFiles": [],
        "returnCode": 0,
        "expectedFailure": false,
        "stdout": "{\"api\": \"groups\", \"variant\": \"six-cards\", \"summaryMetrics\": 5, \"plotSlots\": 2}\n",
        "stderr": "",
        "summary": {
          "overallTPR": "0.666666667",
          "TPRGap": "1",
          "precisionGap": "undefined",
          "unknownMass": "0",
          "partitionResidual": "0"
        },
        "summaryRows": [
          {
            "metric": "overallTPR",
            "value": "0.666666667",
            "exactValue": "2/3",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "TPRGap",
            "value": "1",
            "exactValue": "1",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "precisionGap",
            "value": "undefined",
            "exactValue": "",
            "unit": "dimensionless",
            "defined": "0"
          },
          {
            "metric": "unknownMass",
            "value": "0",
            "exactValue": "0",
            "unit": "mass",
            "defined": "1"
          },
          {
            "metric": "partitionResidual",
            "value": "0",
            "exactValue": "0",
            "unit": "mass",
            "defined": "1"
          }
        ],
        "plotPoints": [
          {
            "series": "0",
            "index": "0",
            "xExact": "0",
            "x": "0",
            "yExact": "1",
            "y": "1",
            "id": "A"
          },
          {
            "series": "0",
            "index": "1",
            "xExact": "1",
            "x": "1",
            "yExact": "0",
            "y": "0",
            "id": "B"
          }
        ],
        "plotFile": "ml14-fixed-results/groups-six-cards-python/plot.svg",
        "plotSHA256": "6c3c6d230162e91027f799dbddf353e4552dad9dd6ed48d91eb1ba150acfda72",
        "files": [
          {
            "file": "ml14-fixed-results/groups-six-cards-python/full.json",
            "sha256": "1eb737adc59cd07088df36f53dc38e1271a2b62272d076b52276d705b1d65b1f",
            "bytes": 16306
          },
          {
            "file": "ml14-fixed-results/groups-six-cards-python/plot-points.csv",
            "sha256": "9921590b957f2fa1800f3ccda3e0ed3e5cc2024df1da8a1d7d4ece2ec9151028",
            "bytes": 65
          },
          {
            "file": "ml14-fixed-results/groups-six-cards-python/plot.svg",
            "sha256": "6c3c6d230162e91027f799dbddf353e4552dad9dd6ed48d91eb1ba150acfda72",
            "bytes": 1201
          },
          {
            "file": "ml14-fixed-results/groups-six-cards-python/summary.csv",
            "sha256": "96740e5dfa7c831444a02b633e9ab6d426e019d45cc35145f7156a88cfc5d53f",
            "bytes": 205
          }
        ],
        "scope": "Actually executed standalone fixed example, Python exact Fraction versus base-R binary64. Approximate R residuals retained; not universal exact arithmetic/web validation/native UI. Source programs read factual3CSV only."
      },
      "unknown-group": {
        "api": "groups",
        "variant": "unknown-group",
        "language": "python",
        "title": "Unknown group stays overall and preserves mass",
        "codeFile": "ml14-code/groups-unknown-group.py",
        "codeSHA256": "fd09adaca424af97e56c3800d001ddd716cda3987f0f9e311534c3d29076a422",
        "code": "#!/usr/bin/env python3\n\"\"\"ML14 standalone exact finite study, Python standard library only.\nInputs: only the three retained factual source CSVs below.\nDerived role/target/group/eligibility columns in those CSVs are NOT inputs.\nRebuilds SHA256 roles, train-only medians/cell scores, validation thresholds,\ntest curves, binary-event reliability and descriptive group ledgers.\nCosts 1/1,1/5,5/1 are hypothetical units, not measured intervention returns.\nThis is author public reproduction, not independent scientific review.\n\"\"\"\n\"\"\"Author Fraction reference, separate from product JavaScript; not independent peer.\"\"\"\nfrom fractions import Fraction as F\nfrom collections import Counter,defaultdict\ndef read(raw):\n rows=[]\n for i,r in enumerate(raw):\n  s=None if r['score']is None else F(str(r['score']));y=None if r['y']is None else F(int(r['y']))if isinstance(r['y'],bool)else F(str(r['y']));w=F(str(r.get('weight','1')));role=r.get('role','evaluation')\n  rows.append(dict(id=r['id'],index=i,score=s,y=y,w=w,role=role,group=r.get('group'),eligible=s is not None and y is not None and w>0 and role!='excluded'))\n return rows\ndef scoped(rows,role='all'):return rows if role=='all'else[r for r in rows if r['role']==role]\ndef divide(n,d):return None if not d else n/d\ndef policy(v):return v if v in ['always-negative','always-positive']else F(str(v))\ndef positive(p,s):return p=='always-positive'if isinstance(p,str)else s>=p\ndef cost(a=None):\n a={}if a is None else a;fp=F(str(a.get('falsePositive','1')));fn=F(str(a.get('falseNegative','1')));return fp,fn\ndef metrics(rows,threshold=F(1,2),cc=(F(1),F(1))):\n counts=dict(TP=F(0),FP=F(0),FN=F(0),TN=F(0));brier=F(0);pred=[]\n for r in rows:\n  if not r['eligible']:pred.append(dict(id=r['id'],index=r['index'],eligible=False,decision=None,probability=None,Brier=None));continue\n  yes=positive(threshold,r['score']);cell=('T'if yes==bool(r['y'])else'F')+('P'if yes else'N');counts[cell]+=r['w'];loss=(r['score']-r['y'])**2;brier+=r['w']*loss;pred.append(dict(id=r['id'],index=r['index'],eligible=True,decision=int(yes),probability=r['score'],Brier=loss))\n TP,FP,FN,TN=[counts[k]for k in ['TP','FP','FN','TN']];P=TP+FN;N=TN+FP;mass=P+N;PP=TP+FP;PN=TN+FN;TPR=divide(TP,P);TNR=divide(TN,N);total=FP*cc[0]+FN*cc[1]\n return dict(confusion=counts,mass=mass,positiveTargetMass=P,negativeTargetMass=N,predictedPositiveMass=PP,predictedNegativeMass=PN,prevalence=divide(P,mass),selectionRate=divide(PP,mass),accuracy=divide(TP+TN,mass),precision=divide(TP,PP),negativePredictiveValue=divide(TN,PN),TPR=TPR,FPR=divide(FP,N),TNR=TNR,FNR=divide(FN,P),F1=divide(2*TP,2*TP+FP+FN),balancedAccuracy=None if TPR is None or TNR is None else(TPR+TNR)/2,Brier=divide(brier,mass),BrierSum=brier,totalCost=total,meanCost=divide(total,mass),predictions=pred,bayesThreshold=divide(cc[0],sum(cc)))\ndef curves(rows):\n use=[r for r in rows if r['eligible']];pos=Counter();neg=Counter()\n for r in use:(pos if r['y']else neg)[r['score']]+=r['w']\n P=sum(pos.values(),F(0));N=sum(neg.values(),F(0));pairs=F(0)\n for a,wa in pos.items():\n  for b,wb in neg.items():pairs+=wa*wb*(F(1)if a>b else F(1,2)if a==b else F(0))\n thresholds=['always-negative']+sorted({r['score']for r in use},reverse=True);points=[];AP=F(0);trap=F(0);lastR=F(0);lastP=F(1)\n for i,p in enumerate(thresholds):\n  m=metrics(rows,p);points.append(dict(policy=p,TP=m['confusion']['TP'],FP=m['confusion']['FP'],FN=m['confusion']['FN'],TN=m['confusion']['TN'],TPR=m['TPR'],FPR=m['FPR'],precision=m['precision'],recall=m['TPR']))\n  if i and P:\n   R=m['TPR'];PP=m['precision'];AP+=(R-lastR)*PP;trap+=(R-lastR)*(PP+lastP)/2;lastR=R;lastP=PP\n return dict(positiveMass=P,negativeMass=N,ROC_AUC=divide(pairs,P*N),weightedConcordantPlusHalfTiedMass=pairs,averagePrecision=AP if P else None,PRTrapezoidWithInitialPrecisionOne=trap if P else None,points=points)\ndef choose(rows,a,cc):\n sr=a.get('selectionRole','validation');er=a.get('evaluationRole','test');rr=scoped(rows,sr);thresholds=[policy(t)for t in a['thresholds']]if'thresholds'in a else['always-negative']+sorted({r['score']for r in rr if r['eligible']},reverse=True)\n candidates=[]\n for i,p in enumerate(thresholds):\n  m=metrics(rr,p,cc);reasons=[]\n  if'minTPR'in a and(m['TPR']is None or m['TPR']<F(str(a['minTPR']))):reasons.append('TPR-undefined'if m['TPR']is None else'below-minTPR')\n  if'maxFPR'in a and(m['FPR']is None or m['FPR']>F(str(a['maxFPR']))):reasons.append('FPR-undefined'if m['FPR']is None else'above-maxFPR')\n  candidates.append(dict(index=i,policy=p,metrics=m,feasible=not reasons,reasons=reasons))\n eligible=[c for c in candidates if c['feasible']];best=min(eligible,key=lambda c:(c['metrics']['meanCost'],c['index']))if eligible else None\n return dict(selectedIndex=None if best is None else best['index'],selectedPolicy=None if best is None else best['policy'],candidates=candidates,selectedValidation=None if best is None else best['metrics'],evaluation=None if best is None or er=='none'else metrics(scoped(rows,er),best['policy'],cc),selectionIDs=[r['id']for r in rr if r['eligible']])\ndef calibrate(rows,ee):\n buckets=[[]for _ in range(len(ee)-1)]\n for r in rows:\n  if not r['eligible']:continue\n  j=next((i for i in range(len(ee)-1)if r['score']<ee[i+1]),len(ee)-2);buckets[j].append(r)\n mass=sum((r['w']for r in rows if r['eligible']),F(0));P=sum((r['w']*r['y']for r in rows if r['eligible']),F(0));pi=divide(P,mass);Brier=None if not mass else sum((r['w']*(r['score']-r['y'])**2 for r in rows if r['eligible']),F(0))/mass;ECE=F(0);reliability=F(0);resolution=F(0);correction=F(0);bins=[]\n for i,rr in enumerate(buckets):\n  w=sum((r['w']for r in rr),F(0));mp=None if not w else sum((r['w']*r['score']for r in rr),F(0))/w;o=None if not w else sum((r['w']*r['y']for r in rr),F(0))/w\n  variance=None if not w else sum((r['w']*(r['score']-mp)**2 for r in rr),F(0))/w\n  covariance=None if not w else sum((r['w']*(r['score']-mp)*(r['y']-o)for r in rr),F(0))/w\n  bc=None if not w else variance-2*covariance;gap=None if not w else mp-o\n  bins.append(dict(index=i,rows=len(rr),mass=w,meanPrediction=mp,eventRate=o,gap=gap,absoluteGap=None if gap is None else abs(gap),scoreVariance=variance,scoreTargetCovariance=covariance,withinBinCorrection=bc,ids=[r['id']for r in rr]))\n  if w:\n   share=w/mass;ECE+=share*abs(gap);reliability+=share*gap**2;resolution+=share*(o-pi)**2;correction+=share*bc\n uncertainty=None if pi is None else pi*(1-pi);residual=None if Brier is None else Brier-(uncertainty-resolution+reliability+correction)\n return dict(mass=mass,prevalence=pi,Brier=Brier,ECE=ECE if mass else None,reliability=reliability if mass else None,resolution=resolution if mass else None,uncertainty=uncertainty,withinBinCorrection=correction if mass else None,BrierIdentityResidual=residual,bins=bins)\ndef typed(v):return type(v).__name__,v\ndef groups(rows,p,cc):\n bins={}\n for r in rows:\n  if r['group']is not None:bins.setdefault(typed(r['group']),[]).append(r)\n gm=[dict(group=rr[0]['group'],metrics=metrics(rr,p,cc))for rr in bins.values()];overall=metrics(rows,p,cc);unknown=metrics([r for r in rows if r['group']is None],p,cc);gaps={}\n for key in ['prevalence','selectionRate','TPR','FPR','precision','accuracy','meanCost']:\n  positive=[g for g in gm if g['metrics']['mass']>0];undefined=[g['group']for g in positive if g['metrics'][key]is None];vals=[g['metrics'][key]for g in positive if g['metrics'][key]is not None]\n  gaps[key]=dict(value=None if len(positive)<2 or undefined else max(vals)-min(vals),undefinedGroups=undefined,comparedPositiveMassGroups=[g['group']for g in positive])\n return dict(overall=overall,groups=gm,unknownGroup=unknown,gaps=gaps,partitionMassResidual=overall['mass']-unknown['mass']-sum((g['metrics']['mass']for g in gm),F(0)))\ndef actual_model(M):\n raw=M['records'];cat=M['categoricalFeatures'];p=len(raw[0]['x']);train=[r for r in raw if r['role']=='train'];medians=[]\n for j in range(p):\n  if j in cat:medians.append(None);continue\n  values=sorted(F(r['x'][j])for r in train);n=len(values);medians.append(values[n//2]if n%2 else(values[n//2-1]+values[n//2])/2)\n def transform(r):return[F(v)if j in cat else F(int(F(v)>medians[j]))for j,v in enumerate(r['x'])]\n counts={}\n for r in train:\n  key=tuple(transform(r));n,s=counts.get(key,(0,0));counts[key]=(n+1,s+int(r['y']))\n probabilities={k:F(s+1,n+2)for k,(n,s)in counts.items()};fallback=F(sum(int(r['y'])for r in train)+1,len(train)+2);scored=[]\n for i,r in enumerate(raw):\n  eligible=r['role']!='excluded';z=transform(r)if eligible else None;key=None if z is None else tuple(z);score=None if not eligible else probabilities.get(key,fallback)\n  scored.append(dict(id=r['id'],index=i,role=r['role'],group=r['group'],y=None if r['y']is None else F(r['y']),score=score,w=F(1),eligible=eligible,transformedX=z,unseenCell=None if not eligible else key not in probabilities))\n return dict(medians=medians,cells=counts,probabilities=probabilities,fallback=fallback,rows=scored,trainIDs=[r['id']for r in train])\n\n\nimport csv,json,hashlib,argparse,datetime\nfrom pathlib import Path\ndef missing(v):return None if v in ['', '.',None]else v\ndef load_sources(folder):\n def read_csv(name):\n  with (folder/name).open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))\n wb=read_csv('actual64-country-four-indicators-original-2024.csv')\n codes=['NY.GDP.PCAP.KD','NY.GDP.MKTP.KD.ZG','FP.CPI.TOTL.ZG','SP.DYN.LE00.IN']\n lookup={(r['countryISO3'],r['indicatorID']):r for r in wb};country=[]\n for i,iso in enumerate(sorted({r['countryISO3']for r in wb}),1):\n  native=[lookup[iso,c]for c in codes];v=[missing(r['originalValueToken'])for r in native]\n  country.append(dict(id=iso+':2024',sourceRow=i,originalID=iso,x=v[:3],y=None if v[3]is None else str(int(F(v[3])>=80)),group=None if v[0]is None else str(int(F(v[0])>=25000)),nativeTarget=v[3],nativeSourceRows=';'.join(r['sourceRow']for r in native)))\n nls=read_csv('actual3613-NLS-original52-fields-groups-roles.csv');person=[]\n for r in nls:\n  y=missing(r['wage76']);person.append(dict(id='person:'+r['sourceRow'],sourceRow=int(r['sourceRow']),originalID=r['id'],x=[missing(r[k])for k in ['ed76','age76','nearc4']],y=None if y is None else str(int(F(y)>=500)),group=missing(r['black']),nativeTarget=y,nativeSourceRows=r['sourceRow']))\n ch=read_csv('actual3150-churn-original14-fields-groups-roles.csv');company=[]\n for r in ch:\n  company.append(dict(id='customer:'+r['sourceRow'],sourceRow=int(r['sourceRow']),originalID='',x=[missing(r[k])for k in ['Call  Failure','Complains','Subscription  Length','Seconds of Use']],y=missing(r['Churn']),group=missing(r['Tariff Plan']),nativeTarget=missing(r['Churn']),nativeSourceRows=r['sourceRow']))\n assert len(wb)==64 and len(country)==16 and len(nls)==3613 and len(ch)==3150\n assert [int(r['sourceRow'])for r in ch if r['Charge  Amount']=='10']==[474,2174,2274,2374,2674,2924,2974]\n models={}\n for kind,raw,cat,units in [('country',country,[],['constant2015USD/person','annualPercent','annualPercent']),('person',person,[2],['years','years','nativeCategory']),('company',company,[1],['count','nativeCategory','months','seconds'])]:\n  order=sorted(range(len(raw)),key=lambda i:(hashlib.sha256(('ML14-role|'+kind+'|'+raw[i]['id']).encode()).hexdigest(),i))\n  for rank,i in enumerate(order):\n   r=raw[i];r['plannedRole']='test'if rank%5==0 else'validation'if rank%5==1 else'train';r['eligible']=None not in r['x']+[r['y']];r['role']=r['plannedRole']if r['eligible']else'excluded';r['weight']='1'\n  models[kind]=dict(records=raw,categoricalFeatures=cat,featureUnits=units)\n assert sum(r['eligible']for r in person)==3017\n return models\n\ndef exact(v):return ''if v is None else str(v)\ndef approx(v):return ''if v is None else format(float(v),'.17g')\ndef scalar_fields(m,keys):\n out={}\n for k in keys:\n  out[k+'Exact']=exact(m[k]);out[k+'Approx']=approx(m[k])\n return out\nCOUNTS=['mass','positiveTargetMass','negativeTargetMass','predictedPositiveMass','predictedNegativeMass']\nRATES=['prevalence','selectionRate','accuracy','precision','negativePredictiveValue','TPR','FPR','TNR','FNR','F1','balancedAccuracy','Brier','BrierSum','totalCost','meanCost']\nSCENARIOS=[('equal',F(1),F(1)),('miss-five',F(1),F(5)),('alarm-five',F(5),F(1))]\ndef packed(v):\n if isinstance(v,F):return str(v)\n if isinstance(v,dict):return{str(k):packed(x)for k,x in v.items()}\n if isinstance(v,(tuple,list)):return[packed(x)for x in v]\n return v\ndef run_study(source,out):\n out.mkdir(parents=True,exist_ok=True);models=load_sources(source)\n tables={name:[]for name in ['predictions','lineage','fit-medians','fit-cells','validation-candidates','test-metrics','test-curves','calibration-bins','group-metrics','chart-points']}\n studies={};charts=[]\n def point(kind,chart,series,index,x,y,xunit='dimensionless',yunit='dimensionless',role='test',tag=''):\n  tables['chart-points'].append(dict(kind=kind,chart=chart,series=series,index=index,xExact=exact(x),xApprox=approx(x),yExact=exact(y),yApprox=approx(y),xUnit=xunit,yUnit=yunit,role=role,tag=tag))\n for kind,M in models.items():\n  fit=actual_model(M);rr=fit['rows'];native=M['records'];test=scoped(rr,'test');cv=curves(test);cal=calibrate(test,[F(0),F(1,5),F(2,5),F(3,5),F(4,5),F(1)]);scenarios=[]\n  for i,r in enumerate(rr):\n   n=native[i];reason=''if r['eligible']else'required-X-or-Y-missing'\n   tables['predictions'].append(dict(kind=kind,id=r['id'],sourceRow=n['sourceRow'],originalID=n['originalID'],plannedRole=n['plannedRole'],role=r['role'],group=''if r['group']is None else r['group'],eligible=int(r['eligible']),targetExact=exact(r['y']),probabilityExact=exact(r['score']),probabilityApprox=approx(r['score']),unseenCell=''if r['unseenCell']is None else int(r['unseenCell']),transformedX=''if r['transformedX']is None else'|'.join(map(str,r['transformedX'])),reason=reason))\n   tables['lineage'].append(dict(kind=kind,id=r['id'],sourceRow=n['sourceRow'],originalID=n['originalID'],nativeSourceRows=n['nativeSourceRows'],rawX='|'.join(''if x is None else x for x in n['x']),nativeTarget=''if n['nativeTarget']is None else n['nativeTarget'],derivedTarget=exact(r['y']),nativeGroup=''if n['group']is None else n['group'],plannedRole=n['plannedRole'],role=r['role'],eligible=int(r['eligible']),analyticalMass='1',reason=reason))\n  for j,v in enumerate(fit['medians']):tables['fit-medians'].append(dict(kind=kind,feature=j,categorical=int(j in M['categoricalFeatures']),fitRows=len(fit['trainIDs']),medianExact=exact(v),medianApprox=approx(v),unit=M['featureUnits'][j]))\n  for key,(mass,pos)in fit['cells'].items():tables['fit-cells'].append(dict(kind=kind,cell='|'.join(map(str,key)),trainingRows=mass,positiveRows=pos,probabilityExact=exact(fit['probabilities'][key]),probabilityApprox=approx(fit['probabilities'][key]),fallbackExact=exact(fit['fallback']),fallbackApprox=approx(fit['fallback'])))\n  for j,p in enumerate(cv['points']):\n   policy=p['policy'];tables['test-curves'].append(dict(kind=kind,point=j,policy=policy if isinstance(policy,str)else'threshold',thresholdExact=''if isinstance(policy,str)else exact(policy),thresholdApprox=''if isinstance(policy,str)else approx(policy),**scalar_fields(p,['TP','FP','FN','TN','TPR','FPR','precision','recall'])))\n   point(kind,'roc','ROC',j,p['FPR'],p['TPR']);point(kind,'pr','PR-observed',j,p['recall'],p['precision'])\n  for b in cal['bins']:\n   tables['calibration-bins'].append(dict(kind=kind,bin=b['index'],leftExact=str(F(b['index'],5)),rightExact=str(F(b['index']+1,5)),rightClosed=int(b['index']==4),rows=b['rows'],ids=';'.join(str(i)for i in b['ids']),**scalar_fields(b,['mass','meanPrediction','eventRate','gap','absoluteGap','scoreVariance','scoreTargetCovariance','withinBinCorrection'])))\n   point(kind,'reliability','Binary event rate',b['index'],b['meanPrediction'],b['eventRate'],tag='rows='+str(b['rows']))\n  for j,r in enumerate(test):\n   point(kind,'test-scores','Training-fitted probability',j,F(j+1),r['score'],'test-row position','probability',tag=r['id'])\n   point(kind,'test-scores','Observed Y',j,F(j+1),r['y'],'test-row position','binary target',tag=r['id'])\n  for name,fp,fn in SCENARIOS:\n   choice=choose(rr,{},(fp,fn));gm=groups(test,choice['selectedPolicy'],(fp,fn));scenarios.append(dict(name=name,costs=dict(falsePositive=fp,falseNegative=fn),selection=choice,groups=gm));ev=choice['evaluation']\n   for c in choice['candidates']:\n    policy=c['policy'];mm=c['metrics'];tables['validation-candidates'].append(dict(kind=kind,scenario=name,candidate=c['index'],selected=int(c['index']==choice['selectedIndex']),policy=policy if isinstance(policy,str)else'threshold',thresholdExact=''if isinstance(policy,str)else exact(policy),thresholdApprox=''if isinstance(policy,str)else approx(policy),feasible=int(c['feasible']),reasons=';'.join(c['reasons']),**{k+'Exact':str(v)for k,v in mm['confusion'].items()},**scalar_fields(mm,COUNTS+['TPR','FPR','precision','meanCost','totalCost'])))\n    point(kind,'validation-cost',name,c['index'],F(c['index']),mm['meanCost'],'candidate index','hypothetical cost units/mass','validation',tag=exact(policy))\n   mm={**ev,**ev['confusion'],**{k:cv[k]for k in ['ROC_AUC','averagePrecision','PRTrapezoidWithInitialPrecisionOne']},**{k:cal[k]for k in ['ECE','reliability','resolution','uncertainty','withinBinCorrection','BrierIdentityResidual']}}\n   for key in ['TP','FP','FN','TN']+COUNTS+RATES+['ROC_AUC','averagePrecision','PRTrapezoidWithInitialPrecisionOne','ECE','reliability','resolution','uncertainty','withinBinCorrection','BrierIdentityResidual']:\n    unit='rows'if key in ['TP','FP','FN','TN']+COUNTS else'hypothetical cost units'if key=='totalCost'else'hypothetical cost units/mass'if key=='meanCost'else'sum squared-probability loss'if key=='BrierSum'else'dimensionless'\n    tables['test-metrics'].append(dict(kind=kind,scenario=name,metric=key,valueExact=exact(mm[key]),valueApprox=approx(mm[key]),unit=unit))\n   allg=[('overall','all',gm['overall'])]+[('known',str(g['group']),g['metrics'])for g in gm['groups']]+[('unknown','',gm['unknownGroup'])]\n   for j,(typ,token,g)in enumerate(allg):\n    tables['group-metrics'].append(dict(kind=kind,scenario=name,groupType=typ,groupToken=token,retainedRows=g.get('retainedRows',sum((r['group']==token)if typ=='known'else(r['group']is None)if typ=='unknown'else True for r in test)),**{k+'Exact':str(v)for k,v in g['confusion'].items()},**scalar_fields(g,COUNTS+RATES)))\n    if typ=='known':point(kind,'group-TPR',name,j-1,F(j-1),g['TPR'],'declared group position','TPR',tag=token)\n  studies[kind]=dict(kind=kind,rows=len(native),eligibleRows=sum(r['eligible']for r in rr),trainingIDs=fit['trainIDs'],fitMedians=fit['medians'],fitCells=[dict(cell=list(k),mass=n,positive=s,probability=fit['probabilities'][k])for k,(n,s)in fit['cells'].items()],fallback=fit['fallback'],scenarios=scenarios,testCurves=cv,testCalibration=cal,rowsScored=rr)\n files=[]\n for name,rows in tables.items():\n  p=out/('computed-'+name+'.csv')\n  with p.open('w',encoding='utf8',newline='')as f:w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows)\n  files.append(dict(file=p.name,rows=len(rows),columns=len(rows[0]),bodyFields=len(rows)*len(rows[0]),sha256=hashlib.sha256(p.read_bytes()).hexdigest()))\n (out/'study.json').write_text(json.dumps(packed(studies),ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\n sourceFiles=[source/n for n in ['actual64-country-four-indicators-original-2024.csv','actual3613-NLS-original52-fields-groups-roles.csv','actual3150-churn-original14-fields-groups-roles.csv']]\n provenance=dict(chapter='ML-14',arithmetic='Python stdlib Fraction exact finite values from original decimal strings; binary64 valueApprox is display only.',inputs=[dict(file=p.name,sha256=hashlib.sha256(p.read_bytes()).hexdigest())for p in sourceFiles],priorEngineModelsScoresOrComputedFilesRead=False,roleRule=\"SHA256('ML14-role|'+kind+'|'+ID),rankmod5=0test/1validation/others train before eligibility\",costs='Hypothetical1/1,1/5,5/1; no causal intervention returns',files=files,observations={k:dict(sourceRows=v['rows'],eligibleRows=v['eligibleRows'],trainingRows=len(v['trainingIDs']))for k,v in studies.items()})\n (out/'provenance.json').write_text(json.dumps(provenance,ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\n print(json.dumps(dict(status='PASS standalone completed',files=len(files),bodyFields=sum(f['bodyFields']for f in files),observations=provenance['observations'])))\n\n# Fixed declared examples: full web budget/option validation is not reproduced.\nfrom html import escape\nimport textwrap\ndef validated_rows(raw):\n for r in raw:\n  assert F(str(r.get('weight','1')))>=0,'negative analytical mass'\n  assert r['score']is None or 0<=F(str(r['score']))<=1,'score outside zero/one'\n  assert r['y']is None or F(str(int(r['y']))if isinstance(r['y'],bool)else str(r['y']))in [0,1],'binary target required'\n return read(raw)\ndef serial(v):\n if isinstance(v,F):return dict(exactFraction=str(v),value=float(v))\n if isinstance(v,(list,tuple)):return[serial(x)for x in v]\n if isinstance(v,dict):return{k:serial(x)for k,x in v.items()}\n return v\ndef fixed_svg(path,points,title,xlabel,ylabel,legend):\n use=[p for p in points if p['xExact']!=''and p['yExact']!=''];xs=[float(F(p['xExact']))for p in use];ys=[float(F(p['yExact']))for p in use]\n xmin=min(xs,default=0);xmax=max(xs,default=1);ymin=min([0]+ys);ymax=max([0]+ys)\n if xmin==xmax:xmin-=.5;xmax+=.5\n if ymin==ymax:ymax=ymin+1\n X=lambda v:85+(float(v)-xmin)/(xmax-xmin)*480;Y=lambda v:278-(float(v)-ymin)/(ymax-ymin)*175\n s='<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"620\" height=\"360\" viewBox=\"0 0 620 360\"><rect width=\"620\" height=\"360\" fill=\"white\"/><g font-family=\"Arial, sans-serif\" font-size=\"13\" fill=\"#17324d\">'\n for i,line in enumerate(textwrap.wrap(title,width=65)):s+='<text x=\"25\" y=\"'+str(24+i*18)+'\">'+escape(line)+'</text>'\n colors=['#176b9b','#b85e18','#437e4d']\n for i,label in enumerate(legend):s+='<circle cx=\"'+str(30+i*250)+'\" cy=\"76\" r=\"4\" fill=\"'+colors[i%3]+'\"/><text x=\"'+str(42+i*250)+'\" y=\"80\">'+escape(label)+'</text>'\n s+='<path d=\"M85 98V278H575\" fill=\"none\" stroke=\"#52677d\"/><text text-anchor=\"middle\" x=\"325\" y=\"338\">'+escape(xlabel)+'</text><text text-anchor=\"middle\" transform=\"translate(21,190) rotate(-90)\">'+escape(ylabel)+'</text>'\n for i in range(5):\n  xx=xmin+(xmax-xmin)*i/4;yy=ymin+(ymax-ymin)*i/4;s+='<text text-anchor=\"middle\" x=\"'+format(X(xx),'.9g')+'\" y=\"305\">'+format(xx,'.4g')+'</text><text text-anchor=\"end\" x=\"77\" y=\"'+format(Y(yy)+4,'.9g')+'\">'+format(yy,'.4g')+'</text>'\n for p in use:s+='<circle cx=\"'+format(X(F(p['xExact'])),'.9g')+'\" cy=\"'+format(Y(F(p['yExact'])),'.9g')+'\" r=\"3\" fill=\"'+colors[p['series']%3]+'\"/>'\n path.write_text(s+'</g></svg>',encoding='utf8')\ndef fixed_run():\n ap=argparse.ArgumentParser();ap.add_argument('--out',type=Path,default=Path('results'));ap.add_argument('--data-dir',type=Path,default=Path(__file__).resolve().parent.parent/'ml14-sources');args=ap.parse_args();args.out.mkdir(parents=True,exist_ok=True)\n api=FIXED['api'];a=FIXED['args'];summary=[];points=[];xlabel='Declared index';ylabel='Value';legend=['Declared result']\n def metric(name,v,unit='dimensionless'):\n  q=None if v is None else v if isinstance(v,F)else F(v);summary.append(dict(metric=name,value='undefined'if q is None else format(float(q),'.9g'),exactValue=''if q is None else str(q),unit=unit,defined=int(q is not None)))\n def pt(i,x,y,ident='',series=0):\n  points.append(dict(series=series,index=i,xExact=''if x is None else str(F(x)),x='undefined'if x is None else format(float(x),'.9g'),yExact=''if y is None else str(F(y)),y='undefined'if y is None else format(float(y),'.9g'),id=str(ident)))\n if api=='realdata':\n  models=load_sources(args.data_dir);model=models[a['kind']];fit=actual_model(model);rr=fit['rows'];test=scoped(rr,'test');scenarios=[]\n  for name,fp,fn in SCENARIOS:\n   c=choose(rr,{},(fp,fn));scenarios.append(dict(name=name,selection=c));metric(name+'Threshold',c['selectedPolicy']);metric(name+'TestCost',c['evaluation']['meanCost'],'hypothetical cost units/mass')\n  cv=curves(test);cal=calibrate(test,[F(0),F(1,5),F(2,5),F(3,5),F(4,5),F(1)]);metric('testAUC',cv['ROC_AUC']);metric('testAP',cv['averagePrecision']);metric('testBrier',cal['Brier']);metric('eligibleRows',sum(r['eligible']for r in rr),'rows')\n  for i,r in enumerate(test):pt(i,i+1,r['score'],r['id'],0);pt(i,i+1,r['y'],r['id'],1)\n  full=dict(kind=a['kind'],fitMedians=fit['medians'],fitCells=[dict(cell=list(k),mass=n,positive=s,probability=fit['probabilities'][k])for k,(n,s)in fit['cells'].items()],rowsScored=rr,scenarios=scenarios,testCurves=cv,testCalibration=cal);xlabel='Test row, native order';ylabel='Y or probability';legend=['Training-fitted probability','Observed Y']\n else:\n  rr=validated_rows(a['rows']);role=a.get('role','all');frame=scoped(rr,role);cc=cost(a.get('costs'));t=policy(a.get('threshold','1/2'))\n  if api=='metrics':\n   full=metrics(frame,t,cc)\n   for k in ['mass','accuracy','precision','TPR','FPR','F1','Brier','meanCost']:metric(k,full[k],'mass'if k=='mass'else'hypothetical cost units/mass'if k=='meanCost'else'dimensionless')\n   metric('BayesThreshold',full['bayesThreshold'])\n   for i,k in enumerate(['TP','FP','FN','TN']):pt(i,i,full['confusion'][k],k)\n   xlabel='TP / FP / FN / TN positions';ylabel='Analytical mass'\n  elif api=='curves':\n   full=curves(frame)\n   for k in ['ROC_AUC','averagePrecision','PRTrapezoidWithInitialPrecisionOne']:metric(k,full[k])\n   for i,p in enumerate(full['points']):pt(i,p['FPR'],p['TPR'],str(p['policy']))\n   xlabel='False positive rate';ylabel='True positive rate';legend=['Observed ROC operating points']\n  elif api=='choose':\n   full=choose(rr,a,cc);metric('selectedIndex',full['selectedIndex'],'candidate index');metric('minimumCost',None if full['selectedValidation']is None else full['selectedValidation']['meanCost'],'hypothetical cost units/mass');metric('feasible',int(full['selectedIndex']is not None),'indicator')\n   for c in full['candidates']:pt(c['index'],c['index'],c['metrics']['meanCost'],str(c['policy']))\n   xlabel='Validation candidate';ylabel='Assumed cost / mass';legend=['Validation candidate costs']\n  elif api=='calibrate':\n   full=calibrate(frame,[F(str(e))for e in a.get('binEdges',['0','1/5','2/5','3/5','4/5','1'])])\n   for k in ['ECE','Brier','uncertainty','resolution','reliability','withinBinCorrection','BrierIdentityResidual']:metric(k,full[k])\n   for b in full['bins']:pt(b['index'],b['meanPrediction'],b['eventRate'],'bin:'+str(b['index']))\n   xlabel='Bin mean forecast';ylabel='Bin event rate';legend=['Binary-event reliability']\n  elif api=='groups':\n   full=groups(frame,t,cc);metric('overallTPR',full['overall']['TPR']);metric('TPRGap',full['gaps']['TPR']['value']);metric('precisionGap',full['gaps']['precision']['value']);metric('unknownMass',full['unknownGroup']['mass'],'mass');metric('partitionResidual',full['partitionMassResidual'],'mass')\n   for i,g in enumerate(full['groups']):pt(i,i,g['metrics']['TPR'],str(g['group']))\n   xlabel='Declared group position';ylabel='True positive rate';legend=['Known-group TPR']\n  else:raise ValueError('unknown fixed API')\n def csvout(name,rows):\n  with(args.out/name).open('w',encoding='utf8',newline='')as f:w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows)\n csvout('summary.csv',summary);csvout('plot-points.csv',points);fixed_svg(args.out/'plot.svg',points,FIXED['title'],xlabel,ylabel,legend)\n (args.out/'full.json').write_text(json.dumps(dict(api=api,variant=FIXED['variant'],input=FIXED['args'],arithmetic='Python standard-library Fraction, declared fixed example; full web validator/budgets not reproduced',result=serial(full)),ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\n print(json.dumps(dict(api=api,variant=FIXED['variant'],summaryMetrics=len(summary),plotSlots=len(points))))\n\nFIXED={'api': 'groups', 'variant': 'unknown-group', 'args': {'rows': [{'id': 'a', 'score': '.9', 'y': 1, 'group': 'A'}, {'id': 'b', 'score': '.8', 'y': 1, 'group': 'A'}, {'id': 'c', 'score': '.8', 'y': 0, 'group': 'A'}, {'id': 'd', 'score': '.6', 'y': 0, 'group': 'B'}, {'id': 'e', 'score': '.4', 'y': 1, 'group': 'B'}, {'id': 'f', 'score': '.1', 'y': 0, 'group': None}], 'threshold': '.4'}, 'title': 'Unknown group stays overall and preserves mass'}\nif __name__=='__main__':fixed_run()\n",
        "codeText": "#!/usr/bin/env python3\n\"\"\"ML14 standalone exact finite study, Python standard library only.\nInputs: only the three retained factual source CSVs below.\nDerived role/target/group/eligibility columns in those CSVs are NOT inputs.\nRebuilds SHA256 roles, train-only medians/cell scores, validation thresholds,\ntest curves, binary-event reliability and descriptive group ledgers.\nCosts 1/1,1/5,5/1 are hypothetical units, not measured intervention returns.\nThis is author public reproduction, not independent scientific review.\n\"\"\"\n\"\"\"Author Fraction reference, separate from product JavaScript; not independent peer.\"\"\"\nfrom fractions import Fraction as F\nfrom collections import Counter,defaultdict\ndef read(raw):\n rows=[]\n for i,r in enumerate(raw):\n  s=None if r['score']is None else F(str(r['score']));y=None if r['y']is None else F(int(r['y']))if isinstance(r['y'],bool)else F(str(r['y']));w=F(str(r.get('weight','1')));role=r.get('role','evaluation')\n  rows.append(dict(id=r['id'],index=i,score=s,y=y,w=w,role=role,group=r.get('group'),eligible=s is not None and y is not None and w>0 and role!='excluded'))\n return rows\ndef scoped(rows,role='all'):return rows if role=='all'else[r for r in rows if r['role']==role]\ndef divide(n,d):return None if not d else n/d\ndef policy(v):return v if v in ['always-negative','always-positive']else F(str(v))\ndef positive(p,s):return p=='always-positive'if isinstance(p,str)else s>=p\ndef cost(a=None):\n a={}if a is None else a;fp=F(str(a.get('falsePositive','1')));fn=F(str(a.get('falseNegative','1')));return fp,fn\ndef metrics(rows,threshold=F(1,2),cc=(F(1),F(1))):\n counts=dict(TP=F(0),FP=F(0),FN=F(0),TN=F(0));brier=F(0);pred=[]\n for r in rows:\n  if not r['eligible']:pred.append(dict(id=r['id'],index=r['index'],eligible=False,decision=None,probability=None,Brier=None));continue\n  yes=positive(threshold,r['score']);cell=('T'if yes==bool(r['y'])else'F')+('P'if yes else'N');counts[cell]+=r['w'];loss=(r['score']-r['y'])**2;brier+=r['w']*loss;pred.append(dict(id=r['id'],index=r['index'],eligible=True,decision=int(yes),probability=r['score'],Brier=loss))\n TP,FP,FN,TN=[counts[k]for k in ['TP','FP','FN','TN']];P=TP+FN;N=TN+FP;mass=P+N;PP=TP+FP;PN=TN+FN;TPR=divide(TP,P);TNR=divide(TN,N);total=FP*cc[0]+FN*cc[1]\n return dict(confusion=counts,mass=mass,positiveTargetMass=P,negativeTargetMass=N,predictedPositiveMass=PP,predictedNegativeMass=PN,prevalence=divide(P,mass),selectionRate=divide(PP,mass),accuracy=divide(TP+TN,mass),precision=divide(TP,PP),negativePredictiveValue=divide(TN,PN),TPR=TPR,FPR=divide(FP,N),TNR=TNR,FNR=divide(FN,P),F1=divide(2*TP,2*TP+FP+FN),balancedAccuracy=None if TPR is None or TNR is None else(TPR+TNR)/2,Brier=divide(brier,mass),BrierSum=brier,totalCost=total,meanCost=divide(total,mass),predictions=pred,bayesThreshold=divide(cc[0],sum(cc)))\ndef curves(rows):\n use=[r for r in rows if r['eligible']];pos=Counter();neg=Counter()\n for r in use:(pos if r['y']else neg)[r['score']]+=r['w']\n P=sum(pos.values(),F(0));N=sum(neg.values(),F(0));pairs=F(0)\n for a,wa in pos.items():\n  for b,wb in neg.items():pairs+=wa*wb*(F(1)if a>b else F(1,2)if a==b else F(0))\n thresholds=['always-negative']+sorted({r['score']for r in use},reverse=True);points=[];AP=F(0);trap=F(0);lastR=F(0);lastP=F(1)\n for i,p in enumerate(thresholds):\n  m=metrics(rows,p);points.append(dict(policy=p,TP=m['confusion']['TP'],FP=m['confusion']['FP'],FN=m['confusion']['FN'],TN=m['confusion']['TN'],TPR=m['TPR'],FPR=m['FPR'],precision=m['precision'],recall=m['TPR']))\n  if i and P:\n   R=m['TPR'];PP=m['precision'];AP+=(R-lastR)*PP;trap+=(R-lastR)*(PP+lastP)/2;lastR=R;lastP=PP\n return dict(positiveMass=P,negativeMass=N,ROC_AUC=divide(pairs,P*N),weightedConcordantPlusHalfTiedMass=pairs,averagePrecision=AP if P else None,PRTrapezoidWithInitialPrecisionOne=trap if P else None,points=points)\ndef choose(rows,a,cc):\n sr=a.get('selectionRole','validation');er=a.get('evaluationRole','test');rr=scoped(rows,sr);thresholds=[policy(t)for t in a['thresholds']]if'thresholds'in a else['always-negative']+sorted({r['score']for r in rr if r['eligible']},reverse=True)\n candidates=[]\n for i,p in enumerate(thresholds):\n  m=metrics(rr,p,cc);reasons=[]\n  if'minTPR'in a and(m['TPR']is None or m['TPR']<F(str(a['minTPR']))):reasons.append('TPR-undefined'if m['TPR']is None else'below-minTPR')\n  if'maxFPR'in a and(m['FPR']is None or m['FPR']>F(str(a['maxFPR']))):reasons.append('FPR-undefined'if m['FPR']is None else'above-maxFPR')\n  candidates.append(dict(index=i,policy=p,metrics=m,feasible=not reasons,reasons=reasons))\n eligible=[c for c in candidates if c['feasible']];best=min(eligible,key=lambda c:(c['metrics']['meanCost'],c['index']))if eligible else None\n return dict(selectedIndex=None if best is None else best['index'],selectedPolicy=None if best is None else best['policy'],candidates=candidates,selectedValidation=None if best is None else best['metrics'],evaluation=None if best is None or er=='none'else metrics(scoped(rows,er),best['policy'],cc),selectionIDs=[r['id']for r in rr if r['eligible']])\ndef calibrate(rows,ee):\n buckets=[[]for _ in range(len(ee)-1)]\n for r in rows:\n  if not r['eligible']:continue\n  j=next((i for i in range(len(ee)-1)if r['score']<ee[i+1]),len(ee)-2);buckets[j].append(r)\n mass=sum((r['w']for r in rows if r['eligible']),F(0));P=sum((r['w']*r['y']for r in rows if r['eligible']),F(0));pi=divide(P,mass);Brier=None if not mass else sum((r['w']*(r['score']-r['y'])**2 for r in rows if r['eligible']),F(0))/mass;ECE=F(0);reliability=F(0);resolution=F(0);correction=F(0);bins=[]\n for i,rr in enumerate(buckets):\n  w=sum((r['w']for r in rr),F(0));mp=None if not w else sum((r['w']*r['score']for r in rr),F(0))/w;o=None if not w else sum((r['w']*r['y']for r in rr),F(0))/w\n  variance=None if not w else sum((r['w']*(r['score']-mp)**2 for r in rr),F(0))/w\n  covariance=None if not w else sum((r['w']*(r['score']-mp)*(r['y']-o)for r in rr),F(0))/w\n  bc=None if not w else variance-2*covariance;gap=None if not w else mp-o\n  bins.append(dict(index=i,rows=len(rr),mass=w,meanPrediction=mp,eventRate=o,gap=gap,absoluteGap=None if gap is None else abs(gap),scoreVariance=variance,scoreTargetCovariance=covariance,withinBinCorrection=bc,ids=[r['id']for r in rr]))\n  if w:\n   share=w/mass;ECE+=share*abs(gap);reliability+=share*gap**2;resolution+=share*(o-pi)**2;correction+=share*bc\n uncertainty=None if pi is None else pi*(1-pi);residual=None if Brier is None else Brier-(uncertainty-resolution+reliability+correction)\n return dict(mass=mass,prevalence=pi,Brier=Brier,ECE=ECE if mass else None,reliability=reliability if mass else None,resolution=resolution if mass else None,uncertainty=uncertainty,withinBinCorrection=correction if mass else None,BrierIdentityResidual=residual,bins=bins)\ndef typed(v):return type(v).__name__,v\ndef groups(rows,p,cc):\n bins={}\n for r in rows:\n  if r['group']is not None:bins.setdefault(typed(r['group']),[]).append(r)\n gm=[dict(group=rr[0]['group'],metrics=metrics(rr,p,cc))for rr in bins.values()];overall=metrics(rows,p,cc);unknown=metrics([r for r in rows if r['group']is None],p,cc);gaps={}\n for key in ['prevalence','selectionRate','TPR','FPR','precision','accuracy','meanCost']:\n  positive=[g for g in gm if g['metrics']['mass']>0];undefined=[g['group']for g in positive if g['metrics'][key]is None];vals=[g['metrics'][key]for g in positive if g['metrics'][key]is not None]\n  gaps[key]=dict(value=None if len(positive)<2 or undefined else max(vals)-min(vals),undefinedGroups=undefined,comparedPositiveMassGroups=[g['group']for g in positive])\n return dict(overall=overall,groups=gm,unknownGroup=unknown,gaps=gaps,partitionMassResidual=overall['mass']-unknown['mass']-sum((g['metrics']['mass']for g in gm),F(0)))\ndef actual_model(M):\n raw=M['records'];cat=M['categoricalFeatures'];p=len(raw[0]['x']);train=[r for r in raw if r['role']=='train'];medians=[]\n for j in range(p):\n  if j in cat:medians.append(None);continue\n  values=sorted(F(r['x'][j])for r in train);n=len(values);medians.append(values[n//2]if n%2 else(values[n//2-1]+values[n//2])/2)\n def transform(r):return[F(v)if j in cat else F(int(F(v)>medians[j]))for j,v in enumerate(r['x'])]\n counts={}\n for r in train:\n  key=tuple(transform(r));n,s=counts.get(key,(0,0));counts[key]=(n+1,s+int(r['y']))\n probabilities={k:F(s+1,n+2)for k,(n,s)in counts.items()};fallback=F(sum(int(r['y'])for r in train)+1,len(train)+2);scored=[]\n for i,r in enumerate(raw):\n  eligible=r['role']!='excluded';z=transform(r)if eligible else None;key=None if z is None else tuple(z);score=None if not eligible else probabilities.get(key,fallback)\n  scored.append(dict(id=r['id'],index=i,role=r['role'],group=r['group'],y=None if r['y']is None else F(r['y']),score=score,w=F(1),eligible=eligible,transformedX=z,unseenCell=None if not eligible else key not in probabilities))\n return dict(medians=medians,cells=counts,probabilities=probabilities,fallback=fallback,rows=scored,trainIDs=[r['id']for r in train])\n\n\nimport csv,json,hashlib,argparse,datetime\nfrom pathlib import Path\ndef missing(v):return None if v in ['', '.',None]else v\ndef load_sources(folder):\n def read_csv(name):\n  with (folder/name).open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))\n wb=read_csv('actual64-country-four-indicators-original-2024.csv')\n codes=['NY.GDP.PCAP.KD','NY.GDP.MKTP.KD.ZG','FP.CPI.TOTL.ZG','SP.DYN.LE00.IN']\n lookup={(r['countryISO3'],r['indicatorID']):r for r in wb};country=[]\n for i,iso in enumerate(sorted({r['countryISO3']for r in wb}),1):\n  native=[lookup[iso,c]for c in codes];v=[missing(r['originalValueToken'])for r in native]\n  country.append(dict(id=iso+':2024',sourceRow=i,originalID=iso,x=v[:3],y=None if v[3]is None else str(int(F(v[3])>=80)),group=None if v[0]is None else str(int(F(v[0])>=25000)),nativeTarget=v[3],nativeSourceRows=';'.join(r['sourceRow']for r in native)))\n nls=read_csv('actual3613-NLS-original52-fields-groups-roles.csv');person=[]\n for r in nls:\n  y=missing(r['wage76']);person.append(dict(id='person:'+r['sourceRow'],sourceRow=int(r['sourceRow']),originalID=r['id'],x=[missing(r[k])for k in ['ed76','age76','nearc4']],y=None if y is None else str(int(F(y)>=500)),group=missing(r['black']),nativeTarget=y,nativeSourceRows=r['sourceRow']))\n ch=read_csv('actual3150-churn-original14-fields-groups-roles.csv');company=[]\n for r in ch:\n  company.append(dict(id='customer:'+r['sourceRow'],sourceRow=int(r['sourceRow']),originalID='',x=[missing(r[k])for k in ['Call  Failure','Complains','Subscription  Length','Seconds of Use']],y=missing(r['Churn']),group=missing(r['Tariff Plan']),nativeTarget=missing(r['Churn']),nativeSourceRows=r['sourceRow']))\n assert len(wb)==64 and len(country)==16 and len(nls)==3613 and len(ch)==3150\n assert [int(r['sourceRow'])for r in ch if r['Charge  Amount']=='10']==[474,2174,2274,2374,2674,2924,2974]\n models={}\n for kind,raw,cat,units in [('country',country,[],['constant2015USD/person','annualPercent','annualPercent']),('person',person,[2],['years','years','nativeCategory']),('company',company,[1],['count','nativeCategory','months','seconds'])]:\n  order=sorted(range(len(raw)),key=lambda i:(hashlib.sha256(('ML14-role|'+kind+'|'+raw[i]['id']).encode()).hexdigest(),i))\n  for rank,i in enumerate(order):\n   r=raw[i];r['plannedRole']='test'if rank%5==0 else'validation'if rank%5==1 else'train';r['eligible']=None not in r['x']+[r['y']];r['role']=r['plannedRole']if r['eligible']else'excluded';r['weight']='1'\n  models[kind]=dict(records=raw,categoricalFeatures=cat,featureUnits=units)\n assert sum(r['eligible']for r in person)==3017\n return models\n\ndef exact(v):return ''if v is None else str(v)\ndef approx(v):return ''if v is None else format(float(v),'.17g')\ndef scalar_fields(m,keys):\n out={}\n for k in keys:\n  out[k+'Exact']=exact(m[k]);out[k+'Approx']=approx(m[k])\n return out\nCOUNTS=['mass','positiveTargetMass','negativeTargetMass','predictedPositiveMass','predictedNegativeMass']\nRATES=['prevalence','selectionRate','accuracy','precision','negativePredictiveValue','TPR','FPR','TNR','FNR','F1','balancedAccuracy','Brier','BrierSum','totalCost','meanCost']\nSCENARIOS=[('equal',F(1),F(1)),('miss-five',F(1),F(5)),('alarm-five',F(5),F(1))]\ndef packed(v):\n if isinstance(v,F):return str(v)\n if isinstance(v,dict):return{str(k):packed(x)for k,x in v.items()}\n if isinstance(v,(tuple,list)):return[packed(x)for x in v]\n return v\ndef run_study(source,out):\n out.mkdir(parents=True,exist_ok=True);models=load_sources(source)\n tables={name:[]for name in ['predictions','lineage','fit-medians','fit-cells','validation-candidates','test-metrics','test-curves','calibration-bins','group-metrics','chart-points']}\n studies={};charts=[]\n def point(kind,chart,series,index,x,y,xunit='dimensionless',yunit='dimensionless',role='test',tag=''):\n  tables['chart-points'].append(dict(kind=kind,chart=chart,series=series,index=index,xExact=exact(x),xApprox=approx(x),yExact=exact(y),yApprox=approx(y),xUnit=xunit,yUnit=yunit,role=role,tag=tag))\n for kind,M in models.items():\n  fit=actual_model(M);rr=fit['rows'];native=M['records'];test=scoped(rr,'test');cv=curves(test);cal=calibrate(test,[F(0),F(1,5),F(2,5),F(3,5),F(4,5),F(1)]);scenarios=[]\n  for i,r in enumerate(rr):\n   n=native[i];reason=''if r['eligible']else'required-X-or-Y-missing'\n   tables['predictions'].append(dict(kind=kind,id=r['id'],sourceRow=n['sourceRow'],originalID=n['originalID'],plannedRole=n['plannedRole'],role=r['role'],group=''if r['group']is None else r['group'],eligible=int(r['eligible']),targetExact=exact(r['y']),probabilityExact=exact(r['score']),probabilityApprox=approx(r['score']),unseenCell=''if r['unseenCell']is None else int(r['unseenCell']),transformedX=''if r['transformedX']is None else'|'.join(map(str,r['transformedX'])),reason=reason))\n   tables['lineage'].append(dict(kind=kind,id=r['id'],sourceRow=n['sourceRow'],originalID=n['originalID'],nativeSourceRows=n['nativeSourceRows'],rawX='|'.join(''if x is None else x for x in n['x']),nativeTarget=''if n['nativeTarget']is None else n['nativeTarget'],derivedTarget=exact(r['y']),nativeGroup=''if n['group']is None else n['group'],plannedRole=n['plannedRole'],role=r['role'],eligible=int(r['eligible']),analyticalMass='1',reason=reason))\n  for j,v in enumerate(fit['medians']):tables['fit-medians'].append(dict(kind=kind,feature=j,categorical=int(j in M['categoricalFeatures']),fitRows=len(fit['trainIDs']),medianExact=exact(v),medianApprox=approx(v),unit=M['featureUnits'][j]))\n  for key,(mass,pos)in fit['cells'].items():tables['fit-cells'].append(dict(kind=kind,cell='|'.join(map(str,key)),trainingRows=mass,positiveRows=pos,probabilityExact=exact(fit['probabilities'][key]),probabilityApprox=approx(fit['probabilities'][key]),fallbackExact=exact(fit['fallback']),fallbackApprox=approx(fit['fallback'])))\n  for j,p in enumerate(cv['points']):\n   policy=p['policy'];tables['test-curves'].append(dict(kind=kind,point=j,policy=policy if isinstance(policy,str)else'threshold',thresholdExact=''if isinstance(policy,str)else exact(policy),thresholdApprox=''if isinstance(policy,str)else approx(policy),**scalar_fields(p,['TP','FP','FN','TN','TPR','FPR','precision','recall'])))\n   point(kind,'roc','ROC',j,p['FPR'],p['TPR']);point(kind,'pr','PR-observed',j,p['recall'],p['precision'])\n  for b in cal['bins']:\n   tables['calibration-bins'].append(dict(kind=kind,bin=b['index'],leftExact=str(F(b['index'],5)),rightExact=str(F(b['index']+1,5)),rightClosed=int(b['index']==4),rows=b['rows'],ids=';'.join(str(i)for i in b['ids']),**scalar_fields(b,['mass','meanPrediction','eventRate','gap','absoluteGap','scoreVariance','scoreTargetCovariance','withinBinCorrection'])))\n   point(kind,'reliability','Binary event rate',b['index'],b['meanPrediction'],b['eventRate'],tag='rows='+str(b['rows']))\n  for j,r in enumerate(test):\n   point(kind,'test-scores','Training-fitted probability',j,F(j+1),r['score'],'test-row position','probability',tag=r['id'])\n   point(kind,'test-scores','Observed Y',j,F(j+1),r['y'],'test-row position','binary target',tag=r['id'])\n  for name,fp,fn in SCENARIOS:\n   choice=choose(rr,{},(fp,fn));gm=groups(test,choice['selectedPolicy'],(fp,fn));scenarios.append(dict(name=name,costs=dict(falsePositive=fp,falseNegative=fn),selection=choice,groups=gm));ev=choice['evaluation']\n   for c in choice['candidates']:\n    policy=c['policy'];mm=c['metrics'];tables['validation-candidates'].append(dict(kind=kind,scenario=name,candidate=c['index'],selected=int(c['index']==choice['selectedIndex']),policy=policy if isinstance(policy,str)else'threshold',thresholdExact=''if isinstance(policy,str)else exact(policy),thresholdApprox=''if isinstance(policy,str)else approx(policy),feasible=int(c['feasible']),reasons=';'.join(c['reasons']),**{k+'Exact':str(v)for k,v in mm['confusion'].items()},**scalar_fields(mm,COUNTS+['TPR','FPR','precision','meanCost','totalCost'])))\n    point(kind,'validation-cost',name,c['index'],F(c['index']),mm['meanCost'],'candidate index','hypothetical cost units/mass','validation',tag=exact(policy))\n   mm={**ev,**ev['confusion'],**{k:cv[k]for k in ['ROC_AUC','averagePrecision','PRTrapezoidWithInitialPrecisionOne']},**{k:cal[k]for k in ['ECE','reliability','resolution','uncertainty','withinBinCorrection','BrierIdentityResidual']}}\n   for key in ['TP','FP','FN','TN']+COUNTS+RATES+['ROC_AUC','averagePrecision','PRTrapezoidWithInitialPrecisionOne','ECE','reliability','resolution','uncertainty','withinBinCorrection','BrierIdentityResidual']:\n    unit='rows'if key in ['TP','FP','FN','TN']+COUNTS else'hypothetical cost units'if key=='totalCost'else'hypothetical cost units/mass'if key=='meanCost'else'sum squared-probability loss'if key=='BrierSum'else'dimensionless'\n    tables['test-metrics'].append(dict(kind=kind,scenario=name,metric=key,valueExact=exact(mm[key]),valueApprox=approx(mm[key]),unit=unit))\n   allg=[('overall','all',gm['overall'])]+[('known',str(g['group']),g['metrics'])for g in gm['groups']]+[('unknown','',gm['unknownGroup'])]\n   for j,(typ,token,g)in enumerate(allg):\n    tables['group-metrics'].append(dict(kind=kind,scenario=name,groupType=typ,groupToken=token,retainedRows=g.get('retainedRows',sum((r['group']==token)if typ=='known'else(r['group']is None)if typ=='unknown'else True for r in test)),**{k+'Exact':str(v)for k,v in g['confusion'].items()},**scalar_fields(g,COUNTS+RATES)))\n    if typ=='known':point(kind,'group-TPR',name,j-1,F(j-1),g['TPR'],'declared group position','TPR',tag=token)\n  studies[kind]=dict(kind=kind,rows=len(native),eligibleRows=sum(r['eligible']for r in rr),trainingIDs=fit['trainIDs'],fitMedians=fit['medians'],fitCells=[dict(cell=list(k),mass=n,positive=s,probability=fit['probabilities'][k])for k,(n,s)in fit['cells'].items()],fallback=fit['fallback'],scenarios=scenarios,testCurves=cv,testCalibration=cal,rowsScored=rr)\n files=[]\n for name,rows in tables.items():\n  p=out/('computed-'+name+'.csv')\n  with p.open('w',encoding='utf8',newline='')as f:w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows)\n  files.append(dict(file=p.name,rows=len(rows),columns=len(rows[0]),bodyFields=len(rows)*len(rows[0]),sha256=hashlib.sha256(p.read_bytes()).hexdigest()))\n (out/'study.json').write_text(json.dumps(packed(studies),ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\n sourceFiles=[source/n for n in ['actual64-country-four-indicators-original-2024.csv','actual3613-NLS-original52-fields-groups-roles.csv','actual3150-churn-original14-fields-groups-roles.csv']]\n provenance=dict(chapter='ML-14',arithmetic='Python stdlib Fraction exact finite values from original decimal strings; binary64 valueApprox is display only.',inputs=[dict(file=p.name,sha256=hashlib.sha256(p.read_bytes()).hexdigest())for p in sourceFiles],priorEngineModelsScoresOrComputedFilesRead=False,roleRule=\"SHA256('ML14-role|'+kind+'|'+ID),rankmod5=0test/1validation/others train before eligibility\",costs='Hypothetical1/1,1/5,5/1; no causal intervention returns',files=files,observations={k:dict(sourceRows=v['rows'],eligibleRows=v['eligibleRows'],trainingRows=len(v['trainingIDs']))for k,v in studies.items()})\n (out/'provenance.json').write_text(json.dumps(provenance,ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\n print(json.dumps(dict(status='PASS standalone completed',files=len(files),bodyFields=sum(f['bodyFields']for f in files),observations=provenance['observations'])))\n\n# Fixed declared examples: full web budget/option validation is not reproduced.\nfrom html import escape\nimport textwrap\ndef validated_rows(raw):\n for r in raw:\n  assert F(str(r.get('weight','1')))>=0,'negative analytical mass'\n  assert r['score']is None or 0<=F(str(r['score']))<=1,'score outside zero/one'\n  assert r['y']is None or F(str(int(r['y']))if isinstance(r['y'],bool)else str(r['y']))in [0,1],'binary target required'\n return read(raw)\ndef serial(v):\n if isinstance(v,F):return dict(exactFraction=str(v),value=float(v))\n if isinstance(v,(list,tuple)):return[serial(x)for x in v]\n if isinstance(v,dict):return{k:serial(x)for k,x in v.items()}\n return v\ndef fixed_svg(path,points,title,xlabel,ylabel,legend):\n use=[p for p in points if p['xExact']!=''and p['yExact']!=''];xs=[float(F(p['xExact']))for p in use];ys=[float(F(p['yExact']))for p in use]\n xmin=min(xs,default=0);xmax=max(xs,default=1);ymin=min([0]+ys);ymax=max([0]+ys)\n if xmin==xmax:xmin-=.5;xmax+=.5\n if ymin==ymax:ymax=ymin+1\n X=lambda v:85+(float(v)-xmin)/(xmax-xmin)*480;Y=lambda v:278-(float(v)-ymin)/(ymax-ymin)*175\n s='<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"620\" height=\"360\" viewBox=\"0 0 620 360\"><rect width=\"620\" height=\"360\" fill=\"white\"/><g font-family=\"Arial, sans-serif\" font-size=\"13\" fill=\"#17324d\">'\n for i,line in enumerate(textwrap.wrap(title,width=65)):s+='<text x=\"25\" y=\"'+str(24+i*18)+'\">'+escape(line)+'</text>'\n colors=['#176b9b','#b85e18','#437e4d']\n for i,label in enumerate(legend):s+='<circle cx=\"'+str(30+i*250)+'\" cy=\"76\" r=\"4\" fill=\"'+colors[i%3]+'\"/><text x=\"'+str(42+i*250)+'\" y=\"80\">'+escape(label)+'</text>'\n s+='<path d=\"M85 98V278H575\" fill=\"none\" stroke=\"#52677d\"/><text text-anchor=\"middle\" x=\"325\" y=\"338\">'+escape(xlabel)+'</text><text text-anchor=\"middle\" transform=\"translate(21,190) rotate(-90)\">'+escape(ylabel)+'</text>'\n for i in range(5):\n  xx=xmin+(xmax-xmin)*i/4;yy=ymin+(ymax-ymin)*i/4;s+='<text text-anchor=\"middle\" x=\"'+format(X(xx),'.9g')+'\" y=\"305\">'+format(xx,'.4g')+'</text><text text-anchor=\"end\" x=\"77\" y=\"'+format(Y(yy)+4,'.9g')+'\">'+format(yy,'.4g')+'</text>'\n for p in use:s+='<circle cx=\"'+format(X(F(p['xExact'])),'.9g')+'\" cy=\"'+format(Y(F(p['yExact'])),'.9g')+'\" r=\"3\" fill=\"'+colors[p['series']%3]+'\"/>'\n path.write_text(s+'</g></svg>',encoding='utf8')\ndef fixed_run():\n ap=argparse.ArgumentParser();ap.add_argument('--out',type=Path,default=Path('results'));ap.add_argument('--data-dir',type=Path,default=Path(__file__).resolve().parent.parent/'ml14-sources');args=ap.parse_args();args.out.mkdir(parents=True,exist_ok=True)\n api=FIXED['api'];a=FIXED['args'];summary=[];points=[];xlabel='Declared index';ylabel='Value';legend=['Declared result']\n def metric(name,v,unit='dimensionless'):\n  q=None if v is None else v if isinstance(v,F)else F(v);summary.append(dict(metric=name,value='undefined'if q is None else format(float(q),'.9g'),exactValue=''if q is None else str(q),unit=unit,defined=int(q is not None)))\n def pt(i,x,y,ident='',series=0):\n  points.append(dict(series=series,index=i,xExact=''if x is None else str(F(x)),x='undefined'if x is None else format(float(x),'.9g'),yExact=''if y is None else str(F(y)),y='undefined'if y is None else format(float(y),'.9g'),id=str(ident)))\n if api=='realdata':\n  models=load_sources(args.data_dir);model=models[a['kind']];fit=actual_model(model);rr=fit['rows'];test=scoped(rr,'test');scenarios=[]\n  for name,fp,fn in SCENARIOS:\n   c=choose(rr,{},(fp,fn));scenarios.append(dict(name=name,selection=c));metric(name+'Threshold',c['selectedPolicy']);metric(name+'TestCost',c['evaluation']['meanCost'],'hypothetical cost units/mass')\n  cv=curves(test);cal=calibrate(test,[F(0),F(1,5),F(2,5),F(3,5),F(4,5),F(1)]);metric('testAUC',cv['ROC_AUC']);metric('testAP',cv['averagePrecision']);metric('testBrier',cal['Brier']);metric('eligibleRows',sum(r['eligible']for r in rr),'rows')\n  for i,r in enumerate(test):pt(i,i+1,r['score'],r['id'],0);pt(i,i+1,r['y'],r['id'],1)\n  full=dict(kind=a['kind'],fitMedians=fit['medians'],fitCells=[dict(cell=list(k),mass=n,positive=s,probability=fit['probabilities'][k])for k,(n,s)in fit['cells'].items()],rowsScored=rr,scenarios=scenarios,testCurves=cv,testCalibration=cal);xlabel='Test row, native order';ylabel='Y or probability';legend=['Training-fitted probability','Observed Y']\n else:\n  rr=validated_rows(a['rows']);role=a.get('role','all');frame=scoped(rr,role);cc=cost(a.get('costs'));t=policy(a.get('threshold','1/2'))\n  if api=='metrics':\n   full=metrics(frame,t,cc)\n   for k in ['mass','accuracy','precision','TPR','FPR','F1','Brier','meanCost']:metric(k,full[k],'mass'if k=='mass'else'hypothetical cost units/mass'if k=='meanCost'else'dimensionless')\n   metric('BayesThreshold',full['bayesThreshold'])\n   for i,k in enumerate(['TP','FP','FN','TN']):pt(i,i,full['confusion'][k],k)\n   xlabel='TP / FP / FN / TN positions';ylabel='Analytical mass'\n  elif api=='curves':\n   full=curves(frame)\n   for k in ['ROC_AUC','averagePrecision','PRTrapezoidWithInitialPrecisionOne']:metric(k,full[k])\n   for i,p in enumerate(full['points']):pt(i,p['FPR'],p['TPR'],str(p['policy']))\n   xlabel='False positive rate';ylabel='True positive rate';legend=['Observed ROC operating points']\n  elif api=='choose':\n   full=choose(rr,a,cc);metric('selectedIndex',full['selectedIndex'],'candidate index');metric('minimumCost',None if full['selectedValidation']is None else full['selectedValidation']['meanCost'],'hypothetical cost units/mass');metric('feasible',int(full['selectedIndex']is not None),'indicator')\n   for c in full['candidates']:pt(c['index'],c['index'],c['metrics']['meanCost'],str(c['policy']))\n   xlabel='Validation candidate';ylabel='Assumed cost / mass';legend=['Validation candidate costs']\n  elif api=='calibrate':\n   full=calibrate(frame,[F(str(e))for e in a.get('binEdges',['0','1/5','2/5','3/5','4/5','1'])])\n   for k in ['ECE','Brier','uncertainty','resolution','reliability','withinBinCorrection','BrierIdentityResidual']:metric(k,full[k])\n   for b in full['bins']:pt(b['index'],b['meanPrediction'],b['eventRate'],'bin:'+str(b['index']))\n   xlabel='Bin mean forecast';ylabel='Bin event rate';legend=['Binary-event reliability']\n  elif api=='groups':\n   full=groups(frame,t,cc);metric('overallTPR',full['overall']['TPR']);metric('TPRGap',full['gaps']['TPR']['value']);metric('precisionGap',full['gaps']['precision']['value']);metric('unknownMass',full['unknownGroup']['mass'],'mass');metric('partitionResidual',full['partitionMassResidual'],'mass')\n   for i,g in enumerate(full['groups']):pt(i,i,g['metrics']['TPR'],str(g['group']))\n   xlabel='Declared group position';ylabel='True positive rate';legend=['Known-group TPR']\n  else:raise ValueError('unknown fixed API')\n def csvout(name,rows):\n  with(args.out/name).open('w',encoding='utf8',newline='')as f:w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows)\n csvout('summary.csv',summary);csvout('plot-points.csv',points);fixed_svg(args.out/'plot.svg',points,FIXED['title'],xlabel,ylabel,legend)\n (args.out/'full.json').write_text(json.dumps(dict(api=api,variant=FIXED['variant'],input=FIXED['args'],arithmetic='Python standard-library Fraction, declared fixed example; full web validator/budgets not reproduced',result=serial(full)),ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\n print(json.dumps(dict(api=api,variant=FIXED['variant'],summaryMetrics=len(summary),plotSlots=len(points))))\n\nFIXED={'api': 'groups', 'variant': 'unknown-group', 'args': {'rows': [{'id': 'a', 'score': '.9', 'y': 1, 'group': 'A'}, {'id': 'b', 'score': '.8', 'y': 1, 'group': 'A'}, {'id': 'c', 'score': '.8', 'y': 0, 'group': 'A'}, {'id': 'd', 'score': '.6', 'y': 0, 'group': 'B'}, {'id': 'e', 'score': '.4', 'y': 1, 'group': 'B'}, {'id': 'f', 'score': '.1', 'y': 0, 'group': None}], 'threshold': '.4'}, 'title': 'Unknown group stays overall and preserves mass'}\nif __name__=='__main__':fixed_run()\n",
        "input": {
          "rows": [
            {
              "id": "a",
              "score": ".9",
              "y": 1,
              "group": "A"
            },
            {
              "id": "b",
              "score": ".8",
              "y": 1,
              "group": "A"
            },
            {
              "id": "c",
              "score": ".8",
              "y": 0,
              "group": "A"
            },
            {
              "id": "d",
              "score": ".6",
              "y": 0,
              "group": "B"
            },
            {
              "id": "e",
              "score": ".4",
              "y": 1,
              "group": "B"
            },
            {
              "id": "f",
              "score": ".1",
              "y": 0,
              "group": null
            }
          ],
          "threshold": ".4"
        },
        "inputFiles": [],
        "returnCode": 0,
        "expectedFailure": false,
        "stdout": "{\"api\": \"groups\", \"variant\": \"unknown-group\", \"summaryMetrics\": 5, \"plotSlots\": 2}\n",
        "stderr": "",
        "summary": {
          "overallTPR": "1",
          "TPRGap": "0",
          "precisionGap": "0.166666667",
          "unknownMass": "1",
          "partitionResidual": "0"
        },
        "summaryRows": [
          {
            "metric": "overallTPR",
            "value": "1",
            "exactValue": "1",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "TPRGap",
            "value": "0",
            "exactValue": "0",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "precisionGap",
            "value": "0.166666667",
            "exactValue": "1/6",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "unknownMass",
            "value": "1",
            "exactValue": "1",
            "unit": "mass",
            "defined": "1"
          },
          {
            "metric": "partitionResidual",
            "value": "0",
            "exactValue": "0",
            "unit": "mass",
            "defined": "1"
          }
        ],
        "plotPoints": [
          {
            "series": "0",
            "index": "0",
            "xExact": "0",
            "x": "0",
            "yExact": "1",
            "y": "1",
            "id": "A"
          },
          {
            "series": "0",
            "index": "1",
            "xExact": "1",
            "x": "1",
            "yExact": "1",
            "y": "1",
            "id": "B"
          }
        ],
        "plotFile": "ml14-fixed-results/groups-unknown-group-python/plot.svg",
        "plotSHA256": "a453d98e20c8cf03669302132e47dd14710f7c7bdf9f2e216eee63f988accb86",
        "files": [
          {
            "file": "ml14-fixed-results/groups-unknown-group-python/full.json",
            "sha256": "de5e516383020943784283c92aeee228eca974c990facc4e33656545df30cc4a",
            "bytes": 16713
          },
          {
            "file": "ml14-fixed-results/groups-unknown-group-python/plot-points.csv",
            "sha256": "ab3196fe6bd76d370462c9f5ba1db767f61aedd2b18050c671f2429a42a583c0",
            "bytes": 65
          },
          {
            "file": "ml14-fixed-results/groups-unknown-group-python/plot.svg",
            "sha256": "a453d98e20c8cf03669302132e47dd14710f7c7bdf9f2e216eee63f988accb86",
            "bytes": 1198
          },
          {
            "file": "ml14-fixed-results/groups-unknown-group-python/summary.csv",
            "sha256": "851095476caab7b6f2b07bc28fff8306e0735b868f75777dc7140f2f4d883385",
            "bytes": 198
          }
        ],
        "scope": "Actually executed standalone fixed example, Python exact Fraction versus base-R binary64. Approximate R residuals retained; not universal exact arithmetic/web validation/native UI. Source programs read factual3CSV only."
      }
    },
    "r": {
      "six-cards": {
        "api": "groups",
        "variant": "six-cards",
        "language": "r",
        "title": "Group TPR gaps and undefined precision comparison",
        "codeFile": "ml14-code/groups-six-cards.R",
        "codeSHA256": "7ac3ed483c469600a682c6b7afd2172cce45b009ca08b90969421f8e7f18be8b",
        "code": "# ML14 standalone public counterpart, base R only.\n# Inputs are only the three factual CSVs; derived columns/previous model answers unused.\n# Binary64 arithmetic, not arbitrary-precision Fraction. At numerical cost ties\n# within 1e-12 retain the earliest candidate. Exact claims belong to Python/web.\n# SHA256 infrastructure below is reused verbatim from the previous public study.\nargs<-commandArgs(trailingOnly=TRUE);filearg<-grep(\"^--file=\",commandArgs(),value=TRUE)\nhere<-if(dir.exists(\"ml14-sources\"))getwd()else if(length(filearg))dirname(normalizePath(sub(\"^--file=\",\"\",filearg[1])))else getwd()\noption<-function(key,default){i<-match(key,args);if(is.na(i))default else args[i+1]}\nsourceDir<-option(\"--source\",file.path(here,\"ml14-sources\"));outDir<-option(\"--out\",file.path(getwd(),\"ml14-r-results\"));dir.create(outDir,recursive=TRUE,showWarnings=FALSE)\nnum<-function(x){x[x%in%c(\"\",\".\")]<-NA_character_;as.numeric(x)}\nfmt<-function(x)ifelse(is.na(x),\"\",sprintf(\"%.17g\",x))\nratio<-function(a,b)if(b==0)NA_real_ else a/b\nreadnative<-function(name)read.csv(file.path(sourceDir,name),check.names=FALSE,colClasses=\"character\",na.strings=character(),stringsAsFactors=FALSE)\n# Vectorized SHA256 for the short ASCII keys used in this study.\n# Unsigned words use exact integer-valued doubles; bit operations use safe\n# 16-bit halves, avoiding R's reserved signed-INT_MIN/NA representation.\nMOD<-2^32\nxor32<-function(a,b) as.double(bitwXor(as.integer(floor(a/65536)),as.integer(floor(b/65536))))*65536+as.double(bitwXor(as.integer(a%%65536),as.integer(b%%65536)))\nand32<-function(a,b) as.double(bitwAnd(as.integer(floor(a/65536)),as.integer(floor(b/65536))))*65536+as.double(bitwAnd(as.integer(a%%65536),as.integer(b%%65536)))\nrot<-function(x,n) floor(x/2^n)+(x%%2^n)*2^(32-n)\nxor3<-function(a,b,c) xor32(xor32(a,b),c)\nK<-c(0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5,0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967,0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070,0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3,0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2)\nsha256<-function(strings) {\n n<-length(strings);bytes<-matrix(0,n,64)\n for(i in seq_len(n)) {v<-utf8ToInt(strings[i]);stopifnot(length(v)<56,all(v<128));if(length(v)) bytes[i,seq_along(v)]<-v;bytes[i,length(v)+1]<-128;bits<-length(v)*8;bytes[i,61:64]<-c(floor(bits/2^24)%%256,floor(bits/2^16)%%256,floor(bits/256)%%256,bits%%256)}\n w<-matrix(0,n,64)\n for(j in 1:16) {b<-4*(j-1)+1;w[,j]<-bytes[,b]*2^24+bytes[,b+1]*2^16+bytes[,b+2]*256+bytes[,b+3]}\n for(j in 17:64) {s0<-xor3(rot(w[,j-15],7),rot(w[,j-15],18),floor(w[,j-15]/8));s1<-xor3(rot(w[,j-2],17),rot(w[,j-2],19),floor(w[,j-2]/1024));w[,j]<-(w[,j-16]+s0+w[,j-7]+s1)%%MOD}\n init<-c(0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19)\n state<-lapply(init,function(v) rep(v,n));a<-state[[1]];b<-state[[2]];c<-state[[3]];d<-state[[4]];e<-state[[5]];f<-state[[6]];g<-state[[7]];h<-state[[8]]\n for(j in 1:64) {S1<-xor3(rot(e,6),rot(e,11),rot(e,25));ch<-xor32(and32(e,f),and32(MOD-1-e,g));t1<-(h+S1+ch+K[j]+w[,j])%%MOD;S0<-xor3(rot(a,2),rot(a,13),rot(a,22));maj<-xor3(and32(a,b),and32(a,c),and32(b,c));t2<-(S0+maj)%%MOD;h<-g;g<-f;f<-e;e<-(d+t1)%%MOD;d<-c;c<-b;b<-a;a<-(t1+t2)%%MOD}\n end<-list(a,b,c,d,e,f,g,h);hex<-lapply(1:8,function(j){v<-(end[[j]]+init[j])%%MOD;paste0(sprintf(\"%04x\",as.integer(floor(v/65536))),sprintf(\"%04x\",as.integer(v%%65536)))})\n do.call(paste0,hex)\n}\nstopifnot(identical(sha256(c(\"abc\",\"\")),c(\"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad\",\"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855\")))\n\nloadData<-function(){\n wb<-readnative(\"actual64-country-four-indicators-original-2024.csv\");codes<-c(\"NY.GDP.PCAP.KD\",\"NY.GDP.MKTP.KD.ZG\",\"FP.CPI.TOTL.ZG\",\"SP.DYN.LE00.IN\");iso<-sort(unique(wb$countryISO3));stopifnot(nrow(wb)==64,length(iso)==16)\n tokens<-t(vapply(iso,function(s)wb$originalValueToken[match(paste(s,codes),paste(wb$countryISO3,wb$indicatorID))],character(4)));vals<-matrix(num(as.vector(tokens)),nrow=nrow(tokens))\n country<-list(id=paste0(iso,\":2024\"),sourceRow=1:16,originalID=iso,x=vals[,1:3,drop=FALSE],rawX=tokens[,1:3,drop=FALSE],nativeTarget=tokens[,4],y=as.integer(vals[,4]>=80),group=ifelse(is.na(vals[,1]),NA_character_,as.character(as.integer(vals[,1]>=25000))),lineage=vapply(iso,function(s)paste(wb$sourceRow[match(paste(s,codes),paste(wb$countryISO3,wb$indicatorID))],collapse=\";\"),character(1)),cat=integer(),units=c(\"constant2015USD/person\",\"annualPercent\",\"annualPercent\"))\n nls<-readnative(\"actual3613-NLS-original52-fields-groups-roles.csv\");raw<-cbind(nls$ed76,nls$age76,nls$nearc4)\n person<-list(id=paste0(\"person:\",nls$sourceRow),sourceRow=as.integer(nls$sourceRow),originalID=nls$id,x=matrix(num(as.vector(raw)),nrow=nrow(raw)),rawX=raw,nativeTarget=nls$wage76,y=as.integer(num(nls$wage76)>=500),group=ifelse(nls$black%in%c(\"\",\".\"),NA_character_,nls$black),lineage=nls$sourceRow,cat=2L,units=c(\"years\",\"years\",\"nativeCategory\"))\n ch<-readnative(\"actual3150-churn-original14-fields-groups-roles.csv\");raw<-cbind(ch[[\"Call  Failure\"]],ch$Complains,ch[[\"Subscription  Length\"]],ch[[\"Seconds of Use\"]])\n company<-list(id=paste0(\"customer:\",ch$sourceRow),sourceRow=as.integer(ch$sourceRow),originalID=rep(\"\",nrow(ch)),x=matrix(num(as.vector(raw)),nrow=nrow(raw)),rawX=raw,nativeTarget=ch$Churn,y=as.integer(ch$Churn),group=ifelse(ch[[\"Tariff Plan\"]]%in%c(\"\",\".\"),NA_character_,ch[[\"Tariff Plan\"]]),lineage=ch$sourceRow,cat=1L,units=c(\"count\",\"nativeCategory\",\"months\",\"seconds\"))\n stopifnot(nrow(nls)==3613,nrow(ch)==3150,identical(as.integer(ch$sourceRow[ch[[\"Charge  Amount\"]]==\"10\"]),c(474L,2174L,2274L,2374L,2674L,2924L,2974L)))\n result<-list(country=country,person=person,company=company)\n for(k in names(result)){d<-result[[k]];n<-length(d$id);d$eligible<-!is.na(d$y)&rowSums(is.na(d$x))==0;hash<-sha256(paste0(\"ML14-role|\",k,\"|\",d$id));rank<-integer(n);rank[order(hash,seq_len(n))]<-seq_len(n)-1L;d$plannedRole<-ifelse(rank%%5==0,\"test\",ifelse(rank%%5==1,\"validation\",\"train\"));d$role<-ifelse(d$eligible,d$plannedRole,\"excluded\");result[[k]]<-d}\n stopifnot(sum(result$person$eligible)==3017);result\n}\nfitmodel<-function(d){\n ids<-which(d$role==\"train\");p<-ncol(d$x);m<-vapply(seq_len(p),function(j)if((j-1)%in%d$cat)NA_real_ else median(d$x[ids,j]),numeric(1));z<-d$x\n for(j in seq_len(p))if(!((j-1)%in%d$cat))z[,j]<-as.numeric(z[,j]>m[j])\n keys<-apply(z,1,function(v)paste(fmt(v),collapse=\"|\"));lev<-unique(keys[ids]);mass<-vapply(lev,function(k)sum(keys[ids]==k),integer(1));positive<-vapply(lev,function(k)sum(d$y[ids][keys[ids]==k]),integer(1));prob<-(positive+1)/(mass+2);fallback<-(sum(d$y[ids])+1)/(length(ids)+2);pred<-prob[match(keys,lev)];unseen<-is.na(pred);pred[unseen]<-fallback;pred[!d$eligible]<-NA_real_;unseen[!d$eligible]<-NA\n list(ids=ids,medians=m,z=z,keys=keys,lev=lev,mass=mass,positive=positive,prob=prob,fallback=fallback,pred=pred,unseen=unseen)\n}\nmeasure<-function(d,p,ids,t=.5,cost=c(1,1)){\n use<-ids[d$eligible[ids]&!is.na(p[ids])];y<-d$y[use];a<-if(is.character(t))rep(t==\"always-positive\",length(use))else p[use]>=t\n TP<-sum(a&y==1);FP<-sum(a&y==0);FN<-sum(!a&y==1);TN<-sum(!a&y==0);P<-TP+FN;N<-FP+TN;W<-P+N;PP<-TP+FP;PN<-TN+FN;TPR<-ratio(TP,P);TNR<-ratio(TN,N);bs<-sum((p[use]-y)^2);tc<-FP*cost[1]+FN*cost[2]\n list(TP=TP,FP=FP,FN=FN,TN=TN,mass=W,positiveTargetMass=P,negativeTargetMass=N,predictedPositiveMass=PP,predictedNegativeMass=PN,prevalence=ratio(P,W),selectionRate=ratio(PP,W),accuracy=ratio(TP+TN,W),precision=ratio(TP,PP),negativePredictiveValue=ratio(TN,PN),TPR=TPR,FPR=ratio(FP,N),TNR=TNR,FNR=ratio(FN,P),F1=ratio(2*TP,2*TP+FP+FN),balancedAccuracy=if(is.na(TPR)||is.na(TNR))NA_real_ else(TPR+TNR)/2,Brier=ratio(bs,W),BrierSum=bs,totalCost=tc,meanCost=ratio(tc,W))\n}\ncurves<-function(d,p,ids){\n use<-ids[d$eligible[ids]&!is.na(p[ids])];scores<-sort(unique(p[use]),decreasing=TRUE);policies<-c(list(\"always-negative\"),as.list(scores));points<-lapply(policies,function(t){m<-measure(d,p,ids,t);c(list(policy=t),m[c(\"TP\",\"FP\",\"FN\",\"TN\",\"TPR\",\"FPR\",\"precision\")],list(recall=m$TPR))})\n pos<-use[d$y[use]==1];neg<-use[d$y[use]==0];U<-0;for(i in pos)U<-U+sum(p[i]>p[neg])+.5*sum(p[i]==p[neg])\n AP<-0;trap<-0;lastR<-0;lastP<-1\n if(length(pos)&&length(scores))for(j in seq_along(scores)){z<-points[[j+1]];AP<-AP+(z$recall-lastR)*z$precision;trap<-trap+(z$recall-lastR)*(z$precision+lastP)/2;lastR<-z$recall;lastP<-z$precision}\n list(points=points,ROC_AUC=ratio(U,length(pos)*length(neg)),averagePrecision=if(length(pos))AP else NA_real_,PRTrapezoidWithInitialPrecisionOne=if(length(pos))trap else NA_real_)\n}\ncalibrate<-function(d,p,ids){\n use<-ids[d$eligible[ids]&!is.na(p[ids])];W<-length(use);pi<-if(W)mean(d$y[use])else NA_real_;bins<-list();ECE<-rel<-res<-correction<-0\n whichbin<-findInterval(p[use],seq(0,1,.2),rightmost.closed=TRUE,all.inside=TRUE)\n for(b in 1:5){rr<-use[whichbin==b];w<-length(rr);mp<-if(w)mean(p[rr])else NA_real_;o<-if(w)mean(d$y[rr])else NA_real_;variance<-if(w)mean((p[rr]-mp)^2)else NA_real_;covariance<-if(w)mean((p[rr]-mp)*(d$y[rr]-o))else NA_real_;bc<-variance-2*covariance;gap<-mp-o\n  bins[[b]]<-list(mass=w,meanPrediction=mp,eventRate=o,gap=gap,absoluteGap=abs(gap),scoreVariance=variance,scoreTargetCovariance=covariance,withinBinCorrection=bc,rows=w,ids=d$id[rr])\n  if(w){share<-w/W;ECE<-ECE+share*abs(gap);rel<-rel+share*gap^2;res<-res+share*(o-pi)^2;correction<-correction+share*bc}\n };bs<-if(W)mean((p[use]-d$y[use])^2)else NA_real_;unc<-pi*(1-pi)\n list(bins=bins,ECE=if(W)ECE else NA_real_,Brier=bs,reliability=if(W)rel else NA_real_,resolution=if(W)res else NA_real_,uncertainty=unc,withinBinCorrection=if(W)correction else NA_real_,BrierIdentityResidual=bs-(unc-res+rel+correction))\n}\ncounts<-c(\"mass\",\"positiveTargetMass\",\"negativeTargetMass\",\"predictedPositiveMass\",\"predictedNegativeMass\");rates<-c(\"prevalence\",\"selectionRate\",\"accuracy\",\"precision\",\"negativePredictiveValue\",\"TPR\",\"FPR\",\"TNR\",\"FNR\",\"F1\",\"balancedAccuracy\",\"Brier\",\"BrierSum\",\"totalCost\",\"meanCost\")\ntables<-setNames(lapply(1:10,function(i)list()),c(\"predictions\",\"lineage\",\"fit-medians\",\"fit-cells\",\"validation-candidates\",\"test-metrics\",\"test-curves\",\"calibration-bins\",\"group-metrics\",\"chart-points\"))\nadd<-function(name,row)tables[[name]][[length(tables[[name]])+1L]]<<-row\nscalars<-function(m,keys){out<-list();for(k in keys){out[[paste0(k,\"Exact\")]]<-\"\";out[[paste0(k,\"Approx\")]]<-fmt(m[[k]])};out}\ntagrow<-function(kind,...)c(list(kind=kind),list(...))\npoint<-function(kind,chart,series,index,x,y,xunit=\"dimensionless\",yunit=\"dimensionless\",role=\"test\",tag=\"\"){add(\"chart-points\",tagrow(kind,chart=chart,series=series,index=index,xExact=\"\",xApprox=fmt(x),yExact=\"\",yApprox=fmt(y),xUnit=xunit,yUnit=yunit,role=role,tag=tag))}\nstudy<-function(kind,d){\n f<-fitmodel(d);n<-length(d$id);train<-which(d$role==\"train\");validation<-which(d$role==\"validation\");test<-which(d$role==\"test\");p<-f$pred;cv<-curves(d,p,test);cal<-calibrate(d,p,test)\n for(i in seq_len(n)){\n  reason<-if(d$eligible[i])\"\"else\"required-X-or-Y-missing\";transformed<-if(d$eligible[i])paste(fmt(f$z[i,]),collapse=\"|\")else\"\"\n  add(\"predictions\",tagrow(kind,id=d$id[i],sourceRow=d$sourceRow[i],originalID=d$originalID[i],plannedRole=d$plannedRole[i],role=d$role[i],group=ifelse(is.na(d$group[i]),\"\",d$group[i]),eligible=as.integer(d$eligible[i]),targetExact=fmt(d$y[i]),probabilityExact=\"\",probabilityApprox=fmt(p[i]),unseenCell=ifelse(is.na(f$unseen[i]),\"\",as.character(as.integer(f$unseen[i]))),transformedX=transformed,reason=reason))\n  raw<-d$rawX[i,];raw[raw%in%c(\"\",\".\")]<-\"\";nativeY<-d$nativeTarget[i];if(nativeY%in%c(\"\",\".\"))nativeY<-\"\"\n  add(\"lineage\",tagrow(kind,id=d$id[i],sourceRow=d$sourceRow[i],originalID=d$originalID[i],nativeSourceRows=d$lineage[i],rawX=paste(raw,collapse=\"|\"),nativeTarget=nativeY,derivedTarget=fmt(d$y[i]),nativeGroup=ifelse(is.na(d$group[i]),\"\",d$group[i]),plannedRole=d$plannedRole[i],role=d$role[i],eligible=as.integer(d$eligible[i]),analyticalMass=\"1\",reason=reason))\n }\n for(j in seq_len(ncol(d$x)))add(\"fit-medians\",tagrow(kind,feature=j-1,categorical=as.integer((j-1)%in%d$cat),fitRows=length(train),medianExact=\"\",medianApprox=fmt(f$medians[j]),unit=d$units[j]))\n for(j in seq_along(f$lev))add(\"fit-cells\",tagrow(kind,cell=f$lev[j],trainingRows=f$mass[j],positiveRows=f$positive[j],probabilityExact=\"\",probabilityApprox=fmt(f$prob[j]),fallbackExact=\"\",fallbackApprox=fmt(f$fallback)))\n for(j in seq_along(cv$points)){\n  z<-cv$points[[j]];t<-z$policy;add(\"test-curves\",c(tagrow(kind,point=j-1,policy=if(is.character(t))t else\"threshold\",thresholdExact=\"\",thresholdApprox=if(is.character(t))\"\"else fmt(t)),scalars(z,c(\"TP\",\"FP\",\"FN\",\"TN\",\"TPR\",\"FPR\",\"precision\",\"recall\"))))\n  point(kind,\"roc\",\"ROC\",j-1,z$FPR,z$TPR);point(kind,\"pr\",\"PR-observed\",j-1,z$recall,z$precision)\n }\n for(b in 1:5){z<-cal$bins[[b]];add(\"calibration-bins\",c(tagrow(kind,bin=b-1,leftExact=c(\"0\",\"1/5\",\"2/5\",\"3/5\",\"4/5\")[b],rightExact=c(\"1/5\",\"2/5\",\"3/5\",\"4/5\",\"1\")[b],rightClosed=as.integer(b==5),rows=z$rows,ids=paste(z$ids,collapse=\";\")),scalars(z,c(\"mass\",\"meanPrediction\",\"eventRate\",\"gap\",\"absoluteGap\",\"scoreVariance\",\"scoreTargetCovariance\",\"withinBinCorrection\"))));point(kind,\"reliability\",\"Binary event rate\",b-1,z$meanPrediction,z$eventRate,tag=paste0(\"rows=\",z$rows))}\n for(j in seq_along(test)){i<-test[j];point(kind,\"test-scores\",\"Training-fitted probability\",j-1,j,p[i],\"test-row position\",\"probability\",tag=d$id[i]);point(kind,\"test-scores\",\"Observed Y\",j-1,j,d$y[i],\"test-row position\",\"binary target\",tag=d$id[i])}\n scenarioNames<-c(\"equal\",\"miss-five\",\"alarm-five\");costs<-list(c(1,1),c(1,5),c(5,1))\n for(s in 1:3){name<-scenarioNames[s];cost<-costs[[s]];grid<-c(list(\"always-negative\"),as.list(sort(unique(p[validation]),decreasing=TRUE)));candidates<-lapply(grid,function(t)measure(d,p,validation,t,cost));values<-vapply(candidates,function(m)m$meanCost,numeric(1));best<-which(values<=min(values)+1e-12)[1];chosen<-grid[[best]];ev<-measure(d,p,test,chosen,cost)\n  for(j in seq_along(grid)){t<-grid[[j]];m<-candidates[[j]];cell<-setNames(lapply(c(\"TP\",\"FP\",\"FN\",\"TN\"),function(k)fmt(m[[k]])),paste0(c(\"TP\",\"FP\",\"FN\",\"TN\"),\"Exact\"));add(\"validation-candidates\",c(tagrow(kind,scenario=name,candidate=j-1,selected=as.integer(j==best),policy=if(is.character(t))t else\"threshold\",thresholdExact=\"\",thresholdApprox=if(is.character(t))\"\"else fmt(t),feasible=1,reasons=\"\"),cell,scalars(m,c(counts,\"TPR\",\"FPR\",\"precision\",\"meanCost\",\"totalCost\"))));point(kind,\"validation-cost\",name,j-1,j-1,m$meanCost,\"candidate index\",\"hypothetical cost units/mass\",\"validation\",if(is.character(t))t else fmt(t))}\n  m<-c(ev,cv[c(\"ROC_AUC\",\"averagePrecision\",\"PRTrapezoidWithInitialPrecisionOne\")],cal[c(\"ECE\",\"reliability\",\"resolution\",\"uncertainty\",\"withinBinCorrection\",\"BrierIdentityResidual\")])\n  for(k in c(\"TP\",\"FP\",\"FN\",\"TN\",counts,rates,\"ROC_AUC\",\"averagePrecision\",\"PRTrapezoidWithInitialPrecisionOne\",\"ECE\",\"reliability\",\"resolution\",\"uncertainty\",\"withinBinCorrection\",\"BrierIdentityResidual\")){\n   unit<-if(k%in%c(\"TP\",\"FP\",\"FN\",\"TN\",counts))\"rows\"else if(k==\"totalCost\")\"hypothetical cost units\"else if(k==\"meanCost\")\"hypothetical cost units/mass\"else if(k==\"BrierSum\")\"sum squared-probability loss\"else\"dimensionless\"\n   add(\"test-metrics\",tagrow(kind,scenario=name,metric=k,valueExact=\"\",valueApprox=fmt(m[[k]]),unit=unit))\n  }\n  lev<-unique(d$group[test][!is.na(d$group[test])]);sets<-c(list(test),lapply(lev,function(g)test[!is.na(d$group[test])&d$group[test]==g]),list(test[is.na(d$group[test])]))\n  types<-c(\"overall\",rep(\"known\",length(lev)),\"unknown\");tokens<-c(\"all\",lev,\"\")\n  for(j in seq_along(sets)){ids<-sets[[j]];m<-measure(d,p,ids,chosen,cost);cell<-setNames(lapply(c(\"TP\",\"FP\",\"FN\",\"TN\"),function(k)fmt(m[[k]])),paste0(c(\"TP\",\"FP\",\"FN\",\"TN\"),\"Exact\"));add(\"group-metrics\",c(tagrow(kind,scenario=name,groupType=types[j],groupToken=tokens[j],retainedRows=length(ids)),cell,scalars(m,c(counts,rates))));if(types[j]==\"known\")point(kind,\"group-TPR\",name,j-2,j-2,m$TPR,\"declared group position\",\"TPR\",tag=tokens[j])}\n }\n invisible(NULL)\n}\n\n# Fixed finite inputs only; not the complete web input/budget validator.\nqnum<-function(v){if(is.null(v))return(NA_real_);if(is.logical(v))return(as.numeric(v));s<-as.character(v);if(grepl(\"/\",s,fixed=TRUE)){a<-strsplit(s,\"/\",fixed=TRUE)[[1]];return(as.numeric(a[1])/as.numeric(a[2]))};as.numeric(s)}\nrowsG<-function(raw){\n n<-length(raw);get<-function(r,k,default=NULL)if(is.null(r[[k]]))default else r[[k]]\n id<-vapply(raw,function(r)as.character(r$id),character(1));p<-vapply(raw,function(r)qnum(r$score),numeric(1));y<-vapply(raw,function(r)qnum(r$y),numeric(1));w<-vapply(raw,function(r)qnum(get(r,\"weight\",\"1\")),numeric(1));role<-vapply(raw,function(r)get(r,\"role\",\"evaluation\"),character(1));group<-vapply(raw,function(r)as.character(get(r,\"group\",NA_character_)),character(1))\n stopifnot(all(w>=0),all(is.na(p)|(p>=0&p<=1)),all(is.na(y)|y%in%c(0,1)),!anyDuplicated(id));list(id=id,p=p,y=y,w=w,role=role,group=group,eligible=!is.na(p)&!is.na(y)&w>0&role!=\"excluded\")\n}\nscopeG<-function(d,role=\"all\")if(role==\"all\")seq_along(d$id)else which(d$role==role)\nmetricsG<-function(d,ids,t=.5,cost=c(1,1)){\n use<-ids[d$eligible[ids]];p<-d$p[use];y<-d$y[use];w<-d$w[use];a<-if(is.character(t))rep(t==\"always-positive\",length(use))else p>=t\n TP<-sum(w[a&y==1]);FP<-sum(w[a&y==0]);FN<-sum(w[!a&y==1]);TN<-sum(w[!a&y==0]);P<-TP+FN;N<-FP+TN;W<-P+N;PP<-TP+FP;PN<-TN+FN;TPR<-ratio(TP,P);TNR<-ratio(TN,N);bs<-sum(w*(p-y)^2);tc<-FP*cost[1]+FN*cost[2]\n list(confusion=list(TP=TP,FP=FP,FN=FN,TN=TN),mass=W,positiveTargetMass=P,negativeTargetMass=N,predictedPositiveMass=PP,predictedNegativeMass=PN,prevalence=ratio(P,W),selectionRate=ratio(PP,W),accuracy=ratio(TP+TN,W),precision=ratio(TP,PP),negativePredictiveValue=ratio(TN,PN),TPR=TPR,FPR=ratio(FP,N),TNR=TNR,FNR=ratio(FN,P),F1=ratio(2*TP,2*TP+FP+FN),balancedAccuracy=if(is.na(TPR)||is.na(TNR))NA_real_ else(TPR+TNR)/2,Brier=ratio(bs,W),BrierSum=bs,totalCost=tc,meanCost=ratio(tc,W),bayesThreshold=ratio(cost[1],sum(cost)))\n}\ncurvesG<-function(d,ids){\n use<-ids[d$eligible[ids]];grid<-c(list(\"always-negative\"),as.list(sort(unique(d$p[use]),decreasing=TRUE)));points<-lapply(grid,function(t){m<-metricsG(d,ids,t);c(list(policy=t),m$confusion,m[c(\"TPR\",\"FPR\",\"precision\")],list(recall=m$TPR))});pos<-use[d$y[use]==1];neg<-use[d$y[use]==0];P<-sum(d$w[pos]);N<-sum(d$w[neg]);U<-0\n for(i in pos)U<-U+d$w[i]*sum(d$w[neg]*((d$p[i]>d$p[neg])+.5*(d$p[i]==d$p[neg])))\n AP<-trap<-lastR<-0;lastP<-1\n if(P&&length(grid)>1)for(j in 2:length(grid)){z<-points[[j]];AP<-AP+(z$recall-lastR)*z$precision;trap<-trap+(z$recall-lastR)*(z$precision+lastP)/2;lastR<-z$recall;lastP<-z$precision}\n list(points=points,ROC_AUC=ratio(U,P*N),averagePrecision=if(P)AP else NA_real_,PRTrapezoidWithInitialPrecisionOne=if(P)trap else NA_real_)\n}\nchooseG<-function(d,a,cost){\n role<-if(is.null(a$selectionRole))\"validation\"else a$selectionRole;er<-if(is.null(a$evaluationRole))\"test\"else a$evaluationRole;ids<-scopeG(d,role);use<-ids[d$eligible[ids]];stopifnot(length(use)>0);grid<-if(is.null(a$thresholds))c(list(\"always-negative\"),as.list(sort(unique(d$p[use]),decreasing=TRUE)))else lapply(a$thresholds,function(t)if(t%in%c(\"always-negative\",\"always-positive\"))t else qnum(t))\n candidates<-lapply(seq_along(grid),function(j){m<-metricsG(d,ids,grid[[j]],cost);feasible<-TRUE;if(!is.null(a$minTPR))feasible<-feasible&&!is.na(m$TPR)&&m$TPR>=qnum(a$minTPR);if(!is.null(a$maxFPR))feasible<-feasible&&!is.na(m$FPR)&&m$FPR<=qnum(a$maxFPR);list(index=j-1,policy=grid[[j]],metrics=m,feasible=feasible)})\n good<-which(vapply(candidates,function(c)c$feasible,logical(1)));best<-NA_integer_;if(length(good)){v<-vapply(candidates[good],function(c)c$metrics$meanCost,numeric(1));best<-good[which(v<=min(v)+1e-12)[1]]}\n list(selectedIndex=if(is.na(best))NA_integer_ else best-1,selectedPolicy=if(is.na(best))NULL else grid[[best]],selectedValidation=if(is.na(best))NULL else candidates[[best]]$metrics,candidates=candidates,evaluation=if(is.na(best)||er==\"none\")NULL else metricsG(d,scopeG(d,er),grid[[best]],cost))\n}\ncalibrateG<-function(d,ids,edges){\n use<-ids[d$eligible[ids]];W<-sum(d$w[use]);pi<-ratio(sum(d$w[use]*d$y[use]),W);bins<-list();ECE<-rel<-res<-correction<-0;assign<-findInterval(d$p[use],edges,rightmost.closed=TRUE,all.inside=TRUE)\n for(b in seq_len(length(edges)-1)){rr<-use[assign==b];w<-sum(d$w[rr]);mp<-ratio(sum(d$w[rr]*d$p[rr]),w);o<-ratio(sum(d$w[rr]*d$y[rr]),w);variance<-if(w)sum(d$w[rr]*(d$p[rr]-mp)^2)/w else NA_real_;covariance<-if(w)sum(d$w[rr]*(d$p[rr]-mp)*(d$y[rr]-o))/w else NA_real_;bc<-variance-2*covariance;gap<-mp-o;bins[[b]]<-list(index=b-1,mass=w,meanPrediction=mp,eventRate=o,scoreVariance=variance,scoreTargetCovariance=covariance,withinBinCorrection=bc,ids=d$id[rr])\n  if(w){s<-w/W;ECE<-ECE+s*abs(gap);rel<-rel+s*gap^2;res<-res+s*(o-pi)^2;correction<-correction+s*bc}\n };bs<-ratio(sum(d$w[use]*(d$p[use]-d$y[use])^2),W);unc<-pi*(1-pi);list(bins=bins,Brier=bs,ECE=if(W)ECE else NA_real_,uncertainty=unc,reliability=if(W)rel else NA_real_,resolution=if(W)res else NA_real_,withinBinCorrection=if(W)correction else NA_real_,BrierIdentityResidual=bs-(unc-res+rel+correction))\n}\ngroupsG<-function(d,ids,t,cost){\n lev<-unique(d$group[ids][!is.na(d$group[ids])]);groups<-lapply(lev,function(g)list(group=g,metrics=metricsG(d,ids[!is.na(d$group[ids])&d$group[ids]==g],t,cost)));overall<-metricsG(d,ids,t,cost);unknown<-metricsG(d,ids[is.na(d$group[ids])],t,cost);gaps<-list()\n for(k in c(\"prevalence\",\"selectionRate\",\"TPR\",\"FPR\",\"precision\",\"accuracy\",\"meanCost\")){use<-Filter(function(g)g$metrics$mass>0,groups);v<-vapply(use,function(g)g$metrics[[k]],numeric(1));gaps[[k]]<-if(length(use)<2||anyNA(v))NA_real_ else max(v)-min(v)}\n list(overall=overall,groups=groups,unknownGroup=unknown,gaps=gaps,partitionMassResidual=overall$mass-unknown$mass-sum(vapply(groups,function(g)g$metrics$mass,numeric(1))))\n}\nsvgFixed<-function(file,points,title,xlabel,ylabel,legend){\n finite<-points[points$y!=\"undefined\"&points$x!=\"undefined\",,drop=FALSE];x<-as.numeric(finite$x);y<-as.numeric(finite$y);xmin<-if(length(x))min(x)else 0;xmax<-if(length(x))max(x)else 1;ymin<-min(c(0,y));ymax<-max(c(0,y));if(xmin==xmax){xmin<-xmin-.5;xmax<-xmax+.5};if(ymin==ymax)ymax<-ymin+1;X<-function(v)85+(v-xmin)/(xmax-xmin)*480;Y<-function(v)278-(v-ymin)/(ymax-ymin)*175\n esc<-function(s){s<-gsub(\"&\",\"&amp;\",s,fixed=TRUE);s<-gsub(\"<\",\"&lt;\",s,fixed=TRUE);gsub(\">\",\"&gt;\",s,fixed=TRUE)};s<-'<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"620\" height=\"360\" viewBox=\"0 0 620 360\"><rect width=\"620\" height=\"360\" fill=\"white\"/><g font-family=\"Arial, sans-serif\" font-size=\"13\" fill=\"#17324d\">'\n lines<-strwrap(title,width=65);for(i in seq_along(lines))s<-paste0(s,'<text x=\"25\" y=\"',24+(i-1)*18,'\">',esc(lines[i]),'</text>');colors<-c(\"#176b9b\",\"#b85e18\",\"#437e4d\")\n for(i in seq_along(legend))s<-paste0(s,'<circle cx=\"',30+(i-1)*250,'\" cy=\"76\" r=\"4\" fill=\"',colors[(i-1)%%3+1],'\"/><text x=\"',42+(i-1)*250,'\" y=\"80\">',esc(legend[i]),'</text>')\n s<-paste0(s,'<path d=\"M85 98V278H575\" fill=\"none\" stroke=\"#52677d\"/><text text-anchor=\"middle\" x=\"325\" y=\"338\">',esc(xlabel),'</text><text text-anchor=\"middle\" transform=\"translate(21,190) rotate(-90)\">',esc(ylabel),'</text>')\n for(i in 0:4){xx<-xmin+(xmax-xmin)*i/4;yy<-ymin+(ymax-ymin)*i/4;s<-paste0(s,'<text text-anchor=\"middle\" x=\"',sprintf(\"%.9g\",X(xx)),'\" y=\"305\">',sprintf(\"%.4g\",xx),'</text><text text-anchor=\"end\" x=\"77\" y=\"',sprintf(\"%.9g\",Y(yy)+4),'\">',sprintf(\"%.4g\",yy),'</text>')}\n for(i in seq_len(nrow(finite)))s<-paste0(s,'<circle cx=\"',sprintf(\"%.9g\",X(x[i])),'\" cy=\"',sprintf(\"%.9g\",Y(y[i])),'\" r=\"3\" fill=\"',colors[as.integer(finite$series[i])%%3+1],'\"/>');writeLines(paste0(s,'</g></svg>'),file,useBytes=TRUE)\n}\nfixedRun<-function(){\n api<-FIXED$api;a<-FIXED$args;summary<-list();points<-list();xlabel<-\"Declared index\";ylabel<-\"Value\";legend<-\"Declared result\"\n metric<-function(name,v,unit=\"dimensionless\"){if(is.null(v))v<-NA_real_;summary[[length(summary)+1L]]<<-data.frame(metric=name,value=if(is.na(v))\"undefined\"else sprintf(\"%.9g\",v),exactValue=\"\",unit=unit,defined=as.integer(!is.na(v)),stringsAsFactors=FALSE)}\n pt<-function(i,x,y,id=\"\",series=0){points[[length(points)+1L]]<<-data.frame(series=series,index=i,xExact=\"\",x=if(is.na(x))\"undefined\"else sprintf(\"%.9g\",x),yExact=\"\",y=if(is.na(y))\"undefined\"else sprintf(\"%.9g\",y),id=as.character(id),stringsAsFactors=FALSE)}\n if(api==\"realdata\"){\n  native<-loadData()[[a$kind]];fit<-fitmodel(native);d<-list(id=native$id,p=fit$pred,y=native$y,w=rep(1,length(native$id)),role=native$role,group=native$group,eligible=native$eligible);scenarios<-list()\n  for(j in 1:3){name<-c(\"equal\",\"miss-five\",\"alarm-five\")[j];cst<-list(c(1,1),c(1,5),c(5,1))[[j]];sel<-chooseG(d,list(),cst);scenarios[[j]]<-list(name=name,selection=sel);metric(paste0(name,\"Threshold\"),sel$selectedPolicy);metric(paste0(name,\"TestCost\"),sel$evaluation$meanCost,\"hypothetical cost units/mass\")}\n  ids<-scopeG(d,\"test\");cv<-curvesG(d,ids);cal<-calibrateG(d,ids,seq(0,1,.2));metric(\"testAUC\",cv$ROC_AUC);metric(\"testAP\",cv$averagePrecision);metric(\"testBrier\",cal$Brier);metric(\"eligibleRows\",sum(d$eligible),\"rows\")\n  for(j in seq_along(ids)){i<-ids[j];pt(j-1,j,d$p[i],d$id[i],0);pt(j-1,j,d$y[i],d$id[i],1)}\n  full<-list(kind=a$kind,fit=fit,scenarios=scenarios,testCurves=cv,testCalibration=cal,rowsScored=d);xlabel<-\"Test row, native order\";ylabel<-\"Y or probability\";legend<-c(\"Training-fitted probability\",\"Observed Y\")\n }else{\n  d<-rowsG(a$rows);role<-if(is.null(a$role))\"all\"else a$role;ids<-scopeG(d,role);cost<-if(is.null(a$costs))c(1,1)else c(qnum(a$costs$falsePositive),qnum(a$costs$falseNegative));t<-if(is.null(a$threshold)).5 else if(a$threshold%in%c(\"always-positive\",\"always-negative\"))a$threshold else qnum(a$threshold)\n  if(api==\"metrics\"){\n   full<-metricsG(d,ids,t,cost);for(k in c(\"mass\",\"accuracy\",\"precision\",\"TPR\",\"FPR\",\"F1\",\"Brier\",\"meanCost\"))metric(k,full[[k]],if(k==\"mass\")\"mass\"else if(k==\"meanCost\")\"hypothetical cost units/mass\"else\"dimensionless\");metric(\"BayesThreshold\",full$bayesThreshold)\n   for(i in 1:4)pt(i-1,i-1,full$confusion[[i]],names(full$confusion)[i]);xlabel<-\"TP / FP / FN / TN positions\";ylabel<-\"Analytical mass\"\n  }else if(api==\"curves\"){\n   full<-curvesG(d,ids);for(k in c(\"ROC_AUC\",\"averagePrecision\",\"PRTrapezoidWithInitialPrecisionOne\"))metric(k,full[[k]])\n   for(j in seq_along(full$points)){p<-full$points[[j]];pt(j-1,p$FPR,p$TPR,if(is.character(p$policy))p$policy else sprintf(\"%.17g\",p$policy))};xlabel<-\"False positive rate\";ylabel<-\"True positive rate\";legend<-\"Observed ROC operating points\"\n  }else if(api==\"choose\"){\n   full<-chooseG(d,a,cost);metric(\"selectedIndex\",full$selectedIndex,\"candidate index\");metric(\"minimumCost\",if(is.null(full$selectedValidation))NULL else full$selectedValidation$meanCost,\"hypothetical cost units/mass\");metric(\"feasible\",as.integer(!is.na(full$selectedIndex)),\"indicator\")\n   for(c in full$candidates)pt(c$index,c$index,c$metrics$meanCost,if(is.character(c$policy))c$policy else sprintf(\"%.17g\",c$policy));xlabel<-\"Validation candidate\";ylabel<-\"Assumed cost / mass\";legend<-\"Validation candidate costs\"\n  }else if(api==\"calibrate\"){\n   edges<-if(is.null(a$binEdges))seq(0,1,.2)else vapply(a$binEdges,qnum,numeric(1));full<-calibrateG(d,ids,edges);for(k in c(\"ECE\",\"Brier\",\"uncertainty\",\"resolution\",\"reliability\",\"withinBinCorrection\",\"BrierIdentityResidual\"))metric(k,full[[k]])\n   for(b in full$bins)pt(b$index,b$meanPrediction,b$eventRate,paste0(\"bin:\",b$index));xlabel<-\"Bin mean forecast\";ylabel<-\"Bin event rate\";legend<-\"Binary-event reliability\"\n  }else if(api==\"groups\"){\n   full<-groupsG(d,ids,t,cost);metric(\"overallTPR\",full$overall$TPR);metric(\"TPRGap\",full$gaps$TPR);metric(\"precisionGap\",full$gaps$precision);metric(\"unknownMass\",full$unknownGroup$mass,\"mass\");metric(\"partitionResidual\",full$partitionMassResidual,\"mass\")\n   for(j in seq_along(full$groups))pt(j-1,j-1,full$groups[[j]]$metrics$TPR,full$groups[[j]]$group);xlabel<-\"Declared group position\";ylabel<-\"True positive rate\";legend<-\"Known-group TPR\"\n  }else stop(\"unknown declared fixed API\")\n }\n sm<-do.call(rbind,summary);pp<-do.call(rbind,points);write.csv(sm,file.path(outDir,\"summary.csv\"),row.names=FALSE,na=\"\");write.csv(pp,file.path(outDir,\"plot-points.csv\"),row.names=FALSE,na=\"\");svgFixed(file.path(outDir,\"plot.svg\"),pp,FIXED$title,xlabel,ylabel,legend);dput(list(api=api,variant=FIXED$variant,input=FIXED$args,arithmetic=\"Base-R binary64 fixed example; not an exact rational general validator\",result=full),file=file.path(outDir,\"full.txt\"));cat(\"PASS\",api,FIXED$variant,\"summary\",nrow(sm),\"points\",nrow(pp),\"\\n\")\n}\n\nFIXED<-list(api=\"groups\",variant=\"six-cards\",args=list(rows=list(list(id=\"a\",score=\".9\",y=1,group=\"A\"),list(id=\"b\",score=\".8\",y=1,group=\"A\"),list(id=\"c\",score=\".8\",y=0,group=\"A\"),list(id=\"d\",score=\".6\",y=0,group=\"B\"),list(id=\"e\",score=\".4\",y=1,group=\"B\"),list(id=\"f\",score=\".1\",y=0,group=\"B\")),threshold=\".8\"),title=\"Group TPR gaps and undefined precision comparison\")\nfixedRun()\n",
        "codeText": "# ML14 standalone public counterpart, base R only.\n# Inputs are only the three factual CSVs; derived columns/previous model answers unused.\n# Binary64 arithmetic, not arbitrary-precision Fraction. At numerical cost ties\n# within 1e-12 retain the earliest candidate. Exact claims belong to Python/web.\n# SHA256 infrastructure below is reused verbatim from the previous public study.\nargs<-commandArgs(trailingOnly=TRUE);filearg<-grep(\"^--file=\",commandArgs(),value=TRUE)\nhere<-if(dir.exists(\"ml14-sources\"))getwd()else if(length(filearg))dirname(normalizePath(sub(\"^--file=\",\"\",filearg[1])))else getwd()\noption<-function(key,default){i<-match(key,args);if(is.na(i))default else args[i+1]}\nsourceDir<-option(\"--source\",file.path(here,\"ml14-sources\"));outDir<-option(\"--out\",file.path(getwd(),\"ml14-r-results\"));dir.create(outDir,recursive=TRUE,showWarnings=FALSE)\nnum<-function(x){x[x%in%c(\"\",\".\")]<-NA_character_;as.numeric(x)}\nfmt<-function(x)ifelse(is.na(x),\"\",sprintf(\"%.17g\",x))\nratio<-function(a,b)if(b==0)NA_real_ else a/b\nreadnative<-function(name)read.csv(file.path(sourceDir,name),check.names=FALSE,colClasses=\"character\",na.strings=character(),stringsAsFactors=FALSE)\n# Vectorized SHA256 for the short ASCII keys used in this study.\n# Unsigned words use exact integer-valued doubles; bit operations use safe\n# 16-bit halves, avoiding R's reserved signed-INT_MIN/NA representation.\nMOD<-2^32\nxor32<-function(a,b) as.double(bitwXor(as.integer(floor(a/65536)),as.integer(floor(b/65536))))*65536+as.double(bitwXor(as.integer(a%%65536),as.integer(b%%65536)))\nand32<-function(a,b) as.double(bitwAnd(as.integer(floor(a/65536)),as.integer(floor(b/65536))))*65536+as.double(bitwAnd(as.integer(a%%65536),as.integer(b%%65536)))\nrot<-function(x,n) floor(x/2^n)+(x%%2^n)*2^(32-n)\nxor3<-function(a,b,c) xor32(xor32(a,b),c)\nK<-c(0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5,0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967,0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070,0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3,0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2)\nsha256<-function(strings) {\n n<-length(strings);bytes<-matrix(0,n,64)\n for(i in seq_len(n)) {v<-utf8ToInt(strings[i]);stopifnot(length(v)<56,all(v<128));if(length(v)) bytes[i,seq_along(v)]<-v;bytes[i,length(v)+1]<-128;bits<-length(v)*8;bytes[i,61:64]<-c(floor(bits/2^24)%%256,floor(bits/2^16)%%256,floor(bits/256)%%256,bits%%256)}\n w<-matrix(0,n,64)\n for(j in 1:16) {b<-4*(j-1)+1;w[,j]<-bytes[,b]*2^24+bytes[,b+1]*2^16+bytes[,b+2]*256+bytes[,b+3]}\n for(j in 17:64) {s0<-xor3(rot(w[,j-15],7),rot(w[,j-15],18),floor(w[,j-15]/8));s1<-xor3(rot(w[,j-2],17),rot(w[,j-2],19),floor(w[,j-2]/1024));w[,j]<-(w[,j-16]+s0+w[,j-7]+s1)%%MOD}\n init<-c(0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19)\n state<-lapply(init,function(v) rep(v,n));a<-state[[1]];b<-state[[2]];c<-state[[3]];d<-state[[4]];e<-state[[5]];f<-state[[6]];g<-state[[7]];h<-state[[8]]\n for(j in 1:64) {S1<-xor3(rot(e,6),rot(e,11),rot(e,25));ch<-xor32(and32(e,f),and32(MOD-1-e,g));t1<-(h+S1+ch+K[j]+w[,j])%%MOD;S0<-xor3(rot(a,2),rot(a,13),rot(a,22));maj<-xor3(and32(a,b),and32(a,c),and32(b,c));t2<-(S0+maj)%%MOD;h<-g;g<-f;f<-e;e<-(d+t1)%%MOD;d<-c;c<-b;b<-a;a<-(t1+t2)%%MOD}\n end<-list(a,b,c,d,e,f,g,h);hex<-lapply(1:8,function(j){v<-(end[[j]]+init[j])%%MOD;paste0(sprintf(\"%04x\",as.integer(floor(v/65536))),sprintf(\"%04x\",as.integer(v%%65536)))})\n do.call(paste0,hex)\n}\nstopifnot(identical(sha256(c(\"abc\",\"\")),c(\"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad\",\"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855\")))\n\nloadData<-function(){\n wb<-readnative(\"actual64-country-four-indicators-original-2024.csv\");codes<-c(\"NY.GDP.PCAP.KD\",\"NY.GDP.MKTP.KD.ZG\",\"FP.CPI.TOTL.ZG\",\"SP.DYN.LE00.IN\");iso<-sort(unique(wb$countryISO3));stopifnot(nrow(wb)==64,length(iso)==16)\n tokens<-t(vapply(iso,function(s)wb$originalValueToken[match(paste(s,codes),paste(wb$countryISO3,wb$indicatorID))],character(4)));vals<-matrix(num(as.vector(tokens)),nrow=nrow(tokens))\n country<-list(id=paste0(iso,\":2024\"),sourceRow=1:16,originalID=iso,x=vals[,1:3,drop=FALSE],rawX=tokens[,1:3,drop=FALSE],nativeTarget=tokens[,4],y=as.integer(vals[,4]>=80),group=ifelse(is.na(vals[,1]),NA_character_,as.character(as.integer(vals[,1]>=25000))),lineage=vapply(iso,function(s)paste(wb$sourceRow[match(paste(s,codes),paste(wb$countryISO3,wb$indicatorID))],collapse=\";\"),character(1)),cat=integer(),units=c(\"constant2015USD/person\",\"annualPercent\",\"annualPercent\"))\n nls<-readnative(\"actual3613-NLS-original52-fields-groups-roles.csv\");raw<-cbind(nls$ed76,nls$age76,nls$nearc4)\n person<-list(id=paste0(\"person:\",nls$sourceRow),sourceRow=as.integer(nls$sourceRow),originalID=nls$id,x=matrix(num(as.vector(raw)),nrow=nrow(raw)),rawX=raw,nativeTarget=nls$wage76,y=as.integer(num(nls$wage76)>=500),group=ifelse(nls$black%in%c(\"\",\".\"),NA_character_,nls$black),lineage=nls$sourceRow,cat=2L,units=c(\"years\",\"years\",\"nativeCategory\"))\n ch<-readnative(\"actual3150-churn-original14-fields-groups-roles.csv\");raw<-cbind(ch[[\"Call  Failure\"]],ch$Complains,ch[[\"Subscription  Length\"]],ch[[\"Seconds of Use\"]])\n company<-list(id=paste0(\"customer:\",ch$sourceRow),sourceRow=as.integer(ch$sourceRow),originalID=rep(\"\",nrow(ch)),x=matrix(num(as.vector(raw)),nrow=nrow(raw)),rawX=raw,nativeTarget=ch$Churn,y=as.integer(ch$Churn),group=ifelse(ch[[\"Tariff Plan\"]]%in%c(\"\",\".\"),NA_character_,ch[[\"Tariff Plan\"]]),lineage=ch$sourceRow,cat=1L,units=c(\"count\",\"nativeCategory\",\"months\",\"seconds\"))\n stopifnot(nrow(nls)==3613,nrow(ch)==3150,identical(as.integer(ch$sourceRow[ch[[\"Charge  Amount\"]]==\"10\"]),c(474L,2174L,2274L,2374L,2674L,2924L,2974L)))\n result<-list(country=country,person=person,company=company)\n for(k in names(result)){d<-result[[k]];n<-length(d$id);d$eligible<-!is.na(d$y)&rowSums(is.na(d$x))==0;hash<-sha256(paste0(\"ML14-role|\",k,\"|\",d$id));rank<-integer(n);rank[order(hash,seq_len(n))]<-seq_len(n)-1L;d$plannedRole<-ifelse(rank%%5==0,\"test\",ifelse(rank%%5==1,\"validation\",\"train\"));d$role<-ifelse(d$eligible,d$plannedRole,\"excluded\");result[[k]]<-d}\n stopifnot(sum(result$person$eligible)==3017);result\n}\nfitmodel<-function(d){\n ids<-which(d$role==\"train\");p<-ncol(d$x);m<-vapply(seq_len(p),function(j)if((j-1)%in%d$cat)NA_real_ else median(d$x[ids,j]),numeric(1));z<-d$x\n for(j in seq_len(p))if(!((j-1)%in%d$cat))z[,j]<-as.numeric(z[,j]>m[j])\n keys<-apply(z,1,function(v)paste(fmt(v),collapse=\"|\"));lev<-unique(keys[ids]);mass<-vapply(lev,function(k)sum(keys[ids]==k),integer(1));positive<-vapply(lev,function(k)sum(d$y[ids][keys[ids]==k]),integer(1));prob<-(positive+1)/(mass+2);fallback<-(sum(d$y[ids])+1)/(length(ids)+2);pred<-prob[match(keys,lev)];unseen<-is.na(pred);pred[unseen]<-fallback;pred[!d$eligible]<-NA_real_;unseen[!d$eligible]<-NA\n list(ids=ids,medians=m,z=z,keys=keys,lev=lev,mass=mass,positive=positive,prob=prob,fallback=fallback,pred=pred,unseen=unseen)\n}\nmeasure<-function(d,p,ids,t=.5,cost=c(1,1)){\n use<-ids[d$eligible[ids]&!is.na(p[ids])];y<-d$y[use];a<-if(is.character(t))rep(t==\"always-positive\",length(use))else p[use]>=t\n TP<-sum(a&y==1);FP<-sum(a&y==0);FN<-sum(!a&y==1);TN<-sum(!a&y==0);P<-TP+FN;N<-FP+TN;W<-P+N;PP<-TP+FP;PN<-TN+FN;TPR<-ratio(TP,P);TNR<-ratio(TN,N);bs<-sum((p[use]-y)^2);tc<-FP*cost[1]+FN*cost[2]\n list(TP=TP,FP=FP,FN=FN,TN=TN,mass=W,positiveTargetMass=P,negativeTargetMass=N,predictedPositiveMass=PP,predictedNegativeMass=PN,prevalence=ratio(P,W),selectionRate=ratio(PP,W),accuracy=ratio(TP+TN,W),precision=ratio(TP,PP),negativePredictiveValue=ratio(TN,PN),TPR=TPR,FPR=ratio(FP,N),TNR=TNR,FNR=ratio(FN,P),F1=ratio(2*TP,2*TP+FP+FN),balancedAccuracy=if(is.na(TPR)||is.na(TNR))NA_real_ else(TPR+TNR)/2,Brier=ratio(bs,W),BrierSum=bs,totalCost=tc,meanCost=ratio(tc,W))\n}\ncurves<-function(d,p,ids){\n use<-ids[d$eligible[ids]&!is.na(p[ids])];scores<-sort(unique(p[use]),decreasing=TRUE);policies<-c(list(\"always-negative\"),as.list(scores));points<-lapply(policies,function(t){m<-measure(d,p,ids,t);c(list(policy=t),m[c(\"TP\",\"FP\",\"FN\",\"TN\",\"TPR\",\"FPR\",\"precision\")],list(recall=m$TPR))})\n pos<-use[d$y[use]==1];neg<-use[d$y[use]==0];U<-0;for(i in pos)U<-U+sum(p[i]>p[neg])+.5*sum(p[i]==p[neg])\n AP<-0;trap<-0;lastR<-0;lastP<-1\n if(length(pos)&&length(scores))for(j in seq_along(scores)){z<-points[[j+1]];AP<-AP+(z$recall-lastR)*z$precision;trap<-trap+(z$recall-lastR)*(z$precision+lastP)/2;lastR<-z$recall;lastP<-z$precision}\n list(points=points,ROC_AUC=ratio(U,length(pos)*length(neg)),averagePrecision=if(length(pos))AP else NA_real_,PRTrapezoidWithInitialPrecisionOne=if(length(pos))trap else NA_real_)\n}\ncalibrate<-function(d,p,ids){\n use<-ids[d$eligible[ids]&!is.na(p[ids])];W<-length(use);pi<-if(W)mean(d$y[use])else NA_real_;bins<-list();ECE<-rel<-res<-correction<-0\n whichbin<-findInterval(p[use],seq(0,1,.2),rightmost.closed=TRUE,all.inside=TRUE)\n for(b in 1:5){rr<-use[whichbin==b];w<-length(rr);mp<-if(w)mean(p[rr])else NA_real_;o<-if(w)mean(d$y[rr])else NA_real_;variance<-if(w)mean((p[rr]-mp)^2)else NA_real_;covariance<-if(w)mean((p[rr]-mp)*(d$y[rr]-o))else NA_real_;bc<-variance-2*covariance;gap<-mp-o\n  bins[[b]]<-list(mass=w,meanPrediction=mp,eventRate=o,gap=gap,absoluteGap=abs(gap),scoreVariance=variance,scoreTargetCovariance=covariance,withinBinCorrection=bc,rows=w,ids=d$id[rr])\n  if(w){share<-w/W;ECE<-ECE+share*abs(gap);rel<-rel+share*gap^2;res<-res+share*(o-pi)^2;correction<-correction+share*bc}\n };bs<-if(W)mean((p[use]-d$y[use])^2)else NA_real_;unc<-pi*(1-pi)\n list(bins=bins,ECE=if(W)ECE else NA_real_,Brier=bs,reliability=if(W)rel else NA_real_,resolution=if(W)res else NA_real_,uncertainty=unc,withinBinCorrection=if(W)correction else NA_real_,BrierIdentityResidual=bs-(unc-res+rel+correction))\n}\ncounts<-c(\"mass\",\"positiveTargetMass\",\"negativeTargetMass\",\"predictedPositiveMass\",\"predictedNegativeMass\");rates<-c(\"prevalence\",\"selectionRate\",\"accuracy\",\"precision\",\"negativePredictiveValue\",\"TPR\",\"FPR\",\"TNR\",\"FNR\",\"F1\",\"balancedAccuracy\",\"Brier\",\"BrierSum\",\"totalCost\",\"meanCost\")\ntables<-setNames(lapply(1:10,function(i)list()),c(\"predictions\",\"lineage\",\"fit-medians\",\"fit-cells\",\"validation-candidates\",\"test-metrics\",\"test-curves\",\"calibration-bins\",\"group-metrics\",\"chart-points\"))\nadd<-function(name,row)tables[[name]][[length(tables[[name]])+1L]]<<-row\nscalars<-function(m,keys){out<-list();for(k in keys){out[[paste0(k,\"Exact\")]]<-\"\";out[[paste0(k,\"Approx\")]]<-fmt(m[[k]])};out}\ntagrow<-function(kind,...)c(list(kind=kind),list(...))\npoint<-function(kind,chart,series,index,x,y,xunit=\"dimensionless\",yunit=\"dimensionless\",role=\"test\",tag=\"\"){add(\"chart-points\",tagrow(kind,chart=chart,series=series,index=index,xExact=\"\",xApprox=fmt(x),yExact=\"\",yApprox=fmt(y),xUnit=xunit,yUnit=yunit,role=role,tag=tag))}\nstudy<-function(kind,d){\n f<-fitmodel(d);n<-length(d$id);train<-which(d$role==\"train\");validation<-which(d$role==\"validation\");test<-which(d$role==\"test\");p<-f$pred;cv<-curves(d,p,test);cal<-calibrate(d,p,test)\n for(i in seq_len(n)){\n  reason<-if(d$eligible[i])\"\"else\"required-X-or-Y-missing\";transformed<-if(d$eligible[i])paste(fmt(f$z[i,]),collapse=\"|\")else\"\"\n  add(\"predictions\",tagrow(kind,id=d$id[i],sourceRow=d$sourceRow[i],originalID=d$originalID[i],plannedRole=d$plannedRole[i],role=d$role[i],group=ifelse(is.na(d$group[i]),\"\",d$group[i]),eligible=as.integer(d$eligible[i]),targetExact=fmt(d$y[i]),probabilityExact=\"\",probabilityApprox=fmt(p[i]),unseenCell=ifelse(is.na(f$unseen[i]),\"\",as.character(as.integer(f$unseen[i]))),transformedX=transformed,reason=reason))\n  raw<-d$rawX[i,];raw[raw%in%c(\"\",\".\")]<-\"\";nativeY<-d$nativeTarget[i];if(nativeY%in%c(\"\",\".\"))nativeY<-\"\"\n  add(\"lineage\",tagrow(kind,id=d$id[i],sourceRow=d$sourceRow[i],originalID=d$originalID[i],nativeSourceRows=d$lineage[i],rawX=paste(raw,collapse=\"|\"),nativeTarget=nativeY,derivedTarget=fmt(d$y[i]),nativeGroup=ifelse(is.na(d$group[i]),\"\",d$group[i]),plannedRole=d$plannedRole[i],role=d$role[i],eligible=as.integer(d$eligible[i]),analyticalMass=\"1\",reason=reason))\n }\n for(j in seq_len(ncol(d$x)))add(\"fit-medians\",tagrow(kind,feature=j-1,categorical=as.integer((j-1)%in%d$cat),fitRows=length(train),medianExact=\"\",medianApprox=fmt(f$medians[j]),unit=d$units[j]))\n for(j in seq_along(f$lev))add(\"fit-cells\",tagrow(kind,cell=f$lev[j],trainingRows=f$mass[j],positiveRows=f$positive[j],probabilityExact=\"\",probabilityApprox=fmt(f$prob[j]),fallbackExact=\"\",fallbackApprox=fmt(f$fallback)))\n for(j in seq_along(cv$points)){\n  z<-cv$points[[j]];t<-z$policy;add(\"test-curves\",c(tagrow(kind,point=j-1,policy=if(is.character(t))t else\"threshold\",thresholdExact=\"\",thresholdApprox=if(is.character(t))\"\"else fmt(t)),scalars(z,c(\"TP\",\"FP\",\"FN\",\"TN\",\"TPR\",\"FPR\",\"precision\",\"recall\"))))\n  point(kind,\"roc\",\"ROC\",j-1,z$FPR,z$TPR);point(kind,\"pr\",\"PR-observed\",j-1,z$recall,z$precision)\n }\n for(b in 1:5){z<-cal$bins[[b]];add(\"calibration-bins\",c(tagrow(kind,bin=b-1,leftExact=c(\"0\",\"1/5\",\"2/5\",\"3/5\",\"4/5\")[b],rightExact=c(\"1/5\",\"2/5\",\"3/5\",\"4/5\",\"1\")[b],rightClosed=as.integer(b==5),rows=z$rows,ids=paste(z$ids,collapse=\";\")),scalars(z,c(\"mass\",\"meanPrediction\",\"eventRate\",\"gap\",\"absoluteGap\",\"scoreVariance\",\"scoreTargetCovariance\",\"withinBinCorrection\"))));point(kind,\"reliability\",\"Binary event rate\",b-1,z$meanPrediction,z$eventRate,tag=paste0(\"rows=\",z$rows))}\n for(j in seq_along(test)){i<-test[j];point(kind,\"test-scores\",\"Training-fitted probability\",j-1,j,p[i],\"test-row position\",\"probability\",tag=d$id[i]);point(kind,\"test-scores\",\"Observed Y\",j-1,j,d$y[i],\"test-row position\",\"binary target\",tag=d$id[i])}\n scenarioNames<-c(\"equal\",\"miss-five\",\"alarm-five\");costs<-list(c(1,1),c(1,5),c(5,1))\n for(s in 1:3){name<-scenarioNames[s];cost<-costs[[s]];grid<-c(list(\"always-negative\"),as.list(sort(unique(p[validation]),decreasing=TRUE)));candidates<-lapply(grid,function(t)measure(d,p,validation,t,cost));values<-vapply(candidates,function(m)m$meanCost,numeric(1));best<-which(values<=min(values)+1e-12)[1];chosen<-grid[[best]];ev<-measure(d,p,test,chosen,cost)\n  for(j in seq_along(grid)){t<-grid[[j]];m<-candidates[[j]];cell<-setNames(lapply(c(\"TP\",\"FP\",\"FN\",\"TN\"),function(k)fmt(m[[k]])),paste0(c(\"TP\",\"FP\",\"FN\",\"TN\"),\"Exact\"));add(\"validation-candidates\",c(tagrow(kind,scenario=name,candidate=j-1,selected=as.integer(j==best),policy=if(is.character(t))t else\"threshold\",thresholdExact=\"\",thresholdApprox=if(is.character(t))\"\"else fmt(t),feasible=1,reasons=\"\"),cell,scalars(m,c(counts,\"TPR\",\"FPR\",\"precision\",\"meanCost\",\"totalCost\"))));point(kind,\"validation-cost\",name,j-1,j-1,m$meanCost,\"candidate index\",\"hypothetical cost units/mass\",\"validation\",if(is.character(t))t else fmt(t))}\n  m<-c(ev,cv[c(\"ROC_AUC\",\"averagePrecision\",\"PRTrapezoidWithInitialPrecisionOne\")],cal[c(\"ECE\",\"reliability\",\"resolution\",\"uncertainty\",\"withinBinCorrection\",\"BrierIdentityResidual\")])\n  for(k in c(\"TP\",\"FP\",\"FN\",\"TN\",counts,rates,\"ROC_AUC\",\"averagePrecision\",\"PRTrapezoidWithInitialPrecisionOne\",\"ECE\",\"reliability\",\"resolution\",\"uncertainty\",\"withinBinCorrection\",\"BrierIdentityResidual\")){\n   unit<-if(k%in%c(\"TP\",\"FP\",\"FN\",\"TN\",counts))\"rows\"else if(k==\"totalCost\")\"hypothetical cost units\"else if(k==\"meanCost\")\"hypothetical cost units/mass\"else if(k==\"BrierSum\")\"sum squared-probability loss\"else\"dimensionless\"\n   add(\"test-metrics\",tagrow(kind,scenario=name,metric=k,valueExact=\"\",valueApprox=fmt(m[[k]]),unit=unit))\n  }\n  lev<-unique(d$group[test][!is.na(d$group[test])]);sets<-c(list(test),lapply(lev,function(g)test[!is.na(d$group[test])&d$group[test]==g]),list(test[is.na(d$group[test])]))\n  types<-c(\"overall\",rep(\"known\",length(lev)),\"unknown\");tokens<-c(\"all\",lev,\"\")\n  for(j in seq_along(sets)){ids<-sets[[j]];m<-measure(d,p,ids,chosen,cost);cell<-setNames(lapply(c(\"TP\",\"FP\",\"FN\",\"TN\"),function(k)fmt(m[[k]])),paste0(c(\"TP\",\"FP\",\"FN\",\"TN\"),\"Exact\"));add(\"group-metrics\",c(tagrow(kind,scenario=name,groupType=types[j],groupToken=tokens[j],retainedRows=length(ids)),cell,scalars(m,c(counts,rates))));if(types[j]==\"known\")point(kind,\"group-TPR\",name,j-2,j-2,m$TPR,\"declared group position\",\"TPR\",tag=tokens[j])}\n }\n invisible(NULL)\n}\n\n# Fixed finite inputs only; not the complete web input/budget validator.\nqnum<-function(v){if(is.null(v))return(NA_real_);if(is.logical(v))return(as.numeric(v));s<-as.character(v);if(grepl(\"/\",s,fixed=TRUE)){a<-strsplit(s,\"/\",fixed=TRUE)[[1]];return(as.numeric(a[1])/as.numeric(a[2]))};as.numeric(s)}\nrowsG<-function(raw){\n n<-length(raw);get<-function(r,k,default=NULL)if(is.null(r[[k]]))default else r[[k]]\n id<-vapply(raw,function(r)as.character(r$id),character(1));p<-vapply(raw,function(r)qnum(r$score),numeric(1));y<-vapply(raw,function(r)qnum(r$y),numeric(1));w<-vapply(raw,function(r)qnum(get(r,\"weight\",\"1\")),numeric(1));role<-vapply(raw,function(r)get(r,\"role\",\"evaluation\"),character(1));group<-vapply(raw,function(r)as.character(get(r,\"group\",NA_character_)),character(1))\n stopifnot(all(w>=0),all(is.na(p)|(p>=0&p<=1)),all(is.na(y)|y%in%c(0,1)),!anyDuplicated(id));list(id=id,p=p,y=y,w=w,role=role,group=group,eligible=!is.na(p)&!is.na(y)&w>0&role!=\"excluded\")\n}\nscopeG<-function(d,role=\"all\")if(role==\"all\")seq_along(d$id)else which(d$role==role)\nmetricsG<-function(d,ids,t=.5,cost=c(1,1)){\n use<-ids[d$eligible[ids]];p<-d$p[use];y<-d$y[use];w<-d$w[use];a<-if(is.character(t))rep(t==\"always-positive\",length(use))else p>=t\n TP<-sum(w[a&y==1]);FP<-sum(w[a&y==0]);FN<-sum(w[!a&y==1]);TN<-sum(w[!a&y==0]);P<-TP+FN;N<-FP+TN;W<-P+N;PP<-TP+FP;PN<-TN+FN;TPR<-ratio(TP,P);TNR<-ratio(TN,N);bs<-sum(w*(p-y)^2);tc<-FP*cost[1]+FN*cost[2]\n list(confusion=list(TP=TP,FP=FP,FN=FN,TN=TN),mass=W,positiveTargetMass=P,negativeTargetMass=N,predictedPositiveMass=PP,predictedNegativeMass=PN,prevalence=ratio(P,W),selectionRate=ratio(PP,W),accuracy=ratio(TP+TN,W),precision=ratio(TP,PP),negativePredictiveValue=ratio(TN,PN),TPR=TPR,FPR=ratio(FP,N),TNR=TNR,FNR=ratio(FN,P),F1=ratio(2*TP,2*TP+FP+FN),balancedAccuracy=if(is.na(TPR)||is.na(TNR))NA_real_ else(TPR+TNR)/2,Brier=ratio(bs,W),BrierSum=bs,totalCost=tc,meanCost=ratio(tc,W),bayesThreshold=ratio(cost[1],sum(cost)))\n}\ncurvesG<-function(d,ids){\n use<-ids[d$eligible[ids]];grid<-c(list(\"always-negative\"),as.list(sort(unique(d$p[use]),decreasing=TRUE)));points<-lapply(grid,function(t){m<-metricsG(d,ids,t);c(list(policy=t),m$confusion,m[c(\"TPR\",\"FPR\",\"precision\")],list(recall=m$TPR))});pos<-use[d$y[use]==1];neg<-use[d$y[use]==0];P<-sum(d$w[pos]);N<-sum(d$w[neg]);U<-0\n for(i in pos)U<-U+d$w[i]*sum(d$w[neg]*((d$p[i]>d$p[neg])+.5*(d$p[i]==d$p[neg])))\n AP<-trap<-lastR<-0;lastP<-1\n if(P&&length(grid)>1)for(j in 2:length(grid)){z<-points[[j]];AP<-AP+(z$recall-lastR)*z$precision;trap<-trap+(z$recall-lastR)*(z$precision+lastP)/2;lastR<-z$recall;lastP<-z$precision}\n list(points=points,ROC_AUC=ratio(U,P*N),averagePrecision=if(P)AP else NA_real_,PRTrapezoidWithInitialPrecisionOne=if(P)trap else NA_real_)\n}\nchooseG<-function(d,a,cost){\n role<-if(is.null(a$selectionRole))\"validation\"else a$selectionRole;er<-if(is.null(a$evaluationRole))\"test\"else a$evaluationRole;ids<-scopeG(d,role);use<-ids[d$eligible[ids]];stopifnot(length(use)>0);grid<-if(is.null(a$thresholds))c(list(\"always-negative\"),as.list(sort(unique(d$p[use]),decreasing=TRUE)))else lapply(a$thresholds,function(t)if(t%in%c(\"always-negative\",\"always-positive\"))t else qnum(t))\n candidates<-lapply(seq_along(grid),function(j){m<-metricsG(d,ids,grid[[j]],cost);feasible<-TRUE;if(!is.null(a$minTPR))feasible<-feasible&&!is.na(m$TPR)&&m$TPR>=qnum(a$minTPR);if(!is.null(a$maxFPR))feasible<-feasible&&!is.na(m$FPR)&&m$FPR<=qnum(a$maxFPR);list(index=j-1,policy=grid[[j]],metrics=m,feasible=feasible)})\n good<-which(vapply(candidates,function(c)c$feasible,logical(1)));best<-NA_integer_;if(length(good)){v<-vapply(candidates[good],function(c)c$metrics$meanCost,numeric(1));best<-good[which(v<=min(v)+1e-12)[1]]}\n list(selectedIndex=if(is.na(best))NA_integer_ else best-1,selectedPolicy=if(is.na(best))NULL else grid[[best]],selectedValidation=if(is.na(best))NULL else candidates[[best]]$metrics,candidates=candidates,evaluation=if(is.na(best)||er==\"none\")NULL else metricsG(d,scopeG(d,er),grid[[best]],cost))\n}\ncalibrateG<-function(d,ids,edges){\n use<-ids[d$eligible[ids]];W<-sum(d$w[use]);pi<-ratio(sum(d$w[use]*d$y[use]),W);bins<-list();ECE<-rel<-res<-correction<-0;assign<-findInterval(d$p[use],edges,rightmost.closed=TRUE,all.inside=TRUE)\n for(b in seq_len(length(edges)-1)){rr<-use[assign==b];w<-sum(d$w[rr]);mp<-ratio(sum(d$w[rr]*d$p[rr]),w);o<-ratio(sum(d$w[rr]*d$y[rr]),w);variance<-if(w)sum(d$w[rr]*(d$p[rr]-mp)^2)/w else NA_real_;covariance<-if(w)sum(d$w[rr]*(d$p[rr]-mp)*(d$y[rr]-o))/w else NA_real_;bc<-variance-2*covariance;gap<-mp-o;bins[[b]]<-list(index=b-1,mass=w,meanPrediction=mp,eventRate=o,scoreVariance=variance,scoreTargetCovariance=covariance,withinBinCorrection=bc,ids=d$id[rr])\n  if(w){s<-w/W;ECE<-ECE+s*abs(gap);rel<-rel+s*gap^2;res<-res+s*(o-pi)^2;correction<-correction+s*bc}\n };bs<-ratio(sum(d$w[use]*(d$p[use]-d$y[use])^2),W);unc<-pi*(1-pi);list(bins=bins,Brier=bs,ECE=if(W)ECE else NA_real_,uncertainty=unc,reliability=if(W)rel else NA_real_,resolution=if(W)res else NA_real_,withinBinCorrection=if(W)correction else NA_real_,BrierIdentityResidual=bs-(unc-res+rel+correction))\n}\ngroupsG<-function(d,ids,t,cost){\n lev<-unique(d$group[ids][!is.na(d$group[ids])]);groups<-lapply(lev,function(g)list(group=g,metrics=metricsG(d,ids[!is.na(d$group[ids])&d$group[ids]==g],t,cost)));overall<-metricsG(d,ids,t,cost);unknown<-metricsG(d,ids[is.na(d$group[ids])],t,cost);gaps<-list()\n for(k in c(\"prevalence\",\"selectionRate\",\"TPR\",\"FPR\",\"precision\",\"accuracy\",\"meanCost\")){use<-Filter(function(g)g$metrics$mass>0,groups);v<-vapply(use,function(g)g$metrics[[k]],numeric(1));gaps[[k]]<-if(length(use)<2||anyNA(v))NA_real_ else max(v)-min(v)}\n list(overall=overall,groups=groups,unknownGroup=unknown,gaps=gaps,partitionMassResidual=overall$mass-unknown$mass-sum(vapply(groups,function(g)g$metrics$mass,numeric(1))))\n}\nsvgFixed<-function(file,points,title,xlabel,ylabel,legend){\n finite<-points[points$y!=\"undefined\"&points$x!=\"undefined\",,drop=FALSE];x<-as.numeric(finite$x);y<-as.numeric(finite$y);xmin<-if(length(x))min(x)else 0;xmax<-if(length(x))max(x)else 1;ymin<-min(c(0,y));ymax<-max(c(0,y));if(xmin==xmax){xmin<-xmin-.5;xmax<-xmax+.5};if(ymin==ymax)ymax<-ymin+1;X<-function(v)85+(v-xmin)/(xmax-xmin)*480;Y<-function(v)278-(v-ymin)/(ymax-ymin)*175\n esc<-function(s){s<-gsub(\"&\",\"&amp;\",s,fixed=TRUE);s<-gsub(\"<\",\"&lt;\",s,fixed=TRUE);gsub(\">\",\"&gt;\",s,fixed=TRUE)};s<-'<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"620\" height=\"360\" viewBox=\"0 0 620 360\"><rect width=\"620\" height=\"360\" fill=\"white\"/><g font-family=\"Arial, sans-serif\" font-size=\"13\" fill=\"#17324d\">'\n lines<-strwrap(title,width=65);for(i in seq_along(lines))s<-paste0(s,'<text x=\"25\" y=\"',24+(i-1)*18,'\">',esc(lines[i]),'</text>');colors<-c(\"#176b9b\",\"#b85e18\",\"#437e4d\")\n for(i in seq_along(legend))s<-paste0(s,'<circle cx=\"',30+(i-1)*250,'\" cy=\"76\" r=\"4\" fill=\"',colors[(i-1)%%3+1],'\"/><text x=\"',42+(i-1)*250,'\" y=\"80\">',esc(legend[i]),'</text>')\n s<-paste0(s,'<path d=\"M85 98V278H575\" fill=\"none\" stroke=\"#52677d\"/><text text-anchor=\"middle\" x=\"325\" y=\"338\">',esc(xlabel),'</text><text text-anchor=\"middle\" transform=\"translate(21,190) rotate(-90)\">',esc(ylabel),'</text>')\n for(i in 0:4){xx<-xmin+(xmax-xmin)*i/4;yy<-ymin+(ymax-ymin)*i/4;s<-paste0(s,'<text text-anchor=\"middle\" x=\"',sprintf(\"%.9g\",X(xx)),'\" y=\"305\">',sprintf(\"%.4g\",xx),'</text><text text-anchor=\"end\" x=\"77\" y=\"',sprintf(\"%.9g\",Y(yy)+4),'\">',sprintf(\"%.4g\",yy),'</text>')}\n for(i in seq_len(nrow(finite)))s<-paste0(s,'<circle cx=\"',sprintf(\"%.9g\",X(x[i])),'\" cy=\"',sprintf(\"%.9g\",Y(y[i])),'\" r=\"3\" fill=\"',colors[as.integer(finite$series[i])%%3+1],'\"/>');writeLines(paste0(s,'</g></svg>'),file,useBytes=TRUE)\n}\nfixedRun<-function(){\n api<-FIXED$api;a<-FIXED$args;summary<-list();points<-list();xlabel<-\"Declared index\";ylabel<-\"Value\";legend<-\"Declared result\"\n metric<-function(name,v,unit=\"dimensionless\"){if(is.null(v))v<-NA_real_;summary[[length(summary)+1L]]<<-data.frame(metric=name,value=if(is.na(v))\"undefined\"else sprintf(\"%.9g\",v),exactValue=\"\",unit=unit,defined=as.integer(!is.na(v)),stringsAsFactors=FALSE)}\n pt<-function(i,x,y,id=\"\",series=0){points[[length(points)+1L]]<<-data.frame(series=series,index=i,xExact=\"\",x=if(is.na(x))\"undefined\"else sprintf(\"%.9g\",x),yExact=\"\",y=if(is.na(y))\"undefined\"else sprintf(\"%.9g\",y),id=as.character(id),stringsAsFactors=FALSE)}\n if(api==\"realdata\"){\n  native<-loadData()[[a$kind]];fit<-fitmodel(native);d<-list(id=native$id,p=fit$pred,y=native$y,w=rep(1,length(native$id)),role=native$role,group=native$group,eligible=native$eligible);scenarios<-list()\n  for(j in 1:3){name<-c(\"equal\",\"miss-five\",\"alarm-five\")[j];cst<-list(c(1,1),c(1,5),c(5,1))[[j]];sel<-chooseG(d,list(),cst);scenarios[[j]]<-list(name=name,selection=sel);metric(paste0(name,\"Threshold\"),sel$selectedPolicy);metric(paste0(name,\"TestCost\"),sel$evaluation$meanCost,\"hypothetical cost units/mass\")}\n  ids<-scopeG(d,\"test\");cv<-curvesG(d,ids);cal<-calibrateG(d,ids,seq(0,1,.2));metric(\"testAUC\",cv$ROC_AUC);metric(\"testAP\",cv$averagePrecision);metric(\"testBrier\",cal$Brier);metric(\"eligibleRows\",sum(d$eligible),\"rows\")\n  for(j in seq_along(ids)){i<-ids[j];pt(j-1,j,d$p[i],d$id[i],0);pt(j-1,j,d$y[i],d$id[i],1)}\n  full<-list(kind=a$kind,fit=fit,scenarios=scenarios,testCurves=cv,testCalibration=cal,rowsScored=d);xlabel<-\"Test row, native order\";ylabel<-\"Y or probability\";legend<-c(\"Training-fitted probability\",\"Observed Y\")\n }else{\n  d<-rowsG(a$rows);role<-if(is.null(a$role))\"all\"else a$role;ids<-scopeG(d,role);cost<-if(is.null(a$costs))c(1,1)else c(qnum(a$costs$falsePositive),qnum(a$costs$falseNegative));t<-if(is.null(a$threshold)).5 else if(a$threshold%in%c(\"always-positive\",\"always-negative\"))a$threshold else qnum(a$threshold)\n  if(api==\"metrics\"){\n   full<-metricsG(d,ids,t,cost);for(k in c(\"mass\",\"accuracy\",\"precision\",\"TPR\",\"FPR\",\"F1\",\"Brier\",\"meanCost\"))metric(k,full[[k]],if(k==\"mass\")\"mass\"else if(k==\"meanCost\")\"hypothetical cost units/mass\"else\"dimensionless\");metric(\"BayesThreshold\",full$bayesThreshold)\n   for(i in 1:4)pt(i-1,i-1,full$confusion[[i]],names(full$confusion)[i]);xlabel<-\"TP / FP / FN / TN positions\";ylabel<-\"Analytical mass\"\n  }else if(api==\"curves\"){\n   full<-curvesG(d,ids);for(k in c(\"ROC_AUC\",\"averagePrecision\",\"PRTrapezoidWithInitialPrecisionOne\"))metric(k,full[[k]])\n   for(j in seq_along(full$points)){p<-full$points[[j]];pt(j-1,p$FPR,p$TPR,if(is.character(p$policy))p$policy else sprintf(\"%.17g\",p$policy))};xlabel<-\"False positive rate\";ylabel<-\"True positive rate\";legend<-\"Observed ROC operating points\"\n  }else if(api==\"choose\"){\n   full<-chooseG(d,a,cost);metric(\"selectedIndex\",full$selectedIndex,\"candidate index\");metric(\"minimumCost\",if(is.null(full$selectedValidation))NULL else full$selectedValidation$meanCost,\"hypothetical cost units/mass\");metric(\"feasible\",as.integer(!is.na(full$selectedIndex)),\"indicator\")\n   for(c in full$candidates)pt(c$index,c$index,c$metrics$meanCost,if(is.character(c$policy))c$policy else sprintf(\"%.17g\",c$policy));xlabel<-\"Validation candidate\";ylabel<-\"Assumed cost / mass\";legend<-\"Validation candidate costs\"\n  }else if(api==\"calibrate\"){\n   edges<-if(is.null(a$binEdges))seq(0,1,.2)else vapply(a$binEdges,qnum,numeric(1));full<-calibrateG(d,ids,edges);for(k in c(\"ECE\",\"Brier\",\"uncertainty\",\"resolution\",\"reliability\",\"withinBinCorrection\",\"BrierIdentityResidual\"))metric(k,full[[k]])\n   for(b in full$bins)pt(b$index,b$meanPrediction,b$eventRate,paste0(\"bin:\",b$index));xlabel<-\"Bin mean forecast\";ylabel<-\"Bin event rate\";legend<-\"Binary-event reliability\"\n  }else if(api==\"groups\"){\n   full<-groupsG(d,ids,t,cost);metric(\"overallTPR\",full$overall$TPR);metric(\"TPRGap\",full$gaps$TPR);metric(\"precisionGap\",full$gaps$precision);metric(\"unknownMass\",full$unknownGroup$mass,\"mass\");metric(\"partitionResidual\",full$partitionMassResidual,\"mass\")\n   for(j in seq_along(full$groups))pt(j-1,j-1,full$groups[[j]]$metrics$TPR,full$groups[[j]]$group);xlabel<-\"Declared group position\";ylabel<-\"True positive rate\";legend<-\"Known-group TPR\"\n  }else stop(\"unknown declared fixed API\")\n }\n sm<-do.call(rbind,summary);pp<-do.call(rbind,points);write.csv(sm,file.path(outDir,\"summary.csv\"),row.names=FALSE,na=\"\");write.csv(pp,file.path(outDir,\"plot-points.csv\"),row.names=FALSE,na=\"\");svgFixed(file.path(outDir,\"plot.svg\"),pp,FIXED$title,xlabel,ylabel,legend);dput(list(api=api,variant=FIXED$variant,input=FIXED$args,arithmetic=\"Base-R binary64 fixed example; not an exact rational general validator\",result=full),file=file.path(outDir,\"full.txt\"));cat(\"PASS\",api,FIXED$variant,\"summary\",nrow(sm),\"points\",nrow(pp),\"\\n\")\n}\n\nFIXED<-list(api=\"groups\",variant=\"six-cards\",args=list(rows=list(list(id=\"a\",score=\".9\",y=1,group=\"A\"),list(id=\"b\",score=\".8\",y=1,group=\"A\"),list(id=\"c\",score=\".8\",y=0,group=\"A\"),list(id=\"d\",score=\".6\",y=0,group=\"B\"),list(id=\"e\",score=\".4\",y=1,group=\"B\"),list(id=\"f\",score=\".1\",y=0,group=\"B\")),threshold=\".8\"),title=\"Group TPR gaps and undefined precision comparison\")\nfixedRun()\n",
        "input": {
          "rows": [
            {
              "id": "a",
              "score": ".9",
              "y": 1,
              "group": "A"
            },
            {
              "id": "b",
              "score": ".8",
              "y": 1,
              "group": "A"
            },
            {
              "id": "c",
              "score": ".8",
              "y": 0,
              "group": "A"
            },
            {
              "id": "d",
              "score": ".6",
              "y": 0,
              "group": "B"
            },
            {
              "id": "e",
              "score": ".4",
              "y": 1,
              "group": "B"
            },
            {
              "id": "f",
              "score": ".1",
              "y": 0,
              "group": "B"
            }
          ],
          "threshold": ".8"
        },
        "inputFiles": [],
        "returnCode": 0,
        "expectedFailure": false,
        "stdout": "PASS groups six-cards summary 5 points 2 \n",
        "stderr": "During startup - Warning messages:\n1: Setting LC_COLLATE=C.UTF-8 failed \n2: Setting LC_CTYPE=C.UTF-8 failed \n3: Setting LC_MONETARY=C.UTF-8 failed \n4: Setting LC_TIME=C.UTF-8 failed \n",
        "summary": {
          "overallTPR": "0.666666667",
          "TPRGap": "1",
          "precisionGap": "undefined",
          "unknownMass": "0",
          "partitionResidual": "0"
        },
        "summaryRows": [
          {
            "metric": "overallTPR",
            "value": "0.666666667",
            "exactValue": "",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "TPRGap",
            "value": "1",
            "exactValue": "",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "precisionGap",
            "value": "undefined",
            "exactValue": "",
            "unit": "dimensionless",
            "defined": "0"
          },
          {
            "metric": "unknownMass",
            "value": "0",
            "exactValue": "",
            "unit": "mass",
            "defined": "1"
          },
          {
            "metric": "partitionResidual",
            "value": "0",
            "exactValue": "",
            "unit": "mass",
            "defined": "1"
          }
        ],
        "plotPoints": [
          {
            "series": "0",
            "index": "0",
            "xExact": "",
            "x": "0",
            "yExact": "",
            "y": "1",
            "id": "A"
          },
          {
            "series": "0",
            "index": "1",
            "xExact": "",
            "x": "1",
            "yExact": "",
            "y": "0",
            "id": "B"
          }
        ],
        "plotFile": "ml14-fixed-results/groups-six-cards-r/plot.svg",
        "plotSHA256": "f9f60e2b9b1461753a60632632da7212d492f22e5da31ae75fd26144474340aa",
        "files": [
          {
            "file": "ml14-fixed-results/groups-six-cards-r/full.txt",
            "sha256": "b63a23953b31dc749d58d9092282b4a64dfd2459d7d47adddd2a0ada92b9c98c",
            "bytes": 3350
          },
          {
            "file": "ml14-fixed-results/groups-six-cards-r/plot-points.csv",
            "sha256": "0f4866e96887cf3d03e5c8dea62b4d4f5d2156caa21537005c24394ee11eedea",
            "bytes": 95
          },
          {
            "file": "ml14-fixed-results/groups-six-cards-r/plot.svg",
            "sha256": "f9f60e2b9b1461753a60632632da7212d492f22e5da31ae75fd26144474340aa",
            "bytes": 1203
          },
          {
            "file": "ml14-fixed-results/groups-six-cards-r/summary.csv",
            "sha256": "239638065990d8482939d750a7fcdb85e690295eabd1b292483e005dde31f2e4",
            "bytes": 249
          }
        ],
        "scope": "Actually executed standalone fixed example, Python exact Fraction versus base-R binary64. Approximate R residuals retained; not universal exact arithmetic/web validation/native UI. Source programs read factual3CSV only."
      },
      "unknown-group": {
        "api": "groups",
        "variant": "unknown-group",
        "language": "r",
        "title": "Unknown group stays overall and preserves mass",
        "codeFile": "ml14-code/groups-unknown-group.R",
        "codeSHA256": "058307dfcf469be794bfbe1a053b797288ffdf2d85a4d437236aca498b613640",
        "code": "# ML14 standalone public counterpart, base R only.\n# Inputs are only the three factual CSVs; derived columns/previous model answers unused.\n# Binary64 arithmetic, not arbitrary-precision Fraction. At numerical cost ties\n# within 1e-12 retain the earliest candidate. Exact claims belong to Python/web.\n# SHA256 infrastructure below is reused verbatim from the previous public study.\nargs<-commandArgs(trailingOnly=TRUE);filearg<-grep(\"^--file=\",commandArgs(),value=TRUE)\nhere<-if(dir.exists(\"ml14-sources\"))getwd()else if(length(filearg))dirname(normalizePath(sub(\"^--file=\",\"\",filearg[1])))else getwd()\noption<-function(key,default){i<-match(key,args);if(is.na(i))default else args[i+1]}\nsourceDir<-option(\"--source\",file.path(here,\"ml14-sources\"));outDir<-option(\"--out\",file.path(getwd(),\"ml14-r-results\"));dir.create(outDir,recursive=TRUE,showWarnings=FALSE)\nnum<-function(x){x[x%in%c(\"\",\".\")]<-NA_character_;as.numeric(x)}\nfmt<-function(x)ifelse(is.na(x),\"\",sprintf(\"%.17g\",x))\nratio<-function(a,b)if(b==0)NA_real_ else a/b\nreadnative<-function(name)read.csv(file.path(sourceDir,name),check.names=FALSE,colClasses=\"character\",na.strings=character(),stringsAsFactors=FALSE)\n# Vectorized SHA256 for the short ASCII keys used in this study.\n# Unsigned words use exact integer-valued doubles; bit operations use safe\n# 16-bit halves, avoiding R's reserved signed-INT_MIN/NA representation.\nMOD<-2^32\nxor32<-function(a,b) as.double(bitwXor(as.integer(floor(a/65536)),as.integer(floor(b/65536))))*65536+as.double(bitwXor(as.integer(a%%65536),as.integer(b%%65536)))\nand32<-function(a,b) as.double(bitwAnd(as.integer(floor(a/65536)),as.integer(floor(b/65536))))*65536+as.double(bitwAnd(as.integer(a%%65536),as.integer(b%%65536)))\nrot<-function(x,n) floor(x/2^n)+(x%%2^n)*2^(32-n)\nxor3<-function(a,b,c) xor32(xor32(a,b),c)\nK<-c(0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5,0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967,0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070,0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3,0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2)\nsha256<-function(strings) {\n n<-length(strings);bytes<-matrix(0,n,64)\n for(i in seq_len(n)) {v<-utf8ToInt(strings[i]);stopifnot(length(v)<56,all(v<128));if(length(v)) bytes[i,seq_along(v)]<-v;bytes[i,length(v)+1]<-128;bits<-length(v)*8;bytes[i,61:64]<-c(floor(bits/2^24)%%256,floor(bits/2^16)%%256,floor(bits/256)%%256,bits%%256)}\n w<-matrix(0,n,64)\n for(j in 1:16) {b<-4*(j-1)+1;w[,j]<-bytes[,b]*2^24+bytes[,b+1]*2^16+bytes[,b+2]*256+bytes[,b+3]}\n for(j in 17:64) {s0<-xor3(rot(w[,j-15],7),rot(w[,j-15],18),floor(w[,j-15]/8));s1<-xor3(rot(w[,j-2],17),rot(w[,j-2],19),floor(w[,j-2]/1024));w[,j]<-(w[,j-16]+s0+w[,j-7]+s1)%%MOD}\n init<-c(0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19)\n state<-lapply(init,function(v) rep(v,n));a<-state[[1]];b<-state[[2]];c<-state[[3]];d<-state[[4]];e<-state[[5]];f<-state[[6]];g<-state[[7]];h<-state[[8]]\n for(j in 1:64) {S1<-xor3(rot(e,6),rot(e,11),rot(e,25));ch<-xor32(and32(e,f),and32(MOD-1-e,g));t1<-(h+S1+ch+K[j]+w[,j])%%MOD;S0<-xor3(rot(a,2),rot(a,13),rot(a,22));maj<-xor3(and32(a,b),and32(a,c),and32(b,c));t2<-(S0+maj)%%MOD;h<-g;g<-f;f<-e;e<-(d+t1)%%MOD;d<-c;c<-b;b<-a;a<-(t1+t2)%%MOD}\n end<-list(a,b,c,d,e,f,g,h);hex<-lapply(1:8,function(j){v<-(end[[j]]+init[j])%%MOD;paste0(sprintf(\"%04x\",as.integer(floor(v/65536))),sprintf(\"%04x\",as.integer(v%%65536)))})\n do.call(paste0,hex)\n}\nstopifnot(identical(sha256(c(\"abc\",\"\")),c(\"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad\",\"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855\")))\n\nloadData<-function(){\n wb<-readnative(\"actual64-country-four-indicators-original-2024.csv\");codes<-c(\"NY.GDP.PCAP.KD\",\"NY.GDP.MKTP.KD.ZG\",\"FP.CPI.TOTL.ZG\",\"SP.DYN.LE00.IN\");iso<-sort(unique(wb$countryISO3));stopifnot(nrow(wb)==64,length(iso)==16)\n tokens<-t(vapply(iso,function(s)wb$originalValueToken[match(paste(s,codes),paste(wb$countryISO3,wb$indicatorID))],character(4)));vals<-matrix(num(as.vector(tokens)),nrow=nrow(tokens))\n country<-list(id=paste0(iso,\":2024\"),sourceRow=1:16,originalID=iso,x=vals[,1:3,drop=FALSE],rawX=tokens[,1:3,drop=FALSE],nativeTarget=tokens[,4],y=as.integer(vals[,4]>=80),group=ifelse(is.na(vals[,1]),NA_character_,as.character(as.integer(vals[,1]>=25000))),lineage=vapply(iso,function(s)paste(wb$sourceRow[match(paste(s,codes),paste(wb$countryISO3,wb$indicatorID))],collapse=\";\"),character(1)),cat=integer(),units=c(\"constant2015USD/person\",\"annualPercent\",\"annualPercent\"))\n nls<-readnative(\"actual3613-NLS-original52-fields-groups-roles.csv\");raw<-cbind(nls$ed76,nls$age76,nls$nearc4)\n person<-list(id=paste0(\"person:\",nls$sourceRow),sourceRow=as.integer(nls$sourceRow),originalID=nls$id,x=matrix(num(as.vector(raw)),nrow=nrow(raw)),rawX=raw,nativeTarget=nls$wage76,y=as.integer(num(nls$wage76)>=500),group=ifelse(nls$black%in%c(\"\",\".\"),NA_character_,nls$black),lineage=nls$sourceRow,cat=2L,units=c(\"years\",\"years\",\"nativeCategory\"))\n ch<-readnative(\"actual3150-churn-original14-fields-groups-roles.csv\");raw<-cbind(ch[[\"Call  Failure\"]],ch$Complains,ch[[\"Subscription  Length\"]],ch[[\"Seconds of Use\"]])\n company<-list(id=paste0(\"customer:\",ch$sourceRow),sourceRow=as.integer(ch$sourceRow),originalID=rep(\"\",nrow(ch)),x=matrix(num(as.vector(raw)),nrow=nrow(raw)),rawX=raw,nativeTarget=ch$Churn,y=as.integer(ch$Churn),group=ifelse(ch[[\"Tariff Plan\"]]%in%c(\"\",\".\"),NA_character_,ch[[\"Tariff Plan\"]]),lineage=ch$sourceRow,cat=1L,units=c(\"count\",\"nativeCategory\",\"months\",\"seconds\"))\n stopifnot(nrow(nls)==3613,nrow(ch)==3150,identical(as.integer(ch$sourceRow[ch[[\"Charge  Amount\"]]==\"10\"]),c(474L,2174L,2274L,2374L,2674L,2924L,2974L)))\n result<-list(country=country,person=person,company=company)\n for(k in names(result)){d<-result[[k]];n<-length(d$id);d$eligible<-!is.na(d$y)&rowSums(is.na(d$x))==0;hash<-sha256(paste0(\"ML14-role|\",k,\"|\",d$id));rank<-integer(n);rank[order(hash,seq_len(n))]<-seq_len(n)-1L;d$plannedRole<-ifelse(rank%%5==0,\"test\",ifelse(rank%%5==1,\"validation\",\"train\"));d$role<-ifelse(d$eligible,d$plannedRole,\"excluded\");result[[k]]<-d}\n stopifnot(sum(result$person$eligible)==3017);result\n}\nfitmodel<-function(d){\n ids<-which(d$role==\"train\");p<-ncol(d$x);m<-vapply(seq_len(p),function(j)if((j-1)%in%d$cat)NA_real_ else median(d$x[ids,j]),numeric(1));z<-d$x\n for(j in seq_len(p))if(!((j-1)%in%d$cat))z[,j]<-as.numeric(z[,j]>m[j])\n keys<-apply(z,1,function(v)paste(fmt(v),collapse=\"|\"));lev<-unique(keys[ids]);mass<-vapply(lev,function(k)sum(keys[ids]==k),integer(1));positive<-vapply(lev,function(k)sum(d$y[ids][keys[ids]==k]),integer(1));prob<-(positive+1)/(mass+2);fallback<-(sum(d$y[ids])+1)/(length(ids)+2);pred<-prob[match(keys,lev)];unseen<-is.na(pred);pred[unseen]<-fallback;pred[!d$eligible]<-NA_real_;unseen[!d$eligible]<-NA\n list(ids=ids,medians=m,z=z,keys=keys,lev=lev,mass=mass,positive=positive,prob=prob,fallback=fallback,pred=pred,unseen=unseen)\n}\nmeasure<-function(d,p,ids,t=.5,cost=c(1,1)){\n use<-ids[d$eligible[ids]&!is.na(p[ids])];y<-d$y[use];a<-if(is.character(t))rep(t==\"always-positive\",length(use))else p[use]>=t\n TP<-sum(a&y==1);FP<-sum(a&y==0);FN<-sum(!a&y==1);TN<-sum(!a&y==0);P<-TP+FN;N<-FP+TN;W<-P+N;PP<-TP+FP;PN<-TN+FN;TPR<-ratio(TP,P);TNR<-ratio(TN,N);bs<-sum((p[use]-y)^2);tc<-FP*cost[1]+FN*cost[2]\n list(TP=TP,FP=FP,FN=FN,TN=TN,mass=W,positiveTargetMass=P,negativeTargetMass=N,predictedPositiveMass=PP,predictedNegativeMass=PN,prevalence=ratio(P,W),selectionRate=ratio(PP,W),accuracy=ratio(TP+TN,W),precision=ratio(TP,PP),negativePredictiveValue=ratio(TN,PN),TPR=TPR,FPR=ratio(FP,N),TNR=TNR,FNR=ratio(FN,P),F1=ratio(2*TP,2*TP+FP+FN),balancedAccuracy=if(is.na(TPR)||is.na(TNR))NA_real_ else(TPR+TNR)/2,Brier=ratio(bs,W),BrierSum=bs,totalCost=tc,meanCost=ratio(tc,W))\n}\ncurves<-function(d,p,ids){\n use<-ids[d$eligible[ids]&!is.na(p[ids])];scores<-sort(unique(p[use]),decreasing=TRUE);policies<-c(list(\"always-negative\"),as.list(scores));points<-lapply(policies,function(t){m<-measure(d,p,ids,t);c(list(policy=t),m[c(\"TP\",\"FP\",\"FN\",\"TN\",\"TPR\",\"FPR\",\"precision\")],list(recall=m$TPR))})\n pos<-use[d$y[use]==1];neg<-use[d$y[use]==0];U<-0;for(i in pos)U<-U+sum(p[i]>p[neg])+.5*sum(p[i]==p[neg])\n AP<-0;trap<-0;lastR<-0;lastP<-1\n if(length(pos)&&length(scores))for(j in seq_along(scores)){z<-points[[j+1]];AP<-AP+(z$recall-lastR)*z$precision;trap<-trap+(z$recall-lastR)*(z$precision+lastP)/2;lastR<-z$recall;lastP<-z$precision}\n list(points=points,ROC_AUC=ratio(U,length(pos)*length(neg)),averagePrecision=if(length(pos))AP else NA_real_,PRTrapezoidWithInitialPrecisionOne=if(length(pos))trap else NA_real_)\n}\ncalibrate<-function(d,p,ids){\n use<-ids[d$eligible[ids]&!is.na(p[ids])];W<-length(use);pi<-if(W)mean(d$y[use])else NA_real_;bins<-list();ECE<-rel<-res<-correction<-0\n whichbin<-findInterval(p[use],seq(0,1,.2),rightmost.closed=TRUE,all.inside=TRUE)\n for(b in 1:5){rr<-use[whichbin==b];w<-length(rr);mp<-if(w)mean(p[rr])else NA_real_;o<-if(w)mean(d$y[rr])else NA_real_;variance<-if(w)mean((p[rr]-mp)^2)else NA_real_;covariance<-if(w)mean((p[rr]-mp)*(d$y[rr]-o))else NA_real_;bc<-variance-2*covariance;gap<-mp-o\n  bins[[b]]<-list(mass=w,meanPrediction=mp,eventRate=o,gap=gap,absoluteGap=abs(gap),scoreVariance=variance,scoreTargetCovariance=covariance,withinBinCorrection=bc,rows=w,ids=d$id[rr])\n  if(w){share<-w/W;ECE<-ECE+share*abs(gap);rel<-rel+share*gap^2;res<-res+share*(o-pi)^2;correction<-correction+share*bc}\n };bs<-if(W)mean((p[use]-d$y[use])^2)else NA_real_;unc<-pi*(1-pi)\n list(bins=bins,ECE=if(W)ECE else NA_real_,Brier=bs,reliability=if(W)rel else NA_real_,resolution=if(W)res else NA_real_,uncertainty=unc,withinBinCorrection=if(W)correction else NA_real_,BrierIdentityResidual=bs-(unc-res+rel+correction))\n}\ncounts<-c(\"mass\",\"positiveTargetMass\",\"negativeTargetMass\",\"predictedPositiveMass\",\"predictedNegativeMass\");rates<-c(\"prevalence\",\"selectionRate\",\"accuracy\",\"precision\",\"negativePredictiveValue\",\"TPR\",\"FPR\",\"TNR\",\"FNR\",\"F1\",\"balancedAccuracy\",\"Brier\",\"BrierSum\",\"totalCost\",\"meanCost\")\ntables<-setNames(lapply(1:10,function(i)list()),c(\"predictions\",\"lineage\",\"fit-medians\",\"fit-cells\",\"validation-candidates\",\"test-metrics\",\"test-curves\",\"calibration-bins\",\"group-metrics\",\"chart-points\"))\nadd<-function(name,row)tables[[name]][[length(tables[[name]])+1L]]<<-row\nscalars<-function(m,keys){out<-list();for(k in keys){out[[paste0(k,\"Exact\")]]<-\"\";out[[paste0(k,\"Approx\")]]<-fmt(m[[k]])};out}\ntagrow<-function(kind,...)c(list(kind=kind),list(...))\npoint<-function(kind,chart,series,index,x,y,xunit=\"dimensionless\",yunit=\"dimensionless\",role=\"test\",tag=\"\"){add(\"chart-points\",tagrow(kind,chart=chart,series=series,index=index,xExact=\"\",xApprox=fmt(x),yExact=\"\",yApprox=fmt(y),xUnit=xunit,yUnit=yunit,role=role,tag=tag))}\nstudy<-function(kind,d){\n f<-fitmodel(d);n<-length(d$id);train<-which(d$role==\"train\");validation<-which(d$role==\"validation\");test<-which(d$role==\"test\");p<-f$pred;cv<-curves(d,p,test);cal<-calibrate(d,p,test)\n for(i in seq_len(n)){\n  reason<-if(d$eligible[i])\"\"else\"required-X-or-Y-missing\";transformed<-if(d$eligible[i])paste(fmt(f$z[i,]),collapse=\"|\")else\"\"\n  add(\"predictions\",tagrow(kind,id=d$id[i],sourceRow=d$sourceRow[i],originalID=d$originalID[i],plannedRole=d$plannedRole[i],role=d$role[i],group=ifelse(is.na(d$group[i]),\"\",d$group[i]),eligible=as.integer(d$eligible[i]),targetExact=fmt(d$y[i]),probabilityExact=\"\",probabilityApprox=fmt(p[i]),unseenCell=ifelse(is.na(f$unseen[i]),\"\",as.character(as.integer(f$unseen[i]))),transformedX=transformed,reason=reason))\n  raw<-d$rawX[i,];raw[raw%in%c(\"\",\".\")]<-\"\";nativeY<-d$nativeTarget[i];if(nativeY%in%c(\"\",\".\"))nativeY<-\"\"\n  add(\"lineage\",tagrow(kind,id=d$id[i],sourceRow=d$sourceRow[i],originalID=d$originalID[i],nativeSourceRows=d$lineage[i],rawX=paste(raw,collapse=\"|\"),nativeTarget=nativeY,derivedTarget=fmt(d$y[i]),nativeGroup=ifelse(is.na(d$group[i]),\"\",d$group[i]),plannedRole=d$plannedRole[i],role=d$role[i],eligible=as.integer(d$eligible[i]),analyticalMass=\"1\",reason=reason))\n }\n for(j in seq_len(ncol(d$x)))add(\"fit-medians\",tagrow(kind,feature=j-1,categorical=as.integer((j-1)%in%d$cat),fitRows=length(train),medianExact=\"\",medianApprox=fmt(f$medians[j]),unit=d$units[j]))\n for(j in seq_along(f$lev))add(\"fit-cells\",tagrow(kind,cell=f$lev[j],trainingRows=f$mass[j],positiveRows=f$positive[j],probabilityExact=\"\",probabilityApprox=fmt(f$prob[j]),fallbackExact=\"\",fallbackApprox=fmt(f$fallback)))\n for(j in seq_along(cv$points)){\n  z<-cv$points[[j]];t<-z$policy;add(\"test-curves\",c(tagrow(kind,point=j-1,policy=if(is.character(t))t else\"threshold\",thresholdExact=\"\",thresholdApprox=if(is.character(t))\"\"else fmt(t)),scalars(z,c(\"TP\",\"FP\",\"FN\",\"TN\",\"TPR\",\"FPR\",\"precision\",\"recall\"))))\n  point(kind,\"roc\",\"ROC\",j-1,z$FPR,z$TPR);point(kind,\"pr\",\"PR-observed\",j-1,z$recall,z$precision)\n }\n for(b in 1:5){z<-cal$bins[[b]];add(\"calibration-bins\",c(tagrow(kind,bin=b-1,leftExact=c(\"0\",\"1/5\",\"2/5\",\"3/5\",\"4/5\")[b],rightExact=c(\"1/5\",\"2/5\",\"3/5\",\"4/5\",\"1\")[b],rightClosed=as.integer(b==5),rows=z$rows,ids=paste(z$ids,collapse=\";\")),scalars(z,c(\"mass\",\"meanPrediction\",\"eventRate\",\"gap\",\"absoluteGap\",\"scoreVariance\",\"scoreTargetCovariance\",\"withinBinCorrection\"))));point(kind,\"reliability\",\"Binary event rate\",b-1,z$meanPrediction,z$eventRate,tag=paste0(\"rows=\",z$rows))}\n for(j in seq_along(test)){i<-test[j];point(kind,\"test-scores\",\"Training-fitted probability\",j-1,j,p[i],\"test-row position\",\"probability\",tag=d$id[i]);point(kind,\"test-scores\",\"Observed Y\",j-1,j,d$y[i],\"test-row position\",\"binary target\",tag=d$id[i])}\n scenarioNames<-c(\"equal\",\"miss-five\",\"alarm-five\");costs<-list(c(1,1),c(1,5),c(5,1))\n for(s in 1:3){name<-scenarioNames[s];cost<-costs[[s]];grid<-c(list(\"always-negative\"),as.list(sort(unique(p[validation]),decreasing=TRUE)));candidates<-lapply(grid,function(t)measure(d,p,validation,t,cost));values<-vapply(candidates,function(m)m$meanCost,numeric(1));best<-which(values<=min(values)+1e-12)[1];chosen<-grid[[best]];ev<-measure(d,p,test,chosen,cost)\n  for(j in seq_along(grid)){t<-grid[[j]];m<-candidates[[j]];cell<-setNames(lapply(c(\"TP\",\"FP\",\"FN\",\"TN\"),function(k)fmt(m[[k]])),paste0(c(\"TP\",\"FP\",\"FN\",\"TN\"),\"Exact\"));add(\"validation-candidates\",c(tagrow(kind,scenario=name,candidate=j-1,selected=as.integer(j==best),policy=if(is.character(t))t else\"threshold\",thresholdExact=\"\",thresholdApprox=if(is.character(t))\"\"else fmt(t),feasible=1,reasons=\"\"),cell,scalars(m,c(counts,\"TPR\",\"FPR\",\"precision\",\"meanCost\",\"totalCost\"))));point(kind,\"validation-cost\",name,j-1,j-1,m$meanCost,\"candidate index\",\"hypothetical cost units/mass\",\"validation\",if(is.character(t))t else fmt(t))}\n  m<-c(ev,cv[c(\"ROC_AUC\",\"averagePrecision\",\"PRTrapezoidWithInitialPrecisionOne\")],cal[c(\"ECE\",\"reliability\",\"resolution\",\"uncertainty\",\"withinBinCorrection\",\"BrierIdentityResidual\")])\n  for(k in c(\"TP\",\"FP\",\"FN\",\"TN\",counts,rates,\"ROC_AUC\",\"averagePrecision\",\"PRTrapezoidWithInitialPrecisionOne\",\"ECE\",\"reliability\",\"resolution\",\"uncertainty\",\"withinBinCorrection\",\"BrierIdentityResidual\")){\n   unit<-if(k%in%c(\"TP\",\"FP\",\"FN\",\"TN\",counts))\"rows\"else if(k==\"totalCost\")\"hypothetical cost units\"else if(k==\"meanCost\")\"hypothetical cost units/mass\"else if(k==\"BrierSum\")\"sum squared-probability loss\"else\"dimensionless\"\n   add(\"test-metrics\",tagrow(kind,scenario=name,metric=k,valueExact=\"\",valueApprox=fmt(m[[k]]),unit=unit))\n  }\n  lev<-unique(d$group[test][!is.na(d$group[test])]);sets<-c(list(test),lapply(lev,function(g)test[!is.na(d$group[test])&d$group[test]==g]),list(test[is.na(d$group[test])]))\n  types<-c(\"overall\",rep(\"known\",length(lev)),\"unknown\");tokens<-c(\"all\",lev,\"\")\n  for(j in seq_along(sets)){ids<-sets[[j]];m<-measure(d,p,ids,chosen,cost);cell<-setNames(lapply(c(\"TP\",\"FP\",\"FN\",\"TN\"),function(k)fmt(m[[k]])),paste0(c(\"TP\",\"FP\",\"FN\",\"TN\"),\"Exact\"));add(\"group-metrics\",c(tagrow(kind,scenario=name,groupType=types[j],groupToken=tokens[j],retainedRows=length(ids)),cell,scalars(m,c(counts,rates))));if(types[j]==\"known\")point(kind,\"group-TPR\",name,j-2,j-2,m$TPR,\"declared group position\",\"TPR\",tag=tokens[j])}\n }\n invisible(NULL)\n}\n\n# Fixed finite inputs only; not the complete web input/budget validator.\nqnum<-function(v){if(is.null(v))return(NA_real_);if(is.logical(v))return(as.numeric(v));s<-as.character(v);if(grepl(\"/\",s,fixed=TRUE)){a<-strsplit(s,\"/\",fixed=TRUE)[[1]];return(as.numeric(a[1])/as.numeric(a[2]))};as.numeric(s)}\nrowsG<-function(raw){\n n<-length(raw);get<-function(r,k,default=NULL)if(is.null(r[[k]]))default else r[[k]]\n id<-vapply(raw,function(r)as.character(r$id),character(1));p<-vapply(raw,function(r)qnum(r$score),numeric(1));y<-vapply(raw,function(r)qnum(r$y),numeric(1));w<-vapply(raw,function(r)qnum(get(r,\"weight\",\"1\")),numeric(1));role<-vapply(raw,function(r)get(r,\"role\",\"evaluation\"),character(1));group<-vapply(raw,function(r)as.character(get(r,\"group\",NA_character_)),character(1))\n stopifnot(all(w>=0),all(is.na(p)|(p>=0&p<=1)),all(is.na(y)|y%in%c(0,1)),!anyDuplicated(id));list(id=id,p=p,y=y,w=w,role=role,group=group,eligible=!is.na(p)&!is.na(y)&w>0&role!=\"excluded\")\n}\nscopeG<-function(d,role=\"all\")if(role==\"all\")seq_along(d$id)else which(d$role==role)\nmetricsG<-function(d,ids,t=.5,cost=c(1,1)){\n use<-ids[d$eligible[ids]];p<-d$p[use];y<-d$y[use];w<-d$w[use];a<-if(is.character(t))rep(t==\"always-positive\",length(use))else p>=t\n TP<-sum(w[a&y==1]);FP<-sum(w[a&y==0]);FN<-sum(w[!a&y==1]);TN<-sum(w[!a&y==0]);P<-TP+FN;N<-FP+TN;W<-P+N;PP<-TP+FP;PN<-TN+FN;TPR<-ratio(TP,P);TNR<-ratio(TN,N);bs<-sum(w*(p-y)^2);tc<-FP*cost[1]+FN*cost[2]\n list(confusion=list(TP=TP,FP=FP,FN=FN,TN=TN),mass=W,positiveTargetMass=P,negativeTargetMass=N,predictedPositiveMass=PP,predictedNegativeMass=PN,prevalence=ratio(P,W),selectionRate=ratio(PP,W),accuracy=ratio(TP+TN,W),precision=ratio(TP,PP),negativePredictiveValue=ratio(TN,PN),TPR=TPR,FPR=ratio(FP,N),TNR=TNR,FNR=ratio(FN,P),F1=ratio(2*TP,2*TP+FP+FN),balancedAccuracy=if(is.na(TPR)||is.na(TNR))NA_real_ else(TPR+TNR)/2,Brier=ratio(bs,W),BrierSum=bs,totalCost=tc,meanCost=ratio(tc,W),bayesThreshold=ratio(cost[1],sum(cost)))\n}\ncurvesG<-function(d,ids){\n use<-ids[d$eligible[ids]];grid<-c(list(\"always-negative\"),as.list(sort(unique(d$p[use]),decreasing=TRUE)));points<-lapply(grid,function(t){m<-metricsG(d,ids,t);c(list(policy=t),m$confusion,m[c(\"TPR\",\"FPR\",\"precision\")],list(recall=m$TPR))});pos<-use[d$y[use]==1];neg<-use[d$y[use]==0];P<-sum(d$w[pos]);N<-sum(d$w[neg]);U<-0\n for(i in pos)U<-U+d$w[i]*sum(d$w[neg]*((d$p[i]>d$p[neg])+.5*(d$p[i]==d$p[neg])))\n AP<-trap<-lastR<-0;lastP<-1\n if(P&&length(grid)>1)for(j in 2:length(grid)){z<-points[[j]];AP<-AP+(z$recall-lastR)*z$precision;trap<-trap+(z$recall-lastR)*(z$precision+lastP)/2;lastR<-z$recall;lastP<-z$precision}\n list(points=points,ROC_AUC=ratio(U,P*N),averagePrecision=if(P)AP else NA_real_,PRTrapezoidWithInitialPrecisionOne=if(P)trap else NA_real_)\n}\nchooseG<-function(d,a,cost){\n role<-if(is.null(a$selectionRole))\"validation\"else a$selectionRole;er<-if(is.null(a$evaluationRole))\"test\"else a$evaluationRole;ids<-scopeG(d,role);use<-ids[d$eligible[ids]];stopifnot(length(use)>0);grid<-if(is.null(a$thresholds))c(list(\"always-negative\"),as.list(sort(unique(d$p[use]),decreasing=TRUE)))else lapply(a$thresholds,function(t)if(t%in%c(\"always-negative\",\"always-positive\"))t else qnum(t))\n candidates<-lapply(seq_along(grid),function(j){m<-metricsG(d,ids,grid[[j]],cost);feasible<-TRUE;if(!is.null(a$minTPR))feasible<-feasible&&!is.na(m$TPR)&&m$TPR>=qnum(a$minTPR);if(!is.null(a$maxFPR))feasible<-feasible&&!is.na(m$FPR)&&m$FPR<=qnum(a$maxFPR);list(index=j-1,policy=grid[[j]],metrics=m,feasible=feasible)})\n good<-which(vapply(candidates,function(c)c$feasible,logical(1)));best<-NA_integer_;if(length(good)){v<-vapply(candidates[good],function(c)c$metrics$meanCost,numeric(1));best<-good[which(v<=min(v)+1e-12)[1]]}\n list(selectedIndex=if(is.na(best))NA_integer_ else best-1,selectedPolicy=if(is.na(best))NULL else grid[[best]],selectedValidation=if(is.na(best))NULL else candidates[[best]]$metrics,candidates=candidates,evaluation=if(is.na(best)||er==\"none\")NULL else metricsG(d,scopeG(d,er),grid[[best]],cost))\n}\ncalibrateG<-function(d,ids,edges){\n use<-ids[d$eligible[ids]];W<-sum(d$w[use]);pi<-ratio(sum(d$w[use]*d$y[use]),W);bins<-list();ECE<-rel<-res<-correction<-0;assign<-findInterval(d$p[use],edges,rightmost.closed=TRUE,all.inside=TRUE)\n for(b in seq_len(length(edges)-1)){rr<-use[assign==b];w<-sum(d$w[rr]);mp<-ratio(sum(d$w[rr]*d$p[rr]),w);o<-ratio(sum(d$w[rr]*d$y[rr]),w);variance<-if(w)sum(d$w[rr]*(d$p[rr]-mp)^2)/w else NA_real_;covariance<-if(w)sum(d$w[rr]*(d$p[rr]-mp)*(d$y[rr]-o))/w else NA_real_;bc<-variance-2*covariance;gap<-mp-o;bins[[b]]<-list(index=b-1,mass=w,meanPrediction=mp,eventRate=o,scoreVariance=variance,scoreTargetCovariance=covariance,withinBinCorrection=bc,ids=d$id[rr])\n  if(w){s<-w/W;ECE<-ECE+s*abs(gap);rel<-rel+s*gap^2;res<-res+s*(o-pi)^2;correction<-correction+s*bc}\n };bs<-ratio(sum(d$w[use]*(d$p[use]-d$y[use])^2),W);unc<-pi*(1-pi);list(bins=bins,Brier=bs,ECE=if(W)ECE else NA_real_,uncertainty=unc,reliability=if(W)rel else NA_real_,resolution=if(W)res else NA_real_,withinBinCorrection=if(W)correction else NA_real_,BrierIdentityResidual=bs-(unc-res+rel+correction))\n}\ngroupsG<-function(d,ids,t,cost){\n lev<-unique(d$group[ids][!is.na(d$group[ids])]);groups<-lapply(lev,function(g)list(group=g,metrics=metricsG(d,ids[!is.na(d$group[ids])&d$group[ids]==g],t,cost)));overall<-metricsG(d,ids,t,cost);unknown<-metricsG(d,ids[is.na(d$group[ids])],t,cost);gaps<-list()\n for(k in c(\"prevalence\",\"selectionRate\",\"TPR\",\"FPR\",\"precision\",\"accuracy\",\"meanCost\")){use<-Filter(function(g)g$metrics$mass>0,groups);v<-vapply(use,function(g)g$metrics[[k]],numeric(1));gaps[[k]]<-if(length(use)<2||anyNA(v))NA_real_ else max(v)-min(v)}\n list(overall=overall,groups=groups,unknownGroup=unknown,gaps=gaps,partitionMassResidual=overall$mass-unknown$mass-sum(vapply(groups,function(g)g$metrics$mass,numeric(1))))\n}\nsvgFixed<-function(file,points,title,xlabel,ylabel,legend){\n finite<-points[points$y!=\"undefined\"&points$x!=\"undefined\",,drop=FALSE];x<-as.numeric(finite$x);y<-as.numeric(finite$y);xmin<-if(length(x))min(x)else 0;xmax<-if(length(x))max(x)else 1;ymin<-min(c(0,y));ymax<-max(c(0,y));if(xmin==xmax){xmin<-xmin-.5;xmax<-xmax+.5};if(ymin==ymax)ymax<-ymin+1;X<-function(v)85+(v-xmin)/(xmax-xmin)*480;Y<-function(v)278-(v-ymin)/(ymax-ymin)*175\n esc<-function(s){s<-gsub(\"&\",\"&amp;\",s,fixed=TRUE);s<-gsub(\"<\",\"&lt;\",s,fixed=TRUE);gsub(\">\",\"&gt;\",s,fixed=TRUE)};s<-'<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"620\" height=\"360\" viewBox=\"0 0 620 360\"><rect width=\"620\" height=\"360\" fill=\"white\"/><g font-family=\"Arial, sans-serif\" font-size=\"13\" fill=\"#17324d\">'\n lines<-strwrap(title,width=65);for(i in seq_along(lines))s<-paste0(s,'<text x=\"25\" y=\"',24+(i-1)*18,'\">',esc(lines[i]),'</text>');colors<-c(\"#176b9b\",\"#b85e18\",\"#437e4d\")\n for(i in seq_along(legend))s<-paste0(s,'<circle cx=\"',30+(i-1)*250,'\" cy=\"76\" r=\"4\" fill=\"',colors[(i-1)%%3+1],'\"/><text x=\"',42+(i-1)*250,'\" y=\"80\">',esc(legend[i]),'</text>')\n s<-paste0(s,'<path d=\"M85 98V278H575\" fill=\"none\" stroke=\"#52677d\"/><text text-anchor=\"middle\" x=\"325\" y=\"338\">',esc(xlabel),'</text><text text-anchor=\"middle\" transform=\"translate(21,190) rotate(-90)\">',esc(ylabel),'</text>')\n for(i in 0:4){xx<-xmin+(xmax-xmin)*i/4;yy<-ymin+(ymax-ymin)*i/4;s<-paste0(s,'<text text-anchor=\"middle\" x=\"',sprintf(\"%.9g\",X(xx)),'\" y=\"305\">',sprintf(\"%.4g\",xx),'</text><text text-anchor=\"end\" x=\"77\" y=\"',sprintf(\"%.9g\",Y(yy)+4),'\">',sprintf(\"%.4g\",yy),'</text>')}\n for(i in seq_len(nrow(finite)))s<-paste0(s,'<circle cx=\"',sprintf(\"%.9g\",X(x[i])),'\" cy=\"',sprintf(\"%.9g\",Y(y[i])),'\" r=\"3\" fill=\"',colors[as.integer(finite$series[i])%%3+1],'\"/>');writeLines(paste0(s,'</g></svg>'),file,useBytes=TRUE)\n}\nfixedRun<-function(){\n api<-FIXED$api;a<-FIXED$args;summary<-list();points<-list();xlabel<-\"Declared index\";ylabel<-\"Value\";legend<-\"Declared result\"\n metric<-function(name,v,unit=\"dimensionless\"){if(is.null(v))v<-NA_real_;summary[[length(summary)+1L]]<<-data.frame(metric=name,value=if(is.na(v))\"undefined\"else sprintf(\"%.9g\",v),exactValue=\"\",unit=unit,defined=as.integer(!is.na(v)),stringsAsFactors=FALSE)}\n pt<-function(i,x,y,id=\"\",series=0){points[[length(points)+1L]]<<-data.frame(series=series,index=i,xExact=\"\",x=if(is.na(x))\"undefined\"else sprintf(\"%.9g\",x),yExact=\"\",y=if(is.na(y))\"undefined\"else sprintf(\"%.9g\",y),id=as.character(id),stringsAsFactors=FALSE)}\n if(api==\"realdata\"){\n  native<-loadData()[[a$kind]];fit<-fitmodel(native);d<-list(id=native$id,p=fit$pred,y=native$y,w=rep(1,length(native$id)),role=native$role,group=native$group,eligible=native$eligible);scenarios<-list()\n  for(j in 1:3){name<-c(\"equal\",\"miss-five\",\"alarm-five\")[j];cst<-list(c(1,1),c(1,5),c(5,1))[[j]];sel<-chooseG(d,list(),cst);scenarios[[j]]<-list(name=name,selection=sel);metric(paste0(name,\"Threshold\"),sel$selectedPolicy);metric(paste0(name,\"TestCost\"),sel$evaluation$meanCost,\"hypothetical cost units/mass\")}\n  ids<-scopeG(d,\"test\");cv<-curvesG(d,ids);cal<-calibrateG(d,ids,seq(0,1,.2));metric(\"testAUC\",cv$ROC_AUC);metric(\"testAP\",cv$averagePrecision);metric(\"testBrier\",cal$Brier);metric(\"eligibleRows\",sum(d$eligible),\"rows\")\n  for(j in seq_along(ids)){i<-ids[j];pt(j-1,j,d$p[i],d$id[i],0);pt(j-1,j,d$y[i],d$id[i],1)}\n  full<-list(kind=a$kind,fit=fit,scenarios=scenarios,testCurves=cv,testCalibration=cal,rowsScored=d);xlabel<-\"Test row, native order\";ylabel<-\"Y or probability\";legend<-c(\"Training-fitted probability\",\"Observed Y\")\n }else{\n  d<-rowsG(a$rows);role<-if(is.null(a$role))\"all\"else a$role;ids<-scopeG(d,role);cost<-if(is.null(a$costs))c(1,1)else c(qnum(a$costs$falsePositive),qnum(a$costs$falseNegative));t<-if(is.null(a$threshold)).5 else if(a$threshold%in%c(\"always-positive\",\"always-negative\"))a$threshold else qnum(a$threshold)\n  if(api==\"metrics\"){\n   full<-metricsG(d,ids,t,cost);for(k in c(\"mass\",\"accuracy\",\"precision\",\"TPR\",\"FPR\",\"F1\",\"Brier\",\"meanCost\"))metric(k,full[[k]],if(k==\"mass\")\"mass\"else if(k==\"meanCost\")\"hypothetical cost units/mass\"else\"dimensionless\");metric(\"BayesThreshold\",full$bayesThreshold)\n   for(i in 1:4)pt(i-1,i-1,full$confusion[[i]],names(full$confusion)[i]);xlabel<-\"TP / FP / FN / TN positions\";ylabel<-\"Analytical mass\"\n  }else if(api==\"curves\"){\n   full<-curvesG(d,ids);for(k in c(\"ROC_AUC\",\"averagePrecision\",\"PRTrapezoidWithInitialPrecisionOne\"))metric(k,full[[k]])\n   for(j in seq_along(full$points)){p<-full$points[[j]];pt(j-1,p$FPR,p$TPR,if(is.character(p$policy))p$policy else sprintf(\"%.17g\",p$policy))};xlabel<-\"False positive rate\";ylabel<-\"True positive rate\";legend<-\"Observed ROC operating points\"\n  }else if(api==\"choose\"){\n   full<-chooseG(d,a,cost);metric(\"selectedIndex\",full$selectedIndex,\"candidate index\");metric(\"minimumCost\",if(is.null(full$selectedValidation))NULL else full$selectedValidation$meanCost,\"hypothetical cost units/mass\");metric(\"feasible\",as.integer(!is.na(full$selectedIndex)),\"indicator\")\n   for(c in full$candidates)pt(c$index,c$index,c$metrics$meanCost,if(is.character(c$policy))c$policy else sprintf(\"%.17g\",c$policy));xlabel<-\"Validation candidate\";ylabel<-\"Assumed cost / mass\";legend<-\"Validation candidate costs\"\n  }else if(api==\"calibrate\"){\n   edges<-if(is.null(a$binEdges))seq(0,1,.2)else vapply(a$binEdges,qnum,numeric(1));full<-calibrateG(d,ids,edges);for(k in c(\"ECE\",\"Brier\",\"uncertainty\",\"resolution\",\"reliability\",\"withinBinCorrection\",\"BrierIdentityResidual\"))metric(k,full[[k]])\n   for(b in full$bins)pt(b$index,b$meanPrediction,b$eventRate,paste0(\"bin:\",b$index));xlabel<-\"Bin mean forecast\";ylabel<-\"Bin event rate\";legend<-\"Binary-event reliability\"\n  }else if(api==\"groups\"){\n   full<-groupsG(d,ids,t,cost);metric(\"overallTPR\",full$overall$TPR);metric(\"TPRGap\",full$gaps$TPR);metric(\"precisionGap\",full$gaps$precision);metric(\"unknownMass\",full$unknownGroup$mass,\"mass\");metric(\"partitionResidual\",full$partitionMassResidual,\"mass\")\n   for(j in seq_along(full$groups))pt(j-1,j-1,full$groups[[j]]$metrics$TPR,full$groups[[j]]$group);xlabel<-\"Declared group position\";ylabel<-\"True positive rate\";legend<-\"Known-group TPR\"\n  }else stop(\"unknown declared fixed API\")\n }\n sm<-do.call(rbind,summary);pp<-do.call(rbind,points);write.csv(sm,file.path(outDir,\"summary.csv\"),row.names=FALSE,na=\"\");write.csv(pp,file.path(outDir,\"plot-points.csv\"),row.names=FALSE,na=\"\");svgFixed(file.path(outDir,\"plot.svg\"),pp,FIXED$title,xlabel,ylabel,legend);dput(list(api=api,variant=FIXED$variant,input=FIXED$args,arithmetic=\"Base-R binary64 fixed example; not an exact rational general validator\",result=full),file=file.path(outDir,\"full.txt\"));cat(\"PASS\",api,FIXED$variant,\"summary\",nrow(sm),\"points\",nrow(pp),\"\\n\")\n}\n\nFIXED<-list(api=\"groups\",variant=\"unknown-group\",args=list(rows=list(list(id=\"a\",score=\".9\",y=1,group=\"A\"),list(id=\"b\",score=\".8\",y=1,group=\"A\"),list(id=\"c\",score=\".8\",y=0,group=\"A\"),list(id=\"d\",score=\".6\",y=0,group=\"B\"),list(id=\"e\",score=\".4\",y=1,group=\"B\"),list(id=\"f\",score=\".1\",y=0,group=NULL)),threshold=\".4\"),title=\"Unknown group stays overall and preserves mass\")\nfixedRun()\n",
        "codeText": "# ML14 standalone public counterpart, base R only.\n# Inputs are only the three factual CSVs; derived columns/previous model answers unused.\n# Binary64 arithmetic, not arbitrary-precision Fraction. At numerical cost ties\n# within 1e-12 retain the earliest candidate. Exact claims belong to Python/web.\n# SHA256 infrastructure below is reused verbatim from the previous public study.\nargs<-commandArgs(trailingOnly=TRUE);filearg<-grep(\"^--file=\",commandArgs(),value=TRUE)\nhere<-if(dir.exists(\"ml14-sources\"))getwd()else if(length(filearg))dirname(normalizePath(sub(\"^--file=\",\"\",filearg[1])))else getwd()\noption<-function(key,default){i<-match(key,args);if(is.na(i))default else args[i+1]}\nsourceDir<-option(\"--source\",file.path(here,\"ml14-sources\"));outDir<-option(\"--out\",file.path(getwd(),\"ml14-r-results\"));dir.create(outDir,recursive=TRUE,showWarnings=FALSE)\nnum<-function(x){x[x%in%c(\"\",\".\")]<-NA_character_;as.numeric(x)}\nfmt<-function(x)ifelse(is.na(x),\"\",sprintf(\"%.17g\",x))\nratio<-function(a,b)if(b==0)NA_real_ else a/b\nreadnative<-function(name)read.csv(file.path(sourceDir,name),check.names=FALSE,colClasses=\"character\",na.strings=character(),stringsAsFactors=FALSE)\n# Vectorized SHA256 for the short ASCII keys used in this study.\n# Unsigned words use exact integer-valued doubles; bit operations use safe\n# 16-bit halves, avoiding R's reserved signed-INT_MIN/NA representation.\nMOD<-2^32\nxor32<-function(a,b) as.double(bitwXor(as.integer(floor(a/65536)),as.integer(floor(b/65536))))*65536+as.double(bitwXor(as.integer(a%%65536),as.integer(b%%65536)))\nand32<-function(a,b) as.double(bitwAnd(as.integer(floor(a/65536)),as.integer(floor(b/65536))))*65536+as.double(bitwAnd(as.integer(a%%65536),as.integer(b%%65536)))\nrot<-function(x,n) floor(x/2^n)+(x%%2^n)*2^(32-n)\nxor3<-function(a,b,c) xor32(xor32(a,b),c)\nK<-c(0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5,0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967,0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070,0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3,0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2)\nsha256<-function(strings) {\n n<-length(strings);bytes<-matrix(0,n,64)\n for(i in seq_len(n)) {v<-utf8ToInt(strings[i]);stopifnot(length(v)<56,all(v<128));if(length(v)) bytes[i,seq_along(v)]<-v;bytes[i,length(v)+1]<-128;bits<-length(v)*8;bytes[i,61:64]<-c(floor(bits/2^24)%%256,floor(bits/2^16)%%256,floor(bits/256)%%256,bits%%256)}\n w<-matrix(0,n,64)\n for(j in 1:16) {b<-4*(j-1)+1;w[,j]<-bytes[,b]*2^24+bytes[,b+1]*2^16+bytes[,b+2]*256+bytes[,b+3]}\n for(j in 17:64) {s0<-xor3(rot(w[,j-15],7),rot(w[,j-15],18),floor(w[,j-15]/8));s1<-xor3(rot(w[,j-2],17),rot(w[,j-2],19),floor(w[,j-2]/1024));w[,j]<-(w[,j-16]+s0+w[,j-7]+s1)%%MOD}\n init<-c(0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19)\n state<-lapply(init,function(v) rep(v,n));a<-state[[1]];b<-state[[2]];c<-state[[3]];d<-state[[4]];e<-state[[5]];f<-state[[6]];g<-state[[7]];h<-state[[8]]\n for(j in 1:64) {S1<-xor3(rot(e,6),rot(e,11),rot(e,25));ch<-xor32(and32(e,f),and32(MOD-1-e,g));t1<-(h+S1+ch+K[j]+w[,j])%%MOD;S0<-xor3(rot(a,2),rot(a,13),rot(a,22));maj<-xor3(and32(a,b),and32(a,c),and32(b,c));t2<-(S0+maj)%%MOD;h<-g;g<-f;f<-e;e<-(d+t1)%%MOD;d<-c;c<-b;b<-a;a<-(t1+t2)%%MOD}\n end<-list(a,b,c,d,e,f,g,h);hex<-lapply(1:8,function(j){v<-(end[[j]]+init[j])%%MOD;paste0(sprintf(\"%04x\",as.integer(floor(v/65536))),sprintf(\"%04x\",as.integer(v%%65536)))})\n do.call(paste0,hex)\n}\nstopifnot(identical(sha256(c(\"abc\",\"\")),c(\"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad\",\"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855\")))\n\nloadData<-function(){\n wb<-readnative(\"actual64-country-four-indicators-original-2024.csv\");codes<-c(\"NY.GDP.PCAP.KD\",\"NY.GDP.MKTP.KD.ZG\",\"FP.CPI.TOTL.ZG\",\"SP.DYN.LE00.IN\");iso<-sort(unique(wb$countryISO3));stopifnot(nrow(wb)==64,length(iso)==16)\n tokens<-t(vapply(iso,function(s)wb$originalValueToken[match(paste(s,codes),paste(wb$countryISO3,wb$indicatorID))],character(4)));vals<-matrix(num(as.vector(tokens)),nrow=nrow(tokens))\n country<-list(id=paste0(iso,\":2024\"),sourceRow=1:16,originalID=iso,x=vals[,1:3,drop=FALSE],rawX=tokens[,1:3,drop=FALSE],nativeTarget=tokens[,4],y=as.integer(vals[,4]>=80),group=ifelse(is.na(vals[,1]),NA_character_,as.character(as.integer(vals[,1]>=25000))),lineage=vapply(iso,function(s)paste(wb$sourceRow[match(paste(s,codes),paste(wb$countryISO3,wb$indicatorID))],collapse=\";\"),character(1)),cat=integer(),units=c(\"constant2015USD/person\",\"annualPercent\",\"annualPercent\"))\n nls<-readnative(\"actual3613-NLS-original52-fields-groups-roles.csv\");raw<-cbind(nls$ed76,nls$age76,nls$nearc4)\n person<-list(id=paste0(\"person:\",nls$sourceRow),sourceRow=as.integer(nls$sourceRow),originalID=nls$id,x=matrix(num(as.vector(raw)),nrow=nrow(raw)),rawX=raw,nativeTarget=nls$wage76,y=as.integer(num(nls$wage76)>=500),group=ifelse(nls$black%in%c(\"\",\".\"),NA_character_,nls$black),lineage=nls$sourceRow,cat=2L,units=c(\"years\",\"years\",\"nativeCategory\"))\n ch<-readnative(\"actual3150-churn-original14-fields-groups-roles.csv\");raw<-cbind(ch[[\"Call  Failure\"]],ch$Complains,ch[[\"Subscription  Length\"]],ch[[\"Seconds of Use\"]])\n company<-list(id=paste0(\"customer:\",ch$sourceRow),sourceRow=as.integer(ch$sourceRow),originalID=rep(\"\",nrow(ch)),x=matrix(num(as.vector(raw)),nrow=nrow(raw)),rawX=raw,nativeTarget=ch$Churn,y=as.integer(ch$Churn),group=ifelse(ch[[\"Tariff Plan\"]]%in%c(\"\",\".\"),NA_character_,ch[[\"Tariff Plan\"]]),lineage=ch$sourceRow,cat=1L,units=c(\"count\",\"nativeCategory\",\"months\",\"seconds\"))\n stopifnot(nrow(nls)==3613,nrow(ch)==3150,identical(as.integer(ch$sourceRow[ch[[\"Charge  Amount\"]]==\"10\"]),c(474L,2174L,2274L,2374L,2674L,2924L,2974L)))\n result<-list(country=country,person=person,company=company)\n for(k in names(result)){d<-result[[k]];n<-length(d$id);d$eligible<-!is.na(d$y)&rowSums(is.na(d$x))==0;hash<-sha256(paste0(\"ML14-role|\",k,\"|\",d$id));rank<-integer(n);rank[order(hash,seq_len(n))]<-seq_len(n)-1L;d$plannedRole<-ifelse(rank%%5==0,\"test\",ifelse(rank%%5==1,\"validation\",\"train\"));d$role<-ifelse(d$eligible,d$plannedRole,\"excluded\");result[[k]]<-d}\n stopifnot(sum(result$person$eligible)==3017);result\n}\nfitmodel<-function(d){\n ids<-which(d$role==\"train\");p<-ncol(d$x);m<-vapply(seq_len(p),function(j)if((j-1)%in%d$cat)NA_real_ else median(d$x[ids,j]),numeric(1));z<-d$x\n for(j in seq_len(p))if(!((j-1)%in%d$cat))z[,j]<-as.numeric(z[,j]>m[j])\n keys<-apply(z,1,function(v)paste(fmt(v),collapse=\"|\"));lev<-unique(keys[ids]);mass<-vapply(lev,function(k)sum(keys[ids]==k),integer(1));positive<-vapply(lev,function(k)sum(d$y[ids][keys[ids]==k]),integer(1));prob<-(positive+1)/(mass+2);fallback<-(sum(d$y[ids])+1)/(length(ids)+2);pred<-prob[match(keys,lev)];unseen<-is.na(pred);pred[unseen]<-fallback;pred[!d$eligible]<-NA_real_;unseen[!d$eligible]<-NA\n list(ids=ids,medians=m,z=z,keys=keys,lev=lev,mass=mass,positive=positive,prob=prob,fallback=fallback,pred=pred,unseen=unseen)\n}\nmeasure<-function(d,p,ids,t=.5,cost=c(1,1)){\n use<-ids[d$eligible[ids]&!is.na(p[ids])];y<-d$y[use];a<-if(is.character(t))rep(t==\"always-positive\",length(use))else p[use]>=t\n TP<-sum(a&y==1);FP<-sum(a&y==0);FN<-sum(!a&y==1);TN<-sum(!a&y==0);P<-TP+FN;N<-FP+TN;W<-P+N;PP<-TP+FP;PN<-TN+FN;TPR<-ratio(TP,P);TNR<-ratio(TN,N);bs<-sum((p[use]-y)^2);tc<-FP*cost[1]+FN*cost[2]\n list(TP=TP,FP=FP,FN=FN,TN=TN,mass=W,positiveTargetMass=P,negativeTargetMass=N,predictedPositiveMass=PP,predictedNegativeMass=PN,prevalence=ratio(P,W),selectionRate=ratio(PP,W),accuracy=ratio(TP+TN,W),precision=ratio(TP,PP),negativePredictiveValue=ratio(TN,PN),TPR=TPR,FPR=ratio(FP,N),TNR=TNR,FNR=ratio(FN,P),F1=ratio(2*TP,2*TP+FP+FN),balancedAccuracy=if(is.na(TPR)||is.na(TNR))NA_real_ else(TPR+TNR)/2,Brier=ratio(bs,W),BrierSum=bs,totalCost=tc,meanCost=ratio(tc,W))\n}\ncurves<-function(d,p,ids){\n use<-ids[d$eligible[ids]&!is.na(p[ids])];scores<-sort(unique(p[use]),decreasing=TRUE);policies<-c(list(\"always-negative\"),as.list(scores));points<-lapply(policies,function(t){m<-measure(d,p,ids,t);c(list(policy=t),m[c(\"TP\",\"FP\",\"FN\",\"TN\",\"TPR\",\"FPR\",\"precision\")],list(recall=m$TPR))})\n pos<-use[d$y[use]==1];neg<-use[d$y[use]==0];U<-0;for(i in pos)U<-U+sum(p[i]>p[neg])+.5*sum(p[i]==p[neg])\n AP<-0;trap<-0;lastR<-0;lastP<-1\n if(length(pos)&&length(scores))for(j in seq_along(scores)){z<-points[[j+1]];AP<-AP+(z$recall-lastR)*z$precision;trap<-trap+(z$recall-lastR)*(z$precision+lastP)/2;lastR<-z$recall;lastP<-z$precision}\n list(points=points,ROC_AUC=ratio(U,length(pos)*length(neg)),averagePrecision=if(length(pos))AP else NA_real_,PRTrapezoidWithInitialPrecisionOne=if(length(pos))trap else NA_real_)\n}\ncalibrate<-function(d,p,ids){\n use<-ids[d$eligible[ids]&!is.na(p[ids])];W<-length(use);pi<-if(W)mean(d$y[use])else NA_real_;bins<-list();ECE<-rel<-res<-correction<-0\n whichbin<-findInterval(p[use],seq(0,1,.2),rightmost.closed=TRUE,all.inside=TRUE)\n for(b in 1:5){rr<-use[whichbin==b];w<-length(rr);mp<-if(w)mean(p[rr])else NA_real_;o<-if(w)mean(d$y[rr])else NA_real_;variance<-if(w)mean((p[rr]-mp)^2)else NA_real_;covariance<-if(w)mean((p[rr]-mp)*(d$y[rr]-o))else NA_real_;bc<-variance-2*covariance;gap<-mp-o\n  bins[[b]]<-list(mass=w,meanPrediction=mp,eventRate=o,gap=gap,absoluteGap=abs(gap),scoreVariance=variance,scoreTargetCovariance=covariance,withinBinCorrection=bc,rows=w,ids=d$id[rr])\n  if(w){share<-w/W;ECE<-ECE+share*abs(gap);rel<-rel+share*gap^2;res<-res+share*(o-pi)^2;correction<-correction+share*bc}\n };bs<-if(W)mean((p[use]-d$y[use])^2)else NA_real_;unc<-pi*(1-pi)\n list(bins=bins,ECE=if(W)ECE else NA_real_,Brier=bs,reliability=if(W)rel else NA_real_,resolution=if(W)res else NA_real_,uncertainty=unc,withinBinCorrection=if(W)correction else NA_real_,BrierIdentityResidual=bs-(unc-res+rel+correction))\n}\ncounts<-c(\"mass\",\"positiveTargetMass\",\"negativeTargetMass\",\"predictedPositiveMass\",\"predictedNegativeMass\");rates<-c(\"prevalence\",\"selectionRate\",\"accuracy\",\"precision\",\"negativePredictiveValue\",\"TPR\",\"FPR\",\"TNR\",\"FNR\",\"F1\",\"balancedAccuracy\",\"Brier\",\"BrierSum\",\"totalCost\",\"meanCost\")\ntables<-setNames(lapply(1:10,function(i)list()),c(\"predictions\",\"lineage\",\"fit-medians\",\"fit-cells\",\"validation-candidates\",\"test-metrics\",\"test-curves\",\"calibration-bins\",\"group-metrics\",\"chart-points\"))\nadd<-function(name,row)tables[[name]][[length(tables[[name]])+1L]]<<-row\nscalars<-function(m,keys){out<-list();for(k in keys){out[[paste0(k,\"Exact\")]]<-\"\";out[[paste0(k,\"Approx\")]]<-fmt(m[[k]])};out}\ntagrow<-function(kind,...)c(list(kind=kind),list(...))\npoint<-function(kind,chart,series,index,x,y,xunit=\"dimensionless\",yunit=\"dimensionless\",role=\"test\",tag=\"\"){add(\"chart-points\",tagrow(kind,chart=chart,series=series,index=index,xExact=\"\",xApprox=fmt(x),yExact=\"\",yApprox=fmt(y),xUnit=xunit,yUnit=yunit,role=role,tag=tag))}\nstudy<-function(kind,d){\n f<-fitmodel(d);n<-length(d$id);train<-which(d$role==\"train\");validation<-which(d$role==\"validation\");test<-which(d$role==\"test\");p<-f$pred;cv<-curves(d,p,test);cal<-calibrate(d,p,test)\n for(i in seq_len(n)){\n  reason<-if(d$eligible[i])\"\"else\"required-X-or-Y-missing\";transformed<-if(d$eligible[i])paste(fmt(f$z[i,]),collapse=\"|\")else\"\"\n  add(\"predictions\",tagrow(kind,id=d$id[i],sourceRow=d$sourceRow[i],originalID=d$originalID[i],plannedRole=d$plannedRole[i],role=d$role[i],group=ifelse(is.na(d$group[i]),\"\",d$group[i]),eligible=as.integer(d$eligible[i]),targetExact=fmt(d$y[i]),probabilityExact=\"\",probabilityApprox=fmt(p[i]),unseenCell=ifelse(is.na(f$unseen[i]),\"\",as.character(as.integer(f$unseen[i]))),transformedX=transformed,reason=reason))\n  raw<-d$rawX[i,];raw[raw%in%c(\"\",\".\")]<-\"\";nativeY<-d$nativeTarget[i];if(nativeY%in%c(\"\",\".\"))nativeY<-\"\"\n  add(\"lineage\",tagrow(kind,id=d$id[i],sourceRow=d$sourceRow[i],originalID=d$originalID[i],nativeSourceRows=d$lineage[i],rawX=paste(raw,collapse=\"|\"),nativeTarget=nativeY,derivedTarget=fmt(d$y[i]),nativeGroup=ifelse(is.na(d$group[i]),\"\",d$group[i]),plannedRole=d$plannedRole[i],role=d$role[i],eligible=as.integer(d$eligible[i]),analyticalMass=\"1\",reason=reason))\n }\n for(j in seq_len(ncol(d$x)))add(\"fit-medians\",tagrow(kind,feature=j-1,categorical=as.integer((j-1)%in%d$cat),fitRows=length(train),medianExact=\"\",medianApprox=fmt(f$medians[j]),unit=d$units[j]))\n for(j in seq_along(f$lev))add(\"fit-cells\",tagrow(kind,cell=f$lev[j],trainingRows=f$mass[j],positiveRows=f$positive[j],probabilityExact=\"\",probabilityApprox=fmt(f$prob[j]),fallbackExact=\"\",fallbackApprox=fmt(f$fallback)))\n for(j in seq_along(cv$points)){\n  z<-cv$points[[j]];t<-z$policy;add(\"test-curves\",c(tagrow(kind,point=j-1,policy=if(is.character(t))t else\"threshold\",thresholdExact=\"\",thresholdApprox=if(is.character(t))\"\"else fmt(t)),scalars(z,c(\"TP\",\"FP\",\"FN\",\"TN\",\"TPR\",\"FPR\",\"precision\",\"recall\"))))\n  point(kind,\"roc\",\"ROC\",j-1,z$FPR,z$TPR);point(kind,\"pr\",\"PR-observed\",j-1,z$recall,z$precision)\n }\n for(b in 1:5){z<-cal$bins[[b]];add(\"calibration-bins\",c(tagrow(kind,bin=b-1,leftExact=c(\"0\",\"1/5\",\"2/5\",\"3/5\",\"4/5\")[b],rightExact=c(\"1/5\",\"2/5\",\"3/5\",\"4/5\",\"1\")[b],rightClosed=as.integer(b==5),rows=z$rows,ids=paste(z$ids,collapse=\";\")),scalars(z,c(\"mass\",\"meanPrediction\",\"eventRate\",\"gap\",\"absoluteGap\",\"scoreVariance\",\"scoreTargetCovariance\",\"withinBinCorrection\"))));point(kind,\"reliability\",\"Binary event rate\",b-1,z$meanPrediction,z$eventRate,tag=paste0(\"rows=\",z$rows))}\n for(j in seq_along(test)){i<-test[j];point(kind,\"test-scores\",\"Training-fitted probability\",j-1,j,p[i],\"test-row position\",\"probability\",tag=d$id[i]);point(kind,\"test-scores\",\"Observed Y\",j-1,j,d$y[i],\"test-row position\",\"binary target\",tag=d$id[i])}\n scenarioNames<-c(\"equal\",\"miss-five\",\"alarm-five\");costs<-list(c(1,1),c(1,5),c(5,1))\n for(s in 1:3){name<-scenarioNames[s];cost<-costs[[s]];grid<-c(list(\"always-negative\"),as.list(sort(unique(p[validation]),decreasing=TRUE)));candidates<-lapply(grid,function(t)measure(d,p,validation,t,cost));values<-vapply(candidates,function(m)m$meanCost,numeric(1));best<-which(values<=min(values)+1e-12)[1];chosen<-grid[[best]];ev<-measure(d,p,test,chosen,cost)\n  for(j in seq_along(grid)){t<-grid[[j]];m<-candidates[[j]];cell<-setNames(lapply(c(\"TP\",\"FP\",\"FN\",\"TN\"),function(k)fmt(m[[k]])),paste0(c(\"TP\",\"FP\",\"FN\",\"TN\"),\"Exact\"));add(\"validation-candidates\",c(tagrow(kind,scenario=name,candidate=j-1,selected=as.integer(j==best),policy=if(is.character(t))t else\"threshold\",thresholdExact=\"\",thresholdApprox=if(is.character(t))\"\"else fmt(t),feasible=1,reasons=\"\"),cell,scalars(m,c(counts,\"TPR\",\"FPR\",\"precision\",\"meanCost\",\"totalCost\"))));point(kind,\"validation-cost\",name,j-1,j-1,m$meanCost,\"candidate index\",\"hypothetical cost units/mass\",\"validation\",if(is.character(t))t else fmt(t))}\n  m<-c(ev,cv[c(\"ROC_AUC\",\"averagePrecision\",\"PRTrapezoidWithInitialPrecisionOne\")],cal[c(\"ECE\",\"reliability\",\"resolution\",\"uncertainty\",\"withinBinCorrection\",\"BrierIdentityResidual\")])\n  for(k in c(\"TP\",\"FP\",\"FN\",\"TN\",counts,rates,\"ROC_AUC\",\"averagePrecision\",\"PRTrapezoidWithInitialPrecisionOne\",\"ECE\",\"reliability\",\"resolution\",\"uncertainty\",\"withinBinCorrection\",\"BrierIdentityResidual\")){\n   unit<-if(k%in%c(\"TP\",\"FP\",\"FN\",\"TN\",counts))\"rows\"else if(k==\"totalCost\")\"hypothetical cost units\"else if(k==\"meanCost\")\"hypothetical cost units/mass\"else if(k==\"BrierSum\")\"sum squared-probability loss\"else\"dimensionless\"\n   add(\"test-metrics\",tagrow(kind,scenario=name,metric=k,valueExact=\"\",valueApprox=fmt(m[[k]]),unit=unit))\n  }\n  lev<-unique(d$group[test][!is.na(d$group[test])]);sets<-c(list(test),lapply(lev,function(g)test[!is.na(d$group[test])&d$group[test]==g]),list(test[is.na(d$group[test])]))\n  types<-c(\"overall\",rep(\"known\",length(lev)),\"unknown\");tokens<-c(\"all\",lev,\"\")\n  for(j in seq_along(sets)){ids<-sets[[j]];m<-measure(d,p,ids,chosen,cost);cell<-setNames(lapply(c(\"TP\",\"FP\",\"FN\",\"TN\"),function(k)fmt(m[[k]])),paste0(c(\"TP\",\"FP\",\"FN\",\"TN\"),\"Exact\"));add(\"group-metrics\",c(tagrow(kind,scenario=name,groupType=types[j],groupToken=tokens[j],retainedRows=length(ids)),cell,scalars(m,c(counts,rates))));if(types[j]==\"known\")point(kind,\"group-TPR\",name,j-2,j-2,m$TPR,\"declared group position\",\"TPR\",tag=tokens[j])}\n }\n invisible(NULL)\n}\n\n# Fixed finite inputs only; not the complete web input/budget validator.\nqnum<-function(v){if(is.null(v))return(NA_real_);if(is.logical(v))return(as.numeric(v));s<-as.character(v);if(grepl(\"/\",s,fixed=TRUE)){a<-strsplit(s,\"/\",fixed=TRUE)[[1]];return(as.numeric(a[1])/as.numeric(a[2]))};as.numeric(s)}\nrowsG<-function(raw){\n n<-length(raw);get<-function(r,k,default=NULL)if(is.null(r[[k]]))default else r[[k]]\n id<-vapply(raw,function(r)as.character(r$id),character(1));p<-vapply(raw,function(r)qnum(r$score),numeric(1));y<-vapply(raw,function(r)qnum(r$y),numeric(1));w<-vapply(raw,function(r)qnum(get(r,\"weight\",\"1\")),numeric(1));role<-vapply(raw,function(r)get(r,\"role\",\"evaluation\"),character(1));group<-vapply(raw,function(r)as.character(get(r,\"group\",NA_character_)),character(1))\n stopifnot(all(w>=0),all(is.na(p)|(p>=0&p<=1)),all(is.na(y)|y%in%c(0,1)),!anyDuplicated(id));list(id=id,p=p,y=y,w=w,role=role,group=group,eligible=!is.na(p)&!is.na(y)&w>0&role!=\"excluded\")\n}\nscopeG<-function(d,role=\"all\")if(role==\"all\")seq_along(d$id)else which(d$role==role)\nmetricsG<-function(d,ids,t=.5,cost=c(1,1)){\n use<-ids[d$eligible[ids]];p<-d$p[use];y<-d$y[use];w<-d$w[use];a<-if(is.character(t))rep(t==\"always-positive\",length(use))else p>=t\n TP<-sum(w[a&y==1]);FP<-sum(w[a&y==0]);FN<-sum(w[!a&y==1]);TN<-sum(w[!a&y==0]);P<-TP+FN;N<-FP+TN;W<-P+N;PP<-TP+FP;PN<-TN+FN;TPR<-ratio(TP,P);TNR<-ratio(TN,N);bs<-sum(w*(p-y)^2);tc<-FP*cost[1]+FN*cost[2]\n list(confusion=list(TP=TP,FP=FP,FN=FN,TN=TN),mass=W,positiveTargetMass=P,negativeTargetMass=N,predictedPositiveMass=PP,predictedNegativeMass=PN,prevalence=ratio(P,W),selectionRate=ratio(PP,W),accuracy=ratio(TP+TN,W),precision=ratio(TP,PP),negativePredictiveValue=ratio(TN,PN),TPR=TPR,FPR=ratio(FP,N),TNR=TNR,FNR=ratio(FN,P),F1=ratio(2*TP,2*TP+FP+FN),balancedAccuracy=if(is.na(TPR)||is.na(TNR))NA_real_ else(TPR+TNR)/2,Brier=ratio(bs,W),BrierSum=bs,totalCost=tc,meanCost=ratio(tc,W),bayesThreshold=ratio(cost[1],sum(cost)))\n}\ncurvesG<-function(d,ids){\n use<-ids[d$eligible[ids]];grid<-c(list(\"always-negative\"),as.list(sort(unique(d$p[use]),decreasing=TRUE)));points<-lapply(grid,function(t){m<-metricsG(d,ids,t);c(list(policy=t),m$confusion,m[c(\"TPR\",\"FPR\",\"precision\")],list(recall=m$TPR))});pos<-use[d$y[use]==1];neg<-use[d$y[use]==0];P<-sum(d$w[pos]);N<-sum(d$w[neg]);U<-0\n for(i in pos)U<-U+d$w[i]*sum(d$w[neg]*((d$p[i]>d$p[neg])+.5*(d$p[i]==d$p[neg])))\n AP<-trap<-lastR<-0;lastP<-1\n if(P&&length(grid)>1)for(j in 2:length(grid)){z<-points[[j]];AP<-AP+(z$recall-lastR)*z$precision;trap<-trap+(z$recall-lastR)*(z$precision+lastP)/2;lastR<-z$recall;lastP<-z$precision}\n list(points=points,ROC_AUC=ratio(U,P*N),averagePrecision=if(P)AP else NA_real_,PRTrapezoidWithInitialPrecisionOne=if(P)trap else NA_real_)\n}\nchooseG<-function(d,a,cost){\n role<-if(is.null(a$selectionRole))\"validation\"else a$selectionRole;er<-if(is.null(a$evaluationRole))\"test\"else a$evaluationRole;ids<-scopeG(d,role);use<-ids[d$eligible[ids]];stopifnot(length(use)>0);grid<-if(is.null(a$thresholds))c(list(\"always-negative\"),as.list(sort(unique(d$p[use]),decreasing=TRUE)))else lapply(a$thresholds,function(t)if(t%in%c(\"always-negative\",\"always-positive\"))t else qnum(t))\n candidates<-lapply(seq_along(grid),function(j){m<-metricsG(d,ids,grid[[j]],cost);feasible<-TRUE;if(!is.null(a$minTPR))feasible<-feasible&&!is.na(m$TPR)&&m$TPR>=qnum(a$minTPR);if(!is.null(a$maxFPR))feasible<-feasible&&!is.na(m$FPR)&&m$FPR<=qnum(a$maxFPR);list(index=j-1,policy=grid[[j]],metrics=m,feasible=feasible)})\n good<-which(vapply(candidates,function(c)c$feasible,logical(1)));best<-NA_integer_;if(length(good)){v<-vapply(candidates[good],function(c)c$metrics$meanCost,numeric(1));best<-good[which(v<=min(v)+1e-12)[1]]}\n list(selectedIndex=if(is.na(best))NA_integer_ else best-1,selectedPolicy=if(is.na(best))NULL else grid[[best]],selectedValidation=if(is.na(best))NULL else candidates[[best]]$metrics,candidates=candidates,evaluation=if(is.na(best)||er==\"none\")NULL else metricsG(d,scopeG(d,er),grid[[best]],cost))\n}\ncalibrateG<-function(d,ids,edges){\n use<-ids[d$eligible[ids]];W<-sum(d$w[use]);pi<-ratio(sum(d$w[use]*d$y[use]),W);bins<-list();ECE<-rel<-res<-correction<-0;assign<-findInterval(d$p[use],edges,rightmost.closed=TRUE,all.inside=TRUE)\n for(b in seq_len(length(edges)-1)){rr<-use[assign==b];w<-sum(d$w[rr]);mp<-ratio(sum(d$w[rr]*d$p[rr]),w);o<-ratio(sum(d$w[rr]*d$y[rr]),w);variance<-if(w)sum(d$w[rr]*(d$p[rr]-mp)^2)/w else NA_real_;covariance<-if(w)sum(d$w[rr]*(d$p[rr]-mp)*(d$y[rr]-o))/w else NA_real_;bc<-variance-2*covariance;gap<-mp-o;bins[[b]]<-list(index=b-1,mass=w,meanPrediction=mp,eventRate=o,scoreVariance=variance,scoreTargetCovariance=covariance,withinBinCorrection=bc,ids=d$id[rr])\n  if(w){s<-w/W;ECE<-ECE+s*abs(gap);rel<-rel+s*gap^2;res<-res+s*(o-pi)^2;correction<-correction+s*bc}\n };bs<-ratio(sum(d$w[use]*(d$p[use]-d$y[use])^2),W);unc<-pi*(1-pi);list(bins=bins,Brier=bs,ECE=if(W)ECE else NA_real_,uncertainty=unc,reliability=if(W)rel else NA_real_,resolution=if(W)res else NA_real_,withinBinCorrection=if(W)correction else NA_real_,BrierIdentityResidual=bs-(unc-res+rel+correction))\n}\ngroupsG<-function(d,ids,t,cost){\n lev<-unique(d$group[ids][!is.na(d$group[ids])]);groups<-lapply(lev,function(g)list(group=g,metrics=metricsG(d,ids[!is.na(d$group[ids])&d$group[ids]==g],t,cost)));overall<-metricsG(d,ids,t,cost);unknown<-metricsG(d,ids[is.na(d$group[ids])],t,cost);gaps<-list()\n for(k in c(\"prevalence\",\"selectionRate\",\"TPR\",\"FPR\",\"precision\",\"accuracy\",\"meanCost\")){use<-Filter(function(g)g$metrics$mass>0,groups);v<-vapply(use,function(g)g$metrics[[k]],numeric(1));gaps[[k]]<-if(length(use)<2||anyNA(v))NA_real_ else max(v)-min(v)}\n list(overall=overall,groups=groups,unknownGroup=unknown,gaps=gaps,partitionMassResidual=overall$mass-unknown$mass-sum(vapply(groups,function(g)g$metrics$mass,numeric(1))))\n}\nsvgFixed<-function(file,points,title,xlabel,ylabel,legend){\n finite<-points[points$y!=\"undefined\"&points$x!=\"undefined\",,drop=FALSE];x<-as.numeric(finite$x);y<-as.numeric(finite$y);xmin<-if(length(x))min(x)else 0;xmax<-if(length(x))max(x)else 1;ymin<-min(c(0,y));ymax<-max(c(0,y));if(xmin==xmax){xmin<-xmin-.5;xmax<-xmax+.5};if(ymin==ymax)ymax<-ymin+1;X<-function(v)85+(v-xmin)/(xmax-xmin)*480;Y<-function(v)278-(v-ymin)/(ymax-ymin)*175\n esc<-function(s){s<-gsub(\"&\",\"&amp;\",s,fixed=TRUE);s<-gsub(\"<\",\"&lt;\",s,fixed=TRUE);gsub(\">\",\"&gt;\",s,fixed=TRUE)};s<-'<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"620\" height=\"360\" viewBox=\"0 0 620 360\"><rect width=\"620\" height=\"360\" fill=\"white\"/><g font-family=\"Arial, sans-serif\" font-size=\"13\" fill=\"#17324d\">'\n lines<-strwrap(title,width=65);for(i in seq_along(lines))s<-paste0(s,'<text x=\"25\" y=\"',24+(i-1)*18,'\">',esc(lines[i]),'</text>');colors<-c(\"#176b9b\",\"#b85e18\",\"#437e4d\")\n for(i in seq_along(legend))s<-paste0(s,'<circle cx=\"',30+(i-1)*250,'\" cy=\"76\" r=\"4\" fill=\"',colors[(i-1)%%3+1],'\"/><text x=\"',42+(i-1)*250,'\" y=\"80\">',esc(legend[i]),'</text>')\n s<-paste0(s,'<path d=\"M85 98V278H575\" fill=\"none\" stroke=\"#52677d\"/><text text-anchor=\"middle\" x=\"325\" y=\"338\">',esc(xlabel),'</text><text text-anchor=\"middle\" transform=\"translate(21,190) rotate(-90)\">',esc(ylabel),'</text>')\n for(i in 0:4){xx<-xmin+(xmax-xmin)*i/4;yy<-ymin+(ymax-ymin)*i/4;s<-paste0(s,'<text text-anchor=\"middle\" x=\"',sprintf(\"%.9g\",X(xx)),'\" y=\"305\">',sprintf(\"%.4g\",xx),'</text><text text-anchor=\"end\" x=\"77\" y=\"',sprintf(\"%.9g\",Y(yy)+4),'\">',sprintf(\"%.4g\",yy),'</text>')}\n for(i in seq_len(nrow(finite)))s<-paste0(s,'<circle cx=\"',sprintf(\"%.9g\",X(x[i])),'\" cy=\"',sprintf(\"%.9g\",Y(y[i])),'\" r=\"3\" fill=\"',colors[as.integer(finite$series[i])%%3+1],'\"/>');writeLines(paste0(s,'</g></svg>'),file,useBytes=TRUE)\n}\nfixedRun<-function(){\n api<-FIXED$api;a<-FIXED$args;summary<-list();points<-list();xlabel<-\"Declared index\";ylabel<-\"Value\";legend<-\"Declared result\"\n metric<-function(name,v,unit=\"dimensionless\"){if(is.null(v))v<-NA_real_;summary[[length(summary)+1L]]<<-data.frame(metric=name,value=if(is.na(v))\"undefined\"else sprintf(\"%.9g\",v),exactValue=\"\",unit=unit,defined=as.integer(!is.na(v)),stringsAsFactors=FALSE)}\n pt<-function(i,x,y,id=\"\",series=0){points[[length(points)+1L]]<<-data.frame(series=series,index=i,xExact=\"\",x=if(is.na(x))\"undefined\"else sprintf(\"%.9g\",x),yExact=\"\",y=if(is.na(y))\"undefined\"else sprintf(\"%.9g\",y),id=as.character(id),stringsAsFactors=FALSE)}\n if(api==\"realdata\"){\n  native<-loadData()[[a$kind]];fit<-fitmodel(native);d<-list(id=native$id,p=fit$pred,y=native$y,w=rep(1,length(native$id)),role=native$role,group=native$group,eligible=native$eligible);scenarios<-list()\n  for(j in 1:3){name<-c(\"equal\",\"miss-five\",\"alarm-five\")[j];cst<-list(c(1,1),c(1,5),c(5,1))[[j]];sel<-chooseG(d,list(),cst);scenarios[[j]]<-list(name=name,selection=sel);metric(paste0(name,\"Threshold\"),sel$selectedPolicy);metric(paste0(name,\"TestCost\"),sel$evaluation$meanCost,\"hypothetical cost units/mass\")}\n  ids<-scopeG(d,\"test\");cv<-curvesG(d,ids);cal<-calibrateG(d,ids,seq(0,1,.2));metric(\"testAUC\",cv$ROC_AUC);metric(\"testAP\",cv$averagePrecision);metric(\"testBrier\",cal$Brier);metric(\"eligibleRows\",sum(d$eligible),\"rows\")\n  for(j in seq_along(ids)){i<-ids[j];pt(j-1,j,d$p[i],d$id[i],0);pt(j-1,j,d$y[i],d$id[i],1)}\n  full<-list(kind=a$kind,fit=fit,scenarios=scenarios,testCurves=cv,testCalibration=cal,rowsScored=d);xlabel<-\"Test row, native order\";ylabel<-\"Y or probability\";legend<-c(\"Training-fitted probability\",\"Observed Y\")\n }else{\n  d<-rowsG(a$rows);role<-if(is.null(a$role))\"all\"else a$role;ids<-scopeG(d,role);cost<-if(is.null(a$costs))c(1,1)else c(qnum(a$costs$falsePositive),qnum(a$costs$falseNegative));t<-if(is.null(a$threshold)).5 else if(a$threshold%in%c(\"always-positive\",\"always-negative\"))a$threshold else qnum(a$threshold)\n  if(api==\"metrics\"){\n   full<-metricsG(d,ids,t,cost);for(k in c(\"mass\",\"accuracy\",\"precision\",\"TPR\",\"FPR\",\"F1\",\"Brier\",\"meanCost\"))metric(k,full[[k]],if(k==\"mass\")\"mass\"else if(k==\"meanCost\")\"hypothetical cost units/mass\"else\"dimensionless\");metric(\"BayesThreshold\",full$bayesThreshold)\n   for(i in 1:4)pt(i-1,i-1,full$confusion[[i]],names(full$confusion)[i]);xlabel<-\"TP / FP / FN / TN positions\";ylabel<-\"Analytical mass\"\n  }else if(api==\"curves\"){\n   full<-curvesG(d,ids);for(k in c(\"ROC_AUC\",\"averagePrecision\",\"PRTrapezoidWithInitialPrecisionOne\"))metric(k,full[[k]])\n   for(j in seq_along(full$points)){p<-full$points[[j]];pt(j-1,p$FPR,p$TPR,if(is.character(p$policy))p$policy else sprintf(\"%.17g\",p$policy))};xlabel<-\"False positive rate\";ylabel<-\"True positive rate\";legend<-\"Observed ROC operating points\"\n  }else if(api==\"choose\"){\n   full<-chooseG(d,a,cost);metric(\"selectedIndex\",full$selectedIndex,\"candidate index\");metric(\"minimumCost\",if(is.null(full$selectedValidation))NULL else full$selectedValidation$meanCost,\"hypothetical cost units/mass\");metric(\"feasible\",as.integer(!is.na(full$selectedIndex)),\"indicator\")\n   for(c in full$candidates)pt(c$index,c$index,c$metrics$meanCost,if(is.character(c$policy))c$policy else sprintf(\"%.17g\",c$policy));xlabel<-\"Validation candidate\";ylabel<-\"Assumed cost / mass\";legend<-\"Validation candidate costs\"\n  }else if(api==\"calibrate\"){\n   edges<-if(is.null(a$binEdges))seq(0,1,.2)else vapply(a$binEdges,qnum,numeric(1));full<-calibrateG(d,ids,edges);for(k in c(\"ECE\",\"Brier\",\"uncertainty\",\"resolution\",\"reliability\",\"withinBinCorrection\",\"BrierIdentityResidual\"))metric(k,full[[k]])\n   for(b in full$bins)pt(b$index,b$meanPrediction,b$eventRate,paste0(\"bin:\",b$index));xlabel<-\"Bin mean forecast\";ylabel<-\"Bin event rate\";legend<-\"Binary-event reliability\"\n  }else if(api==\"groups\"){\n   full<-groupsG(d,ids,t,cost);metric(\"overallTPR\",full$overall$TPR);metric(\"TPRGap\",full$gaps$TPR);metric(\"precisionGap\",full$gaps$precision);metric(\"unknownMass\",full$unknownGroup$mass,\"mass\");metric(\"partitionResidual\",full$partitionMassResidual,\"mass\")\n   for(j in seq_along(full$groups))pt(j-1,j-1,full$groups[[j]]$metrics$TPR,full$groups[[j]]$group);xlabel<-\"Declared group position\";ylabel<-\"True positive rate\";legend<-\"Known-group TPR\"\n  }else stop(\"unknown declared fixed API\")\n }\n sm<-do.call(rbind,summary);pp<-do.call(rbind,points);write.csv(sm,file.path(outDir,\"summary.csv\"),row.names=FALSE,na=\"\");write.csv(pp,file.path(outDir,\"plot-points.csv\"),row.names=FALSE,na=\"\");svgFixed(file.path(outDir,\"plot.svg\"),pp,FIXED$title,xlabel,ylabel,legend);dput(list(api=api,variant=FIXED$variant,input=FIXED$args,arithmetic=\"Base-R binary64 fixed example; not an exact rational general validator\",result=full),file=file.path(outDir,\"full.txt\"));cat(\"PASS\",api,FIXED$variant,\"summary\",nrow(sm),\"points\",nrow(pp),\"\\n\")\n}\n\nFIXED<-list(api=\"groups\",variant=\"unknown-group\",args=list(rows=list(list(id=\"a\",score=\".9\",y=1,group=\"A\"),list(id=\"b\",score=\".8\",y=1,group=\"A\"),list(id=\"c\",score=\".8\",y=0,group=\"A\"),list(id=\"d\",score=\".6\",y=0,group=\"B\"),list(id=\"e\",score=\".4\",y=1,group=\"B\"),list(id=\"f\",score=\".1\",y=0,group=NULL)),threshold=\".4\"),title=\"Unknown group stays overall and preserves mass\")\nfixedRun()\n",
        "input": {
          "rows": [
            {
              "id": "a",
              "score": ".9",
              "y": 1,
              "group": "A"
            },
            {
              "id": "b",
              "score": ".8",
              "y": 1,
              "group": "A"
            },
            {
              "id": "c",
              "score": ".8",
              "y": 0,
              "group": "A"
            },
            {
              "id": "d",
              "score": ".6",
              "y": 0,
              "group": "B"
            },
            {
              "id": "e",
              "score": ".4",
              "y": 1,
              "group": "B"
            },
            {
              "id": "f",
              "score": ".1",
              "y": 0,
              "group": null
            }
          ],
          "threshold": ".4"
        },
        "inputFiles": [],
        "returnCode": 0,
        "expectedFailure": false,
        "stdout": "PASS groups unknown-group summary 5 points 2 \n",
        "stderr": "During startup - Warning messages:\n1: Setting LC_COLLATE=C.UTF-8 failed \n2: Setting LC_CTYPE=C.UTF-8 failed \n3: Setting LC_MONETARY=C.UTF-8 failed \n4: Setting LC_TIME=C.UTF-8 failed \n",
        "summary": {
          "overallTPR": "1",
          "TPRGap": "0",
          "precisionGap": "0.166666667",
          "unknownMass": "1",
          "partitionResidual": "0"
        },
        "summaryRows": [
          {
            "metric": "overallTPR",
            "value": "1",
            "exactValue": "",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "TPRGap",
            "value": "0",
            "exactValue": "",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "precisionGap",
            "value": "0.166666667",
            "exactValue": "",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "unknownMass",
            "value": "1",
            "exactValue": "",
            "unit": "mass",
            "defined": "1"
          },
          {
            "metric": "partitionResidual",
            "value": "0",
            "exactValue": "",
            "unit": "mass",
            "defined": "1"
          }
        ],
        "plotPoints": [
          {
            "series": "0",
            "index": "0",
            "xExact": "",
            "x": "0",
            "yExact": "",
            "y": "1",
            "id": "A"
          },
          {
            "series": "0",
            "index": "1",
            "xExact": "",
            "x": "1",
            "yExact": "",
            "y": "1",
            "id": "B"
          }
        ],
        "plotFile": "ml14-fixed-results/groups-unknown-group-r/plot.svg",
        "plotSHA256": "7345533c93d1caeb13d26b0e5d566a9d25a7c0dbb58cb9533df73bd52c3f77d9",
        "files": [
          {
            "file": "ml14-fixed-results/groups-unknown-group-r/full.txt",
            "sha256": "18fb79ea04c91bc08558ebdabe4e50ea75067ff26277dfad410d53f2b094f5d7",
            "bytes": 3244
          },
          {
            "file": "ml14-fixed-results/groups-unknown-group-r/plot-points.csv",
            "sha256": "7cc428a6d4d8fdb2271076df0e7a8add88214e639cb464503d7c436710b947ce",
            "bytes": 95
          },
          {
            "file": "ml14-fixed-results/groups-unknown-group-r/plot.svg",
            "sha256": "7345533c93d1caeb13d26b0e5d566a9d25a7c0dbb58cb9533df73bd52c3f77d9",
            "bytes": 1200
          },
          {
            "file": "ml14-fixed-results/groups-unknown-group-r/summary.csv",
            "sha256": "581fe7065e2e848002ce3d4d54ba83684a3c99fc3ad3b98e5ccaf87ea4206e44",
            "bytes": 241
          }
        ],
        "scope": "Actually executed standalone fixed example, Python exact Fraction versus base-R binary64. Approximate R residuals retained; not universal exact arithmetic/web validation/native UI. Source programs read factual3CSV only."
      }
    }
  },
  "realdata": {
    "python": {
      "country": {
        "api": "realdata",
        "variant": "country",
        "language": "python",
        "title": "Actual country fixed train/validation/test procedure",
        "codeFile": "ml14-code/realdata-country.py",
        "codeSHA256": "f99f786343598a8f138e26c10b7420d05f65fbd3bc1072a8d60835635dd49b80",
        "code": "#!/usr/bin/env python3\n\"\"\"ML14 standalone exact finite study, Python standard library only.\nInputs: only the three retained factual source CSVs below.\nDerived role/target/group/eligibility columns in those CSVs are NOT inputs.\nRebuilds SHA256 roles, train-only medians/cell scores, validation thresholds,\ntest curves, binary-event reliability and descriptive group ledgers.\nCosts 1/1,1/5,5/1 are hypothetical units, not measured intervention returns.\nThis is author public reproduction, not independent scientific review.\n\"\"\"\n\"\"\"Author Fraction reference, separate from product JavaScript; not independent peer.\"\"\"\nfrom fractions import Fraction as F\nfrom collections import Counter,defaultdict\ndef read(raw):\n rows=[]\n for i,r in enumerate(raw):\n  s=None if r['score']is None else F(str(r['score']));y=None if r['y']is None else F(int(r['y']))if isinstance(r['y'],bool)else F(str(r['y']));w=F(str(r.get('weight','1')));role=r.get('role','evaluation')\n  rows.append(dict(id=r['id'],index=i,score=s,y=y,w=w,role=role,group=r.get('group'),eligible=s is not None and y is not None and w>0 and role!='excluded'))\n return rows\ndef scoped(rows,role='all'):return rows if role=='all'else[r for r in rows if r['role']==role]\ndef divide(n,d):return None if not d else n/d\ndef policy(v):return v if v in ['always-negative','always-positive']else F(str(v))\ndef positive(p,s):return p=='always-positive'if isinstance(p,str)else s>=p\ndef cost(a=None):\n a={}if a is None else a;fp=F(str(a.get('falsePositive','1')));fn=F(str(a.get('falseNegative','1')));return fp,fn\ndef metrics(rows,threshold=F(1,2),cc=(F(1),F(1))):\n counts=dict(TP=F(0),FP=F(0),FN=F(0),TN=F(0));brier=F(0);pred=[]\n for r in rows:\n  if not r['eligible']:pred.append(dict(id=r['id'],index=r['index'],eligible=False,decision=None,probability=None,Brier=None));continue\n  yes=positive(threshold,r['score']);cell=('T'if yes==bool(r['y'])else'F')+('P'if yes else'N');counts[cell]+=r['w'];loss=(r['score']-r['y'])**2;brier+=r['w']*loss;pred.append(dict(id=r['id'],index=r['index'],eligible=True,decision=int(yes),probability=r['score'],Brier=loss))\n TP,FP,FN,TN=[counts[k]for k in ['TP','FP','FN','TN']];P=TP+FN;N=TN+FP;mass=P+N;PP=TP+FP;PN=TN+FN;TPR=divide(TP,P);TNR=divide(TN,N);total=FP*cc[0]+FN*cc[1]\n return dict(confusion=counts,mass=mass,positiveTargetMass=P,negativeTargetMass=N,predictedPositiveMass=PP,predictedNegativeMass=PN,prevalence=divide(P,mass),selectionRate=divide(PP,mass),accuracy=divide(TP+TN,mass),precision=divide(TP,PP),negativePredictiveValue=divide(TN,PN),TPR=TPR,FPR=divide(FP,N),TNR=TNR,FNR=divide(FN,P),F1=divide(2*TP,2*TP+FP+FN),balancedAccuracy=None if TPR is None or TNR is None else(TPR+TNR)/2,Brier=divide(brier,mass),BrierSum=brier,totalCost=total,meanCost=divide(total,mass),predictions=pred,bayesThreshold=divide(cc[0],sum(cc)))\ndef curves(rows):\n use=[r for r in rows if r['eligible']];pos=Counter();neg=Counter()\n for r in use:(pos if r['y']else neg)[r['score']]+=r['w']\n P=sum(pos.values(),F(0));N=sum(neg.values(),F(0));pairs=F(0)\n for a,wa in pos.items():\n  for b,wb in neg.items():pairs+=wa*wb*(F(1)if a>b else F(1,2)if a==b else F(0))\n thresholds=['always-negative']+sorted({r['score']for r in use},reverse=True);points=[];AP=F(0);trap=F(0);lastR=F(0);lastP=F(1)\n for i,p in enumerate(thresholds):\n  m=metrics(rows,p);points.append(dict(policy=p,TP=m['confusion']['TP'],FP=m['confusion']['FP'],FN=m['confusion']['FN'],TN=m['confusion']['TN'],TPR=m['TPR'],FPR=m['FPR'],precision=m['precision'],recall=m['TPR']))\n  if i and P:\n   R=m['TPR'];PP=m['precision'];AP+=(R-lastR)*PP;trap+=(R-lastR)*(PP+lastP)/2;lastR=R;lastP=PP\n return dict(positiveMass=P,negativeMass=N,ROC_AUC=divide(pairs,P*N),weightedConcordantPlusHalfTiedMass=pairs,averagePrecision=AP if P else None,PRTrapezoidWithInitialPrecisionOne=trap if P else None,points=points)\ndef choose(rows,a,cc):\n sr=a.get('selectionRole','validation');er=a.get('evaluationRole','test');rr=scoped(rows,sr);thresholds=[policy(t)for t in a['thresholds']]if'thresholds'in a else['always-negative']+sorted({r['score']for r in rr if r['eligible']},reverse=True)\n candidates=[]\n for i,p in enumerate(thresholds):\n  m=metrics(rr,p,cc);reasons=[]\n  if'minTPR'in a and(m['TPR']is None or m['TPR']<F(str(a['minTPR']))):reasons.append('TPR-undefined'if m['TPR']is None else'below-minTPR')\n  if'maxFPR'in a and(m['FPR']is None or m['FPR']>F(str(a['maxFPR']))):reasons.append('FPR-undefined'if m['FPR']is None else'above-maxFPR')\n  candidates.append(dict(index=i,policy=p,metrics=m,feasible=not reasons,reasons=reasons))\n eligible=[c for c in candidates if c['feasible']];best=min(eligible,key=lambda c:(c['metrics']['meanCost'],c['index']))if eligible else None\n return dict(selectedIndex=None if best is None else best['index'],selectedPolicy=None if best is None else best['policy'],candidates=candidates,selectedValidation=None if best is None else best['metrics'],evaluation=None if best is None or er=='none'else metrics(scoped(rows,er),best['policy'],cc),selectionIDs=[r['id']for r in rr if r['eligible']])\ndef calibrate(rows,ee):\n buckets=[[]for _ in range(len(ee)-1)]\n for r in rows:\n  if not r['eligible']:continue\n  j=next((i for i in range(len(ee)-1)if r['score']<ee[i+1]),len(ee)-2);buckets[j].append(r)\n mass=sum((r['w']for r in rows if r['eligible']),F(0));P=sum((r['w']*r['y']for r in rows if r['eligible']),F(0));pi=divide(P,mass);Brier=None if not mass else sum((r['w']*(r['score']-r['y'])**2 for r in rows if r['eligible']),F(0))/mass;ECE=F(0);reliability=F(0);resolution=F(0);correction=F(0);bins=[]\n for i,rr in enumerate(buckets):\n  w=sum((r['w']for r in rr),F(0));mp=None if not w else sum((r['w']*r['score']for r in rr),F(0))/w;o=None if not w else sum((r['w']*r['y']for r in rr),F(0))/w\n  variance=None if not w else sum((r['w']*(r['score']-mp)**2 for r in rr),F(0))/w\n  covariance=None if not w else sum((r['w']*(r['score']-mp)*(r['y']-o)for r in rr),F(0))/w\n  bc=None if not w else variance-2*covariance;gap=None if not w else mp-o\n  bins.append(dict(index=i,rows=len(rr),mass=w,meanPrediction=mp,eventRate=o,gap=gap,absoluteGap=None if gap is None else abs(gap),scoreVariance=variance,scoreTargetCovariance=covariance,withinBinCorrection=bc,ids=[r['id']for r in rr]))\n  if w:\n   share=w/mass;ECE+=share*abs(gap);reliability+=share*gap**2;resolution+=share*(o-pi)**2;correction+=share*bc\n uncertainty=None if pi is None else pi*(1-pi);residual=None if Brier is None else Brier-(uncertainty-resolution+reliability+correction)\n return dict(mass=mass,prevalence=pi,Brier=Brier,ECE=ECE if mass else None,reliability=reliability if mass else None,resolution=resolution if mass else None,uncertainty=uncertainty,withinBinCorrection=correction if mass else None,BrierIdentityResidual=residual,bins=bins)\ndef typed(v):return type(v).__name__,v\ndef groups(rows,p,cc):\n bins={}\n for r in rows:\n  if r['group']is not None:bins.setdefault(typed(r['group']),[]).append(r)\n gm=[dict(group=rr[0]['group'],metrics=metrics(rr,p,cc))for rr in bins.values()];overall=metrics(rows,p,cc);unknown=metrics([r for r in rows if r['group']is None],p,cc);gaps={}\n for key in ['prevalence','selectionRate','TPR','FPR','precision','accuracy','meanCost']:\n  positive=[g for g in gm if g['metrics']['mass']>0];undefined=[g['group']for g in positive if g['metrics'][key]is None];vals=[g['metrics'][key]for g in positive if g['metrics'][key]is not None]\n  gaps[key]=dict(value=None if len(positive)<2 or undefined else max(vals)-min(vals),undefinedGroups=undefined,comparedPositiveMassGroups=[g['group']for g in positive])\n return dict(overall=overall,groups=gm,unknownGroup=unknown,gaps=gaps,partitionMassResidual=overall['mass']-unknown['mass']-sum((g['metrics']['mass']for g in gm),F(0)))\ndef actual_model(M):\n raw=M['records'];cat=M['categoricalFeatures'];p=len(raw[0]['x']);train=[r for r in raw if r['role']=='train'];medians=[]\n for j in range(p):\n  if j in cat:medians.append(None);continue\n  values=sorted(F(r['x'][j])for r in train);n=len(values);medians.append(values[n//2]if n%2 else(values[n//2-1]+values[n//2])/2)\n def transform(r):return[F(v)if j in cat else F(int(F(v)>medians[j]))for j,v in enumerate(r['x'])]\n counts={}\n for r in train:\n  key=tuple(transform(r));n,s=counts.get(key,(0,0));counts[key]=(n+1,s+int(r['y']))\n probabilities={k:F(s+1,n+2)for k,(n,s)in counts.items()};fallback=F(sum(int(r['y'])for r in train)+1,len(train)+2);scored=[]\n for i,r in enumerate(raw):\n  eligible=r['role']!='excluded';z=transform(r)if eligible else None;key=None if z is None else tuple(z);score=None if not eligible else probabilities.get(key,fallback)\n  scored.append(dict(id=r['id'],index=i,role=r['role'],group=r['group'],y=None if r['y']is None else F(r['y']),score=score,w=F(1),eligible=eligible,transformedX=z,unseenCell=None if not eligible else key not in probabilities))\n return dict(medians=medians,cells=counts,probabilities=probabilities,fallback=fallback,rows=scored,trainIDs=[r['id']for r in train])\n\n\nimport csv,json,hashlib,argparse,datetime\nfrom pathlib import Path\ndef missing(v):return None if v in ['', '.',None]else v\ndef load_sources(folder):\n def read_csv(name):\n  with (folder/name).open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))\n wb=read_csv('actual64-country-four-indicators-original-2024.csv')\n codes=['NY.GDP.PCAP.KD','NY.GDP.MKTP.KD.ZG','FP.CPI.TOTL.ZG','SP.DYN.LE00.IN']\n lookup={(r['countryISO3'],r['indicatorID']):r for r in wb};country=[]\n for i,iso in enumerate(sorted({r['countryISO3']for r in wb}),1):\n  native=[lookup[iso,c]for c in codes];v=[missing(r['originalValueToken'])for r in native]\n  country.append(dict(id=iso+':2024',sourceRow=i,originalID=iso,x=v[:3],y=None if v[3]is None else str(int(F(v[3])>=80)),group=None if v[0]is None else str(int(F(v[0])>=25000)),nativeTarget=v[3],nativeSourceRows=';'.join(r['sourceRow']for r in native)))\n nls=read_csv('actual3613-NLS-original52-fields-groups-roles.csv');person=[]\n for r in nls:\n  y=missing(r['wage76']);person.append(dict(id='person:'+r['sourceRow'],sourceRow=int(r['sourceRow']),originalID=r['id'],x=[missing(r[k])for k in ['ed76','age76','nearc4']],y=None if y is None else str(int(F(y)>=500)),group=missing(r['black']),nativeTarget=y,nativeSourceRows=r['sourceRow']))\n ch=read_csv('actual3150-churn-original14-fields-groups-roles.csv');company=[]\n for r in ch:\n  company.append(dict(id='customer:'+r['sourceRow'],sourceRow=int(r['sourceRow']),originalID='',x=[missing(r[k])for k in ['Call  Failure','Complains','Subscription  Length','Seconds of Use']],y=missing(r['Churn']),group=missing(r['Tariff Plan']),nativeTarget=missing(r['Churn']),nativeSourceRows=r['sourceRow']))\n assert len(wb)==64 and len(country)==16 and len(nls)==3613 and len(ch)==3150\n assert [int(r['sourceRow'])for r in ch if r['Charge  Amount']=='10']==[474,2174,2274,2374,2674,2924,2974]\n models={}\n for kind,raw,cat,units in [('country',country,[],['constant2015USD/person','annualPercent','annualPercent']),('person',person,[2],['years','years','nativeCategory']),('company',company,[1],['count','nativeCategory','months','seconds'])]:\n  order=sorted(range(len(raw)),key=lambda i:(hashlib.sha256(('ML14-role|'+kind+'|'+raw[i]['id']).encode()).hexdigest(),i))\n  for rank,i in enumerate(order):\n   r=raw[i];r['plannedRole']='test'if rank%5==0 else'validation'if rank%5==1 else'train';r['eligible']=None not in r['x']+[r['y']];r['role']=r['plannedRole']if r['eligible']else'excluded';r['weight']='1'\n  models[kind]=dict(records=raw,categoricalFeatures=cat,featureUnits=units)\n assert sum(r['eligible']for r in person)==3017\n return models\n\ndef exact(v):return ''if v is None else str(v)\ndef approx(v):return ''if v is None else format(float(v),'.17g')\ndef scalar_fields(m,keys):\n out={}\n for k in keys:\n  out[k+'Exact']=exact(m[k]);out[k+'Approx']=approx(m[k])\n return out\nCOUNTS=['mass','positiveTargetMass','negativeTargetMass','predictedPositiveMass','predictedNegativeMass']\nRATES=['prevalence','selectionRate','accuracy','precision','negativePredictiveValue','TPR','FPR','TNR','FNR','F1','balancedAccuracy','Brier','BrierSum','totalCost','meanCost']\nSCENARIOS=[('equal',F(1),F(1)),('miss-five',F(1),F(5)),('alarm-five',F(5),F(1))]\ndef packed(v):\n if isinstance(v,F):return str(v)\n if isinstance(v,dict):return{str(k):packed(x)for k,x in v.items()}\n if isinstance(v,(tuple,list)):return[packed(x)for x in v]\n return v\ndef run_study(source,out):\n out.mkdir(parents=True,exist_ok=True);models=load_sources(source)\n tables={name:[]for name in ['predictions','lineage','fit-medians','fit-cells','validation-candidates','test-metrics','test-curves','calibration-bins','group-metrics','chart-points']}\n studies={};charts=[]\n def point(kind,chart,series,index,x,y,xunit='dimensionless',yunit='dimensionless',role='test',tag=''):\n  tables['chart-points'].append(dict(kind=kind,chart=chart,series=series,index=index,xExact=exact(x),xApprox=approx(x),yExact=exact(y),yApprox=approx(y),xUnit=xunit,yUnit=yunit,role=role,tag=tag))\n for kind,M in models.items():\n  fit=actual_model(M);rr=fit['rows'];native=M['records'];test=scoped(rr,'test');cv=curves(test);cal=calibrate(test,[F(0),F(1,5),F(2,5),F(3,5),F(4,5),F(1)]);scenarios=[]\n  for i,r in enumerate(rr):\n   n=native[i];reason=''if r['eligible']else'required-X-or-Y-missing'\n   tables['predictions'].append(dict(kind=kind,id=r['id'],sourceRow=n['sourceRow'],originalID=n['originalID'],plannedRole=n['plannedRole'],role=r['role'],group=''if r['group']is None else r['group'],eligible=int(r['eligible']),targetExact=exact(r['y']),probabilityExact=exact(r['score']),probabilityApprox=approx(r['score']),unseenCell=''if r['unseenCell']is None else int(r['unseenCell']),transformedX=''if r['transformedX']is None else'|'.join(map(str,r['transformedX'])),reason=reason))\n   tables['lineage'].append(dict(kind=kind,id=r['id'],sourceRow=n['sourceRow'],originalID=n['originalID'],nativeSourceRows=n['nativeSourceRows'],rawX='|'.join(''if x is None else x for x in n['x']),nativeTarget=''if n['nativeTarget']is None else n['nativeTarget'],derivedTarget=exact(r['y']),nativeGroup=''if n['group']is None else n['group'],plannedRole=n['plannedRole'],role=r['role'],eligible=int(r['eligible']),analyticalMass='1',reason=reason))\n  for j,v in enumerate(fit['medians']):tables['fit-medians'].append(dict(kind=kind,feature=j,categorical=int(j in M['categoricalFeatures']),fitRows=len(fit['trainIDs']),medianExact=exact(v),medianApprox=approx(v),unit=M['featureUnits'][j]))\n  for key,(mass,pos)in fit['cells'].items():tables['fit-cells'].append(dict(kind=kind,cell='|'.join(map(str,key)),trainingRows=mass,positiveRows=pos,probabilityExact=exact(fit['probabilities'][key]),probabilityApprox=approx(fit['probabilities'][key]),fallbackExact=exact(fit['fallback']),fallbackApprox=approx(fit['fallback'])))\n  for j,p in enumerate(cv['points']):\n   policy=p['policy'];tables['test-curves'].append(dict(kind=kind,point=j,policy=policy if isinstance(policy,str)else'threshold',thresholdExact=''if isinstance(policy,str)else exact(policy),thresholdApprox=''if isinstance(policy,str)else approx(policy),**scalar_fields(p,['TP','FP','FN','TN','TPR','FPR','precision','recall'])))\n   point(kind,'roc','ROC',j,p['FPR'],p['TPR']);point(kind,'pr','PR-observed',j,p['recall'],p['precision'])\n  for b in cal['bins']:\n   tables['calibration-bins'].append(dict(kind=kind,bin=b['index'],leftExact=str(F(b['index'],5)),rightExact=str(F(b['index']+1,5)),rightClosed=int(b['index']==4),rows=b['rows'],ids=';'.join(str(i)for i in b['ids']),**scalar_fields(b,['mass','meanPrediction','eventRate','gap','absoluteGap','scoreVariance','scoreTargetCovariance','withinBinCorrection'])))\n   point(kind,'reliability','Binary event rate',b['index'],b['meanPrediction'],b['eventRate'],tag='rows='+str(b['rows']))\n  for j,r in enumerate(test):\n   point(kind,'test-scores','Training-fitted probability',j,F(j+1),r['score'],'test-row position','probability',tag=r['id'])\n   point(kind,'test-scores','Observed Y',j,F(j+1),r['y'],'test-row position','binary target',tag=r['id'])\n  for name,fp,fn in SCENARIOS:\n   choice=choose(rr,{},(fp,fn));gm=groups(test,choice['selectedPolicy'],(fp,fn));scenarios.append(dict(name=name,costs=dict(falsePositive=fp,falseNegative=fn),selection=choice,groups=gm));ev=choice['evaluation']\n   for c in choice['candidates']:\n    policy=c['policy'];mm=c['metrics'];tables['validation-candidates'].append(dict(kind=kind,scenario=name,candidate=c['index'],selected=int(c['index']==choice['selectedIndex']),policy=policy if isinstance(policy,str)else'threshold',thresholdExact=''if isinstance(policy,str)else exact(policy),thresholdApprox=''if isinstance(policy,str)else approx(policy),feasible=int(c['feasible']),reasons=';'.join(c['reasons']),**{k+'Exact':str(v)for k,v in mm['confusion'].items()},**scalar_fields(mm,COUNTS+['TPR','FPR','precision','meanCost','totalCost'])))\n    point(kind,'validation-cost',name,c['index'],F(c['index']),mm['meanCost'],'candidate index','hypothetical cost units/mass','validation',tag=exact(policy))\n   mm={**ev,**ev['confusion'],**{k:cv[k]for k in ['ROC_AUC','averagePrecision','PRTrapezoidWithInitialPrecisionOne']},**{k:cal[k]for k in ['ECE','reliability','resolution','uncertainty','withinBinCorrection','BrierIdentityResidual']}}\n   for key in ['TP','FP','FN','TN']+COUNTS+RATES+['ROC_AUC','averagePrecision','PRTrapezoidWithInitialPrecisionOne','ECE','reliability','resolution','uncertainty','withinBinCorrection','BrierIdentityResidual']:\n    unit='rows'if key in ['TP','FP','FN','TN']+COUNTS else'hypothetical cost units'if key=='totalCost'else'hypothetical cost units/mass'if key=='meanCost'else'sum squared-probability loss'if key=='BrierSum'else'dimensionless'\n    tables['test-metrics'].append(dict(kind=kind,scenario=name,metric=key,valueExact=exact(mm[key]),valueApprox=approx(mm[key]),unit=unit))\n   allg=[('overall','all',gm['overall'])]+[('known',str(g['group']),g['metrics'])for g in gm['groups']]+[('unknown','',gm['unknownGroup'])]\n   for j,(typ,token,g)in enumerate(allg):\n    tables['group-metrics'].append(dict(kind=kind,scenario=name,groupType=typ,groupToken=token,retainedRows=g.get('retainedRows',sum((r['group']==token)if typ=='known'else(r['group']is None)if typ=='unknown'else True for r in test)),**{k+'Exact':str(v)for k,v in g['confusion'].items()},**scalar_fields(g,COUNTS+RATES)))\n    if typ=='known':point(kind,'group-TPR',name,j-1,F(j-1),g['TPR'],'declared group position','TPR',tag=token)\n  studies[kind]=dict(kind=kind,rows=len(native),eligibleRows=sum(r['eligible']for r in rr),trainingIDs=fit['trainIDs'],fitMedians=fit['medians'],fitCells=[dict(cell=list(k),mass=n,positive=s,probability=fit['probabilities'][k])for k,(n,s)in fit['cells'].items()],fallback=fit['fallback'],scenarios=scenarios,testCurves=cv,testCalibration=cal,rowsScored=rr)\n files=[]\n for name,rows in tables.items():\n  p=out/('computed-'+name+'.csv')\n  with p.open('w',encoding='utf8',newline='')as f:w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows)\n  files.append(dict(file=p.name,rows=len(rows),columns=len(rows[0]),bodyFields=len(rows)*len(rows[0]),sha256=hashlib.sha256(p.read_bytes()).hexdigest()))\n (out/'study.json').write_text(json.dumps(packed(studies),ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\n sourceFiles=[source/n for n in ['actual64-country-four-indicators-original-2024.csv','actual3613-NLS-original52-fields-groups-roles.csv','actual3150-churn-original14-fields-groups-roles.csv']]\n provenance=dict(chapter='ML-14',arithmetic='Python stdlib Fraction exact finite values from original decimal strings; binary64 valueApprox is display only.',inputs=[dict(file=p.name,sha256=hashlib.sha256(p.read_bytes()).hexdigest())for p in sourceFiles],priorEngineModelsScoresOrComputedFilesRead=False,roleRule=\"SHA256('ML14-role|'+kind+'|'+ID),rankmod5=0test/1validation/others train before eligibility\",costs='Hypothetical1/1,1/5,5/1; no causal intervention returns',files=files,observations={k:dict(sourceRows=v['rows'],eligibleRows=v['eligibleRows'],trainingRows=len(v['trainingIDs']))for k,v in studies.items()})\n (out/'provenance.json').write_text(json.dumps(provenance,ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\n print(json.dumps(dict(status='PASS standalone completed',files=len(files),bodyFields=sum(f['bodyFields']for f in files),observations=provenance['observations'])))\n\n# Fixed declared examples: full web budget/option validation is not reproduced.\nfrom html import escape\nimport textwrap\ndef validated_rows(raw):\n for r in raw:\n  assert F(str(r.get('weight','1')))>=0,'negative analytical mass'\n  assert r['score']is None or 0<=F(str(r['score']))<=1,'score outside zero/one'\n  assert r['y']is None or F(str(int(r['y']))if isinstance(r['y'],bool)else str(r['y']))in [0,1],'binary target required'\n return read(raw)\ndef serial(v):\n if isinstance(v,F):return dict(exactFraction=str(v),value=float(v))\n if isinstance(v,(list,tuple)):return[serial(x)for x in v]\n if isinstance(v,dict):return{k:serial(x)for k,x in v.items()}\n return v\ndef fixed_svg(path,points,title,xlabel,ylabel,legend):\n use=[p for p in points if p['xExact']!=''and p['yExact']!=''];xs=[float(F(p['xExact']))for p in use];ys=[float(F(p['yExact']))for p in use]\n xmin=min(xs,default=0);xmax=max(xs,default=1);ymin=min([0]+ys);ymax=max([0]+ys)\n if xmin==xmax:xmin-=.5;xmax+=.5\n if ymin==ymax:ymax=ymin+1\n X=lambda v:85+(float(v)-xmin)/(xmax-xmin)*480;Y=lambda v:278-(float(v)-ymin)/(ymax-ymin)*175\n s='<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"620\" height=\"360\" viewBox=\"0 0 620 360\"><rect width=\"620\" height=\"360\" fill=\"white\"/><g font-family=\"Arial, sans-serif\" font-size=\"13\" fill=\"#17324d\">'\n for i,line in enumerate(textwrap.wrap(title,width=65)):s+='<text x=\"25\" y=\"'+str(24+i*18)+'\">'+escape(line)+'</text>'\n colors=['#176b9b','#b85e18','#437e4d']\n for i,label in enumerate(legend):s+='<circle cx=\"'+str(30+i*250)+'\" cy=\"76\" r=\"4\" fill=\"'+colors[i%3]+'\"/><text x=\"'+str(42+i*250)+'\" y=\"80\">'+escape(label)+'</text>'\n s+='<path d=\"M85 98V278H575\" fill=\"none\" stroke=\"#52677d\"/><text text-anchor=\"middle\" x=\"325\" y=\"338\">'+escape(xlabel)+'</text><text text-anchor=\"middle\" transform=\"translate(21,190) rotate(-90)\">'+escape(ylabel)+'</text>'\n for i in range(5):\n  xx=xmin+(xmax-xmin)*i/4;yy=ymin+(ymax-ymin)*i/4;s+='<text text-anchor=\"middle\" x=\"'+format(X(xx),'.9g')+'\" y=\"305\">'+format(xx,'.4g')+'</text><text text-anchor=\"end\" x=\"77\" y=\"'+format(Y(yy)+4,'.9g')+'\">'+format(yy,'.4g')+'</text>'\n for p in use:s+='<circle cx=\"'+format(X(F(p['xExact'])),'.9g')+'\" cy=\"'+format(Y(F(p['yExact'])),'.9g')+'\" r=\"3\" fill=\"'+colors[p['series']%3]+'\"/>'\n path.write_text(s+'</g></svg>',encoding='utf8')\ndef fixed_run():\n ap=argparse.ArgumentParser();ap.add_argument('--out',type=Path,default=Path('results'));ap.add_argument('--data-dir',type=Path,default=Path(__file__).resolve().parent.parent/'ml14-sources');args=ap.parse_args();args.out.mkdir(parents=True,exist_ok=True)\n api=FIXED['api'];a=FIXED['args'];summary=[];points=[];xlabel='Declared index';ylabel='Value';legend=['Declared result']\n def metric(name,v,unit='dimensionless'):\n  q=None if v is None else v if isinstance(v,F)else F(v);summary.append(dict(metric=name,value='undefined'if q is None else format(float(q),'.9g'),exactValue=''if q is None else str(q),unit=unit,defined=int(q is not None)))\n def pt(i,x,y,ident='',series=0):\n  points.append(dict(series=series,index=i,xExact=''if x is None else str(F(x)),x='undefined'if x is None else format(float(x),'.9g'),yExact=''if y is None else str(F(y)),y='undefined'if y is None else format(float(y),'.9g'),id=str(ident)))\n if api=='realdata':\n  models=load_sources(args.data_dir);model=models[a['kind']];fit=actual_model(model);rr=fit['rows'];test=scoped(rr,'test');scenarios=[]\n  for name,fp,fn in SCENARIOS:\n   c=choose(rr,{},(fp,fn));scenarios.append(dict(name=name,selection=c));metric(name+'Threshold',c['selectedPolicy']);metric(name+'TestCost',c['evaluation']['meanCost'],'hypothetical cost units/mass')\n  cv=curves(test);cal=calibrate(test,[F(0),F(1,5),F(2,5),F(3,5),F(4,5),F(1)]);metric('testAUC',cv['ROC_AUC']);metric('testAP',cv['averagePrecision']);metric('testBrier',cal['Brier']);metric('eligibleRows',sum(r['eligible']for r in rr),'rows')\n  for i,r in enumerate(test):pt(i,i+1,r['score'],r['id'],0);pt(i,i+1,r['y'],r['id'],1)\n  full=dict(kind=a['kind'],fitMedians=fit['medians'],fitCells=[dict(cell=list(k),mass=n,positive=s,probability=fit['probabilities'][k])for k,(n,s)in fit['cells'].items()],rowsScored=rr,scenarios=scenarios,testCurves=cv,testCalibration=cal);xlabel='Test row, native order';ylabel='Y or probability';legend=['Training-fitted probability','Observed Y']\n else:\n  rr=validated_rows(a['rows']);role=a.get('role','all');frame=scoped(rr,role);cc=cost(a.get('costs'));t=policy(a.get('threshold','1/2'))\n  if api=='metrics':\n   full=metrics(frame,t,cc)\n   for k in ['mass','accuracy','precision','TPR','FPR','F1','Brier','meanCost']:metric(k,full[k],'mass'if k=='mass'else'hypothetical cost units/mass'if k=='meanCost'else'dimensionless')\n   metric('BayesThreshold',full['bayesThreshold'])\n   for i,k in enumerate(['TP','FP','FN','TN']):pt(i,i,full['confusion'][k],k)\n   xlabel='TP / FP / FN / TN positions';ylabel='Analytical mass'\n  elif api=='curves':\n   full=curves(frame)\n   for k in ['ROC_AUC','averagePrecision','PRTrapezoidWithInitialPrecisionOne']:metric(k,full[k])\n   for i,p in enumerate(full['points']):pt(i,p['FPR'],p['TPR'],str(p['policy']))\n   xlabel='False positive rate';ylabel='True positive rate';legend=['Observed ROC operating points']\n  elif api=='choose':\n   full=choose(rr,a,cc);metric('selectedIndex',full['selectedIndex'],'candidate index');metric('minimumCost',None if full['selectedValidation']is None else full['selectedValidation']['meanCost'],'hypothetical cost units/mass');metric('feasible',int(full['selectedIndex']is not None),'indicator')\n   for c in full['candidates']:pt(c['index'],c['index'],c['metrics']['meanCost'],str(c['policy']))\n   xlabel='Validation candidate';ylabel='Assumed cost / mass';legend=['Validation candidate costs']\n  elif api=='calibrate':\n   full=calibrate(frame,[F(str(e))for e in a.get('binEdges',['0','1/5','2/5','3/5','4/5','1'])])\n   for k in ['ECE','Brier','uncertainty','resolution','reliability','withinBinCorrection','BrierIdentityResidual']:metric(k,full[k])\n   for b in full['bins']:pt(b['index'],b['meanPrediction'],b['eventRate'],'bin:'+str(b['index']))\n   xlabel='Bin mean forecast';ylabel='Bin event rate';legend=['Binary-event reliability']\n  elif api=='groups':\n   full=groups(frame,t,cc);metric('overallTPR',full['overall']['TPR']);metric('TPRGap',full['gaps']['TPR']['value']);metric('precisionGap',full['gaps']['precision']['value']);metric('unknownMass',full['unknownGroup']['mass'],'mass');metric('partitionResidual',full['partitionMassResidual'],'mass')\n   for i,g in enumerate(full['groups']):pt(i,i,g['metrics']['TPR'],str(g['group']))\n   xlabel='Declared group position';ylabel='True positive rate';legend=['Known-group TPR']\n  else:raise ValueError('unknown fixed API')\n def csvout(name,rows):\n  with(args.out/name).open('w',encoding='utf8',newline='')as f:w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows)\n csvout('summary.csv',summary);csvout('plot-points.csv',points);fixed_svg(args.out/'plot.svg',points,FIXED['title'],xlabel,ylabel,legend)\n (args.out/'full.json').write_text(json.dumps(dict(api=api,variant=FIXED['variant'],input=FIXED['args'],arithmetic='Python standard-library Fraction, declared fixed example; full web validator/budgets not reproduced',result=serial(full)),ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\n print(json.dumps(dict(api=api,variant=FIXED['variant'],summaryMetrics=len(summary),plotSlots=len(points))))\n\nFIXED={'api': 'realdata', 'variant': 'country', 'args': {'kind': 'country'}, 'title': 'Actual country fixed train/validation/test procedure'}\nif __name__=='__main__':fixed_run()\n",
        "codeText": "#!/usr/bin/env python3\n\"\"\"ML14 standalone exact finite study, Python standard library only.\nInputs: only the three retained factual source CSVs below.\nDerived role/target/group/eligibility columns in those CSVs are NOT inputs.\nRebuilds SHA256 roles, train-only medians/cell scores, validation thresholds,\ntest curves, binary-event reliability and descriptive group ledgers.\nCosts 1/1,1/5,5/1 are hypothetical units, not measured intervention returns.\nThis is author public reproduction, not independent scientific review.\n\"\"\"\n\"\"\"Author Fraction reference, separate from product JavaScript; not independent peer.\"\"\"\nfrom fractions import Fraction as F\nfrom collections import Counter,defaultdict\ndef read(raw):\n rows=[]\n for i,r in enumerate(raw):\n  s=None if r['score']is None else F(str(r['score']));y=None if r['y']is None else F(int(r['y']))if isinstance(r['y'],bool)else F(str(r['y']));w=F(str(r.get('weight','1')));role=r.get('role','evaluation')\n  rows.append(dict(id=r['id'],index=i,score=s,y=y,w=w,role=role,group=r.get('group'),eligible=s is not None and y is not None and w>0 and role!='excluded'))\n return rows\ndef scoped(rows,role='all'):return rows if role=='all'else[r for r in rows if r['role']==role]\ndef divide(n,d):return None if not d else n/d\ndef policy(v):return v if v in ['always-negative','always-positive']else F(str(v))\ndef positive(p,s):return p=='always-positive'if isinstance(p,str)else s>=p\ndef cost(a=None):\n a={}if a is None else a;fp=F(str(a.get('falsePositive','1')));fn=F(str(a.get('falseNegative','1')));return fp,fn\ndef metrics(rows,threshold=F(1,2),cc=(F(1),F(1))):\n counts=dict(TP=F(0),FP=F(0),FN=F(0),TN=F(0));brier=F(0);pred=[]\n for r in rows:\n  if not r['eligible']:pred.append(dict(id=r['id'],index=r['index'],eligible=False,decision=None,probability=None,Brier=None));continue\n  yes=positive(threshold,r['score']);cell=('T'if yes==bool(r['y'])else'F')+('P'if yes else'N');counts[cell]+=r['w'];loss=(r['score']-r['y'])**2;brier+=r['w']*loss;pred.append(dict(id=r['id'],index=r['index'],eligible=True,decision=int(yes),probability=r['score'],Brier=loss))\n TP,FP,FN,TN=[counts[k]for k in ['TP','FP','FN','TN']];P=TP+FN;N=TN+FP;mass=P+N;PP=TP+FP;PN=TN+FN;TPR=divide(TP,P);TNR=divide(TN,N);total=FP*cc[0]+FN*cc[1]\n return dict(confusion=counts,mass=mass,positiveTargetMass=P,negativeTargetMass=N,predictedPositiveMass=PP,predictedNegativeMass=PN,prevalence=divide(P,mass),selectionRate=divide(PP,mass),accuracy=divide(TP+TN,mass),precision=divide(TP,PP),negativePredictiveValue=divide(TN,PN),TPR=TPR,FPR=divide(FP,N),TNR=TNR,FNR=divide(FN,P),F1=divide(2*TP,2*TP+FP+FN),balancedAccuracy=None if TPR is None or TNR is None else(TPR+TNR)/2,Brier=divide(brier,mass),BrierSum=brier,totalCost=total,meanCost=divide(total,mass),predictions=pred,bayesThreshold=divide(cc[0],sum(cc)))\ndef curves(rows):\n use=[r for r in rows if r['eligible']];pos=Counter();neg=Counter()\n for r in use:(pos if r['y']else neg)[r['score']]+=r['w']\n P=sum(pos.values(),F(0));N=sum(neg.values(),F(0));pairs=F(0)\n for a,wa in pos.items():\n  for b,wb in neg.items():pairs+=wa*wb*(F(1)if a>b else F(1,2)if a==b else F(0))\n thresholds=['always-negative']+sorted({r['score']for r in use},reverse=True);points=[];AP=F(0);trap=F(0);lastR=F(0);lastP=F(1)\n for i,p in enumerate(thresholds):\n  m=metrics(rows,p);points.append(dict(policy=p,TP=m['confusion']['TP'],FP=m['confusion']['FP'],FN=m['confusion']['FN'],TN=m['confusion']['TN'],TPR=m['TPR'],FPR=m['FPR'],precision=m['precision'],recall=m['TPR']))\n  if i and P:\n   R=m['TPR'];PP=m['precision'];AP+=(R-lastR)*PP;trap+=(R-lastR)*(PP+lastP)/2;lastR=R;lastP=PP\n return dict(positiveMass=P,negativeMass=N,ROC_AUC=divide(pairs,P*N),weightedConcordantPlusHalfTiedMass=pairs,averagePrecision=AP if P else None,PRTrapezoidWithInitialPrecisionOne=trap if P else None,points=points)\ndef choose(rows,a,cc):\n sr=a.get('selectionRole','validation');er=a.get('evaluationRole','test');rr=scoped(rows,sr);thresholds=[policy(t)for t in a['thresholds']]if'thresholds'in a else['always-negative']+sorted({r['score']for r in rr if r['eligible']},reverse=True)\n candidates=[]\n for i,p in enumerate(thresholds):\n  m=metrics(rr,p,cc);reasons=[]\n  if'minTPR'in a and(m['TPR']is None or m['TPR']<F(str(a['minTPR']))):reasons.append('TPR-undefined'if m['TPR']is None else'below-minTPR')\n  if'maxFPR'in a and(m['FPR']is None or m['FPR']>F(str(a['maxFPR']))):reasons.append('FPR-undefined'if m['FPR']is None else'above-maxFPR')\n  candidates.append(dict(index=i,policy=p,metrics=m,feasible=not reasons,reasons=reasons))\n eligible=[c for c in candidates if c['feasible']];best=min(eligible,key=lambda c:(c['metrics']['meanCost'],c['index']))if eligible else None\n return dict(selectedIndex=None if best is None else best['index'],selectedPolicy=None if best is None else best['policy'],candidates=candidates,selectedValidation=None if best is None else best['metrics'],evaluation=None if best is None or er=='none'else metrics(scoped(rows,er),best['policy'],cc),selectionIDs=[r['id']for r in rr if r['eligible']])\ndef calibrate(rows,ee):\n buckets=[[]for _ in range(len(ee)-1)]\n for r in rows:\n  if not r['eligible']:continue\n  j=next((i for i in range(len(ee)-1)if r['score']<ee[i+1]),len(ee)-2);buckets[j].append(r)\n mass=sum((r['w']for r in rows if r['eligible']),F(0));P=sum((r['w']*r['y']for r in rows if r['eligible']),F(0));pi=divide(P,mass);Brier=None if not mass else sum((r['w']*(r['score']-r['y'])**2 for r in rows if r['eligible']),F(0))/mass;ECE=F(0);reliability=F(0);resolution=F(0);correction=F(0);bins=[]\n for i,rr in enumerate(buckets):\n  w=sum((r['w']for r in rr),F(0));mp=None if not w else sum((r['w']*r['score']for r in rr),F(0))/w;o=None if not w else sum((r['w']*r['y']for r in rr),F(0))/w\n  variance=None if not w else sum((r['w']*(r['score']-mp)**2 for r in rr),F(0))/w\n  covariance=None if not w else sum((r['w']*(r['score']-mp)*(r['y']-o)for r in rr),F(0))/w\n  bc=None if not w else variance-2*covariance;gap=None if not w else mp-o\n  bins.append(dict(index=i,rows=len(rr),mass=w,meanPrediction=mp,eventRate=o,gap=gap,absoluteGap=None if gap is None else abs(gap),scoreVariance=variance,scoreTargetCovariance=covariance,withinBinCorrection=bc,ids=[r['id']for r in rr]))\n  if w:\n   share=w/mass;ECE+=share*abs(gap);reliability+=share*gap**2;resolution+=share*(o-pi)**2;correction+=share*bc\n uncertainty=None if pi is None else pi*(1-pi);residual=None if Brier is None else Brier-(uncertainty-resolution+reliability+correction)\n return dict(mass=mass,prevalence=pi,Brier=Brier,ECE=ECE if mass else None,reliability=reliability if mass else None,resolution=resolution if mass else None,uncertainty=uncertainty,withinBinCorrection=correction if mass else None,BrierIdentityResidual=residual,bins=bins)\ndef typed(v):return type(v).__name__,v\ndef groups(rows,p,cc):\n bins={}\n for r in rows:\n  if r['group']is not None:bins.setdefault(typed(r['group']),[]).append(r)\n gm=[dict(group=rr[0]['group'],metrics=metrics(rr,p,cc))for rr in bins.values()];overall=metrics(rows,p,cc);unknown=metrics([r for r in rows if r['group']is None],p,cc);gaps={}\n for key in ['prevalence','selectionRate','TPR','FPR','precision','accuracy','meanCost']:\n  positive=[g for g in gm if g['metrics']['mass']>0];undefined=[g['group']for g in positive if g['metrics'][key]is None];vals=[g['metrics'][key]for g in positive if g['metrics'][key]is not None]\n  gaps[key]=dict(value=None if len(positive)<2 or undefined else max(vals)-min(vals),undefinedGroups=undefined,comparedPositiveMassGroups=[g['group']for g in positive])\n return dict(overall=overall,groups=gm,unknownGroup=unknown,gaps=gaps,partitionMassResidual=overall['mass']-unknown['mass']-sum((g['metrics']['mass']for g in gm),F(0)))\ndef actual_model(M):\n raw=M['records'];cat=M['categoricalFeatures'];p=len(raw[0]['x']);train=[r for r in raw if r['role']=='train'];medians=[]\n for j in range(p):\n  if j in cat:medians.append(None);continue\n  values=sorted(F(r['x'][j])for r in train);n=len(values);medians.append(values[n//2]if n%2 else(values[n//2-1]+values[n//2])/2)\n def transform(r):return[F(v)if j in cat else F(int(F(v)>medians[j]))for j,v in enumerate(r['x'])]\n counts={}\n for r in train:\n  key=tuple(transform(r));n,s=counts.get(key,(0,0));counts[key]=(n+1,s+int(r['y']))\n probabilities={k:F(s+1,n+2)for k,(n,s)in counts.items()};fallback=F(sum(int(r['y'])for r in train)+1,len(train)+2);scored=[]\n for i,r in enumerate(raw):\n  eligible=r['role']!='excluded';z=transform(r)if eligible else None;key=None if z is None else tuple(z);score=None if not eligible else probabilities.get(key,fallback)\n  scored.append(dict(id=r['id'],index=i,role=r['role'],group=r['group'],y=None if r['y']is None else F(r['y']),score=score,w=F(1),eligible=eligible,transformedX=z,unseenCell=None if not eligible else key not in probabilities))\n return dict(medians=medians,cells=counts,probabilities=probabilities,fallback=fallback,rows=scored,trainIDs=[r['id']for r in train])\n\n\nimport csv,json,hashlib,argparse,datetime\nfrom pathlib import Path\ndef missing(v):return None if v in ['', '.',None]else v\ndef load_sources(folder):\n def read_csv(name):\n  with (folder/name).open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))\n wb=read_csv('actual64-country-four-indicators-original-2024.csv')\n codes=['NY.GDP.PCAP.KD','NY.GDP.MKTP.KD.ZG','FP.CPI.TOTL.ZG','SP.DYN.LE00.IN']\n lookup={(r['countryISO3'],r['indicatorID']):r for r in wb};country=[]\n for i,iso in enumerate(sorted({r['countryISO3']for r in wb}),1):\n  native=[lookup[iso,c]for c in codes];v=[missing(r['originalValueToken'])for r in native]\n  country.append(dict(id=iso+':2024',sourceRow=i,originalID=iso,x=v[:3],y=None if v[3]is None else str(int(F(v[3])>=80)),group=None if v[0]is None else str(int(F(v[0])>=25000)),nativeTarget=v[3],nativeSourceRows=';'.join(r['sourceRow']for r in native)))\n nls=read_csv('actual3613-NLS-original52-fields-groups-roles.csv');person=[]\n for r in nls:\n  y=missing(r['wage76']);person.append(dict(id='person:'+r['sourceRow'],sourceRow=int(r['sourceRow']),originalID=r['id'],x=[missing(r[k])for k in ['ed76','age76','nearc4']],y=None if y is None else str(int(F(y)>=500)),group=missing(r['black']),nativeTarget=y,nativeSourceRows=r['sourceRow']))\n ch=read_csv('actual3150-churn-original14-fields-groups-roles.csv');company=[]\n for r in ch:\n  company.append(dict(id='customer:'+r['sourceRow'],sourceRow=int(r['sourceRow']),originalID='',x=[missing(r[k])for k in ['Call  Failure','Complains','Subscription  Length','Seconds of Use']],y=missing(r['Churn']),group=missing(r['Tariff Plan']),nativeTarget=missing(r['Churn']),nativeSourceRows=r['sourceRow']))\n assert len(wb)==64 and len(country)==16 and len(nls)==3613 and len(ch)==3150\n assert [int(r['sourceRow'])for r in ch if r['Charge  Amount']=='10']==[474,2174,2274,2374,2674,2924,2974]\n models={}\n for kind,raw,cat,units in [('country',country,[],['constant2015USD/person','annualPercent','annualPercent']),('person',person,[2],['years','years','nativeCategory']),('company',company,[1],['count','nativeCategory','months','seconds'])]:\n  order=sorted(range(len(raw)),key=lambda i:(hashlib.sha256(('ML14-role|'+kind+'|'+raw[i]['id']).encode()).hexdigest(),i))\n  for rank,i in enumerate(order):\n   r=raw[i];r['plannedRole']='test'if rank%5==0 else'validation'if rank%5==1 else'train';r['eligible']=None not in r['x']+[r['y']];r['role']=r['plannedRole']if r['eligible']else'excluded';r['weight']='1'\n  models[kind]=dict(records=raw,categoricalFeatures=cat,featureUnits=units)\n assert sum(r['eligible']for r in person)==3017\n return models\n\ndef exact(v):return ''if v is None else str(v)\ndef approx(v):return ''if v is None else format(float(v),'.17g')\ndef scalar_fields(m,keys):\n out={}\n for k in keys:\n  out[k+'Exact']=exact(m[k]);out[k+'Approx']=approx(m[k])\n return out\nCOUNTS=['mass','positiveTargetMass','negativeTargetMass','predictedPositiveMass','predictedNegativeMass']\nRATES=['prevalence','selectionRate','accuracy','precision','negativePredictiveValue','TPR','FPR','TNR','FNR','F1','balancedAccuracy','Brier','BrierSum','totalCost','meanCost']\nSCENARIOS=[('equal',F(1),F(1)),('miss-five',F(1),F(5)),('alarm-five',F(5),F(1))]\ndef packed(v):\n if isinstance(v,F):return str(v)\n if isinstance(v,dict):return{str(k):packed(x)for k,x in v.items()}\n if isinstance(v,(tuple,list)):return[packed(x)for x in v]\n return v\ndef run_study(source,out):\n out.mkdir(parents=True,exist_ok=True);models=load_sources(source)\n tables={name:[]for name in ['predictions','lineage','fit-medians','fit-cells','validation-candidates','test-metrics','test-curves','calibration-bins','group-metrics','chart-points']}\n studies={};charts=[]\n def point(kind,chart,series,index,x,y,xunit='dimensionless',yunit='dimensionless',role='test',tag=''):\n  tables['chart-points'].append(dict(kind=kind,chart=chart,series=series,index=index,xExact=exact(x),xApprox=approx(x),yExact=exact(y),yApprox=approx(y),xUnit=xunit,yUnit=yunit,role=role,tag=tag))\n for kind,M in models.items():\n  fit=actual_model(M);rr=fit['rows'];native=M['records'];test=scoped(rr,'test');cv=curves(test);cal=calibrate(test,[F(0),F(1,5),F(2,5),F(3,5),F(4,5),F(1)]);scenarios=[]\n  for i,r in enumerate(rr):\n   n=native[i];reason=''if r['eligible']else'required-X-or-Y-missing'\n   tables['predictions'].append(dict(kind=kind,id=r['id'],sourceRow=n['sourceRow'],originalID=n['originalID'],plannedRole=n['plannedRole'],role=r['role'],group=''if r['group']is None else r['group'],eligible=int(r['eligible']),targetExact=exact(r['y']),probabilityExact=exact(r['score']),probabilityApprox=approx(r['score']),unseenCell=''if r['unseenCell']is None else int(r['unseenCell']),transformedX=''if r['transformedX']is None else'|'.join(map(str,r['transformedX'])),reason=reason))\n   tables['lineage'].append(dict(kind=kind,id=r['id'],sourceRow=n['sourceRow'],originalID=n['originalID'],nativeSourceRows=n['nativeSourceRows'],rawX='|'.join(''if x is None else x for x in n['x']),nativeTarget=''if n['nativeTarget']is None else n['nativeTarget'],derivedTarget=exact(r['y']),nativeGroup=''if n['group']is None else n['group'],plannedRole=n['plannedRole'],role=r['role'],eligible=int(r['eligible']),analyticalMass='1',reason=reason))\n  for j,v in enumerate(fit['medians']):tables['fit-medians'].append(dict(kind=kind,feature=j,categorical=int(j in M['categoricalFeatures']),fitRows=len(fit['trainIDs']),medianExact=exact(v),medianApprox=approx(v),unit=M['featureUnits'][j]))\n  for key,(mass,pos)in fit['cells'].items():tables['fit-cells'].append(dict(kind=kind,cell='|'.join(map(str,key)),trainingRows=mass,positiveRows=pos,probabilityExact=exact(fit['probabilities'][key]),probabilityApprox=approx(fit['probabilities'][key]),fallbackExact=exact(fit['fallback']),fallbackApprox=approx(fit['fallback'])))\n  for j,p in enumerate(cv['points']):\n   policy=p['policy'];tables['test-curves'].append(dict(kind=kind,point=j,policy=policy if isinstance(policy,str)else'threshold',thresholdExact=''if isinstance(policy,str)else exact(policy),thresholdApprox=''if isinstance(policy,str)else approx(policy),**scalar_fields(p,['TP','FP','FN','TN','TPR','FPR','precision','recall'])))\n   point(kind,'roc','ROC',j,p['FPR'],p['TPR']);point(kind,'pr','PR-observed',j,p['recall'],p['precision'])\n  for b in cal['bins']:\n   tables['calibration-bins'].append(dict(kind=kind,bin=b['index'],leftExact=str(F(b['index'],5)),rightExact=str(F(b['index']+1,5)),rightClosed=int(b['index']==4),rows=b['rows'],ids=';'.join(str(i)for i in b['ids']),**scalar_fields(b,['mass','meanPrediction','eventRate','gap','absoluteGap','scoreVariance','scoreTargetCovariance','withinBinCorrection'])))\n   point(kind,'reliability','Binary event rate',b['index'],b['meanPrediction'],b['eventRate'],tag='rows='+str(b['rows']))\n  for j,r in enumerate(test):\n   point(kind,'test-scores','Training-fitted probability',j,F(j+1),r['score'],'test-row position','probability',tag=r['id'])\n   point(kind,'test-scores','Observed Y',j,F(j+1),r['y'],'test-row position','binary target',tag=r['id'])\n  for name,fp,fn in SCENARIOS:\n   choice=choose(rr,{},(fp,fn));gm=groups(test,choice['selectedPolicy'],(fp,fn));scenarios.append(dict(name=name,costs=dict(falsePositive=fp,falseNegative=fn),selection=choice,groups=gm));ev=choice['evaluation']\n   for c in choice['candidates']:\n    policy=c['policy'];mm=c['metrics'];tables['validation-candidates'].append(dict(kind=kind,scenario=name,candidate=c['index'],selected=int(c['index']==choice['selectedIndex']),policy=policy if isinstance(policy,str)else'threshold',thresholdExact=''if isinstance(policy,str)else exact(policy),thresholdApprox=''if isinstance(policy,str)else approx(policy),feasible=int(c['feasible']),reasons=';'.join(c['reasons']),**{k+'Exact':str(v)for k,v in mm['confusion'].items()},**scalar_fields(mm,COUNTS+['TPR','FPR','precision','meanCost','totalCost'])))\n    point(kind,'validation-cost',name,c['index'],F(c['index']),mm['meanCost'],'candidate index','hypothetical cost units/mass','validation',tag=exact(policy))\n   mm={**ev,**ev['confusion'],**{k:cv[k]for k in ['ROC_AUC','averagePrecision','PRTrapezoidWithInitialPrecisionOne']},**{k:cal[k]for k in ['ECE','reliability','resolution','uncertainty','withinBinCorrection','BrierIdentityResidual']}}\n   for key in ['TP','FP','FN','TN']+COUNTS+RATES+['ROC_AUC','averagePrecision','PRTrapezoidWithInitialPrecisionOne','ECE','reliability','resolution','uncertainty','withinBinCorrection','BrierIdentityResidual']:\n    unit='rows'if key in ['TP','FP','FN','TN']+COUNTS else'hypothetical cost units'if key=='totalCost'else'hypothetical cost units/mass'if key=='meanCost'else'sum squared-probability loss'if key=='BrierSum'else'dimensionless'\n    tables['test-metrics'].append(dict(kind=kind,scenario=name,metric=key,valueExact=exact(mm[key]),valueApprox=approx(mm[key]),unit=unit))\n   allg=[('overall','all',gm['overall'])]+[('known',str(g['group']),g['metrics'])for g in gm['groups']]+[('unknown','',gm['unknownGroup'])]\n   for j,(typ,token,g)in enumerate(allg):\n    tables['group-metrics'].append(dict(kind=kind,scenario=name,groupType=typ,groupToken=token,retainedRows=g.get('retainedRows',sum((r['group']==token)if typ=='known'else(r['group']is None)if typ=='unknown'else True for r in test)),**{k+'Exact':str(v)for k,v in g['confusion'].items()},**scalar_fields(g,COUNTS+RATES)))\n    if typ=='known':point(kind,'group-TPR',name,j-1,F(j-1),g['TPR'],'declared group position','TPR',tag=token)\n  studies[kind]=dict(kind=kind,rows=len(native),eligibleRows=sum(r['eligible']for r in rr),trainingIDs=fit['trainIDs'],fitMedians=fit['medians'],fitCells=[dict(cell=list(k),mass=n,positive=s,probability=fit['probabilities'][k])for k,(n,s)in fit['cells'].items()],fallback=fit['fallback'],scenarios=scenarios,testCurves=cv,testCalibration=cal,rowsScored=rr)\n files=[]\n for name,rows in tables.items():\n  p=out/('computed-'+name+'.csv')\n  with p.open('w',encoding='utf8',newline='')as f:w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows)\n  files.append(dict(file=p.name,rows=len(rows),columns=len(rows[0]),bodyFields=len(rows)*len(rows[0]),sha256=hashlib.sha256(p.read_bytes()).hexdigest()))\n (out/'study.json').write_text(json.dumps(packed(studies),ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\n sourceFiles=[source/n for n in ['actual64-country-four-indicators-original-2024.csv','actual3613-NLS-original52-fields-groups-roles.csv','actual3150-churn-original14-fields-groups-roles.csv']]\n provenance=dict(chapter='ML-14',arithmetic='Python stdlib Fraction exact finite values from original decimal strings; binary64 valueApprox is display only.',inputs=[dict(file=p.name,sha256=hashlib.sha256(p.read_bytes()).hexdigest())for p in sourceFiles],priorEngineModelsScoresOrComputedFilesRead=False,roleRule=\"SHA256('ML14-role|'+kind+'|'+ID),rankmod5=0test/1validation/others train before eligibility\",costs='Hypothetical1/1,1/5,5/1; no causal intervention returns',files=files,observations={k:dict(sourceRows=v['rows'],eligibleRows=v['eligibleRows'],trainingRows=len(v['trainingIDs']))for k,v in studies.items()})\n (out/'provenance.json').write_text(json.dumps(provenance,ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\n print(json.dumps(dict(status='PASS standalone completed',files=len(files),bodyFields=sum(f['bodyFields']for f in files),observations=provenance['observations'])))\n\n# Fixed declared examples: full web budget/option validation is not reproduced.\nfrom html import escape\nimport textwrap\ndef validated_rows(raw):\n for r in raw:\n  assert F(str(r.get('weight','1')))>=0,'negative analytical mass'\n  assert r['score']is None or 0<=F(str(r['score']))<=1,'score outside zero/one'\n  assert r['y']is None or F(str(int(r['y']))if isinstance(r['y'],bool)else str(r['y']))in [0,1],'binary target required'\n return read(raw)\ndef serial(v):\n if isinstance(v,F):return dict(exactFraction=str(v),value=float(v))\n if isinstance(v,(list,tuple)):return[serial(x)for x in v]\n if isinstance(v,dict):return{k:serial(x)for k,x in v.items()}\n return v\ndef fixed_svg(path,points,title,xlabel,ylabel,legend):\n use=[p for p in points if p['xExact']!=''and p['yExact']!=''];xs=[float(F(p['xExact']))for p in use];ys=[float(F(p['yExact']))for p in use]\n xmin=min(xs,default=0);xmax=max(xs,default=1);ymin=min([0]+ys);ymax=max([0]+ys)\n if xmin==xmax:xmin-=.5;xmax+=.5\n if ymin==ymax:ymax=ymin+1\n X=lambda v:85+(float(v)-xmin)/(xmax-xmin)*480;Y=lambda v:278-(float(v)-ymin)/(ymax-ymin)*175\n s='<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"620\" height=\"360\" viewBox=\"0 0 620 360\"><rect width=\"620\" height=\"360\" fill=\"white\"/><g font-family=\"Arial, sans-serif\" font-size=\"13\" fill=\"#17324d\">'\n for i,line in enumerate(textwrap.wrap(title,width=65)):s+='<text x=\"25\" y=\"'+str(24+i*18)+'\">'+escape(line)+'</text>'\n colors=['#176b9b','#b85e18','#437e4d']\n for i,label in enumerate(legend):s+='<circle cx=\"'+str(30+i*250)+'\" cy=\"76\" r=\"4\" fill=\"'+colors[i%3]+'\"/><text x=\"'+str(42+i*250)+'\" y=\"80\">'+escape(label)+'</text>'\n s+='<path d=\"M85 98V278H575\" fill=\"none\" stroke=\"#52677d\"/><text text-anchor=\"middle\" x=\"325\" y=\"338\">'+escape(xlabel)+'</text><text text-anchor=\"middle\" transform=\"translate(21,190) rotate(-90)\">'+escape(ylabel)+'</text>'\n for i in range(5):\n  xx=xmin+(xmax-xmin)*i/4;yy=ymin+(ymax-ymin)*i/4;s+='<text text-anchor=\"middle\" x=\"'+format(X(xx),'.9g')+'\" y=\"305\">'+format(xx,'.4g')+'</text><text text-anchor=\"end\" x=\"77\" y=\"'+format(Y(yy)+4,'.9g')+'\">'+format(yy,'.4g')+'</text>'\n for p in use:s+='<circle cx=\"'+format(X(F(p['xExact'])),'.9g')+'\" cy=\"'+format(Y(F(p['yExact'])),'.9g')+'\" r=\"3\" fill=\"'+colors[p['series']%3]+'\"/>'\n path.write_text(s+'</g></svg>',encoding='utf8')\ndef fixed_run():\n ap=argparse.ArgumentParser();ap.add_argument('--out',type=Path,default=Path('results'));ap.add_argument('--data-dir',type=Path,default=Path(__file__).resolve().parent.parent/'ml14-sources');args=ap.parse_args();args.out.mkdir(parents=True,exist_ok=True)\n api=FIXED['api'];a=FIXED['args'];summary=[];points=[];xlabel='Declared index';ylabel='Value';legend=['Declared result']\n def metric(name,v,unit='dimensionless'):\n  q=None if v is None else v if isinstance(v,F)else F(v);summary.append(dict(metric=name,value='undefined'if q is None else format(float(q),'.9g'),exactValue=''if q is None else str(q),unit=unit,defined=int(q is not None)))\n def pt(i,x,y,ident='',series=0):\n  points.append(dict(series=series,index=i,xExact=''if x is None else str(F(x)),x='undefined'if x is None else format(float(x),'.9g'),yExact=''if y is None else str(F(y)),y='undefined'if y is None else format(float(y),'.9g'),id=str(ident)))\n if api=='realdata':\n  models=load_sources(args.data_dir);model=models[a['kind']];fit=actual_model(model);rr=fit['rows'];test=scoped(rr,'test');scenarios=[]\n  for name,fp,fn in SCENARIOS:\n   c=choose(rr,{},(fp,fn));scenarios.append(dict(name=name,selection=c));metric(name+'Threshold',c['selectedPolicy']);metric(name+'TestCost',c['evaluation']['meanCost'],'hypothetical cost units/mass')\n  cv=curves(test);cal=calibrate(test,[F(0),F(1,5),F(2,5),F(3,5),F(4,5),F(1)]);metric('testAUC',cv['ROC_AUC']);metric('testAP',cv['averagePrecision']);metric('testBrier',cal['Brier']);metric('eligibleRows',sum(r['eligible']for r in rr),'rows')\n  for i,r in enumerate(test):pt(i,i+1,r['score'],r['id'],0);pt(i,i+1,r['y'],r['id'],1)\n  full=dict(kind=a['kind'],fitMedians=fit['medians'],fitCells=[dict(cell=list(k),mass=n,positive=s,probability=fit['probabilities'][k])for k,(n,s)in fit['cells'].items()],rowsScored=rr,scenarios=scenarios,testCurves=cv,testCalibration=cal);xlabel='Test row, native order';ylabel='Y or probability';legend=['Training-fitted probability','Observed Y']\n else:\n  rr=validated_rows(a['rows']);role=a.get('role','all');frame=scoped(rr,role);cc=cost(a.get('costs'));t=policy(a.get('threshold','1/2'))\n  if api=='metrics':\n   full=metrics(frame,t,cc)\n   for k in ['mass','accuracy','precision','TPR','FPR','F1','Brier','meanCost']:metric(k,full[k],'mass'if k=='mass'else'hypothetical cost units/mass'if k=='meanCost'else'dimensionless')\n   metric('BayesThreshold',full['bayesThreshold'])\n   for i,k in enumerate(['TP','FP','FN','TN']):pt(i,i,full['confusion'][k],k)\n   xlabel='TP / FP / FN / TN positions';ylabel='Analytical mass'\n  elif api=='curves':\n   full=curves(frame)\n   for k in ['ROC_AUC','averagePrecision','PRTrapezoidWithInitialPrecisionOne']:metric(k,full[k])\n   for i,p in enumerate(full['points']):pt(i,p['FPR'],p['TPR'],str(p['policy']))\n   xlabel='False positive rate';ylabel='True positive rate';legend=['Observed ROC operating points']\n  elif api=='choose':\n   full=choose(rr,a,cc);metric('selectedIndex',full['selectedIndex'],'candidate index');metric('minimumCost',None if full['selectedValidation']is None else full['selectedValidation']['meanCost'],'hypothetical cost units/mass');metric('feasible',int(full['selectedIndex']is not None),'indicator')\n   for c in full['candidates']:pt(c['index'],c['index'],c['metrics']['meanCost'],str(c['policy']))\n   xlabel='Validation candidate';ylabel='Assumed cost / mass';legend=['Validation candidate costs']\n  elif api=='calibrate':\n   full=calibrate(frame,[F(str(e))for e in a.get('binEdges',['0','1/5','2/5','3/5','4/5','1'])])\n   for k in ['ECE','Brier','uncertainty','resolution','reliability','withinBinCorrection','BrierIdentityResidual']:metric(k,full[k])\n   for b in full['bins']:pt(b['index'],b['meanPrediction'],b['eventRate'],'bin:'+str(b['index']))\n   xlabel='Bin mean forecast';ylabel='Bin event rate';legend=['Binary-event reliability']\n  elif api=='groups':\n   full=groups(frame,t,cc);metric('overallTPR',full['overall']['TPR']);metric('TPRGap',full['gaps']['TPR']['value']);metric('precisionGap',full['gaps']['precision']['value']);metric('unknownMass',full['unknownGroup']['mass'],'mass');metric('partitionResidual',full['partitionMassResidual'],'mass')\n   for i,g in enumerate(full['groups']):pt(i,i,g['metrics']['TPR'],str(g['group']))\n   xlabel='Declared group position';ylabel='True positive rate';legend=['Known-group TPR']\n  else:raise ValueError('unknown fixed API')\n def csvout(name,rows):\n  with(args.out/name).open('w',encoding='utf8',newline='')as f:w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows)\n csvout('summary.csv',summary);csvout('plot-points.csv',points);fixed_svg(args.out/'plot.svg',points,FIXED['title'],xlabel,ylabel,legend)\n (args.out/'full.json').write_text(json.dumps(dict(api=api,variant=FIXED['variant'],input=FIXED['args'],arithmetic='Python standard-library Fraction, declared fixed example; full web validator/budgets not reproduced',result=serial(full)),ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\n print(json.dumps(dict(api=api,variant=FIXED['variant'],summaryMetrics=len(summary),plotSlots=len(points))))\n\nFIXED={'api': 'realdata', 'variant': 'country', 'args': {'kind': 'country'}, 'title': 'Actual country fixed train/validation/test procedure'}\nif __name__=='__main__':fixed_run()\n",
        "input": {
          "kind": "country"
        },
        "inputFiles": [
          {
            "file": "../ml14-sources/actual64-country-four-indicators-original-2024.csv",
            "sha256": "3d2b655cf807bf3ff049af187a9b7484b4e637f441f6f1925aba7acc5b0c861c"
          },
          {
            "file": "../ml14-sources/actual3613-NLS-original52-fields-groups-roles.csv",
            "sha256": "df404c3ce0336ab3ae2bfdd6b246c6e8acc058fd526ebf950dde270787bcd600"
          },
          {
            "file": "../ml14-sources/actual3150-churn-original14-fields-groups-roles.csv",
            "sha256": "d8af1f4905af8699e3ea024a6998319c82ac97b33ba1dec182391c0b30795023"
          }
        ],
        "returnCode": 0,
        "expectedFailure": false,
        "stdout": "{\"api\": \"realdata\", \"variant\": \"country\", \"summaryMetrics\": 10, \"plotSlots\": 8}\n",
        "stderr": "",
        "summary": {
          "equalThreshold": "0.75",
          "equalTestCost": "0.25",
          "miss-fiveThreshold": "0.75",
          "miss-fiveTestCost": "0.25",
          "alarm-fiveThreshold": "0.75",
          "alarm-fiveTestCost": "1.25",
          "testAUC": "0.75",
          "testAP": "0.666666667",
          "testBrier": "0.1875",
          "eligibleRows": "16"
        },
        "summaryRows": [
          {
            "metric": "equalThreshold",
            "value": "0.75",
            "exactValue": "3/4",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "equalTestCost",
            "value": "0.25",
            "exactValue": "1/4",
            "unit": "hypothetical cost units/mass",
            "defined": "1"
          },
          {
            "metric": "miss-fiveThreshold",
            "value": "0.75",
            "exactValue": "3/4",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "miss-fiveTestCost",
            "value": "0.25",
            "exactValue": "1/4",
            "unit": "hypothetical cost units/mass",
            "defined": "1"
          },
          {
            "metric": "alarm-fiveThreshold",
            "value": "0.75",
            "exactValue": "3/4",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "alarm-fiveTestCost",
            "value": "1.25",
            "exactValue": "5/4",
            "unit": "hypothetical cost units/mass",
            "defined": "1"
          },
          {
            "metric": "testAUC",
            "value": "0.75",
            "exactValue": "3/4",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "testAP",
            "value": "0.666666667",
            "exactValue": "2/3",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "testBrier",
            "value": "0.1875",
            "exactValue": "3/16",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "eligibleRows",
            "value": "16",
            "exactValue": "16",
            "unit": "rows",
            "defined": "1"
          }
        ],
        "plotPoints": [
          {
            "series": "0",
            "index": "0",
            "xExact": "1",
            "x": "1",
            "yExact": "3/4",
            "y": "0.75",
            "id": "CAN:2024"
          },
          {
            "series": "1",
            "index": "0",
            "xExact": "1",
            "x": "1",
            "yExact": "1",
            "y": "1",
            "id": "CAN:2024"
          },
          {
            "series": "0",
            "index": "1",
            "xExact": "2",
            "x": "2",
            "yExact": "3/4",
            "y": "0.75",
            "id": "JPN:2024"
          },
          {
            "series": "1",
            "index": "1",
            "xExact": "2",
            "x": "2",
            "yExact": "1",
            "y": "1",
            "id": "JPN:2024"
          },
          {
            "series": "0",
            "index": "2",
            "xExact": "3",
            "x": "3",
            "yExact": "1/4",
            "y": "0.25",
            "id": "MEX:2024"
          },
          {
            "series": "1",
            "index": "2",
            "xExact": "3",
            "x": "3",
            "yExact": "0",
            "y": "0",
            "id": "MEX:2024"
          },
          {
            "series": "0",
            "index": "3",
            "xExact": "4",
            "x": "4",
            "yExact": "3/4",
            "y": "0.75",
            "id": "USA:2024"
          },
          {
            "series": "1",
            "index": "3",
            "xExact": "4",
            "x": "4",
            "yExact": "0",
            "y": "0",
            "id": "USA:2024"
          }
        ],
        "plotFile": "ml14-fixed-results/realdata-country-python/plot.svg",
        "plotSHA256": "574e0646a22fdf93419b1c92f8c7b600a219f38cb2fceda718795aa6d7a2b998",
        "files": [
          {
            "file": "ml14-fixed-results/realdata-country-python/full.json",
            "sha256": "b0d3fdb30d4161b042789c0d51166dbecb7246979efeb6ff0415911d4bd61974",
            "bytes": 95909
          },
          {
            "file": "ml14-fixed-results/realdata-country-python/plot-points.csv",
            "sha256": "dd542e866c26000ff9c68b64b6e310fe9ee959cfa301926563efa93a29b1f6fc",
            "bytes": 231
          },
          {
            "file": "ml14-fixed-results/realdata-country-python/plot.svg",
            "sha256": "574e0646a22fdf93419b1c92f8c7b600a219f38cb2fceda718795aa6d7a2b998",
            "bytes": 1597
          },
          {
            "file": "ml14-fixed-results/realdata-country-python/summary.csv",
            "sha256": "f202521522eadfad9e6ef634035c1bcb5dfa8b52f951d051cead5d9b7a31e534",
            "bytes": 484
          }
        ],
        "scope": "Actually executed standalone fixed example, Python exact Fraction versus base-R binary64. Approximate R residuals retained; not universal exact arithmetic/web validation/native UI. Source programs read factual3CSV only."
      },
      "person": {
        "api": "realdata",
        "variant": "person",
        "language": "python",
        "title": "Actual person fixed train/validation/test procedure",
        "codeFile": "ml14-code/realdata-person.py",
        "codeSHA256": "979879037f8455848104b7eeff87c573aaf7aa826bf943ba569eb0762267e70d",
        "code": "#!/usr/bin/env python3\n\"\"\"ML14 standalone exact finite study, Python standard library only.\nInputs: only the three retained factual source CSVs below.\nDerived role/target/group/eligibility columns in those CSVs are NOT inputs.\nRebuilds SHA256 roles, train-only medians/cell scores, validation thresholds,\ntest curves, binary-event reliability and descriptive group ledgers.\nCosts 1/1,1/5,5/1 are hypothetical units, not measured intervention returns.\nThis is author public reproduction, not independent scientific review.\n\"\"\"\n\"\"\"Author Fraction reference, separate from product JavaScript; not independent peer.\"\"\"\nfrom fractions import Fraction as F\nfrom collections import Counter,defaultdict\ndef read(raw):\n rows=[]\n for i,r in enumerate(raw):\n  s=None if r['score']is None else F(str(r['score']));y=None if r['y']is None else F(int(r['y']))if isinstance(r['y'],bool)else F(str(r['y']));w=F(str(r.get('weight','1')));role=r.get('role','evaluation')\n  rows.append(dict(id=r['id'],index=i,score=s,y=y,w=w,role=role,group=r.get('group'),eligible=s is not None and y is not None and w>0 and role!='excluded'))\n return rows\ndef scoped(rows,role='all'):return rows if role=='all'else[r for r in rows if r['role']==role]\ndef divide(n,d):return None if not d else n/d\ndef policy(v):return v if v in ['always-negative','always-positive']else F(str(v))\ndef positive(p,s):return p=='always-positive'if isinstance(p,str)else s>=p\ndef cost(a=None):\n a={}if a is None else a;fp=F(str(a.get('falsePositive','1')));fn=F(str(a.get('falseNegative','1')));return fp,fn\ndef metrics(rows,threshold=F(1,2),cc=(F(1),F(1))):\n counts=dict(TP=F(0),FP=F(0),FN=F(0),TN=F(0));brier=F(0);pred=[]\n for r in rows:\n  if not r['eligible']:pred.append(dict(id=r['id'],index=r['index'],eligible=False,decision=None,probability=None,Brier=None));continue\n  yes=positive(threshold,r['score']);cell=('T'if yes==bool(r['y'])else'F')+('P'if yes else'N');counts[cell]+=r['w'];loss=(r['score']-r['y'])**2;brier+=r['w']*loss;pred.append(dict(id=r['id'],index=r['index'],eligible=True,decision=int(yes),probability=r['score'],Brier=loss))\n TP,FP,FN,TN=[counts[k]for k in ['TP','FP','FN','TN']];P=TP+FN;N=TN+FP;mass=P+N;PP=TP+FP;PN=TN+FN;TPR=divide(TP,P);TNR=divide(TN,N);total=FP*cc[0]+FN*cc[1]\n return dict(confusion=counts,mass=mass,positiveTargetMass=P,negativeTargetMass=N,predictedPositiveMass=PP,predictedNegativeMass=PN,prevalence=divide(P,mass),selectionRate=divide(PP,mass),accuracy=divide(TP+TN,mass),precision=divide(TP,PP),negativePredictiveValue=divide(TN,PN),TPR=TPR,FPR=divide(FP,N),TNR=TNR,FNR=divide(FN,P),F1=divide(2*TP,2*TP+FP+FN),balancedAccuracy=None if TPR is None or TNR is None else(TPR+TNR)/2,Brier=divide(brier,mass),BrierSum=brier,totalCost=total,meanCost=divide(total,mass),predictions=pred,bayesThreshold=divide(cc[0],sum(cc)))\ndef curves(rows):\n use=[r for r in rows if r['eligible']];pos=Counter();neg=Counter()\n for r in use:(pos if r['y']else neg)[r['score']]+=r['w']\n P=sum(pos.values(),F(0));N=sum(neg.values(),F(0));pairs=F(0)\n for a,wa in pos.items():\n  for b,wb in neg.items():pairs+=wa*wb*(F(1)if a>b else F(1,2)if a==b else F(0))\n thresholds=['always-negative']+sorted({r['score']for r in use},reverse=True);points=[];AP=F(0);trap=F(0);lastR=F(0);lastP=F(1)\n for i,p in enumerate(thresholds):\n  m=metrics(rows,p);points.append(dict(policy=p,TP=m['confusion']['TP'],FP=m['confusion']['FP'],FN=m['confusion']['FN'],TN=m['confusion']['TN'],TPR=m['TPR'],FPR=m['FPR'],precision=m['precision'],recall=m['TPR']))\n  if i and P:\n   R=m['TPR'];PP=m['precision'];AP+=(R-lastR)*PP;trap+=(R-lastR)*(PP+lastP)/2;lastR=R;lastP=PP\n return dict(positiveMass=P,negativeMass=N,ROC_AUC=divide(pairs,P*N),weightedConcordantPlusHalfTiedMass=pairs,averagePrecision=AP if P else None,PRTrapezoidWithInitialPrecisionOne=trap if P else None,points=points)\ndef choose(rows,a,cc):\n sr=a.get('selectionRole','validation');er=a.get('evaluationRole','test');rr=scoped(rows,sr);thresholds=[policy(t)for t in a['thresholds']]if'thresholds'in a else['always-negative']+sorted({r['score']for r in rr if r['eligible']},reverse=True)\n candidates=[]\n for i,p in enumerate(thresholds):\n  m=metrics(rr,p,cc);reasons=[]\n  if'minTPR'in a and(m['TPR']is None or m['TPR']<F(str(a['minTPR']))):reasons.append('TPR-undefined'if m['TPR']is None else'below-minTPR')\n  if'maxFPR'in a and(m['FPR']is None or m['FPR']>F(str(a['maxFPR']))):reasons.append('FPR-undefined'if m['FPR']is None else'above-maxFPR')\n  candidates.append(dict(index=i,policy=p,metrics=m,feasible=not reasons,reasons=reasons))\n eligible=[c for c in candidates if c['feasible']];best=min(eligible,key=lambda c:(c['metrics']['meanCost'],c['index']))if eligible else None\n return dict(selectedIndex=None if best is None else best['index'],selectedPolicy=None if best is None else best['policy'],candidates=candidates,selectedValidation=None if best is None else best['metrics'],evaluation=None if best is None or er=='none'else metrics(scoped(rows,er),best['policy'],cc),selectionIDs=[r['id']for r in rr if r['eligible']])\ndef calibrate(rows,ee):\n buckets=[[]for _ in range(len(ee)-1)]\n for r in rows:\n  if not r['eligible']:continue\n  j=next((i for i in range(len(ee)-1)if r['score']<ee[i+1]),len(ee)-2);buckets[j].append(r)\n mass=sum((r['w']for r in rows if r['eligible']),F(0));P=sum((r['w']*r['y']for r in rows if r['eligible']),F(0));pi=divide(P,mass);Brier=None if not mass else sum((r['w']*(r['score']-r['y'])**2 for r in rows if r['eligible']),F(0))/mass;ECE=F(0);reliability=F(0);resolution=F(0);correction=F(0);bins=[]\n for i,rr in enumerate(buckets):\n  w=sum((r['w']for r in rr),F(0));mp=None if not w else sum((r['w']*r['score']for r in rr),F(0))/w;o=None if not w else sum((r['w']*r['y']for r in rr),F(0))/w\n  variance=None if not w else sum((r['w']*(r['score']-mp)**2 for r in rr),F(0))/w\n  covariance=None if not w else sum((r['w']*(r['score']-mp)*(r['y']-o)for r in rr),F(0))/w\n  bc=None if not w else variance-2*covariance;gap=None if not w else mp-o\n  bins.append(dict(index=i,rows=len(rr),mass=w,meanPrediction=mp,eventRate=o,gap=gap,absoluteGap=None if gap is None else abs(gap),scoreVariance=variance,scoreTargetCovariance=covariance,withinBinCorrection=bc,ids=[r['id']for r in rr]))\n  if w:\n   share=w/mass;ECE+=share*abs(gap);reliability+=share*gap**2;resolution+=share*(o-pi)**2;correction+=share*bc\n uncertainty=None if pi is None else pi*(1-pi);residual=None if Brier is None else Brier-(uncertainty-resolution+reliability+correction)\n return dict(mass=mass,prevalence=pi,Brier=Brier,ECE=ECE if mass else None,reliability=reliability if mass else None,resolution=resolution if mass else None,uncertainty=uncertainty,withinBinCorrection=correction if mass else None,BrierIdentityResidual=residual,bins=bins)\ndef typed(v):return type(v).__name__,v\ndef groups(rows,p,cc):\n bins={}\n for r in rows:\n  if r['group']is not None:bins.setdefault(typed(r['group']),[]).append(r)\n gm=[dict(group=rr[0]['group'],metrics=metrics(rr,p,cc))for rr in bins.values()];overall=metrics(rows,p,cc);unknown=metrics([r for r in rows if r['group']is None],p,cc);gaps={}\n for key in ['prevalence','selectionRate','TPR','FPR','precision','accuracy','meanCost']:\n  positive=[g for g in gm if g['metrics']['mass']>0];undefined=[g['group']for g in positive if g['metrics'][key]is None];vals=[g['metrics'][key]for g in positive if g['metrics'][key]is not None]\n  gaps[key]=dict(value=None if len(positive)<2 or undefined else max(vals)-min(vals),undefinedGroups=undefined,comparedPositiveMassGroups=[g['group']for g in positive])\n return dict(overall=overall,groups=gm,unknownGroup=unknown,gaps=gaps,partitionMassResidual=overall['mass']-unknown['mass']-sum((g['metrics']['mass']for g in gm),F(0)))\ndef actual_model(M):\n raw=M['records'];cat=M['categoricalFeatures'];p=len(raw[0]['x']);train=[r for r in raw if r['role']=='train'];medians=[]\n for j in range(p):\n  if j in cat:medians.append(None);continue\n  values=sorted(F(r['x'][j])for r in train);n=len(values);medians.append(values[n//2]if n%2 else(values[n//2-1]+values[n//2])/2)\n def transform(r):return[F(v)if j in cat else F(int(F(v)>medians[j]))for j,v in enumerate(r['x'])]\n counts={}\n for r in train:\n  key=tuple(transform(r));n,s=counts.get(key,(0,0));counts[key]=(n+1,s+int(r['y']))\n probabilities={k:F(s+1,n+2)for k,(n,s)in counts.items()};fallback=F(sum(int(r['y'])for r in train)+1,len(train)+2);scored=[]\n for i,r in enumerate(raw):\n  eligible=r['role']!='excluded';z=transform(r)if eligible else None;key=None if z is None else tuple(z);score=None if not eligible else probabilities.get(key,fallback)\n  scored.append(dict(id=r['id'],index=i,role=r['role'],group=r['group'],y=None if r['y']is None else F(r['y']),score=score,w=F(1),eligible=eligible,transformedX=z,unseenCell=None if not eligible else key not in probabilities))\n return dict(medians=medians,cells=counts,probabilities=probabilities,fallback=fallback,rows=scored,trainIDs=[r['id']for r in train])\n\n\nimport csv,json,hashlib,argparse,datetime\nfrom pathlib import Path\ndef missing(v):return None if v in ['', '.',None]else v\ndef load_sources(folder):\n def read_csv(name):\n  with (folder/name).open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))\n wb=read_csv('actual64-country-four-indicators-original-2024.csv')\n codes=['NY.GDP.PCAP.KD','NY.GDP.MKTP.KD.ZG','FP.CPI.TOTL.ZG','SP.DYN.LE00.IN']\n lookup={(r['countryISO3'],r['indicatorID']):r for r in wb};country=[]\n for i,iso in enumerate(sorted({r['countryISO3']for r in wb}),1):\n  native=[lookup[iso,c]for c in codes];v=[missing(r['originalValueToken'])for r in native]\n  country.append(dict(id=iso+':2024',sourceRow=i,originalID=iso,x=v[:3],y=None if v[3]is None else str(int(F(v[3])>=80)),group=None if v[0]is None else str(int(F(v[0])>=25000)),nativeTarget=v[3],nativeSourceRows=';'.join(r['sourceRow']for r in native)))\n nls=read_csv('actual3613-NLS-original52-fields-groups-roles.csv');person=[]\n for r in nls:\n  y=missing(r['wage76']);person.append(dict(id='person:'+r['sourceRow'],sourceRow=int(r['sourceRow']),originalID=r['id'],x=[missing(r[k])for k in ['ed76','age76','nearc4']],y=None if y is None else str(int(F(y)>=500)),group=missing(r['black']),nativeTarget=y,nativeSourceRows=r['sourceRow']))\n ch=read_csv('actual3150-churn-original14-fields-groups-roles.csv');company=[]\n for r in ch:\n  company.append(dict(id='customer:'+r['sourceRow'],sourceRow=int(r['sourceRow']),originalID='',x=[missing(r[k])for k in ['Call  Failure','Complains','Subscription  Length','Seconds of Use']],y=missing(r['Churn']),group=missing(r['Tariff Plan']),nativeTarget=missing(r['Churn']),nativeSourceRows=r['sourceRow']))\n assert len(wb)==64 and len(country)==16 and len(nls)==3613 and len(ch)==3150\n assert [int(r['sourceRow'])for r in ch if r['Charge  Amount']=='10']==[474,2174,2274,2374,2674,2924,2974]\n models={}\n for kind,raw,cat,units in [('country',country,[],['constant2015USD/person','annualPercent','annualPercent']),('person',person,[2],['years','years','nativeCategory']),('company',company,[1],['count','nativeCategory','months','seconds'])]:\n  order=sorted(range(len(raw)),key=lambda i:(hashlib.sha256(('ML14-role|'+kind+'|'+raw[i]['id']).encode()).hexdigest(),i))\n  for rank,i in enumerate(order):\n   r=raw[i];r['plannedRole']='test'if rank%5==0 else'validation'if rank%5==1 else'train';r['eligible']=None not in r['x']+[r['y']];r['role']=r['plannedRole']if r['eligible']else'excluded';r['weight']='1'\n  models[kind]=dict(records=raw,categoricalFeatures=cat,featureUnits=units)\n assert sum(r['eligible']for r in person)==3017\n return models\n\ndef exact(v):return ''if v is None else str(v)\ndef approx(v):return ''if v is None else format(float(v),'.17g')\ndef scalar_fields(m,keys):\n out={}\n for k in keys:\n  out[k+'Exact']=exact(m[k]);out[k+'Approx']=approx(m[k])\n return out\nCOUNTS=['mass','positiveTargetMass','negativeTargetMass','predictedPositiveMass','predictedNegativeMass']\nRATES=['prevalence','selectionRate','accuracy','precision','negativePredictiveValue','TPR','FPR','TNR','FNR','F1','balancedAccuracy','Brier','BrierSum','totalCost','meanCost']\nSCENARIOS=[('equal',F(1),F(1)),('miss-five',F(1),F(5)),('alarm-five',F(5),F(1))]\ndef packed(v):\n if isinstance(v,F):return str(v)\n if isinstance(v,dict):return{str(k):packed(x)for k,x in v.items()}\n if isinstance(v,(tuple,list)):return[packed(x)for x in v]\n return v\ndef run_study(source,out):\n out.mkdir(parents=True,exist_ok=True);models=load_sources(source)\n tables={name:[]for name in ['predictions','lineage','fit-medians','fit-cells','validation-candidates','test-metrics','test-curves','calibration-bins','group-metrics','chart-points']}\n studies={};charts=[]\n def point(kind,chart,series,index,x,y,xunit='dimensionless',yunit='dimensionless',role='test',tag=''):\n  tables['chart-points'].append(dict(kind=kind,chart=chart,series=series,index=index,xExact=exact(x),xApprox=approx(x),yExact=exact(y),yApprox=approx(y),xUnit=xunit,yUnit=yunit,role=role,tag=tag))\n for kind,M in models.items():\n  fit=actual_model(M);rr=fit['rows'];native=M['records'];test=scoped(rr,'test');cv=curves(test);cal=calibrate(test,[F(0),F(1,5),F(2,5),F(3,5),F(4,5),F(1)]);scenarios=[]\n  for i,r in enumerate(rr):\n   n=native[i];reason=''if r['eligible']else'required-X-or-Y-missing'\n   tables['predictions'].append(dict(kind=kind,id=r['id'],sourceRow=n['sourceRow'],originalID=n['originalID'],plannedRole=n['plannedRole'],role=r['role'],group=''if r['group']is None else r['group'],eligible=int(r['eligible']),targetExact=exact(r['y']),probabilityExact=exact(r['score']),probabilityApprox=approx(r['score']),unseenCell=''if r['unseenCell']is None else int(r['unseenCell']),transformedX=''if r['transformedX']is None else'|'.join(map(str,r['transformedX'])),reason=reason))\n   tables['lineage'].append(dict(kind=kind,id=r['id'],sourceRow=n['sourceRow'],originalID=n['originalID'],nativeSourceRows=n['nativeSourceRows'],rawX='|'.join(''if x is None else x for x in n['x']),nativeTarget=''if n['nativeTarget']is None else n['nativeTarget'],derivedTarget=exact(r['y']),nativeGroup=''if n['group']is None else n['group'],plannedRole=n['plannedRole'],role=r['role'],eligible=int(r['eligible']),analyticalMass='1',reason=reason))\n  for j,v in enumerate(fit['medians']):tables['fit-medians'].append(dict(kind=kind,feature=j,categorical=int(j in M['categoricalFeatures']),fitRows=len(fit['trainIDs']),medianExact=exact(v),medianApprox=approx(v),unit=M['featureUnits'][j]))\n  for key,(mass,pos)in fit['cells'].items():tables['fit-cells'].append(dict(kind=kind,cell='|'.join(map(str,key)),trainingRows=mass,positiveRows=pos,probabilityExact=exact(fit['probabilities'][key]),probabilityApprox=approx(fit['probabilities'][key]),fallbackExact=exact(fit['fallback']),fallbackApprox=approx(fit['fallback'])))\n  for j,p in enumerate(cv['points']):\n   policy=p['policy'];tables['test-curves'].append(dict(kind=kind,point=j,policy=policy if isinstance(policy,str)else'threshold',thresholdExact=''if isinstance(policy,str)else exact(policy),thresholdApprox=''if isinstance(policy,str)else approx(policy),**scalar_fields(p,['TP','FP','FN','TN','TPR','FPR','precision','recall'])))\n   point(kind,'roc','ROC',j,p['FPR'],p['TPR']);point(kind,'pr','PR-observed',j,p['recall'],p['precision'])\n  for b in cal['bins']:\n   tables['calibration-bins'].append(dict(kind=kind,bin=b['index'],leftExact=str(F(b['index'],5)),rightExact=str(F(b['index']+1,5)),rightClosed=int(b['index']==4),rows=b['rows'],ids=';'.join(str(i)for i in b['ids']),**scalar_fields(b,['mass','meanPrediction','eventRate','gap','absoluteGap','scoreVariance','scoreTargetCovariance','withinBinCorrection'])))\n   point(kind,'reliability','Binary event rate',b['index'],b['meanPrediction'],b['eventRate'],tag='rows='+str(b['rows']))\n  for j,r in enumerate(test):\n   point(kind,'test-scores','Training-fitted probability',j,F(j+1),r['score'],'test-row position','probability',tag=r['id'])\n   point(kind,'test-scores','Observed Y',j,F(j+1),r['y'],'test-row position','binary target',tag=r['id'])\n  for name,fp,fn in SCENARIOS:\n   choice=choose(rr,{},(fp,fn));gm=groups(test,choice['selectedPolicy'],(fp,fn));scenarios.append(dict(name=name,costs=dict(falsePositive=fp,falseNegative=fn),selection=choice,groups=gm));ev=choice['evaluation']\n   for c in choice['candidates']:\n    policy=c['policy'];mm=c['metrics'];tables['validation-candidates'].append(dict(kind=kind,scenario=name,candidate=c['index'],selected=int(c['index']==choice['selectedIndex']),policy=policy if isinstance(policy,str)else'threshold',thresholdExact=''if isinstance(policy,str)else exact(policy),thresholdApprox=''if isinstance(policy,str)else approx(policy),feasible=int(c['feasible']),reasons=';'.join(c['reasons']),**{k+'Exact':str(v)for k,v in mm['confusion'].items()},**scalar_fields(mm,COUNTS+['TPR','FPR','precision','meanCost','totalCost'])))\n    point(kind,'validation-cost',name,c['index'],F(c['index']),mm['meanCost'],'candidate index','hypothetical cost units/mass','validation',tag=exact(policy))\n   mm={**ev,**ev['confusion'],**{k:cv[k]for k in ['ROC_AUC','averagePrecision','PRTrapezoidWithInitialPrecisionOne']},**{k:cal[k]for k in ['ECE','reliability','resolution','uncertainty','withinBinCorrection','BrierIdentityResidual']}}\n   for key in ['TP','FP','FN','TN']+COUNTS+RATES+['ROC_AUC','averagePrecision','PRTrapezoidWithInitialPrecisionOne','ECE','reliability','resolution','uncertainty','withinBinCorrection','BrierIdentityResidual']:\n    unit='rows'if key in ['TP','FP','FN','TN']+COUNTS else'hypothetical cost units'if key=='totalCost'else'hypothetical cost units/mass'if key=='meanCost'else'sum squared-probability loss'if key=='BrierSum'else'dimensionless'\n    tables['test-metrics'].append(dict(kind=kind,scenario=name,metric=key,valueExact=exact(mm[key]),valueApprox=approx(mm[key]),unit=unit))\n   allg=[('overall','all',gm['overall'])]+[('known',str(g['group']),g['metrics'])for g in gm['groups']]+[('unknown','',gm['unknownGroup'])]\n   for j,(typ,token,g)in enumerate(allg):\n    tables['group-metrics'].append(dict(kind=kind,scenario=name,groupType=typ,groupToken=token,retainedRows=g.get('retainedRows',sum((r['group']==token)if typ=='known'else(r['group']is None)if typ=='unknown'else True for r in test)),**{k+'Exact':str(v)for k,v in g['confusion'].items()},**scalar_fields(g,COUNTS+RATES)))\n    if typ=='known':point(kind,'group-TPR',name,j-1,F(j-1),g['TPR'],'declared group position','TPR',tag=token)\n  studies[kind]=dict(kind=kind,rows=len(native),eligibleRows=sum(r['eligible']for r in rr),trainingIDs=fit['trainIDs'],fitMedians=fit['medians'],fitCells=[dict(cell=list(k),mass=n,positive=s,probability=fit['probabilities'][k])for k,(n,s)in fit['cells'].items()],fallback=fit['fallback'],scenarios=scenarios,testCurves=cv,testCalibration=cal,rowsScored=rr)\n files=[]\n for name,rows in tables.items():\n  p=out/('computed-'+name+'.csv')\n  with p.open('w',encoding='utf8',newline='')as f:w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows)\n  files.append(dict(file=p.name,rows=len(rows),columns=len(rows[0]),bodyFields=len(rows)*len(rows[0]),sha256=hashlib.sha256(p.read_bytes()).hexdigest()))\n (out/'study.json').write_text(json.dumps(packed(studies),ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\n sourceFiles=[source/n for n in ['actual64-country-four-indicators-original-2024.csv','actual3613-NLS-original52-fields-groups-roles.csv','actual3150-churn-original14-fields-groups-roles.csv']]\n provenance=dict(chapter='ML-14',arithmetic='Python stdlib Fraction exact finite values from original decimal strings; binary64 valueApprox is display only.',inputs=[dict(file=p.name,sha256=hashlib.sha256(p.read_bytes()).hexdigest())for p in sourceFiles],priorEngineModelsScoresOrComputedFilesRead=False,roleRule=\"SHA256('ML14-role|'+kind+'|'+ID),rankmod5=0test/1validation/others train before eligibility\",costs='Hypothetical1/1,1/5,5/1; no causal intervention returns',files=files,observations={k:dict(sourceRows=v['rows'],eligibleRows=v['eligibleRows'],trainingRows=len(v['trainingIDs']))for k,v in studies.items()})\n (out/'provenance.json').write_text(json.dumps(provenance,ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\n print(json.dumps(dict(status='PASS standalone completed',files=len(files),bodyFields=sum(f['bodyFields']for f in files),observations=provenance['observations'])))\n\n# Fixed declared examples: full web budget/option validation is not reproduced.\nfrom html import escape\nimport textwrap\ndef validated_rows(raw):\n for r in raw:\n  assert F(str(r.get('weight','1')))>=0,'negative analytical mass'\n  assert r['score']is None or 0<=F(str(r['score']))<=1,'score outside zero/one'\n  assert r['y']is None or F(str(int(r['y']))if isinstance(r['y'],bool)else str(r['y']))in [0,1],'binary target required'\n return read(raw)\ndef serial(v):\n if isinstance(v,F):return dict(exactFraction=str(v),value=float(v))\n if isinstance(v,(list,tuple)):return[serial(x)for x in v]\n if isinstance(v,dict):return{k:serial(x)for k,x in v.items()}\n return v\ndef fixed_svg(path,points,title,xlabel,ylabel,legend):\n use=[p for p in points if p['xExact']!=''and p['yExact']!=''];xs=[float(F(p['xExact']))for p in use];ys=[float(F(p['yExact']))for p in use]\n xmin=min(xs,default=0);xmax=max(xs,default=1);ymin=min([0]+ys);ymax=max([0]+ys)\n if xmin==xmax:xmin-=.5;xmax+=.5\n if ymin==ymax:ymax=ymin+1\n X=lambda v:85+(float(v)-xmin)/(xmax-xmin)*480;Y=lambda v:278-(float(v)-ymin)/(ymax-ymin)*175\n s='<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"620\" height=\"360\" viewBox=\"0 0 620 360\"><rect width=\"620\" height=\"360\" fill=\"white\"/><g font-family=\"Arial, sans-serif\" font-size=\"13\" fill=\"#17324d\">'\n for i,line in enumerate(textwrap.wrap(title,width=65)):s+='<text x=\"25\" y=\"'+str(24+i*18)+'\">'+escape(line)+'</text>'\n colors=['#176b9b','#b85e18','#437e4d']\n for i,label in enumerate(legend):s+='<circle cx=\"'+str(30+i*250)+'\" cy=\"76\" r=\"4\" fill=\"'+colors[i%3]+'\"/><text x=\"'+str(42+i*250)+'\" y=\"80\">'+escape(label)+'</text>'\n s+='<path d=\"M85 98V278H575\" fill=\"none\" stroke=\"#52677d\"/><text text-anchor=\"middle\" x=\"325\" y=\"338\">'+escape(xlabel)+'</text><text text-anchor=\"middle\" transform=\"translate(21,190) rotate(-90)\">'+escape(ylabel)+'</text>'\n for i in range(5):\n  xx=xmin+(xmax-xmin)*i/4;yy=ymin+(ymax-ymin)*i/4;s+='<text text-anchor=\"middle\" x=\"'+format(X(xx),'.9g')+'\" y=\"305\">'+format(xx,'.4g')+'</text><text text-anchor=\"end\" x=\"77\" y=\"'+format(Y(yy)+4,'.9g')+'\">'+format(yy,'.4g')+'</text>'\n for p in use:s+='<circle cx=\"'+format(X(F(p['xExact'])),'.9g')+'\" cy=\"'+format(Y(F(p['yExact'])),'.9g')+'\" r=\"3\" fill=\"'+colors[p['series']%3]+'\"/>'\n path.write_text(s+'</g></svg>',encoding='utf8')\ndef fixed_run():\n ap=argparse.ArgumentParser();ap.add_argument('--out',type=Path,default=Path('results'));ap.add_argument('--data-dir',type=Path,default=Path(__file__).resolve().parent.parent/'ml14-sources');args=ap.parse_args();args.out.mkdir(parents=True,exist_ok=True)\n api=FIXED['api'];a=FIXED['args'];summary=[];points=[];xlabel='Declared index';ylabel='Value';legend=['Declared result']\n def metric(name,v,unit='dimensionless'):\n  q=None if v is None else v if isinstance(v,F)else F(v);summary.append(dict(metric=name,value='undefined'if q is None else format(float(q),'.9g'),exactValue=''if q is None else str(q),unit=unit,defined=int(q is not None)))\n def pt(i,x,y,ident='',series=0):\n  points.append(dict(series=series,index=i,xExact=''if x is None else str(F(x)),x='undefined'if x is None else format(float(x),'.9g'),yExact=''if y is None else str(F(y)),y='undefined'if y is None else format(float(y),'.9g'),id=str(ident)))\n if api=='realdata':\n  models=load_sources(args.data_dir);model=models[a['kind']];fit=actual_model(model);rr=fit['rows'];test=scoped(rr,'test');scenarios=[]\n  for name,fp,fn in SCENARIOS:\n   c=choose(rr,{},(fp,fn));scenarios.append(dict(name=name,selection=c));metric(name+'Threshold',c['selectedPolicy']);metric(name+'TestCost',c['evaluation']['meanCost'],'hypothetical cost units/mass')\n  cv=curves(test);cal=calibrate(test,[F(0),F(1,5),F(2,5),F(3,5),F(4,5),F(1)]);metric('testAUC',cv['ROC_AUC']);metric('testAP',cv['averagePrecision']);metric('testBrier',cal['Brier']);metric('eligibleRows',sum(r['eligible']for r in rr),'rows')\n  for i,r in enumerate(test):pt(i,i+1,r['score'],r['id'],0);pt(i,i+1,r['y'],r['id'],1)\n  full=dict(kind=a['kind'],fitMedians=fit['medians'],fitCells=[dict(cell=list(k),mass=n,positive=s,probability=fit['probabilities'][k])for k,(n,s)in fit['cells'].items()],rowsScored=rr,scenarios=scenarios,testCurves=cv,testCalibration=cal);xlabel='Test row, native order';ylabel='Y or probability';legend=['Training-fitted probability','Observed Y']\n else:\n  rr=validated_rows(a['rows']);role=a.get('role','all');frame=scoped(rr,role);cc=cost(a.get('costs'));t=policy(a.get('threshold','1/2'))\n  if api=='metrics':\n   full=metrics(frame,t,cc)\n   for k in ['mass','accuracy','precision','TPR','FPR','F1','Brier','meanCost']:metric(k,full[k],'mass'if k=='mass'else'hypothetical cost units/mass'if k=='meanCost'else'dimensionless')\n   metric('BayesThreshold',full['bayesThreshold'])\n   for i,k in enumerate(['TP','FP','FN','TN']):pt(i,i,full['confusion'][k],k)\n   xlabel='TP / FP / FN / TN positions';ylabel='Analytical mass'\n  elif api=='curves':\n   full=curves(frame)\n   for k in ['ROC_AUC','averagePrecision','PRTrapezoidWithInitialPrecisionOne']:metric(k,full[k])\n   for i,p in enumerate(full['points']):pt(i,p['FPR'],p['TPR'],str(p['policy']))\n   xlabel='False positive rate';ylabel='True positive rate';legend=['Observed ROC operating points']\n  elif api=='choose':\n   full=choose(rr,a,cc);metric('selectedIndex',full['selectedIndex'],'candidate index');metric('minimumCost',None if full['selectedValidation']is None else full['selectedValidation']['meanCost'],'hypothetical cost units/mass');metric('feasible',int(full['selectedIndex']is not None),'indicator')\n   for c in full['candidates']:pt(c['index'],c['index'],c['metrics']['meanCost'],str(c['policy']))\n   xlabel='Validation candidate';ylabel='Assumed cost / mass';legend=['Validation candidate costs']\n  elif api=='calibrate':\n   full=calibrate(frame,[F(str(e))for e in a.get('binEdges',['0','1/5','2/5','3/5','4/5','1'])])\n   for k in ['ECE','Brier','uncertainty','resolution','reliability','withinBinCorrection','BrierIdentityResidual']:metric(k,full[k])\n   for b in full['bins']:pt(b['index'],b['meanPrediction'],b['eventRate'],'bin:'+str(b['index']))\n   xlabel='Bin mean forecast';ylabel='Bin event rate';legend=['Binary-event reliability']\n  elif api=='groups':\n   full=groups(frame,t,cc);metric('overallTPR',full['overall']['TPR']);metric('TPRGap',full['gaps']['TPR']['value']);metric('precisionGap',full['gaps']['precision']['value']);metric('unknownMass',full['unknownGroup']['mass'],'mass');metric('partitionResidual',full['partitionMassResidual'],'mass')\n   for i,g in enumerate(full['groups']):pt(i,i,g['metrics']['TPR'],str(g['group']))\n   xlabel='Declared group position';ylabel='True positive rate';legend=['Known-group TPR']\n  else:raise ValueError('unknown fixed API')\n def csvout(name,rows):\n  with(args.out/name).open('w',encoding='utf8',newline='')as f:w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows)\n csvout('summary.csv',summary);csvout('plot-points.csv',points);fixed_svg(args.out/'plot.svg',points,FIXED['title'],xlabel,ylabel,legend)\n (args.out/'full.json').write_text(json.dumps(dict(api=api,variant=FIXED['variant'],input=FIXED['args'],arithmetic='Python standard-library Fraction, declared fixed example; full web validator/budgets not reproduced',result=serial(full)),ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\n print(json.dumps(dict(api=api,variant=FIXED['variant'],summaryMetrics=len(summary),plotSlots=len(points))))\n\nFIXED={'api': 'realdata', 'variant': 'person', 'args': {'kind': 'person'}, 'title': 'Actual person fixed train/validation/test procedure'}\nif __name__=='__main__':fixed_run()\n",
        "codeText": "#!/usr/bin/env python3\n\"\"\"ML14 standalone exact finite study, Python standard library only.\nInputs: only the three retained factual source CSVs below.\nDerived role/target/group/eligibility columns in those CSVs are NOT inputs.\nRebuilds SHA256 roles, train-only medians/cell scores, validation thresholds,\ntest curves, binary-event reliability and descriptive group ledgers.\nCosts 1/1,1/5,5/1 are hypothetical units, not measured intervention returns.\nThis is author public reproduction, not independent scientific review.\n\"\"\"\n\"\"\"Author Fraction reference, separate from product JavaScript; not independent peer.\"\"\"\nfrom fractions import Fraction as F\nfrom collections import Counter,defaultdict\ndef read(raw):\n rows=[]\n for i,r in enumerate(raw):\n  s=None if r['score']is None else F(str(r['score']));y=None if r['y']is None else F(int(r['y']))if isinstance(r['y'],bool)else F(str(r['y']));w=F(str(r.get('weight','1')));role=r.get('role','evaluation')\n  rows.append(dict(id=r['id'],index=i,score=s,y=y,w=w,role=role,group=r.get('group'),eligible=s is not None and y is not None and w>0 and role!='excluded'))\n return rows\ndef scoped(rows,role='all'):return rows if role=='all'else[r for r in rows if r['role']==role]\ndef divide(n,d):return None if not d else n/d\ndef policy(v):return v if v in ['always-negative','always-positive']else F(str(v))\ndef positive(p,s):return p=='always-positive'if isinstance(p,str)else s>=p\ndef cost(a=None):\n a={}if a is None else a;fp=F(str(a.get('falsePositive','1')));fn=F(str(a.get('falseNegative','1')));return fp,fn\ndef metrics(rows,threshold=F(1,2),cc=(F(1),F(1))):\n counts=dict(TP=F(0),FP=F(0),FN=F(0),TN=F(0));brier=F(0);pred=[]\n for r in rows:\n  if not r['eligible']:pred.append(dict(id=r['id'],index=r['index'],eligible=False,decision=None,probability=None,Brier=None));continue\n  yes=positive(threshold,r['score']);cell=('T'if yes==bool(r['y'])else'F')+('P'if yes else'N');counts[cell]+=r['w'];loss=(r['score']-r['y'])**2;brier+=r['w']*loss;pred.append(dict(id=r['id'],index=r['index'],eligible=True,decision=int(yes),probability=r['score'],Brier=loss))\n TP,FP,FN,TN=[counts[k]for k in ['TP','FP','FN','TN']];P=TP+FN;N=TN+FP;mass=P+N;PP=TP+FP;PN=TN+FN;TPR=divide(TP,P);TNR=divide(TN,N);total=FP*cc[0]+FN*cc[1]\n return dict(confusion=counts,mass=mass,positiveTargetMass=P,negativeTargetMass=N,predictedPositiveMass=PP,predictedNegativeMass=PN,prevalence=divide(P,mass),selectionRate=divide(PP,mass),accuracy=divide(TP+TN,mass),precision=divide(TP,PP),negativePredictiveValue=divide(TN,PN),TPR=TPR,FPR=divide(FP,N),TNR=TNR,FNR=divide(FN,P),F1=divide(2*TP,2*TP+FP+FN),balancedAccuracy=None if TPR is None or TNR is None else(TPR+TNR)/2,Brier=divide(brier,mass),BrierSum=brier,totalCost=total,meanCost=divide(total,mass),predictions=pred,bayesThreshold=divide(cc[0],sum(cc)))\ndef curves(rows):\n use=[r for r in rows if r['eligible']];pos=Counter();neg=Counter()\n for r in use:(pos if r['y']else neg)[r['score']]+=r['w']\n P=sum(pos.values(),F(0));N=sum(neg.values(),F(0));pairs=F(0)\n for a,wa in pos.items():\n  for b,wb in neg.items():pairs+=wa*wb*(F(1)if a>b else F(1,2)if a==b else F(0))\n thresholds=['always-negative']+sorted({r['score']for r in use},reverse=True);points=[];AP=F(0);trap=F(0);lastR=F(0);lastP=F(1)\n for i,p in enumerate(thresholds):\n  m=metrics(rows,p);points.append(dict(policy=p,TP=m['confusion']['TP'],FP=m['confusion']['FP'],FN=m['confusion']['FN'],TN=m['confusion']['TN'],TPR=m['TPR'],FPR=m['FPR'],precision=m['precision'],recall=m['TPR']))\n  if i and P:\n   R=m['TPR'];PP=m['precision'];AP+=(R-lastR)*PP;trap+=(R-lastR)*(PP+lastP)/2;lastR=R;lastP=PP\n return dict(positiveMass=P,negativeMass=N,ROC_AUC=divide(pairs,P*N),weightedConcordantPlusHalfTiedMass=pairs,averagePrecision=AP if P else None,PRTrapezoidWithInitialPrecisionOne=trap if P else None,points=points)\ndef choose(rows,a,cc):\n sr=a.get('selectionRole','validation');er=a.get('evaluationRole','test');rr=scoped(rows,sr);thresholds=[policy(t)for t in a['thresholds']]if'thresholds'in a else['always-negative']+sorted({r['score']for r in rr if r['eligible']},reverse=True)\n candidates=[]\n for i,p in enumerate(thresholds):\n  m=metrics(rr,p,cc);reasons=[]\n  if'minTPR'in a and(m['TPR']is None or m['TPR']<F(str(a['minTPR']))):reasons.append('TPR-undefined'if m['TPR']is None else'below-minTPR')\n  if'maxFPR'in a and(m['FPR']is None or m['FPR']>F(str(a['maxFPR']))):reasons.append('FPR-undefined'if m['FPR']is None else'above-maxFPR')\n  candidates.append(dict(index=i,policy=p,metrics=m,feasible=not reasons,reasons=reasons))\n eligible=[c for c in candidates if c['feasible']];best=min(eligible,key=lambda c:(c['metrics']['meanCost'],c['index']))if eligible else None\n return dict(selectedIndex=None if best is None else best['index'],selectedPolicy=None if best is None else best['policy'],candidates=candidates,selectedValidation=None if best is None else best['metrics'],evaluation=None if best is None or er=='none'else metrics(scoped(rows,er),best['policy'],cc),selectionIDs=[r['id']for r in rr if r['eligible']])\ndef calibrate(rows,ee):\n buckets=[[]for _ in range(len(ee)-1)]\n for r in rows:\n  if not r['eligible']:continue\n  j=next((i for i in range(len(ee)-1)if r['score']<ee[i+1]),len(ee)-2);buckets[j].append(r)\n mass=sum((r['w']for r in rows if r['eligible']),F(0));P=sum((r['w']*r['y']for r in rows if r['eligible']),F(0));pi=divide(P,mass);Brier=None if not mass else sum((r['w']*(r['score']-r['y'])**2 for r in rows if r['eligible']),F(0))/mass;ECE=F(0);reliability=F(0);resolution=F(0);correction=F(0);bins=[]\n for i,rr in enumerate(buckets):\n  w=sum((r['w']for r in rr),F(0));mp=None if not w else sum((r['w']*r['score']for r in rr),F(0))/w;o=None if not w else sum((r['w']*r['y']for r in rr),F(0))/w\n  variance=None if not w else sum((r['w']*(r['score']-mp)**2 for r in rr),F(0))/w\n  covariance=None if not w else sum((r['w']*(r['score']-mp)*(r['y']-o)for r in rr),F(0))/w\n  bc=None if not w else variance-2*covariance;gap=None if not w else mp-o\n  bins.append(dict(index=i,rows=len(rr),mass=w,meanPrediction=mp,eventRate=o,gap=gap,absoluteGap=None if gap is None else abs(gap),scoreVariance=variance,scoreTargetCovariance=covariance,withinBinCorrection=bc,ids=[r['id']for r in rr]))\n  if w:\n   share=w/mass;ECE+=share*abs(gap);reliability+=share*gap**2;resolution+=share*(o-pi)**2;correction+=share*bc\n uncertainty=None if pi is None else pi*(1-pi);residual=None if Brier is None else Brier-(uncertainty-resolution+reliability+correction)\n return dict(mass=mass,prevalence=pi,Brier=Brier,ECE=ECE if mass else None,reliability=reliability if mass else None,resolution=resolution if mass else None,uncertainty=uncertainty,withinBinCorrection=correction if mass else None,BrierIdentityResidual=residual,bins=bins)\ndef typed(v):return type(v).__name__,v\ndef groups(rows,p,cc):\n bins={}\n for r in rows:\n  if r['group']is not None:bins.setdefault(typed(r['group']),[]).append(r)\n gm=[dict(group=rr[0]['group'],metrics=metrics(rr,p,cc))for rr in bins.values()];overall=metrics(rows,p,cc);unknown=metrics([r for r in rows if r['group']is None],p,cc);gaps={}\n for key in ['prevalence','selectionRate','TPR','FPR','precision','accuracy','meanCost']:\n  positive=[g for g in gm if g['metrics']['mass']>0];undefined=[g['group']for g in positive if g['metrics'][key]is None];vals=[g['metrics'][key]for g in positive if g['metrics'][key]is not None]\n  gaps[key]=dict(value=None if len(positive)<2 or undefined else max(vals)-min(vals),undefinedGroups=undefined,comparedPositiveMassGroups=[g['group']for g in positive])\n return dict(overall=overall,groups=gm,unknownGroup=unknown,gaps=gaps,partitionMassResidual=overall['mass']-unknown['mass']-sum((g['metrics']['mass']for g in gm),F(0)))\ndef actual_model(M):\n raw=M['records'];cat=M['categoricalFeatures'];p=len(raw[0]['x']);train=[r for r in raw if r['role']=='train'];medians=[]\n for j in range(p):\n  if j in cat:medians.append(None);continue\n  values=sorted(F(r['x'][j])for r in train);n=len(values);medians.append(values[n//2]if n%2 else(values[n//2-1]+values[n//2])/2)\n def transform(r):return[F(v)if j in cat else F(int(F(v)>medians[j]))for j,v in enumerate(r['x'])]\n counts={}\n for r in train:\n  key=tuple(transform(r));n,s=counts.get(key,(0,0));counts[key]=(n+1,s+int(r['y']))\n probabilities={k:F(s+1,n+2)for k,(n,s)in counts.items()};fallback=F(sum(int(r['y'])for r in train)+1,len(train)+2);scored=[]\n for i,r in enumerate(raw):\n  eligible=r['role']!='excluded';z=transform(r)if eligible else None;key=None if z is None else tuple(z);score=None if not eligible else probabilities.get(key,fallback)\n  scored.append(dict(id=r['id'],index=i,role=r['role'],group=r['group'],y=None if r['y']is None else F(r['y']),score=score,w=F(1),eligible=eligible,transformedX=z,unseenCell=None if not eligible else key not in probabilities))\n return dict(medians=medians,cells=counts,probabilities=probabilities,fallback=fallback,rows=scored,trainIDs=[r['id']for r in train])\n\n\nimport csv,json,hashlib,argparse,datetime\nfrom pathlib import Path\ndef missing(v):return None if v in ['', '.',None]else v\ndef load_sources(folder):\n def read_csv(name):\n  with (folder/name).open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))\n wb=read_csv('actual64-country-four-indicators-original-2024.csv')\n codes=['NY.GDP.PCAP.KD','NY.GDP.MKTP.KD.ZG','FP.CPI.TOTL.ZG','SP.DYN.LE00.IN']\n lookup={(r['countryISO3'],r['indicatorID']):r for r in wb};country=[]\n for i,iso in enumerate(sorted({r['countryISO3']for r in wb}),1):\n  native=[lookup[iso,c]for c in codes];v=[missing(r['originalValueToken'])for r in native]\n  country.append(dict(id=iso+':2024',sourceRow=i,originalID=iso,x=v[:3],y=None if v[3]is None else str(int(F(v[3])>=80)),group=None if v[0]is None else str(int(F(v[0])>=25000)),nativeTarget=v[3],nativeSourceRows=';'.join(r['sourceRow']for r in native)))\n nls=read_csv('actual3613-NLS-original52-fields-groups-roles.csv');person=[]\n for r in nls:\n  y=missing(r['wage76']);person.append(dict(id='person:'+r['sourceRow'],sourceRow=int(r['sourceRow']),originalID=r['id'],x=[missing(r[k])for k in ['ed76','age76','nearc4']],y=None if y is None else str(int(F(y)>=500)),group=missing(r['black']),nativeTarget=y,nativeSourceRows=r['sourceRow']))\n ch=read_csv('actual3150-churn-original14-fields-groups-roles.csv');company=[]\n for r in ch:\n  company.append(dict(id='customer:'+r['sourceRow'],sourceRow=int(r['sourceRow']),originalID='',x=[missing(r[k])for k in ['Call  Failure','Complains','Subscription  Length','Seconds of Use']],y=missing(r['Churn']),group=missing(r['Tariff Plan']),nativeTarget=missing(r['Churn']),nativeSourceRows=r['sourceRow']))\n assert len(wb)==64 and len(country)==16 and len(nls)==3613 and len(ch)==3150\n assert [int(r['sourceRow'])for r in ch if r['Charge  Amount']=='10']==[474,2174,2274,2374,2674,2924,2974]\n models={}\n for kind,raw,cat,units in [('country',country,[],['constant2015USD/person','annualPercent','annualPercent']),('person',person,[2],['years','years','nativeCategory']),('company',company,[1],['count','nativeCategory','months','seconds'])]:\n  order=sorted(range(len(raw)),key=lambda i:(hashlib.sha256(('ML14-role|'+kind+'|'+raw[i]['id']).encode()).hexdigest(),i))\n  for rank,i in enumerate(order):\n   r=raw[i];r['plannedRole']='test'if rank%5==0 else'validation'if rank%5==1 else'train';r['eligible']=None not in r['x']+[r['y']];r['role']=r['plannedRole']if r['eligible']else'excluded';r['weight']='1'\n  models[kind]=dict(records=raw,categoricalFeatures=cat,featureUnits=units)\n assert sum(r['eligible']for r in person)==3017\n return models\n\ndef exact(v):return ''if v is None else str(v)\ndef approx(v):return ''if v is None else format(float(v),'.17g')\ndef scalar_fields(m,keys):\n out={}\n for k in keys:\n  out[k+'Exact']=exact(m[k]);out[k+'Approx']=approx(m[k])\n return out\nCOUNTS=['mass','positiveTargetMass','negativeTargetMass','predictedPositiveMass','predictedNegativeMass']\nRATES=['prevalence','selectionRate','accuracy','precision','negativePredictiveValue','TPR','FPR','TNR','FNR','F1','balancedAccuracy','Brier','BrierSum','totalCost','meanCost']\nSCENARIOS=[('equal',F(1),F(1)),('miss-five',F(1),F(5)),('alarm-five',F(5),F(1))]\ndef packed(v):\n if isinstance(v,F):return str(v)\n if isinstance(v,dict):return{str(k):packed(x)for k,x in v.items()}\n if isinstance(v,(tuple,list)):return[packed(x)for x in v]\n return v\ndef run_study(source,out):\n out.mkdir(parents=True,exist_ok=True);models=load_sources(source)\n tables={name:[]for name in ['predictions','lineage','fit-medians','fit-cells','validation-candidates','test-metrics','test-curves','calibration-bins','group-metrics','chart-points']}\n studies={};charts=[]\n def point(kind,chart,series,index,x,y,xunit='dimensionless',yunit='dimensionless',role='test',tag=''):\n  tables['chart-points'].append(dict(kind=kind,chart=chart,series=series,index=index,xExact=exact(x),xApprox=approx(x),yExact=exact(y),yApprox=approx(y),xUnit=xunit,yUnit=yunit,role=role,tag=tag))\n for kind,M in models.items():\n  fit=actual_model(M);rr=fit['rows'];native=M['records'];test=scoped(rr,'test');cv=curves(test);cal=calibrate(test,[F(0),F(1,5),F(2,5),F(3,5),F(4,5),F(1)]);scenarios=[]\n  for i,r in enumerate(rr):\n   n=native[i];reason=''if r['eligible']else'required-X-or-Y-missing'\n   tables['predictions'].append(dict(kind=kind,id=r['id'],sourceRow=n['sourceRow'],originalID=n['originalID'],plannedRole=n['plannedRole'],role=r['role'],group=''if r['group']is None else r['group'],eligible=int(r['eligible']),targetExact=exact(r['y']),probabilityExact=exact(r['score']),probabilityApprox=approx(r['score']),unseenCell=''if r['unseenCell']is None else int(r['unseenCell']),transformedX=''if r['transformedX']is None else'|'.join(map(str,r['transformedX'])),reason=reason))\n   tables['lineage'].append(dict(kind=kind,id=r['id'],sourceRow=n['sourceRow'],originalID=n['originalID'],nativeSourceRows=n['nativeSourceRows'],rawX='|'.join(''if x is None else x for x in n['x']),nativeTarget=''if n['nativeTarget']is None else n['nativeTarget'],derivedTarget=exact(r['y']),nativeGroup=''if n['group']is None else n['group'],plannedRole=n['plannedRole'],role=r['role'],eligible=int(r['eligible']),analyticalMass='1',reason=reason))\n  for j,v in enumerate(fit['medians']):tables['fit-medians'].append(dict(kind=kind,feature=j,categorical=int(j in M['categoricalFeatures']),fitRows=len(fit['trainIDs']),medianExact=exact(v),medianApprox=approx(v),unit=M['featureUnits'][j]))\n  for key,(mass,pos)in fit['cells'].items():tables['fit-cells'].append(dict(kind=kind,cell='|'.join(map(str,key)),trainingRows=mass,positiveRows=pos,probabilityExact=exact(fit['probabilities'][key]),probabilityApprox=approx(fit['probabilities'][key]),fallbackExact=exact(fit['fallback']),fallbackApprox=approx(fit['fallback'])))\n  for j,p in enumerate(cv['points']):\n   policy=p['policy'];tables['test-curves'].append(dict(kind=kind,point=j,policy=policy if isinstance(policy,str)else'threshold',thresholdExact=''if isinstance(policy,str)else exact(policy),thresholdApprox=''if isinstance(policy,str)else approx(policy),**scalar_fields(p,['TP','FP','FN','TN','TPR','FPR','precision','recall'])))\n   point(kind,'roc','ROC',j,p['FPR'],p['TPR']);point(kind,'pr','PR-observed',j,p['recall'],p['precision'])\n  for b in cal['bins']:\n   tables['calibration-bins'].append(dict(kind=kind,bin=b['index'],leftExact=str(F(b['index'],5)),rightExact=str(F(b['index']+1,5)),rightClosed=int(b['index']==4),rows=b['rows'],ids=';'.join(str(i)for i in b['ids']),**scalar_fields(b,['mass','meanPrediction','eventRate','gap','absoluteGap','scoreVariance','scoreTargetCovariance','withinBinCorrection'])))\n   point(kind,'reliability','Binary event rate',b['index'],b['meanPrediction'],b['eventRate'],tag='rows='+str(b['rows']))\n  for j,r in enumerate(test):\n   point(kind,'test-scores','Training-fitted probability',j,F(j+1),r['score'],'test-row position','probability',tag=r['id'])\n   point(kind,'test-scores','Observed Y',j,F(j+1),r['y'],'test-row position','binary target',tag=r['id'])\n  for name,fp,fn in SCENARIOS:\n   choice=choose(rr,{},(fp,fn));gm=groups(test,choice['selectedPolicy'],(fp,fn));scenarios.append(dict(name=name,costs=dict(falsePositive=fp,falseNegative=fn),selection=choice,groups=gm));ev=choice['evaluation']\n   for c in choice['candidates']:\n    policy=c['policy'];mm=c['metrics'];tables['validation-candidates'].append(dict(kind=kind,scenario=name,candidate=c['index'],selected=int(c['index']==choice['selectedIndex']),policy=policy if isinstance(policy,str)else'threshold',thresholdExact=''if isinstance(policy,str)else exact(policy),thresholdApprox=''if isinstance(policy,str)else approx(policy),feasible=int(c['feasible']),reasons=';'.join(c['reasons']),**{k+'Exact':str(v)for k,v in mm['confusion'].items()},**scalar_fields(mm,COUNTS+['TPR','FPR','precision','meanCost','totalCost'])))\n    point(kind,'validation-cost',name,c['index'],F(c['index']),mm['meanCost'],'candidate index','hypothetical cost units/mass','validation',tag=exact(policy))\n   mm={**ev,**ev['confusion'],**{k:cv[k]for k in ['ROC_AUC','averagePrecision','PRTrapezoidWithInitialPrecisionOne']},**{k:cal[k]for k in ['ECE','reliability','resolution','uncertainty','withinBinCorrection','BrierIdentityResidual']}}\n   for key in ['TP','FP','FN','TN']+COUNTS+RATES+['ROC_AUC','averagePrecision','PRTrapezoidWithInitialPrecisionOne','ECE','reliability','resolution','uncertainty','withinBinCorrection','BrierIdentityResidual']:\n    unit='rows'if key in ['TP','FP','FN','TN']+COUNTS else'hypothetical cost units'if key=='totalCost'else'hypothetical cost units/mass'if key=='meanCost'else'sum squared-probability loss'if key=='BrierSum'else'dimensionless'\n    tables['test-metrics'].append(dict(kind=kind,scenario=name,metric=key,valueExact=exact(mm[key]),valueApprox=approx(mm[key]),unit=unit))\n   allg=[('overall','all',gm['overall'])]+[('known',str(g['group']),g['metrics'])for g in gm['groups']]+[('unknown','',gm['unknownGroup'])]\n   for j,(typ,token,g)in enumerate(allg):\n    tables['group-metrics'].append(dict(kind=kind,scenario=name,groupType=typ,groupToken=token,retainedRows=g.get('retainedRows',sum((r['group']==token)if typ=='known'else(r['group']is None)if typ=='unknown'else True for r in test)),**{k+'Exact':str(v)for k,v in g['confusion'].items()},**scalar_fields(g,COUNTS+RATES)))\n    if typ=='known':point(kind,'group-TPR',name,j-1,F(j-1),g['TPR'],'declared group position','TPR',tag=token)\n  studies[kind]=dict(kind=kind,rows=len(native),eligibleRows=sum(r['eligible']for r in rr),trainingIDs=fit['trainIDs'],fitMedians=fit['medians'],fitCells=[dict(cell=list(k),mass=n,positive=s,probability=fit['probabilities'][k])for k,(n,s)in fit['cells'].items()],fallback=fit['fallback'],scenarios=scenarios,testCurves=cv,testCalibration=cal,rowsScored=rr)\n files=[]\n for name,rows in tables.items():\n  p=out/('computed-'+name+'.csv')\n  with p.open('w',encoding='utf8',newline='')as f:w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows)\n  files.append(dict(file=p.name,rows=len(rows),columns=len(rows[0]),bodyFields=len(rows)*len(rows[0]),sha256=hashlib.sha256(p.read_bytes()).hexdigest()))\n (out/'study.json').write_text(json.dumps(packed(studies),ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\n sourceFiles=[source/n for n in ['actual64-country-four-indicators-original-2024.csv','actual3613-NLS-original52-fields-groups-roles.csv','actual3150-churn-original14-fields-groups-roles.csv']]\n provenance=dict(chapter='ML-14',arithmetic='Python stdlib Fraction exact finite values from original decimal strings; binary64 valueApprox is display only.',inputs=[dict(file=p.name,sha256=hashlib.sha256(p.read_bytes()).hexdigest())for p in sourceFiles],priorEngineModelsScoresOrComputedFilesRead=False,roleRule=\"SHA256('ML14-role|'+kind+'|'+ID),rankmod5=0test/1validation/others train before eligibility\",costs='Hypothetical1/1,1/5,5/1; no causal intervention returns',files=files,observations={k:dict(sourceRows=v['rows'],eligibleRows=v['eligibleRows'],trainingRows=len(v['trainingIDs']))for k,v in studies.items()})\n (out/'provenance.json').write_text(json.dumps(provenance,ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\n print(json.dumps(dict(status='PASS standalone completed',files=len(files),bodyFields=sum(f['bodyFields']for f in files),observations=provenance['observations'])))\n\n# Fixed declared examples: full web budget/option validation is not reproduced.\nfrom html import escape\nimport textwrap\ndef validated_rows(raw):\n for r in raw:\n  assert F(str(r.get('weight','1')))>=0,'negative analytical mass'\n  assert r['score']is None or 0<=F(str(r['score']))<=1,'score outside zero/one'\n  assert r['y']is None or F(str(int(r['y']))if isinstance(r['y'],bool)else str(r['y']))in [0,1],'binary target required'\n return read(raw)\ndef serial(v):\n if isinstance(v,F):return dict(exactFraction=str(v),value=float(v))\n if isinstance(v,(list,tuple)):return[serial(x)for x in v]\n if isinstance(v,dict):return{k:serial(x)for k,x in v.items()}\n return v\ndef fixed_svg(path,points,title,xlabel,ylabel,legend):\n use=[p for p in points if p['xExact']!=''and p['yExact']!=''];xs=[float(F(p['xExact']))for p in use];ys=[float(F(p['yExact']))for p in use]\n xmin=min(xs,default=0);xmax=max(xs,default=1);ymin=min([0]+ys);ymax=max([0]+ys)\n if xmin==xmax:xmin-=.5;xmax+=.5\n if ymin==ymax:ymax=ymin+1\n X=lambda v:85+(float(v)-xmin)/(xmax-xmin)*480;Y=lambda v:278-(float(v)-ymin)/(ymax-ymin)*175\n s='<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"620\" height=\"360\" viewBox=\"0 0 620 360\"><rect width=\"620\" height=\"360\" fill=\"white\"/><g font-family=\"Arial, sans-serif\" font-size=\"13\" fill=\"#17324d\">'\n for i,line in enumerate(textwrap.wrap(title,width=65)):s+='<text x=\"25\" y=\"'+str(24+i*18)+'\">'+escape(line)+'</text>'\n colors=['#176b9b','#b85e18','#437e4d']\n for i,label in enumerate(legend):s+='<circle cx=\"'+str(30+i*250)+'\" cy=\"76\" r=\"4\" fill=\"'+colors[i%3]+'\"/><text x=\"'+str(42+i*250)+'\" y=\"80\">'+escape(label)+'</text>'\n s+='<path d=\"M85 98V278H575\" fill=\"none\" stroke=\"#52677d\"/><text text-anchor=\"middle\" x=\"325\" y=\"338\">'+escape(xlabel)+'</text><text text-anchor=\"middle\" transform=\"translate(21,190) rotate(-90)\">'+escape(ylabel)+'</text>'\n for i in range(5):\n  xx=xmin+(xmax-xmin)*i/4;yy=ymin+(ymax-ymin)*i/4;s+='<text text-anchor=\"middle\" x=\"'+format(X(xx),'.9g')+'\" y=\"305\">'+format(xx,'.4g')+'</text><text text-anchor=\"end\" x=\"77\" y=\"'+format(Y(yy)+4,'.9g')+'\">'+format(yy,'.4g')+'</text>'\n for p in use:s+='<circle cx=\"'+format(X(F(p['xExact'])),'.9g')+'\" cy=\"'+format(Y(F(p['yExact'])),'.9g')+'\" r=\"3\" fill=\"'+colors[p['series']%3]+'\"/>'\n path.write_text(s+'</g></svg>',encoding='utf8')\ndef fixed_run():\n ap=argparse.ArgumentParser();ap.add_argument('--out',type=Path,default=Path('results'));ap.add_argument('--data-dir',type=Path,default=Path(__file__).resolve().parent.parent/'ml14-sources');args=ap.parse_args();args.out.mkdir(parents=True,exist_ok=True)\n api=FIXED['api'];a=FIXED['args'];summary=[];points=[];xlabel='Declared index';ylabel='Value';legend=['Declared result']\n def metric(name,v,unit='dimensionless'):\n  q=None if v is None else v if isinstance(v,F)else F(v);summary.append(dict(metric=name,value='undefined'if q is None else format(float(q),'.9g'),exactValue=''if q is None else str(q),unit=unit,defined=int(q is not None)))\n def pt(i,x,y,ident='',series=0):\n  points.append(dict(series=series,index=i,xExact=''if x is None else str(F(x)),x='undefined'if x is None else format(float(x),'.9g'),yExact=''if y is None else str(F(y)),y='undefined'if y is None else format(float(y),'.9g'),id=str(ident)))\n if api=='realdata':\n  models=load_sources(args.data_dir);model=models[a['kind']];fit=actual_model(model);rr=fit['rows'];test=scoped(rr,'test');scenarios=[]\n  for name,fp,fn in SCENARIOS:\n   c=choose(rr,{},(fp,fn));scenarios.append(dict(name=name,selection=c));metric(name+'Threshold',c['selectedPolicy']);metric(name+'TestCost',c['evaluation']['meanCost'],'hypothetical cost units/mass')\n  cv=curves(test);cal=calibrate(test,[F(0),F(1,5),F(2,5),F(3,5),F(4,5),F(1)]);metric('testAUC',cv['ROC_AUC']);metric('testAP',cv['averagePrecision']);metric('testBrier',cal['Brier']);metric('eligibleRows',sum(r['eligible']for r in rr),'rows')\n  for i,r in enumerate(test):pt(i,i+1,r['score'],r['id'],0);pt(i,i+1,r['y'],r['id'],1)\n  full=dict(kind=a['kind'],fitMedians=fit['medians'],fitCells=[dict(cell=list(k),mass=n,positive=s,probability=fit['probabilities'][k])for k,(n,s)in fit['cells'].items()],rowsScored=rr,scenarios=scenarios,testCurves=cv,testCalibration=cal);xlabel='Test row, native order';ylabel='Y or probability';legend=['Training-fitted probability','Observed Y']\n else:\n  rr=validated_rows(a['rows']);role=a.get('role','all');frame=scoped(rr,role);cc=cost(a.get('costs'));t=policy(a.get('threshold','1/2'))\n  if api=='metrics':\n   full=metrics(frame,t,cc)\n   for k in ['mass','accuracy','precision','TPR','FPR','F1','Brier','meanCost']:metric(k,full[k],'mass'if k=='mass'else'hypothetical cost units/mass'if k=='meanCost'else'dimensionless')\n   metric('BayesThreshold',full['bayesThreshold'])\n   for i,k in enumerate(['TP','FP','FN','TN']):pt(i,i,full['confusion'][k],k)\n   xlabel='TP / FP / FN / TN positions';ylabel='Analytical mass'\n  elif api=='curves':\n   full=curves(frame)\n   for k in ['ROC_AUC','averagePrecision','PRTrapezoidWithInitialPrecisionOne']:metric(k,full[k])\n   for i,p in enumerate(full['points']):pt(i,p['FPR'],p['TPR'],str(p['policy']))\n   xlabel='False positive rate';ylabel='True positive rate';legend=['Observed ROC operating points']\n  elif api=='choose':\n   full=choose(rr,a,cc);metric('selectedIndex',full['selectedIndex'],'candidate index');metric('minimumCost',None if full['selectedValidation']is None else full['selectedValidation']['meanCost'],'hypothetical cost units/mass');metric('feasible',int(full['selectedIndex']is not None),'indicator')\n   for c in full['candidates']:pt(c['index'],c['index'],c['metrics']['meanCost'],str(c['policy']))\n   xlabel='Validation candidate';ylabel='Assumed cost / mass';legend=['Validation candidate costs']\n  elif api=='calibrate':\n   full=calibrate(frame,[F(str(e))for e in a.get('binEdges',['0','1/5','2/5','3/5','4/5','1'])])\n   for k in ['ECE','Brier','uncertainty','resolution','reliability','withinBinCorrection','BrierIdentityResidual']:metric(k,full[k])\n   for b in full['bins']:pt(b['index'],b['meanPrediction'],b['eventRate'],'bin:'+str(b['index']))\n   xlabel='Bin mean forecast';ylabel='Bin event rate';legend=['Binary-event reliability']\n  elif api=='groups':\n   full=groups(frame,t,cc);metric('overallTPR',full['overall']['TPR']);metric('TPRGap',full['gaps']['TPR']['value']);metric('precisionGap',full['gaps']['precision']['value']);metric('unknownMass',full['unknownGroup']['mass'],'mass');metric('partitionResidual',full['partitionMassResidual'],'mass')\n   for i,g in enumerate(full['groups']):pt(i,i,g['metrics']['TPR'],str(g['group']))\n   xlabel='Declared group position';ylabel='True positive rate';legend=['Known-group TPR']\n  else:raise ValueError('unknown fixed API')\n def csvout(name,rows):\n  with(args.out/name).open('w',encoding='utf8',newline='')as f:w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows)\n csvout('summary.csv',summary);csvout('plot-points.csv',points);fixed_svg(args.out/'plot.svg',points,FIXED['title'],xlabel,ylabel,legend)\n (args.out/'full.json').write_text(json.dumps(dict(api=api,variant=FIXED['variant'],input=FIXED['args'],arithmetic='Python standard-library Fraction, declared fixed example; full web validator/budgets not reproduced',result=serial(full)),ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\n print(json.dumps(dict(api=api,variant=FIXED['variant'],summaryMetrics=len(summary),plotSlots=len(points))))\n\nFIXED={'api': 'realdata', 'variant': 'person', 'args': {'kind': 'person'}, 'title': 'Actual person fixed train/validation/test procedure'}\nif __name__=='__main__':fixed_run()\n",
        "input": {
          "kind": "person"
        },
        "inputFiles": [
          {
            "file": "../ml14-sources/actual64-country-four-indicators-original-2024.csv",
            "sha256": "3d2b655cf807bf3ff049af187a9b7484b4e637f441f6f1925aba7acc5b0c861c"
          },
          {
            "file": "../ml14-sources/actual3613-NLS-original52-fields-groups-roles.csv",
            "sha256": "df404c3ce0336ab3ae2bfdd6b246c6e8acc058fd526ebf950dde270787bcd600"
          },
          {
            "file": "../ml14-sources/actual3150-churn-original14-fields-groups-roles.csv",
            "sha256": "d8af1f4905af8699e3ea024a6998319c82ac97b33ba1dec182391c0b30795023"
          }
        ],
        "returnCode": 0,
        "expectedFailure": false,
        "stdout": "{\"api\": \"realdata\", \"variant\": \"person\", \"summaryMetrics\": 10, \"plotSlots\": 1214}\n",
        "stderr": "",
        "summary": {
          "equalThreshold": "0.616564417",
          "equalTestCost": "0.380560132",
          "miss-fiveThreshold": "0.362068966",
          "miss-fiveTestCost": "0.441515651",
          "alarm-fiveThreshold": "0.757575758",
          "alarm-fiveTestCost": "0.477759473",
          "testAUC": "0.674085326",
          "testAP": "0.720385902",
          "testBrier": "0.222886072",
          "eligibleRows": "3017"
        },
        "summaryRows": [
          {
            "metric": "equalThreshold",
            "value": "0.616564417",
            "exactValue": "201/326",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "equalTestCost",
            "value": "0.380560132",
            "exactValue": "231/607",
            "unit": "hypothetical cost units/mass",
            "defined": "1"
          },
          {
            "metric": "miss-fiveThreshold",
            "value": "0.362068966",
            "exactValue": "21/58",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "miss-fiveTestCost",
            "value": "0.441515651",
            "exactValue": "268/607",
            "unit": "hypothetical cost units/mass",
            "defined": "1"
          },
          {
            "metric": "alarm-fiveThreshold",
            "value": "0.757575758",
            "exactValue": "25/33",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "alarm-fiveTestCost",
            "value": "0.477759473",
            "exactValue": "290/607",
            "unit": "hypothetical cost units/mass",
            "defined": "1"
          },
          {
            "metric": "testAUC",
            "value": "0.674085326",
            "exactValue": "10207/15142",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "testAP",
            "value": "0.720385902",
            "exactValue": "3179505850205605883/4413614759611331274",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "testBrier",
            "value": "0.222886072",
            "exactValue": "161250531585586987321305719/723466163565783399733166250",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "eligibleRows",
            "value": "3017",
            "exactValue": "3017",
            "unit": "rows",
            "defined": "1"
          }
        ],
        "plotPoints": [
          {
            "series": "0",
            "index": "0",
            "xExact": "1",
            "x": "1",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:4"
          },
          {
            "series": "1",
            "index": "0",
            "xExact": "1",
            "x": "1",
            "yExact": "0",
            "y": "0",
            "id": "person:4"
          },
          {
            "series": "0",
            "index": "1",
            "xExact": "2",
            "x": "2",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:6"
          },
          {
            "series": "1",
            "index": "1",
            "xExact": "2",
            "x": "2",
            "yExact": "1",
            "y": "1",
            "id": "person:6"
          },
          {
            "series": "0",
            "index": "2",
            "xExact": "3",
            "x": "3",
            "yExact": "179/268",
            "y": "0.667910448",
            "id": "person:18"
          },
          {
            "series": "1",
            "index": "2",
            "xExact": "3",
            "x": "3",
            "yExact": "0",
            "y": "0",
            "id": "person:18"
          },
          {
            "series": "0",
            "index": "3",
            "xExact": "4",
            "x": "4",
            "yExact": "197/239",
            "y": "0.824267782",
            "id": "person:19"
          },
          {
            "series": "1",
            "index": "3",
            "xExact": "4",
            "x": "4",
            "yExact": "1",
            "y": "1",
            "id": "person:19"
          },
          {
            "series": "0",
            "index": "4",
            "xExact": "5",
            "x": "5",
            "yExact": "197/239",
            "y": "0.824267782",
            "id": "person:25"
          },
          {
            "series": "1",
            "index": "4",
            "xExact": "5",
            "x": "5",
            "yExact": "1",
            "y": "1",
            "id": "person:25"
          },
          {
            "series": "0",
            "index": "5",
            "xExact": "6",
            "x": "6",
            "yExact": "179/268",
            "y": "0.667910448",
            "id": "person:27"
          },
          {
            "series": "1",
            "index": "5",
            "xExact": "6",
            "x": "6",
            "yExact": "1",
            "y": "1",
            "id": "person:27"
          },
          {
            "series": "0",
            "index": "6",
            "xExact": "7",
            "x": "7",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:35"
          },
          {
            "series": "1",
            "index": "6",
            "xExact": "7",
            "x": "7",
            "yExact": "0",
            "y": "0",
            "id": "person:35"
          },
          {
            "series": "0",
            "index": "7",
            "xExact": "8",
            "x": "8",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:45"
          },
          {
            "series": "1",
            "index": "7",
            "xExact": "8",
            "x": "8",
            "yExact": "0",
            "y": "0",
            "id": "person:45"
          },
          {
            "series": "0",
            "index": "8",
            "xExact": "9",
            "x": "9",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:46"
          },
          {
            "series": "1",
            "index": "8",
            "xExact": "9",
            "x": "9",
            "yExact": "0",
            "y": "0",
            "id": "person:46"
          },
          {
            "series": "0",
            "index": "9",
            "xExact": "10",
            "x": "10",
            "yExact": "179/268",
            "y": "0.667910448",
            "id": "person:47"
          },
          {
            "series": "1",
            "index": "9",
            "xExact": "10",
            "x": "10",
            "yExact": "1",
            "y": "1",
            "id": "person:47"
          },
          {
            "series": "0",
            "index": "10",
            "xExact": "11",
            "x": "11",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:52"
          },
          {
            "series": "1",
            "index": "10",
            "xExact": "11",
            "x": "11",
            "yExact": "0",
            "y": "0",
            "id": "person:52"
          },
          {
            "series": "0",
            "index": "11",
            "xExact": "12",
            "x": "12",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:61"
          },
          {
            "series": "1",
            "index": "11",
            "xExact": "12",
            "x": "12",
            "yExact": "0",
            "y": "0",
            "id": "person:61"
          },
          {
            "series": "0",
            "index": "12",
            "xExact": "13",
            "x": "13",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:62"
          },
          {
            "series": "1",
            "index": "12",
            "xExact": "13",
            "x": "13",
            "yExact": "1",
            "y": "1",
            "id": "person:62"
          },
          {
            "series": "0",
            "index": "13",
            "xExact": "14",
            "x": "14",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:63"
          },
          {
            "series": "1",
            "index": "13",
            "xExact": "14",
            "x": "14",
            "yExact": "0",
            "y": "0",
            "id": "person:63"
          },
          {
            "series": "0",
            "index": "14",
            "xExact": "15",
            "x": "15",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:64"
          },
          {
            "series": "1",
            "index": "14",
            "xExact": "15",
            "x": "15",
            "yExact": "1",
            "y": "1",
            "id": "person:64"
          },
          {
            "series": "0",
            "index": "15",
            "xExact": "16",
            "x": "16",
            "yExact": "197/239",
            "y": "0.824267782",
            "id": "person:65"
          },
          {
            "series": "1",
            "index": "15",
            "xExact": "16",
            "x": "16",
            "yExact": "1",
            "y": "1",
            "id": "person:65"
          },
          {
            "series": "0",
            "index": "16",
            "xExact": "17",
            "x": "17",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:90"
          },
          {
            "series": "1",
            "index": "16",
            "xExact": "17",
            "x": "17",
            "yExact": "0",
            "y": "0",
            "id": "person:90"
          },
          {
            "series": "0",
            "index": "17",
            "xExact": "18",
            "x": "18",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:92"
          },
          {
            "series": "1",
            "index": "17",
            "xExact": "18",
            "x": "18",
            "yExact": "0",
            "y": "0",
            "id": "person:92"
          },
          {
            "series": "0",
            "index": "18",
            "xExact": "19",
            "x": "19",
            "yExact": "179/268",
            "y": "0.667910448",
            "id": "person:95"
          },
          {
            "series": "1",
            "index": "18",
            "xExact": "19",
            "x": "19",
            "yExact": "1",
            "y": "1",
            "id": "person:95"
          },
          {
            "series": "0",
            "index": "19",
            "xExact": "20",
            "x": "20",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:96"
          },
          {
            "series": "1",
            "index": "19",
            "xExact": "20",
            "x": "20",
            "yExact": "1",
            "y": "1",
            "id": "person:96"
          },
          {
            "series": "0",
            "index": "20",
            "xExact": "21",
            "x": "21",
            "yExact": "197/239",
            "y": "0.824267782",
            "id": "person:97"
          },
          {
            "series": "1",
            "index": "20",
            "xExact": "21",
            "x": "21",
            "yExact": "1",
            "y": "1",
            "id": "person:97"
          },
          {
            "series": "0",
            "index": "21",
            "xExact": "22",
            "x": "22",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:106"
          },
          {
            "series": "1",
            "index": "21",
            "xExact": "22",
            "x": "22",
            "yExact": "0",
            "y": "0",
            "id": "person:106"
          },
          {
            "series": "0",
            "index": "22",
            "xExact": "23",
            "x": "23",
            "yExact": "179/268",
            "y": "0.667910448",
            "id": "person:108"
          },
          {
            "series": "1",
            "index": "22",
            "xExact": "23",
            "x": "23",
            "yExact": "1",
            "y": "1",
            "id": "person:108"
          },
          {
            "series": "0",
            "index": "23",
            "xExact": "24",
            "x": "24",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:113"
          },
          {
            "series": "1",
            "index": "23",
            "xExact": "24",
            "x": "24",
            "yExact": "1",
            "y": "1",
            "id": "person:113"
          },
          {
            "series": "0",
            "index": "24",
            "xExact": "25",
            "x": "25",
            "yExact": "197/239",
            "y": "0.824267782",
            "id": "person:120"
          },
          {
            "series": "1",
            "index": "24",
            "xExact": "25",
            "x": "25",
            "yExact": "1",
            "y": "1",
            "id": "person:120"
          },
          {
            "series": "0",
            "index": "25",
            "xExact": "26",
            "x": "26",
            "yExact": "197/239",
            "y": "0.824267782",
            "id": "person:122"
          },
          {
            "series": "1",
            "index": "25",
            "xExact": "26",
            "x": "26",
            "yExact": "1",
            "y": "1",
            "id": "person:122"
          },
          {
            "series": "0",
            "index": "26",
            "xExact": "27",
            "x": "27",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:132"
          },
          {
            "series": "1",
            "index": "26",
            "xExact": "27",
            "x": "27",
            "yExact": "0",
            "y": "0",
            "id": "person:132"
          },
          {
            "series": "0",
            "index": "27",
            "xExact": "28",
            "x": "28",
            "yExact": "197/239",
            "y": "0.824267782",
            "id": "person:140"
          },
          {
            "series": "1",
            "index": "27",
            "xExact": "28",
            "x": "28",
            "yExact": "1",
            "y": "1",
            "id": "person:140"
          },
          {
            "series": "0",
            "index": "28",
            "xExact": "29",
            "x": "29",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:146"
          },
          {
            "series": "1",
            "index": "28",
            "xExact": "29",
            "x": "29",
            "yExact": "0",
            "y": "0",
            "id": "person:146"
          },
          {
            "series": "0",
            "index": "29",
            "xExact": "30",
            "x": "30",
            "yExact": "179/268",
            "y": "0.667910448",
            "id": "person:148"
          },
          {
            "series": "1",
            "index": "29",
            "xExact": "30",
            "x": "30",
            "yExact": "1",
            "y": "1",
            "id": "person:148"
          },
          {
            "series": "0",
            "index": "30",
            "xExact": "31",
            "x": "31",
            "yExact": "197/239",
            "y": "0.824267782",
            "id": "person:150"
          },
          {
            "series": "1",
            "index": "30",
            "xExact": "31",
            "x": "31",
            "yExact": "1",
            "y": "1",
            "id": "person:150"
          },
          {
            "series": "0",
            "index": "31",
            "xExact": "32",
            "x": "32",
            "yExact": "197/239",
            "y": "0.824267782",
            "id": "person:151"
          },
          {
            "series": "1",
            "index": "31",
            "xExact": "32",
            "x": "32",
            "yExact": "1",
            "y": "1",
            "id": "person:151"
          },
          {
            "series": "0",
            "index": "32",
            "xExact": "33",
            "x": "33",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:156"
          },
          {
            "series": "1",
            "index": "32",
            "xExact": "33",
            "x": "33",
            "yExact": "1",
            "y": "1",
            "id": "person:156"
          },
          {
            "series": "0",
            "index": "33",
            "xExact": "34",
            "x": "34",
            "yExact": "197/239",
            "y": "0.824267782",
            "id": "person:160"
          },
          {
            "series": "1",
            "index": "33",
            "xExact": "34",
            "x": "34",
            "yExact": "1",
            "y": "1",
            "id": "person:160"
          },
          {
            "series": "0",
            "index": "34",
            "xExact": "35",
            "x": "35",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:164"
          },
          {
            "series": "1",
            "index": "34",
            "xExact": "35",
            "x": "35",
            "yExact": "1",
            "y": "1",
            "id": "person:164"
          },
          {
            "series": "0",
            "index": "35",
            "xExact": "36",
            "x": "36",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:170"
          },
          {
            "series": "1",
            "index": "35",
            "xExact": "36",
            "x": "36",
            "yExact": "1",
            "y": "1",
            "id": "person:170"
          },
          {
            "series": "0",
            "index": "36",
            "xExact": "37",
            "x": "37",
            "yExact": "179/268",
            "y": "0.667910448",
            "id": "person:171"
          },
          {
            "series": "1",
            "index": "36",
            "xExact": "37",
            "x": "37",
            "yExact": "1",
            "y": "1",
            "id": "person:171"
          },
          {
            "series": "0",
            "index": "37",
            "xExact": "38",
            "x": "38",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:176"
          },
          {
            "series": "1",
            "index": "37",
            "xExact": "38",
            "x": "38",
            "yExact": "0",
            "y": "0",
            "id": "person:176"
          },
          {
            "series": "0",
            "index": "38",
            "xExact": "39",
            "x": "39",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:183"
          },
          {
            "series": "1",
            "index": "38",
            "xExact": "39",
            "x": "39",
            "yExact": "0",
            "y": "0",
            "id": "person:183"
          },
          {
            "series": "0",
            "index": "39",
            "xExact": "40",
            "x": "40",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:185"
          },
          {
            "series": "1",
            "index": "39",
            "xExact": "40",
            "x": "40",
            "yExact": "0",
            "y": "0",
            "id": "person:185"
          },
          {
            "series": "0",
            "index": "40",
            "xExact": "41",
            "x": "41",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:188"
          },
          {
            "series": "1",
            "index": "40",
            "xExact": "41",
            "x": "41",
            "yExact": "1",
            "y": "1",
            "id": "person:188"
          },
          {
            "series": "0",
            "index": "41",
            "xExact": "42",
            "x": "42",
            "yExact": "179/268",
            "y": "0.667910448",
            "id": "person:191"
          },
          {
            "series": "1",
            "index": "41",
            "xExact": "42",
            "x": "42",
            "yExact": "1",
            "y": "1",
            "id": "person:191"
          },
          {
            "series": "0",
            "index": "42",
            "xExact": "43",
            "x": "43",
            "yExact": "179/268",
            "y": "0.667910448",
            "id": "person:204"
          },
          {
            "series": "1",
            "index": "42",
            "xExact": "43",
            "x": "43",
            "yExact": "0",
            "y": "0",
            "id": "person:204"
          },
          {
            "series": "0",
            "index": "43",
            "xExact": "44",
            "x": "44",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:206"
          },
          {
            "series": "1",
            "index": "43",
            "xExact": "44",
            "x": "44",
            "yExact": "1",
            "y": "1",
            "id": "person:206"
          },
          {
            "series": "0",
            "index": "44",
            "xExact": "45",
            "x": "45",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:212"
          },
          {
            "series": "1",
            "index": "44",
            "xExact": "45",
            "x": "45",
            "yExact": "0",
            "y": "0",
            "id": "person:212"
          },
          {
            "series": "0",
            "index": "45",
            "xExact": "46",
            "x": "46",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:227"
          },
          {
            "series": "1",
            "index": "45",
            "xExact": "46",
            "x": "46",
            "yExact": "0",
            "y": "0",
            "id": "person:227"
          },
          {
            "series": "0",
            "index": "46",
            "xExact": "47",
            "x": "47",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:230"
          },
          {
            "series": "1",
            "index": "46",
            "xExact": "47",
            "x": "47",
            "yExact": "1",
            "y": "1",
            "id": "person:230"
          },
          {
            "series": "0",
            "index": "47",
            "xExact": "48",
            "x": "48",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:254"
          },
          {
            "series": "1",
            "index": "47",
            "xExact": "48",
            "x": "48",
            "yExact": "1",
            "y": "1",
            "id": "person:254"
          },
          {
            "series": "0",
            "index": "48",
            "xExact": "49",
            "x": "49",
            "yExact": "179/268",
            "y": "0.667910448",
            "id": "person:256"
          },
          {
            "series": "1",
            "index": "48",
            "xExact": "49",
            "x": "49",
            "yExact": "1",
            "y": "1",
            "id": "person:256"
          },
          {
            "series": "0",
            "index": "49",
            "xExact": "50",
            "x": "50",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:265"
          },
          {
            "series": "1",
            "index": "49",
            "xExact": "50",
            "x": "50",
            "yExact": "1",
            "y": "1",
            "id": "person:265"
          },
          {
            "series": "0",
            "index": "50",
            "xExact": "51",
            "x": "51",
            "yExact": "197/239",
            "y": "0.824267782",
            "id": "person:270"
          },
          {
            "series": "1",
            "index": "50",
            "xExact": "51",
            "x": "51",
            "yExact": "1",
            "y": "1",
            "id": "person:270"
          },
          {
            "series": "0",
            "index": "51",
            "xExact": "52",
            "x": "52",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:272"
          },
          {
            "series": "1",
            "index": "51",
            "xExact": "52",
            "x": "52",
            "yExact": "0",
            "y": "0",
            "id": "person:272"
          },
          {
            "series": "0",
            "index": "52",
            "xExact": "53",
            "x": "53",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:275"
          },
          {
            "series": "1",
            "index": "52",
            "xExact": "53",
            "x": "53",
            "yExact": "0",
            "y": "0",
            "id": "person:275"
          },
          {
            "series": "0",
            "index": "53",
            "xExact": "54",
            "x": "54",
            "yExact": "179/268",
            "y": "0.667910448",
            "id": "person:278"
          },
          {
            "series": "1",
            "index": "53",
            "xExact": "54",
            "x": "54",
            "yExact": "1",
            "y": "1",
            "id": "person:278"
          },
          {
            "series": "0",
            "index": "54",
            "xExact": "55",
            "x": "55",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:279"
          },
          {
            "series": "1",
            "index": "54",
            "xExact": "55",
            "x": "55",
            "yExact": "0",
            "y": "0",
            "id": "person:279"
          },
          {
            "series": "0",
            "index": "55",
            "xExact": "56",
            "x": "56",
            "yExact": "197/239",
            "y": "0.824267782",
            "id": "person:297"
          },
          {
            "series": "1",
            "index": "55",
            "xExact": "56",
            "x": "56",
            "yExact": "1",
            "y": "1",
            "id": "person:297"
          },
          {
            "series": "0",
            "index": "56",
            "xExact": "57",
            "x": "57",
            "yExact": "179/268",
            "y": "0.667910448",
            "id": "person:298"
          },
          {
            "series": "1",
            "index": "56",
            "xExact": "57",
            "x": "57",
            "yExact": "1",
            "y": "1",
            "id": "person:298"
          },
          {
            "series": "0",
            "index": "57",
            "xExact": "58",
            "x": "58",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:300"
          },
          {
            "series": "1",
            "index": "57",
            "xExact": "58",
            "x": "58",
            "yExact": "1",
            "y": "1",
            "id": "person:300"
          },
          {
            "series": "0",
            "index": "58",
            "xExact": "59",
            "x": "59",
            "yExact": "179/268",
            "y": "0.667910448",
            "id": "person:318"
          },
          {
            "series": "1",
            "index": "58",
            "xExact": "59",
            "x": "59",
            "yExact": "1",
            "y": "1",
            "id": "person:318"
          },
          {
            "series": "0",
            "index": "59",
            "xExact": "60",
            "x": "60",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:324"
          },
          {
            "series": "1",
            "index": "59",
            "xExact": "60",
            "x": "60",
            "yExact": "1",
            "y": "1",
            "id": "person:324"
          },
          {
            "series": "0",
            "index": "60",
            "xExact": "61",
            "x": "61",
            "yExact": "179/268",
            "y": "0.667910448",
            "id": "person:325"
          },
          {
            "series": "1",
            "index": "60",
            "xExact": "61",
            "x": "61",
            "yExact": "1",
            "y": "1",
            "id": "person:325"
          },
          {
            "series": "0",
            "index": "61",
            "xExact": "62",
            "x": "62",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:328"
          },
          {
            "series": "1",
            "index": "61",
            "xExact": "62",
            "x": "62",
            "yExact": "0",
            "y": "0",
            "id": "person:328"
          },
          {
            "series": "0",
            "index": "62",
            "xExact": "63",
            "x": "63",
            "yExact": "21/58",
            "y": "0.362068966",
            "id": "person:341"
          },
          {
            "series": "1",
            "index": "62",
            "xExact": "63",
            "x": "63",
            "yExact": "1",
            "y": "1",
            "id": "person:341"
          },
          {
            "series": "0",
            "index": "63",
            "xExact": "64",
            "x": "64",
            "yExact": "20/41",
            "y": "0.487804878",
            "id": "person:346"
          },
          {
            "series": "1",
            "index": "63",
            "xExact": "64",
            "x": "64",
            "yExact": "1",
            "y": "1",
            "id": "person:346"
          },
          {
            "series": "0",
            "index": "64",
            "xExact": "65",
            "x": "65",
            "yExact": "20/41",
            "y": "0.487804878",
            "id": "person:352"
          },
          {
            "series": "1",
            "index": "64",
            "xExact": "65",
            "x": "65",
            "yExact": "0",
            "y": "0",
            "id": "person:352"
          },
          {
            "series": "0",
            "index": "65",
            "xExact": "66",
            "x": "66",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:354"
          },
          {
            "series": "1",
            "index": "65",
            "xExact": "66",
            "x": "66",
            "yExact": "0",
            "y": "0",
            "id": "person:354"
          },
          {
            "series": "0",
            "index": "66",
            "xExact": "67",
            "x": "67",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:355"
          },
          {
            "series": "1",
            "index": "66",
            "xExact": "67",
            "x": "67",
            "yExact": "0",
            "y": "0",
            "id": "person:355"
          },
          {
            "series": "0",
            "index": "67",
            "xExact": "68",
            "x": "68",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:366"
          },
          {
            "series": "1",
            "index": "67",
            "xExact": "68",
            "x": "68",
            "yExact": "1",
            "y": "1",
            "id": "person:366"
          },
          {
            "series": "0",
            "index": "68",
            "xExact": "69",
            "x": "69",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:368"
          },
          {
            "series": "1",
            "index": "68",
            "xExact": "69",
            "x": "69",
            "yExact": "0",
            "y": "0",
            "id": "person:368"
          },
          {
            "series": "0",
            "index": "69",
            "xExact": "70",
            "x": "70",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:369"
          },
          {
            "series": "1",
            "index": "69",
            "xExact": "70",
            "x": "70",
            "yExact": "1",
            "y": "1",
            "id": "person:369"
          },
          {
            "series": "0",
            "index": "70",
            "xExact": "71",
            "x": "71",
            "yExact": "197/239",
            "y": "0.824267782",
            "id": "person:407"
          },
          {
            "series": "1",
            "index": "70",
            "xExact": "71",
            "x": "71",
            "yExact": "1",
            "y": "1",
            "id": "person:407"
          },
          {
            "series": "0",
            "index": "71",
            "xExact": "72",
            "x": "72",
            "yExact": "179/268",
            "y": "0.667910448",
            "id": "person:414"
          },
          {
            "series": "1",
            "index": "71",
            "xExact": "72",
            "x": "72",
            "yExact": "1",
            "y": "1",
            "id": "person:414"
          },
          {
            "series": "0",
            "index": "72",
            "xExact": "73",
            "x": "73",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:423"
          },
          {
            "series": "1",
            "index": "72",
            "xExact": "73",
            "x": "73",
            "yExact": "0",
            "y": "0",
            "id": "person:423"
          },
          {
            "series": "0",
            "index": "73",
            "xExact": "74",
            "x": "74",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:426"
          },
          {
            "series": "1",
            "index": "73",
            "xExact": "74",
            "x": "74",
            "yExact": "0",
            "y": "0",
            "id": "person:426"
          },
          {
            "series": "0",
            "index": "74",
            "xExact": "75",
            "x": "75",
            "yExact": "179/268",
            "y": "0.667910448",
            "id": "person:439"
          },
          {
            "series": "1",
            "index": "74",
            "xExact": "75",
            "x": "75",
            "yExact": "0",
            "y": "0",
            "id": "person:439"
          },
          {
            "series": "0",
            "index": "75",
            "xExact": "76",
            "x": "76",
            "yExact": "197/239",
            "y": "0.824267782",
            "id": "person:440"
          },
          {
            "series": "1",
            "index": "75",
            "xExact": "76",
            "x": "76",
            "yExact": "1",
            "y": "1",
            "id": "person:440"
          },
          {
            "series": "0",
            "index": "76",
            "xExact": "77",
            "x": "77",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:457"
          },
          {
            "series": "1",
            "index": "76",
            "xExact": "77",
            "x": "77",
            "yExact": "1",
            "y": "1",
            "id": "person:457"
          },
          {
            "series": "0",
            "index": "77",
            "xExact": "78",
            "x": "78",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:464"
          },
          {
            "series": "1",
            "index": "77",
            "xExact": "78",
            "x": "78",
            "yExact": "1",
            "y": "1",
            "id": "person:464"
          },
          {
            "series": "0",
            "index": "78",
            "xExact": "79",
            "x": "79",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:480"
          },
          {
            "series": "1",
            "index": "78",
            "xExact": "79",
            "x": "79",
            "yExact": "1",
            "y": "1",
            "id": "person:480"
          },
          {
            "series": "0",
            "index": "79",
            "xExact": "80",
            "x": "80",
            "yExact": "197/239",
            "y": "0.824267782",
            "id": "person:489"
          },
          {
            "series": "1",
            "index": "79",
            "xExact": "80",
            "x": "80",
            "yExact": "1",
            "y": "1",
            "id": "person:489"
          },
          {
            "series": "0",
            "index": "80",
            "xExact": "81",
            "x": "81",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:494"
          },
          {
            "series": "1",
            "index": "80",
            "xExact": "81",
            "x": "81",
            "yExact": "1",
            "y": "1",
            "id": "person:494"
          },
          {
            "series": "0",
            "index": "81",
            "xExact": "82",
            "x": "82",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:497"
          },
          {
            "series": "1",
            "index": "81",
            "xExact": "82",
            "x": "82",
            "yExact": "0",
            "y": "0",
            "id": "person:497"
          },
          {
            "series": "0",
            "index": "82",
            "xExact": "83",
            "x": "83",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:502"
          },
          {
            "series": "1",
            "index": "82",
            "xExact": "83",
            "x": "83",
            "yExact": "1",
            "y": "1",
            "id": "person:502"
          },
          {
            "series": "0",
            "index": "83",
            "xExact": "84",
            "x": "84",
            "yExact": "197/239",
            "y": "0.824267782",
            "id": "person:504"
          },
          {
            "series": "1",
            "index": "83",
            "xExact": "84",
            "x": "84",
            "yExact": "1",
            "y": "1",
            "id": "person:504"
          },
          {
            "series": "0",
            "index": "84",
            "xExact": "85",
            "x": "85",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:506"
          },
          {
            "series": "1",
            "index": "84",
            "xExact": "85",
            "x": "85",
            "yExact": "0",
            "y": "0",
            "id": "person:506"
          },
          {
            "series": "0",
            "index": "85",
            "xExact": "86",
            "x": "86",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:508"
          },
          {
            "series": "1",
            "index": "85",
            "xExact": "86",
            "x": "86",
            "yExact": "1",
            "y": "1",
            "id": "person:508"
          },
          {
            "series": "0",
            "index": "86",
            "xExact": "87",
            "x": "87",
            "yExact": "197/239",
            "y": "0.824267782",
            "id": "person:510"
          },
          {
            "series": "1",
            "index": "86",
            "xExact": "87",
            "x": "87",
            "yExact": "1",
            "y": "1",
            "id": "person:510"
          },
          {
            "series": "0",
            "index": "87",
            "xExact": "88",
            "x": "88",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:513"
          },
          {
            "series": "1",
            "index": "87",
            "xExact": "88",
            "x": "88",
            "yExact": "0",
            "y": "0",
            "id": "person:513"
          },
          {
            "series": "0",
            "index": "88",
            "xExact": "89",
            "x": "89",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:526"
          },
          {
            "series": "1",
            "index": "88",
            "xExact": "89",
            "x": "89",
            "yExact": "0",
            "y": "0",
            "id": "person:526"
          },
          {
            "series": "0",
            "index": "89",
            "xExact": "90",
            "x": "90",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:528"
          },
          {
            "series": "1",
            "index": "89",
            "xExact": "90",
            "x": "90",
            "yExact": "1",
            "y": "1",
            "id": "person:528"
          },
          {
            "series": "0",
            "index": "90",
            "xExact": "91",
            "x": "91",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:537"
          },
          {
            "series": "1",
            "index": "90",
            "xExact": "91",
            "x": "91",
            "yExact": "0",
            "y": "0",
            "id": "person:537"
          },
          {
            "series": "0",
            "index": "91",
            "xExact": "92",
            "x": "92",
            "yExact": "197/239",
            "y": "0.824267782",
            "id": "person:543"
          },
          {
            "series": "1",
            "index": "91",
            "xExact": "92",
            "x": "92",
            "yExact": "1",
            "y": "1",
            "id": "person:543"
          },
          {
            "series": "0",
            "index": "92",
            "xExact": "93",
            "x": "93",
            "yExact": "197/239",
            "y": "0.824267782",
            "id": "person:554"
          },
          {
            "series": "1",
            "index": "92",
            "xExact": "93",
            "x": "93",
            "yExact": "1",
            "y": "1",
            "id": "person:554"
          },
          {
            "series": "0",
            "index": "93",
            "xExact": "94",
            "x": "94",
            "yExact": "179/268",
            "y": "0.667910448",
            "id": "person:574"
          },
          {
            "series": "1",
            "index": "93",
            "xExact": "94",
            "x": "94",
            "yExact": "1",
            "y": "1",
            "id": "person:574"
          },
          {
            "series": "0",
            "index": "94",
            "xExact": "95",
            "x": "95",
            "yExact": "21/58",
            "y": "0.362068966",
            "id": "person:583"
          },
          {
            "series": "1",
            "index": "94",
            "xExact": "95",
            "x": "95",
            "yExact": "1",
            "y": "1",
            "id": "person:583"
          },
          {
            "series": "0",
            "index": "95",
            "xExact": "96",
            "x": "96",
            "yExact": "25/33",
            "y": "0.757575758",
            "id": "person:594"
          },
          {
            "series": "1",
            "index": "95",
            "xExact": "96",
            "x": "96",
            "yExact": "1",
            "y": "1",
            "id": "person:594"
          },
          {
            "series": "0",
            "index": "96",
            "xExact": "97",
            "x": "97",
            "yExact": "21/58",
            "y": "0.362068966",
            "id": "person:601"
          },
          {
            "series": "1",
            "index": "96",
            "xExact": "97",
            "x": "97",
            "yExact": "0",
            "y": "0",
            "id": "person:601"
          },
          {
            "series": "0",
            "index": "97",
            "xExact": "98",
            "x": "98",
            "yExact": "21/58",
            "y": "0.362068966",
            "id": "person:613"
          },
          {
            "series": "1",
            "index": "97",
            "xExact": "98",
            "x": "98",
            "yExact": "1",
            "y": "1",
            "id": "person:613"
          },
          {
            "series": "0",
            "index": "98",
            "xExact": "99",
            "x": "99",
            "yExact": "25/33",
            "y": "0.757575758",
            "id": "person:614"
          },
          {
            "series": "1",
            "index": "98",
            "xExact": "99",
            "x": "99",
            "yExact": "1",
            "y": "1",
            "id": "person:614"
          },
          {
            "series": "0",
            "index": "99",
            "xExact": "100",
            "x": "100",
            "yExact": "179/268",
            "y": "0.667910448",
            "id": "person:625"
          },
          {
            "series": "1",
            "index": "99",
            "xExact": "100",
            "x": "100",
            "yExact": "1",
            "y": "1",
            "id": "person:625"
          },
          {
            "series": "0",
            "index": "100",
            "xExact": "101",
            "x": "101",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:630"
          },
          {
            "series": "1",
            "index": "100",
            "xExact": "101",
            "x": "101",
            "yExact": "0",
            "y": "0",
            "id": "person:630"
          },
          {
            "series": "0",
            "index": "101",
            "xExact": "102",
            "x": "102",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:638"
          },
          {
            "series": "1",
            "index": "101",
            "xExact": "102",
            "x": "102",
            "yExact": "1",
            "y": "1",
            "id": "person:638"
          },
          {
            "series": "0",
            "index": "102",
            "xExact": "103",
            "x": "103",
            "yExact": "179/268",
            "y": "0.667910448",
            "id": "person:648"
          },
          {
            "series": "1",
            "index": "102",
            "xExact": "103",
            "x": "103",
            "yExact": "0",
            "y": "0",
            "id": "person:648"
          },
          {
            "series": "0",
            "index": "103",
            "xExact": "104",
            "x": "104",
            "yExact": "197/239",
            "y": "0.824267782",
            "id": "person:656"
          },
          {
            "series": "1",
            "index": "103",
            "xExact": "104",
            "x": "104",
            "yExact": "1",
            "y": "1",
            "id": "person:656"
          },
          {
            "series": "0",
            "index": "104",
            "xExact": "105",
            "x": "105",
            "yExact": "197/239",
            "y": "0.824267782",
            "id": "person:659"
          },
          {
            "series": "1",
            "index": "104",
            "xExact": "105",
            "x": "105",
            "yExact": "1",
            "y": "1",
            "id": "person:659"
          },
          {
            "series": "0",
            "index": "105",
            "xExact": "106",
            "x": "106",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:678"
          },
          {
            "series": "1",
            "index": "105",
            "xExact": "106",
            "x": "106",
            "yExact": "0",
            "y": "0",
            "id": "person:678"
          },
          {
            "series": "0",
            "index": "106",
            "xExact": "107",
            "x": "107",
            "yExact": "21/58",
            "y": "0.362068966",
            "id": "person:686"
          },
          {
            "series": "1",
            "index": "106",
            "xExact": "107",
            "x": "107",
            "yExact": "0",
            "y": "0",
            "id": "person:686"
          },
          {
            "series": "0",
            "index": "107",
            "xExact": "108",
            "x": "108",
            "yExact": "20/41",
            "y": "0.487804878",
            "id": "person:689"
          },
          {
            "series": "1",
            "index": "107",
            "xExact": "108",
            "x": "108",
            "yExact": "1",
            "y": "1",
            "id": "person:689"
          },
          {
            "series": "0",
            "index": "108",
            "xExact": "109",
            "x": "109",
            "yExact": "12/25",
            "y": "0.48",
            "id": "person:696"
          },
          {
            "series": "1",
            "index": "108",
            "xExact": "109",
            "x": "109",
            "yExact": "0",
            "y": "0",
            "id": "person:696"
          },
          {
            "series": "0",
            "index": "109",
            "xExact": "110",
            "x": "110",
            "yExact": "21/58",
            "y": "0.362068966",
            "id": "person:700"
          },
          {
            "series": "1",
            "index": "109",
            "xExact": "110",
            "x": "110",
            "yExact": "0",
            "y": "0",
            "id": "person:700"
          },
          {
            "series": "0",
            "index": "110",
            "xExact": "111",
            "x": "111",
            "yExact": "12/25",
            "y": "0.48",
            "id": "person:706"
          },
          {
            "series": "1",
            "index": "110",
            "xExact": "111",
            "x": "111",
            "yExact": "0",
            "y": "0",
            "id": "person:706"
          },
          {
            "series": "0",
            "index": "111",
            "xExact": "112",
            "x": "112",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:707"
          },
          {
            "series": "1",
            "index": "111",
            "xExact": "112",
            "x": "112",
            "yExact": "0",
            "y": "0",
            "id": "person:707"
          },
          {
            "series": "0",
            "index": "112",
            "xExact": "113",
            "x": "113",
            "yExact": "179/268",
            "y": "0.667910448",
            "id": "person:724"
          },
          {
            "series": "1",
            "index": "112",
            "xExact": "113",
            "x": "113",
            "yExact": "0",
            "y": "0",
            "id": "person:724"
          },
          {
            "series": "0",
            "index": "113",
            "xExact": "114",
            "x": "114",
            "yExact": "179/268",
            "y": "0.667910448",
            "id": "person:727"
          },
          {
            "series": "1",
            "index": "113",
            "xExact": "114",
            "x": "114",
            "yExact": "1",
            "y": "1",
            "id": "person:727"
          },
          {
            "series": "0",
            "index": "114",
            "xExact": "115",
            "x": "115",
            "yExact": "179/268",
            "y": "0.667910448",
            "id": "person:730"
          },
          {
            "series": "1",
            "index": "114",
            "xExact": "115",
            "x": "115",
            "yExact": "0",
            "y": "0",
            "id": "person:730"
          },
          {
            "series": "0",
            "index": "115",
            "xExact": "116",
            "x": "116",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:733"
          },
          {
            "series": "1",
            "index": "115",
            "xExact": "116",
            "x": "116",
            "yExact": "0",
            "y": "0",
            "id": "person:733"
          },
          {
            "series": "0",
            "index": "116",
            "xExact": "117",
            "x": "117",
            "yExact": "197/239",
            "y": "0.824267782",
            "id": "person:737"
          },
          {
            "series": "1",
            "index": "116",
            "xExact": "117",
            "x": "117",
            "yExact": "1",
            "y": "1",
            "id": "person:737"
          },
          {
            "series": "0",
            "index": "117",
            "xExact": "118",
            "x": "118",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:739"
          },
          {
            "series": "1",
            "index": "117",
            "xExact": "118",
            "x": "118",
            "yExact": "0",
            "y": "0",
            "id": "person:739"
          },
          {
            "series": "0",
            "index": "118",
            "xExact": "119",
            "x": "119",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:745"
          },
          {
            "series": "1",
            "index": "118",
            "xExact": "119",
            "x": "119",
            "yExact": "0",
            "y": "0",
            "id": "person:745"
          },
          {
            "series": "0",
            "index": "119",
            "xExact": "120",
            "x": "120",
            "yExact": "179/268",
            "y": "0.667910448",
            "id": "person:755"
          },
          {
            "series": "1",
            "index": "119",
            "xExact": "120",
            "x": "120",
            "yExact": "1",
            "y": "1",
            "id": "person:755"
          },
          {
            "series": "0",
            "index": "120",
            "xExact": "121",
            "x": "121",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:765"
          },
          {
            "series": "1",
            "index": "120",
            "xExact": "121",
            "x": "121",
            "yExact": "1",
            "y": "1",
            "id": "person:765"
          },
          {
            "series": "0",
            "index": "121",
            "xExact": "122",
            "x": "122",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:771"
          },
          {
            "series": "1",
            "index": "121",
            "xExact": "122",
            "x": "122",
            "yExact": "1",
            "y": "1",
            "id": "person:771"
          },
          {
            "series": "0",
            "index": "122",
            "xExact": "123",
            "x": "123",
            "yExact": "179/268",
            "y": "0.667910448",
            "id": "person:779"
          },
          {
            "series": "1",
            "index": "122",
            "xExact": "123",
            "x": "123",
            "yExact": "1",
            "y": "1",
            "id": "person:779"
          },
          {
            "series": "0",
            "index": "123",
            "xExact": "124",
            "x": "124",
            "yExact": "197/239",
            "y": "0.824267782",
            "id": "person:781"
          },
          {
            "series": "1",
            "index": "123",
            "xExact": "124",
            "x": "124",
            "yExact": "1",
            "y": "1",
            "id": "person:781"
          },
          {
            "series": "0",
            "index": "124",
            "xExact": "125",
            "x": "125",
            "yExact": "197/239",
            "y": "0.824267782",
            "id": "person:782"
          },
          {
            "series": "1",
            "index": "124",
            "xExact": "125",
            "x": "125",
            "yExact": "1",
            "y": "1",
            "id": "person:782"
          },
          {
            "series": "0",
            "index": "125",
            "xExact": "126",
            "x": "126",
            "yExact": "179/268",
            "y": "0.667910448",
            "id": "person:787"
          },
          {
            "series": "1",
            "index": "125",
            "xExact": "126",
            "x": "126",
            "yExact": "1",
            "y": "1",
            "id": "person:787"
          },
          {
            "series": "0",
            "index": "126",
            "xExact": "127",
            "x": "127",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:791"
          },
          {
            "series": "1",
            "index": "126",
            "xExact": "127",
            "x": "127",
            "yExact": "1",
            "y": "1",
            "id": "person:791"
          },
          {
            "series": "0",
            "index": "127",
            "xExact": "128",
            "x": "128",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:796"
          },
          {
            "series": "1",
            "index": "127",
            "xExact": "128",
            "x": "128",
            "yExact": "0",
            "y": "0",
            "id": "person:796"
          },
          {
            "series": "0",
            "index": "128",
            "xExact": "129",
            "x": "129",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:801"
          },
          {
            "series": "1",
            "index": "128",
            "xExact": "129",
            "x": "129",
            "yExact": "1",
            "y": "1",
            "id": "person:801"
          },
          {
            "series": "0",
            "index": "129",
            "xExact": "130",
            "x": "130",
            "yExact": "179/268",
            "y": "0.667910448",
            "id": "person:805"
          },
          {
            "series": "1",
            "index": "129",
            "xExact": "130",
            "x": "130",
            "yExact": "0",
            "y": "0",
            "id": "person:805"
          },
          {
            "series": "0",
            "index": "130",
            "xExact": "131",
            "x": "131",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:809"
          },
          {
            "series": "1",
            "index": "130",
            "xExact": "131",
            "x": "131",
            "yExact": "1",
            "y": "1",
            "id": "person:809"
          },
          {
            "series": "0",
            "index": "131",
            "xExact": "132",
            "x": "132",
            "yExact": "179/268",
            "y": "0.667910448",
            "id": "person:810"
          },
          {
            "series": "1",
            "index": "131",
            "xExact": "132",
            "x": "132",
            "yExact": "1",
            "y": "1",
            "id": "person:810"
          },
          {
            "series": "0",
            "index": "132",
            "xExact": "133",
            "x": "133",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:820"
          },
          {
            "series": "1",
            "index": "132",
            "xExact": "133",
            "x": "133",
            "yExact": "1",
            "y": "1",
            "id": "person:820"
          },
          {
            "series": "0",
            "index": "133",
            "xExact": "134",
            "x": "134",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:824"
          },
          {
            "series": "1",
            "index": "133",
            "xExact": "134",
            "x": "134",
            "yExact": "0",
            "y": "0",
            "id": "person:824"
          },
          {
            "series": "0",
            "index": "134",
            "xExact": "135",
            "x": "135",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:829"
          },
          {
            "series": "1",
            "index": "134",
            "xExact": "135",
            "x": "135",
            "yExact": "0",
            "y": "0",
            "id": "person:829"
          },
          {
            "series": "0",
            "index": "135",
            "xExact": "136",
            "x": "136",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:840"
          },
          {
            "series": "1",
            "index": "135",
            "xExact": "136",
            "x": "136",
            "yExact": "1",
            "y": "1",
            "id": "person:840"
          },
          {
            "series": "0",
            "index": "136",
            "xExact": "137",
            "x": "137",
            "yExact": "197/239",
            "y": "0.824267782",
            "id": "person:851"
          },
          {
            "series": "1",
            "index": "136",
            "xExact": "137",
            "x": "137",
            "yExact": "1",
            "y": "1",
            "id": "person:851"
          },
          {
            "series": "0",
            "index": "137",
            "xExact": "138",
            "x": "138",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:879"
          },
          {
            "series": "1",
            "index": "137",
            "xExact": "138",
            "x": "138",
            "yExact": "0",
            "y": "0",
            "id": "person:879"
          },
          {
            "series": "0",
            "index": "138",
            "xExact": "139",
            "x": "139",
            "yExact": "197/239",
            "y": "0.824267782",
            "id": "person:880"
          },
          {
            "series": "1",
            "index": "138",
            "xExact": "139",
            "x": "139",
            "yExact": "1",
            "y": "1",
            "id": "person:880"
          },
          {
            "series": "0",
            "index": "139",
            "xExact": "140",
            "x": "140",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:887"
          },
          {
            "series": "1",
            "index": "139",
            "xExact": "140",
            "x": "140",
            "yExact": "1",
            "y": "1",
            "id": "person:887"
          },
          {
            "series": "0",
            "index": "140",
            "xExact": "141",
            "x": "141",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:899"
          },
          {
            "series": "1",
            "index": "140",
            "xExact": "141",
            "x": "141",
            "yExact": "0",
            "y": "0",
            "id": "person:899"
          },
          {
            "series": "0",
            "index": "141",
            "xExact": "142",
            "x": "142",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:900"
          },
          {
            "series": "1",
            "index": "141",
            "xExact": "142",
            "x": "142",
            "yExact": "1",
            "y": "1",
            "id": "person:900"
          },
          {
            "series": "0",
            "index": "142",
            "xExact": "143",
            "x": "143",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:916"
          },
          {
            "series": "1",
            "index": "142",
            "xExact": "143",
            "x": "143",
            "yExact": "1",
            "y": "1",
            "id": "person:916"
          },
          {
            "series": "0",
            "index": "143",
            "xExact": "144",
            "x": "144",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:926"
          },
          {
            "series": "1",
            "index": "143",
            "xExact": "144",
            "x": "144",
            "yExact": "0",
            "y": "0",
            "id": "person:926"
          },
          {
            "series": "0",
            "index": "144",
            "xExact": "145",
            "x": "145",
            "yExact": "179/268",
            "y": "0.667910448",
            "id": "person:931"
          },
          {
            "series": "1",
            "index": "144",
            "xExact": "145",
            "x": "145",
            "yExact": "1",
            "y": "1",
            "id": "person:931"
          },
          {
            "series": "0",
            "index": "145",
            "xExact": "146",
            "x": "146",
            "yExact": "197/239",
            "y": "0.824267782",
            "id": "person:943"
          },
          {
            "series": "1",
            "index": "145",
            "xExact": "146",
            "x": "146",
            "yExact": "1",
            "y": "1",
            "id": "person:943"
          },
          {
            "series": "0",
            "index": "146",
            "xExact": "147",
            "x": "147",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:949"
          },
          {
            "series": "1",
            "index": "146",
            "xExact": "147",
            "x": "147",
            "yExact": "0",
            "y": "0",
            "id": "person:949"
          },
          {
            "series": "0",
            "index": "147",
            "xExact": "148",
            "x": "148",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:952"
          },
          {
            "series": "1",
            "index": "147",
            "xExact": "148",
            "x": "148",
            "yExact": "1",
            "y": "1",
            "id": "person:952"
          },
          {
            "series": "0",
            "index": "148",
            "xExact": "149",
            "x": "149",
            "yExact": "179/268",
            "y": "0.667910448",
            "id": "person:966"
          },
          {
            "series": "1",
            "index": "148",
            "xExact": "149",
            "x": "149",
            "yExact": "1",
            "y": "1",
            "id": "person:966"
          },
          {
            "series": "0",
            "index": "149",
            "xExact": "150",
            "x": "150",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:969"
          },
          {
            "series": "1",
            "index": "149",
            "xExact": "150",
            "x": "150",
            "yExact": "0",
            "y": "0",
            "id": "person:969"
          },
          {
            "series": "0",
            "index": "150",
            "xExact": "151",
            "x": "151",
            "yExact": "197/239",
            "y": "0.824267782",
            "id": "person:977"
          },
          {
            "series": "1",
            "index": "150",
            "xExact": "151",
            "x": "151",
            "yExact": "1",
            "y": "1",
            "id": "person:977"
          },
          {
            "series": "0",
            "index": "151",
            "xExact": "152",
            "x": "152",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:979"
          },
          {
            "series": "1",
            "index": "151",
            "xExact": "152",
            "x": "152",
            "yExact": "1",
            "y": "1",
            "id": "person:979"
          },
          {
            "series": "0",
            "index": "152",
            "xExact": "153",
            "x": "153",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:983"
          },
          {
            "series": "1",
            "index": "152",
            "xExact": "153",
            "x": "153",
            "yExact": "1",
            "y": "1",
            "id": "person:983"
          },
          {
            "series": "0",
            "index": "153",
            "xExact": "154",
            "x": "154",
            "yExact": "179/268",
            "y": "0.667910448",
            "id": "person:987"
          },
          {
            "series": "1",
            "index": "153",
            "xExact": "154",
            "x": "154",
            "yExact": "1",
            "y": "1",
            "id": "person:987"
          },
          {
            "series": "0",
            "index": "154",
            "xExact": "155",
            "x": "155",
            "yExact": "179/268",
            "y": "0.667910448",
            "id": "person:988"
          },
          {
            "series": "1",
            "index": "154",
            "xExact": "155",
            "x": "155",
            "yExact": "1",
            "y": "1",
            "id": "person:988"
          },
          {
            "series": "0",
            "index": "155",
            "xExact": "156",
            "x": "156",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:989"
          },
          {
            "series": "1",
            "index": "155",
            "xExact": "156",
            "x": "156",
            "yExact": "1",
            "y": "1",
            "id": "person:989"
          },
          {
            "series": "0",
            "index": "156",
            "xExact": "157",
            "x": "157",
            "yExact": "197/239",
            "y": "0.824267782",
            "id": "person:1001"
          },
          {
            "series": "1",
            "index": "156",
            "xExact": "157",
            "x": "157",
            "yExact": "1",
            "y": "1",
            "id": "person:1001"
          },
          {
            "series": "0",
            "index": "157",
            "xExact": "158",
            "x": "158",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:1005"
          },
          {
            "series": "1",
            "index": "157",
            "xExact": "158",
            "x": "158",
            "yExact": "0",
            "y": "0",
            "id": "person:1005"
          },
          {
            "series": "0",
            "index": "158",
            "xExact": "159",
            "x": "159",
            "yExact": "197/239",
            "y": "0.824267782",
            "id": "person:1008"
          },
          {
            "series": "1",
            "index": "158",
            "xExact": "159",
            "x": "159",
            "yExact": "0",
            "y": "0",
            "id": "person:1008"
          },
          {
            "series": "0",
            "index": "159",
            "xExact": "160",
            "x": "160",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:1010"
          },
          {
            "series": "1",
            "index": "159",
            "xExact": "160",
            "x": "160",
            "yExact": "1",
            "y": "1",
            "id": "person:1010"
          },
          {
            "series": "0",
            "index": "160",
            "xExact": "161",
            "x": "161",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:1011"
          },
          {
            "series": "1",
            "index": "160",
            "xExact": "161",
            "x": "161",
            "yExact": "1",
            "y": "1",
            "id": "person:1011"
          },
          {
            "series": "0",
            "index": "161",
            "xExact": "162",
            "x": "162",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:1026"
          },
          {
            "series": "1",
            "index": "161",
            "xExact": "162",
            "x": "162",
            "yExact": "1",
            "y": "1",
            "id": "person:1026"
          },
          {
            "series": "0",
            "index": "162",
            "xExact": "163",
            "x": "163",
            "yExact": "197/239",
            "y": "0.824267782",
            "id": "person:1034"
          },
          {
            "series": "1",
            "index": "162",
            "xExact": "163",
            "x": "163",
            "yExact": "1",
            "y": "1",
            "id": "person:1034"
          },
          {
            "series": "0",
            "index": "163",
            "xExact": "164",
            "x": "164",
            "yExact": "197/239",
            "y": "0.824267782",
            "id": "person:1035"
          },
          {
            "series": "1",
            "index": "163",
            "xExact": "164",
            "x": "164",
            "yExact": "1",
            "y": "1",
            "id": "person:1035"
          },
          {
            "series": "0",
            "index": "164",
            "xExact": "165",
            "x": "165",
            "yExact": "179/268",
            "y": "0.667910448",
            "id": "person:1036"
          },
          {
            "series": "1",
            "index": "164",
            "xExact": "165",
            "x": "165",
            "yExact": "0",
            "y": "0",
            "id": "person:1036"
          },
          {
            "series": "0",
            "index": "165",
            "xExact": "166",
            "x": "166",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:1041"
          },
          {
            "series": "1",
            "index": "165",
            "xExact": "166",
            "x": "166",
            "yExact": "1",
            "y": "1",
            "id": "person:1041"
          },
          {
            "series": "0",
            "index": "166",
            "xExact": "167",
            "x": "167",
            "yExact": "179/268",
            "y": "0.667910448",
            "id": "person:1046"
          },
          {
            "series": "1",
            "index": "166",
            "xExact": "167",
            "x": "167",
            "yExact": "1",
            "y": "1",
            "id": "person:1046"
          },
          {
            "series": "0",
            "index": "167",
            "xExact": "168",
            "x": "168",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:1049"
          },
          {
            "series": "1",
            "index": "167",
            "xExact": "168",
            "x": "168",
            "yExact": "0",
            "y": "0",
            "id": "person:1049"
          },
          {
            "series": "0",
            "index": "168",
            "xExact": "169",
            "x": "169",
            "yExact": "197/239",
            "y": "0.824267782",
            "id": "person:1055"
          },
          {
            "series": "1",
            "index": "168",
            "xExact": "169",
            "x": "169",
            "yExact": "1",
            "y": "1",
            "id": "person:1055"
          },
          {
            "series": "0",
            "index": "169",
            "xExact": "170",
            "x": "170",
            "yExact": "197/239",
            "y": "0.824267782",
            "id": "person:1057"
          },
          {
            "series": "1",
            "index": "169",
            "xExact": "170",
            "x": "170",
            "yExact": "1",
            "y": "1",
            "id": "person:1057"
          },
          {
            "series": "0",
            "index": "170",
            "xExact": "171",
            "x": "171",
            "yExact": "20/41",
            "y": "0.487804878",
            "id": "person:1063"
          },
          {
            "series": "1",
            "index": "170",
            "xExact": "171",
            "x": "171",
            "yExact": "1",
            "y": "1",
            "id": "person:1063"
          },
          {
            "series": "0",
            "index": "171",
            "xExact": "172",
            "x": "172",
            "yExact": "21/58",
            "y": "0.362068966",
            "id": "person:1071"
          },
          {
            "series": "1",
            "index": "171",
            "xExact": "172",
            "x": "172",
            "yExact": "1",
            "y": "1",
            "id": "person:1071"
          },
          {
            "series": "0",
            "index": "172",
            "xExact": "173",
            "x": "173",
            "yExact": "179/268",
            "y": "0.667910448",
            "id": "person:1073"
          },
          {
            "series": "1",
            "index": "172",
            "xExact": "173",
            "x": "173",
            "yExact": "1",
            "y": "1",
            "id": "person:1073"
          },
          {
            "series": "0",
            "index": "173",
            "xExact": "174",
            "x": "174",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:1083"
          },
          {
            "series": "1",
            "index": "173",
            "xExact": "174",
            "x": "174",
            "yExact": "1",
            "y": "1",
            "id": "person:1083"
          },
          {
            "series": "0",
            "index": "174",
            "xExact": "175",
            "x": "175",
            "yExact": "12/25",
            "y": "0.48",
            "id": "person:1094"
          },
          {
            "series": "1",
            "index": "174",
            "xExact": "175",
            "x": "175",
            "yExact": "1",
            "y": "1",
            "id": "person:1094"
          },
          {
            "series": "0",
            "index": "175",
            "xExact": "176",
            "x": "176",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:1099"
          },
          {
            "series": "1",
            "index": "175",
            "xExact": "176",
            "x": "176",
            "yExact": "1",
            "y": "1",
            "id": "person:1099"
          },
          {
            "series": "0",
            "index": "176",
            "xExact": "177",
            "x": "177",
            "yExact": "197/239",
            "y": "0.824267782",
            "id": "person:1104"
          },
          {
            "series": "1",
            "index": "176",
            "xExact": "177",
            "x": "177",
            "yExact": "1",
            "y": "1",
            "id": "person:1104"
          },
          {
            "series": "0",
            "index": "177",
            "xExact": "178",
            "x": "178",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:1108"
          },
          {
            "series": "1",
            "index": "177",
            "xExact": "178",
            "x": "178",
            "yExact": "0",
            "y": "0",
            "id": "person:1108"
          },
          {
            "series": "0",
            "index": "178",
            "xExact": "179",
            "x": "179",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:1122"
          },
          {
            "series": "1",
            "index": "178",
            "xExact": "179",
            "x": "179",
            "yExact": "1",
            "y": "1",
            "id": "person:1122"
          },
          {
            "series": "0",
            "index": "179",
            "xExact": "180",
            "x": "180",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:1123"
          },
          {
            "series": "1",
            "index": "179",
            "xExact": "180",
            "x": "180",
            "yExact": "1",
            "y": "1",
            "id": "person:1123"
          },
          {
            "series": "0",
            "index": "180",
            "xExact": "181",
            "x": "181",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:1138"
          },
          {
            "series": "1",
            "index": "180",
            "xExact": "181",
            "x": "181",
            "yExact": "0",
            "y": "0",
            "id": "person:1138"
          },
          {
            "series": "0",
            "index": "181",
            "xExact": "182",
            "x": "182",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:1147"
          },
          {
            "series": "1",
            "index": "181",
            "xExact": "182",
            "x": "182",
            "yExact": "1",
            "y": "1",
            "id": "person:1147"
          },
          {
            "series": "0",
            "index": "182",
            "xExact": "183",
            "x": "183",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:1163"
          },
          {
            "series": "1",
            "index": "182",
            "xExact": "183",
            "x": "183",
            "yExact": "1",
            "y": "1",
            "id": "person:1163"
          },
          {
            "series": "0",
            "index": "183",
            "xExact": "184",
            "x": "184",
            "yExact": "197/239",
            "y": "0.824267782",
            "id": "person:1165"
          },
          {
            "series": "1",
            "index": "183",
            "xExact": "184",
            "x": "184",
            "yExact": "1",
            "y": "1",
            "id": "person:1165"
          },
          {
            "series": "0",
            "index": "184",
            "xExact": "185",
            "x": "185",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:1166"
          },
          {
            "series": "1",
            "index": "184",
            "xExact": "185",
            "x": "185",
            "yExact": "1",
            "y": "1",
            "id": "person:1166"
          },
          {
            "series": "0",
            "index": "185",
            "xExact": "186",
            "x": "186",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:1169"
          },
          {
            "series": "1",
            "index": "185",
            "xExact": "186",
            "x": "186",
            "yExact": "1",
            "y": "1",
            "id": "person:1169"
          },
          {
            "series": "0",
            "index": "186",
            "xExact": "187",
            "x": "187",
            "yExact": "179/268",
            "y": "0.667910448",
            "id": "person:1171"
          },
          {
            "series": "1",
            "index": "186",
            "xExact": "187",
            "x": "187",
            "yExact": "1",
            "y": "1",
            "id": "person:1171"
          },
          {
            "series": "0",
            "index": "187",
            "xExact": "188",
            "x": "188",
            "yExact": "21/58",
            "y": "0.362068966",
            "id": "person:1175"
          },
          {
            "series": "1",
            "index": "187",
            "xExact": "188",
            "x": "188",
            "yExact": "0",
            "y": "0",
            "id": "person:1175"
          },
          {
            "series": "0",
            "index": "188",
            "xExact": "189",
            "x": "189",
            "yExact": "20/41",
            "y": "0.487804878",
            "id": "person:1189"
          },
          {
            "series": "1",
            "index": "188",
            "xExact": "189",
            "x": "189",
            "yExact": "0",
            "y": "0",
            "id": "person:1189"
          },
          {
            "series": "0",
            "index": "189",
            "xExact": "190",
            "x": "190",
            "yExact": "21/58",
            "y": "0.362068966",
            "id": "person:1194"
          },
          {
            "series": "1",
            "index": "189",
            "xExact": "190",
            "x": "190",
            "yExact": "1",
            "y": "1",
            "id": "person:1194"
          },
          {
            "series": "0",
            "index": "190",
            "xExact": "191",
            "x": "191",
            "yExact": "21/58",
            "y": "0.362068966",
            "id": "person:1196"
          },
          {
            "series": "1",
            "index": "190",
            "xExact": "191",
            "x": "191",
            "yExact": "0",
            "y": "0",
            "id": "person:1196"
          },
          {
            "series": "0",
            "index": "191",
            "xExact": "192",
            "x": "192",
            "yExact": "20/41",
            "y": "0.487804878",
            "id": "person:1200"
          },
          {
            "series": "1",
            "index": "191",
            "xExact": "192",
            "x": "192",
            "yExact": "0",
            "y": "0",
            "id": "person:1200"
          },
          {
            "series": "0",
            "index": "192",
            "xExact": "193",
            "x": "193",
            "yExact": "20/41",
            "y": "0.487804878",
            "id": "person:1213"
          },
          {
            "series": "1",
            "index": "192",
            "xExact": "193",
            "x": "193",
            "yExact": "0",
            "y": "0",
            "id": "person:1213"
          },
          {
            "series": "0",
            "index": "193",
            "xExact": "194",
            "x": "194",
            "yExact": "12/25",
            "y": "0.48",
            "id": "person:1219"
          },
          {
            "series": "1",
            "index": "193",
            "xExact": "194",
            "x": "194",
            "yExact": "0",
            "y": "0",
            "id": "person:1219"
          },
          {
            "series": "0",
            "index": "194",
            "xExact": "195",
            "x": "195",
            "yExact": "21/58",
            "y": "0.362068966",
            "id": "person:1220"
          },
          {
            "series": "1",
            "index": "194",
            "xExact": "195",
            "x": "195",
            "yExact": "1",
            "y": "1",
            "id": "person:1220"
          },
          {
            "series": "0",
            "index": "195",
            "xExact": "196",
            "x": "196",
            "yExact": "12/25",
            "y": "0.48",
            "id": "person:1223"
          },
          {
            "series": "1",
            "index": "195",
            "xExact": "196",
            "x": "196",
            "yExact": "1",
            "y": "1",
            "id": "person:1223"
          },
          {
            "series": "0",
            "index": "196",
            "xExact": "197",
            "x": "197",
            "yExact": "179/268",
            "y": "0.667910448",
            "id": "person:1231"
          },
          {
            "series": "1",
            "index": "196",
            "xExact": "197",
            "x": "197",
            "yExact": "0",
            "y": "0",
            "id": "person:1231"
          },
          {
            "series": "0",
            "index": "197",
            "xExact": "198",
            "x": "198",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:1233"
          },
          {
            "series": "1",
            "index": "197",
            "xExact": "198",
            "x": "198",
            "yExact": "1",
            "y": "1",
            "id": "person:1233"
          },
          {
            "series": "0",
            "index": "198",
            "xExact": "199",
            "x": "199",
            "yExact": "12/25",
            "y": "0.48",
            "id": "person:1236"
          },
          {
            "series": "1",
            "index": "198",
            "xExact": "199",
            "x": "199",
            "yExact": "0",
            "y": "0",
            "id": "person:1236"
          },
          {
            "series": "0",
            "index": "199",
            "xExact": "200",
            "x": "200",
            "yExact": "20/41",
            "y": "0.487804878",
            "id": "person:1252"
          },
          {
            "series": "1",
            "index": "199",
            "xExact": "200",
            "x": "200",
            "yExact": "1",
            "y": "1",
            "id": "person:1252"
          },
          {
            "series": "0",
            "index": "200",
            "xExact": "201",
            "x": "201",
            "yExact": "25/33",
            "y": "0.757575758",
            "id": "person:1257"
          },
          {
            "series": "1",
            "index": "200",
            "xExact": "201",
            "x": "201",
            "yExact": "1",
            "y": "1",
            "id": "person:1257"
          },
          {
            "series": "0",
            "index": "201",
            "xExact": "202",
            "x": "202",
            "yExact": "21/58",
            "y": "0.362068966",
            "id": "person:1259"
          },
          {
            "series": "1",
            "index": "201",
            "xExact": "202",
            "x": "202",
            "yExact": "0",
            "y": "0",
            "id": "person:1259"
          },
          {
            "series": "0",
            "index": "202",
            "xExact": "203",
            "x": "203",
            "yExact": "21/58",
            "y": "0.362068966",
            "id": "person:1277"
          },
          {
            "series": "1",
            "index": "202",
            "xExact": "203",
            "x": "203",
            "yExact": "1",
            "y": "1",
            "id": "person:1277"
          },
          {
            "series": "0",
            "index": "203",
            "xExact": "204",
            "x": "204",
            "yExact": "12/25",
            "y": "0.48",
            "id": "person:1279"
          },
          {
            "series": "1",
            "index": "203",
            "xExact": "204",
            "x": "204",
            "yExact": "1",
            "y": "1",
            "id": "person:1279"
          },
          {
            "series": "0",
            "index": "204",
            "xExact": "205",
            "x": "205",
            "yExact": "20/41",
            "y": "0.487804878",
            "id": "person:1281"
          },
          {
            "series": "1",
            "index": "204",
            "xExact": "205",
            "x": "205",
            "yExact": "0",
            "y": "0",
            "id": "person:1281"
          },
          {
            "series": "0",
            "index": "205",
            "xExact": "206",
            "x": "206",
            "yExact": "12/25",
            "y": "0.48",
            "id": "person:1284"
          },
          {
            "series": "1",
            "index": "205",
            "xExact": "206",
            "x": "206",
            "yExact": "1",
            "y": "1",
            "id": "person:1284"
          },
          {
            "series": "0",
            "index": "206",
            "xExact": "207",
            "x": "207",
            "yExact": "12/25",
            "y": "0.48",
            "id": "person:1288"
          },
          {
            "series": "1",
            "index": "206",
            "xExact": "207",
            "x": "207",
            "yExact": "1",
            "y": "1",
            "id": "person:1288"
          },
          {
            "series": "0",
            "index": "207",
            "xExact": "208",
            "x": "208",
            "yExact": "20/41",
            "y": "0.487804878",
            "id": "person:1294"
          },
          {
            "series": "1",
            "index": "207",
            "xExact": "208",
            "x": "208",
            "yExact": "1",
            "y": "1",
            "id": "person:1294"
          },
          {
            "series": "0",
            "index": "208",
            "xExact": "209",
            "x": "209",
            "yExact": "20/41",
            "y": "0.487804878",
            "id": "person:1296"
          },
          {
            "series": "1",
            "index": "208",
            "xExact": "209",
            "x": "209",
            "yExact": "1",
            "y": "1",
            "id": "person:1296"
          },
          {
            "series": "0",
            "index": "209",
            "xExact": "210",
            "x": "210",
            "yExact": "21/58",
            "y": "0.362068966",
            "id": "person:1304"
          },
          {
            "series": "1",
            "index": "209",
            "xExact": "210",
            "x": "210",
            "yExact": "0",
            "y": "0",
            "id": "person:1304"
          },
          {
            "series": "0",
            "index": "210",
            "xExact": "211",
            "x": "211",
            "yExact": "21/58",
            "y": "0.362068966",
            "id": "person:1310"
          },
          {
            "series": "1",
            "index": "210",
            "xExact": "211",
            "x": "211",
            "yExact": "1",
            "y": "1",
            "id": "person:1310"
          },
          {
            "series": "0",
            "index": "211",
            "xExact": "212",
            "x": "212",
            "yExact": "179/268",
            "y": "0.667910448",
            "id": "person:1314"
          },
          {
            "series": "1",
            "index": "211",
            "xExact": "212",
            "x": "212",
            "yExact": "1",
            "y": "1",
            "id": "person:1314"
          },
          {
            "series": "0",
            "index": "212",
            "xExact": "213",
            "x": "213",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:1321"
          },
          {
            "series": "1",
            "index": "212",
            "xExact": "213",
            "x": "213",
            "yExact": "1",
            "y": "1",
            "id": "person:1321"
          },
          {
            "series": "0",
            "index": "213",
            "xExact": "214",
            "x": "214",
            "yExact": "197/239",
            "y": "0.824267782",
            "id": "person:1332"
          },
          {
            "series": "1",
            "index": "213",
            "xExact": "214",
            "x": "214",
            "yExact": "1",
            "y": "1",
            "id": "person:1332"
          },
          {
            "series": "0",
            "index": "214",
            "xExact": "215",
            "x": "215",
            "yExact": "179/268",
            "y": "0.667910448",
            "id": "person:1345"
          },
          {
            "series": "1",
            "index": "214",
            "xExact": "215",
            "x": "215",
            "yExact": "0",
            "y": "0",
            "id": "person:1345"
          },
          {
            "series": "0",
            "index": "215",
            "xExact": "216",
            "x": "216",
            "yExact": "197/239",
            "y": "0.824267782",
            "id": "person:1352"
          },
          {
            "series": "1",
            "index": "215",
            "xExact": "216",
            "x": "216",
            "yExact": "1",
            "y": "1",
            "id": "person:1352"
          },
          {
            "series": "0",
            "index": "216",
            "xExact": "217",
            "x": "217",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:1358"
          },
          {
            "series": "1",
            "index": "216",
            "xExact": "217",
            "x": "217",
            "yExact": "0",
            "y": "0",
            "id": "person:1358"
          },
          {
            "series": "0",
            "index": "217",
            "xExact": "218",
            "x": "218",
            "yExact": "197/239",
            "y": "0.824267782",
            "id": "person:1365"
          },
          {
            "series": "1",
            "index": "217",
            "xExact": "218",
            "x": "218",
            "yExact": "1",
            "y": "1",
            "id": "person:1365"
          },
          {
            "series": "0",
            "index": "218",
            "xExact": "219",
            "x": "219",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:1366"
          },
          {
            "series": "1",
            "index": "218",
            "xExact": "219",
            "x": "219",
            "yExact": "1",
            "y": "1",
            "id": "person:1366"
          },
          {
            "series": "0",
            "index": "219",
            "xExact": "220",
            "x": "220",
            "yExact": "179/268",
            "y": "0.667910448",
            "id": "person:1368"
          },
          {
            "series": "1",
            "index": "219",
            "xExact": "220",
            "x": "220",
            "yExact": "1",
            "y": "1",
            "id": "person:1368"
          },
          {
            "series": "0",
            "index": "220",
            "xExact": "221",
            "x": "221",
            "yExact": "197/239",
            "y": "0.824267782",
            "id": "person:1372"
          },
          {
            "series": "1",
            "index": "220",
            "xExact": "221",
            "x": "221",
            "yExact": "1",
            "y": "1",
            "id": "person:1372"
          },
          {
            "series": "0",
            "index": "221",
            "xExact": "222",
            "x": "222",
            "yExact": "179/268",
            "y": "0.667910448",
            "id": "person:1377"
          },
          {
            "series": "1",
            "index": "221",
            "xExact": "222",
            "x": "222",
            "yExact": "1",
            "y": "1",
            "id": "person:1377"
          },
          {
            "series": "0",
            "index": "222",
            "xExact": "223",
            "x": "223",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:1378"
          },
          {
            "series": "1",
            "index": "222",
            "xExact": "223",
            "x": "223",
            "yExact": "1",
            "y": "1",
            "id": "person:1378"
          },
          {
            "series": "0",
            "index": "223",
            "xExact": "224",
            "x": "224",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:1384"
          },
          {
            "series": "1",
            "index": "223",
            "xExact": "224",
            "x": "224",
            "yExact": "1",
            "y": "1",
            "id": "person:1384"
          },
          {
            "series": "0",
            "index": "224",
            "xExact": "225",
            "x": "225",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:1388"
          },
          {
            "series": "1",
            "index": "224",
            "xExact": "225",
            "x": "225",
            "yExact": "0",
            "y": "0",
            "id": "person:1388"
          },
          {
            "series": "0",
            "index": "225",
            "xExact": "226",
            "x": "226",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:1404"
          },
          {
            "series": "1",
            "index": "225",
            "xExact": "226",
            "x": "226",
            "yExact": "1",
            "y": "1",
            "id": "person:1404"
          },
          {
            "series": "0",
            "index": "226",
            "xExact": "227",
            "x": "227",
            "yExact": "179/268",
            "y": "0.667910448",
            "id": "person:1408"
          },
          {
            "series": "1",
            "index": "226",
            "xExact": "227",
            "x": "227",
            "yExact": "0",
            "y": "0",
            "id": "person:1408"
          },
          {
            "series": "0",
            "index": "227",
            "xExact": "228",
            "x": "228",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:1409"
          },
          {
            "series": "1",
            "index": "227",
            "xExact": "228",
            "x": "228",
            "yExact": "1",
            "y": "1",
            "id": "person:1409"
          },
          {
            "series": "0",
            "index": "228",
            "xExact": "229",
            "x": "229",
            "yExact": "179/268",
            "y": "0.667910448",
            "id": "person:1412"
          },
          {
            "series": "1",
            "index": "228",
            "xExact": "229",
            "x": "229",
            "yExact": "1",
            "y": "1",
            "id": "person:1412"
          },
          {
            "series": "0",
            "index": "229",
            "xExact": "230",
            "x": "230",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:1415"
          },
          {
            "series": "1",
            "index": "229",
            "xExact": "230",
            "x": "230",
            "yExact": "1",
            "y": "1",
            "id": "person:1415"
          },
          {
            "series": "0",
            "index": "230",
            "xExact": "231",
            "x": "231",
            "yExact": "12/25",
            "y": "0.48",
            "id": "person:1433"
          },
          {
            "series": "1",
            "index": "230",
            "xExact": "231",
            "x": "231",
            "yExact": "0",
            "y": "0",
            "id": "person:1433"
          },
          {
            "series": "0",
            "index": "231",
            "xExact": "232",
            "x": "232",
            "yExact": "21/58",
            "y": "0.362068966",
            "id": "person:1434"
          },
          {
            "series": "1",
            "index": "231",
            "xExact": "232",
            "x": "232",
            "yExact": "1",
            "y": "1",
            "id": "person:1434"
          },
          {
            "series": "0",
            "index": "232",
            "xExact": "233",
            "x": "233",
            "yExact": "21/58",
            "y": "0.362068966",
            "id": "person:1439"
          },
          {
            "series": "1",
            "index": "232",
            "xExact": "233",
            "x": "233",
            "yExact": "0",
            "y": "0",
            "id": "person:1439"
          },
          {
            "series": "0",
            "index": "233",
            "xExact": "234",
            "x": "234",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:1444"
          },
          {
            "series": "1",
            "index": "233",
            "xExact": "234",
            "x": "234",
            "yExact": "0",
            "y": "0",
            "id": "person:1444"
          },
          {
            "series": "0",
            "index": "234",
            "xExact": "235",
            "x": "235",
            "yExact": "179/268",
            "y": "0.667910448",
            "id": "person:1447"
          },
          {
            "series": "1",
            "index": "234",
            "xExact": "235",
            "x": "235",
            "yExact": "1",
            "y": "1",
            "id": "person:1447"
          },
          {
            "series": "0",
            "index": "235",
            "xExact": "236",
            "x": "236",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:1471"
          },
          {
            "series": "1",
            "index": "235",
            "xExact": "236",
            "x": "236",
            "yExact": "1",
            "y": "1",
            "id": "person:1471"
          },
          {
            "series": "0",
            "index": "236",
            "xExact": "237",
            "x": "237",
            "yExact": "197/239",
            "y": "0.824267782",
            "id": "person:1479"
          },
          {
            "series": "1",
            "index": "236",
            "xExact": "237",
            "x": "237",
            "yExact": "0",
            "y": "0",
            "id": "person:1479"
          },
          {
            "series": "0",
            "index": "237",
            "xExact": "238",
            "x": "238",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:1484"
          },
          {
            "series": "1",
            "index": "237",
            "xExact": "238",
            "x": "238",
            "yExact": "0",
            "y": "0",
            "id": "person:1484"
          },
          {
            "series": "0",
            "index": "238",
            "xExact": "239",
            "x": "239",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:1488"
          },
          {
            "series": "1",
            "index": "238",
            "xExact": "239",
            "x": "239",
            "yExact": "0",
            "y": "0",
            "id": "person:1488"
          },
          {
            "series": "0",
            "index": "239",
            "xExact": "240",
            "x": "240",
            "yExact": "179/268",
            "y": "0.667910448",
            "id": "person:1497"
          },
          {
            "series": "1",
            "index": "239",
            "xExact": "240",
            "x": "240",
            "yExact": "1",
            "y": "1",
            "id": "person:1497"
          },
          {
            "series": "0",
            "index": "240",
            "xExact": "241",
            "x": "241",
            "yExact": "179/268",
            "y": "0.667910448",
            "id": "person:1498"
          },
          {
            "series": "1",
            "index": "240",
            "xExact": "241",
            "x": "241",
            "yExact": "0",
            "y": "0",
            "id": "person:1498"
          },
          {
            "series": "0",
            "index": "241",
            "xExact": "242",
            "x": "242",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:1515"
          },
          {
            "series": "1",
            "index": "241",
            "xExact": "242",
            "x": "242",
            "yExact": "0",
            "y": "0",
            "id": "person:1515"
          },
          {
            "series": "0",
            "index": "242",
            "xExact": "243",
            "x": "243",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:1516"
          },
          {
            "series": "1",
            "index": "242",
            "xExact": "243",
            "x": "243",
            "yExact": "0",
            "y": "0",
            "id": "person:1516"
          },
          {
            "series": "0",
            "index": "243",
            "xExact": "244",
            "x": "244",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:1518"
          },
          {
            "series": "1",
            "index": "243",
            "xExact": "244",
            "x": "244",
            "yExact": "0",
            "y": "0",
            "id": "person:1518"
          },
          {
            "series": "0",
            "index": "244",
            "xExact": "245",
            "x": "245",
            "yExact": "197/239",
            "y": "0.824267782",
            "id": "person:1522"
          },
          {
            "series": "1",
            "index": "244",
            "xExact": "245",
            "x": "245",
            "yExact": "1",
            "y": "1",
            "id": "person:1522"
          },
          {
            "series": "0",
            "index": "245",
            "xExact": "246",
            "x": "246",
            "yExact": "20/41",
            "y": "0.487804878",
            "id": "person:1527"
          },
          {
            "series": "1",
            "index": "245",
            "xExact": "246",
            "x": "246",
            "yExact": "0",
            "y": "0",
            "id": "person:1527"
          },
          {
            "series": "0",
            "index": "246",
            "xExact": "247",
            "x": "247",
            "yExact": "25/33",
            "y": "0.757575758",
            "id": "person:1528"
          },
          {
            "series": "1",
            "index": "246",
            "xExact": "247",
            "x": "247",
            "yExact": "1",
            "y": "1",
            "id": "person:1528"
          },
          {
            "series": "0",
            "index": "247",
            "xExact": "248",
            "x": "248",
            "yExact": "20/41",
            "y": "0.487804878",
            "id": "person:1538"
          },
          {
            "series": "1",
            "index": "247",
            "xExact": "248",
            "x": "248",
            "yExact": "0",
            "y": "0",
            "id": "person:1538"
          },
          {
            "series": "0",
            "index": "248",
            "xExact": "249",
            "x": "249",
            "yExact": "12/25",
            "y": "0.48",
            "id": "person:1539"
          },
          {
            "series": "1",
            "index": "248",
            "xExact": "249",
            "x": "249",
            "yExact": "0",
            "y": "0",
            "id": "person:1539"
          },
          {
            "series": "0",
            "index": "249",
            "xExact": "250",
            "x": "250",
            "yExact": "25/33",
            "y": "0.757575758",
            "id": "person:1551"
          },
          {
            "series": "1",
            "index": "249",
            "xExact": "250",
            "x": "250",
            "yExact": "1",
            "y": "1",
            "id": "person:1551"
          },
          {
            "series": "0",
            "index": "250",
            "xExact": "251",
            "x": "251",
            "yExact": "25/33",
            "y": "0.757575758",
            "id": "person:1552"
          },
          {
            "series": "1",
            "index": "250",
            "xExact": "251",
            "x": "251",
            "yExact": "1",
            "y": "1",
            "id": "person:1552"
          },
          {
            "series": "0",
            "index": "251",
            "xExact": "252",
            "x": "252",
            "yExact": "21/58",
            "y": "0.362068966",
            "id": "person:1556"
          },
          {
            "series": "1",
            "index": "251",
            "xExact": "252",
            "x": "252",
            "yExact": "1",
            "y": "1",
            "id": "person:1556"
          },
          {
            "series": "0",
            "index": "252",
            "xExact": "253",
            "x": "253",
            "yExact": "20/41",
            "y": "0.487804878",
            "id": "person:1561"
          },
          {
            "series": "1",
            "index": "252",
            "xExact": "253",
            "x": "253",
            "yExact": "1",
            "y": "1",
            "id": "person:1561"
          },
          {
            "series": "0",
            "index": "253",
            "xExact": "254",
            "x": "254",
            "yExact": "25/33",
            "y": "0.757575758",
            "id": "person:1562"
          },
          {
            "series": "1",
            "index": "253",
            "xExact": "254",
            "x": "254",
            "yExact": "1",
            "y": "1",
            "id": "person:1562"
          },
          {
            "series": "0",
            "index": "254",
            "xExact": "255",
            "x": "255",
            "yExact": "12/25",
            "y": "0.48",
            "id": "person:1563"
          },
          {
            "series": "1",
            "index": "254",
            "xExact": "255",
            "x": "255",
            "yExact": "0",
            "y": "0",
            "id": "person:1563"
          },
          {
            "series": "0",
            "index": "255",
            "xExact": "256",
            "x": "256",
            "yExact": "21/58",
            "y": "0.362068966",
            "id": "person:1564"
          },
          {
            "series": "1",
            "index": "255",
            "xExact": "256",
            "x": "256",
            "yExact": "1",
            "y": "1",
            "id": "person:1564"
          },
          {
            "series": "0",
            "index": "256",
            "xExact": "257",
            "x": "257",
            "yExact": "197/239",
            "y": "0.824267782",
            "id": "person:1566"
          },
          {
            "series": "1",
            "index": "256",
            "xExact": "257",
            "x": "257",
            "yExact": "1",
            "y": "1",
            "id": "person:1566"
          },
          {
            "series": "0",
            "index": "257",
            "xExact": "258",
            "x": "258",
            "yExact": "21/58",
            "y": "0.362068966",
            "id": "person:1571"
          },
          {
            "series": "1",
            "index": "257",
            "xExact": "258",
            "x": "258",
            "yExact": "1",
            "y": "1",
            "id": "person:1571"
          },
          {
            "series": "0",
            "index": "258",
            "xExact": "259",
            "x": "259",
            "yExact": "21/58",
            "y": "0.362068966",
            "id": "person:1573"
          },
          {
            "series": "1",
            "index": "258",
            "xExact": "259",
            "x": "259",
            "yExact": "0",
            "y": "0",
            "id": "person:1573"
          },
          {
            "series": "0",
            "index": "259",
            "xExact": "260",
            "x": "260",
            "yExact": "12/25",
            "y": "0.48",
            "id": "person:1574"
          },
          {
            "series": "1",
            "index": "259",
            "xExact": "260",
            "x": "260",
            "yExact": "1",
            "y": "1",
            "id": "person:1574"
          },
          {
            "series": "0",
            "index": "260",
            "xExact": "261",
            "x": "261",
            "yExact": "12/25",
            "y": "0.48",
            "id": "person:1575"
          },
          {
            "series": "1",
            "index": "260",
            "xExact": "261",
            "x": "261",
            "yExact": "0",
            "y": "0",
            "id": "person:1575"
          },
          {
            "series": "0",
            "index": "261",
            "xExact": "262",
            "x": "262",
            "yExact": "21/58",
            "y": "0.362068966",
            "id": "person:1580"
          },
          {
            "series": "1",
            "index": "261",
            "xExact": "262",
            "x": "262",
            "yExact": "1",
            "y": "1",
            "id": "person:1580"
          },
          {
            "series": "0",
            "index": "262",
            "xExact": "263",
            "x": "263",
            "yExact": "21/58",
            "y": "0.362068966",
            "id": "person:1588"
          },
          {
            "series": "1",
            "index": "262",
            "xExact": "263",
            "x": "263",
            "yExact": "1",
            "y": "1",
            "id": "person:1588"
          },
          {
            "series": "0",
            "index": "263",
            "xExact": "264",
            "x": "264",
            "yExact": "25/33",
            "y": "0.757575758",
            "id": "person:1596"
          },
          {
            "series": "1",
            "index": "263",
            "xExact": "264",
            "x": "264",
            "yExact": "1",
            "y": "1",
            "id": "person:1596"
          },
          {
            "series": "0",
            "index": "264",
            "xExact": "265",
            "x": "265",
            "yExact": "21/58",
            "y": "0.362068966",
            "id": "person:1603"
          },
          {
            "series": "1",
            "index": "264",
            "xExact": "265",
            "x": "265",
            "yExact": "1",
            "y": "1",
            "id": "person:1603"
          },
          {
            "series": "0",
            "index": "265",
            "xExact": "266",
            "x": "266",
            "yExact": "25/33",
            "y": "0.757575758",
            "id": "person:1609"
          },
          {
            "series": "1",
            "index": "265",
            "xExact": "266",
            "x": "266",
            "yExact": "1",
            "y": "1",
            "id": "person:1609"
          },
          {
            "series": "0",
            "index": "266",
            "xExact": "267",
            "x": "267",
            "yExact": "20/41",
            "y": "0.487804878",
            "id": "person:1625"
          },
          {
            "series": "1",
            "index": "266",
            "xExact": "267",
            "x": "267",
            "yExact": "0",
            "y": "0",
            "id": "person:1625"
          },
          {
            "series": "0",
            "index": "267",
            "xExact": "268",
            "x": "268",
            "yExact": "21/58",
            "y": "0.362068966",
            "id": "person:1630"
          },
          {
            "series": "1",
            "index": "267",
            "xExact": "268",
            "x": "268",
            "yExact": "1",
            "y": "1",
            "id": "person:1630"
          },
          {
            "series": "0",
            "index": "268",
            "xExact": "269",
            "x": "269",
            "yExact": "12/25",
            "y": "0.48",
            "id": "person:1634"
          },
          {
            "series": "1",
            "index": "268",
            "xExact": "269",
            "x": "269",
            "yExact": "1",
            "y": "1",
            "id": "person:1634"
          },
          {
            "series": "0",
            "index": "269",
            "xExact": "270",
            "x": "270",
            "yExact": "21/58",
            "y": "0.362068966",
            "id": "person:1635"
          },
          {
            "series": "1",
            "index": "269",
            "xExact": "270",
            "x": "270",
            "yExact": "1",
            "y": "1",
            "id": "person:1635"
          },
          {
            "series": "0",
            "index": "270",
            "xExact": "271",
            "x": "271",
            "yExact": "179/268",
            "y": "0.667910448",
            "id": "person:1638"
          },
          {
            "series": "1",
            "index": "270",
            "xExact": "271",
            "x": "271",
            "yExact": "0",
            "y": "0",
            "id": "person:1638"
          },
          {
            "series": "0",
            "index": "271",
            "xExact": "272",
            "x": "272",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:1641"
          },
          {
            "series": "1",
            "index": "271",
            "xExact": "272",
            "x": "272",
            "yExact": "1",
            "y": "1",
            "id": "person:1641"
          },
          {
            "series": "0",
            "index": "272",
            "xExact": "273",
            "x": "273",
            "yExact": "179/268",
            "y": "0.667910448",
            "id": "person:1653"
          },
          {
            "series": "1",
            "index": "272",
            "xExact": "273",
            "x": "273",
            "yExact": "0",
            "y": "0",
            "id": "person:1653"
          },
          {
            "series": "0",
            "index": "273",
            "xExact": "274",
            "x": "274",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:1656"
          },
          {
            "series": "1",
            "index": "273",
            "xExact": "274",
            "x": "274",
            "yExact": "1",
            "y": "1",
            "id": "person:1656"
          },
          {
            "series": "0",
            "index": "274",
            "xExact": "275",
            "x": "275",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:1658"
          },
          {
            "series": "1",
            "index": "274",
            "xExact": "275",
            "x": "275",
            "yExact": "1",
            "y": "1",
            "id": "person:1658"
          },
          {
            "series": "0",
            "index": "275",
            "xExact": "276",
            "x": "276",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:1673"
          },
          {
            "series": "1",
            "index": "275",
            "xExact": "276",
            "x": "276",
            "yExact": "1",
            "y": "1",
            "id": "person:1673"
          },
          {
            "series": "0",
            "index": "276",
            "xExact": "277",
            "x": "277",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:1684"
          },
          {
            "series": "1",
            "index": "276",
            "xExact": "277",
            "x": "277",
            "yExact": "1",
            "y": "1",
            "id": "person:1684"
          },
          {
            "series": "0",
            "index": "277",
            "xExact": "278",
            "x": "278",
            "yExact": "197/239",
            "y": "0.824267782",
            "id": "person:1686"
          },
          {
            "series": "1",
            "index": "277",
            "xExact": "278",
            "x": "278",
            "yExact": "1",
            "y": "1",
            "id": "person:1686"
          },
          {
            "series": "0",
            "index": "278",
            "xExact": "279",
            "x": "279",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:1692"
          },
          {
            "series": "1",
            "index": "278",
            "xExact": "279",
            "x": "279",
            "yExact": "0",
            "y": "0",
            "id": "person:1692"
          },
          {
            "series": "0",
            "index": "279",
            "xExact": "280",
            "x": "280",
            "yExact": "179/268",
            "y": "0.667910448",
            "id": "person:1720"
          },
          {
            "series": "1",
            "index": "279",
            "xExact": "280",
            "x": "280",
            "yExact": "1",
            "y": "1",
            "id": "person:1720"
          },
          {
            "series": "0",
            "index": "280",
            "xExact": "281",
            "x": "281",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:1722"
          },
          {
            "series": "1",
            "index": "280",
            "xExact": "281",
            "x": "281",
            "yExact": "1",
            "y": "1",
            "id": "person:1722"
          },
          {
            "series": "0",
            "index": "281",
            "xExact": "282",
            "x": "282",
            "yExact": "179/268",
            "y": "0.667910448",
            "id": "person:1740"
          },
          {
            "series": "1",
            "index": "281",
            "xExact": "282",
            "x": "282",
            "yExact": "1",
            "y": "1",
            "id": "person:1740"
          },
          {
            "series": "0",
            "index": "282",
            "xExact": "283",
            "x": "283",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:1742"
          },
          {
            "series": "1",
            "index": "282",
            "xExact": "283",
            "x": "283",
            "yExact": "1",
            "y": "1",
            "id": "person:1742"
          },
          {
            "series": "0",
            "index": "283",
            "xExact": "284",
            "x": "284",
            "yExact": "179/268",
            "y": "0.667910448",
            "id": "person:1744"
          },
          {
            "series": "1",
            "index": "283",
            "xExact": "284",
            "x": "284",
            "yExact": "0",
            "y": "0",
            "id": "person:1744"
          },
          {
            "series": "0",
            "index": "284",
            "xExact": "285",
            "x": "285",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:1745"
          },
          {
            "series": "1",
            "index": "284",
            "xExact": "285",
            "x": "285",
            "yExact": "0",
            "y": "0",
            "id": "person:1745"
          },
          {
            "series": "0",
            "index": "285",
            "xExact": "286",
            "x": "286",
            "yExact": "179/268",
            "y": "0.667910448",
            "id": "person:1755"
          },
          {
            "series": "1",
            "index": "285",
            "xExact": "286",
            "x": "286",
            "yExact": "1",
            "y": "1",
            "id": "person:1755"
          },
          {
            "series": "0",
            "index": "286",
            "xExact": "287",
            "x": "287",
            "yExact": "179/268",
            "y": "0.667910448",
            "id": "person:1760"
          },
          {
            "series": "1",
            "index": "286",
            "xExact": "287",
            "x": "287",
            "yExact": "0",
            "y": "0",
            "id": "person:1760"
          },
          {
            "series": "0",
            "index": "287",
            "xExact": "288",
            "x": "288",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:1765"
          },
          {
            "series": "1",
            "index": "287",
            "xExact": "288",
            "x": "288",
            "yExact": "0",
            "y": "0",
            "id": "person:1765"
          },
          {
            "series": "0",
            "index": "288",
            "xExact": "289",
            "x": "289",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:1771"
          },
          {
            "series": "1",
            "index": "288",
            "xExact": "289",
            "x": "289",
            "yExact": "1",
            "y": "1",
            "id": "person:1771"
          },
          {
            "series": "0",
            "index": "289",
            "xExact": "290",
            "x": "290",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:1777"
          },
          {
            "series": "1",
            "index": "289",
            "xExact": "290",
            "x": "290",
            "yExact": "1",
            "y": "1",
            "id": "person:1777"
          },
          {
            "series": "0",
            "index": "290",
            "xExact": "291",
            "x": "291",
            "yExact": "179/268",
            "y": "0.667910448",
            "id": "person:1781"
          },
          {
            "series": "1",
            "index": "290",
            "xExact": "291",
            "x": "291",
            "yExact": "0",
            "y": "0",
            "id": "person:1781"
          },
          {
            "series": "0",
            "index": "291",
            "xExact": "292",
            "x": "292",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:1785"
          },
          {
            "series": "1",
            "index": "291",
            "xExact": "292",
            "x": "292",
            "yExact": "0",
            "y": "0",
            "id": "person:1785"
          },
          {
            "series": "0",
            "index": "292",
            "xExact": "293",
            "x": "293",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:1800"
          },
          {
            "series": "1",
            "index": "292",
            "xExact": "293",
            "x": "293",
            "yExact": "1",
            "y": "1",
            "id": "person:1800"
          },
          {
            "series": "0",
            "index": "293",
            "xExact": "294",
            "x": "294",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:1801"
          },
          {
            "series": "1",
            "index": "293",
            "xExact": "294",
            "x": "294",
            "yExact": "0",
            "y": "0",
            "id": "person:1801"
          },
          {
            "series": "0",
            "index": "294",
            "xExact": "295",
            "x": "295",
            "yExact": "179/268",
            "y": "0.667910448",
            "id": "person:1804"
          },
          {
            "series": "1",
            "index": "294",
            "xExact": "295",
            "x": "295",
            "yExact": "1",
            "y": "1",
            "id": "person:1804"
          },
          {
            "series": "0",
            "index": "295",
            "xExact": "296",
            "x": "296",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:1808"
          },
          {
            "series": "1",
            "index": "295",
            "xExact": "296",
            "x": "296",
            "yExact": "0",
            "y": "0",
            "id": "person:1808"
          },
          {
            "series": "0",
            "index": "296",
            "xExact": "297",
            "x": "297",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:1811"
          },
          {
            "series": "1",
            "index": "296",
            "xExact": "297",
            "x": "297",
            "yExact": "1",
            "y": "1",
            "id": "person:1811"
          },
          {
            "series": "0",
            "index": "297",
            "xExact": "298",
            "x": "298",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:1823"
          },
          {
            "series": "1",
            "index": "297",
            "xExact": "298",
            "x": "298",
            "yExact": "1",
            "y": "1",
            "id": "person:1823"
          },
          {
            "series": "0",
            "index": "298",
            "xExact": "299",
            "x": "299",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:1825"
          },
          {
            "series": "1",
            "index": "298",
            "xExact": "299",
            "x": "299",
            "yExact": "1",
            "y": "1",
            "id": "person:1825"
          },
          {
            "series": "0",
            "index": "299",
            "xExact": "300",
            "x": "300",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:1826"
          },
          {
            "series": "1",
            "index": "299",
            "xExact": "300",
            "x": "300",
            "yExact": "1",
            "y": "1",
            "id": "person:1826"
          },
          {
            "series": "0",
            "index": "300",
            "xExact": "301",
            "x": "301",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:1828"
          },
          {
            "series": "1",
            "index": "300",
            "xExact": "301",
            "x": "301",
            "yExact": "0",
            "y": "0",
            "id": "person:1828"
          },
          {
            "series": "0",
            "index": "301",
            "xExact": "302",
            "x": "302",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:1837"
          },
          {
            "series": "1",
            "index": "301",
            "xExact": "302",
            "x": "302",
            "yExact": "1",
            "y": "1",
            "id": "person:1837"
          },
          {
            "series": "0",
            "index": "302",
            "xExact": "303",
            "x": "303",
            "yExact": "197/239",
            "y": "0.824267782",
            "id": "person:1842"
          },
          {
            "series": "1",
            "index": "302",
            "xExact": "303",
            "x": "303",
            "yExact": "0",
            "y": "0",
            "id": "person:1842"
          },
          {
            "series": "0",
            "index": "303",
            "xExact": "304",
            "x": "304",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:1852"
          },
          {
            "series": "1",
            "index": "303",
            "xExact": "304",
            "x": "304",
            "yExact": "1",
            "y": "1",
            "id": "person:1852"
          },
          {
            "series": "0",
            "index": "304",
            "xExact": "305",
            "x": "305",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:1853"
          },
          {
            "series": "1",
            "index": "304",
            "xExact": "305",
            "x": "305",
            "yExact": "1",
            "y": "1",
            "id": "person:1853"
          },
          {
            "series": "0",
            "index": "305",
            "xExact": "306",
            "x": "306",
            "yExact": "197/239",
            "y": "0.824267782",
            "id": "person:1859"
          },
          {
            "series": "1",
            "index": "305",
            "xExact": "306",
            "x": "306",
            "yExact": "1",
            "y": "1",
            "id": "person:1859"
          },
          {
            "series": "0",
            "index": "306",
            "xExact": "307",
            "x": "307",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:1861"
          },
          {
            "series": "1",
            "index": "306",
            "xExact": "307",
            "x": "307",
            "yExact": "1",
            "y": "1",
            "id": "person:1861"
          },
          {
            "series": "0",
            "index": "307",
            "xExact": "308",
            "x": "308",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:1864"
          },
          {
            "series": "1",
            "index": "307",
            "xExact": "308",
            "x": "308",
            "yExact": "1",
            "y": "1",
            "id": "person:1864"
          },
          {
            "series": "0",
            "index": "308",
            "xExact": "309",
            "x": "309",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:1867"
          },
          {
            "series": "1",
            "index": "308",
            "xExact": "309",
            "x": "309",
            "yExact": "1",
            "y": "1",
            "id": "person:1867"
          },
          {
            "series": "0",
            "index": "309",
            "xExact": "310",
            "x": "310",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:1871"
          },
          {
            "series": "1",
            "index": "309",
            "xExact": "310",
            "x": "310",
            "yExact": "1",
            "y": "1",
            "id": "person:1871"
          },
          {
            "series": "0",
            "index": "310",
            "xExact": "311",
            "x": "311",
            "yExact": "179/268",
            "y": "0.667910448",
            "id": "person:1881"
          },
          {
            "series": "1",
            "index": "310",
            "xExact": "311",
            "x": "311",
            "yExact": "0",
            "y": "0",
            "id": "person:1881"
          },
          {
            "series": "0",
            "index": "311",
            "xExact": "312",
            "x": "312",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:1886"
          },
          {
            "series": "1",
            "index": "311",
            "xExact": "312",
            "x": "312",
            "yExact": "1",
            "y": "1",
            "id": "person:1886"
          },
          {
            "series": "0",
            "index": "312",
            "xExact": "313",
            "x": "313",
            "yExact": "197/239",
            "y": "0.824267782",
            "id": "person:1890"
          },
          {
            "series": "1",
            "index": "312",
            "xExact": "313",
            "x": "313",
            "yExact": "1",
            "y": "1",
            "id": "person:1890"
          },
          {
            "series": "0",
            "index": "313",
            "xExact": "314",
            "x": "314",
            "yExact": "179/268",
            "y": "0.667910448",
            "id": "person:1898"
          },
          {
            "series": "1",
            "index": "313",
            "xExact": "314",
            "x": "314",
            "yExact": "0",
            "y": "0",
            "id": "person:1898"
          },
          {
            "series": "0",
            "index": "314",
            "xExact": "315",
            "x": "315",
            "yExact": "21/58",
            "y": "0.362068966",
            "id": "person:1900"
          },
          {
            "series": "1",
            "index": "314",
            "xExact": "315",
            "x": "315",
            "yExact": "1",
            "y": "1",
            "id": "person:1900"
          },
          {
            "series": "0",
            "index": "315",
            "xExact": "316",
            "x": "316",
            "yExact": "20/41",
            "y": "0.487804878",
            "id": "person:1902"
          },
          {
            "series": "1",
            "index": "315",
            "xExact": "316",
            "x": "316",
            "yExact": "1",
            "y": "1",
            "id": "person:1902"
          },
          {
            "series": "0",
            "index": "316",
            "xExact": "317",
            "x": "317",
            "yExact": "20/41",
            "y": "0.487804878",
            "id": "person:1909"
          },
          {
            "series": "1",
            "index": "316",
            "xExact": "317",
            "x": "317",
            "yExact": "1",
            "y": "1",
            "id": "person:1909"
          },
          {
            "series": "0",
            "index": "317",
            "xExact": "318",
            "x": "318",
            "yExact": "20/41",
            "y": "0.487804878",
            "id": "person:1912"
          },
          {
            "series": "1",
            "index": "317",
            "xExact": "318",
            "x": "318",
            "yExact": "0",
            "y": "0",
            "id": "person:1912"
          },
          {
            "series": "0",
            "index": "318",
            "xExact": "319",
            "x": "319",
            "yExact": "21/58",
            "y": "0.362068966",
            "id": "person:1916"
          },
          {
            "series": "1",
            "index": "318",
            "xExact": "319",
            "x": "319",
            "yExact": "1",
            "y": "1",
            "id": "person:1916"
          },
          {
            "series": "0",
            "index": "319",
            "xExact": "320",
            "x": "320",
            "yExact": "21/58",
            "y": "0.362068966",
            "id": "person:1918"
          },
          {
            "series": "1",
            "index": "319",
            "xExact": "320",
            "x": "320",
            "yExact": "1",
            "y": "1",
            "id": "person:1918"
          },
          {
            "series": "0",
            "index": "320",
            "xExact": "321",
            "x": "321",
            "yExact": "21/58",
            "y": "0.362068966",
            "id": "person:1922"
          },
          {
            "series": "1",
            "index": "320",
            "xExact": "321",
            "x": "321",
            "yExact": "0",
            "y": "0",
            "id": "person:1922"
          },
          {
            "series": "0",
            "index": "321",
            "xExact": "322",
            "x": "322",
            "yExact": "21/58",
            "y": "0.362068966",
            "id": "person:1923"
          },
          {
            "series": "1",
            "index": "321",
            "xExact": "322",
            "x": "322",
            "yExact": "0",
            "y": "0",
            "id": "person:1923"
          },
          {
            "series": "0",
            "index": "322",
            "xExact": "323",
            "x": "323",
            "yExact": "21/58",
            "y": "0.362068966",
            "id": "person:1929"
          },
          {
            "series": "1",
            "index": "322",
            "xExact": "323",
            "x": "323",
            "yExact": "1",
            "y": "1",
            "id": "person:1929"
          },
          {
            "series": "0",
            "index": "323",
            "xExact": "324",
            "x": "324",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:1933"
          },
          {
            "series": "1",
            "index": "323",
            "xExact": "324",
            "x": "324",
            "yExact": "0",
            "y": "0",
            "id": "person:1933"
          },
          {
            "series": "0",
            "index": "324",
            "xExact": "325",
            "x": "325",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:1934"
          },
          {
            "series": "1",
            "index": "324",
            "xExact": "325",
            "x": "325",
            "yExact": "0",
            "y": "0",
            "id": "person:1934"
          },
          {
            "series": "0",
            "index": "325",
            "xExact": "326",
            "x": "326",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:1935"
          },
          {
            "series": "1",
            "index": "325",
            "xExact": "326",
            "x": "326",
            "yExact": "0",
            "y": "0",
            "id": "person:1935"
          },
          {
            "series": "0",
            "index": "326",
            "xExact": "327",
            "x": "327",
            "yExact": "179/268",
            "y": "0.667910448",
            "id": "person:1943"
          },
          {
            "series": "1",
            "index": "326",
            "xExact": "327",
            "x": "327",
            "yExact": "0",
            "y": "0",
            "id": "person:1943"
          },
          {
            "series": "0",
            "index": "327",
            "xExact": "328",
            "x": "328",
            "yExact": "179/268",
            "y": "0.667910448",
            "id": "person:1945"
          },
          {
            "series": "1",
            "index": "327",
            "xExact": "328",
            "x": "328",
            "yExact": "1",
            "y": "1",
            "id": "person:1945"
          },
          {
            "series": "0",
            "index": "328",
            "xExact": "329",
            "x": "329",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:1958"
          },
          {
            "series": "1",
            "index": "328",
            "xExact": "329",
            "x": "329",
            "yExact": "0",
            "y": "0",
            "id": "person:1958"
          },
          {
            "series": "0",
            "index": "329",
            "xExact": "330",
            "x": "330",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:1971"
          },
          {
            "series": "1",
            "index": "329",
            "xExact": "330",
            "x": "330",
            "yExact": "0",
            "y": "0",
            "id": "person:1971"
          },
          {
            "series": "0",
            "index": "330",
            "xExact": "331",
            "x": "331",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:1980"
          },
          {
            "series": "1",
            "index": "330",
            "xExact": "331",
            "x": "331",
            "yExact": "0",
            "y": "0",
            "id": "person:1980"
          },
          {
            "series": "0",
            "index": "331",
            "xExact": "332",
            "x": "332",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:1989"
          },
          {
            "series": "1",
            "index": "331",
            "xExact": "332",
            "x": "332",
            "yExact": "1",
            "y": "1",
            "id": "person:1989"
          },
          {
            "series": "0",
            "index": "332",
            "xExact": "333",
            "x": "333",
            "yExact": "179/268",
            "y": "0.667910448",
            "id": "person:1996"
          },
          {
            "series": "1",
            "index": "332",
            "xExact": "333",
            "x": "333",
            "yExact": "1",
            "y": "1",
            "id": "person:1996"
          },
          {
            "series": "0",
            "index": "333",
            "xExact": "334",
            "x": "334",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:1999"
          },
          {
            "series": "1",
            "index": "333",
            "xExact": "334",
            "x": "334",
            "yExact": "0",
            "y": "0",
            "id": "person:1999"
          },
          {
            "series": "0",
            "index": "334",
            "xExact": "335",
            "x": "335",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:2007"
          },
          {
            "series": "1",
            "index": "334",
            "xExact": "335",
            "x": "335",
            "yExact": "0",
            "y": "0",
            "id": "person:2007"
          },
          {
            "series": "0",
            "index": "335",
            "xExact": "336",
            "x": "336",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:2015"
          },
          {
            "series": "1",
            "index": "335",
            "xExact": "336",
            "x": "336",
            "yExact": "0",
            "y": "0",
            "id": "person:2015"
          },
          {
            "series": "0",
            "index": "336",
            "xExact": "337",
            "x": "337",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:2018"
          },
          {
            "series": "1",
            "index": "336",
            "xExact": "337",
            "x": "337",
            "yExact": "0",
            "y": "0",
            "id": "person:2018"
          },
          {
            "series": "0",
            "index": "337",
            "xExact": "338",
            "x": "338",
            "yExact": "179/268",
            "y": "0.667910448",
            "id": "person:2021"
          },
          {
            "series": "1",
            "index": "337",
            "xExact": "338",
            "x": "338",
            "yExact": "0",
            "y": "0",
            "id": "person:2021"
          },
          {
            "series": "0",
            "index": "338",
            "xExact": "339",
            "x": "339",
            "yExact": "197/239",
            "y": "0.824267782",
            "id": "person:2026"
          },
          {
            "series": "1",
            "index": "338",
            "xExact": "339",
            "x": "339",
            "yExact": "1",
            "y": "1",
            "id": "person:2026"
          },
          {
            "series": "0",
            "index": "339",
            "xExact": "340",
            "x": "340",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:2034"
          },
          {
            "series": "1",
            "index": "339",
            "xExact": "340",
            "x": "340",
            "yExact": "0",
            "y": "0",
            "id": "person:2034"
          },
          {
            "series": "0",
            "index": "340",
            "xExact": "341",
            "x": "341",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:2038"
          },
          {
            "series": "1",
            "index": "340",
            "xExact": "341",
            "x": "341",
            "yExact": "1",
            "y": "1",
            "id": "person:2038"
          },
          {
            "series": "0",
            "index": "341",
            "xExact": "342",
            "x": "342",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:2040"
          },
          {
            "series": "1",
            "index": "341",
            "xExact": "342",
            "x": "342",
            "yExact": "0",
            "y": "0",
            "id": "person:2040"
          },
          {
            "series": "0",
            "index": "342",
            "xExact": "343",
            "x": "343",
            "yExact": "197/239",
            "y": "0.824267782",
            "id": "person:2048"
          },
          {
            "series": "1",
            "index": "342",
            "xExact": "343",
            "x": "343",
            "yExact": "1",
            "y": "1",
            "id": "person:2048"
          },
          {
            "series": "0",
            "index": "343",
            "xExact": "344",
            "x": "344",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:2049"
          },
          {
            "series": "1",
            "index": "343",
            "xExact": "344",
            "x": "344",
            "yExact": "0",
            "y": "0",
            "id": "person:2049"
          },
          {
            "series": "0",
            "index": "344",
            "xExact": "345",
            "x": "345",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:2058"
          },
          {
            "series": "1",
            "index": "344",
            "xExact": "345",
            "x": "345",
            "yExact": "1",
            "y": "1",
            "id": "person:2058"
          },
          {
            "series": "0",
            "index": "345",
            "xExact": "346",
            "x": "346",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:2076"
          },
          {
            "series": "1",
            "index": "345",
            "xExact": "346",
            "x": "346",
            "yExact": "0",
            "y": "0",
            "id": "person:2076"
          },
          {
            "series": "0",
            "index": "346",
            "xExact": "347",
            "x": "347",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:2077"
          },
          {
            "series": "1",
            "index": "346",
            "xExact": "347",
            "x": "347",
            "yExact": "0",
            "y": "0",
            "id": "person:2077"
          },
          {
            "series": "0",
            "index": "347",
            "xExact": "348",
            "x": "348",
            "yExact": "12/25",
            "y": "0.48",
            "id": "person:2084"
          },
          {
            "series": "1",
            "index": "347",
            "xExact": "348",
            "x": "348",
            "yExact": "1",
            "y": "1",
            "id": "person:2084"
          },
          {
            "series": "0",
            "index": "348",
            "xExact": "349",
            "x": "349",
            "yExact": "20/41",
            "y": "0.487804878",
            "id": "person:2091"
          },
          {
            "series": "1",
            "index": "348",
            "xExact": "349",
            "x": "349",
            "yExact": "1",
            "y": "1",
            "id": "person:2091"
          },
          {
            "series": "0",
            "index": "349",
            "xExact": "350",
            "x": "350",
            "yExact": "12/25",
            "y": "0.48",
            "id": "person:2100"
          },
          {
            "series": "1",
            "index": "349",
            "xExact": "350",
            "x": "350",
            "yExact": "1",
            "y": "1",
            "id": "person:2100"
          },
          {
            "series": "0",
            "index": "350",
            "xExact": "351",
            "x": "351",
            "yExact": "21/58",
            "y": "0.362068966",
            "id": "person:2103"
          },
          {
            "series": "1",
            "index": "350",
            "xExact": "351",
            "x": "351",
            "yExact": "1",
            "y": "1",
            "id": "person:2103"
          },
          {
            "series": "0",
            "index": "351",
            "xExact": "352",
            "x": "352",
            "yExact": "25/33",
            "y": "0.757575758",
            "id": "person:2106"
          },
          {
            "series": "1",
            "index": "351",
            "xExact": "352",
            "x": "352",
            "yExact": "1",
            "y": "1",
            "id": "person:2106"
          },
          {
            "series": "0",
            "index": "352",
            "xExact": "353",
            "x": "353",
            "yExact": "20/41",
            "y": "0.487804878",
            "id": "person:2110"
          },
          {
            "series": "1",
            "index": "352",
            "xExact": "353",
            "x": "353",
            "yExact": "1",
            "y": "1",
            "id": "person:2110"
          },
          {
            "series": "0",
            "index": "353",
            "xExact": "354",
            "x": "354",
            "yExact": "179/268",
            "y": "0.667910448",
            "id": "person:2127"
          },
          {
            "series": "1",
            "index": "353",
            "xExact": "354",
            "x": "354",
            "yExact": "1",
            "y": "1",
            "id": "person:2127"
          },
          {
            "series": "0",
            "index": "354",
            "xExact": "355",
            "x": "355",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:2132"
          },
          {
            "series": "1",
            "index": "354",
            "xExact": "355",
            "x": "355",
            "yExact": "1",
            "y": "1",
            "id": "person:2132"
          },
          {
            "series": "0",
            "index": "355",
            "xExact": "356",
            "x": "356",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:2135"
          },
          {
            "series": "1",
            "index": "355",
            "xExact": "356",
            "x": "356",
            "yExact": "0",
            "y": "0",
            "id": "person:2135"
          },
          {
            "series": "0",
            "index": "356",
            "xExact": "357",
            "x": "357",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:2138"
          },
          {
            "series": "1",
            "index": "356",
            "xExact": "357",
            "x": "357",
            "yExact": "0",
            "y": "0",
            "id": "person:2138"
          },
          {
            "series": "0",
            "index": "357",
            "xExact": "358",
            "x": "358",
            "yExact": "179/268",
            "y": "0.667910448",
            "id": "person:2143"
          },
          {
            "series": "1",
            "index": "357",
            "xExact": "358",
            "x": "358",
            "yExact": "0",
            "y": "0",
            "id": "person:2143"
          },
          {
            "series": "0",
            "index": "358",
            "xExact": "359",
            "x": "359",
            "yExact": "12/25",
            "y": "0.48",
            "id": "person:2156"
          },
          {
            "series": "1",
            "index": "358",
            "xExact": "359",
            "x": "359",
            "yExact": "0",
            "y": "0",
            "id": "person:2156"
          },
          {
            "series": "0",
            "index": "359",
            "xExact": "360",
            "x": "360",
            "yExact": "12/25",
            "y": "0.48",
            "id": "person:2170"
          },
          {
            "series": "1",
            "index": "359",
            "xExact": "360",
            "x": "360",
            "yExact": "0",
            "y": "0",
            "id": "person:2170"
          },
          {
            "series": "0",
            "index": "360",
            "xExact": "361",
            "x": "361",
            "yExact": "21/58",
            "y": "0.362068966",
            "id": "person:2172"
          },
          {
            "series": "1",
            "index": "360",
            "xExact": "361",
            "x": "361",
            "yExact": "0",
            "y": "0",
            "id": "person:2172"
          },
          {
            "series": "0",
            "index": "361",
            "xExact": "362",
            "x": "362",
            "yExact": "20/41",
            "y": "0.487804878",
            "id": "person:2173"
          },
          {
            "series": "1",
            "index": "361",
            "xExact": "362",
            "x": "362",
            "yExact": "0",
            "y": "0",
            "id": "person:2173"
          },
          {
            "series": "0",
            "index": "362",
            "xExact": "363",
            "x": "363",
            "yExact": "12/25",
            "y": "0.48",
            "id": "person:2182"
          },
          {
            "series": "1",
            "index": "362",
            "xExact": "363",
            "x": "363",
            "yExact": "0",
            "y": "0",
            "id": "person:2182"
          },
          {
            "series": "0",
            "index": "363",
            "xExact": "364",
            "x": "364",
            "yExact": "20/41",
            "y": "0.487804878",
            "id": "person:2194"
          },
          {
            "series": "1",
            "index": "363",
            "xExact": "364",
            "x": "364",
            "yExact": "1",
            "y": "1",
            "id": "person:2194"
          },
          {
            "series": "0",
            "index": "364",
            "xExact": "365",
            "x": "365",
            "yExact": "179/268",
            "y": "0.667910448",
            "id": "person:2199"
          },
          {
            "series": "1",
            "index": "364",
            "xExact": "365",
            "x": "365",
            "yExact": "0",
            "y": "0",
            "id": "person:2199"
          },
          {
            "series": "0",
            "index": "365",
            "xExact": "366",
            "x": "366",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:2201"
          },
          {
            "series": "1",
            "index": "365",
            "xExact": "366",
            "x": "366",
            "yExact": "0",
            "y": "0",
            "id": "person:2201"
          },
          {
            "series": "0",
            "index": "366",
            "xExact": "367",
            "x": "367",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:2203"
          },
          {
            "series": "1",
            "index": "366",
            "xExact": "367",
            "x": "367",
            "yExact": "0",
            "y": "0",
            "id": "person:2203"
          },
          {
            "series": "0",
            "index": "367",
            "xExact": "368",
            "x": "368",
            "yExact": "179/268",
            "y": "0.667910448",
            "id": "person:2214"
          },
          {
            "series": "1",
            "index": "367",
            "xExact": "368",
            "x": "368",
            "yExact": "1",
            "y": "1",
            "id": "person:2214"
          },
          {
            "series": "0",
            "index": "368",
            "xExact": "369",
            "x": "369",
            "yExact": "21/58",
            "y": "0.362068966",
            "id": "person:2216"
          },
          {
            "series": "1",
            "index": "368",
            "xExact": "369",
            "x": "369",
            "yExact": "0",
            "y": "0",
            "id": "person:2216"
          },
          {
            "series": "0",
            "index": "369",
            "xExact": "370",
            "x": "370",
            "yExact": "21/58",
            "y": "0.362068966",
            "id": "person:2224"
          },
          {
            "series": "1",
            "index": "369",
            "xExact": "370",
            "x": "370",
            "yExact": "1",
            "y": "1",
            "id": "person:2224"
          },
          {
            "series": "0",
            "index": "370",
            "xExact": "371",
            "x": "371",
            "yExact": "197/239",
            "y": "0.824267782",
            "id": "person:2235"
          },
          {
            "series": "1",
            "index": "370",
            "xExact": "371",
            "x": "371",
            "yExact": "1",
            "y": "1",
            "id": "person:2235"
          },
          {
            "series": "0",
            "index": "371",
            "xExact": "372",
            "x": "372",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:2237"
          },
          {
            "series": "1",
            "index": "371",
            "xExact": "372",
            "x": "372",
            "yExact": "0",
            "y": "0",
            "id": "person:2237"
          },
          {
            "series": "0",
            "index": "372",
            "xExact": "373",
            "x": "373",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:2243"
          },
          {
            "series": "1",
            "index": "372",
            "xExact": "373",
            "x": "373",
            "yExact": "0",
            "y": "0",
            "id": "person:2243"
          },
          {
            "series": "0",
            "index": "373",
            "xExact": "374",
            "x": "374",
            "yExact": "12/25",
            "y": "0.48",
            "id": "person:2249"
          },
          {
            "series": "1",
            "index": "373",
            "xExact": "374",
            "x": "374",
            "yExact": "1",
            "y": "1",
            "id": "person:2249"
          },
          {
            "series": "0",
            "index": "374",
            "xExact": "375",
            "x": "375",
            "yExact": "21/58",
            "y": "0.362068966",
            "id": "person:2251"
          },
          {
            "series": "1",
            "index": "374",
            "xExact": "375",
            "x": "375",
            "yExact": "0",
            "y": "0",
            "id": "person:2251"
          },
          {
            "series": "0",
            "index": "375",
            "xExact": "376",
            "x": "376",
            "yExact": "25/33",
            "y": "0.757575758",
            "id": "person:2254"
          },
          {
            "series": "1",
            "index": "375",
            "xExact": "376",
            "x": "376",
            "yExact": "1",
            "y": "1",
            "id": "person:2254"
          },
          {
            "series": "0",
            "index": "376",
            "xExact": "377",
            "x": "377",
            "yExact": "179/268",
            "y": "0.667910448",
            "id": "person:2266"
          },
          {
            "series": "1",
            "index": "376",
            "xExact": "377",
            "x": "377",
            "yExact": "1",
            "y": "1",
            "id": "person:2266"
          },
          {
            "series": "0",
            "index": "377",
            "xExact": "378",
            "x": "378",
            "yExact": "179/268",
            "y": "0.667910448",
            "id": "person:2268"
          },
          {
            "series": "1",
            "index": "377",
            "xExact": "378",
            "x": "378",
            "yExact": "0",
            "y": "0",
            "id": "person:2268"
          },
          {
            "series": "0",
            "index": "378",
            "xExact": "379",
            "x": "379",
            "yExact": "179/268",
            "y": "0.667910448",
            "id": "person:2275"
          },
          {
            "series": "1",
            "index": "378",
            "xExact": "379",
            "x": "379",
            "yExact": "1",
            "y": "1",
            "id": "person:2275"
          },
          {
            "series": "0",
            "index": "379",
            "xExact": "380",
            "x": "380",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:2277"
          },
          {
            "series": "1",
            "index": "379",
            "xExact": "380",
            "x": "380",
            "yExact": "0",
            "y": "0",
            "id": "person:2277"
          },
          {
            "series": "0",
            "index": "380",
            "xExact": "381",
            "x": "381",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:2282"
          },
          {
            "series": "1",
            "index": "380",
            "xExact": "381",
            "x": "381",
            "yExact": "0",
            "y": "0",
            "id": "person:2282"
          },
          {
            "series": "0",
            "index": "381",
            "xExact": "382",
            "x": "382",
            "yExact": "179/268",
            "y": "0.667910448",
            "id": "person:2286"
          },
          {
            "series": "1",
            "index": "381",
            "xExact": "382",
            "x": "382",
            "yExact": "0",
            "y": "0",
            "id": "person:2286"
          },
          {
            "series": "0",
            "index": "382",
            "xExact": "383",
            "x": "383",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:2287"
          },
          {
            "series": "1",
            "index": "382",
            "xExact": "383",
            "x": "383",
            "yExact": "1",
            "y": "1",
            "id": "person:2287"
          },
          {
            "series": "0",
            "index": "383",
            "xExact": "384",
            "x": "384",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:2293"
          },
          {
            "series": "1",
            "index": "383",
            "xExact": "384",
            "x": "384",
            "yExact": "0",
            "y": "0",
            "id": "person:2293"
          },
          {
            "series": "0",
            "index": "384",
            "xExact": "385",
            "x": "385",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:2303"
          },
          {
            "series": "1",
            "index": "384",
            "xExact": "385",
            "x": "385",
            "yExact": "0",
            "y": "0",
            "id": "person:2303"
          },
          {
            "series": "0",
            "index": "385",
            "xExact": "386",
            "x": "386",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:2307"
          },
          {
            "series": "1",
            "index": "385",
            "xExact": "386",
            "x": "386",
            "yExact": "1",
            "y": "1",
            "id": "person:2307"
          },
          {
            "series": "0",
            "index": "386",
            "xExact": "387",
            "x": "387",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:2313"
          },
          {
            "series": "1",
            "index": "386",
            "xExact": "387",
            "x": "387",
            "yExact": "0",
            "y": "0",
            "id": "person:2313"
          },
          {
            "series": "0",
            "index": "387",
            "xExact": "388",
            "x": "388",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:2318"
          },
          {
            "series": "1",
            "index": "387",
            "xExact": "388",
            "x": "388",
            "yExact": "0",
            "y": "0",
            "id": "person:2318"
          },
          {
            "series": "0",
            "index": "388",
            "xExact": "389",
            "x": "389",
            "yExact": "179/268",
            "y": "0.667910448",
            "id": "person:2320"
          },
          {
            "series": "1",
            "index": "388",
            "xExact": "389",
            "x": "389",
            "yExact": "0",
            "y": "0",
            "id": "person:2320"
          },
          {
            "series": "0",
            "index": "389",
            "xExact": "390",
            "x": "390",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:2321"
          },
          {
            "series": "1",
            "index": "389",
            "xExact": "390",
            "x": "390",
            "yExact": "0",
            "y": "0",
            "id": "person:2321"
          },
          {
            "series": "0",
            "index": "390",
            "xExact": "391",
            "x": "391",
            "yExact": "179/268",
            "y": "0.667910448",
            "id": "person:2334"
          },
          {
            "series": "1",
            "index": "390",
            "xExact": "391",
            "x": "391",
            "yExact": "1",
            "y": "1",
            "id": "person:2334"
          },
          {
            "series": "0",
            "index": "391",
            "xExact": "392",
            "x": "392",
            "yExact": "179/268",
            "y": "0.667910448",
            "id": "person:2335"
          },
          {
            "series": "1",
            "index": "391",
            "xExact": "392",
            "x": "392",
            "yExact": "1",
            "y": "1",
            "id": "person:2335"
          },
          {
            "series": "0",
            "index": "392",
            "xExact": "393",
            "x": "393",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:2340"
          },
          {
            "series": "1",
            "index": "392",
            "xExact": "393",
            "x": "393",
            "yExact": "0",
            "y": "0",
            "id": "person:2340"
          },
          {
            "series": "0",
            "index": "393",
            "xExact": "394",
            "x": "394",
            "yExact": "179/268",
            "y": "0.667910448",
            "id": "person:2353"
          },
          {
            "series": "1",
            "index": "393",
            "xExact": "394",
            "x": "394",
            "yExact": "0",
            "y": "0",
            "id": "person:2353"
          },
          {
            "series": "0",
            "index": "394",
            "xExact": "395",
            "x": "395",
            "yExact": "197/239",
            "y": "0.824267782",
            "id": "person:2359"
          },
          {
            "series": "1",
            "index": "394",
            "xExact": "395",
            "x": "395",
            "yExact": "1",
            "y": "1",
            "id": "person:2359"
          },
          {
            "series": "0",
            "index": "395",
            "xExact": "396",
            "x": "396",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:2370"
          },
          {
            "series": "1",
            "index": "395",
            "xExact": "396",
            "x": "396",
            "yExact": "0",
            "y": "0",
            "id": "person:2370"
          },
          {
            "series": "0",
            "index": "396",
            "xExact": "397",
            "x": "397",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:2385"
          },
          {
            "series": "1",
            "index": "396",
            "xExact": "397",
            "x": "397",
            "yExact": "0",
            "y": "0",
            "id": "person:2385"
          },
          {
            "series": "0",
            "index": "397",
            "xExact": "398",
            "x": "398",
            "yExact": "25/33",
            "y": "0.757575758",
            "id": "person:2392"
          },
          {
            "series": "1",
            "index": "397",
            "xExact": "398",
            "x": "398",
            "yExact": "1",
            "y": "1",
            "id": "person:2392"
          },
          {
            "series": "0",
            "index": "398",
            "xExact": "399",
            "x": "399",
            "yExact": "21/58",
            "y": "0.362068966",
            "id": "person:2395"
          },
          {
            "series": "1",
            "index": "398",
            "xExact": "399",
            "x": "399",
            "yExact": "0",
            "y": "0",
            "id": "person:2395"
          },
          {
            "series": "0",
            "index": "399",
            "xExact": "400",
            "x": "400",
            "yExact": "12/25",
            "y": "0.48",
            "id": "person:2397"
          },
          {
            "series": "1",
            "index": "399",
            "xExact": "400",
            "x": "400",
            "yExact": "1",
            "y": "1",
            "id": "person:2397"
          },
          {
            "series": "0",
            "index": "400",
            "xExact": "401",
            "x": "401",
            "yExact": "179/268",
            "y": "0.667910448",
            "id": "person:2400"
          },
          {
            "series": "1",
            "index": "400",
            "xExact": "401",
            "x": "401",
            "yExact": "1",
            "y": "1",
            "id": "person:2400"
          },
          {
            "series": "0",
            "index": "401",
            "xExact": "402",
            "x": "402",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:2409"
          },
          {
            "series": "1",
            "index": "401",
            "xExact": "402",
            "x": "402",
            "yExact": "1",
            "y": "1",
            "id": "person:2409"
          },
          {
            "series": "0",
            "index": "402",
            "xExact": "403",
            "x": "403",
            "yExact": "179/268",
            "y": "0.667910448",
            "id": "person:2412"
          },
          {
            "series": "1",
            "index": "402",
            "xExact": "403",
            "x": "403",
            "yExact": "0",
            "y": "0",
            "id": "person:2412"
          },
          {
            "series": "0",
            "index": "403",
            "xExact": "404",
            "x": "404",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:2416"
          },
          {
            "series": "1",
            "index": "403",
            "xExact": "404",
            "x": "404",
            "yExact": "0",
            "y": "0",
            "id": "person:2416"
          },
          {
            "series": "0",
            "index": "404",
            "xExact": "405",
            "x": "405",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:2423"
          },
          {
            "series": "1",
            "index": "404",
            "xExact": "405",
            "x": "405",
            "yExact": "0",
            "y": "0",
            "id": "person:2423"
          },
          {
            "series": "0",
            "index": "405",
            "xExact": "406",
            "x": "406",
            "yExact": "20/41",
            "y": "0.487804878",
            "id": "person:2447"
          },
          {
            "series": "1",
            "index": "405",
            "xExact": "406",
            "x": "406",
            "yExact": "1",
            "y": "1",
            "id": "person:2447"
          },
          {
            "series": "0",
            "index": "406",
            "xExact": "407",
            "x": "407",
            "yExact": "25/33",
            "y": "0.757575758",
            "id": "person:2451"
          },
          {
            "series": "1",
            "index": "406",
            "xExact": "407",
            "x": "407",
            "yExact": "1",
            "y": "1",
            "id": "person:2451"
          },
          {
            "series": "0",
            "index": "407",
            "xExact": "408",
            "x": "408",
            "yExact": "20/41",
            "y": "0.487804878",
            "id": "person:2454"
          },
          {
            "series": "1",
            "index": "407",
            "xExact": "408",
            "x": "408",
            "yExact": "1",
            "y": "1",
            "id": "person:2454"
          },
          {
            "series": "0",
            "index": "408",
            "xExact": "409",
            "x": "409",
            "yExact": "12/25",
            "y": "0.48",
            "id": "person:2459"
          },
          {
            "series": "1",
            "index": "408",
            "xExact": "409",
            "x": "409",
            "yExact": "1",
            "y": "1",
            "id": "person:2459"
          },
          {
            "series": "0",
            "index": "409",
            "xExact": "410",
            "x": "410",
            "yExact": "12/25",
            "y": "0.48",
            "id": "person:2460"
          },
          {
            "series": "1",
            "index": "409",
            "xExact": "410",
            "x": "410",
            "yExact": "0",
            "y": "0",
            "id": "person:2460"
          },
          {
            "series": "0",
            "index": "410",
            "xExact": "411",
            "x": "411",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:2467"
          },
          {
            "series": "1",
            "index": "410",
            "xExact": "411",
            "x": "411",
            "yExact": "1",
            "y": "1",
            "id": "person:2467"
          },
          {
            "series": "0",
            "index": "411",
            "xExact": "412",
            "x": "412",
            "yExact": "197/239",
            "y": "0.824267782",
            "id": "person:2470"
          },
          {
            "series": "1",
            "index": "411",
            "xExact": "412",
            "x": "412",
            "yExact": "1",
            "y": "1",
            "id": "person:2470"
          },
          {
            "series": "0",
            "index": "412",
            "xExact": "413",
            "x": "413",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:2502"
          },
          {
            "series": "1",
            "index": "412",
            "xExact": "413",
            "x": "413",
            "yExact": "0",
            "y": "0",
            "id": "person:2502"
          },
          {
            "series": "0",
            "index": "413",
            "xExact": "414",
            "x": "414",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:2504"
          },
          {
            "series": "1",
            "index": "413",
            "xExact": "414",
            "x": "414",
            "yExact": "0",
            "y": "0",
            "id": "person:2504"
          },
          {
            "series": "0",
            "index": "414",
            "xExact": "415",
            "x": "415",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:2512"
          },
          {
            "series": "1",
            "index": "414",
            "xExact": "415",
            "x": "415",
            "yExact": "0",
            "y": "0",
            "id": "person:2512"
          },
          {
            "series": "0",
            "index": "415",
            "xExact": "416",
            "x": "416",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:2517"
          },
          {
            "series": "1",
            "index": "415",
            "xExact": "416",
            "x": "416",
            "yExact": "1",
            "y": "1",
            "id": "person:2517"
          },
          {
            "series": "0",
            "index": "416",
            "xExact": "417",
            "x": "417",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:2521"
          },
          {
            "series": "1",
            "index": "416",
            "xExact": "417",
            "x": "417",
            "yExact": "0",
            "y": "0",
            "id": "person:2521"
          },
          {
            "series": "0",
            "index": "417",
            "xExact": "418",
            "x": "418",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:2531"
          },
          {
            "series": "1",
            "index": "417",
            "xExact": "418",
            "x": "418",
            "yExact": "1",
            "y": "1",
            "id": "person:2531"
          },
          {
            "series": "0",
            "index": "418",
            "xExact": "419",
            "x": "419",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:2533"
          },
          {
            "series": "1",
            "index": "418",
            "xExact": "419",
            "x": "419",
            "yExact": "1",
            "y": "1",
            "id": "person:2533"
          },
          {
            "series": "0",
            "index": "419",
            "xExact": "420",
            "x": "420",
            "yExact": "197/239",
            "y": "0.824267782",
            "id": "person:2537"
          },
          {
            "series": "1",
            "index": "419",
            "xExact": "420",
            "x": "420",
            "yExact": "1",
            "y": "1",
            "id": "person:2537"
          },
          {
            "series": "0",
            "index": "420",
            "xExact": "421",
            "x": "421",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:2543"
          },
          {
            "series": "1",
            "index": "420",
            "xExact": "421",
            "x": "421",
            "yExact": "1",
            "y": "1",
            "id": "person:2543"
          },
          {
            "series": "0",
            "index": "421",
            "xExact": "422",
            "x": "422",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:2544"
          },
          {
            "series": "1",
            "index": "421",
            "xExact": "422",
            "x": "422",
            "yExact": "1",
            "y": "1",
            "id": "person:2544"
          },
          {
            "series": "0",
            "index": "422",
            "xExact": "423",
            "x": "423",
            "yExact": "197/239",
            "y": "0.824267782",
            "id": "person:2546"
          },
          {
            "series": "1",
            "index": "422",
            "xExact": "423",
            "x": "423",
            "yExact": "1",
            "y": "1",
            "id": "person:2546"
          },
          {
            "series": "0",
            "index": "423",
            "xExact": "424",
            "x": "424",
            "yExact": "197/239",
            "y": "0.824267782",
            "id": "person:2550"
          },
          {
            "series": "1",
            "index": "423",
            "xExact": "424",
            "x": "424",
            "yExact": "1",
            "y": "1",
            "id": "person:2550"
          },
          {
            "series": "0",
            "index": "424",
            "xExact": "425",
            "x": "425",
            "yExact": "197/239",
            "y": "0.824267782",
            "id": "person:2555"
          },
          {
            "series": "1",
            "index": "424",
            "xExact": "425",
            "x": "425",
            "yExact": "1",
            "y": "1",
            "id": "person:2555"
          },
          {
            "series": "0",
            "index": "425",
            "xExact": "426",
            "x": "426",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:2563"
          },
          {
            "series": "1",
            "index": "425",
            "xExact": "426",
            "x": "426",
            "yExact": "1",
            "y": "1",
            "id": "person:2563"
          },
          {
            "series": "0",
            "index": "426",
            "xExact": "427",
            "x": "427",
            "yExact": "179/268",
            "y": "0.667910448",
            "id": "person:2564"
          },
          {
            "series": "1",
            "index": "426",
            "xExact": "427",
            "x": "427",
            "yExact": "1",
            "y": "1",
            "id": "person:2564"
          },
          {
            "series": "0",
            "index": "427",
            "xExact": "428",
            "x": "428",
            "yExact": "179/268",
            "y": "0.667910448",
            "id": "person:2568"
          },
          {
            "series": "1",
            "index": "427",
            "xExact": "428",
            "x": "428",
            "yExact": "1",
            "y": "1",
            "id": "person:2568"
          },
          {
            "series": "0",
            "index": "428",
            "xExact": "429",
            "x": "429",
            "yExact": "197/239",
            "y": "0.824267782",
            "id": "person:2575"
          },
          {
            "series": "1",
            "index": "428",
            "xExact": "429",
            "x": "429",
            "yExact": "0",
            "y": "0",
            "id": "person:2575"
          },
          {
            "series": "0",
            "index": "429",
            "xExact": "430",
            "x": "430",
            "yExact": "179/268",
            "y": "0.667910448",
            "id": "person:2580"
          },
          {
            "series": "1",
            "index": "429",
            "xExact": "430",
            "x": "430",
            "yExact": "1",
            "y": "1",
            "id": "person:2580"
          },
          {
            "series": "0",
            "index": "430",
            "xExact": "431",
            "x": "431",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:2582"
          },
          {
            "series": "1",
            "index": "430",
            "xExact": "431",
            "x": "431",
            "yExact": "0",
            "y": "0",
            "id": "person:2582"
          },
          {
            "series": "0",
            "index": "431",
            "xExact": "432",
            "x": "432",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:2585"
          },
          {
            "series": "1",
            "index": "431",
            "xExact": "432",
            "x": "432",
            "yExact": "1",
            "y": "1",
            "id": "person:2585"
          },
          {
            "series": "0",
            "index": "432",
            "xExact": "433",
            "x": "433",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:2589"
          },
          {
            "series": "1",
            "index": "432",
            "xExact": "433",
            "x": "433",
            "yExact": "0",
            "y": "0",
            "id": "person:2589"
          },
          {
            "series": "0",
            "index": "433",
            "xExact": "434",
            "x": "434",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:2600"
          },
          {
            "series": "1",
            "index": "433",
            "xExact": "434",
            "x": "434",
            "yExact": "1",
            "y": "1",
            "id": "person:2600"
          },
          {
            "series": "0",
            "index": "434",
            "xExact": "435",
            "x": "435",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:2605"
          },
          {
            "series": "1",
            "index": "434",
            "xExact": "435",
            "x": "435",
            "yExact": "0",
            "y": "0",
            "id": "person:2605"
          },
          {
            "series": "0",
            "index": "435",
            "xExact": "436",
            "x": "436",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:2608"
          },
          {
            "series": "1",
            "index": "435",
            "xExact": "436",
            "x": "436",
            "yExact": "1",
            "y": "1",
            "id": "person:2608"
          },
          {
            "series": "0",
            "index": "436",
            "xExact": "437",
            "x": "437",
            "yExact": "197/239",
            "y": "0.824267782",
            "id": "person:2614"
          },
          {
            "series": "1",
            "index": "436",
            "xExact": "437",
            "x": "437",
            "yExact": "1",
            "y": "1",
            "id": "person:2614"
          },
          {
            "series": "0",
            "index": "437",
            "xExact": "438",
            "x": "438",
            "yExact": "197/239",
            "y": "0.824267782",
            "id": "person:2619"
          },
          {
            "series": "1",
            "index": "437",
            "xExact": "438",
            "x": "438",
            "yExact": "1",
            "y": "1",
            "id": "person:2619"
          },
          {
            "series": "0",
            "index": "438",
            "xExact": "439",
            "x": "439",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:2628"
          },
          {
            "series": "1",
            "index": "438",
            "xExact": "439",
            "x": "439",
            "yExact": "0",
            "y": "0",
            "id": "person:2628"
          },
          {
            "series": "0",
            "index": "439",
            "xExact": "440",
            "x": "440",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:2642"
          },
          {
            "series": "1",
            "index": "439",
            "xExact": "440",
            "x": "440",
            "yExact": "0",
            "y": "0",
            "id": "person:2642"
          },
          {
            "series": "0",
            "index": "440",
            "xExact": "441",
            "x": "441",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:2650"
          },
          {
            "series": "1",
            "index": "440",
            "xExact": "441",
            "x": "441",
            "yExact": "0",
            "y": "0",
            "id": "person:2650"
          },
          {
            "series": "0",
            "index": "441",
            "xExact": "442",
            "x": "442",
            "yExact": "197/239",
            "y": "0.824267782",
            "id": "person:2655"
          },
          {
            "series": "1",
            "index": "441",
            "xExact": "442",
            "x": "442",
            "yExact": "1",
            "y": "1",
            "id": "person:2655"
          },
          {
            "series": "0",
            "index": "442",
            "xExact": "443",
            "x": "443",
            "yExact": "197/239",
            "y": "0.824267782",
            "id": "person:2656"
          },
          {
            "series": "1",
            "index": "442",
            "xExact": "443",
            "x": "443",
            "yExact": "1",
            "y": "1",
            "id": "person:2656"
          },
          {
            "series": "0",
            "index": "443",
            "xExact": "444",
            "x": "444",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:2661"
          },
          {
            "series": "1",
            "index": "443",
            "xExact": "444",
            "x": "444",
            "yExact": "0",
            "y": "0",
            "id": "person:2661"
          },
          {
            "series": "0",
            "index": "444",
            "xExact": "445",
            "x": "445",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:2663"
          },
          {
            "series": "1",
            "index": "444",
            "xExact": "445",
            "x": "445",
            "yExact": "0",
            "y": "0",
            "id": "person:2663"
          },
          {
            "series": "0",
            "index": "445",
            "xExact": "446",
            "x": "446",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:2671"
          },
          {
            "series": "1",
            "index": "445",
            "xExact": "446",
            "x": "446",
            "yExact": "1",
            "y": "1",
            "id": "person:2671"
          },
          {
            "series": "0",
            "index": "446",
            "xExact": "447",
            "x": "447",
            "yExact": "197/239",
            "y": "0.824267782",
            "id": "person:2676"
          },
          {
            "series": "1",
            "index": "446",
            "xExact": "447",
            "x": "447",
            "yExact": "0",
            "y": "0",
            "id": "person:2676"
          },
          {
            "series": "0",
            "index": "447",
            "xExact": "448",
            "x": "448",
            "yExact": "197/239",
            "y": "0.824267782",
            "id": "person:2693"
          },
          {
            "series": "1",
            "index": "447",
            "xExact": "448",
            "x": "448",
            "yExact": "1",
            "y": "1",
            "id": "person:2693"
          },
          {
            "series": "0",
            "index": "448",
            "xExact": "449",
            "x": "449",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:2696"
          },
          {
            "series": "1",
            "index": "448",
            "xExact": "449",
            "x": "449",
            "yExact": "1",
            "y": "1",
            "id": "person:2696"
          },
          {
            "series": "0",
            "index": "449",
            "xExact": "450",
            "x": "450",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:2703"
          },
          {
            "series": "1",
            "index": "449",
            "xExact": "450",
            "x": "450",
            "yExact": "1",
            "y": "1",
            "id": "person:2703"
          },
          {
            "series": "0",
            "index": "450",
            "xExact": "451",
            "x": "451",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:2707"
          },
          {
            "series": "1",
            "index": "450",
            "xExact": "451",
            "x": "451",
            "yExact": "1",
            "y": "1",
            "id": "person:2707"
          },
          {
            "series": "0",
            "index": "451",
            "xExact": "452",
            "x": "452",
            "yExact": "179/268",
            "y": "0.667910448",
            "id": "person:2734"
          },
          {
            "series": "1",
            "index": "451",
            "xExact": "452",
            "x": "452",
            "yExact": "1",
            "y": "1",
            "id": "person:2734"
          },
          {
            "series": "0",
            "index": "452",
            "xExact": "453",
            "x": "453",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:2737"
          },
          {
            "series": "1",
            "index": "452",
            "xExact": "453",
            "x": "453",
            "yExact": "1",
            "y": "1",
            "id": "person:2737"
          },
          {
            "series": "0",
            "index": "453",
            "xExact": "454",
            "x": "454",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:2745"
          },
          {
            "series": "1",
            "index": "453",
            "xExact": "454",
            "x": "454",
            "yExact": "1",
            "y": "1",
            "id": "person:2745"
          },
          {
            "series": "0",
            "index": "454",
            "xExact": "455",
            "x": "455",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:2747"
          },
          {
            "series": "1",
            "index": "454",
            "xExact": "455",
            "x": "455",
            "yExact": "1",
            "y": "1",
            "id": "person:2747"
          },
          {
            "series": "0",
            "index": "455",
            "xExact": "456",
            "x": "456",
            "yExact": "197/239",
            "y": "0.824267782",
            "id": "person:2750"
          },
          {
            "series": "1",
            "index": "455",
            "xExact": "456",
            "x": "456",
            "yExact": "1",
            "y": "1",
            "id": "person:2750"
          },
          {
            "series": "0",
            "index": "456",
            "xExact": "457",
            "x": "457",
            "yExact": "197/239",
            "y": "0.824267782",
            "id": "person:2752"
          },
          {
            "series": "1",
            "index": "456",
            "xExact": "457",
            "x": "457",
            "yExact": "1",
            "y": "1",
            "id": "person:2752"
          },
          {
            "series": "0",
            "index": "457",
            "xExact": "458",
            "x": "458",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:2755"
          },
          {
            "series": "1",
            "index": "457",
            "xExact": "458",
            "x": "458",
            "yExact": "0",
            "y": "0",
            "id": "person:2755"
          },
          {
            "series": "0",
            "index": "458",
            "xExact": "459",
            "x": "459",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:2756"
          },
          {
            "series": "1",
            "index": "458",
            "xExact": "459",
            "x": "459",
            "yExact": "0",
            "y": "0",
            "id": "person:2756"
          },
          {
            "series": "0",
            "index": "459",
            "xExact": "460",
            "x": "460",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:2758"
          },
          {
            "series": "1",
            "index": "459",
            "xExact": "460",
            "x": "460",
            "yExact": "1",
            "y": "1",
            "id": "person:2758"
          },
          {
            "series": "0",
            "index": "460",
            "xExact": "461",
            "x": "461",
            "yExact": "179/268",
            "y": "0.667910448",
            "id": "person:2759"
          },
          {
            "series": "1",
            "index": "460",
            "xExact": "461",
            "x": "461",
            "yExact": "0",
            "y": "0",
            "id": "person:2759"
          },
          {
            "series": "0",
            "index": "461",
            "xExact": "462",
            "x": "462",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:2771"
          },
          {
            "series": "1",
            "index": "461",
            "xExact": "462",
            "x": "462",
            "yExact": "1",
            "y": "1",
            "id": "person:2771"
          },
          {
            "series": "0",
            "index": "462",
            "xExact": "463",
            "x": "463",
            "yExact": "179/268",
            "y": "0.667910448",
            "id": "person:2773"
          },
          {
            "series": "1",
            "index": "462",
            "xExact": "463",
            "x": "463",
            "yExact": "1",
            "y": "1",
            "id": "person:2773"
          },
          {
            "series": "0",
            "index": "463",
            "xExact": "464",
            "x": "464",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:2778"
          },
          {
            "series": "1",
            "index": "463",
            "xExact": "464",
            "x": "464",
            "yExact": "1",
            "y": "1",
            "id": "person:2778"
          },
          {
            "series": "0",
            "index": "464",
            "xExact": "465",
            "x": "465",
            "yExact": "21/58",
            "y": "0.362068966",
            "id": "person:2792"
          },
          {
            "series": "1",
            "index": "464",
            "xExact": "465",
            "x": "465",
            "yExact": "1",
            "y": "1",
            "id": "person:2792"
          },
          {
            "series": "0",
            "index": "465",
            "xExact": "466",
            "x": "466",
            "yExact": "20/41",
            "y": "0.487804878",
            "id": "person:2793"
          },
          {
            "series": "1",
            "index": "465",
            "xExact": "466",
            "x": "466",
            "yExact": "0",
            "y": "0",
            "id": "person:2793"
          },
          {
            "series": "0",
            "index": "466",
            "xExact": "467",
            "x": "467",
            "yExact": "25/33",
            "y": "0.757575758",
            "id": "person:2794"
          },
          {
            "series": "1",
            "index": "466",
            "xExact": "467",
            "x": "467",
            "yExact": "1",
            "y": "1",
            "id": "person:2794"
          },
          {
            "series": "0",
            "index": "467",
            "xExact": "468",
            "x": "468",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:2798"
          },
          {
            "series": "1",
            "index": "467",
            "xExact": "468",
            "x": "468",
            "yExact": "1",
            "y": "1",
            "id": "person:2798"
          },
          {
            "series": "0",
            "index": "468",
            "xExact": "469",
            "x": "469",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:2802"
          },
          {
            "series": "1",
            "index": "468",
            "xExact": "469",
            "x": "469",
            "yExact": "1",
            "y": "1",
            "id": "person:2802"
          },
          {
            "series": "0",
            "index": "469",
            "xExact": "470",
            "x": "470",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:2821"
          },
          {
            "series": "1",
            "index": "469",
            "xExact": "470",
            "x": "470",
            "yExact": "0",
            "y": "0",
            "id": "person:2821"
          },
          {
            "series": "0",
            "index": "470",
            "xExact": "471",
            "x": "471",
            "yExact": "179/268",
            "y": "0.667910448",
            "id": "person:2835"
          },
          {
            "series": "1",
            "index": "470",
            "xExact": "471",
            "x": "471",
            "yExact": "1",
            "y": "1",
            "id": "person:2835"
          },
          {
            "series": "0",
            "index": "471",
            "xExact": "472",
            "x": "472",
            "yExact": "20/41",
            "y": "0.487804878",
            "id": "person:2850"
          },
          {
            "series": "1",
            "index": "471",
            "xExact": "472",
            "x": "472",
            "yExact": "1",
            "y": "1",
            "id": "person:2850"
          },
          {
            "series": "0",
            "index": "472",
            "xExact": "473",
            "x": "473",
            "yExact": "25/33",
            "y": "0.757575758",
            "id": "person:2851"
          },
          {
            "series": "1",
            "index": "472",
            "xExact": "473",
            "x": "473",
            "yExact": "1",
            "y": "1",
            "id": "person:2851"
          },
          {
            "series": "0",
            "index": "473",
            "xExact": "474",
            "x": "474",
            "yExact": "12/25",
            "y": "0.48",
            "id": "person:2859"
          },
          {
            "series": "1",
            "index": "473",
            "xExact": "474",
            "x": "474",
            "yExact": "1",
            "y": "1",
            "id": "person:2859"
          },
          {
            "series": "0",
            "index": "474",
            "xExact": "475",
            "x": "475",
            "yExact": "25/33",
            "y": "0.757575758",
            "id": "person:2863"
          },
          {
            "series": "1",
            "index": "474",
            "xExact": "475",
            "x": "475",
            "yExact": "1",
            "y": "1",
            "id": "person:2863"
          },
          {
            "series": "0",
            "index": "475",
            "xExact": "476",
            "x": "476",
            "yExact": "25/33",
            "y": "0.757575758",
            "id": "person:2865"
          },
          {
            "series": "1",
            "index": "475",
            "xExact": "476",
            "x": "476",
            "yExact": "1",
            "y": "1",
            "id": "person:2865"
          },
          {
            "series": "0",
            "index": "476",
            "xExact": "477",
            "x": "477",
            "yExact": "20/41",
            "y": "0.487804878",
            "id": "person:2868"
          },
          {
            "series": "1",
            "index": "476",
            "xExact": "477",
            "x": "477",
            "yExact": "1",
            "y": "1",
            "id": "person:2868"
          },
          {
            "series": "0",
            "index": "477",
            "xExact": "478",
            "x": "478",
            "yExact": "12/25",
            "y": "0.48",
            "id": "person:2887"
          },
          {
            "series": "1",
            "index": "477",
            "xExact": "478",
            "x": "478",
            "yExact": "0",
            "y": "0",
            "id": "person:2887"
          },
          {
            "series": "0",
            "index": "478",
            "xExact": "479",
            "x": "479",
            "yExact": "25/33",
            "y": "0.757575758",
            "id": "person:2894"
          },
          {
            "series": "1",
            "index": "478",
            "xExact": "479",
            "x": "479",
            "yExact": "1",
            "y": "1",
            "id": "person:2894"
          },
          {
            "series": "0",
            "index": "479",
            "xExact": "480",
            "x": "480",
            "yExact": "12/25",
            "y": "0.48",
            "id": "person:2897"
          },
          {
            "series": "1",
            "index": "479",
            "xExact": "480",
            "x": "480",
            "yExact": "0",
            "y": "0",
            "id": "person:2897"
          },
          {
            "series": "0",
            "index": "480",
            "xExact": "481",
            "x": "481",
            "yExact": "20/41",
            "y": "0.487804878",
            "id": "person:2902"
          },
          {
            "series": "1",
            "index": "480",
            "xExact": "481",
            "x": "481",
            "yExact": "0",
            "y": "0",
            "id": "person:2902"
          },
          {
            "series": "0",
            "index": "481",
            "xExact": "482",
            "x": "482",
            "yExact": "20/41",
            "y": "0.487804878",
            "id": "person:2909"
          },
          {
            "series": "1",
            "index": "481",
            "xExact": "482",
            "x": "482",
            "yExact": "1",
            "y": "1",
            "id": "person:2909"
          },
          {
            "series": "0",
            "index": "482",
            "xExact": "483",
            "x": "483",
            "yExact": "21/58",
            "y": "0.362068966",
            "id": "person:2910"
          },
          {
            "series": "1",
            "index": "482",
            "xExact": "483",
            "x": "483",
            "yExact": "1",
            "y": "1",
            "id": "person:2910"
          },
          {
            "series": "0",
            "index": "483",
            "xExact": "484",
            "x": "484",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:2925"
          },
          {
            "series": "1",
            "index": "483",
            "xExact": "484",
            "x": "484",
            "yExact": "0",
            "y": "0",
            "id": "person:2925"
          },
          {
            "series": "0",
            "index": "484",
            "xExact": "485",
            "x": "485",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:2928"
          },
          {
            "series": "1",
            "index": "484",
            "xExact": "485",
            "x": "485",
            "yExact": "1",
            "y": "1",
            "id": "person:2928"
          },
          {
            "series": "0",
            "index": "485",
            "xExact": "486",
            "x": "486",
            "yExact": "179/268",
            "y": "0.667910448",
            "id": "person:2930"
          },
          {
            "series": "1",
            "index": "485",
            "xExact": "486",
            "x": "486",
            "yExact": "1",
            "y": "1",
            "id": "person:2930"
          },
          {
            "series": "0",
            "index": "486",
            "xExact": "487",
            "x": "487",
            "yExact": "197/239",
            "y": "0.824267782",
            "id": "person:2941"
          },
          {
            "series": "1",
            "index": "486",
            "xExact": "487",
            "x": "487",
            "yExact": "1",
            "y": "1",
            "id": "person:2941"
          },
          {
            "series": "0",
            "index": "487",
            "xExact": "488",
            "x": "488",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:2942"
          },
          {
            "series": "1",
            "index": "487",
            "xExact": "488",
            "x": "488",
            "yExact": "1",
            "y": "1",
            "id": "person:2942"
          },
          {
            "series": "0",
            "index": "488",
            "xExact": "489",
            "x": "489",
            "yExact": "179/268",
            "y": "0.667910448",
            "id": "person:2947"
          },
          {
            "series": "1",
            "index": "488",
            "xExact": "489",
            "x": "489",
            "yExact": "1",
            "y": "1",
            "id": "person:2947"
          },
          {
            "series": "0",
            "index": "489",
            "xExact": "490",
            "x": "490",
            "yExact": "179/268",
            "y": "0.667910448",
            "id": "person:2948"
          },
          {
            "series": "1",
            "index": "489",
            "xExact": "490",
            "x": "490",
            "yExact": "1",
            "y": "1",
            "id": "person:2948"
          },
          {
            "series": "0",
            "index": "490",
            "xExact": "491",
            "x": "491",
            "yExact": "197/239",
            "y": "0.824267782",
            "id": "person:2951"
          },
          {
            "series": "1",
            "index": "490",
            "xExact": "491",
            "x": "491",
            "yExact": "1",
            "y": "1",
            "id": "person:2951"
          },
          {
            "series": "0",
            "index": "491",
            "xExact": "492",
            "x": "492",
            "yExact": "20/41",
            "y": "0.487804878",
            "id": "person:2955"
          },
          {
            "series": "1",
            "index": "491",
            "xExact": "492",
            "x": "492",
            "yExact": "0",
            "y": "0",
            "id": "person:2955"
          },
          {
            "series": "0",
            "index": "492",
            "xExact": "493",
            "x": "493",
            "yExact": "20/41",
            "y": "0.487804878",
            "id": "person:2956"
          },
          {
            "series": "1",
            "index": "492",
            "xExact": "493",
            "x": "493",
            "yExact": "1",
            "y": "1",
            "id": "person:2956"
          },
          {
            "series": "0",
            "index": "493",
            "xExact": "494",
            "x": "494",
            "yExact": "21/58",
            "y": "0.362068966",
            "id": "person:2957"
          },
          {
            "series": "1",
            "index": "493",
            "xExact": "494",
            "x": "494",
            "yExact": "1",
            "y": "1",
            "id": "person:2957"
          },
          {
            "series": "0",
            "index": "494",
            "xExact": "495",
            "x": "495",
            "yExact": "21/58",
            "y": "0.362068966",
            "id": "person:2959"
          },
          {
            "series": "1",
            "index": "494",
            "xExact": "495",
            "x": "495",
            "yExact": "0",
            "y": "0",
            "id": "person:2959"
          },
          {
            "series": "0",
            "index": "495",
            "xExact": "496",
            "x": "496",
            "yExact": "21/58",
            "y": "0.362068966",
            "id": "person:2962"
          },
          {
            "series": "1",
            "index": "495",
            "xExact": "496",
            "x": "496",
            "yExact": "0",
            "y": "0",
            "id": "person:2962"
          },
          {
            "series": "0",
            "index": "496",
            "xExact": "497",
            "x": "497",
            "yExact": "21/58",
            "y": "0.362068966",
            "id": "person:2974"
          },
          {
            "series": "1",
            "index": "496",
            "xExact": "497",
            "x": "497",
            "yExact": "0",
            "y": "0",
            "id": "person:2974"
          },
          {
            "series": "0",
            "index": "497",
            "xExact": "498",
            "x": "498",
            "yExact": "25/33",
            "y": "0.757575758",
            "id": "person:2980"
          },
          {
            "series": "1",
            "index": "497",
            "xExact": "498",
            "x": "498",
            "yExact": "1",
            "y": "1",
            "id": "person:2980"
          },
          {
            "series": "0",
            "index": "498",
            "xExact": "499",
            "x": "499",
            "yExact": "21/58",
            "y": "0.362068966",
            "id": "person:2981"
          },
          {
            "series": "1",
            "index": "498",
            "xExact": "499",
            "x": "499",
            "yExact": "0",
            "y": "0",
            "id": "person:2981"
          },
          {
            "series": "0",
            "index": "499",
            "xExact": "500",
            "x": "500",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:2994"
          },
          {
            "series": "1",
            "index": "499",
            "xExact": "500",
            "x": "500",
            "yExact": "1",
            "y": "1",
            "id": "person:2994"
          },
          {
            "series": "0",
            "index": "500",
            "xExact": "501",
            "x": "501",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:2998"
          },
          {
            "series": "1",
            "index": "500",
            "xExact": "501",
            "x": "501",
            "yExact": "0",
            "y": "0",
            "id": "person:2998"
          },
          {
            "series": "0",
            "index": "501",
            "xExact": "502",
            "x": "502",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:3009"
          },
          {
            "series": "1",
            "index": "501",
            "xExact": "502",
            "x": "502",
            "yExact": "0",
            "y": "0",
            "id": "person:3009"
          },
          {
            "series": "0",
            "index": "502",
            "xExact": "503",
            "x": "503",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:3018"
          },
          {
            "series": "1",
            "index": "502",
            "xExact": "503",
            "x": "503",
            "yExact": "0",
            "y": "0",
            "id": "person:3018"
          },
          {
            "series": "0",
            "index": "503",
            "xExact": "504",
            "x": "504",
            "yExact": "179/268",
            "y": "0.667910448",
            "id": "person:3019"
          },
          {
            "series": "1",
            "index": "503",
            "xExact": "504",
            "x": "504",
            "yExact": "0",
            "y": "0",
            "id": "person:3019"
          },
          {
            "series": "0",
            "index": "504",
            "xExact": "505",
            "x": "505",
            "yExact": "25/33",
            "y": "0.757575758",
            "id": "person:3027"
          },
          {
            "series": "1",
            "index": "504",
            "xExact": "505",
            "x": "505",
            "yExact": "1",
            "y": "1",
            "id": "person:3027"
          },
          {
            "series": "0",
            "index": "505",
            "xExact": "506",
            "x": "506",
            "yExact": "21/58",
            "y": "0.362068966",
            "id": "person:3044"
          },
          {
            "series": "1",
            "index": "505",
            "xExact": "506",
            "x": "506",
            "yExact": "0",
            "y": "0",
            "id": "person:3044"
          },
          {
            "series": "0",
            "index": "506",
            "xExact": "507",
            "x": "507",
            "yExact": "21/58",
            "y": "0.362068966",
            "id": "person:3050"
          },
          {
            "series": "1",
            "index": "506",
            "xExact": "507",
            "x": "507",
            "yExact": "1",
            "y": "1",
            "id": "person:3050"
          },
          {
            "series": "0",
            "index": "507",
            "xExact": "508",
            "x": "508",
            "yExact": "21/58",
            "y": "0.362068966",
            "id": "person:3051"
          },
          {
            "series": "1",
            "index": "507",
            "xExact": "508",
            "x": "508",
            "yExact": "0",
            "y": "0",
            "id": "person:3051"
          },
          {
            "series": "0",
            "index": "508",
            "xExact": "509",
            "x": "509",
            "yExact": "21/58",
            "y": "0.362068966",
            "id": "person:3052"
          },
          {
            "series": "1",
            "index": "508",
            "xExact": "509",
            "x": "509",
            "yExact": "0",
            "y": "0",
            "id": "person:3052"
          },
          {
            "series": "0",
            "index": "509",
            "xExact": "510",
            "x": "510",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:3061"
          },
          {
            "series": "1",
            "index": "509",
            "xExact": "510",
            "x": "510",
            "yExact": "1",
            "y": "1",
            "id": "person:3061"
          },
          {
            "series": "0",
            "index": "510",
            "xExact": "511",
            "x": "511",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:3064"
          },
          {
            "series": "1",
            "index": "510",
            "xExact": "511",
            "x": "511",
            "yExact": "0",
            "y": "0",
            "id": "person:3064"
          },
          {
            "series": "0",
            "index": "511",
            "xExact": "512",
            "x": "512",
            "yExact": "179/268",
            "y": "0.667910448",
            "id": "person:3065"
          },
          {
            "series": "1",
            "index": "511",
            "xExact": "512",
            "x": "512",
            "yExact": "0",
            "y": "0",
            "id": "person:3065"
          },
          {
            "series": "0",
            "index": "512",
            "xExact": "513",
            "x": "513",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:3067"
          },
          {
            "series": "1",
            "index": "512",
            "xExact": "513",
            "x": "513",
            "yExact": "0",
            "y": "0",
            "id": "person:3067"
          },
          {
            "series": "0",
            "index": "513",
            "xExact": "514",
            "x": "514",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:3068"
          },
          {
            "series": "1",
            "index": "513",
            "xExact": "514",
            "x": "514",
            "yExact": "0",
            "y": "0",
            "id": "person:3068"
          },
          {
            "series": "0",
            "index": "514",
            "xExact": "515",
            "x": "515",
            "yExact": "179/268",
            "y": "0.667910448",
            "id": "person:3069"
          },
          {
            "series": "1",
            "index": "514",
            "xExact": "515",
            "x": "515",
            "yExact": "1",
            "y": "1",
            "id": "person:3069"
          },
          {
            "series": "0",
            "index": "515",
            "xExact": "516",
            "x": "516",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:3072"
          },
          {
            "series": "1",
            "index": "515",
            "xExact": "516",
            "x": "516",
            "yExact": "0",
            "y": "0",
            "id": "person:3072"
          },
          {
            "series": "0",
            "index": "516",
            "xExact": "517",
            "x": "517",
            "yExact": "197/239",
            "y": "0.824267782",
            "id": "person:3077"
          },
          {
            "series": "1",
            "index": "516",
            "xExact": "517",
            "x": "517",
            "yExact": "0",
            "y": "0",
            "id": "person:3077"
          },
          {
            "series": "0",
            "index": "517",
            "xExact": "518",
            "x": "518",
            "yExact": "197/239",
            "y": "0.824267782",
            "id": "person:3079"
          },
          {
            "series": "1",
            "index": "517",
            "xExact": "518",
            "x": "518",
            "yExact": "0",
            "y": "0",
            "id": "person:3079"
          },
          {
            "series": "0",
            "index": "518",
            "xExact": "519",
            "x": "519",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:3080"
          },
          {
            "series": "1",
            "index": "518",
            "xExact": "519",
            "x": "519",
            "yExact": "0",
            "y": "0",
            "id": "person:3080"
          },
          {
            "series": "0",
            "index": "519",
            "xExact": "520",
            "x": "520",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:3083"
          },
          {
            "series": "1",
            "index": "519",
            "xExact": "520",
            "x": "520",
            "yExact": "0",
            "y": "0",
            "id": "person:3083"
          },
          {
            "series": "0",
            "index": "520",
            "xExact": "521",
            "x": "521",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:3084"
          },
          {
            "series": "1",
            "index": "520",
            "xExact": "521",
            "x": "521",
            "yExact": "0",
            "y": "0",
            "id": "person:3084"
          },
          {
            "series": "0",
            "index": "521",
            "xExact": "522",
            "x": "522",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:3085"
          },
          {
            "series": "1",
            "index": "521",
            "xExact": "522",
            "x": "522",
            "yExact": "1",
            "y": "1",
            "id": "person:3085"
          },
          {
            "series": "0",
            "index": "522",
            "xExact": "523",
            "x": "523",
            "yExact": "179/268",
            "y": "0.667910448",
            "id": "person:3087"
          },
          {
            "series": "1",
            "index": "522",
            "xExact": "523",
            "x": "523",
            "yExact": "1",
            "y": "1",
            "id": "person:3087"
          },
          {
            "series": "0",
            "index": "523",
            "xExact": "524",
            "x": "524",
            "yExact": "21/58",
            "y": "0.362068966",
            "id": "person:3102"
          },
          {
            "series": "1",
            "index": "523",
            "xExact": "524",
            "x": "524",
            "yExact": "0",
            "y": "0",
            "id": "person:3102"
          },
          {
            "series": "0",
            "index": "524",
            "xExact": "525",
            "x": "525",
            "yExact": "21/58",
            "y": "0.362068966",
            "id": "person:3103"
          },
          {
            "series": "1",
            "index": "524",
            "xExact": "525",
            "x": "525",
            "yExact": "0",
            "y": "0",
            "id": "person:3103"
          },
          {
            "series": "0",
            "index": "525",
            "xExact": "526",
            "x": "526",
            "yExact": "12/25",
            "y": "0.48",
            "id": "person:3106"
          },
          {
            "series": "1",
            "index": "525",
            "xExact": "526",
            "x": "526",
            "yExact": "0",
            "y": "0",
            "id": "person:3106"
          },
          {
            "series": "0",
            "index": "526",
            "xExact": "527",
            "x": "527",
            "yExact": "21/58",
            "y": "0.362068966",
            "id": "person:3114"
          },
          {
            "series": "1",
            "index": "526",
            "xExact": "527",
            "x": "527",
            "yExact": "0",
            "y": "0",
            "id": "person:3114"
          },
          {
            "series": "0",
            "index": "527",
            "xExact": "528",
            "x": "528",
            "yExact": "20/41",
            "y": "0.487804878",
            "id": "person:3120"
          },
          {
            "series": "1",
            "index": "527",
            "xExact": "528",
            "x": "528",
            "yExact": "1",
            "y": "1",
            "id": "person:3120"
          },
          {
            "series": "0",
            "index": "528",
            "xExact": "529",
            "x": "529",
            "yExact": "21/58",
            "y": "0.362068966",
            "id": "person:3123"
          },
          {
            "series": "1",
            "index": "528",
            "xExact": "529",
            "x": "529",
            "yExact": "0",
            "y": "0",
            "id": "person:3123"
          },
          {
            "series": "0",
            "index": "529",
            "xExact": "530",
            "x": "530",
            "yExact": "12/25",
            "y": "0.48",
            "id": "person:3129"
          },
          {
            "series": "1",
            "index": "529",
            "xExact": "530",
            "x": "530",
            "yExact": "0",
            "y": "0",
            "id": "person:3129"
          },
          {
            "series": "0",
            "index": "530",
            "xExact": "531",
            "x": "531",
            "yExact": "21/58",
            "y": "0.362068966",
            "id": "person:3131"
          },
          {
            "series": "1",
            "index": "530",
            "xExact": "531",
            "x": "531",
            "yExact": "1",
            "y": "1",
            "id": "person:3131"
          },
          {
            "series": "0",
            "index": "531",
            "xExact": "532",
            "x": "532",
            "yExact": "12/25",
            "y": "0.48",
            "id": "person:3133"
          },
          {
            "series": "1",
            "index": "531",
            "xExact": "532",
            "x": "532",
            "yExact": "0",
            "y": "0",
            "id": "person:3133"
          },
          {
            "series": "0",
            "index": "532",
            "xExact": "533",
            "x": "533",
            "yExact": "12/25",
            "y": "0.48",
            "id": "person:3140"
          },
          {
            "series": "1",
            "index": "532",
            "xExact": "533",
            "x": "533",
            "yExact": "0",
            "y": "0",
            "id": "person:3140"
          },
          {
            "series": "0",
            "index": "533",
            "xExact": "534",
            "x": "534",
            "yExact": "12/25",
            "y": "0.48",
            "id": "person:3146"
          },
          {
            "series": "1",
            "index": "533",
            "xExact": "534",
            "x": "534",
            "yExact": "0",
            "y": "0",
            "id": "person:3146"
          },
          {
            "series": "0",
            "index": "534",
            "xExact": "535",
            "x": "535",
            "yExact": "25/33",
            "y": "0.757575758",
            "id": "person:3154"
          },
          {
            "series": "1",
            "index": "534",
            "xExact": "535",
            "x": "535",
            "yExact": "1",
            "y": "1",
            "id": "person:3154"
          },
          {
            "series": "0",
            "index": "535",
            "xExact": "536",
            "x": "536",
            "yExact": "12/25",
            "y": "0.48",
            "id": "person:3156"
          },
          {
            "series": "1",
            "index": "535",
            "xExact": "536",
            "x": "536",
            "yExact": "1",
            "y": "1",
            "id": "person:3156"
          },
          {
            "series": "0",
            "index": "536",
            "xExact": "537",
            "x": "537",
            "yExact": "21/58",
            "y": "0.362068966",
            "id": "person:3163"
          },
          {
            "series": "1",
            "index": "536",
            "xExact": "537",
            "x": "537",
            "yExact": "0",
            "y": "0",
            "id": "person:3163"
          },
          {
            "series": "0",
            "index": "537",
            "xExact": "538",
            "x": "538",
            "yExact": "12/25",
            "y": "0.48",
            "id": "person:3164"
          },
          {
            "series": "1",
            "index": "537",
            "xExact": "538",
            "x": "538",
            "yExact": "1",
            "y": "1",
            "id": "person:3164"
          },
          {
            "series": "0",
            "index": "538",
            "xExact": "539",
            "x": "539",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:3181"
          },
          {
            "series": "1",
            "index": "538",
            "xExact": "539",
            "x": "539",
            "yExact": "1",
            "y": "1",
            "id": "person:3181"
          },
          {
            "series": "0",
            "index": "539",
            "xExact": "540",
            "x": "540",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:3182"
          },
          {
            "series": "1",
            "index": "539",
            "xExact": "540",
            "x": "540",
            "yExact": "1",
            "y": "1",
            "id": "person:3182"
          },
          {
            "series": "0",
            "index": "540",
            "xExact": "541",
            "x": "541",
            "yExact": "179/268",
            "y": "0.667910448",
            "id": "person:3183"
          },
          {
            "series": "1",
            "index": "540",
            "xExact": "541",
            "x": "541",
            "yExact": "1",
            "y": "1",
            "id": "person:3183"
          },
          {
            "series": "0",
            "index": "541",
            "xExact": "542",
            "x": "542",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:3184"
          },
          {
            "series": "1",
            "index": "541",
            "xExact": "542",
            "x": "542",
            "yExact": "0",
            "y": "0",
            "id": "person:3184"
          },
          {
            "series": "0",
            "index": "542",
            "xExact": "543",
            "x": "543",
            "yExact": "21/58",
            "y": "0.362068966",
            "id": "person:3194"
          },
          {
            "series": "1",
            "index": "542",
            "xExact": "543",
            "x": "543",
            "yExact": "0",
            "y": "0",
            "id": "person:3194"
          },
          {
            "series": "0",
            "index": "543",
            "xExact": "544",
            "x": "544",
            "yExact": "21/58",
            "y": "0.362068966",
            "id": "person:3199"
          },
          {
            "series": "1",
            "index": "543",
            "xExact": "544",
            "x": "544",
            "yExact": "0",
            "y": "0",
            "id": "person:3199"
          },
          {
            "series": "0",
            "index": "544",
            "xExact": "545",
            "x": "545",
            "yExact": "21/58",
            "y": "0.362068966",
            "id": "person:3201"
          },
          {
            "series": "1",
            "index": "544",
            "xExact": "545",
            "x": "545",
            "yExact": "0",
            "y": "0",
            "id": "person:3201"
          },
          {
            "series": "0",
            "index": "545",
            "xExact": "546",
            "x": "546",
            "yExact": "21/58",
            "y": "0.362068966",
            "id": "person:3202"
          },
          {
            "series": "1",
            "index": "545",
            "xExact": "546",
            "x": "546",
            "yExact": "0",
            "y": "0",
            "id": "person:3202"
          },
          {
            "series": "0",
            "index": "546",
            "xExact": "547",
            "x": "547",
            "yExact": "21/58",
            "y": "0.362068966",
            "id": "person:3213"
          },
          {
            "series": "1",
            "index": "546",
            "xExact": "547",
            "x": "547",
            "yExact": "0",
            "y": "0",
            "id": "person:3213"
          },
          {
            "series": "0",
            "index": "547",
            "xExact": "548",
            "x": "548",
            "yExact": "12/25",
            "y": "0.48",
            "id": "person:3215"
          },
          {
            "series": "1",
            "index": "547",
            "xExact": "548",
            "x": "548",
            "yExact": "0",
            "y": "0",
            "id": "person:3215"
          },
          {
            "series": "0",
            "index": "548",
            "xExact": "549",
            "x": "549",
            "yExact": "21/58",
            "y": "0.362068966",
            "id": "person:3228"
          },
          {
            "series": "1",
            "index": "548",
            "xExact": "549",
            "x": "549",
            "yExact": "1",
            "y": "1",
            "id": "person:3228"
          },
          {
            "series": "0",
            "index": "549",
            "xExact": "550",
            "x": "550",
            "yExact": "12/25",
            "y": "0.48",
            "id": "person:3231"
          },
          {
            "series": "1",
            "index": "549",
            "xExact": "550",
            "x": "550",
            "yExact": "1",
            "y": "1",
            "id": "person:3231"
          },
          {
            "series": "0",
            "index": "550",
            "xExact": "551",
            "x": "551",
            "yExact": "21/58",
            "y": "0.362068966",
            "id": "person:3234"
          },
          {
            "series": "1",
            "index": "550",
            "xExact": "551",
            "x": "551",
            "yExact": "0",
            "y": "0",
            "id": "person:3234"
          },
          {
            "series": "0",
            "index": "551",
            "xExact": "552",
            "x": "552",
            "yExact": "21/58",
            "y": "0.362068966",
            "id": "person:3239"
          },
          {
            "series": "1",
            "index": "551",
            "xExact": "552",
            "x": "552",
            "yExact": "0",
            "y": "0",
            "id": "person:3239"
          },
          {
            "series": "0",
            "index": "552",
            "xExact": "553",
            "x": "553",
            "yExact": "21/58",
            "y": "0.362068966",
            "id": "person:3246"
          },
          {
            "series": "1",
            "index": "552",
            "xExact": "553",
            "x": "553",
            "yExact": "0",
            "y": "0",
            "id": "person:3246"
          },
          {
            "series": "0",
            "index": "553",
            "xExact": "554",
            "x": "554",
            "yExact": "21/58",
            "y": "0.362068966",
            "id": "person:3249"
          },
          {
            "series": "1",
            "index": "553",
            "xExact": "554",
            "x": "554",
            "yExact": "0",
            "y": "0",
            "id": "person:3249"
          },
          {
            "series": "0",
            "index": "554",
            "xExact": "555",
            "x": "555",
            "yExact": "12/25",
            "y": "0.48",
            "id": "person:3251"
          },
          {
            "series": "1",
            "index": "554",
            "xExact": "555",
            "x": "555",
            "yExact": "0",
            "y": "0",
            "id": "person:3251"
          },
          {
            "series": "0",
            "index": "555",
            "xExact": "556",
            "x": "556",
            "yExact": "21/58",
            "y": "0.362068966",
            "id": "person:3257"
          },
          {
            "series": "1",
            "index": "555",
            "xExact": "556",
            "x": "556",
            "yExact": "0",
            "y": "0",
            "id": "person:3257"
          },
          {
            "series": "0",
            "index": "556",
            "xExact": "557",
            "x": "557",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:3259"
          },
          {
            "series": "1",
            "index": "556",
            "xExact": "557",
            "x": "557",
            "yExact": "0",
            "y": "0",
            "id": "person:3259"
          },
          {
            "series": "0",
            "index": "557",
            "xExact": "558",
            "x": "558",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:3262"
          },
          {
            "series": "1",
            "index": "557",
            "xExact": "558",
            "x": "558",
            "yExact": "0",
            "y": "0",
            "id": "person:3262"
          },
          {
            "series": "0",
            "index": "558",
            "xExact": "559",
            "x": "559",
            "yExact": "179/268",
            "y": "0.667910448",
            "id": "person:3264"
          },
          {
            "series": "1",
            "index": "558",
            "xExact": "559",
            "x": "559",
            "yExact": "0",
            "y": "0",
            "id": "person:3264"
          },
          {
            "series": "0",
            "index": "559",
            "xExact": "560",
            "x": "560",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:3265"
          },
          {
            "series": "1",
            "index": "559",
            "xExact": "560",
            "x": "560",
            "yExact": "0",
            "y": "0",
            "id": "person:3265"
          },
          {
            "series": "0",
            "index": "560",
            "xExact": "561",
            "x": "561",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:3268"
          },
          {
            "series": "1",
            "index": "560",
            "xExact": "561",
            "x": "561",
            "yExact": "1",
            "y": "1",
            "id": "person:3268"
          },
          {
            "series": "0",
            "index": "561",
            "xExact": "562",
            "x": "562",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:3269"
          },
          {
            "series": "1",
            "index": "561",
            "xExact": "562",
            "x": "562",
            "yExact": "0",
            "y": "0",
            "id": "person:3269"
          },
          {
            "series": "0",
            "index": "562",
            "xExact": "563",
            "x": "563",
            "yExact": "21/58",
            "y": "0.362068966",
            "id": "person:3298"
          },
          {
            "series": "1",
            "index": "562",
            "xExact": "563",
            "x": "563",
            "yExact": "0",
            "y": "0",
            "id": "person:3298"
          },
          {
            "series": "0",
            "index": "563",
            "xExact": "564",
            "x": "564",
            "yExact": "20/41",
            "y": "0.487804878",
            "id": "person:3299"
          },
          {
            "series": "1",
            "index": "563",
            "xExact": "564",
            "x": "564",
            "yExact": "0",
            "y": "0",
            "id": "person:3299"
          },
          {
            "series": "0",
            "index": "564",
            "xExact": "565",
            "x": "565",
            "yExact": "21/58",
            "y": "0.362068966",
            "id": "person:3300"
          },
          {
            "series": "1",
            "index": "564",
            "xExact": "565",
            "x": "565",
            "yExact": "0",
            "y": "0",
            "id": "person:3300"
          },
          {
            "series": "0",
            "index": "565",
            "xExact": "566",
            "x": "566",
            "yExact": "21/58",
            "y": "0.362068966",
            "id": "person:3309"
          },
          {
            "series": "1",
            "index": "565",
            "xExact": "566",
            "x": "566",
            "yExact": "1",
            "y": "1",
            "id": "person:3309"
          },
          {
            "series": "0",
            "index": "566",
            "xExact": "567",
            "x": "567",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:3313"
          },
          {
            "series": "1",
            "index": "566",
            "xExact": "567",
            "x": "567",
            "yExact": "1",
            "y": "1",
            "id": "person:3313"
          },
          {
            "series": "0",
            "index": "567",
            "xExact": "568",
            "x": "568",
            "yExact": "179/268",
            "y": "0.667910448",
            "id": "person:3319"
          },
          {
            "series": "1",
            "index": "567",
            "xExact": "568",
            "x": "568",
            "yExact": "1",
            "y": "1",
            "id": "person:3319"
          },
          {
            "series": "0",
            "index": "568",
            "xExact": "569",
            "x": "569",
            "yExact": "179/268",
            "y": "0.667910448",
            "id": "person:3320"
          },
          {
            "series": "1",
            "index": "568",
            "xExact": "569",
            "x": "569",
            "yExact": "1",
            "y": "1",
            "id": "person:3320"
          },
          {
            "series": "0",
            "index": "569",
            "xExact": "570",
            "x": "570",
            "yExact": "12/25",
            "y": "0.48",
            "id": "person:3332"
          },
          {
            "series": "1",
            "index": "569",
            "xExact": "570",
            "x": "570",
            "yExact": "1",
            "y": "1",
            "id": "person:3332"
          },
          {
            "series": "0",
            "index": "570",
            "xExact": "571",
            "x": "571",
            "yExact": "21/58",
            "y": "0.362068966",
            "id": "person:3344"
          },
          {
            "series": "1",
            "index": "570",
            "xExact": "571",
            "x": "571",
            "yExact": "0",
            "y": "0",
            "id": "person:3344"
          },
          {
            "series": "0",
            "index": "571",
            "xExact": "572",
            "x": "572",
            "yExact": "12/25",
            "y": "0.48",
            "id": "person:3351"
          },
          {
            "series": "1",
            "index": "571",
            "xExact": "572",
            "x": "572",
            "yExact": "0",
            "y": "0",
            "id": "person:3351"
          },
          {
            "series": "0",
            "index": "572",
            "xExact": "573",
            "x": "573",
            "yExact": "21/58",
            "y": "0.362068966",
            "id": "person:3355"
          },
          {
            "series": "1",
            "index": "572",
            "xExact": "573",
            "x": "573",
            "yExact": "0",
            "y": "0",
            "id": "person:3355"
          },
          {
            "series": "0",
            "index": "573",
            "xExact": "574",
            "x": "574",
            "yExact": "12/25",
            "y": "0.48",
            "id": "person:3356"
          },
          {
            "series": "1",
            "index": "573",
            "xExact": "574",
            "x": "574",
            "yExact": "0",
            "y": "0",
            "id": "person:3356"
          },
          {
            "series": "0",
            "index": "574",
            "xExact": "575",
            "x": "575",
            "yExact": "21/58",
            "y": "0.362068966",
            "id": "person:3362"
          },
          {
            "series": "1",
            "index": "574",
            "xExact": "575",
            "x": "575",
            "yExact": "0",
            "y": "0",
            "id": "person:3362"
          },
          {
            "series": "0",
            "index": "575",
            "xExact": "576",
            "x": "576",
            "yExact": "12/25",
            "y": "0.48",
            "id": "person:3370"
          },
          {
            "series": "1",
            "index": "575",
            "xExact": "576",
            "x": "576",
            "yExact": "0",
            "y": "0",
            "id": "person:3370"
          },
          {
            "series": "0",
            "index": "576",
            "xExact": "577",
            "x": "577",
            "yExact": "21/58",
            "y": "0.362068966",
            "id": "person:3380"
          },
          {
            "series": "1",
            "index": "576",
            "xExact": "577",
            "x": "577",
            "yExact": "1",
            "y": "1",
            "id": "person:3380"
          },
          {
            "series": "0",
            "index": "577",
            "xExact": "578",
            "x": "578",
            "yExact": "12/25",
            "y": "0.48",
            "id": "person:3384"
          },
          {
            "series": "1",
            "index": "577",
            "xExact": "578",
            "x": "578",
            "yExact": "0",
            "y": "0",
            "id": "person:3384"
          },
          {
            "series": "0",
            "index": "578",
            "xExact": "579",
            "x": "579",
            "yExact": "12/25",
            "y": "0.48",
            "id": "person:3394"
          },
          {
            "series": "1",
            "index": "578",
            "xExact": "579",
            "x": "579",
            "yExact": "0",
            "y": "0",
            "id": "person:3394"
          },
          {
            "series": "0",
            "index": "579",
            "xExact": "580",
            "x": "580",
            "yExact": "12/25",
            "y": "0.48",
            "id": "person:3399"
          },
          {
            "series": "1",
            "index": "579",
            "xExact": "580",
            "x": "580",
            "yExact": "0",
            "y": "0",
            "id": "person:3399"
          },
          {
            "series": "0",
            "index": "580",
            "xExact": "581",
            "x": "581",
            "yExact": "21/58",
            "y": "0.362068966",
            "id": "person:3402"
          },
          {
            "series": "1",
            "index": "580",
            "xExact": "581",
            "x": "581",
            "yExact": "1",
            "y": "1",
            "id": "person:3402"
          },
          {
            "series": "0",
            "index": "581",
            "xExact": "582",
            "x": "582",
            "yExact": "21/58",
            "y": "0.362068966",
            "id": "person:3404"
          },
          {
            "series": "1",
            "index": "581",
            "xExact": "582",
            "x": "582",
            "yExact": "1",
            "y": "1",
            "id": "person:3404"
          },
          {
            "series": "0",
            "index": "582",
            "xExact": "583",
            "x": "583",
            "yExact": "12/25",
            "y": "0.48",
            "id": "person:3412"
          },
          {
            "series": "1",
            "index": "582",
            "xExact": "583",
            "x": "583",
            "yExact": "0",
            "y": "0",
            "id": "person:3412"
          },
          {
            "series": "0",
            "index": "583",
            "xExact": "584",
            "x": "584",
            "yExact": "21/58",
            "y": "0.362068966",
            "id": "person:3436"
          },
          {
            "series": "1",
            "index": "583",
            "xExact": "584",
            "x": "584",
            "yExact": "0",
            "y": "0",
            "id": "person:3436"
          },
          {
            "series": "0",
            "index": "584",
            "xExact": "585",
            "x": "585",
            "yExact": "12/25",
            "y": "0.48",
            "id": "person:3456"
          },
          {
            "series": "1",
            "index": "584",
            "xExact": "585",
            "x": "585",
            "yExact": "0",
            "y": "0",
            "id": "person:3456"
          },
          {
            "series": "0",
            "index": "585",
            "xExact": "586",
            "x": "586",
            "yExact": "21/58",
            "y": "0.362068966",
            "id": "person:3463"
          },
          {
            "series": "1",
            "index": "585",
            "xExact": "586",
            "x": "586",
            "yExact": "0",
            "y": "0",
            "id": "person:3463"
          },
          {
            "series": "0",
            "index": "586",
            "xExact": "587",
            "x": "587",
            "yExact": "21/58",
            "y": "0.362068966",
            "id": "person:3473"
          },
          {
            "series": "1",
            "index": "586",
            "xExact": "587",
            "x": "587",
            "yExact": "0",
            "y": "0",
            "id": "person:3473"
          },
          {
            "series": "0",
            "index": "587",
            "xExact": "588",
            "x": "588",
            "yExact": "12/25",
            "y": "0.48",
            "id": "person:3486"
          },
          {
            "series": "1",
            "index": "587",
            "xExact": "588",
            "x": "588",
            "yExact": "0",
            "y": "0",
            "id": "person:3486"
          },
          {
            "series": "0",
            "index": "588",
            "xExact": "589",
            "x": "589",
            "yExact": "12/25",
            "y": "0.48",
            "id": "person:3487"
          },
          {
            "series": "1",
            "index": "588",
            "xExact": "589",
            "x": "589",
            "yExact": "0",
            "y": "0",
            "id": "person:3487"
          },
          {
            "series": "0",
            "index": "589",
            "xExact": "590",
            "x": "590",
            "yExact": "20/41",
            "y": "0.487804878",
            "id": "person:3490"
          },
          {
            "series": "1",
            "index": "589",
            "xExact": "590",
            "x": "590",
            "yExact": "1",
            "y": "1",
            "id": "person:3490"
          },
          {
            "series": "0",
            "index": "590",
            "xExact": "591",
            "x": "591",
            "yExact": "21/58",
            "y": "0.362068966",
            "id": "person:3493"
          },
          {
            "series": "1",
            "index": "590",
            "xExact": "591",
            "x": "591",
            "yExact": "0",
            "y": "0",
            "id": "person:3493"
          },
          {
            "series": "0",
            "index": "591",
            "xExact": "592",
            "x": "592",
            "yExact": "20/41",
            "y": "0.487804878",
            "id": "person:3509"
          },
          {
            "series": "1",
            "index": "591",
            "xExact": "592",
            "x": "592",
            "yExact": "0",
            "y": "0",
            "id": "person:3509"
          },
          {
            "series": "0",
            "index": "592",
            "xExact": "593",
            "x": "593",
            "yExact": "12/25",
            "y": "0.48",
            "id": "person:3525"
          },
          {
            "series": "1",
            "index": "592",
            "xExact": "593",
            "x": "593",
            "yExact": "1",
            "y": "1",
            "id": "person:3525"
          },
          {
            "series": "0",
            "index": "593",
            "xExact": "594",
            "x": "594",
            "yExact": "12/25",
            "y": "0.48",
            "id": "person:3536"
          },
          {
            "series": "1",
            "index": "593",
            "xExact": "594",
            "x": "594",
            "yExact": "1",
            "y": "1",
            "id": "person:3536"
          },
          {
            "series": "0",
            "index": "594",
            "xExact": "595",
            "x": "595",
            "yExact": "21/58",
            "y": "0.362068966",
            "id": "person:3555"
          },
          {
            "series": "1",
            "index": "594",
            "xExact": "595",
            "x": "595",
            "yExact": "0",
            "y": "0",
            "id": "person:3555"
          },
          {
            "series": "0",
            "index": "595",
            "xExact": "596",
            "x": "596",
            "yExact": "20/41",
            "y": "0.487804878",
            "id": "person:3558"
          },
          {
            "series": "1",
            "index": "595",
            "xExact": "596",
            "x": "596",
            "yExact": "1",
            "y": "1",
            "id": "person:3558"
          },
          {
            "series": "0",
            "index": "596",
            "xExact": "597",
            "x": "597",
            "yExact": "21/58",
            "y": "0.362068966",
            "id": "person:3566"
          },
          {
            "series": "1",
            "index": "596",
            "xExact": "597",
            "x": "597",
            "yExact": "0",
            "y": "0",
            "id": "person:3566"
          },
          {
            "series": "0",
            "index": "597",
            "xExact": "598",
            "x": "598",
            "yExact": "21/58",
            "y": "0.362068966",
            "id": "person:3569"
          },
          {
            "series": "1",
            "index": "597",
            "xExact": "598",
            "x": "598",
            "yExact": "0",
            "y": "0",
            "id": "person:3569"
          },
          {
            "series": "0",
            "index": "598",
            "xExact": "599",
            "x": "599",
            "yExact": "25/33",
            "y": "0.757575758",
            "id": "person:3575"
          },
          {
            "series": "1",
            "index": "598",
            "xExact": "599",
            "x": "599",
            "yExact": "1",
            "y": "1",
            "id": "person:3575"
          },
          {
            "series": "0",
            "index": "599",
            "xExact": "600",
            "x": "600",
            "yExact": "12/25",
            "y": "0.48",
            "id": "person:3576"
          },
          {
            "series": "1",
            "index": "599",
            "xExact": "600",
            "x": "600",
            "yExact": "0",
            "y": "0",
            "id": "person:3576"
          },
          {
            "series": "0",
            "index": "600",
            "xExact": "601",
            "x": "601",
            "yExact": "21/58",
            "y": "0.362068966",
            "id": "person:3577"
          },
          {
            "series": "1",
            "index": "600",
            "xExact": "601",
            "x": "601",
            "yExact": "0",
            "y": "0",
            "id": "person:3577"
          },
          {
            "series": "0",
            "index": "601",
            "xExact": "602",
            "x": "602",
            "yExact": "21/58",
            "y": "0.362068966",
            "id": "person:3580"
          },
          {
            "series": "1",
            "index": "601",
            "xExact": "602",
            "x": "602",
            "yExact": "0",
            "y": "0",
            "id": "person:3580"
          },
          {
            "series": "0",
            "index": "602",
            "xExact": "603",
            "x": "603",
            "yExact": "20/41",
            "y": "0.487804878",
            "id": "person:3583"
          },
          {
            "series": "1",
            "index": "602",
            "xExact": "603",
            "x": "603",
            "yExact": "1",
            "y": "1",
            "id": "person:3583"
          },
          {
            "series": "0",
            "index": "603",
            "xExact": "604",
            "x": "604",
            "yExact": "12/25",
            "y": "0.48",
            "id": "person:3584"
          },
          {
            "series": "1",
            "index": "603",
            "xExact": "604",
            "x": "604",
            "yExact": "0",
            "y": "0",
            "id": "person:3584"
          },
          {
            "series": "0",
            "index": "604",
            "xExact": "605",
            "x": "605",
            "yExact": "201/326",
            "y": "0.616564417",
            "id": "person:3600"
          },
          {
            "series": "1",
            "index": "604",
            "xExact": "605",
            "x": "605",
            "yExact": "0",
            "y": "0",
            "id": "person:3600"
          },
          {
            "series": "0",
            "index": "605",
            "xExact": "606",
            "x": "606",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:3602"
          },
          {
            "series": "1",
            "index": "605",
            "xExact": "606",
            "x": "606",
            "yExact": "1",
            "y": "1",
            "id": "person:3602"
          },
          {
            "series": "0",
            "index": "606",
            "xExact": "607",
            "x": "607",
            "yExact": "106/201",
            "y": "0.527363184",
            "id": "person:3608"
          },
          {
            "series": "1",
            "index": "606",
            "xExact": "607",
            "x": "607",
            "yExact": "0",
            "y": "0",
            "id": "person:3608"
          }
        ],
        "plotFile": "ml14-fixed-results/realdata-person-python/plot.svg",
        "plotSHA256": "2c15f767ac76d81d7887d251a2ad114692b1638bb5a45c07063ae8b6cab97bf3",
        "files": [
          {
            "file": "ml14-fixed-results/realdata-person-python/full.json",
            "sha256": "f572373f51900a2125e9de9680beeb2607d710ab0c10da7b6fe0804816b81b66",
            "bytes": 13047442
          },
          {
            "file": "ml14-fixed-results/realdata-person-python/plot-points.csv",
            "sha256": "fd2620e20dd0ca858c7d4d94e3671fb382223ff7e2bd3d0f8c82f3d7721fd3bf",
            "bytes": 45617
          },
          {
            "file": "ml14-fixed-results/realdata-person-python/plot.svg",
            "sha256": "2c15f767ac76d81d7887d251a2ad114692b1638bb5a45c07063ae8b6cab97bf3",
            "bytes": 71643
          },
          {
            "file": "ml14-fixed-results/realdata-person-python/summary.csv",
            "sha256": "64a762294a228342ab1704cbcebdc9de2d1636c81cab1384daef8cd71d4aab6e",
            "bytes": 657
          }
        ],
        "scope": "Actually executed standalone fixed example, Python exact Fraction versus base-R binary64. Approximate R residuals retained; not universal exact arithmetic/web validation/native UI. Source programs read factual3CSV only."
      },
      "company": {
        "api": "realdata",
        "variant": "company",
        "language": "python",
        "title": "Actual company fixed train/validation/test procedure",
        "codeFile": "ml14-code/realdata-company.py",
        "codeSHA256": "30fe968ff51237d8c947c6af3a928ca5395721e1643366e5e4e9bb393242011d",
        "code": "#!/usr/bin/env python3\n\"\"\"ML14 standalone exact finite study, Python standard library only.\nInputs: only the three retained factual source CSVs below.\nDerived role/target/group/eligibility columns in those CSVs are NOT inputs.\nRebuilds SHA256 roles, train-only medians/cell scores, validation thresholds,\ntest curves, binary-event reliability and descriptive group ledgers.\nCosts 1/1,1/5,5/1 are hypothetical units, not measured intervention returns.\nThis is author public reproduction, not independent scientific review.\n\"\"\"\n\"\"\"Author Fraction reference, separate from product JavaScript; not independent peer.\"\"\"\nfrom fractions import Fraction as F\nfrom collections import Counter,defaultdict\ndef read(raw):\n rows=[]\n for i,r in enumerate(raw):\n  s=None if r['score']is None else F(str(r['score']));y=None if r['y']is None else F(int(r['y']))if isinstance(r['y'],bool)else F(str(r['y']));w=F(str(r.get('weight','1')));role=r.get('role','evaluation')\n  rows.append(dict(id=r['id'],index=i,score=s,y=y,w=w,role=role,group=r.get('group'),eligible=s is not None and y is not None and w>0 and role!='excluded'))\n return rows\ndef scoped(rows,role='all'):return rows if role=='all'else[r for r in rows if r['role']==role]\ndef divide(n,d):return None if not d else n/d\ndef policy(v):return v if v in ['always-negative','always-positive']else F(str(v))\ndef positive(p,s):return p=='always-positive'if isinstance(p,str)else s>=p\ndef cost(a=None):\n a={}if a is None else a;fp=F(str(a.get('falsePositive','1')));fn=F(str(a.get('falseNegative','1')));return fp,fn\ndef metrics(rows,threshold=F(1,2),cc=(F(1),F(1))):\n counts=dict(TP=F(0),FP=F(0),FN=F(0),TN=F(0));brier=F(0);pred=[]\n for r in rows:\n  if not r['eligible']:pred.append(dict(id=r['id'],index=r['index'],eligible=False,decision=None,probability=None,Brier=None));continue\n  yes=positive(threshold,r['score']);cell=('T'if yes==bool(r['y'])else'F')+('P'if yes else'N');counts[cell]+=r['w'];loss=(r['score']-r['y'])**2;brier+=r['w']*loss;pred.append(dict(id=r['id'],index=r['index'],eligible=True,decision=int(yes),probability=r['score'],Brier=loss))\n TP,FP,FN,TN=[counts[k]for k in ['TP','FP','FN','TN']];P=TP+FN;N=TN+FP;mass=P+N;PP=TP+FP;PN=TN+FN;TPR=divide(TP,P);TNR=divide(TN,N);total=FP*cc[0]+FN*cc[1]\n return dict(confusion=counts,mass=mass,positiveTargetMass=P,negativeTargetMass=N,predictedPositiveMass=PP,predictedNegativeMass=PN,prevalence=divide(P,mass),selectionRate=divide(PP,mass),accuracy=divide(TP+TN,mass),precision=divide(TP,PP),negativePredictiveValue=divide(TN,PN),TPR=TPR,FPR=divide(FP,N),TNR=TNR,FNR=divide(FN,P),F1=divide(2*TP,2*TP+FP+FN),balancedAccuracy=None if TPR is None or TNR is None else(TPR+TNR)/2,Brier=divide(brier,mass),BrierSum=brier,totalCost=total,meanCost=divide(total,mass),predictions=pred,bayesThreshold=divide(cc[0],sum(cc)))\ndef curves(rows):\n use=[r for r in rows if r['eligible']];pos=Counter();neg=Counter()\n for r in use:(pos if r['y']else neg)[r['score']]+=r['w']\n P=sum(pos.values(),F(0));N=sum(neg.values(),F(0));pairs=F(0)\n for a,wa in pos.items():\n  for b,wb in neg.items():pairs+=wa*wb*(F(1)if a>b else F(1,2)if a==b else F(0))\n thresholds=['always-negative']+sorted({r['score']for r in use},reverse=True);points=[];AP=F(0);trap=F(0);lastR=F(0);lastP=F(1)\n for i,p in enumerate(thresholds):\n  m=metrics(rows,p);points.append(dict(policy=p,TP=m['confusion']['TP'],FP=m['confusion']['FP'],FN=m['confusion']['FN'],TN=m['confusion']['TN'],TPR=m['TPR'],FPR=m['FPR'],precision=m['precision'],recall=m['TPR']))\n  if i and P:\n   R=m['TPR'];PP=m['precision'];AP+=(R-lastR)*PP;trap+=(R-lastR)*(PP+lastP)/2;lastR=R;lastP=PP\n return dict(positiveMass=P,negativeMass=N,ROC_AUC=divide(pairs,P*N),weightedConcordantPlusHalfTiedMass=pairs,averagePrecision=AP if P else None,PRTrapezoidWithInitialPrecisionOne=trap if P else None,points=points)\ndef choose(rows,a,cc):\n sr=a.get('selectionRole','validation');er=a.get('evaluationRole','test');rr=scoped(rows,sr);thresholds=[policy(t)for t in a['thresholds']]if'thresholds'in a else['always-negative']+sorted({r['score']for r in rr if r['eligible']},reverse=True)\n candidates=[]\n for i,p in enumerate(thresholds):\n  m=metrics(rr,p,cc);reasons=[]\n  if'minTPR'in a and(m['TPR']is None or m['TPR']<F(str(a['minTPR']))):reasons.append('TPR-undefined'if m['TPR']is None else'below-minTPR')\n  if'maxFPR'in a and(m['FPR']is None or m['FPR']>F(str(a['maxFPR']))):reasons.append('FPR-undefined'if m['FPR']is None else'above-maxFPR')\n  candidates.append(dict(index=i,policy=p,metrics=m,feasible=not reasons,reasons=reasons))\n eligible=[c for c in candidates if c['feasible']];best=min(eligible,key=lambda c:(c['metrics']['meanCost'],c['index']))if eligible else None\n return dict(selectedIndex=None if best is None else best['index'],selectedPolicy=None if best is None else best['policy'],candidates=candidates,selectedValidation=None if best is None else best['metrics'],evaluation=None if best is None or er=='none'else metrics(scoped(rows,er),best['policy'],cc),selectionIDs=[r['id']for r in rr if r['eligible']])\ndef calibrate(rows,ee):\n buckets=[[]for _ in range(len(ee)-1)]\n for r in rows:\n  if not r['eligible']:continue\n  j=next((i for i in range(len(ee)-1)if r['score']<ee[i+1]),len(ee)-2);buckets[j].append(r)\n mass=sum((r['w']for r in rows if r['eligible']),F(0));P=sum((r['w']*r['y']for r in rows if r['eligible']),F(0));pi=divide(P,mass);Brier=None if not mass else sum((r['w']*(r['score']-r['y'])**2 for r in rows if r['eligible']),F(0))/mass;ECE=F(0);reliability=F(0);resolution=F(0);correction=F(0);bins=[]\n for i,rr in enumerate(buckets):\n  w=sum((r['w']for r in rr),F(0));mp=None if not w else sum((r['w']*r['score']for r in rr),F(0))/w;o=None if not w else sum((r['w']*r['y']for r in rr),F(0))/w\n  variance=None if not w else sum((r['w']*(r['score']-mp)**2 for r in rr),F(0))/w\n  covariance=None if not w else sum((r['w']*(r['score']-mp)*(r['y']-o)for r in rr),F(0))/w\n  bc=None if not w else variance-2*covariance;gap=None if not w else mp-o\n  bins.append(dict(index=i,rows=len(rr),mass=w,meanPrediction=mp,eventRate=o,gap=gap,absoluteGap=None if gap is None else abs(gap),scoreVariance=variance,scoreTargetCovariance=covariance,withinBinCorrection=bc,ids=[r['id']for r in rr]))\n  if w:\n   share=w/mass;ECE+=share*abs(gap);reliability+=share*gap**2;resolution+=share*(o-pi)**2;correction+=share*bc\n uncertainty=None if pi is None else pi*(1-pi);residual=None if Brier is None else Brier-(uncertainty-resolution+reliability+correction)\n return dict(mass=mass,prevalence=pi,Brier=Brier,ECE=ECE if mass else None,reliability=reliability if mass else None,resolution=resolution if mass else None,uncertainty=uncertainty,withinBinCorrection=correction if mass else None,BrierIdentityResidual=residual,bins=bins)\ndef typed(v):return type(v).__name__,v\ndef groups(rows,p,cc):\n bins={}\n for r in rows:\n  if r['group']is not None:bins.setdefault(typed(r['group']),[]).append(r)\n gm=[dict(group=rr[0]['group'],metrics=metrics(rr,p,cc))for rr in bins.values()];overall=metrics(rows,p,cc);unknown=metrics([r for r in rows if r['group']is None],p,cc);gaps={}\n for key in ['prevalence','selectionRate','TPR','FPR','precision','accuracy','meanCost']:\n  positive=[g for g in gm if g['metrics']['mass']>0];undefined=[g['group']for g in positive if g['metrics'][key]is None];vals=[g['metrics'][key]for g in positive if g['metrics'][key]is not None]\n  gaps[key]=dict(value=None if len(positive)<2 or undefined else max(vals)-min(vals),undefinedGroups=undefined,comparedPositiveMassGroups=[g['group']for g in positive])\n return dict(overall=overall,groups=gm,unknownGroup=unknown,gaps=gaps,partitionMassResidual=overall['mass']-unknown['mass']-sum((g['metrics']['mass']for g in gm),F(0)))\ndef actual_model(M):\n raw=M['records'];cat=M['categoricalFeatures'];p=len(raw[0]['x']);train=[r for r in raw if r['role']=='train'];medians=[]\n for j in range(p):\n  if j in cat:medians.append(None);continue\n  values=sorted(F(r['x'][j])for r in train);n=len(values);medians.append(values[n//2]if n%2 else(values[n//2-1]+values[n//2])/2)\n def transform(r):return[F(v)if j in cat else F(int(F(v)>medians[j]))for j,v in enumerate(r['x'])]\n counts={}\n for r in train:\n  key=tuple(transform(r));n,s=counts.get(key,(0,0));counts[key]=(n+1,s+int(r['y']))\n probabilities={k:F(s+1,n+2)for k,(n,s)in counts.items()};fallback=F(sum(int(r['y'])for r in train)+1,len(train)+2);scored=[]\n for i,r in enumerate(raw):\n  eligible=r['role']!='excluded';z=transform(r)if eligible else None;key=None if z is None else tuple(z);score=None if not eligible else probabilities.get(key,fallback)\n  scored.append(dict(id=r['id'],index=i,role=r['role'],group=r['group'],y=None if r['y']is None else F(r['y']),score=score,w=F(1),eligible=eligible,transformedX=z,unseenCell=None if not eligible else key not in probabilities))\n return dict(medians=medians,cells=counts,probabilities=probabilities,fallback=fallback,rows=scored,trainIDs=[r['id']for r in train])\n\n\nimport csv,json,hashlib,argparse,datetime\nfrom pathlib import Path\ndef missing(v):return None if v in ['', '.',None]else v\ndef load_sources(folder):\n def read_csv(name):\n  with (folder/name).open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))\n wb=read_csv('actual64-country-four-indicators-original-2024.csv')\n codes=['NY.GDP.PCAP.KD','NY.GDP.MKTP.KD.ZG','FP.CPI.TOTL.ZG','SP.DYN.LE00.IN']\n lookup={(r['countryISO3'],r['indicatorID']):r for r in wb};country=[]\n for i,iso in enumerate(sorted({r['countryISO3']for r in wb}),1):\n  native=[lookup[iso,c]for c in codes];v=[missing(r['originalValueToken'])for r in native]\n  country.append(dict(id=iso+':2024',sourceRow=i,originalID=iso,x=v[:3],y=None if v[3]is None else str(int(F(v[3])>=80)),group=None if v[0]is None else str(int(F(v[0])>=25000)),nativeTarget=v[3],nativeSourceRows=';'.join(r['sourceRow']for r in native)))\n nls=read_csv('actual3613-NLS-original52-fields-groups-roles.csv');person=[]\n for r in nls:\n  y=missing(r['wage76']);person.append(dict(id='person:'+r['sourceRow'],sourceRow=int(r['sourceRow']),originalID=r['id'],x=[missing(r[k])for k in ['ed76','age76','nearc4']],y=None if y is None else str(int(F(y)>=500)),group=missing(r['black']),nativeTarget=y,nativeSourceRows=r['sourceRow']))\n ch=read_csv('actual3150-churn-original14-fields-groups-roles.csv');company=[]\n for r in ch:\n  company.append(dict(id='customer:'+r['sourceRow'],sourceRow=int(r['sourceRow']),originalID='',x=[missing(r[k])for k in ['Call  Failure','Complains','Subscription  Length','Seconds of Use']],y=missing(r['Churn']),group=missing(r['Tariff Plan']),nativeTarget=missing(r['Churn']),nativeSourceRows=r['sourceRow']))\n assert len(wb)==64 and len(country)==16 and len(nls)==3613 and len(ch)==3150\n assert [int(r['sourceRow'])for r in ch if r['Charge  Amount']=='10']==[474,2174,2274,2374,2674,2924,2974]\n models={}\n for kind,raw,cat,units in [('country',country,[],['constant2015USD/person','annualPercent','annualPercent']),('person',person,[2],['years','years','nativeCategory']),('company',company,[1],['count','nativeCategory','months','seconds'])]:\n  order=sorted(range(len(raw)),key=lambda i:(hashlib.sha256(('ML14-role|'+kind+'|'+raw[i]['id']).encode()).hexdigest(),i))\n  for rank,i in enumerate(order):\n   r=raw[i];r['plannedRole']='test'if rank%5==0 else'validation'if rank%5==1 else'train';r['eligible']=None not in r['x']+[r['y']];r['role']=r['plannedRole']if r['eligible']else'excluded';r['weight']='1'\n  models[kind]=dict(records=raw,categoricalFeatures=cat,featureUnits=units)\n assert sum(r['eligible']for r in person)==3017\n return models\n\ndef exact(v):return ''if v is None else str(v)\ndef approx(v):return ''if v is None else format(float(v),'.17g')\ndef scalar_fields(m,keys):\n out={}\n for k in keys:\n  out[k+'Exact']=exact(m[k]);out[k+'Approx']=approx(m[k])\n return out\nCOUNTS=['mass','positiveTargetMass','negativeTargetMass','predictedPositiveMass','predictedNegativeMass']\nRATES=['prevalence','selectionRate','accuracy','precision','negativePredictiveValue','TPR','FPR','TNR','FNR','F1','balancedAccuracy','Brier','BrierSum','totalCost','meanCost']\nSCENARIOS=[('equal',F(1),F(1)),('miss-five',F(1),F(5)),('alarm-five',F(5),F(1))]\ndef packed(v):\n if isinstance(v,F):return str(v)\n if isinstance(v,dict):return{str(k):packed(x)for k,x in v.items()}\n if isinstance(v,(tuple,list)):return[packed(x)for x in v]\n return v\ndef run_study(source,out):\n out.mkdir(parents=True,exist_ok=True);models=load_sources(source)\n tables={name:[]for name in ['predictions','lineage','fit-medians','fit-cells','validation-candidates','test-metrics','test-curves','calibration-bins','group-metrics','chart-points']}\n studies={};charts=[]\n def point(kind,chart,series,index,x,y,xunit='dimensionless',yunit='dimensionless',role='test',tag=''):\n  tables['chart-points'].append(dict(kind=kind,chart=chart,series=series,index=index,xExact=exact(x),xApprox=approx(x),yExact=exact(y),yApprox=approx(y),xUnit=xunit,yUnit=yunit,role=role,tag=tag))\n for kind,M in models.items():\n  fit=actual_model(M);rr=fit['rows'];native=M['records'];test=scoped(rr,'test');cv=curves(test);cal=calibrate(test,[F(0),F(1,5),F(2,5),F(3,5),F(4,5),F(1)]);scenarios=[]\n  for i,r in enumerate(rr):\n   n=native[i];reason=''if r['eligible']else'required-X-or-Y-missing'\n   tables['predictions'].append(dict(kind=kind,id=r['id'],sourceRow=n['sourceRow'],originalID=n['originalID'],plannedRole=n['plannedRole'],role=r['role'],group=''if r['group']is None else r['group'],eligible=int(r['eligible']),targetExact=exact(r['y']),probabilityExact=exact(r['score']),probabilityApprox=approx(r['score']),unseenCell=''if r['unseenCell']is None else int(r['unseenCell']),transformedX=''if r['transformedX']is None else'|'.join(map(str,r['transformedX'])),reason=reason))\n   tables['lineage'].append(dict(kind=kind,id=r['id'],sourceRow=n['sourceRow'],originalID=n['originalID'],nativeSourceRows=n['nativeSourceRows'],rawX='|'.join(''if x is None else x for x in n['x']),nativeTarget=''if n['nativeTarget']is None else n['nativeTarget'],derivedTarget=exact(r['y']),nativeGroup=''if n['group']is None else n['group'],plannedRole=n['plannedRole'],role=r['role'],eligible=int(r['eligible']),analyticalMass='1',reason=reason))\n  for j,v in enumerate(fit['medians']):tables['fit-medians'].append(dict(kind=kind,feature=j,categorical=int(j in M['categoricalFeatures']),fitRows=len(fit['trainIDs']),medianExact=exact(v),medianApprox=approx(v),unit=M['featureUnits'][j]))\n  for key,(mass,pos)in fit['cells'].items():tables['fit-cells'].append(dict(kind=kind,cell='|'.join(map(str,key)),trainingRows=mass,positiveRows=pos,probabilityExact=exact(fit['probabilities'][key]),probabilityApprox=approx(fit['probabilities'][key]),fallbackExact=exact(fit['fallback']),fallbackApprox=approx(fit['fallback'])))\n  for j,p in enumerate(cv['points']):\n   policy=p['policy'];tables['test-curves'].append(dict(kind=kind,point=j,policy=policy if isinstance(policy,str)else'threshold',thresholdExact=''if isinstance(policy,str)else exact(policy),thresholdApprox=''if isinstance(policy,str)else approx(policy),**scalar_fields(p,['TP','FP','FN','TN','TPR','FPR','precision','recall'])))\n   point(kind,'roc','ROC',j,p['FPR'],p['TPR']);point(kind,'pr','PR-observed',j,p['recall'],p['precision'])\n  for b in cal['bins']:\n   tables['calibration-bins'].append(dict(kind=kind,bin=b['index'],leftExact=str(F(b['index'],5)),rightExact=str(F(b['index']+1,5)),rightClosed=int(b['index']==4),rows=b['rows'],ids=';'.join(str(i)for i in b['ids']),**scalar_fields(b,['mass','meanPrediction','eventRate','gap','absoluteGap','scoreVariance','scoreTargetCovariance','withinBinCorrection'])))\n   point(kind,'reliability','Binary event rate',b['index'],b['meanPrediction'],b['eventRate'],tag='rows='+str(b['rows']))\n  for j,r in enumerate(test):\n   point(kind,'test-scores','Training-fitted probability',j,F(j+1),r['score'],'test-row position','probability',tag=r['id'])\n   point(kind,'test-scores','Observed Y',j,F(j+1),r['y'],'test-row position','binary target',tag=r['id'])\n  for name,fp,fn in SCENARIOS:\n   choice=choose(rr,{},(fp,fn));gm=groups(test,choice['selectedPolicy'],(fp,fn));scenarios.append(dict(name=name,costs=dict(falsePositive=fp,falseNegative=fn),selection=choice,groups=gm));ev=choice['evaluation']\n   for c in choice['candidates']:\n    policy=c['policy'];mm=c['metrics'];tables['validation-candidates'].append(dict(kind=kind,scenario=name,candidate=c['index'],selected=int(c['index']==choice['selectedIndex']),policy=policy if isinstance(policy,str)else'threshold',thresholdExact=''if isinstance(policy,str)else exact(policy),thresholdApprox=''if isinstance(policy,str)else approx(policy),feasible=int(c['feasible']),reasons=';'.join(c['reasons']),**{k+'Exact':str(v)for k,v in mm['confusion'].items()},**scalar_fields(mm,COUNTS+['TPR','FPR','precision','meanCost','totalCost'])))\n    point(kind,'validation-cost',name,c['index'],F(c['index']),mm['meanCost'],'candidate index','hypothetical cost units/mass','validation',tag=exact(policy))\n   mm={**ev,**ev['confusion'],**{k:cv[k]for k in ['ROC_AUC','averagePrecision','PRTrapezoidWithInitialPrecisionOne']},**{k:cal[k]for k in ['ECE','reliability','resolution','uncertainty','withinBinCorrection','BrierIdentityResidual']}}\n   for key in ['TP','FP','FN','TN']+COUNTS+RATES+['ROC_AUC','averagePrecision','PRTrapezoidWithInitialPrecisionOne','ECE','reliability','resolution','uncertainty','withinBinCorrection','BrierIdentityResidual']:\n    unit='rows'if key in ['TP','FP','FN','TN']+COUNTS else'hypothetical cost units'if key=='totalCost'else'hypothetical cost units/mass'if key=='meanCost'else'sum squared-probability loss'if key=='BrierSum'else'dimensionless'\n    tables['test-metrics'].append(dict(kind=kind,scenario=name,metric=key,valueExact=exact(mm[key]),valueApprox=approx(mm[key]),unit=unit))\n   allg=[('overall','all',gm['overall'])]+[('known',str(g['group']),g['metrics'])for g in gm['groups']]+[('unknown','',gm['unknownGroup'])]\n   for j,(typ,token,g)in enumerate(allg):\n    tables['group-metrics'].append(dict(kind=kind,scenario=name,groupType=typ,groupToken=token,retainedRows=g.get('retainedRows',sum((r['group']==token)if typ=='known'else(r['group']is None)if typ=='unknown'else True for r in test)),**{k+'Exact':str(v)for k,v in g['confusion'].items()},**scalar_fields(g,COUNTS+RATES)))\n    if typ=='known':point(kind,'group-TPR',name,j-1,F(j-1),g['TPR'],'declared group position','TPR',tag=token)\n  studies[kind]=dict(kind=kind,rows=len(native),eligibleRows=sum(r['eligible']for r in rr),trainingIDs=fit['trainIDs'],fitMedians=fit['medians'],fitCells=[dict(cell=list(k),mass=n,positive=s,probability=fit['probabilities'][k])for k,(n,s)in fit['cells'].items()],fallback=fit['fallback'],scenarios=scenarios,testCurves=cv,testCalibration=cal,rowsScored=rr)\n files=[]\n for name,rows in tables.items():\n  p=out/('computed-'+name+'.csv')\n  with p.open('w',encoding='utf8',newline='')as f:w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows)\n  files.append(dict(file=p.name,rows=len(rows),columns=len(rows[0]),bodyFields=len(rows)*len(rows[0]),sha256=hashlib.sha256(p.read_bytes()).hexdigest()))\n (out/'study.json').write_text(json.dumps(packed(studies),ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\n sourceFiles=[source/n for n in ['actual64-country-four-indicators-original-2024.csv','actual3613-NLS-original52-fields-groups-roles.csv','actual3150-churn-original14-fields-groups-roles.csv']]\n provenance=dict(chapter='ML-14',arithmetic='Python stdlib Fraction exact finite values from original decimal strings; binary64 valueApprox is display only.',inputs=[dict(file=p.name,sha256=hashlib.sha256(p.read_bytes()).hexdigest())for p in sourceFiles],priorEngineModelsScoresOrComputedFilesRead=False,roleRule=\"SHA256('ML14-role|'+kind+'|'+ID),rankmod5=0test/1validation/others train before eligibility\",costs='Hypothetical1/1,1/5,5/1; no causal intervention returns',files=files,observations={k:dict(sourceRows=v['rows'],eligibleRows=v['eligibleRows'],trainingRows=len(v['trainingIDs']))for k,v in studies.items()})\n (out/'provenance.json').write_text(json.dumps(provenance,ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\n print(json.dumps(dict(status='PASS standalone completed',files=len(files),bodyFields=sum(f['bodyFields']for f in files),observations=provenance['observations'])))\n\n# Fixed declared examples: full web budget/option validation is not reproduced.\nfrom html import escape\nimport textwrap\ndef validated_rows(raw):\n for r in raw:\n  assert F(str(r.get('weight','1')))>=0,'negative analytical mass'\n  assert r['score']is None or 0<=F(str(r['score']))<=1,'score outside zero/one'\n  assert r['y']is None or F(str(int(r['y']))if isinstance(r['y'],bool)else str(r['y']))in [0,1],'binary target required'\n return read(raw)\ndef serial(v):\n if isinstance(v,F):return dict(exactFraction=str(v),value=float(v))\n if isinstance(v,(list,tuple)):return[serial(x)for x in v]\n if isinstance(v,dict):return{k:serial(x)for k,x in v.items()}\n return v\ndef fixed_svg(path,points,title,xlabel,ylabel,legend):\n use=[p for p in points if p['xExact']!=''and p['yExact']!=''];xs=[float(F(p['xExact']))for p in use];ys=[float(F(p['yExact']))for p in use]\n xmin=min(xs,default=0);xmax=max(xs,default=1);ymin=min([0]+ys);ymax=max([0]+ys)\n if xmin==xmax:xmin-=.5;xmax+=.5\n if ymin==ymax:ymax=ymin+1\n X=lambda v:85+(float(v)-xmin)/(xmax-xmin)*480;Y=lambda v:278-(float(v)-ymin)/(ymax-ymin)*175\n s='<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"620\" height=\"360\" viewBox=\"0 0 620 360\"><rect width=\"620\" height=\"360\" fill=\"white\"/><g font-family=\"Arial, sans-serif\" font-size=\"13\" fill=\"#17324d\">'\n for i,line in enumerate(textwrap.wrap(title,width=65)):s+='<text x=\"25\" y=\"'+str(24+i*18)+'\">'+escape(line)+'</text>'\n colors=['#176b9b','#b85e18','#437e4d']\n for i,label in enumerate(legend):s+='<circle cx=\"'+str(30+i*250)+'\" cy=\"76\" r=\"4\" fill=\"'+colors[i%3]+'\"/><text x=\"'+str(42+i*250)+'\" y=\"80\">'+escape(label)+'</text>'\n s+='<path d=\"M85 98V278H575\" fill=\"none\" stroke=\"#52677d\"/><text text-anchor=\"middle\" x=\"325\" y=\"338\">'+escape(xlabel)+'</text><text text-anchor=\"middle\" transform=\"translate(21,190) rotate(-90)\">'+escape(ylabel)+'</text>'\n for i in range(5):\n  xx=xmin+(xmax-xmin)*i/4;yy=ymin+(ymax-ymin)*i/4;s+='<text text-anchor=\"middle\" x=\"'+format(X(xx),'.9g')+'\" y=\"305\">'+format(xx,'.4g')+'</text><text text-anchor=\"end\" x=\"77\" y=\"'+format(Y(yy)+4,'.9g')+'\">'+format(yy,'.4g')+'</text>'\n for p in use:s+='<circle cx=\"'+format(X(F(p['xExact'])),'.9g')+'\" cy=\"'+format(Y(F(p['yExact'])),'.9g')+'\" r=\"3\" fill=\"'+colors[p['series']%3]+'\"/>'\n path.write_text(s+'</g></svg>',encoding='utf8')\ndef fixed_run():\n ap=argparse.ArgumentParser();ap.add_argument('--out',type=Path,default=Path('results'));ap.add_argument('--data-dir',type=Path,default=Path(__file__).resolve().parent.parent/'ml14-sources');args=ap.parse_args();args.out.mkdir(parents=True,exist_ok=True)\n api=FIXED['api'];a=FIXED['args'];summary=[];points=[];xlabel='Declared index';ylabel='Value';legend=['Declared result']\n def metric(name,v,unit='dimensionless'):\n  q=None if v is None else v if isinstance(v,F)else F(v);summary.append(dict(metric=name,value='undefined'if q is None else format(float(q),'.9g'),exactValue=''if q is None else str(q),unit=unit,defined=int(q is not None)))\n def pt(i,x,y,ident='',series=0):\n  points.append(dict(series=series,index=i,xExact=''if x is None else str(F(x)),x='undefined'if x is None else format(float(x),'.9g'),yExact=''if y is None else str(F(y)),y='undefined'if y is None else format(float(y),'.9g'),id=str(ident)))\n if api=='realdata':\n  models=load_sources(args.data_dir);model=models[a['kind']];fit=actual_model(model);rr=fit['rows'];test=scoped(rr,'test');scenarios=[]\n  for name,fp,fn in SCENARIOS:\n   c=choose(rr,{},(fp,fn));scenarios.append(dict(name=name,selection=c));metric(name+'Threshold',c['selectedPolicy']);metric(name+'TestCost',c['evaluation']['meanCost'],'hypothetical cost units/mass')\n  cv=curves(test);cal=calibrate(test,[F(0),F(1,5),F(2,5),F(3,5),F(4,5),F(1)]);metric('testAUC',cv['ROC_AUC']);metric('testAP',cv['averagePrecision']);metric('testBrier',cal['Brier']);metric('eligibleRows',sum(r['eligible']for r in rr),'rows')\n  for i,r in enumerate(test):pt(i,i+1,r['score'],r['id'],0);pt(i,i+1,r['y'],r['id'],1)\n  full=dict(kind=a['kind'],fitMedians=fit['medians'],fitCells=[dict(cell=list(k),mass=n,positive=s,probability=fit['probabilities'][k])for k,(n,s)in fit['cells'].items()],rowsScored=rr,scenarios=scenarios,testCurves=cv,testCalibration=cal);xlabel='Test row, native order';ylabel='Y or probability';legend=['Training-fitted probability','Observed Y']\n else:\n  rr=validated_rows(a['rows']);role=a.get('role','all');frame=scoped(rr,role);cc=cost(a.get('costs'));t=policy(a.get('threshold','1/2'))\n  if api=='metrics':\n   full=metrics(frame,t,cc)\n   for k in ['mass','accuracy','precision','TPR','FPR','F1','Brier','meanCost']:metric(k,full[k],'mass'if k=='mass'else'hypothetical cost units/mass'if k=='meanCost'else'dimensionless')\n   metric('BayesThreshold',full['bayesThreshold'])\n   for i,k in enumerate(['TP','FP','FN','TN']):pt(i,i,full['confusion'][k],k)\n   xlabel='TP / FP / FN / TN positions';ylabel='Analytical mass'\n  elif api=='curves':\n   full=curves(frame)\n   for k in ['ROC_AUC','averagePrecision','PRTrapezoidWithInitialPrecisionOne']:metric(k,full[k])\n   for i,p in enumerate(full['points']):pt(i,p['FPR'],p['TPR'],str(p['policy']))\n   xlabel='False positive rate';ylabel='True positive rate';legend=['Observed ROC operating points']\n  elif api=='choose':\n   full=choose(rr,a,cc);metric('selectedIndex',full['selectedIndex'],'candidate index');metric('minimumCost',None if full['selectedValidation']is None else full['selectedValidation']['meanCost'],'hypothetical cost units/mass');metric('feasible',int(full['selectedIndex']is not None),'indicator')\n   for c in full['candidates']:pt(c['index'],c['index'],c['metrics']['meanCost'],str(c['policy']))\n   xlabel='Validation candidate';ylabel='Assumed cost / mass';legend=['Validation candidate costs']\n  elif api=='calibrate':\n   full=calibrate(frame,[F(str(e))for e in a.get('binEdges',['0','1/5','2/5','3/5','4/5','1'])])\n   for k in ['ECE','Brier','uncertainty','resolution','reliability','withinBinCorrection','BrierIdentityResidual']:metric(k,full[k])\n   for b in full['bins']:pt(b['index'],b['meanPrediction'],b['eventRate'],'bin:'+str(b['index']))\n   xlabel='Bin mean forecast';ylabel='Bin event rate';legend=['Binary-event reliability']\n  elif api=='groups':\n   full=groups(frame,t,cc);metric('overallTPR',full['overall']['TPR']);metric('TPRGap',full['gaps']['TPR']['value']);metric('precisionGap',full['gaps']['precision']['value']);metric('unknownMass',full['unknownGroup']['mass'],'mass');metric('partitionResidual',full['partitionMassResidual'],'mass')\n   for i,g in enumerate(full['groups']):pt(i,i,g['metrics']['TPR'],str(g['group']))\n   xlabel='Declared group position';ylabel='True positive rate';legend=['Known-group TPR']\n  else:raise ValueError('unknown fixed API')\n def csvout(name,rows):\n  with(args.out/name).open('w',encoding='utf8',newline='')as f:w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows)\n csvout('summary.csv',summary);csvout('plot-points.csv',points);fixed_svg(args.out/'plot.svg',points,FIXED['title'],xlabel,ylabel,legend)\n (args.out/'full.json').write_text(json.dumps(dict(api=api,variant=FIXED['variant'],input=FIXED['args'],arithmetic='Python standard-library Fraction, declared fixed example; full web validator/budgets not reproduced',result=serial(full)),ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\n print(json.dumps(dict(api=api,variant=FIXED['variant'],summaryMetrics=len(summary),plotSlots=len(points))))\n\nFIXED={'api': 'realdata', 'variant': 'company', 'args': {'kind': 'company'}, 'title': 'Actual company fixed train/validation/test procedure'}\nif __name__=='__main__':fixed_run()\n",
        "codeText": "#!/usr/bin/env python3\n\"\"\"ML14 standalone exact finite study, Python standard library only.\nInputs: only the three retained factual source CSVs below.\nDerived role/target/group/eligibility columns in those CSVs are NOT inputs.\nRebuilds SHA256 roles, train-only medians/cell scores, validation thresholds,\ntest curves, binary-event reliability and descriptive group ledgers.\nCosts 1/1,1/5,5/1 are hypothetical units, not measured intervention returns.\nThis is author public reproduction, not independent scientific review.\n\"\"\"\n\"\"\"Author Fraction reference, separate from product JavaScript; not independent peer.\"\"\"\nfrom fractions import Fraction as F\nfrom collections import Counter,defaultdict\ndef read(raw):\n rows=[]\n for i,r in enumerate(raw):\n  s=None if r['score']is None else F(str(r['score']));y=None if r['y']is None else F(int(r['y']))if isinstance(r['y'],bool)else F(str(r['y']));w=F(str(r.get('weight','1')));role=r.get('role','evaluation')\n  rows.append(dict(id=r['id'],index=i,score=s,y=y,w=w,role=role,group=r.get('group'),eligible=s is not None and y is not None and w>0 and role!='excluded'))\n return rows\ndef scoped(rows,role='all'):return rows if role=='all'else[r for r in rows if r['role']==role]\ndef divide(n,d):return None if not d else n/d\ndef policy(v):return v if v in ['always-negative','always-positive']else F(str(v))\ndef positive(p,s):return p=='always-positive'if isinstance(p,str)else s>=p\ndef cost(a=None):\n a={}if a is None else a;fp=F(str(a.get('falsePositive','1')));fn=F(str(a.get('falseNegative','1')));return fp,fn\ndef metrics(rows,threshold=F(1,2),cc=(F(1),F(1))):\n counts=dict(TP=F(0),FP=F(0),FN=F(0),TN=F(0));brier=F(0);pred=[]\n for r in rows:\n  if not r['eligible']:pred.append(dict(id=r['id'],index=r['index'],eligible=False,decision=None,probability=None,Brier=None));continue\n  yes=positive(threshold,r['score']);cell=('T'if yes==bool(r['y'])else'F')+('P'if yes else'N');counts[cell]+=r['w'];loss=(r['score']-r['y'])**2;brier+=r['w']*loss;pred.append(dict(id=r['id'],index=r['index'],eligible=True,decision=int(yes),probability=r['score'],Brier=loss))\n TP,FP,FN,TN=[counts[k]for k in ['TP','FP','FN','TN']];P=TP+FN;N=TN+FP;mass=P+N;PP=TP+FP;PN=TN+FN;TPR=divide(TP,P);TNR=divide(TN,N);total=FP*cc[0]+FN*cc[1]\n return dict(confusion=counts,mass=mass,positiveTargetMass=P,negativeTargetMass=N,predictedPositiveMass=PP,predictedNegativeMass=PN,prevalence=divide(P,mass),selectionRate=divide(PP,mass),accuracy=divide(TP+TN,mass),precision=divide(TP,PP),negativePredictiveValue=divide(TN,PN),TPR=TPR,FPR=divide(FP,N),TNR=TNR,FNR=divide(FN,P),F1=divide(2*TP,2*TP+FP+FN),balancedAccuracy=None if TPR is None or TNR is None else(TPR+TNR)/2,Brier=divide(brier,mass),BrierSum=brier,totalCost=total,meanCost=divide(total,mass),predictions=pred,bayesThreshold=divide(cc[0],sum(cc)))\ndef curves(rows):\n use=[r for r in rows if r['eligible']];pos=Counter();neg=Counter()\n for r in use:(pos if r['y']else neg)[r['score']]+=r['w']\n P=sum(pos.values(),F(0));N=sum(neg.values(),F(0));pairs=F(0)\n for a,wa in pos.items():\n  for b,wb in neg.items():pairs+=wa*wb*(F(1)if a>b else F(1,2)if a==b else F(0))\n thresholds=['always-negative']+sorted({r['score']for r in use},reverse=True);points=[];AP=F(0);trap=F(0);lastR=F(0);lastP=F(1)\n for i,p in enumerate(thresholds):\n  m=metrics(rows,p);points.append(dict(policy=p,TP=m['confusion']['TP'],FP=m['confusion']['FP'],FN=m['confusion']['FN'],TN=m['confusion']['TN'],TPR=m['TPR'],FPR=m['FPR'],precision=m['precision'],recall=m['TPR']))\n  if i and P:\n   R=m['TPR'];PP=m['precision'];AP+=(R-lastR)*PP;trap+=(R-lastR)*(PP+lastP)/2;lastR=R;lastP=PP\n return dict(positiveMass=P,negativeMass=N,ROC_AUC=divide(pairs,P*N),weightedConcordantPlusHalfTiedMass=pairs,averagePrecision=AP if P else None,PRTrapezoidWithInitialPrecisionOne=trap if P else None,points=points)\ndef choose(rows,a,cc):\n sr=a.get('selectionRole','validation');er=a.get('evaluationRole','test');rr=scoped(rows,sr);thresholds=[policy(t)for t in a['thresholds']]if'thresholds'in a else['always-negative']+sorted({r['score']for r in rr if r['eligible']},reverse=True)\n candidates=[]\n for i,p in enumerate(thresholds):\n  m=metrics(rr,p,cc);reasons=[]\n  if'minTPR'in a and(m['TPR']is None or m['TPR']<F(str(a['minTPR']))):reasons.append('TPR-undefined'if m['TPR']is None else'below-minTPR')\n  if'maxFPR'in a and(m['FPR']is None or m['FPR']>F(str(a['maxFPR']))):reasons.append('FPR-undefined'if m['FPR']is None else'above-maxFPR')\n  candidates.append(dict(index=i,policy=p,metrics=m,feasible=not reasons,reasons=reasons))\n eligible=[c for c in candidates if c['feasible']];best=min(eligible,key=lambda c:(c['metrics']['meanCost'],c['index']))if eligible else None\n return dict(selectedIndex=None if best is None else best['index'],selectedPolicy=None if best is None else best['policy'],candidates=candidates,selectedValidation=None if best is None else best['metrics'],evaluation=None if best is None or er=='none'else metrics(scoped(rows,er),best['policy'],cc),selectionIDs=[r['id']for r in rr if r['eligible']])\ndef calibrate(rows,ee):\n buckets=[[]for _ in range(len(ee)-1)]\n for r in rows:\n  if not r['eligible']:continue\n  j=next((i for i in range(len(ee)-1)if r['score']<ee[i+1]),len(ee)-2);buckets[j].append(r)\n mass=sum((r['w']for r in rows if r['eligible']),F(0));P=sum((r['w']*r['y']for r in rows if r['eligible']),F(0));pi=divide(P,mass);Brier=None if not mass else sum((r['w']*(r['score']-r['y'])**2 for r in rows if r['eligible']),F(0))/mass;ECE=F(0);reliability=F(0);resolution=F(0);correction=F(0);bins=[]\n for i,rr in enumerate(buckets):\n  w=sum((r['w']for r in rr),F(0));mp=None if not w else sum((r['w']*r['score']for r in rr),F(0))/w;o=None if not w else sum((r['w']*r['y']for r in rr),F(0))/w\n  variance=None if not w else sum((r['w']*(r['score']-mp)**2 for r in rr),F(0))/w\n  covariance=None if not w else sum((r['w']*(r['score']-mp)*(r['y']-o)for r in rr),F(0))/w\n  bc=None if not w else variance-2*covariance;gap=None if not w else mp-o\n  bins.append(dict(index=i,rows=len(rr),mass=w,meanPrediction=mp,eventRate=o,gap=gap,absoluteGap=None if gap is None else abs(gap),scoreVariance=variance,scoreTargetCovariance=covariance,withinBinCorrection=bc,ids=[r['id']for r in rr]))\n  if w:\n   share=w/mass;ECE+=share*abs(gap);reliability+=share*gap**2;resolution+=share*(o-pi)**2;correction+=share*bc\n uncertainty=None if pi is None else pi*(1-pi);residual=None if Brier is None else Brier-(uncertainty-resolution+reliability+correction)\n return dict(mass=mass,prevalence=pi,Brier=Brier,ECE=ECE if mass else None,reliability=reliability if mass else None,resolution=resolution if mass else None,uncertainty=uncertainty,withinBinCorrection=correction if mass else None,BrierIdentityResidual=residual,bins=bins)\ndef typed(v):return type(v).__name__,v\ndef groups(rows,p,cc):\n bins={}\n for r in rows:\n  if r['group']is not None:bins.setdefault(typed(r['group']),[]).append(r)\n gm=[dict(group=rr[0]['group'],metrics=metrics(rr,p,cc))for rr in bins.values()];overall=metrics(rows,p,cc);unknown=metrics([r for r in rows if r['group']is None],p,cc);gaps={}\n for key in ['prevalence','selectionRate','TPR','FPR','precision','accuracy','meanCost']:\n  positive=[g for g in gm if g['metrics']['mass']>0];undefined=[g['group']for g in positive if g['metrics'][key]is None];vals=[g['metrics'][key]for g in positive if g['metrics'][key]is not None]\n  gaps[key]=dict(value=None if len(positive)<2 or undefined else max(vals)-min(vals),undefinedGroups=undefined,comparedPositiveMassGroups=[g['group']for g in positive])\n return dict(overall=overall,groups=gm,unknownGroup=unknown,gaps=gaps,partitionMassResidual=overall['mass']-unknown['mass']-sum((g['metrics']['mass']for g in gm),F(0)))\ndef actual_model(M):\n raw=M['records'];cat=M['categoricalFeatures'];p=len(raw[0]['x']);train=[r for r in raw if r['role']=='train'];medians=[]\n for j in range(p):\n  if j in cat:medians.append(None);continue\n  values=sorted(F(r['x'][j])for r in train);n=len(values);medians.append(values[n//2]if n%2 else(values[n//2-1]+values[n//2])/2)\n def transform(r):return[F(v)if j in cat else F(int(F(v)>medians[j]))for j,v in enumerate(r['x'])]\n counts={}\n for r in train:\n  key=tuple(transform(r));n,s=counts.get(key,(0,0));counts[key]=(n+1,s+int(r['y']))\n probabilities={k:F(s+1,n+2)for k,(n,s)in counts.items()};fallback=F(sum(int(r['y'])for r in train)+1,len(train)+2);scored=[]\n for i,r in enumerate(raw):\n  eligible=r['role']!='excluded';z=transform(r)if eligible else None;key=None if z is None else tuple(z);score=None if not eligible else probabilities.get(key,fallback)\n  scored.append(dict(id=r['id'],index=i,role=r['role'],group=r['group'],y=None if r['y']is None else F(r['y']),score=score,w=F(1),eligible=eligible,transformedX=z,unseenCell=None if not eligible else key not in probabilities))\n return dict(medians=medians,cells=counts,probabilities=probabilities,fallback=fallback,rows=scored,trainIDs=[r['id']for r in train])\n\n\nimport csv,json,hashlib,argparse,datetime\nfrom pathlib import Path\ndef missing(v):return None if v in ['', '.',None]else v\ndef load_sources(folder):\n def read_csv(name):\n  with (folder/name).open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))\n wb=read_csv('actual64-country-four-indicators-original-2024.csv')\n codes=['NY.GDP.PCAP.KD','NY.GDP.MKTP.KD.ZG','FP.CPI.TOTL.ZG','SP.DYN.LE00.IN']\n lookup={(r['countryISO3'],r['indicatorID']):r for r in wb};country=[]\n for i,iso in enumerate(sorted({r['countryISO3']for r in wb}),1):\n  native=[lookup[iso,c]for c in codes];v=[missing(r['originalValueToken'])for r in native]\n  country.append(dict(id=iso+':2024',sourceRow=i,originalID=iso,x=v[:3],y=None if v[3]is None else str(int(F(v[3])>=80)),group=None if v[0]is None else str(int(F(v[0])>=25000)),nativeTarget=v[3],nativeSourceRows=';'.join(r['sourceRow']for r in native)))\n nls=read_csv('actual3613-NLS-original52-fields-groups-roles.csv');person=[]\n for r in nls:\n  y=missing(r['wage76']);person.append(dict(id='person:'+r['sourceRow'],sourceRow=int(r['sourceRow']),originalID=r['id'],x=[missing(r[k])for k in ['ed76','age76','nearc4']],y=None if y is None else str(int(F(y)>=500)),group=missing(r['black']),nativeTarget=y,nativeSourceRows=r['sourceRow']))\n ch=read_csv('actual3150-churn-original14-fields-groups-roles.csv');company=[]\n for r in ch:\n  company.append(dict(id='customer:'+r['sourceRow'],sourceRow=int(r['sourceRow']),originalID='',x=[missing(r[k])for k in ['Call  Failure','Complains','Subscription  Length','Seconds of Use']],y=missing(r['Churn']),group=missing(r['Tariff Plan']),nativeTarget=missing(r['Churn']),nativeSourceRows=r['sourceRow']))\n assert len(wb)==64 and len(country)==16 and len(nls)==3613 and len(ch)==3150\n assert [int(r['sourceRow'])for r in ch if r['Charge  Amount']=='10']==[474,2174,2274,2374,2674,2924,2974]\n models={}\n for kind,raw,cat,units in [('country',country,[],['constant2015USD/person','annualPercent','annualPercent']),('person',person,[2],['years','years','nativeCategory']),('company',company,[1],['count','nativeCategory','months','seconds'])]:\n  order=sorted(range(len(raw)),key=lambda i:(hashlib.sha256(('ML14-role|'+kind+'|'+raw[i]['id']).encode()).hexdigest(),i))\n  for rank,i in enumerate(order):\n   r=raw[i];r['plannedRole']='test'if rank%5==0 else'validation'if rank%5==1 else'train';r['eligible']=None not in r['x']+[r['y']];r['role']=r['plannedRole']if r['eligible']else'excluded';r['weight']='1'\n  models[kind]=dict(records=raw,categoricalFeatures=cat,featureUnits=units)\n assert sum(r['eligible']for r in person)==3017\n return models\n\ndef exact(v):return ''if v is None else str(v)\ndef approx(v):return ''if v is None else format(float(v),'.17g')\ndef scalar_fields(m,keys):\n out={}\n for k in keys:\n  out[k+'Exact']=exact(m[k]);out[k+'Approx']=approx(m[k])\n return out\nCOUNTS=['mass','positiveTargetMass','negativeTargetMass','predictedPositiveMass','predictedNegativeMass']\nRATES=['prevalence','selectionRate','accuracy','precision','negativePredictiveValue','TPR','FPR','TNR','FNR','F1','balancedAccuracy','Brier','BrierSum','totalCost','meanCost']\nSCENARIOS=[('equal',F(1),F(1)),('miss-five',F(1),F(5)),('alarm-five',F(5),F(1))]\ndef packed(v):\n if isinstance(v,F):return str(v)\n if isinstance(v,dict):return{str(k):packed(x)for k,x in v.items()}\n if isinstance(v,(tuple,list)):return[packed(x)for x in v]\n return v\ndef run_study(source,out):\n out.mkdir(parents=True,exist_ok=True);models=load_sources(source)\n tables={name:[]for name in ['predictions','lineage','fit-medians','fit-cells','validation-candidates','test-metrics','test-curves','calibration-bins','group-metrics','chart-points']}\n studies={};charts=[]\n def point(kind,chart,series,index,x,y,xunit='dimensionless',yunit='dimensionless',role='test',tag=''):\n  tables['chart-points'].append(dict(kind=kind,chart=chart,series=series,index=index,xExact=exact(x),xApprox=approx(x),yExact=exact(y),yApprox=approx(y),xUnit=xunit,yUnit=yunit,role=role,tag=tag))\n for kind,M in models.items():\n  fit=actual_model(M);rr=fit['rows'];native=M['records'];test=scoped(rr,'test');cv=curves(test);cal=calibrate(test,[F(0),F(1,5),F(2,5),F(3,5),F(4,5),F(1)]);scenarios=[]\n  for i,r in enumerate(rr):\n   n=native[i];reason=''if r['eligible']else'required-X-or-Y-missing'\n   tables['predictions'].append(dict(kind=kind,id=r['id'],sourceRow=n['sourceRow'],originalID=n['originalID'],plannedRole=n['plannedRole'],role=r['role'],group=''if r['group']is None else r['group'],eligible=int(r['eligible']),targetExact=exact(r['y']),probabilityExact=exact(r['score']),probabilityApprox=approx(r['score']),unseenCell=''if r['unseenCell']is None else int(r['unseenCell']),transformedX=''if r['transformedX']is None else'|'.join(map(str,r['transformedX'])),reason=reason))\n   tables['lineage'].append(dict(kind=kind,id=r['id'],sourceRow=n['sourceRow'],originalID=n['originalID'],nativeSourceRows=n['nativeSourceRows'],rawX='|'.join(''if x is None else x for x in n['x']),nativeTarget=''if n['nativeTarget']is None else n['nativeTarget'],derivedTarget=exact(r['y']),nativeGroup=''if n['group']is None else n['group'],plannedRole=n['plannedRole'],role=r['role'],eligible=int(r['eligible']),analyticalMass='1',reason=reason))\n  for j,v in enumerate(fit['medians']):tables['fit-medians'].append(dict(kind=kind,feature=j,categorical=int(j in M['categoricalFeatures']),fitRows=len(fit['trainIDs']),medianExact=exact(v),medianApprox=approx(v),unit=M['featureUnits'][j]))\n  for key,(mass,pos)in fit['cells'].items():tables['fit-cells'].append(dict(kind=kind,cell='|'.join(map(str,key)),trainingRows=mass,positiveRows=pos,probabilityExact=exact(fit['probabilities'][key]),probabilityApprox=approx(fit['probabilities'][key]),fallbackExact=exact(fit['fallback']),fallbackApprox=approx(fit['fallback'])))\n  for j,p in enumerate(cv['points']):\n   policy=p['policy'];tables['test-curves'].append(dict(kind=kind,point=j,policy=policy if isinstance(policy,str)else'threshold',thresholdExact=''if isinstance(policy,str)else exact(policy),thresholdApprox=''if isinstance(policy,str)else approx(policy),**scalar_fields(p,['TP','FP','FN','TN','TPR','FPR','precision','recall'])))\n   point(kind,'roc','ROC',j,p['FPR'],p['TPR']);point(kind,'pr','PR-observed',j,p['recall'],p['precision'])\n  for b in cal['bins']:\n   tables['calibration-bins'].append(dict(kind=kind,bin=b['index'],leftExact=str(F(b['index'],5)),rightExact=str(F(b['index']+1,5)),rightClosed=int(b['index']==4),rows=b['rows'],ids=';'.join(str(i)for i in b['ids']),**scalar_fields(b,['mass','meanPrediction','eventRate','gap','absoluteGap','scoreVariance','scoreTargetCovariance','withinBinCorrection'])))\n   point(kind,'reliability','Binary event rate',b['index'],b['meanPrediction'],b['eventRate'],tag='rows='+str(b['rows']))\n  for j,r in enumerate(test):\n   point(kind,'test-scores','Training-fitted probability',j,F(j+1),r['score'],'test-row position','probability',tag=r['id'])\n   point(kind,'test-scores','Observed Y',j,F(j+1),r['y'],'test-row position','binary target',tag=r['id'])\n  for name,fp,fn in SCENARIOS:\n   choice=choose(rr,{},(fp,fn));gm=groups(test,choice['selectedPolicy'],(fp,fn));scenarios.append(dict(name=name,costs=dict(falsePositive=fp,falseNegative=fn),selection=choice,groups=gm));ev=choice['evaluation']\n   for c in choice['candidates']:\n    policy=c['policy'];mm=c['metrics'];tables['validation-candidates'].append(dict(kind=kind,scenario=name,candidate=c['index'],selected=int(c['index']==choice['selectedIndex']),policy=policy if isinstance(policy,str)else'threshold',thresholdExact=''if isinstance(policy,str)else exact(policy),thresholdApprox=''if isinstance(policy,str)else approx(policy),feasible=int(c['feasible']),reasons=';'.join(c['reasons']),**{k+'Exact':str(v)for k,v in mm['confusion'].items()},**scalar_fields(mm,COUNTS+['TPR','FPR','precision','meanCost','totalCost'])))\n    point(kind,'validation-cost',name,c['index'],F(c['index']),mm['meanCost'],'candidate index','hypothetical cost units/mass','validation',tag=exact(policy))\n   mm={**ev,**ev['confusion'],**{k:cv[k]for k in ['ROC_AUC','averagePrecision','PRTrapezoidWithInitialPrecisionOne']},**{k:cal[k]for k in ['ECE','reliability','resolution','uncertainty','withinBinCorrection','BrierIdentityResidual']}}\n   for key in ['TP','FP','FN','TN']+COUNTS+RATES+['ROC_AUC','averagePrecision','PRTrapezoidWithInitialPrecisionOne','ECE','reliability','resolution','uncertainty','withinBinCorrection','BrierIdentityResidual']:\n    unit='rows'if key in ['TP','FP','FN','TN']+COUNTS else'hypothetical cost units'if key=='totalCost'else'hypothetical cost units/mass'if key=='meanCost'else'sum squared-probability loss'if key=='BrierSum'else'dimensionless'\n    tables['test-metrics'].append(dict(kind=kind,scenario=name,metric=key,valueExact=exact(mm[key]),valueApprox=approx(mm[key]),unit=unit))\n   allg=[('overall','all',gm['overall'])]+[('known',str(g['group']),g['metrics'])for g in gm['groups']]+[('unknown','',gm['unknownGroup'])]\n   for j,(typ,token,g)in enumerate(allg):\n    tables['group-metrics'].append(dict(kind=kind,scenario=name,groupType=typ,groupToken=token,retainedRows=g.get('retainedRows',sum((r['group']==token)if typ=='known'else(r['group']is None)if typ=='unknown'else True for r in test)),**{k+'Exact':str(v)for k,v in g['confusion'].items()},**scalar_fields(g,COUNTS+RATES)))\n    if typ=='known':point(kind,'group-TPR',name,j-1,F(j-1),g['TPR'],'declared group position','TPR',tag=token)\n  studies[kind]=dict(kind=kind,rows=len(native),eligibleRows=sum(r['eligible']for r in rr),trainingIDs=fit['trainIDs'],fitMedians=fit['medians'],fitCells=[dict(cell=list(k),mass=n,positive=s,probability=fit['probabilities'][k])for k,(n,s)in fit['cells'].items()],fallback=fit['fallback'],scenarios=scenarios,testCurves=cv,testCalibration=cal,rowsScored=rr)\n files=[]\n for name,rows in tables.items():\n  p=out/('computed-'+name+'.csv')\n  with p.open('w',encoding='utf8',newline='')as f:w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows)\n  files.append(dict(file=p.name,rows=len(rows),columns=len(rows[0]),bodyFields=len(rows)*len(rows[0]),sha256=hashlib.sha256(p.read_bytes()).hexdigest()))\n (out/'study.json').write_text(json.dumps(packed(studies),ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\n sourceFiles=[source/n for n in ['actual64-country-four-indicators-original-2024.csv','actual3613-NLS-original52-fields-groups-roles.csv','actual3150-churn-original14-fields-groups-roles.csv']]\n provenance=dict(chapter='ML-14',arithmetic='Python stdlib Fraction exact finite values from original decimal strings; binary64 valueApprox is display only.',inputs=[dict(file=p.name,sha256=hashlib.sha256(p.read_bytes()).hexdigest())for p in sourceFiles],priorEngineModelsScoresOrComputedFilesRead=False,roleRule=\"SHA256('ML14-role|'+kind+'|'+ID),rankmod5=0test/1validation/others train before eligibility\",costs='Hypothetical1/1,1/5,5/1; no causal intervention returns',files=files,observations={k:dict(sourceRows=v['rows'],eligibleRows=v['eligibleRows'],trainingRows=len(v['trainingIDs']))for k,v in studies.items()})\n (out/'provenance.json').write_text(json.dumps(provenance,ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\n print(json.dumps(dict(status='PASS standalone completed',files=len(files),bodyFields=sum(f['bodyFields']for f in files),observations=provenance['observations'])))\n\n# Fixed declared examples: full web budget/option validation is not reproduced.\nfrom html import escape\nimport textwrap\ndef validated_rows(raw):\n for r in raw:\n  assert F(str(r.get('weight','1')))>=0,'negative analytical mass'\n  assert r['score']is None or 0<=F(str(r['score']))<=1,'score outside zero/one'\n  assert r['y']is None or F(str(int(r['y']))if isinstance(r['y'],bool)else str(r['y']))in [0,1],'binary target required'\n return read(raw)\ndef serial(v):\n if isinstance(v,F):return dict(exactFraction=str(v),value=float(v))\n if isinstance(v,(list,tuple)):return[serial(x)for x in v]\n if isinstance(v,dict):return{k:serial(x)for k,x in v.items()}\n return v\ndef fixed_svg(path,points,title,xlabel,ylabel,legend):\n use=[p for p in points if p['xExact']!=''and p['yExact']!=''];xs=[float(F(p['xExact']))for p in use];ys=[float(F(p['yExact']))for p in use]\n xmin=min(xs,default=0);xmax=max(xs,default=1);ymin=min([0]+ys);ymax=max([0]+ys)\n if xmin==xmax:xmin-=.5;xmax+=.5\n if ymin==ymax:ymax=ymin+1\n X=lambda v:85+(float(v)-xmin)/(xmax-xmin)*480;Y=lambda v:278-(float(v)-ymin)/(ymax-ymin)*175\n s='<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"620\" height=\"360\" viewBox=\"0 0 620 360\"><rect width=\"620\" height=\"360\" fill=\"white\"/><g font-family=\"Arial, sans-serif\" font-size=\"13\" fill=\"#17324d\">'\n for i,line in enumerate(textwrap.wrap(title,width=65)):s+='<text x=\"25\" y=\"'+str(24+i*18)+'\">'+escape(line)+'</text>'\n colors=['#176b9b','#b85e18','#437e4d']\n for i,label in enumerate(legend):s+='<circle cx=\"'+str(30+i*250)+'\" cy=\"76\" r=\"4\" fill=\"'+colors[i%3]+'\"/><text x=\"'+str(42+i*250)+'\" y=\"80\">'+escape(label)+'</text>'\n s+='<path d=\"M85 98V278H575\" fill=\"none\" stroke=\"#52677d\"/><text text-anchor=\"middle\" x=\"325\" y=\"338\">'+escape(xlabel)+'</text><text text-anchor=\"middle\" transform=\"translate(21,190) rotate(-90)\">'+escape(ylabel)+'</text>'\n for i in range(5):\n  xx=xmin+(xmax-xmin)*i/4;yy=ymin+(ymax-ymin)*i/4;s+='<text text-anchor=\"middle\" x=\"'+format(X(xx),'.9g')+'\" y=\"305\">'+format(xx,'.4g')+'</text><text text-anchor=\"end\" x=\"77\" y=\"'+format(Y(yy)+4,'.9g')+'\">'+format(yy,'.4g')+'</text>'\n for p in use:s+='<circle cx=\"'+format(X(F(p['xExact'])),'.9g')+'\" cy=\"'+format(Y(F(p['yExact'])),'.9g')+'\" r=\"3\" fill=\"'+colors[p['series']%3]+'\"/>'\n path.write_text(s+'</g></svg>',encoding='utf8')\ndef fixed_run():\n ap=argparse.ArgumentParser();ap.add_argument('--out',type=Path,default=Path('results'));ap.add_argument('--data-dir',type=Path,default=Path(__file__).resolve().parent.parent/'ml14-sources');args=ap.parse_args();args.out.mkdir(parents=True,exist_ok=True)\n api=FIXED['api'];a=FIXED['args'];summary=[];points=[];xlabel='Declared index';ylabel='Value';legend=['Declared result']\n def metric(name,v,unit='dimensionless'):\n  q=None if v is None else v if isinstance(v,F)else F(v);summary.append(dict(metric=name,value='undefined'if q is None else format(float(q),'.9g'),exactValue=''if q is None else str(q),unit=unit,defined=int(q is not None)))\n def pt(i,x,y,ident='',series=0):\n  points.append(dict(series=series,index=i,xExact=''if x is None else str(F(x)),x='undefined'if x is None else format(float(x),'.9g'),yExact=''if y is None else str(F(y)),y='undefined'if y is None else format(float(y),'.9g'),id=str(ident)))\n if api=='realdata':\n  models=load_sources(args.data_dir);model=models[a['kind']];fit=actual_model(model);rr=fit['rows'];test=scoped(rr,'test');scenarios=[]\n  for name,fp,fn in SCENARIOS:\n   c=choose(rr,{},(fp,fn));scenarios.append(dict(name=name,selection=c));metric(name+'Threshold',c['selectedPolicy']);metric(name+'TestCost',c['evaluation']['meanCost'],'hypothetical cost units/mass')\n  cv=curves(test);cal=calibrate(test,[F(0),F(1,5),F(2,5),F(3,5),F(4,5),F(1)]);metric('testAUC',cv['ROC_AUC']);metric('testAP',cv['averagePrecision']);metric('testBrier',cal['Brier']);metric('eligibleRows',sum(r['eligible']for r in rr),'rows')\n  for i,r in enumerate(test):pt(i,i+1,r['score'],r['id'],0);pt(i,i+1,r['y'],r['id'],1)\n  full=dict(kind=a['kind'],fitMedians=fit['medians'],fitCells=[dict(cell=list(k),mass=n,positive=s,probability=fit['probabilities'][k])for k,(n,s)in fit['cells'].items()],rowsScored=rr,scenarios=scenarios,testCurves=cv,testCalibration=cal);xlabel='Test row, native order';ylabel='Y or probability';legend=['Training-fitted probability','Observed Y']\n else:\n  rr=validated_rows(a['rows']);role=a.get('role','all');frame=scoped(rr,role);cc=cost(a.get('costs'));t=policy(a.get('threshold','1/2'))\n  if api=='metrics':\n   full=metrics(frame,t,cc)\n   for k in ['mass','accuracy','precision','TPR','FPR','F1','Brier','meanCost']:metric(k,full[k],'mass'if k=='mass'else'hypothetical cost units/mass'if k=='meanCost'else'dimensionless')\n   metric('BayesThreshold',full['bayesThreshold'])\n   for i,k in enumerate(['TP','FP','FN','TN']):pt(i,i,full['confusion'][k],k)\n   xlabel='TP / FP / FN / TN positions';ylabel='Analytical mass'\n  elif api=='curves':\n   full=curves(frame)\n   for k in ['ROC_AUC','averagePrecision','PRTrapezoidWithInitialPrecisionOne']:metric(k,full[k])\n   for i,p in enumerate(full['points']):pt(i,p['FPR'],p['TPR'],str(p['policy']))\n   xlabel='False positive rate';ylabel='True positive rate';legend=['Observed ROC operating points']\n  elif api=='choose':\n   full=choose(rr,a,cc);metric('selectedIndex',full['selectedIndex'],'candidate index');metric('minimumCost',None if full['selectedValidation']is None else full['selectedValidation']['meanCost'],'hypothetical cost units/mass');metric('feasible',int(full['selectedIndex']is not None),'indicator')\n   for c in full['candidates']:pt(c['index'],c['index'],c['metrics']['meanCost'],str(c['policy']))\n   xlabel='Validation candidate';ylabel='Assumed cost / mass';legend=['Validation candidate costs']\n  elif api=='calibrate':\n   full=calibrate(frame,[F(str(e))for e in a.get('binEdges',['0','1/5','2/5','3/5','4/5','1'])])\n   for k in ['ECE','Brier','uncertainty','resolution','reliability','withinBinCorrection','BrierIdentityResidual']:metric(k,full[k])\n   for b in full['bins']:pt(b['index'],b['meanPrediction'],b['eventRate'],'bin:'+str(b['index']))\n   xlabel='Bin mean forecast';ylabel='Bin event rate';legend=['Binary-event reliability']\n  elif api=='groups':\n   full=groups(frame,t,cc);metric('overallTPR',full['overall']['TPR']);metric('TPRGap',full['gaps']['TPR']['value']);metric('precisionGap',full['gaps']['precision']['value']);metric('unknownMass',full['unknownGroup']['mass'],'mass');metric('partitionResidual',full['partitionMassResidual'],'mass')\n   for i,g in enumerate(full['groups']):pt(i,i,g['metrics']['TPR'],str(g['group']))\n   xlabel='Declared group position';ylabel='True positive rate';legend=['Known-group TPR']\n  else:raise ValueError('unknown fixed API')\n def csvout(name,rows):\n  with(args.out/name).open('w',encoding='utf8',newline='')as f:w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows)\n csvout('summary.csv',summary);csvout('plot-points.csv',points);fixed_svg(args.out/'plot.svg',points,FIXED['title'],xlabel,ylabel,legend)\n (args.out/'full.json').write_text(json.dumps(dict(api=api,variant=FIXED['variant'],input=FIXED['args'],arithmetic='Python standard-library Fraction, declared fixed example; full web validator/budgets not reproduced',result=serial(full)),ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\n print(json.dumps(dict(api=api,variant=FIXED['variant'],summaryMetrics=len(summary),plotSlots=len(points))))\n\nFIXED={'api': 'realdata', 'variant': 'company', 'args': {'kind': 'company'}, 'title': 'Actual company fixed train/validation/test procedure'}\nif __name__=='__main__':fixed_run()\n",
        "input": {
          "kind": "company"
        },
        "inputFiles": [
          {
            "file": "../ml14-sources/actual64-country-four-indicators-original-2024.csv",
            "sha256": "3d2b655cf807bf3ff049af187a9b7484b4e637f441f6f1925aba7acc5b0c861c"
          },
          {
            "file": "../ml14-sources/actual3613-NLS-original52-fields-groups-roles.csv",
            "sha256": "df404c3ce0336ab3ae2bfdd6b246c6e8acc058fd526ebf950dde270787bcd600"
          },
          {
            "file": "../ml14-sources/actual3150-churn-original14-fields-groups-roles.csv",
            "sha256": "d8af1f4905af8699e3ea024a6998319c82ac97b33ba1dec182391c0b30795023"
          }
        ],
        "returnCode": 0,
        "expectedFailure": false,
        "stdout": "{\"api\": \"realdata\", \"variant\": \"company\", \"summaryMetrics\": 10, \"plotSlots\": 1260}\n",
        "stderr": "",
        "summary": {
          "equalThreshold": "0.586206897",
          "equalTestCost": "0.114285714",
          "miss-fiveThreshold": "0.151785714",
          "miss-fiveTestCost": "0.482539683",
          "alarm-fiveThreshold": "0.947368421",
          "alarm-fiveTestCost": "0.142857143",
          "testAUC": "0.815066038",
          "testAP": "0.528392751",
          "testBrier": "0.0968492331",
          "eligibleRows": "3150"
        },
        "summaryRows": [
          {
            "metric": "equalThreshold",
            "value": "0.586206897",
            "exactValue": "17/29",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "equalTestCost",
            "value": "0.114285714",
            "exactValue": "4/35",
            "unit": "hypothetical cost units/mass",
            "defined": "1"
          },
          {
            "metric": "miss-fiveThreshold",
            "value": "0.151785714",
            "exactValue": "17/112",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "miss-fiveTestCost",
            "value": "0.482539683",
            "exactValue": "152/315",
            "unit": "hypothetical cost units/mass",
            "defined": "1"
          },
          {
            "metric": "alarm-fiveThreshold",
            "value": "0.947368421",
            "exactValue": "18/19",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "alarm-fiveTestCost",
            "value": "0.142857143",
            "exactValue": "1/7",
            "unit": "hypothetical cost units/mass",
            "defined": "1"
          },
          {
            "metric": "testAUC",
            "value": "0.815066038",
            "exactValue": "86397/106000",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "testAP",
            "value": "0.528392751",
            "exactValue": "980446097344243/1855525262323200",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "testBrier",
            "value": "0.0968492331",
            "exactValue": "117575189288750222525346092691872719/1214002274785803298773233054685169920",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "eligibleRows",
            "value": "3150",
            "exactValue": "3150",
            "unit": "rows",
            "defined": "1"
          }
        ],
        "plotPoints": [
          {
            "series": "0",
            "index": "0",
            "xExact": "1",
            "x": "1",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:1"
          },
          {
            "series": "1",
            "index": "0",
            "xExact": "1",
            "x": "1",
            "yExact": "0",
            "y": "0",
            "id": "customer:1"
          },
          {
            "series": "0",
            "index": "1",
            "xExact": "2",
            "x": "2",
            "yExact": "43/218",
            "y": "0.197247706",
            "id": "customer:7"
          },
          {
            "series": "1",
            "index": "1",
            "xExact": "2",
            "x": "2",
            "yExact": "0",
            "y": "0",
            "id": "customer:7"
          },
          {
            "series": "0",
            "index": "2",
            "xExact": "3",
            "x": "3",
            "yExact": "43/218",
            "y": "0.197247706",
            "id": "customer:19"
          },
          {
            "series": "1",
            "index": "2",
            "xExact": "3",
            "x": "3",
            "yExact": "1",
            "y": "1",
            "id": "customer:19"
          },
          {
            "series": "0",
            "index": "3",
            "xExact": "4",
            "x": "4",
            "yExact": "2/53",
            "y": "0.0377358491",
            "id": "customer:27"
          },
          {
            "series": "1",
            "index": "3",
            "xExact": "4",
            "x": "4",
            "yExact": "1",
            "y": "1",
            "id": "customer:27"
          },
          {
            "series": "0",
            "index": "4",
            "xExact": "5",
            "x": "5",
            "yExact": "17/29",
            "y": "0.586206897",
            "id": "customer:28"
          },
          {
            "series": "1",
            "index": "4",
            "xExact": "5",
            "x": "5",
            "yExact": "1",
            "y": "1",
            "id": "customer:28"
          },
          {
            "series": "0",
            "index": "5",
            "xExact": "6",
            "x": "6",
            "yExact": "43/218",
            "y": "0.197247706",
            "id": "customer:29"
          },
          {
            "series": "1",
            "index": "5",
            "xExact": "6",
            "x": "6",
            "yExact": "1",
            "y": "1",
            "id": "customer:29"
          },
          {
            "series": "0",
            "index": "6",
            "xExact": "7",
            "x": "7",
            "yExact": "43/218",
            "y": "0.197247706",
            "id": "customer:38"
          },
          {
            "series": "1",
            "index": "6",
            "xExact": "7",
            "x": "7",
            "yExact": "0",
            "y": "0",
            "id": "customer:38"
          },
          {
            "series": "0",
            "index": "7",
            "xExact": "8",
            "x": "8",
            "yExact": "3/205",
            "y": "0.0146341463",
            "id": "customer:44"
          },
          {
            "series": "1",
            "index": "7",
            "xExact": "8",
            "x": "8",
            "yExact": "0",
            "y": "0",
            "id": "customer:44"
          },
          {
            "series": "0",
            "index": "8",
            "xExact": "9",
            "x": "9",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:45"
          },
          {
            "series": "1",
            "index": "8",
            "xExact": "9",
            "x": "9",
            "yExact": "0",
            "y": "0",
            "id": "customer:45"
          },
          {
            "series": "0",
            "index": "9",
            "xExact": "10",
            "x": "10",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:54"
          },
          {
            "series": "1",
            "index": "9",
            "xExact": "10",
            "x": "10",
            "yExact": "0",
            "y": "0",
            "id": "customer:54"
          },
          {
            "series": "0",
            "index": "10",
            "xExact": "11",
            "x": "11",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:60"
          },
          {
            "series": "1",
            "index": "10",
            "xExact": "11",
            "x": "11",
            "yExact": "0",
            "y": "0",
            "id": "customer:60"
          },
          {
            "series": "0",
            "index": "11",
            "xExact": "12",
            "x": "12",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:63"
          },
          {
            "series": "1",
            "index": "11",
            "xExact": "12",
            "x": "12",
            "yExact": "0",
            "y": "0",
            "id": "customer:63"
          },
          {
            "series": "0",
            "index": "12",
            "xExact": "13",
            "x": "13",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:65"
          },
          {
            "series": "1",
            "index": "12",
            "xExact": "13",
            "x": "13",
            "yExact": "0",
            "y": "0",
            "id": "customer:65"
          },
          {
            "series": "0",
            "index": "13",
            "xExact": "14",
            "x": "14",
            "yExact": "43/218",
            "y": "0.197247706",
            "id": "customer:82"
          },
          {
            "series": "1",
            "index": "13",
            "xExact": "14",
            "x": "14",
            "yExact": "1",
            "y": "1",
            "id": "customer:82"
          },
          {
            "series": "0",
            "index": "14",
            "xExact": "15",
            "x": "15",
            "yExact": "43/218",
            "y": "0.197247706",
            "id": "customer:83"
          },
          {
            "series": "1",
            "index": "14",
            "xExact": "15",
            "x": "15",
            "yExact": "0",
            "y": "0",
            "id": "customer:83"
          },
          {
            "series": "0",
            "index": "15",
            "xExact": "16",
            "x": "16",
            "yExact": "2/53",
            "y": "0.0377358491",
            "id": "customer:84"
          },
          {
            "series": "1",
            "index": "15",
            "xExact": "16",
            "x": "16",
            "yExact": "0",
            "y": "0",
            "id": "customer:84"
          },
          {
            "series": "0",
            "index": "16",
            "xExact": "17",
            "x": "17",
            "yExact": "1/139",
            "y": "0.0071942446",
            "id": "customer:86"
          },
          {
            "series": "1",
            "index": "16",
            "xExact": "17",
            "x": "17",
            "yExact": "0",
            "y": "0",
            "id": "customer:86"
          },
          {
            "series": "0",
            "index": "17",
            "xExact": "18",
            "x": "18",
            "yExact": "17/112",
            "y": "0.151785714",
            "id": "customer:88"
          },
          {
            "series": "1",
            "index": "17",
            "xExact": "18",
            "x": "18",
            "yExact": "0",
            "y": "0",
            "id": "customer:88"
          },
          {
            "series": "0",
            "index": "18",
            "xExact": "19",
            "x": "19",
            "yExact": "43/218",
            "y": "0.197247706",
            "id": "customer:102"
          },
          {
            "series": "1",
            "index": "18",
            "xExact": "19",
            "x": "19",
            "yExact": "0",
            "y": "0",
            "id": "customer:102"
          },
          {
            "series": "0",
            "index": "19",
            "xExact": "20",
            "x": "20",
            "yExact": "43/218",
            "y": "0.197247706",
            "id": "customer:105"
          },
          {
            "series": "1",
            "index": "19",
            "xExact": "20",
            "x": "20",
            "yExact": "0",
            "y": "0",
            "id": "customer:105"
          },
          {
            "series": "0",
            "index": "20",
            "xExact": "21",
            "x": "21",
            "yExact": "1/139",
            "y": "0.0071942446",
            "id": "customer:111"
          },
          {
            "series": "1",
            "index": "20",
            "xExact": "21",
            "x": "21",
            "yExact": "0",
            "y": "0",
            "id": "customer:111"
          },
          {
            "series": "0",
            "index": "21",
            "xExact": "22",
            "x": "22",
            "yExact": "3/205",
            "y": "0.0146341463",
            "id": "customer:116"
          },
          {
            "series": "1",
            "index": "21",
            "xExact": "22",
            "x": "22",
            "yExact": "0",
            "y": "0",
            "id": "customer:116"
          },
          {
            "series": "0",
            "index": "22",
            "xExact": "23",
            "x": "23",
            "yExact": "3/205",
            "y": "0.0146341463",
            "id": "customer:121"
          },
          {
            "series": "1",
            "index": "22",
            "xExact": "23",
            "x": "23",
            "yExact": "0",
            "y": "0",
            "id": "customer:121"
          },
          {
            "series": "0",
            "index": "23",
            "xExact": "24",
            "x": "24",
            "yExact": "2/53",
            "y": "0.0377358491",
            "id": "customer:125"
          },
          {
            "series": "1",
            "index": "23",
            "xExact": "24",
            "x": "24",
            "yExact": "1",
            "y": "1",
            "id": "customer:125"
          },
          {
            "series": "0",
            "index": "24",
            "xExact": "25",
            "x": "25",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:126"
          },
          {
            "series": "1",
            "index": "24",
            "xExact": "25",
            "x": "25",
            "yExact": "0",
            "y": "0",
            "id": "customer:126"
          },
          {
            "series": "0",
            "index": "25",
            "xExact": "26",
            "x": "26",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:132"
          },
          {
            "series": "1",
            "index": "25",
            "xExact": "26",
            "x": "26",
            "yExact": "1",
            "y": "1",
            "id": "customer:132"
          },
          {
            "series": "0",
            "index": "26",
            "xExact": "27",
            "x": "27",
            "yExact": "3/205",
            "y": "0.0146341463",
            "id": "customer:135"
          },
          {
            "series": "1",
            "index": "26",
            "xExact": "27",
            "x": "27",
            "yExact": "0",
            "y": "0",
            "id": "customer:135"
          },
          {
            "series": "0",
            "index": "27",
            "xExact": "28",
            "x": "28",
            "yExact": "2/53",
            "y": "0.0377358491",
            "id": "customer:146"
          },
          {
            "series": "1",
            "index": "27",
            "xExact": "28",
            "x": "28",
            "yExact": "0",
            "y": "0",
            "id": "customer:146"
          },
          {
            "series": "0",
            "index": "28",
            "xExact": "29",
            "x": "29",
            "yExact": "3/205",
            "y": "0.0146341463",
            "id": "customer:149"
          },
          {
            "series": "1",
            "index": "28",
            "xExact": "29",
            "x": "29",
            "yExact": "0",
            "y": "0",
            "id": "customer:149"
          },
          {
            "series": "0",
            "index": "29",
            "xExact": "30",
            "x": "30",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:156"
          },
          {
            "series": "1",
            "index": "29",
            "xExact": "30",
            "x": "30",
            "yExact": "0",
            "y": "0",
            "id": "customer:156"
          },
          {
            "series": "0",
            "index": "30",
            "xExact": "31",
            "x": "31",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:163"
          },
          {
            "series": "1",
            "index": "30",
            "xExact": "31",
            "x": "31",
            "yExact": "0",
            "y": "0",
            "id": "customer:163"
          },
          {
            "series": "0",
            "index": "31",
            "xExact": "32",
            "x": "32",
            "yExact": "43/218",
            "y": "0.197247706",
            "id": "customer:168"
          },
          {
            "series": "1",
            "index": "31",
            "xExact": "32",
            "x": "32",
            "yExact": "0",
            "y": "0",
            "id": "customer:168"
          },
          {
            "series": "0",
            "index": "32",
            "xExact": "33",
            "x": "33",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:171"
          },
          {
            "series": "1",
            "index": "32",
            "xExact": "33",
            "x": "33",
            "yExact": "0",
            "y": "0",
            "id": "customer:171"
          },
          {
            "series": "0",
            "index": "33",
            "xExact": "34",
            "x": "34",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:172"
          },
          {
            "series": "1",
            "index": "33",
            "xExact": "34",
            "x": "34",
            "yExact": "0",
            "y": "0",
            "id": "customer:172"
          },
          {
            "series": "0",
            "index": "34",
            "xExact": "35",
            "x": "35",
            "yExact": "17/29",
            "y": "0.586206897",
            "id": "customer:174"
          },
          {
            "series": "1",
            "index": "34",
            "xExact": "35",
            "x": "35",
            "yExact": "0",
            "y": "0",
            "id": "customer:174"
          },
          {
            "series": "0",
            "index": "35",
            "xExact": "36",
            "x": "36",
            "yExact": "17/29",
            "y": "0.586206897",
            "id": "customer:178"
          },
          {
            "series": "1",
            "index": "35",
            "xExact": "36",
            "x": "36",
            "yExact": "1",
            "y": "1",
            "id": "customer:178"
          },
          {
            "series": "0",
            "index": "36",
            "xExact": "37",
            "x": "37",
            "yExact": "43/218",
            "y": "0.197247706",
            "id": "customer:179"
          },
          {
            "series": "1",
            "index": "36",
            "xExact": "37",
            "x": "37",
            "yExact": "1",
            "y": "1",
            "id": "customer:179"
          },
          {
            "series": "0",
            "index": "37",
            "xExact": "38",
            "x": "38",
            "yExact": "6/7",
            "y": "0.857142857",
            "id": "customer:182"
          },
          {
            "series": "1",
            "index": "37",
            "xExact": "38",
            "x": "38",
            "yExact": "1",
            "y": "1",
            "id": "customer:182"
          },
          {
            "series": "0",
            "index": "38",
            "xExact": "39",
            "x": "39",
            "yExact": "43/218",
            "y": "0.197247706",
            "id": "customer:183"
          },
          {
            "series": "1",
            "index": "38",
            "xExact": "39",
            "x": "39",
            "yExact": "0",
            "y": "0",
            "id": "customer:183"
          },
          {
            "series": "0",
            "index": "39",
            "xExact": "40",
            "x": "40",
            "yExact": "17/29",
            "y": "0.586206897",
            "id": "customer:185"
          },
          {
            "series": "1",
            "index": "39",
            "xExact": "40",
            "x": "40",
            "yExact": "0",
            "y": "0",
            "id": "customer:185"
          },
          {
            "series": "0",
            "index": "40",
            "xExact": "41",
            "x": "41",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:189"
          },
          {
            "series": "1",
            "index": "40",
            "xExact": "41",
            "x": "41",
            "yExact": "0",
            "y": "0",
            "id": "customer:189"
          },
          {
            "series": "0",
            "index": "41",
            "xExact": "42",
            "x": "42",
            "yExact": "2/53",
            "y": "0.0377358491",
            "id": "customer:197"
          },
          {
            "series": "1",
            "index": "41",
            "xExact": "42",
            "x": "42",
            "yExact": "0",
            "y": "0",
            "id": "customer:197"
          },
          {
            "series": "0",
            "index": "42",
            "xExact": "43",
            "x": "43",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:202"
          },
          {
            "series": "1",
            "index": "42",
            "xExact": "43",
            "x": "43",
            "yExact": "0",
            "y": "0",
            "id": "customer:202"
          },
          {
            "series": "0",
            "index": "43",
            "xExact": "44",
            "x": "44",
            "yExact": "2/53",
            "y": "0.0377358491",
            "id": "customer:204"
          },
          {
            "series": "1",
            "index": "43",
            "xExact": "44",
            "x": "44",
            "yExact": "0",
            "y": "0",
            "id": "customer:204"
          },
          {
            "series": "0",
            "index": "44",
            "xExact": "45",
            "x": "45",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:205"
          },
          {
            "series": "1",
            "index": "44",
            "xExact": "45",
            "x": "45",
            "yExact": "0",
            "y": "0",
            "id": "customer:205"
          },
          {
            "series": "0",
            "index": "45",
            "xExact": "46",
            "x": "46",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:207"
          },
          {
            "series": "1",
            "index": "45",
            "xExact": "46",
            "x": "46",
            "yExact": "0",
            "y": "0",
            "id": "customer:207"
          },
          {
            "series": "0",
            "index": "46",
            "xExact": "47",
            "x": "47",
            "yExact": "2/53",
            "y": "0.0377358491",
            "id": "customer:208"
          },
          {
            "series": "1",
            "index": "46",
            "xExact": "47",
            "x": "47",
            "yExact": "0",
            "y": "0",
            "id": "customer:208"
          },
          {
            "series": "0",
            "index": "47",
            "xExact": "48",
            "x": "48",
            "yExact": "3/205",
            "y": "0.0146341463",
            "id": "customer:209"
          },
          {
            "series": "1",
            "index": "47",
            "xExact": "48",
            "x": "48",
            "yExact": "0",
            "y": "0",
            "id": "customer:209"
          },
          {
            "series": "0",
            "index": "48",
            "xExact": "49",
            "x": "49",
            "yExact": "3/205",
            "y": "0.0146341463",
            "id": "customer:211"
          },
          {
            "series": "1",
            "index": "48",
            "xExact": "49",
            "x": "49",
            "yExact": "0",
            "y": "0",
            "id": "customer:211"
          },
          {
            "series": "0",
            "index": "49",
            "xExact": "50",
            "x": "50",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:217"
          },
          {
            "series": "1",
            "index": "49",
            "xExact": "50",
            "x": "50",
            "yExact": "0",
            "y": "0",
            "id": "customer:217"
          },
          {
            "series": "0",
            "index": "50",
            "xExact": "51",
            "x": "51",
            "yExact": "2/3",
            "y": "0.666666667",
            "id": "customer:225"
          },
          {
            "series": "1",
            "index": "50",
            "xExact": "51",
            "x": "51",
            "yExact": "1",
            "y": "1",
            "id": "customer:225"
          },
          {
            "series": "0",
            "index": "51",
            "xExact": "52",
            "x": "52",
            "yExact": "4/23",
            "y": "0.173913043",
            "id": "customer:228"
          },
          {
            "series": "1",
            "index": "51",
            "xExact": "52",
            "x": "52",
            "yExact": "1",
            "y": "1",
            "id": "customer:228"
          },
          {
            "series": "0",
            "index": "52",
            "xExact": "53",
            "x": "53",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:238"
          },
          {
            "series": "1",
            "index": "52",
            "xExact": "53",
            "x": "53",
            "yExact": "0",
            "y": "0",
            "id": "customer:238"
          },
          {
            "series": "0",
            "index": "53",
            "xExact": "54",
            "x": "54",
            "yExact": "2/53",
            "y": "0.0377358491",
            "id": "customer:246"
          },
          {
            "series": "1",
            "index": "53",
            "xExact": "54",
            "x": "54",
            "yExact": "0",
            "y": "0",
            "id": "customer:246"
          },
          {
            "series": "0",
            "index": "54",
            "xExact": "55",
            "x": "55",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:263"
          },
          {
            "series": "1",
            "index": "54",
            "xExact": "55",
            "x": "55",
            "yExact": "0",
            "y": "0",
            "id": "customer:263"
          },
          {
            "series": "0",
            "index": "55",
            "xExact": "56",
            "x": "56",
            "yExact": "43/218",
            "y": "0.197247706",
            "id": "customer:267"
          },
          {
            "series": "1",
            "index": "55",
            "xExact": "56",
            "x": "56",
            "yExact": "0",
            "y": "0",
            "id": "customer:267"
          },
          {
            "series": "0",
            "index": "56",
            "xExact": "57",
            "x": "57",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:270"
          },
          {
            "series": "1",
            "index": "56",
            "xExact": "57",
            "x": "57",
            "yExact": "0",
            "y": "0",
            "id": "customer:270"
          },
          {
            "series": "0",
            "index": "57",
            "xExact": "58",
            "x": "58",
            "yExact": "17/29",
            "y": "0.586206897",
            "id": "customer:278"
          },
          {
            "series": "1",
            "index": "57",
            "xExact": "58",
            "x": "58",
            "yExact": "1",
            "y": "1",
            "id": "customer:278"
          },
          {
            "series": "0",
            "index": "58",
            "xExact": "59",
            "x": "59",
            "yExact": "43/218",
            "y": "0.197247706",
            "id": "customer:282"
          },
          {
            "series": "1",
            "index": "58",
            "xExact": "59",
            "x": "59",
            "yExact": "1",
            "y": "1",
            "id": "customer:282"
          },
          {
            "series": "0",
            "index": "59",
            "xExact": "60",
            "x": "60",
            "yExact": "43/218",
            "y": "0.197247706",
            "id": "customer:283"
          },
          {
            "series": "1",
            "index": "59",
            "xExact": "60",
            "x": "60",
            "yExact": "0",
            "y": "0",
            "id": "customer:283"
          },
          {
            "series": "0",
            "index": "60",
            "xExact": "61",
            "x": "61",
            "yExact": "4/23",
            "y": "0.173913043",
            "id": "customer:290"
          },
          {
            "series": "1",
            "index": "60",
            "xExact": "61",
            "x": "61",
            "yExact": "0",
            "y": "0",
            "id": "customer:290"
          },
          {
            "series": "0",
            "index": "61",
            "xExact": "62",
            "x": "62",
            "yExact": "2/53",
            "y": "0.0377358491",
            "id": "customer:294"
          },
          {
            "series": "1",
            "index": "61",
            "xExact": "62",
            "x": "62",
            "yExact": "0",
            "y": "0",
            "id": "customer:294"
          },
          {
            "series": "0",
            "index": "62",
            "xExact": "63",
            "x": "63",
            "yExact": "4/23",
            "y": "0.173913043",
            "id": "customer:295"
          },
          {
            "series": "1",
            "index": "62",
            "xExact": "63",
            "x": "63",
            "yExact": "0",
            "y": "0",
            "id": "customer:295"
          },
          {
            "series": "0",
            "index": "63",
            "xExact": "64",
            "x": "64",
            "yExact": "2/53",
            "y": "0.0377358491",
            "id": "customer:298"
          },
          {
            "series": "1",
            "index": "63",
            "xExact": "64",
            "x": "64",
            "yExact": "0",
            "y": "0",
            "id": "customer:298"
          },
          {
            "series": "0",
            "index": "64",
            "xExact": "65",
            "x": "65",
            "yExact": "3/205",
            "y": "0.0146341463",
            "id": "customer:301"
          },
          {
            "series": "1",
            "index": "64",
            "xExact": "65",
            "x": "65",
            "yExact": "0",
            "y": "0",
            "id": "customer:301"
          },
          {
            "series": "0",
            "index": "65",
            "xExact": "66",
            "x": "66",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:305"
          },
          {
            "series": "1",
            "index": "65",
            "xExact": "66",
            "x": "66",
            "yExact": "0",
            "y": "0",
            "id": "customer:305"
          },
          {
            "series": "0",
            "index": "66",
            "xExact": "67",
            "x": "67",
            "yExact": "3/205",
            "y": "0.0146341463",
            "id": "customer:316"
          },
          {
            "series": "1",
            "index": "66",
            "xExact": "67",
            "x": "67",
            "yExact": "0",
            "y": "0",
            "id": "customer:316"
          },
          {
            "series": "0",
            "index": "67",
            "xExact": "68",
            "x": "68",
            "yExact": "2/53",
            "y": "0.0377358491",
            "id": "customer:324"
          },
          {
            "series": "1",
            "index": "67",
            "xExact": "68",
            "x": "68",
            "yExact": "0",
            "y": "0",
            "id": "customer:324"
          },
          {
            "series": "0",
            "index": "68",
            "xExact": "69",
            "x": "69",
            "yExact": "2/53",
            "y": "0.0377358491",
            "id": "customer:334"
          },
          {
            "series": "1",
            "index": "68",
            "xExact": "69",
            "x": "69",
            "yExact": "0",
            "y": "0",
            "id": "customer:334"
          },
          {
            "series": "0",
            "index": "69",
            "xExact": "70",
            "x": "70",
            "yExact": "3/205",
            "y": "0.0146341463",
            "id": "customer:335"
          },
          {
            "series": "1",
            "index": "69",
            "xExact": "70",
            "x": "70",
            "yExact": "0",
            "y": "0",
            "id": "customer:335"
          },
          {
            "series": "0",
            "index": "70",
            "xExact": "71",
            "x": "71",
            "yExact": "2/53",
            "y": "0.0377358491",
            "id": "customer:346"
          },
          {
            "series": "1",
            "index": "70",
            "xExact": "71",
            "x": "71",
            "yExact": "0",
            "y": "0",
            "id": "customer:346"
          },
          {
            "series": "0",
            "index": "71",
            "xExact": "72",
            "x": "72",
            "yExact": "43/218",
            "y": "0.197247706",
            "id": "customer:355"
          },
          {
            "series": "1",
            "index": "71",
            "xExact": "72",
            "x": "72",
            "yExact": "0",
            "y": "0",
            "id": "customer:355"
          },
          {
            "series": "0",
            "index": "72",
            "xExact": "73",
            "x": "73",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:356"
          },
          {
            "series": "1",
            "index": "72",
            "xExact": "73",
            "x": "73",
            "yExact": "0",
            "y": "0",
            "id": "customer:356"
          },
          {
            "series": "0",
            "index": "73",
            "xExact": "74",
            "x": "74",
            "yExact": "43/218",
            "y": "0.197247706",
            "id": "customer:367"
          },
          {
            "series": "1",
            "index": "73",
            "xExact": "74",
            "x": "74",
            "yExact": "0",
            "y": "0",
            "id": "customer:367"
          },
          {
            "series": "0",
            "index": "74",
            "xExact": "75",
            "x": "75",
            "yExact": "43/218",
            "y": "0.197247706",
            "id": "customer:369"
          },
          {
            "series": "1",
            "index": "74",
            "xExact": "75",
            "x": "75",
            "yExact": "1",
            "y": "1",
            "id": "customer:369"
          },
          {
            "series": "0",
            "index": "75",
            "xExact": "76",
            "x": "76",
            "yExact": "1/139",
            "y": "0.0071942446",
            "id": "customer:370"
          },
          {
            "series": "1",
            "index": "75",
            "xExact": "76",
            "x": "76",
            "yExact": "0",
            "y": "0",
            "id": "customer:370"
          },
          {
            "series": "0",
            "index": "76",
            "xExact": "77",
            "x": "77",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:371"
          },
          {
            "series": "1",
            "index": "76",
            "xExact": "77",
            "x": "77",
            "yExact": "0",
            "y": "0",
            "id": "customer:371"
          },
          {
            "series": "0",
            "index": "77",
            "xExact": "78",
            "x": "78",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:375"
          },
          {
            "series": "1",
            "index": "77",
            "xExact": "78",
            "x": "78",
            "yExact": "0",
            "y": "0",
            "id": "customer:375"
          },
          {
            "series": "0",
            "index": "78",
            "xExact": "79",
            "x": "79",
            "yExact": "17/29",
            "y": "0.586206897",
            "id": "customer:377"
          },
          {
            "series": "1",
            "index": "78",
            "xExact": "79",
            "x": "79",
            "yExact": "1",
            "y": "1",
            "id": "customer:377"
          },
          {
            "series": "0",
            "index": "79",
            "xExact": "80",
            "x": "80",
            "yExact": "43/218",
            "y": "0.197247706",
            "id": "customer:387"
          },
          {
            "series": "1",
            "index": "79",
            "xExact": "80",
            "x": "80",
            "yExact": "0",
            "y": "0",
            "id": "customer:387"
          },
          {
            "series": "0",
            "index": "80",
            "xExact": "81",
            "x": "81",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:388"
          },
          {
            "series": "1",
            "index": "80",
            "xExact": "81",
            "x": "81",
            "yExact": "0",
            "y": "0",
            "id": "customer:388"
          },
          {
            "series": "0",
            "index": "81",
            "xExact": "82",
            "x": "82",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:390"
          },
          {
            "series": "1",
            "index": "81",
            "xExact": "82",
            "x": "82",
            "yExact": "0",
            "y": "0",
            "id": "customer:390"
          },
          {
            "series": "0",
            "index": "82",
            "xExact": "83",
            "x": "83",
            "yExact": "2/53",
            "y": "0.0377358491",
            "id": "customer:396"
          },
          {
            "series": "1",
            "index": "82",
            "xExact": "83",
            "x": "83",
            "yExact": "0",
            "y": "0",
            "id": "customer:396"
          },
          {
            "series": "0",
            "index": "83",
            "xExact": "84",
            "x": "84",
            "yExact": "3/205",
            "y": "0.0146341463",
            "id": "customer:401"
          },
          {
            "series": "1",
            "index": "83",
            "xExact": "84",
            "x": "84",
            "yExact": "0",
            "y": "0",
            "id": "customer:401"
          },
          {
            "series": "0",
            "index": "84",
            "xExact": "85",
            "x": "85",
            "yExact": "2/53",
            "y": "0.0377358491",
            "id": "customer:404"
          },
          {
            "series": "1",
            "index": "84",
            "xExact": "85",
            "x": "85",
            "yExact": "0",
            "y": "0",
            "id": "customer:404"
          },
          {
            "series": "0",
            "index": "85",
            "xExact": "86",
            "x": "86",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:405"
          },
          {
            "series": "1",
            "index": "85",
            "xExact": "86",
            "x": "86",
            "yExact": "0",
            "y": "0",
            "id": "customer:405"
          },
          {
            "series": "0",
            "index": "86",
            "xExact": "87",
            "x": "87",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:407"
          },
          {
            "series": "1",
            "index": "86",
            "xExact": "87",
            "x": "87",
            "yExact": "0",
            "y": "0",
            "id": "customer:407"
          },
          {
            "series": "0",
            "index": "87",
            "xExact": "88",
            "x": "88",
            "yExact": "3/205",
            "y": "0.0146341463",
            "id": "customer:410"
          },
          {
            "series": "1",
            "index": "87",
            "xExact": "88",
            "x": "88",
            "yExact": "0",
            "y": "0",
            "id": "customer:410"
          },
          {
            "series": "0",
            "index": "88",
            "xExact": "89",
            "x": "89",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:417"
          },
          {
            "series": "1",
            "index": "88",
            "xExact": "89",
            "x": "89",
            "yExact": "0",
            "y": "0",
            "id": "customer:417"
          },
          {
            "series": "0",
            "index": "89",
            "xExact": "90",
            "x": "90",
            "yExact": "2/53",
            "y": "0.0377358491",
            "id": "customer:424"
          },
          {
            "series": "1",
            "index": "89",
            "xExact": "90",
            "x": "90",
            "yExact": "0",
            "y": "0",
            "id": "customer:424"
          },
          {
            "series": "0",
            "index": "90",
            "xExact": "91",
            "x": "91",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:426"
          },
          {
            "series": "1",
            "index": "90",
            "xExact": "91",
            "x": "91",
            "yExact": "0",
            "y": "0",
            "id": "customer:426"
          },
          {
            "series": "0",
            "index": "91",
            "xExact": "92",
            "x": "92",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:432"
          },
          {
            "series": "1",
            "index": "91",
            "xExact": "92",
            "x": "92",
            "yExact": "1",
            "y": "1",
            "id": "customer:432"
          },
          {
            "series": "0",
            "index": "92",
            "xExact": "93",
            "x": "93",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:451"
          },
          {
            "series": "1",
            "index": "92",
            "xExact": "93",
            "x": "93",
            "yExact": "0",
            "y": "0",
            "id": "customer:451"
          },
          {
            "series": "0",
            "index": "93",
            "xExact": "94",
            "x": "94",
            "yExact": "43/218",
            "y": "0.197247706",
            "id": "customer:452"
          },
          {
            "series": "1",
            "index": "93",
            "xExact": "94",
            "x": "94",
            "yExact": "0",
            "y": "0",
            "id": "customer:452"
          },
          {
            "series": "0",
            "index": "94",
            "xExact": "95",
            "x": "95",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:453"
          },
          {
            "series": "1",
            "index": "94",
            "xExact": "95",
            "x": "95",
            "yExact": "0",
            "y": "0",
            "id": "customer:453"
          },
          {
            "series": "0",
            "index": "95",
            "xExact": "96",
            "x": "96",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:455"
          },
          {
            "series": "1",
            "index": "95",
            "xExact": "96",
            "x": "96",
            "yExact": "0",
            "y": "0",
            "id": "customer:455"
          },
          {
            "series": "0",
            "index": "96",
            "xExact": "97",
            "x": "97",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:463"
          },
          {
            "series": "1",
            "index": "96",
            "xExact": "97",
            "x": "97",
            "yExact": "0",
            "y": "0",
            "id": "customer:463"
          },
          {
            "series": "0",
            "index": "97",
            "xExact": "98",
            "x": "98",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:464"
          },
          {
            "series": "1",
            "index": "97",
            "xExact": "98",
            "x": "98",
            "yExact": "0",
            "y": "0",
            "id": "customer:464"
          },
          {
            "series": "0",
            "index": "98",
            "xExact": "99",
            "x": "99",
            "yExact": "43/218",
            "y": "0.197247706",
            "id": "customer:467"
          },
          {
            "series": "1",
            "index": "98",
            "xExact": "99",
            "x": "99",
            "yExact": "0",
            "y": "0",
            "id": "customer:467"
          },
          {
            "series": "0",
            "index": "99",
            "xExact": "100",
            "x": "100",
            "yExact": "43/218",
            "y": "0.197247706",
            "id": "customer:469"
          },
          {
            "series": "1",
            "index": "99",
            "xExact": "100",
            "x": "100",
            "yExact": "1",
            "y": "1",
            "id": "customer:469"
          },
          {
            "series": "0",
            "index": "100",
            "xExact": "101",
            "x": "101",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:471"
          },
          {
            "series": "1",
            "index": "100",
            "xExact": "101",
            "x": "101",
            "yExact": "0",
            "y": "0",
            "id": "customer:471"
          },
          {
            "series": "0",
            "index": "101",
            "xExact": "102",
            "x": "102",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:472"
          },
          {
            "series": "1",
            "index": "101",
            "xExact": "102",
            "x": "102",
            "yExact": "0",
            "y": "0",
            "id": "customer:472"
          },
          {
            "series": "0",
            "index": "102",
            "xExact": "103",
            "x": "103",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:474"
          },
          {
            "series": "1",
            "index": "102",
            "xExact": "103",
            "x": "103",
            "yExact": "0",
            "y": "0",
            "id": "customer:474"
          },
          {
            "series": "0",
            "index": "103",
            "xExact": "104",
            "x": "104",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:475"
          },
          {
            "series": "1",
            "index": "103",
            "xExact": "104",
            "x": "104",
            "yExact": "0",
            "y": "0",
            "id": "customer:475"
          },
          {
            "series": "0",
            "index": "104",
            "xExact": "105",
            "x": "105",
            "yExact": "3/205",
            "y": "0.0146341463",
            "id": "customer:476"
          },
          {
            "series": "1",
            "index": "104",
            "xExact": "105",
            "x": "105",
            "yExact": "0",
            "y": "0",
            "id": "customer:476"
          },
          {
            "series": "0",
            "index": "105",
            "xExact": "106",
            "x": "106",
            "yExact": "1/139",
            "y": "0.0071942446",
            "id": "customer:486"
          },
          {
            "series": "1",
            "index": "105",
            "xExact": "106",
            "x": "106",
            "yExact": "0",
            "y": "0",
            "id": "customer:486"
          },
          {
            "series": "0",
            "index": "106",
            "xExact": "107",
            "x": "107",
            "yExact": "4/23",
            "y": "0.173913043",
            "id": "customer:493"
          },
          {
            "series": "1",
            "index": "106",
            "xExact": "107",
            "x": "107",
            "yExact": "0",
            "y": "0",
            "id": "customer:493"
          },
          {
            "series": "0",
            "index": "107",
            "xExact": "108",
            "x": "108",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:495"
          },
          {
            "series": "1",
            "index": "107",
            "xExact": "108",
            "x": "108",
            "yExact": "0",
            "y": "0",
            "id": "customer:495"
          },
          {
            "series": "0",
            "index": "108",
            "xExact": "109",
            "x": "109",
            "yExact": "43/218",
            "y": "0.197247706",
            "id": "customer:503"
          },
          {
            "series": "1",
            "index": "108",
            "xExact": "109",
            "x": "109",
            "yExact": "0",
            "y": "0",
            "id": "customer:503"
          },
          {
            "series": "0",
            "index": "109",
            "xExact": "110",
            "x": "110",
            "yExact": "1/139",
            "y": "0.0071942446",
            "id": "customer:504"
          },
          {
            "series": "1",
            "index": "109",
            "xExact": "110",
            "x": "110",
            "yExact": "0",
            "y": "0",
            "id": "customer:504"
          },
          {
            "series": "0",
            "index": "110",
            "xExact": "111",
            "x": "111",
            "yExact": "1/139",
            "y": "0.0071942446",
            "id": "customer:511"
          },
          {
            "series": "1",
            "index": "110",
            "xExact": "111",
            "x": "111",
            "yExact": "0",
            "y": "0",
            "id": "customer:511"
          },
          {
            "series": "0",
            "index": "111",
            "xExact": "112",
            "x": "112",
            "yExact": "43/218",
            "y": "0.197247706",
            "id": "customer:512"
          },
          {
            "series": "1",
            "index": "111",
            "xExact": "112",
            "x": "112",
            "yExact": "0",
            "y": "0",
            "id": "customer:512"
          },
          {
            "series": "0",
            "index": "112",
            "xExact": "113",
            "x": "113",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:526"
          },
          {
            "series": "1",
            "index": "112",
            "xExact": "113",
            "x": "113",
            "yExact": "0",
            "y": "0",
            "id": "customer:526"
          },
          {
            "series": "0",
            "index": "113",
            "xExact": "114",
            "x": "114",
            "yExact": "43/218",
            "y": "0.197247706",
            "id": "customer:533"
          },
          {
            "series": "1",
            "index": "113",
            "xExact": "114",
            "x": "114",
            "yExact": "0",
            "y": "0",
            "id": "customer:533"
          },
          {
            "series": "0",
            "index": "114",
            "xExact": "115",
            "x": "115",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:548"
          },
          {
            "series": "1",
            "index": "114",
            "xExact": "115",
            "x": "115",
            "yExact": "0",
            "y": "0",
            "id": "customer:548"
          },
          {
            "series": "0",
            "index": "115",
            "xExact": "116",
            "x": "116",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:551"
          },
          {
            "series": "1",
            "index": "115",
            "xExact": "116",
            "x": "116",
            "yExact": "0",
            "y": "0",
            "id": "customer:551"
          },
          {
            "series": "0",
            "index": "116",
            "xExact": "117",
            "x": "117",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:559"
          },
          {
            "series": "1",
            "index": "116",
            "xExact": "117",
            "x": "117",
            "yExact": "0",
            "y": "0",
            "id": "customer:559"
          },
          {
            "series": "0",
            "index": "117",
            "xExact": "118",
            "x": "118",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:560"
          },
          {
            "series": "1",
            "index": "117",
            "xExact": "118",
            "x": "118",
            "yExact": "0",
            "y": "0",
            "id": "customer:560"
          },
          {
            "series": "0",
            "index": "118",
            "xExact": "119",
            "x": "119",
            "yExact": "1/139",
            "y": "0.0071942446",
            "id": "customer:561"
          },
          {
            "series": "1",
            "index": "118",
            "xExact": "119",
            "x": "119",
            "yExact": "0",
            "y": "0",
            "id": "customer:561"
          },
          {
            "series": "0",
            "index": "119",
            "xExact": "120",
            "x": "120",
            "yExact": "43/218",
            "y": "0.197247706",
            "id": "customer:567"
          },
          {
            "series": "1",
            "index": "119",
            "xExact": "120",
            "x": "120",
            "yExact": "0",
            "y": "0",
            "id": "customer:567"
          },
          {
            "series": "0",
            "index": "120",
            "xExact": "121",
            "x": "121",
            "yExact": "43/218",
            "y": "0.197247706",
            "id": "customer:569"
          },
          {
            "series": "1",
            "index": "120",
            "xExact": "121",
            "x": "121",
            "yExact": "1",
            "y": "1",
            "id": "customer:569"
          },
          {
            "series": "0",
            "index": "121",
            "xExact": "122",
            "x": "122",
            "yExact": "1/139",
            "y": "0.0071942446",
            "id": "customer:570"
          },
          {
            "series": "1",
            "index": "121",
            "xExact": "122",
            "x": "122",
            "yExact": "0",
            "y": "0",
            "id": "customer:570"
          },
          {
            "series": "0",
            "index": "122",
            "xExact": "123",
            "x": "123",
            "yExact": "3/205",
            "y": "0.0146341463",
            "id": "customer:576"
          },
          {
            "series": "1",
            "index": "122",
            "xExact": "123",
            "x": "123",
            "yExact": "0",
            "y": "0",
            "id": "customer:576"
          },
          {
            "series": "0",
            "index": "123",
            "xExact": "124",
            "x": "124",
            "yExact": "43/218",
            "y": "0.197247706",
            "id": "customer:580"
          },
          {
            "series": "1",
            "index": "123",
            "xExact": "124",
            "x": "124",
            "yExact": "0",
            "y": "0",
            "id": "customer:580"
          },
          {
            "series": "0",
            "index": "124",
            "xExact": "125",
            "x": "125",
            "yExact": "43/218",
            "y": "0.197247706",
            "id": "customer:583"
          },
          {
            "series": "1",
            "index": "124",
            "xExact": "125",
            "x": "125",
            "yExact": "0",
            "y": "0",
            "id": "customer:583"
          },
          {
            "series": "0",
            "index": "125",
            "xExact": "126",
            "x": "126",
            "yExact": "43/218",
            "y": "0.197247706",
            "id": "customer:587"
          },
          {
            "series": "1",
            "index": "125",
            "xExact": "126",
            "x": "126",
            "yExact": "0",
            "y": "0",
            "id": "customer:587"
          },
          {
            "series": "0",
            "index": "126",
            "xExact": "127",
            "x": "127",
            "yExact": "4/23",
            "y": "0.173913043",
            "id": "customer:593"
          },
          {
            "series": "1",
            "index": "126",
            "xExact": "127",
            "x": "127",
            "yExact": "0",
            "y": "0",
            "id": "customer:593"
          },
          {
            "series": "0",
            "index": "127",
            "xExact": "128",
            "x": "128",
            "yExact": "17/112",
            "y": "0.151785714",
            "id": "customer:603"
          },
          {
            "series": "1",
            "index": "127",
            "xExact": "128",
            "x": "128",
            "yExact": "0",
            "y": "0",
            "id": "customer:603"
          },
          {
            "series": "0",
            "index": "128",
            "xExact": "129",
            "x": "129",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:606"
          },
          {
            "series": "1",
            "index": "128",
            "xExact": "129",
            "x": "129",
            "yExact": "0",
            "y": "0",
            "id": "customer:606"
          },
          {
            "series": "0",
            "index": "129",
            "xExact": "130",
            "x": "130",
            "yExact": "43/218",
            "y": "0.197247706",
            "id": "customer:607"
          },
          {
            "series": "1",
            "index": "129",
            "xExact": "130",
            "x": "130",
            "yExact": "0",
            "y": "0",
            "id": "customer:607"
          },
          {
            "series": "0",
            "index": "130",
            "xExact": "131",
            "x": "131",
            "yExact": "1/139",
            "y": "0.0071942446",
            "id": "customer:616"
          },
          {
            "series": "1",
            "index": "130",
            "xExact": "131",
            "x": "131",
            "yExact": "0",
            "y": "0",
            "id": "customer:616"
          },
          {
            "series": "0",
            "index": "131",
            "xExact": "132",
            "x": "132",
            "yExact": "1/139",
            "y": "0.0071942446",
            "id": "customer:620"
          },
          {
            "series": "1",
            "index": "131",
            "xExact": "132",
            "x": "132",
            "yExact": "0",
            "y": "0",
            "id": "customer:620"
          },
          {
            "series": "0",
            "index": "132",
            "xExact": "133",
            "x": "133",
            "yExact": "2/3",
            "y": "0.666666667",
            "id": "customer:625"
          },
          {
            "series": "1",
            "index": "132",
            "xExact": "133",
            "x": "133",
            "yExact": "1",
            "y": "1",
            "id": "customer:625"
          },
          {
            "series": "0",
            "index": "133",
            "xExact": "134",
            "x": "134",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:626"
          },
          {
            "series": "1",
            "index": "133",
            "xExact": "134",
            "x": "134",
            "yExact": "0",
            "y": "0",
            "id": "customer:626"
          },
          {
            "series": "0",
            "index": "134",
            "xExact": "135",
            "x": "135",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:630"
          },
          {
            "series": "1",
            "index": "134",
            "xExact": "135",
            "x": "135",
            "yExact": "0",
            "y": "0",
            "id": "customer:630"
          },
          {
            "series": "0",
            "index": "135",
            "xExact": "136",
            "x": "136",
            "yExact": "2/53",
            "y": "0.0377358491",
            "id": "customer:634"
          },
          {
            "series": "1",
            "index": "135",
            "xExact": "136",
            "x": "136",
            "yExact": "0",
            "y": "0",
            "id": "customer:634"
          },
          {
            "series": "0",
            "index": "136",
            "xExact": "137",
            "x": "137",
            "yExact": "3/205",
            "y": "0.0146341463",
            "id": "customer:636"
          },
          {
            "series": "1",
            "index": "136",
            "xExact": "137",
            "x": "137",
            "yExact": "0",
            "y": "0",
            "id": "customer:636"
          },
          {
            "series": "0",
            "index": "137",
            "xExact": "138",
            "x": "138",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:637"
          },
          {
            "series": "1",
            "index": "137",
            "xExact": "138",
            "x": "138",
            "yExact": "0",
            "y": "0",
            "id": "customer:637"
          },
          {
            "series": "0",
            "index": "138",
            "xExact": "139",
            "x": "139",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:640"
          },
          {
            "series": "1",
            "index": "138",
            "xExact": "139",
            "x": "139",
            "yExact": "0",
            "y": "0",
            "id": "customer:640"
          },
          {
            "series": "0",
            "index": "139",
            "xExact": "140",
            "x": "140",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:642"
          },
          {
            "series": "1",
            "index": "139",
            "xExact": "140",
            "x": "140",
            "yExact": "0",
            "y": "0",
            "id": "customer:642"
          },
          {
            "series": "0",
            "index": "140",
            "xExact": "141",
            "x": "141",
            "yExact": "2/53",
            "y": "0.0377358491",
            "id": "customer:647"
          },
          {
            "series": "1",
            "index": "140",
            "xExact": "141",
            "x": "141",
            "yExact": "0",
            "y": "0",
            "id": "customer:647"
          },
          {
            "series": "0",
            "index": "141",
            "xExact": "142",
            "x": "142",
            "yExact": "43/218",
            "y": "0.197247706",
            "id": "customer:655"
          },
          {
            "series": "1",
            "index": "141",
            "xExact": "142",
            "x": "142",
            "yExact": "0",
            "y": "0",
            "id": "customer:655"
          },
          {
            "series": "0",
            "index": "142",
            "xExact": "143",
            "x": "143",
            "yExact": "43/218",
            "y": "0.197247706",
            "id": "customer:669"
          },
          {
            "series": "1",
            "index": "142",
            "xExact": "143",
            "x": "143",
            "yExact": "1",
            "y": "1",
            "id": "customer:669"
          },
          {
            "series": "0",
            "index": "143",
            "xExact": "144",
            "x": "144",
            "yExact": "1/139",
            "y": "0.0071942446",
            "id": "customer:670"
          },
          {
            "series": "1",
            "index": "143",
            "xExact": "144",
            "x": "144",
            "yExact": "0",
            "y": "0",
            "id": "customer:670"
          },
          {
            "series": "0",
            "index": "144",
            "xExact": "145",
            "x": "145",
            "yExact": "18/19",
            "y": "0.947368421",
            "id": "customer:673"
          },
          {
            "series": "1",
            "index": "144",
            "xExact": "145",
            "x": "145",
            "yExact": "1",
            "y": "1",
            "id": "customer:673"
          },
          {
            "series": "0",
            "index": "145",
            "xExact": "146",
            "x": "146",
            "yExact": "4/23",
            "y": "0.173913043",
            "id": "customer:691"
          },
          {
            "series": "1",
            "index": "145",
            "xExact": "146",
            "x": "146",
            "yExact": "0",
            "y": "0",
            "id": "customer:691"
          },
          {
            "series": "0",
            "index": "146",
            "xExact": "147",
            "x": "147",
            "yExact": "17/112",
            "y": "0.151785714",
            "id": "customer:703"
          },
          {
            "series": "1",
            "index": "146",
            "xExact": "147",
            "x": "147",
            "yExact": "0",
            "y": "0",
            "id": "customer:703"
          },
          {
            "series": "0",
            "index": "147",
            "xExact": "148",
            "x": "148",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:715"
          },
          {
            "series": "1",
            "index": "147",
            "xExact": "148",
            "x": "148",
            "yExact": "0",
            "y": "0",
            "id": "customer:715"
          },
          {
            "series": "0",
            "index": "148",
            "xExact": "149",
            "x": "149",
            "yExact": "43/218",
            "y": "0.197247706",
            "id": "customer:719"
          },
          {
            "series": "1",
            "index": "148",
            "xExact": "149",
            "x": "149",
            "yExact": "1",
            "y": "1",
            "id": "customer:719"
          },
          {
            "series": "0",
            "index": "149",
            "xExact": "150",
            "x": "150",
            "yExact": "1/139",
            "y": "0.0071942446",
            "id": "customer:721"
          },
          {
            "series": "1",
            "index": "149",
            "xExact": "150",
            "x": "150",
            "yExact": "0",
            "y": "0",
            "id": "customer:721"
          },
          {
            "series": "0",
            "index": "150",
            "xExact": "151",
            "x": "151",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:725"
          },
          {
            "series": "1",
            "index": "150",
            "xExact": "151",
            "x": "151",
            "yExact": "1",
            "y": "1",
            "id": "customer:725"
          },
          {
            "series": "0",
            "index": "151",
            "xExact": "152",
            "x": "152",
            "yExact": "3/205",
            "y": "0.0146341463",
            "id": "customer:731"
          },
          {
            "series": "1",
            "index": "151",
            "xExact": "152",
            "x": "152",
            "yExact": "0",
            "y": "0",
            "id": "customer:731"
          },
          {
            "series": "0",
            "index": "152",
            "xExact": "153",
            "x": "153",
            "yExact": "3/205",
            "y": "0.0146341463",
            "id": "customer:735"
          },
          {
            "series": "1",
            "index": "152",
            "xExact": "153",
            "x": "153",
            "yExact": "0",
            "y": "0",
            "id": "customer:735"
          },
          {
            "series": "0",
            "index": "153",
            "xExact": "154",
            "x": "154",
            "yExact": "3/205",
            "y": "0.0146341463",
            "id": "customer:744"
          },
          {
            "series": "1",
            "index": "153",
            "xExact": "154",
            "x": "154",
            "yExact": "0",
            "y": "0",
            "id": "customer:744"
          },
          {
            "series": "0",
            "index": "154",
            "xExact": "155",
            "x": "155",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:745"
          },
          {
            "series": "1",
            "index": "154",
            "xExact": "155",
            "x": "155",
            "yExact": "0",
            "y": "0",
            "id": "customer:745"
          },
          {
            "series": "0",
            "index": "155",
            "xExact": "156",
            "x": "156",
            "yExact": "3/205",
            "y": "0.0146341463",
            "id": "customer:751"
          },
          {
            "series": "1",
            "index": "155",
            "xExact": "156",
            "x": "156",
            "yExact": "0",
            "y": "0",
            "id": "customer:751"
          },
          {
            "series": "0",
            "index": "156",
            "xExact": "157",
            "x": "157",
            "yExact": "2/53",
            "y": "0.0377358491",
            "id": "customer:756"
          },
          {
            "series": "1",
            "index": "156",
            "xExact": "157",
            "x": "157",
            "yExact": "0",
            "y": "0",
            "id": "customer:756"
          },
          {
            "series": "0",
            "index": "157",
            "xExact": "158",
            "x": "158",
            "yExact": "2/53",
            "y": "0.0377358491",
            "id": "customer:763"
          },
          {
            "series": "1",
            "index": "157",
            "xExact": "158",
            "x": "158",
            "yExact": "0",
            "y": "0",
            "id": "customer:763"
          },
          {
            "series": "0",
            "index": "158",
            "xExact": "159",
            "x": "159",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:769"
          },
          {
            "series": "1",
            "index": "158",
            "xExact": "159",
            "x": "159",
            "yExact": "1",
            "y": "1",
            "id": "customer:769"
          },
          {
            "series": "0",
            "index": "159",
            "xExact": "160",
            "x": "160",
            "yExact": "3/205",
            "y": "0.0146341463",
            "id": "customer:770"
          },
          {
            "series": "1",
            "index": "159",
            "xExact": "160",
            "x": "160",
            "yExact": "0",
            "y": "0",
            "id": "customer:770"
          },
          {
            "series": "0",
            "index": "160",
            "xExact": "161",
            "x": "161",
            "yExact": "2/53",
            "y": "0.0377358491",
            "id": "customer:775"
          },
          {
            "series": "1",
            "index": "160",
            "xExact": "161",
            "x": "161",
            "yExact": "1",
            "y": "1",
            "id": "customer:775"
          },
          {
            "series": "0",
            "index": "161",
            "xExact": "162",
            "x": "162",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:776"
          },
          {
            "series": "1",
            "index": "161",
            "xExact": "162",
            "x": "162",
            "yExact": "0",
            "y": "0",
            "id": "customer:776"
          },
          {
            "series": "0",
            "index": "162",
            "xExact": "163",
            "x": "163",
            "yExact": "23/24",
            "y": "0.958333333",
            "id": "customer:779"
          },
          {
            "series": "1",
            "index": "162",
            "xExact": "163",
            "x": "163",
            "yExact": "1",
            "y": "1",
            "id": "customer:779"
          },
          {
            "series": "0",
            "index": "163",
            "xExact": "164",
            "x": "164",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:780"
          },
          {
            "series": "1",
            "index": "163",
            "xExact": "164",
            "x": "164",
            "yExact": "0",
            "y": "0",
            "id": "customer:780"
          },
          {
            "series": "0",
            "index": "164",
            "xExact": "165",
            "x": "165",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:789"
          },
          {
            "series": "1",
            "index": "164",
            "xExact": "165",
            "x": "165",
            "yExact": "0",
            "y": "0",
            "id": "customer:789"
          },
          {
            "series": "0",
            "index": "165",
            "xExact": "166",
            "x": "166",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:790"
          },
          {
            "series": "1",
            "index": "165",
            "xExact": "166",
            "x": "166",
            "yExact": "0",
            "y": "0",
            "id": "customer:790"
          },
          {
            "series": "0",
            "index": "166",
            "xExact": "167",
            "x": "167",
            "yExact": "4/23",
            "y": "0.173913043",
            "id": "customer:793"
          },
          {
            "series": "1",
            "index": "166",
            "xExact": "167",
            "x": "167",
            "yExact": "0",
            "y": "0",
            "id": "customer:793"
          },
          {
            "series": "0",
            "index": "167",
            "xExact": "168",
            "x": "168",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:795"
          },
          {
            "series": "1",
            "index": "167",
            "xExact": "168",
            "x": "168",
            "yExact": "0",
            "y": "0",
            "id": "customer:795"
          },
          {
            "series": "0",
            "index": "168",
            "xExact": "169",
            "x": "169",
            "yExact": "43/218",
            "y": "0.197247706",
            "id": "customer:807"
          },
          {
            "series": "1",
            "index": "168",
            "xExact": "169",
            "x": "169",
            "yExact": "0",
            "y": "0",
            "id": "customer:807"
          },
          {
            "series": "0",
            "index": "169",
            "xExact": "170",
            "x": "170",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:809"
          },
          {
            "series": "1",
            "index": "169",
            "xExact": "170",
            "x": "170",
            "yExact": "0",
            "y": "0",
            "id": "customer:809"
          },
          {
            "series": "0",
            "index": "170",
            "xExact": "171",
            "x": "171",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:815"
          },
          {
            "series": "1",
            "index": "170",
            "xExact": "171",
            "x": "171",
            "yExact": "0",
            "y": "0",
            "id": "customer:815"
          },
          {
            "series": "0",
            "index": "171",
            "xExact": "172",
            "x": "172",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:822"
          },
          {
            "series": "1",
            "index": "171",
            "xExact": "172",
            "x": "172",
            "yExact": "0",
            "y": "0",
            "id": "customer:822"
          },
          {
            "series": "0",
            "index": "172",
            "xExact": "173",
            "x": "173",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:825"
          },
          {
            "series": "1",
            "index": "172",
            "xExact": "173",
            "x": "173",
            "yExact": "0",
            "y": "0",
            "id": "customer:825"
          },
          {
            "series": "0",
            "index": "173",
            "xExact": "174",
            "x": "174",
            "yExact": "17/29",
            "y": "0.586206897",
            "id": "customer:828"
          },
          {
            "series": "1",
            "index": "173",
            "xExact": "174",
            "x": "174",
            "yExact": "1",
            "y": "1",
            "id": "customer:828"
          },
          {
            "series": "0",
            "index": "174",
            "xExact": "175",
            "x": "175",
            "yExact": "43/218",
            "y": "0.197247706",
            "id": "customer:829"
          },
          {
            "series": "1",
            "index": "174",
            "xExact": "175",
            "x": "175",
            "yExact": "1",
            "y": "1",
            "id": "customer:829"
          },
          {
            "series": "0",
            "index": "175",
            "xExact": "176",
            "x": "176",
            "yExact": "43/218",
            "y": "0.197247706",
            "id": "customer:830"
          },
          {
            "series": "1",
            "index": "175",
            "xExact": "176",
            "x": "176",
            "yExact": "0",
            "y": "0",
            "id": "customer:830"
          },
          {
            "series": "0",
            "index": "176",
            "xExact": "177",
            "x": "177",
            "yExact": "1/139",
            "y": "0.0071942446",
            "id": "customer:831"
          },
          {
            "series": "1",
            "index": "176",
            "xExact": "177",
            "x": "177",
            "yExact": "0",
            "y": "0",
            "id": "customer:831"
          },
          {
            "series": "0",
            "index": "177",
            "xExact": "178",
            "x": "178",
            "yExact": "43/218",
            "y": "0.197247706",
            "id": "customer:833"
          },
          {
            "series": "1",
            "index": "177",
            "xExact": "178",
            "x": "178",
            "yExact": "0",
            "y": "0",
            "id": "customer:833"
          },
          {
            "series": "0",
            "index": "178",
            "xExact": "179",
            "x": "179",
            "yExact": "1/139",
            "y": "0.0071942446",
            "id": "customer:836"
          },
          {
            "series": "1",
            "index": "178",
            "xExact": "179",
            "x": "179",
            "yExact": "0",
            "y": "0",
            "id": "customer:836"
          },
          {
            "series": "0",
            "index": "179",
            "xExact": "180",
            "x": "180",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:856"
          },
          {
            "series": "1",
            "index": "179",
            "xExact": "180",
            "x": "180",
            "yExact": "0",
            "y": "0",
            "id": "customer:856"
          },
          {
            "series": "0",
            "index": "180",
            "xExact": "181",
            "x": "181",
            "yExact": "43/218",
            "y": "0.197247706",
            "id": "customer:867"
          },
          {
            "series": "1",
            "index": "180",
            "xExact": "181",
            "x": "181",
            "yExact": "0",
            "y": "0",
            "id": "customer:867"
          },
          {
            "series": "0",
            "index": "181",
            "xExact": "182",
            "x": "182",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:870"
          },
          {
            "series": "1",
            "index": "181",
            "xExact": "182",
            "x": "182",
            "yExact": "0",
            "y": "0",
            "id": "customer:870"
          },
          {
            "series": "0",
            "index": "182",
            "xExact": "183",
            "x": "183",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:871"
          },
          {
            "series": "1",
            "index": "182",
            "xExact": "183",
            "x": "183",
            "yExact": "0",
            "y": "0",
            "id": "customer:871"
          },
          {
            "series": "0",
            "index": "183",
            "xExact": "184",
            "x": "184",
            "yExact": "17/29",
            "y": "0.586206897",
            "id": "customer:877"
          },
          {
            "series": "1",
            "index": "183",
            "xExact": "184",
            "x": "184",
            "yExact": "1",
            "y": "1",
            "id": "customer:877"
          },
          {
            "series": "0",
            "index": "184",
            "xExact": "185",
            "x": "185",
            "yExact": "2/53",
            "y": "0.0377358491",
            "id": "customer:881"
          },
          {
            "series": "1",
            "index": "184",
            "xExact": "185",
            "x": "185",
            "yExact": "0",
            "y": "0",
            "id": "customer:881"
          },
          {
            "series": "0",
            "index": "185",
            "xExact": "186",
            "x": "186",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:892"
          },
          {
            "series": "1",
            "index": "185",
            "xExact": "186",
            "x": "186",
            "yExact": "0",
            "y": "0",
            "id": "customer:892"
          },
          {
            "series": "0",
            "index": "186",
            "xExact": "187",
            "x": "187",
            "yExact": "4/23",
            "y": "0.173913043",
            "id": "customer:895"
          },
          {
            "series": "1",
            "index": "186",
            "xExact": "187",
            "x": "187",
            "yExact": "0",
            "y": "0",
            "id": "customer:895"
          },
          {
            "series": "0",
            "index": "187",
            "xExact": "188",
            "x": "188",
            "yExact": "2/53",
            "y": "0.0377358491",
            "id": "customer:896"
          },
          {
            "series": "1",
            "index": "187",
            "xExact": "188",
            "x": "188",
            "yExact": "0",
            "y": "0",
            "id": "customer:896"
          },
          {
            "series": "0",
            "index": "188",
            "xExact": "189",
            "x": "189",
            "yExact": "2/53",
            "y": "0.0377358491",
            "id": "customer:897"
          },
          {
            "series": "1",
            "index": "188",
            "xExact": "189",
            "x": "189",
            "yExact": "0",
            "y": "0",
            "id": "customer:897"
          },
          {
            "series": "0",
            "index": "189",
            "xExact": "190",
            "x": "190",
            "yExact": "2/53",
            "y": "0.0377358491",
            "id": "customer:899"
          },
          {
            "series": "1",
            "index": "189",
            "xExact": "190",
            "x": "190",
            "yExact": "0",
            "y": "0",
            "id": "customer:899"
          },
          {
            "series": "0",
            "index": "190",
            "xExact": "191",
            "x": "191",
            "yExact": "43/218",
            "y": "0.197247706",
            "id": "customer:903"
          },
          {
            "series": "1",
            "index": "190",
            "xExact": "191",
            "x": "191",
            "yExact": "0",
            "y": "0",
            "id": "customer:903"
          },
          {
            "series": "0",
            "index": "191",
            "xExact": "192",
            "x": "192",
            "yExact": "1/139",
            "y": "0.0071942446",
            "id": "customer:910"
          },
          {
            "series": "1",
            "index": "191",
            "xExact": "192",
            "x": "192",
            "yExact": "0",
            "y": "0",
            "id": "customer:910"
          },
          {
            "series": "0",
            "index": "192",
            "xExact": "193",
            "x": "193",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:913"
          },
          {
            "series": "1",
            "index": "192",
            "xExact": "193",
            "x": "193",
            "yExact": "0",
            "y": "0",
            "id": "customer:913"
          },
          {
            "series": "0",
            "index": "193",
            "xExact": "194",
            "x": "194",
            "yExact": "1/139",
            "y": "0.0071942446",
            "id": "customer:921"
          },
          {
            "series": "1",
            "index": "193",
            "xExact": "194",
            "x": "194",
            "yExact": "0",
            "y": "0",
            "id": "customer:921"
          },
          {
            "series": "0",
            "index": "194",
            "xExact": "195",
            "x": "195",
            "yExact": "2/53",
            "y": "0.0377358491",
            "id": "customer:925"
          },
          {
            "series": "1",
            "index": "194",
            "xExact": "195",
            "x": "195",
            "yExact": "1",
            "y": "1",
            "id": "customer:925"
          },
          {
            "series": "0",
            "index": "195",
            "xExact": "196",
            "x": "196",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:926"
          },
          {
            "series": "1",
            "index": "195",
            "xExact": "196",
            "x": "196",
            "yExact": "0",
            "y": "0",
            "id": "customer:926"
          },
          {
            "series": "0",
            "index": "196",
            "xExact": "197",
            "x": "197",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:930"
          },
          {
            "series": "1",
            "index": "196",
            "xExact": "197",
            "x": "197",
            "yExact": "0",
            "y": "0",
            "id": "customer:930"
          },
          {
            "series": "0",
            "index": "197",
            "xExact": "198",
            "x": "198",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:933"
          },
          {
            "series": "1",
            "index": "197",
            "xExact": "198",
            "x": "198",
            "yExact": "0",
            "y": "0",
            "id": "customer:933"
          },
          {
            "series": "0",
            "index": "198",
            "xExact": "199",
            "x": "199",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:940"
          },
          {
            "series": "1",
            "index": "198",
            "xExact": "199",
            "x": "199",
            "yExact": "0",
            "y": "0",
            "id": "customer:940"
          },
          {
            "series": "0",
            "index": "199",
            "xExact": "200",
            "x": "200",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:941"
          },
          {
            "series": "1",
            "index": "199",
            "xExact": "200",
            "x": "200",
            "yExact": "0",
            "y": "0",
            "id": "customer:941"
          },
          {
            "series": "0",
            "index": "200",
            "xExact": "201",
            "x": "201",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:943"
          },
          {
            "series": "1",
            "index": "200",
            "xExact": "201",
            "x": "201",
            "yExact": "0",
            "y": "0",
            "id": "customer:943"
          },
          {
            "series": "0",
            "index": "201",
            "xExact": "202",
            "x": "202",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:948"
          },
          {
            "series": "1",
            "index": "201",
            "xExact": "202",
            "x": "202",
            "yExact": "0",
            "y": "0",
            "id": "customer:948"
          },
          {
            "series": "0",
            "index": "202",
            "xExact": "203",
            "x": "203",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:951"
          },
          {
            "series": "1",
            "index": "202",
            "xExact": "203",
            "x": "203",
            "yExact": "0",
            "y": "0",
            "id": "customer:951"
          },
          {
            "series": "0",
            "index": "203",
            "xExact": "204",
            "x": "204",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:954"
          },
          {
            "series": "1",
            "index": "203",
            "xExact": "204",
            "x": "204",
            "yExact": "0",
            "y": "0",
            "id": "customer:954"
          },
          {
            "series": "0",
            "index": "204",
            "xExact": "205",
            "x": "205",
            "yExact": "43/218",
            "y": "0.197247706",
            "id": "customer:955"
          },
          {
            "series": "1",
            "index": "204",
            "xExact": "205",
            "x": "205",
            "yExact": "0",
            "y": "0",
            "id": "customer:955"
          },
          {
            "series": "0",
            "index": "205",
            "xExact": "206",
            "x": "206",
            "yExact": "43/218",
            "y": "0.197247706",
            "id": "customer:957"
          },
          {
            "series": "1",
            "index": "205",
            "xExact": "206",
            "x": "206",
            "yExact": "0",
            "y": "0",
            "id": "customer:957"
          },
          {
            "series": "0",
            "index": "206",
            "xExact": "207",
            "x": "207",
            "yExact": "1/139",
            "y": "0.0071942446",
            "id": "customer:966"
          },
          {
            "series": "1",
            "index": "206",
            "xExact": "207",
            "x": "207",
            "yExact": "0",
            "y": "0",
            "id": "customer:966"
          },
          {
            "series": "0",
            "index": "207",
            "xExact": "208",
            "x": "208",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:971"
          },
          {
            "series": "1",
            "index": "207",
            "xExact": "208",
            "x": "208",
            "yExact": "0",
            "y": "0",
            "id": "customer:971"
          },
          {
            "series": "0",
            "index": "208",
            "xExact": "209",
            "x": "209",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:975"
          },
          {
            "series": "1",
            "index": "208",
            "xExact": "209",
            "x": "209",
            "yExact": "1",
            "y": "1",
            "id": "customer:975"
          },
          {
            "series": "0",
            "index": "209",
            "xExact": "210",
            "x": "210",
            "yExact": "2/3",
            "y": "0.666666667",
            "id": "customer:977"
          },
          {
            "series": "1",
            "index": "209",
            "xExact": "210",
            "x": "210",
            "yExact": "1",
            "y": "1",
            "id": "customer:977"
          },
          {
            "series": "0",
            "index": "210",
            "xExact": "211",
            "x": "211",
            "yExact": "43/218",
            "y": "0.197247706",
            "id": "customer:979"
          },
          {
            "series": "1",
            "index": "210",
            "xExact": "211",
            "x": "211",
            "yExact": "1",
            "y": "1",
            "id": "customer:979"
          },
          {
            "series": "0",
            "index": "211",
            "xExact": "212",
            "x": "212",
            "yExact": "43/218",
            "y": "0.197247706",
            "id": "customer:982"
          },
          {
            "series": "1",
            "index": "211",
            "xExact": "212",
            "x": "212",
            "yExact": "1",
            "y": "1",
            "id": "customer:982"
          },
          {
            "series": "0",
            "index": "212",
            "xExact": "213",
            "x": "213",
            "yExact": "3/205",
            "y": "0.0146341463",
            "id": "customer:985"
          },
          {
            "series": "1",
            "index": "212",
            "xExact": "213",
            "x": "213",
            "yExact": "0",
            "y": "0",
            "id": "customer:985"
          },
          {
            "series": "0",
            "index": "213",
            "xExact": "214",
            "x": "214",
            "yExact": "1/139",
            "y": "0.0071942446",
            "id": "customer:986"
          },
          {
            "series": "1",
            "index": "213",
            "xExact": "214",
            "x": "214",
            "yExact": "0",
            "y": "0",
            "id": "customer:986"
          },
          {
            "series": "0",
            "index": "214",
            "xExact": "215",
            "x": "215",
            "yExact": "4/23",
            "y": "0.173913043",
            "id": "customer:991"
          },
          {
            "series": "1",
            "index": "214",
            "xExact": "215",
            "x": "215",
            "yExact": "0",
            "y": "0",
            "id": "customer:991"
          },
          {
            "series": "0",
            "index": "215",
            "xExact": "216",
            "x": "216",
            "yExact": "3/205",
            "y": "0.0146341463",
            "id": "customer:994"
          },
          {
            "series": "1",
            "index": "215",
            "xExact": "216",
            "x": "216",
            "yExact": "0",
            "y": "0",
            "id": "customer:994"
          },
          {
            "series": "0",
            "index": "216",
            "xExact": "217",
            "x": "217",
            "yExact": "4/23",
            "y": "0.173913043",
            "id": "customer:998"
          },
          {
            "series": "1",
            "index": "216",
            "xExact": "217",
            "x": "217",
            "yExact": "0",
            "y": "0",
            "id": "customer:998"
          },
          {
            "series": "0",
            "index": "217",
            "xExact": "218",
            "x": "218",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:1008"
          },
          {
            "series": "1",
            "index": "217",
            "xExact": "218",
            "x": "218",
            "yExact": "0",
            "y": "0",
            "id": "customer:1008"
          },
          {
            "series": "0",
            "index": "218",
            "xExact": "219",
            "x": "219",
            "yExact": "1/139",
            "y": "0.0071942446",
            "id": "customer:1014"
          },
          {
            "series": "1",
            "index": "218",
            "xExact": "219",
            "x": "219",
            "yExact": "0",
            "y": "0",
            "id": "customer:1014"
          },
          {
            "series": "0",
            "index": "219",
            "xExact": "220",
            "x": "220",
            "yExact": "1/139",
            "y": "0.0071942446",
            "id": "customer:1016"
          },
          {
            "series": "1",
            "index": "219",
            "xExact": "220",
            "x": "220",
            "yExact": "0",
            "y": "0",
            "id": "customer:1016"
          },
          {
            "series": "0",
            "index": "220",
            "xExact": "221",
            "x": "221",
            "yExact": "43/218",
            "y": "0.197247706",
            "id": "customer:1017"
          },
          {
            "series": "1",
            "index": "220",
            "xExact": "221",
            "x": "221",
            "yExact": "0",
            "y": "0",
            "id": "customer:1017"
          },
          {
            "series": "0",
            "index": "221",
            "xExact": "222",
            "x": "222",
            "yExact": "43/218",
            "y": "0.197247706",
            "id": "customer:1030"
          },
          {
            "series": "1",
            "index": "221",
            "xExact": "222",
            "x": "222",
            "yExact": "0",
            "y": "0",
            "id": "customer:1030"
          },
          {
            "series": "0",
            "index": "222",
            "xExact": "223",
            "x": "223",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:1037"
          },
          {
            "series": "1",
            "index": "222",
            "xExact": "223",
            "x": "223",
            "yExact": "0",
            "y": "0",
            "id": "customer:1037"
          },
          {
            "series": "0",
            "index": "223",
            "xExact": "224",
            "x": "224",
            "yExact": "43/218",
            "y": "0.197247706",
            "id": "customer:1038"
          },
          {
            "series": "1",
            "index": "223",
            "xExact": "224",
            "x": "224",
            "yExact": "0",
            "y": "0",
            "id": "customer:1038"
          },
          {
            "series": "0",
            "index": "224",
            "xExact": "225",
            "x": "225",
            "yExact": "3/205",
            "y": "0.0146341463",
            "id": "customer:1049"
          },
          {
            "series": "1",
            "index": "224",
            "xExact": "225",
            "x": "225",
            "yExact": "0",
            "y": "0",
            "id": "customer:1049"
          },
          {
            "series": "0",
            "index": "225",
            "xExact": "226",
            "x": "226",
            "yExact": "1/139",
            "y": "0.0071942446",
            "id": "customer:1059"
          },
          {
            "series": "1",
            "index": "225",
            "xExact": "226",
            "x": "226",
            "yExact": "0",
            "y": "0",
            "id": "customer:1059"
          },
          {
            "series": "0",
            "index": "226",
            "xExact": "227",
            "x": "227",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:1063"
          },
          {
            "series": "1",
            "index": "226",
            "xExact": "227",
            "x": "227",
            "yExact": "0",
            "y": "0",
            "id": "customer:1063"
          },
          {
            "series": "0",
            "index": "227",
            "xExact": "228",
            "x": "228",
            "yExact": "43/218",
            "y": "0.197247706",
            "id": "customer:1064"
          },
          {
            "series": "1",
            "index": "227",
            "xExact": "228",
            "x": "228",
            "yExact": "0",
            "y": "0",
            "id": "customer:1064"
          },
          {
            "series": "0",
            "index": "228",
            "xExact": "229",
            "x": "229",
            "yExact": "3/205",
            "y": "0.0146341463",
            "id": "customer:1065"
          },
          {
            "series": "1",
            "index": "228",
            "xExact": "229",
            "x": "229",
            "yExact": "0",
            "y": "0",
            "id": "customer:1065"
          },
          {
            "series": "0",
            "index": "229",
            "xExact": "230",
            "x": "230",
            "yExact": "3/205",
            "y": "0.0146341463",
            "id": "customer:1071"
          },
          {
            "series": "1",
            "index": "229",
            "xExact": "230",
            "x": "230",
            "yExact": "0",
            "y": "0",
            "id": "customer:1071"
          },
          {
            "series": "0",
            "index": "230",
            "xExact": "231",
            "x": "231",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:1076"
          },
          {
            "series": "1",
            "index": "230",
            "xExact": "231",
            "x": "231",
            "yExact": "0",
            "y": "0",
            "id": "customer:1076"
          },
          {
            "series": "0",
            "index": "231",
            "xExact": "232",
            "x": "232",
            "yExact": "3/205",
            "y": "0.0146341463",
            "id": "customer:1081"
          },
          {
            "series": "1",
            "index": "231",
            "xExact": "232",
            "x": "232",
            "yExact": "0",
            "y": "0",
            "id": "customer:1081"
          },
          {
            "series": "0",
            "index": "232",
            "xExact": "233",
            "x": "233",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:1082"
          },
          {
            "series": "1",
            "index": "232",
            "xExact": "233",
            "x": "233",
            "yExact": "1",
            "y": "1",
            "id": "customer:1082"
          },
          {
            "series": "0",
            "index": "233",
            "xExact": "234",
            "x": "234",
            "yExact": "3/205",
            "y": "0.0146341463",
            "id": "customer:1085"
          },
          {
            "series": "1",
            "index": "233",
            "xExact": "234",
            "x": "234",
            "yExact": "0",
            "y": "0",
            "id": "customer:1085"
          },
          {
            "series": "0",
            "index": "234",
            "xExact": "235",
            "x": "235",
            "yExact": "3/205",
            "y": "0.0146341463",
            "id": "customer:1086"
          },
          {
            "series": "1",
            "index": "234",
            "xExact": "235",
            "x": "235",
            "yExact": "0",
            "y": "0",
            "id": "customer:1086"
          },
          {
            "series": "0",
            "index": "235",
            "xExact": "236",
            "x": "236",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:1090"
          },
          {
            "series": "1",
            "index": "235",
            "xExact": "236",
            "x": "236",
            "yExact": "0",
            "y": "0",
            "id": "customer:1090"
          },
          {
            "series": "0",
            "index": "236",
            "xExact": "237",
            "x": "237",
            "yExact": "2/53",
            "y": "0.0377358491",
            "id": "customer:1096"
          },
          {
            "series": "1",
            "index": "236",
            "xExact": "237",
            "x": "237",
            "yExact": "0",
            "y": "0",
            "id": "customer:1096"
          },
          {
            "series": "0",
            "index": "237",
            "xExact": "238",
            "x": "238",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:1108"
          },
          {
            "series": "1",
            "index": "237",
            "xExact": "238",
            "x": "238",
            "yExact": "0",
            "y": "0",
            "id": "customer:1108"
          },
          {
            "series": "0",
            "index": "238",
            "xExact": "239",
            "x": "239",
            "yExact": "43/218",
            "y": "0.197247706",
            "id": "customer:1114"
          },
          {
            "series": "1",
            "index": "238",
            "xExact": "239",
            "x": "239",
            "yExact": "0",
            "y": "0",
            "id": "customer:1114"
          },
          {
            "series": "0",
            "index": "239",
            "xExact": "240",
            "x": "240",
            "yExact": "43/218",
            "y": "0.197247706",
            "id": "customer:1119"
          },
          {
            "series": "1",
            "index": "239",
            "xExact": "240",
            "x": "240",
            "yExact": "1",
            "y": "1",
            "id": "customer:1119"
          },
          {
            "series": "0",
            "index": "240",
            "xExact": "241",
            "x": "241",
            "yExact": "1/139",
            "y": "0.0071942446",
            "id": "customer:1136"
          },
          {
            "series": "1",
            "index": "240",
            "xExact": "241",
            "x": "241",
            "yExact": "0",
            "y": "0",
            "id": "customer:1136"
          },
          {
            "series": "0",
            "index": "241",
            "xExact": "242",
            "x": "242",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:1142"
          },
          {
            "series": "1",
            "index": "241",
            "xExact": "242",
            "x": "242",
            "yExact": "0",
            "y": "0",
            "id": "customer:1142"
          },
          {
            "series": "0",
            "index": "242",
            "xExact": "243",
            "x": "243",
            "yExact": "3/205",
            "y": "0.0146341463",
            "id": "customer:1156"
          },
          {
            "series": "1",
            "index": "242",
            "xExact": "243",
            "x": "243",
            "yExact": "0",
            "y": "0",
            "id": "customer:1156"
          },
          {
            "series": "0",
            "index": "243",
            "xExact": "244",
            "x": "244",
            "yExact": "3/205",
            "y": "0.0146341463",
            "id": "customer:1159"
          },
          {
            "series": "1",
            "index": "243",
            "xExact": "244",
            "x": "244",
            "yExact": "0",
            "y": "0",
            "id": "customer:1159"
          },
          {
            "series": "0",
            "index": "244",
            "xExact": "245",
            "x": "245",
            "yExact": "4/23",
            "y": "0.173913043",
            "id": "customer:1173"
          },
          {
            "series": "1",
            "index": "244",
            "xExact": "245",
            "x": "245",
            "yExact": "1",
            "y": "1",
            "id": "customer:1173"
          },
          {
            "series": "0",
            "index": "245",
            "xExact": "246",
            "x": "246",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:1192"
          },
          {
            "series": "1",
            "index": "245",
            "xExact": "246",
            "x": "246",
            "yExact": "0",
            "y": "0",
            "id": "customer:1192"
          },
          {
            "series": "0",
            "index": "246",
            "xExact": "247",
            "x": "247",
            "yExact": "43/218",
            "y": "0.197247706",
            "id": "customer:1205"
          },
          {
            "series": "1",
            "index": "246",
            "xExact": "247",
            "x": "247",
            "yExact": "0",
            "y": "0",
            "id": "customer:1205"
          },
          {
            "series": "0",
            "index": "247",
            "xExact": "248",
            "x": "248",
            "yExact": "43/218",
            "y": "0.197247706",
            "id": "customer:1218"
          },
          {
            "series": "1",
            "index": "247",
            "xExact": "248",
            "x": "248",
            "yExact": "0",
            "y": "0",
            "id": "customer:1218"
          },
          {
            "series": "0",
            "index": "248",
            "xExact": "249",
            "x": "249",
            "yExact": "43/218",
            "y": "0.197247706",
            "id": "customer:1219"
          },
          {
            "series": "1",
            "index": "248",
            "xExact": "249",
            "x": "249",
            "yExact": "1",
            "y": "1",
            "id": "customer:1219"
          },
          {
            "series": "0",
            "index": "249",
            "xExact": "250",
            "x": "250",
            "yExact": "1/139",
            "y": "0.0071942446",
            "id": "customer:1220"
          },
          {
            "series": "1",
            "index": "249",
            "xExact": "250",
            "x": "250",
            "yExact": "0",
            "y": "0",
            "id": "customer:1220"
          },
          {
            "series": "0",
            "index": "250",
            "xExact": "251",
            "x": "251",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:1225"
          },
          {
            "series": "1",
            "index": "250",
            "xExact": "251",
            "x": "251",
            "yExact": "1",
            "y": "1",
            "id": "customer:1225"
          },
          {
            "series": "0",
            "index": "251",
            "xExact": "252",
            "x": "252",
            "yExact": "43/218",
            "y": "0.197247706",
            "id": "customer:1229"
          },
          {
            "series": "1",
            "index": "251",
            "xExact": "252",
            "x": "252",
            "yExact": "1",
            "y": "1",
            "id": "customer:1229"
          },
          {
            "series": "0",
            "index": "252",
            "xExact": "253",
            "x": "253",
            "yExact": "6/7",
            "y": "0.857142857",
            "id": "customer:1232"
          },
          {
            "series": "1",
            "index": "252",
            "xExact": "253",
            "x": "253",
            "yExact": "1",
            "y": "1",
            "id": "customer:1232"
          },
          {
            "series": "0",
            "index": "253",
            "xExact": "254",
            "x": "254",
            "yExact": "2/53",
            "y": "0.0377358491",
            "id": "customer:1234"
          },
          {
            "series": "1",
            "index": "253",
            "xExact": "254",
            "x": "254",
            "yExact": "0",
            "y": "0",
            "id": "customer:1234"
          },
          {
            "series": "0",
            "index": "254",
            "xExact": "255",
            "x": "255",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:1240"
          },
          {
            "series": "1",
            "index": "254",
            "xExact": "255",
            "x": "255",
            "yExact": "0",
            "y": "0",
            "id": "customer:1240"
          },
          {
            "series": "0",
            "index": "255",
            "xExact": "256",
            "x": "256",
            "yExact": "3/205",
            "y": "0.0146341463",
            "id": "customer:1244"
          },
          {
            "series": "1",
            "index": "255",
            "xExact": "256",
            "x": "256",
            "yExact": "0",
            "y": "0",
            "id": "customer:1244"
          },
          {
            "series": "0",
            "index": "256",
            "xExact": "257",
            "x": "257",
            "yExact": "2/53",
            "y": "0.0377358491",
            "id": "customer:1246"
          },
          {
            "series": "1",
            "index": "256",
            "xExact": "257",
            "x": "257",
            "yExact": "0",
            "y": "0",
            "id": "customer:1246"
          },
          {
            "series": "0",
            "index": "257",
            "xExact": "258",
            "x": "258",
            "yExact": "2/53",
            "y": "0.0377358491",
            "id": "customer:1247"
          },
          {
            "series": "1",
            "index": "257",
            "xExact": "258",
            "x": "258",
            "yExact": "0",
            "y": "0",
            "id": "customer:1247"
          },
          {
            "series": "0",
            "index": "258",
            "xExact": "259",
            "x": "259",
            "yExact": "3/205",
            "y": "0.0146341463",
            "id": "customer:1254"
          },
          {
            "series": "1",
            "index": "258",
            "xExact": "259",
            "x": "259",
            "yExact": "0",
            "y": "0",
            "id": "customer:1254"
          },
          {
            "series": "0",
            "index": "259",
            "xExact": "260",
            "x": "260",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:1255"
          },
          {
            "series": "1",
            "index": "259",
            "xExact": "260",
            "x": "260",
            "yExact": "0",
            "y": "0",
            "id": "customer:1255"
          },
          {
            "series": "0",
            "index": "260",
            "xExact": "261",
            "x": "261",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:1267"
          },
          {
            "series": "1",
            "index": "260",
            "xExact": "261",
            "x": "261",
            "yExact": "0",
            "y": "0",
            "id": "customer:1267"
          },
          {
            "series": "0",
            "index": "261",
            "xExact": "262",
            "x": "262",
            "yExact": "3/205",
            "y": "0.0146341463",
            "id": "customer:1271"
          },
          {
            "series": "1",
            "index": "261",
            "xExact": "262",
            "x": "262",
            "yExact": "0",
            "y": "0",
            "id": "customer:1271"
          },
          {
            "series": "0",
            "index": "262",
            "xExact": "263",
            "x": "263",
            "yExact": "2/53",
            "y": "0.0377358491",
            "id": "customer:1275"
          },
          {
            "series": "1",
            "index": "262",
            "xExact": "263",
            "x": "263",
            "yExact": "1",
            "y": "1",
            "id": "customer:1275"
          },
          {
            "series": "0",
            "index": "263",
            "xExact": "264",
            "x": "264",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:1278"
          },
          {
            "series": "1",
            "index": "263",
            "xExact": "264",
            "x": "264",
            "yExact": "1",
            "y": "1",
            "id": "customer:1278"
          },
          {
            "series": "0",
            "index": "264",
            "xExact": "265",
            "x": "265",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:1283"
          },
          {
            "series": "1",
            "index": "264",
            "xExact": "265",
            "x": "265",
            "yExact": "0",
            "y": "0",
            "id": "customer:1283"
          },
          {
            "series": "0",
            "index": "265",
            "xExact": "266",
            "x": "266",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:1289"
          },
          {
            "series": "1",
            "index": "265",
            "xExact": "266",
            "x": "266",
            "yExact": "0",
            "y": "0",
            "id": "customer:1289"
          },
          {
            "series": "0",
            "index": "266",
            "xExact": "267",
            "x": "267",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:1294"
          },
          {
            "series": "1",
            "index": "266",
            "xExact": "267",
            "x": "267",
            "yExact": "0",
            "y": "0",
            "id": "customer:1294"
          },
          {
            "series": "0",
            "index": "267",
            "xExact": "268",
            "x": "268",
            "yExact": "3/205",
            "y": "0.0146341463",
            "id": "customer:1297"
          },
          {
            "series": "1",
            "index": "267",
            "xExact": "268",
            "x": "268",
            "yExact": "0",
            "y": "0",
            "id": "customer:1297"
          },
          {
            "series": "0",
            "index": "268",
            "xExact": "269",
            "x": "269",
            "yExact": "43/218",
            "y": "0.197247706",
            "id": "customer:1307"
          },
          {
            "series": "1",
            "index": "268",
            "xExact": "269",
            "x": "269",
            "yExact": "0",
            "y": "0",
            "id": "customer:1307"
          },
          {
            "series": "0",
            "index": "269",
            "xExact": "270",
            "x": "270",
            "yExact": "1/139",
            "y": "0.0071942446",
            "id": "customer:1311"
          },
          {
            "series": "1",
            "index": "269",
            "xExact": "270",
            "x": "270",
            "yExact": "0",
            "y": "0",
            "id": "customer:1311"
          },
          {
            "series": "0",
            "index": "270",
            "xExact": "271",
            "x": "271",
            "yExact": "43/218",
            "y": "0.197247706",
            "id": "customer:1317"
          },
          {
            "series": "1",
            "index": "270",
            "xExact": "271",
            "x": "271",
            "yExact": "0",
            "y": "0",
            "id": "customer:1317"
          },
          {
            "series": "0",
            "index": "271",
            "xExact": "272",
            "x": "272",
            "yExact": "43/218",
            "y": "0.197247706",
            "id": "customer:1319"
          },
          {
            "series": "1",
            "index": "271",
            "xExact": "272",
            "x": "272",
            "yExact": "1",
            "y": "1",
            "id": "customer:1319"
          },
          {
            "series": "0",
            "index": "272",
            "xExact": "273",
            "x": "273",
            "yExact": "1/139",
            "y": "0.0071942446",
            "id": "customer:1320"
          },
          {
            "series": "1",
            "index": "272",
            "xExact": "273",
            "x": "273",
            "yExact": "0",
            "y": "0",
            "id": "customer:1320"
          },
          {
            "series": "0",
            "index": "273",
            "xExact": "274",
            "x": "274",
            "yExact": "17/29",
            "y": "0.586206897",
            "id": "customer:1324"
          },
          {
            "series": "1",
            "index": "273",
            "xExact": "274",
            "x": "274",
            "yExact": "0",
            "y": "0",
            "id": "customer:1324"
          },
          {
            "series": "0",
            "index": "274",
            "xExact": "275",
            "x": "275",
            "yExact": "17/29",
            "y": "0.586206897",
            "id": "customer:1327"
          },
          {
            "series": "1",
            "index": "274",
            "xExact": "275",
            "x": "275",
            "yExact": "1",
            "y": "1",
            "id": "customer:1327"
          },
          {
            "series": "0",
            "index": "275",
            "xExact": "276",
            "x": "276",
            "yExact": "17/112",
            "y": "0.151785714",
            "id": "customer:1328"
          },
          {
            "series": "1",
            "index": "275",
            "xExact": "276",
            "x": "276",
            "yExact": "1",
            "y": "1",
            "id": "customer:1328"
          },
          {
            "series": "0",
            "index": "276",
            "xExact": "277",
            "x": "277",
            "yExact": "6/7",
            "y": "0.857142857",
            "id": "customer:1332"
          },
          {
            "series": "1",
            "index": "276",
            "xExact": "277",
            "x": "277",
            "yExact": "1",
            "y": "1",
            "id": "customer:1332"
          },
          {
            "series": "0",
            "index": "277",
            "xExact": "278",
            "x": "278",
            "yExact": "2/53",
            "y": "0.0377358491",
            "id": "customer:1334"
          },
          {
            "series": "1",
            "index": "277",
            "xExact": "278",
            "x": "278",
            "yExact": "0",
            "y": "0",
            "id": "customer:1334"
          },
          {
            "series": "0",
            "index": "278",
            "xExact": "279",
            "x": "279",
            "yExact": "43/218",
            "y": "0.197247706",
            "id": "customer:1337"
          },
          {
            "series": "1",
            "index": "278",
            "xExact": "279",
            "x": "279",
            "yExact": "0",
            "y": "0",
            "id": "customer:1337"
          },
          {
            "series": "0",
            "index": "279",
            "xExact": "280",
            "x": "280",
            "yExact": "43/218",
            "y": "0.197247706",
            "id": "customer:1338"
          },
          {
            "series": "1",
            "index": "279",
            "xExact": "280",
            "x": "280",
            "yExact": "0",
            "y": "0",
            "id": "customer:1338"
          },
          {
            "series": "0",
            "index": "280",
            "xExact": "281",
            "x": "281",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:1339"
          },
          {
            "series": "1",
            "index": "280",
            "xExact": "281",
            "x": "281",
            "yExact": "0",
            "y": "0",
            "id": "customer:1339"
          },
          {
            "series": "0",
            "index": "281",
            "xExact": "282",
            "x": "282",
            "yExact": "3/205",
            "y": "0.0146341463",
            "id": "customer:1351"
          },
          {
            "series": "1",
            "index": "281",
            "xExact": "282",
            "x": "282",
            "yExact": "0",
            "y": "0",
            "id": "customer:1351"
          },
          {
            "series": "0",
            "index": "282",
            "xExact": "283",
            "x": "283",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:1352"
          },
          {
            "series": "1",
            "index": "282",
            "xExact": "283",
            "x": "283",
            "yExact": "0",
            "y": "0",
            "id": "customer:1352"
          },
          {
            "series": "0",
            "index": "283",
            "xExact": "284",
            "x": "284",
            "yExact": "2/53",
            "y": "0.0377358491",
            "id": "customer:1363"
          },
          {
            "series": "1",
            "index": "283",
            "xExact": "284",
            "x": "284",
            "yExact": "0",
            "y": "0",
            "id": "customer:1363"
          },
          {
            "series": "0",
            "index": "284",
            "xExact": "285",
            "x": "285",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:1364"
          },
          {
            "series": "1",
            "index": "284",
            "xExact": "285",
            "x": "285",
            "yExact": "0",
            "y": "0",
            "id": "customer:1364"
          },
          {
            "series": "0",
            "index": "285",
            "xExact": "286",
            "x": "286",
            "yExact": "3/205",
            "y": "0.0146341463",
            "id": "customer:1365"
          },
          {
            "series": "1",
            "index": "285",
            "xExact": "286",
            "x": "286",
            "yExact": "0",
            "y": "0",
            "id": "customer:1365"
          },
          {
            "series": "0",
            "index": "286",
            "xExact": "287",
            "x": "287",
            "yExact": "3/205",
            "y": "0.0146341463",
            "id": "customer:1366"
          },
          {
            "series": "1",
            "index": "286",
            "xExact": "287",
            "x": "287",
            "yExact": "0",
            "y": "0",
            "id": "customer:1366"
          },
          {
            "series": "0",
            "index": "287",
            "xExact": "288",
            "x": "288",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:1367"
          },
          {
            "series": "1",
            "index": "287",
            "xExact": "288",
            "x": "288",
            "yExact": "0",
            "y": "0",
            "id": "customer:1367"
          },
          {
            "series": "0",
            "index": "288",
            "xExact": "289",
            "x": "289",
            "yExact": "3/205",
            "y": "0.0146341463",
            "id": "customer:1372"
          },
          {
            "series": "1",
            "index": "288",
            "xExact": "289",
            "x": "289",
            "yExact": "0",
            "y": "0",
            "id": "customer:1372"
          },
          {
            "series": "0",
            "index": "289",
            "xExact": "290",
            "x": "290",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:1376"
          },
          {
            "series": "1",
            "index": "289",
            "xExact": "290",
            "x": "290",
            "yExact": "0",
            "y": "0",
            "id": "customer:1376"
          },
          {
            "series": "0",
            "index": "290",
            "xExact": "291",
            "x": "291",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:1388"
          },
          {
            "series": "1",
            "index": "290",
            "xExact": "291",
            "x": "291",
            "yExact": "0",
            "y": "0",
            "id": "customer:1388"
          },
          {
            "series": "0",
            "index": "291",
            "xExact": "292",
            "x": "292",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:1389"
          },
          {
            "series": "1",
            "index": "291",
            "xExact": "292",
            "x": "292",
            "yExact": "0",
            "y": "0",
            "id": "customer:1389"
          },
          {
            "series": "0",
            "index": "292",
            "xExact": "293",
            "x": "293",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:1392"
          },
          {
            "series": "1",
            "index": "292",
            "xExact": "293",
            "x": "293",
            "yExact": "0",
            "y": "0",
            "id": "customer:1392"
          },
          {
            "series": "0",
            "index": "293",
            "xExact": "294",
            "x": "294",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:1394"
          },
          {
            "series": "1",
            "index": "293",
            "xExact": "294",
            "x": "294",
            "yExact": "0",
            "y": "0",
            "id": "customer:1394"
          },
          {
            "series": "0",
            "index": "294",
            "xExact": "295",
            "x": "295",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:1395"
          },
          {
            "series": "1",
            "index": "294",
            "xExact": "295",
            "x": "295",
            "yExact": "0",
            "y": "0",
            "id": "customer:1395"
          },
          {
            "series": "0",
            "index": "295",
            "xExact": "296",
            "x": "296",
            "yExact": "1/139",
            "y": "0.0071942446",
            "id": "customer:1401"
          },
          {
            "series": "1",
            "index": "295",
            "xExact": "296",
            "x": "296",
            "yExact": "0",
            "y": "0",
            "id": "customer:1401"
          },
          {
            "series": "0",
            "index": "296",
            "xExact": "297",
            "x": "297",
            "yExact": "43/218",
            "y": "0.197247706",
            "id": "customer:1412"
          },
          {
            "series": "1",
            "index": "296",
            "xExact": "297",
            "x": "297",
            "yExact": "0",
            "y": "0",
            "id": "customer:1412"
          },
          {
            "series": "0",
            "index": "297",
            "xExact": "298",
            "x": "298",
            "yExact": "1/139",
            "y": "0.0071942446",
            "id": "customer:1414"
          },
          {
            "series": "1",
            "index": "297",
            "xExact": "298",
            "x": "298",
            "yExact": "0",
            "y": "0",
            "id": "customer:1414"
          },
          {
            "series": "0",
            "index": "298",
            "xExact": "299",
            "x": "299",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:1426"
          },
          {
            "series": "1",
            "index": "298",
            "xExact": "299",
            "x": "299",
            "yExact": "0",
            "y": "0",
            "id": "customer:1426"
          },
          {
            "series": "0",
            "index": "299",
            "xExact": "300",
            "x": "300",
            "yExact": "43/218",
            "y": "0.197247706",
            "id": "customer:1438"
          },
          {
            "series": "1",
            "index": "299",
            "xExact": "300",
            "x": "300",
            "yExact": "0",
            "y": "0",
            "id": "customer:1438"
          },
          {
            "series": "0",
            "index": "300",
            "xExact": "301",
            "x": "301",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:1440"
          },
          {
            "series": "1",
            "index": "300",
            "xExact": "301",
            "x": "301",
            "yExact": "0",
            "y": "0",
            "id": "customer:1440"
          },
          {
            "series": "0",
            "index": "301",
            "xExact": "302",
            "x": "302",
            "yExact": "3/205",
            "y": "0.0146341463",
            "id": "customer:1449"
          },
          {
            "series": "1",
            "index": "301",
            "xExact": "302",
            "x": "302",
            "yExact": "0",
            "y": "0",
            "id": "customer:1449"
          },
          {
            "series": "0",
            "index": "302",
            "xExact": "303",
            "x": "303",
            "yExact": "3/205",
            "y": "0.0146341463",
            "id": "customer:1458"
          },
          {
            "series": "1",
            "index": "302",
            "xExact": "303",
            "x": "303",
            "yExact": "0",
            "y": "0",
            "id": "customer:1458"
          },
          {
            "series": "0",
            "index": "303",
            "xExact": "304",
            "x": "304",
            "yExact": "3/205",
            "y": "0.0146341463",
            "id": "customer:1459"
          },
          {
            "series": "1",
            "index": "303",
            "xExact": "304",
            "x": "304",
            "yExact": "0",
            "y": "0",
            "id": "customer:1459"
          },
          {
            "series": "0",
            "index": "304",
            "xExact": "305",
            "x": "305",
            "yExact": "3/205",
            "y": "0.0146341463",
            "id": "customer:1472"
          },
          {
            "series": "1",
            "index": "304",
            "xExact": "305",
            "x": "305",
            "yExact": "0",
            "y": "0",
            "id": "customer:1472"
          },
          {
            "series": "0",
            "index": "305",
            "xExact": "306",
            "x": "306",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:1478"
          },
          {
            "series": "1",
            "index": "305",
            "xExact": "306",
            "x": "306",
            "yExact": "1",
            "y": "1",
            "id": "customer:1478"
          },
          {
            "series": "0",
            "index": "306",
            "xExact": "307",
            "x": "307",
            "yExact": "3/205",
            "y": "0.0146341463",
            "id": "customer:1485"
          },
          {
            "series": "1",
            "index": "306",
            "xExact": "307",
            "x": "307",
            "yExact": "0",
            "y": "0",
            "id": "customer:1485"
          },
          {
            "series": "0",
            "index": "307",
            "xExact": "308",
            "x": "308",
            "yExact": "3/205",
            "y": "0.0146341463",
            "id": "customer:1486"
          },
          {
            "series": "1",
            "index": "307",
            "xExact": "308",
            "x": "308",
            "yExact": "0",
            "y": "0",
            "id": "customer:1486"
          },
          {
            "series": "0",
            "index": "308",
            "xExact": "309",
            "x": "309",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:1488"
          },
          {
            "series": "1",
            "index": "308",
            "xExact": "309",
            "x": "309",
            "yExact": "0",
            "y": "0",
            "id": "customer:1488"
          },
          {
            "series": "0",
            "index": "309",
            "xExact": "310",
            "x": "310",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:1490"
          },
          {
            "series": "1",
            "index": "309",
            "xExact": "310",
            "x": "310",
            "yExact": "0",
            "y": "0",
            "id": "customer:1490"
          },
          {
            "series": "0",
            "index": "310",
            "xExact": "311",
            "x": "311",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:1491"
          },
          {
            "series": "1",
            "index": "310",
            "xExact": "311",
            "x": "311",
            "yExact": "0",
            "y": "0",
            "id": "customer:1491"
          },
          {
            "series": "0",
            "index": "311",
            "xExact": "312",
            "x": "312",
            "yExact": "3/205",
            "y": "0.0146341463",
            "id": "customer:1497"
          },
          {
            "series": "1",
            "index": "311",
            "xExact": "312",
            "x": "312",
            "yExact": "0",
            "y": "0",
            "id": "customer:1497"
          },
          {
            "series": "0",
            "index": "312",
            "xExact": "313",
            "x": "313",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:1500"
          },
          {
            "series": "1",
            "index": "312",
            "xExact": "313",
            "x": "313",
            "yExact": "1",
            "y": "1",
            "id": "customer:1500"
          },
          {
            "series": "0",
            "index": "313",
            "xExact": "314",
            "x": "314",
            "yExact": "1/139",
            "y": "0.0071942446",
            "id": "customer:1509"
          },
          {
            "series": "1",
            "index": "313",
            "xExact": "314",
            "x": "314",
            "yExact": "0",
            "y": "0",
            "id": "customer:1509"
          },
          {
            "series": "0",
            "index": "314",
            "xExact": "315",
            "x": "315",
            "yExact": "43/218",
            "y": "0.197247706",
            "id": "customer:1518"
          },
          {
            "series": "1",
            "index": "314",
            "xExact": "315",
            "x": "315",
            "yExact": "0",
            "y": "0",
            "id": "customer:1518"
          },
          {
            "series": "0",
            "index": "315",
            "xExact": "316",
            "x": "316",
            "yExact": "2/53",
            "y": "0.0377358491",
            "id": "customer:1524"
          },
          {
            "series": "1",
            "index": "315",
            "xExact": "316",
            "x": "316",
            "yExact": "0",
            "y": "0",
            "id": "customer:1524"
          },
          {
            "series": "0",
            "index": "316",
            "xExact": "317",
            "x": "317",
            "yExact": "18/19",
            "y": "0.947368421",
            "id": "customer:1528"
          },
          {
            "series": "1",
            "index": "316",
            "xExact": "317",
            "x": "317",
            "yExact": "1",
            "y": "1",
            "id": "customer:1528"
          },
          {
            "series": "0",
            "index": "317",
            "xExact": "318",
            "x": "318",
            "yExact": "3/205",
            "y": "0.0146341463",
            "id": "customer:1531"
          },
          {
            "series": "1",
            "index": "317",
            "xExact": "318",
            "x": "318",
            "yExact": "0",
            "y": "0",
            "id": "customer:1531"
          },
          {
            "series": "0",
            "index": "318",
            "xExact": "319",
            "x": "319",
            "yExact": "2/53",
            "y": "0.0377358491",
            "id": "customer:1547"
          },
          {
            "series": "1",
            "index": "318",
            "xExact": "319",
            "x": "319",
            "yExact": "0",
            "y": "0",
            "id": "customer:1547"
          },
          {
            "series": "0",
            "index": "319",
            "xExact": "320",
            "x": "320",
            "yExact": "1/139",
            "y": "0.0071942446",
            "id": "customer:1560"
          },
          {
            "series": "1",
            "index": "319",
            "xExact": "320",
            "x": "320",
            "yExact": "0",
            "y": "0",
            "id": "customer:1560"
          },
          {
            "series": "0",
            "index": "320",
            "xExact": "321",
            "x": "321",
            "yExact": "43/218",
            "y": "0.197247706",
            "id": "customer:1562"
          },
          {
            "series": "1",
            "index": "320",
            "xExact": "321",
            "x": "321",
            "yExact": "0",
            "y": "0",
            "id": "customer:1562"
          },
          {
            "series": "0",
            "index": "321",
            "xExact": "322",
            "x": "322",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:1563"
          },
          {
            "series": "1",
            "index": "321",
            "xExact": "322",
            "x": "322",
            "yExact": "0",
            "y": "0",
            "id": "customer:1563"
          },
          {
            "series": "0",
            "index": "322",
            "xExact": "323",
            "x": "323",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:1569"
          },
          {
            "series": "1",
            "index": "322",
            "xExact": "323",
            "x": "323",
            "yExact": "1",
            "y": "1",
            "id": "customer:1569"
          },
          {
            "series": "0",
            "index": "323",
            "xExact": "324",
            "x": "324",
            "yExact": "2/53",
            "y": "0.0377358491",
            "id": "customer:1574"
          },
          {
            "series": "1",
            "index": "323",
            "xExact": "324",
            "x": "324",
            "yExact": "0",
            "y": "0",
            "id": "customer:1574"
          },
          {
            "series": "0",
            "index": "324",
            "xExact": "325",
            "x": "325",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:1576"
          },
          {
            "series": "1",
            "index": "324",
            "xExact": "325",
            "x": "325",
            "yExact": "0",
            "y": "0",
            "id": "customer:1576"
          },
          {
            "series": "0",
            "index": "325",
            "xExact": "326",
            "x": "326",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:1579"
          },
          {
            "series": "1",
            "index": "325",
            "xExact": "326",
            "x": "326",
            "yExact": "1",
            "y": "1",
            "id": "customer:1579"
          },
          {
            "series": "0",
            "index": "326",
            "xExact": "327",
            "x": "327",
            "yExact": "23/24",
            "y": "0.958333333",
            "id": "customer:1582"
          },
          {
            "series": "1",
            "index": "326",
            "xExact": "327",
            "x": "327",
            "yExact": "1",
            "y": "1",
            "id": "customer:1582"
          },
          {
            "series": "0",
            "index": "327",
            "xExact": "328",
            "x": "328",
            "yExact": "2/53",
            "y": "0.0377358491",
            "id": "customer:1584"
          },
          {
            "series": "1",
            "index": "327",
            "xExact": "328",
            "x": "328",
            "yExact": "0",
            "y": "0",
            "id": "customer:1584"
          },
          {
            "series": "0",
            "index": "328",
            "xExact": "329",
            "x": "329",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:1586"
          },
          {
            "series": "1",
            "index": "328",
            "xExact": "329",
            "x": "329",
            "yExact": "0",
            "y": "0",
            "id": "customer:1586"
          },
          {
            "series": "0",
            "index": "329",
            "xExact": "330",
            "x": "330",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:1591"
          },
          {
            "series": "1",
            "index": "329",
            "xExact": "330",
            "x": "330",
            "yExact": "0",
            "y": "0",
            "id": "customer:1591"
          },
          {
            "series": "0",
            "index": "330",
            "xExact": "331",
            "x": "331",
            "yExact": "3/205",
            "y": "0.0146341463",
            "id": "customer:1597"
          },
          {
            "series": "1",
            "index": "330",
            "xExact": "331",
            "x": "331",
            "yExact": "0",
            "y": "0",
            "id": "customer:1597"
          },
          {
            "series": "0",
            "index": "331",
            "xExact": "332",
            "x": "332",
            "yExact": "1/139",
            "y": "0.0071942446",
            "id": "customer:1604"
          },
          {
            "series": "1",
            "index": "331",
            "xExact": "332",
            "x": "332",
            "yExact": "0",
            "y": "0",
            "id": "customer:1604"
          },
          {
            "series": "0",
            "index": "332",
            "xExact": "333",
            "x": "333",
            "yExact": "43/218",
            "y": "0.197247706",
            "id": "customer:1619"
          },
          {
            "series": "1",
            "index": "332",
            "xExact": "333",
            "x": "333",
            "yExact": "1",
            "y": "1",
            "id": "customer:1619"
          },
          {
            "series": "0",
            "index": "333",
            "xExact": "334",
            "x": "334",
            "yExact": "1/139",
            "y": "0.0071942446",
            "id": "customer:1622"
          },
          {
            "series": "1",
            "index": "333",
            "xExact": "334",
            "x": "334",
            "yExact": "0",
            "y": "0",
            "id": "customer:1622"
          },
          {
            "series": "0",
            "index": "334",
            "xExact": "335",
            "x": "335",
            "yExact": "23/24",
            "y": "0.958333333",
            "id": "customer:1627"
          },
          {
            "series": "1",
            "index": "334",
            "xExact": "335",
            "x": "335",
            "yExact": "1",
            "y": "1",
            "id": "customer:1627"
          },
          {
            "series": "0",
            "index": "335",
            "xExact": "336",
            "x": "336",
            "yExact": "2/53",
            "y": "0.0377358491",
            "id": "customer:1634"
          },
          {
            "series": "1",
            "index": "335",
            "xExact": "336",
            "x": "336",
            "yExact": "0",
            "y": "0",
            "id": "customer:1634"
          },
          {
            "series": "0",
            "index": "336",
            "xExact": "337",
            "x": "337",
            "yExact": "3/205",
            "y": "0.0146341463",
            "id": "customer:1636"
          },
          {
            "series": "1",
            "index": "336",
            "xExact": "337",
            "x": "337",
            "yExact": "0",
            "y": "0",
            "id": "customer:1636"
          },
          {
            "series": "0",
            "index": "337",
            "xExact": "338",
            "x": "338",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:1645"
          },
          {
            "series": "1",
            "index": "337",
            "xExact": "338",
            "x": "338",
            "yExact": "0",
            "y": "0",
            "id": "customer:1645"
          },
          {
            "series": "0",
            "index": "338",
            "xExact": "339",
            "x": "339",
            "yExact": "2/53",
            "y": "0.0377358491",
            "id": "customer:1646"
          },
          {
            "series": "1",
            "index": "338",
            "xExact": "339",
            "x": "339",
            "yExact": "0",
            "y": "0",
            "id": "customer:1646"
          },
          {
            "series": "0",
            "index": "339",
            "xExact": "340",
            "x": "340",
            "yExact": "3/205",
            "y": "0.0146341463",
            "id": "customer:1649"
          },
          {
            "series": "1",
            "index": "339",
            "xExact": "340",
            "x": "340",
            "yExact": "0",
            "y": "0",
            "id": "customer:1649"
          },
          {
            "series": "0",
            "index": "340",
            "xExact": "341",
            "x": "341",
            "yExact": "2/53",
            "y": "0.0377358491",
            "id": "customer:1658"
          },
          {
            "series": "1",
            "index": "340",
            "xExact": "341",
            "x": "341",
            "yExact": "0",
            "y": "0",
            "id": "customer:1658"
          },
          {
            "series": "0",
            "index": "341",
            "xExact": "342",
            "x": "342",
            "yExact": "3/205",
            "y": "0.0146341463",
            "id": "customer:1661"
          },
          {
            "series": "1",
            "index": "341",
            "xExact": "342",
            "x": "342",
            "yExact": "0",
            "y": "0",
            "id": "customer:1661"
          },
          {
            "series": "0",
            "index": "342",
            "xExact": "343",
            "x": "343",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:1662"
          },
          {
            "series": "1",
            "index": "342",
            "xExact": "343",
            "x": "343",
            "yExact": "0",
            "y": "0",
            "id": "customer:1662"
          },
          {
            "series": "0",
            "index": "343",
            "xExact": "344",
            "x": "344",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:1664"
          },
          {
            "series": "1",
            "index": "343",
            "xExact": "344",
            "x": "344",
            "yExact": "0",
            "y": "0",
            "id": "customer:1664"
          },
          {
            "series": "0",
            "index": "344",
            "xExact": "345",
            "x": "345",
            "yExact": "3/205",
            "y": "0.0146341463",
            "id": "customer:1672"
          },
          {
            "series": "1",
            "index": "344",
            "xExact": "345",
            "x": "345",
            "yExact": "0",
            "y": "0",
            "id": "customer:1672"
          },
          {
            "series": "0",
            "index": "345",
            "xExact": "346",
            "x": "346",
            "yExact": "2/53",
            "y": "0.0377358491",
            "id": "customer:1675"
          },
          {
            "series": "1",
            "index": "345",
            "xExact": "346",
            "x": "346",
            "yExact": "1",
            "y": "1",
            "id": "customer:1675"
          },
          {
            "series": "0",
            "index": "346",
            "xExact": "347",
            "x": "347",
            "yExact": "3/205",
            "y": "0.0146341463",
            "id": "customer:1685"
          },
          {
            "series": "1",
            "index": "346",
            "xExact": "347",
            "x": "347",
            "yExact": "0",
            "y": "0",
            "id": "customer:1685"
          },
          {
            "series": "0",
            "index": "347",
            "xExact": "348",
            "x": "348",
            "yExact": "3/205",
            "y": "0.0146341463",
            "id": "customer:1699"
          },
          {
            "series": "1",
            "index": "347",
            "xExact": "348",
            "x": "348",
            "yExact": "0",
            "y": "0",
            "id": "customer:1699"
          },
          {
            "series": "0",
            "index": "348",
            "xExact": "349",
            "x": "349",
            "yExact": "3/205",
            "y": "0.0146341463",
            "id": "customer:1716"
          },
          {
            "series": "1",
            "index": "348",
            "xExact": "349",
            "x": "349",
            "yExact": "0",
            "y": "0",
            "id": "customer:1716"
          },
          {
            "series": "0",
            "index": "349",
            "xExact": "350",
            "x": "350",
            "yExact": "3/205",
            "y": "0.0146341463",
            "id": "customer:1720"
          },
          {
            "series": "1",
            "index": "349",
            "xExact": "350",
            "x": "350",
            "yExact": "0",
            "y": "0",
            "id": "customer:1720"
          },
          {
            "series": "0",
            "index": "350",
            "xExact": "351",
            "x": "351",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:1729"
          },
          {
            "series": "1",
            "index": "350",
            "xExact": "351",
            "x": "351",
            "yExact": "1",
            "y": "1",
            "id": "customer:1729"
          },
          {
            "series": "0",
            "index": "351",
            "xExact": "352",
            "x": "352",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:1733"
          },
          {
            "series": "1",
            "index": "351",
            "xExact": "352",
            "x": "352",
            "yExact": "0",
            "y": "0",
            "id": "customer:1733"
          },
          {
            "series": "0",
            "index": "352",
            "xExact": "353",
            "x": "353",
            "yExact": "3/205",
            "y": "0.0146341463",
            "id": "customer:1735"
          },
          {
            "series": "1",
            "index": "352",
            "xExact": "353",
            "x": "353",
            "yExact": "0",
            "y": "0",
            "id": "customer:1735"
          },
          {
            "series": "0",
            "index": "353",
            "xExact": "354",
            "x": "354",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:1739"
          },
          {
            "series": "1",
            "index": "353",
            "xExact": "354",
            "x": "354",
            "yExact": "0",
            "y": "0",
            "id": "customer:1739"
          },
          {
            "series": "0",
            "index": "354",
            "xExact": "355",
            "x": "355",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:1745"
          },
          {
            "series": "1",
            "index": "354",
            "xExact": "355",
            "x": "355",
            "yExact": "0",
            "y": "0",
            "id": "customer:1745"
          },
          {
            "series": "0",
            "index": "355",
            "xExact": "356",
            "x": "356",
            "yExact": "3/205",
            "y": "0.0146341463",
            "id": "customer:1749"
          },
          {
            "series": "1",
            "index": "355",
            "xExact": "356",
            "x": "356",
            "yExact": "0",
            "y": "0",
            "id": "customer:1749"
          },
          {
            "series": "0",
            "index": "356",
            "xExact": "357",
            "x": "357",
            "yExact": "23/24",
            "y": "0.958333333",
            "id": "customer:1750"
          },
          {
            "series": "1",
            "index": "356",
            "xExact": "357",
            "x": "357",
            "yExact": "1",
            "y": "1",
            "id": "customer:1750"
          },
          {
            "series": "0",
            "index": "357",
            "xExact": "358",
            "x": "358",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:1753"
          },
          {
            "series": "1",
            "index": "357",
            "xExact": "358",
            "x": "358",
            "yExact": "0",
            "y": "0",
            "id": "customer:1753"
          },
          {
            "series": "0",
            "index": "358",
            "xExact": "359",
            "x": "359",
            "yExact": "1/139",
            "y": "0.0071942446",
            "id": "customer:1759"
          },
          {
            "series": "1",
            "index": "358",
            "xExact": "359",
            "x": "359",
            "yExact": "0",
            "y": "0",
            "id": "customer:1759"
          },
          {
            "series": "0",
            "index": "359",
            "xExact": "360",
            "x": "360",
            "yExact": "3/205",
            "y": "0.0146341463",
            "id": "customer:1765"
          },
          {
            "series": "1",
            "index": "359",
            "xExact": "360",
            "x": "360",
            "yExact": "0",
            "y": "0",
            "id": "customer:1765"
          },
          {
            "series": "0",
            "index": "360",
            "xExact": "361",
            "x": "361",
            "yExact": "43/218",
            "y": "0.197247706",
            "id": "customer:1768"
          },
          {
            "series": "1",
            "index": "360",
            "xExact": "361",
            "x": "361",
            "yExact": "0",
            "y": "0",
            "id": "customer:1768"
          },
          {
            "series": "0",
            "index": "361",
            "xExact": "362",
            "x": "362",
            "yExact": "3/205",
            "y": "0.0146341463",
            "id": "customer:1770"
          },
          {
            "series": "1",
            "index": "361",
            "xExact": "362",
            "x": "362",
            "yExact": "0",
            "y": "0",
            "id": "customer:1770"
          },
          {
            "series": "0",
            "index": "362",
            "xExact": "363",
            "x": "363",
            "yExact": "3/205",
            "y": "0.0146341463",
            "id": "customer:1772"
          },
          {
            "series": "1",
            "index": "362",
            "xExact": "363",
            "x": "363",
            "yExact": "0",
            "y": "0",
            "id": "customer:1772"
          },
          {
            "series": "0",
            "index": "363",
            "xExact": "364",
            "x": "364",
            "yExact": "2/53",
            "y": "0.0377358491",
            "id": "customer:1784"
          },
          {
            "series": "1",
            "index": "363",
            "xExact": "364",
            "x": "364",
            "yExact": "0",
            "y": "0",
            "id": "customer:1784"
          },
          {
            "series": "0",
            "index": "364",
            "xExact": "365",
            "x": "365",
            "yExact": "3/205",
            "y": "0.0146341463",
            "id": "customer:1786"
          },
          {
            "series": "1",
            "index": "364",
            "xExact": "365",
            "x": "365",
            "yExact": "0",
            "y": "0",
            "id": "customer:1786"
          },
          {
            "series": "0",
            "index": "365",
            "xExact": "366",
            "x": "366",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:1787"
          },
          {
            "series": "1",
            "index": "365",
            "xExact": "366",
            "x": "366",
            "yExact": "0",
            "y": "0",
            "id": "customer:1787"
          },
          {
            "series": "0",
            "index": "366",
            "xExact": "367",
            "x": "367",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:1792"
          },
          {
            "series": "1",
            "index": "366",
            "xExact": "367",
            "x": "367",
            "yExact": "0",
            "y": "0",
            "id": "customer:1792"
          },
          {
            "series": "0",
            "index": "367",
            "xExact": "368",
            "x": "368",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:1794"
          },
          {
            "series": "1",
            "index": "367",
            "xExact": "368",
            "x": "368",
            "yExact": "0",
            "y": "0",
            "id": "customer:1794"
          },
          {
            "series": "0",
            "index": "368",
            "xExact": "369",
            "x": "369",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:1795"
          },
          {
            "series": "1",
            "index": "368",
            "xExact": "369",
            "x": "369",
            "yExact": "0",
            "y": "0",
            "id": "customer:1795"
          },
          {
            "series": "0",
            "index": "369",
            "xExact": "370",
            "x": "370",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:1798"
          },
          {
            "series": "1",
            "index": "369",
            "xExact": "370",
            "x": "370",
            "yExact": "0",
            "y": "0",
            "id": "customer:1798"
          },
          {
            "series": "0",
            "index": "370",
            "xExact": "371",
            "x": "371",
            "yExact": "3/205",
            "y": "0.0146341463",
            "id": "customer:1799"
          },
          {
            "series": "1",
            "index": "370",
            "xExact": "371",
            "x": "371",
            "yExact": "0",
            "y": "0",
            "id": "customer:1799"
          },
          {
            "series": "0",
            "index": "371",
            "xExact": "372",
            "x": "372",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:1803"
          },
          {
            "series": "1",
            "index": "371",
            "xExact": "372",
            "x": "372",
            "yExact": "0",
            "y": "0",
            "id": "customer:1803"
          },
          {
            "series": "0",
            "index": "372",
            "xExact": "373",
            "x": "373",
            "yExact": "3/205",
            "y": "0.0146341463",
            "id": "customer:1808"
          },
          {
            "series": "1",
            "index": "372",
            "xExact": "373",
            "x": "373",
            "yExact": "0",
            "y": "0",
            "id": "customer:1808"
          },
          {
            "series": "0",
            "index": "373",
            "xExact": "374",
            "x": "374",
            "yExact": "4/23",
            "y": "0.173913043",
            "id": "customer:1823"
          },
          {
            "series": "1",
            "index": "373",
            "xExact": "374",
            "x": "374",
            "yExact": "1",
            "y": "1",
            "id": "customer:1823"
          },
          {
            "series": "0",
            "index": "374",
            "xExact": "375",
            "x": "375",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:1827"
          },
          {
            "series": "1",
            "index": "374",
            "xExact": "375",
            "x": "375",
            "yExact": "1",
            "y": "1",
            "id": "customer:1827"
          },
          {
            "series": "0",
            "index": "375",
            "xExact": "376",
            "x": "376",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:1828"
          },
          {
            "series": "1",
            "index": "375",
            "xExact": "376",
            "x": "376",
            "yExact": "1",
            "y": "1",
            "id": "customer:1828"
          },
          {
            "series": "0",
            "index": "376",
            "xExact": "377",
            "x": "377",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:1832"
          },
          {
            "series": "1",
            "index": "376",
            "xExact": "377",
            "x": "377",
            "yExact": "1",
            "y": "1",
            "id": "customer:1832"
          },
          {
            "series": "0",
            "index": "377",
            "xExact": "378",
            "x": "378",
            "yExact": "2/53",
            "y": "0.0377358491",
            "id": "customer:1834"
          },
          {
            "series": "1",
            "index": "377",
            "xExact": "378",
            "x": "378",
            "yExact": "0",
            "y": "0",
            "id": "customer:1834"
          },
          {
            "series": "0",
            "index": "378",
            "xExact": "379",
            "x": "379",
            "yExact": "3/205",
            "y": "0.0146341463",
            "id": "customer:1836"
          },
          {
            "series": "1",
            "index": "378",
            "xExact": "379",
            "x": "379",
            "yExact": "0",
            "y": "0",
            "id": "customer:1836"
          },
          {
            "series": "0",
            "index": "379",
            "xExact": "380",
            "x": "380",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:1837"
          },
          {
            "series": "1",
            "index": "379",
            "xExact": "380",
            "x": "380",
            "yExact": "0",
            "y": "0",
            "id": "customer:1837"
          },
          {
            "series": "0",
            "index": "380",
            "xExact": "381",
            "x": "381",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:1839"
          },
          {
            "series": "1",
            "index": "380",
            "xExact": "381",
            "x": "381",
            "yExact": "0",
            "y": "0",
            "id": "customer:1839"
          },
          {
            "series": "0",
            "index": "381",
            "xExact": "382",
            "x": "382",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:1844"
          },
          {
            "series": "1",
            "index": "381",
            "xExact": "382",
            "x": "382",
            "yExact": "0",
            "y": "0",
            "id": "customer:1844"
          },
          {
            "series": "0",
            "index": "382",
            "xExact": "383",
            "x": "383",
            "yExact": "43/218",
            "y": "0.197247706",
            "id": "customer:1852"
          },
          {
            "series": "1",
            "index": "382",
            "xExact": "383",
            "x": "383",
            "yExact": "0",
            "y": "0",
            "id": "customer:1852"
          },
          {
            "series": "0",
            "index": "383",
            "xExact": "384",
            "x": "384",
            "yExact": "17/112",
            "y": "0.151785714",
            "id": "customer:1853"
          },
          {
            "series": "1",
            "index": "383",
            "xExact": "384",
            "x": "384",
            "yExact": "0",
            "y": "0",
            "id": "customer:1853"
          },
          {
            "series": "0",
            "index": "384",
            "xExact": "385",
            "x": "385",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:1858"
          },
          {
            "series": "1",
            "index": "384",
            "xExact": "385",
            "x": "385",
            "yExact": "0",
            "y": "0",
            "id": "customer:1858"
          },
          {
            "series": "0",
            "index": "385",
            "xExact": "386",
            "x": "386",
            "yExact": "1/139",
            "y": "0.0071942446",
            "id": "customer:1861"
          },
          {
            "series": "1",
            "index": "385",
            "xExact": "386",
            "x": "386",
            "yExact": "0",
            "y": "0",
            "id": "customer:1861"
          },
          {
            "series": "0",
            "index": "386",
            "xExact": "387",
            "x": "387",
            "yExact": "43/218",
            "y": "0.197247706",
            "id": "customer:1862"
          },
          {
            "series": "1",
            "index": "386",
            "xExact": "387",
            "x": "387",
            "yExact": "0",
            "y": "0",
            "id": "customer:1862"
          },
          {
            "series": "0",
            "index": "387",
            "xExact": "388",
            "x": "388",
            "yExact": "1/139",
            "y": "0.0071942446",
            "id": "customer:1871"
          },
          {
            "series": "1",
            "index": "387",
            "xExact": "388",
            "x": "388",
            "yExact": "0",
            "y": "0",
            "id": "customer:1871"
          },
          {
            "series": "0",
            "index": "388",
            "xExact": "389",
            "x": "389",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:1875"
          },
          {
            "series": "1",
            "index": "388",
            "xExact": "389",
            "x": "389",
            "yExact": "1",
            "y": "1",
            "id": "customer:1875"
          },
          {
            "series": "0",
            "index": "389",
            "xExact": "390",
            "x": "390",
            "yExact": "43/218",
            "y": "0.197247706",
            "id": "customer:1883"
          },
          {
            "series": "1",
            "index": "389",
            "xExact": "390",
            "x": "390",
            "yExact": "0",
            "y": "0",
            "id": "customer:1883"
          },
          {
            "series": "0",
            "index": "390",
            "xExact": "391",
            "x": "391",
            "yExact": "1/139",
            "y": "0.0071942446",
            "id": "customer:1886"
          },
          {
            "series": "1",
            "index": "390",
            "xExact": "391",
            "x": "391",
            "yExact": "0",
            "y": "0",
            "id": "customer:1886"
          },
          {
            "series": "0",
            "index": "391",
            "xExact": "392",
            "x": "392",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:1892"
          },
          {
            "series": "1",
            "index": "391",
            "xExact": "392",
            "x": "392",
            "yExact": "0",
            "y": "0",
            "id": "customer:1892"
          },
          {
            "series": "0",
            "index": "392",
            "xExact": "393",
            "x": "393",
            "yExact": "4/23",
            "y": "0.173913043",
            "id": "customer:1893"
          },
          {
            "series": "1",
            "index": "392",
            "xExact": "393",
            "x": "393",
            "yExact": "0",
            "y": "0",
            "id": "customer:1893"
          },
          {
            "series": "0",
            "index": "393",
            "xExact": "394",
            "x": "394",
            "yExact": "2/53",
            "y": "0.0377358491",
            "id": "customer:1896"
          },
          {
            "series": "1",
            "index": "393",
            "xExact": "394",
            "x": "394",
            "yExact": "0",
            "y": "0",
            "id": "customer:1896"
          },
          {
            "series": "0",
            "index": "394",
            "xExact": "395",
            "x": "395",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:1898"
          },
          {
            "series": "1",
            "index": "394",
            "xExact": "395",
            "x": "395",
            "yExact": "0",
            "y": "0",
            "id": "customer:1898"
          },
          {
            "series": "0",
            "index": "395",
            "xExact": "396",
            "x": "396",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:1908"
          },
          {
            "series": "1",
            "index": "395",
            "xExact": "396",
            "x": "396",
            "yExact": "0",
            "y": "0",
            "id": "customer:1908"
          },
          {
            "series": "0",
            "index": "396",
            "xExact": "397",
            "x": "397",
            "yExact": "2/53",
            "y": "0.0377358491",
            "id": "customer:1927"
          },
          {
            "series": "1",
            "index": "396",
            "xExact": "397",
            "x": "397",
            "yExact": "1",
            "y": "1",
            "id": "customer:1927"
          },
          {
            "series": "0",
            "index": "397",
            "xExact": "398",
            "x": "398",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:1933"
          },
          {
            "series": "1",
            "index": "397",
            "xExact": "398",
            "x": "398",
            "yExact": "0",
            "y": "0",
            "id": "customer:1933"
          },
          {
            "series": "0",
            "index": "398",
            "xExact": "399",
            "x": "399",
            "yExact": "2/53",
            "y": "0.0377358491",
            "id": "customer:1938"
          },
          {
            "series": "1",
            "index": "398",
            "xExact": "399",
            "x": "399",
            "yExact": "0",
            "y": "0",
            "id": "customer:1938"
          },
          {
            "series": "0",
            "index": "399",
            "xExact": "400",
            "x": "400",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:1940"
          },
          {
            "series": "1",
            "index": "399",
            "xExact": "400",
            "x": "400",
            "yExact": "0",
            "y": "0",
            "id": "customer:1940"
          },
          {
            "series": "0",
            "index": "400",
            "xExact": "401",
            "x": "401",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:1955"
          },
          {
            "series": "1",
            "index": "400",
            "xExact": "401",
            "x": "401",
            "yExact": "0",
            "y": "0",
            "id": "customer:1955"
          },
          {
            "series": "0",
            "index": "401",
            "xExact": "402",
            "x": "402",
            "yExact": "3/205",
            "y": "0.0146341463",
            "id": "customer:1959"
          },
          {
            "series": "1",
            "index": "401",
            "xExact": "402",
            "x": "402",
            "yExact": "0",
            "y": "0",
            "id": "customer:1959"
          },
          {
            "series": "0",
            "index": "402",
            "xExact": "403",
            "x": "403",
            "yExact": "3/205",
            "y": "0.0146341463",
            "id": "customer:1966"
          },
          {
            "series": "1",
            "index": "402",
            "xExact": "403",
            "x": "403",
            "yExact": "0",
            "y": "0",
            "id": "customer:1966"
          },
          {
            "series": "0",
            "index": "403",
            "xExact": "404",
            "x": "404",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:1969"
          },
          {
            "series": "1",
            "index": "403",
            "xExact": "404",
            "x": "404",
            "yExact": "1",
            "y": "1",
            "id": "customer:1969"
          },
          {
            "series": "0",
            "index": "404",
            "xExact": "405",
            "x": "405",
            "yExact": "2/53",
            "y": "0.0377358491",
            "id": "customer:1974"
          },
          {
            "series": "1",
            "index": "404",
            "xExact": "405",
            "x": "405",
            "yExact": "0",
            "y": "0",
            "id": "customer:1974"
          },
          {
            "series": "0",
            "index": "405",
            "xExact": "406",
            "x": "406",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:1980"
          },
          {
            "series": "1",
            "index": "405",
            "xExact": "406",
            "x": "406",
            "yExact": "0",
            "y": "0",
            "id": "customer:1980"
          },
          {
            "series": "0",
            "index": "406",
            "xExact": "407",
            "x": "407",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:1983"
          },
          {
            "series": "1",
            "index": "406",
            "xExact": "407",
            "x": "407",
            "yExact": "0",
            "y": "0",
            "id": "customer:1983"
          },
          {
            "series": "0",
            "index": "407",
            "xExact": "408",
            "x": "408",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:1987"
          },
          {
            "series": "1",
            "index": "407",
            "xExact": "408",
            "x": "408",
            "yExact": "0",
            "y": "0",
            "id": "customer:1987"
          },
          {
            "series": "0",
            "index": "408",
            "xExact": "409",
            "x": "409",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:1991"
          },
          {
            "series": "1",
            "index": "408",
            "xExact": "409",
            "x": "409",
            "yExact": "0",
            "y": "0",
            "id": "customer:1991"
          },
          {
            "series": "0",
            "index": "409",
            "xExact": "410",
            "x": "410",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:1994"
          },
          {
            "series": "1",
            "index": "409",
            "xExact": "410",
            "x": "410",
            "yExact": "0",
            "y": "0",
            "id": "customer:1994"
          },
          {
            "series": "0",
            "index": "410",
            "xExact": "411",
            "x": "411",
            "yExact": "43/218",
            "y": "0.197247706",
            "id": "customer:2007"
          },
          {
            "series": "1",
            "index": "410",
            "xExact": "411",
            "x": "411",
            "yExact": "0",
            "y": "0",
            "id": "customer:2007"
          },
          {
            "series": "0",
            "index": "411",
            "xExact": "412",
            "x": "412",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:2027"
          },
          {
            "series": "1",
            "index": "411",
            "xExact": "412",
            "x": "412",
            "yExact": "1",
            "y": "1",
            "id": "customer:2027"
          },
          {
            "series": "0",
            "index": "412",
            "xExact": "413",
            "x": "413",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:2029"
          },
          {
            "series": "1",
            "index": "412",
            "xExact": "413",
            "x": "413",
            "yExact": "1",
            "y": "1",
            "id": "customer:2029"
          },
          {
            "series": "0",
            "index": "413",
            "xExact": "414",
            "x": "414",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:2053"
          },
          {
            "series": "1",
            "index": "413",
            "xExact": "414",
            "x": "414",
            "yExact": "0",
            "y": "0",
            "id": "customer:2053"
          },
          {
            "series": "0",
            "index": "414",
            "xExact": "415",
            "x": "415",
            "yExact": "43/218",
            "y": "0.197247706",
            "id": "customer:2055"
          },
          {
            "series": "1",
            "index": "414",
            "xExact": "415",
            "x": "415",
            "yExact": "0",
            "y": "0",
            "id": "customer:2055"
          },
          {
            "series": "0",
            "index": "415",
            "xExact": "416",
            "x": "416",
            "yExact": "43/218",
            "y": "0.197247706",
            "id": "customer:2057"
          },
          {
            "series": "1",
            "index": "415",
            "xExact": "416",
            "x": "416",
            "yExact": "0",
            "y": "0",
            "id": "customer:2057"
          },
          {
            "series": "0",
            "index": "416",
            "xExact": "417",
            "x": "417",
            "yExact": "2/53",
            "y": "0.0377358491",
            "id": "customer:2058"
          },
          {
            "series": "1",
            "index": "416",
            "xExact": "417",
            "x": "417",
            "yExact": "0",
            "y": "0",
            "id": "customer:2058"
          },
          {
            "series": "0",
            "index": "417",
            "xExact": "418",
            "x": "418",
            "yExact": "3/205",
            "y": "0.0146341463",
            "id": "customer:2066"
          },
          {
            "series": "1",
            "index": "417",
            "xExact": "418",
            "x": "418",
            "yExact": "0",
            "y": "0",
            "id": "customer:2066"
          },
          {
            "series": "0",
            "index": "418",
            "xExact": "419",
            "x": "419",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:2067"
          },
          {
            "series": "1",
            "index": "418",
            "xExact": "419",
            "x": "419",
            "yExact": "0",
            "y": "0",
            "id": "customer:2067"
          },
          {
            "series": "0",
            "index": "419",
            "xExact": "420",
            "x": "420",
            "yExact": "43/218",
            "y": "0.197247706",
            "id": "customer:2068"
          },
          {
            "series": "1",
            "index": "419",
            "xExact": "420",
            "x": "420",
            "yExact": "0",
            "y": "0",
            "id": "customer:2068"
          },
          {
            "series": "0",
            "index": "420",
            "xExact": "421",
            "x": "421",
            "yExact": "3/205",
            "y": "0.0146341463",
            "id": "customer:2070"
          },
          {
            "series": "1",
            "index": "420",
            "xExact": "421",
            "x": "421",
            "yExact": "0",
            "y": "0",
            "id": "customer:2070"
          },
          {
            "series": "0",
            "index": "421",
            "xExact": "422",
            "x": "422",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:2078"
          },
          {
            "series": "1",
            "index": "421",
            "xExact": "422",
            "x": "422",
            "yExact": "1",
            "y": "1",
            "id": "customer:2078"
          },
          {
            "series": "0",
            "index": "422",
            "xExact": "423",
            "x": "423",
            "yExact": "3/205",
            "y": "0.0146341463",
            "id": "customer:2086"
          },
          {
            "series": "1",
            "index": "422",
            "xExact": "423",
            "x": "423",
            "yExact": "0",
            "y": "0",
            "id": "customer:2086"
          },
          {
            "series": "0",
            "index": "423",
            "xExact": "424",
            "x": "424",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:2089"
          },
          {
            "series": "1",
            "index": "423",
            "xExact": "424",
            "x": "424",
            "yExact": "0",
            "y": "0",
            "id": "customer:2089"
          },
          {
            "series": "0",
            "index": "424",
            "xExact": "425",
            "x": "425",
            "yExact": "2/53",
            "y": "0.0377358491",
            "id": "customer:2097"
          },
          {
            "series": "1",
            "index": "424",
            "xExact": "425",
            "x": "425",
            "yExact": "0",
            "y": "0",
            "id": "customer:2097"
          },
          {
            "series": "0",
            "index": "425",
            "xExact": "426",
            "x": "426",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:2100"
          },
          {
            "series": "1",
            "index": "425",
            "xExact": "426",
            "x": "426",
            "yExact": "1",
            "y": "1",
            "id": "customer:2100"
          },
          {
            "series": "0",
            "index": "426",
            "xExact": "427",
            "x": "427",
            "yExact": "17/112",
            "y": "0.151785714",
            "id": "customer:2103"
          },
          {
            "series": "1",
            "index": "426",
            "xExact": "427",
            "x": "427",
            "yExact": "0",
            "y": "0",
            "id": "customer:2103"
          },
          {
            "series": "0",
            "index": "427",
            "xExact": "428",
            "x": "428",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:2104"
          },
          {
            "series": "1",
            "index": "427",
            "xExact": "428",
            "x": "428",
            "yExact": "0",
            "y": "0",
            "id": "customer:2104"
          },
          {
            "series": "0",
            "index": "428",
            "xExact": "429",
            "x": "429",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:2106"
          },
          {
            "series": "1",
            "index": "428",
            "xExact": "429",
            "x": "429",
            "yExact": "0",
            "y": "0",
            "id": "customer:2106"
          },
          {
            "series": "0",
            "index": "429",
            "xExact": "430",
            "x": "430",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:2110"
          },
          {
            "series": "1",
            "index": "429",
            "xExact": "430",
            "x": "430",
            "yExact": "0",
            "y": "0",
            "id": "customer:2110"
          },
          {
            "series": "0",
            "index": "430",
            "xExact": "431",
            "x": "431",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:2114"
          },
          {
            "series": "1",
            "index": "430",
            "xExact": "431",
            "x": "431",
            "yExact": "0",
            "y": "0",
            "id": "customer:2114"
          },
          {
            "series": "0",
            "index": "431",
            "xExact": "432",
            "x": "432",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:2122"
          },
          {
            "series": "1",
            "index": "431",
            "xExact": "432",
            "x": "432",
            "yExact": "0",
            "y": "0",
            "id": "customer:2122"
          },
          {
            "series": "0",
            "index": "432",
            "xExact": "433",
            "x": "433",
            "yExact": "17/112",
            "y": "0.151785714",
            "id": "customer:2157"
          },
          {
            "series": "1",
            "index": "432",
            "xExact": "433",
            "x": "433",
            "yExact": "0",
            "y": "0",
            "id": "customer:2157"
          },
          {
            "series": "0",
            "index": "433",
            "xExact": "434",
            "x": "434",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:2158"
          },
          {
            "series": "1",
            "index": "433",
            "xExact": "434",
            "x": "434",
            "yExact": "0",
            "y": "0",
            "id": "customer:2158"
          },
          {
            "series": "0",
            "index": "434",
            "xExact": "435",
            "x": "435",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:2161"
          },
          {
            "series": "1",
            "index": "434",
            "xExact": "435",
            "x": "435",
            "yExact": "0",
            "y": "0",
            "id": "customer:2161"
          },
          {
            "series": "0",
            "index": "435",
            "xExact": "436",
            "x": "436",
            "yExact": "17/112",
            "y": "0.151785714",
            "id": "customer:2167"
          },
          {
            "series": "1",
            "index": "435",
            "xExact": "436",
            "x": "436",
            "yExact": "0",
            "y": "0",
            "id": "customer:2167"
          },
          {
            "series": "0",
            "index": "436",
            "xExact": "437",
            "x": "437",
            "yExact": "17/112",
            "y": "0.151785714",
            "id": "customer:2169"
          },
          {
            "series": "1",
            "index": "436",
            "xExact": "437",
            "x": "437",
            "yExact": "1",
            "y": "1",
            "id": "customer:2169"
          },
          {
            "series": "0",
            "index": "437",
            "xExact": "438",
            "x": "438",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:2172"
          },
          {
            "series": "1",
            "index": "437",
            "xExact": "438",
            "x": "438",
            "yExact": "0",
            "y": "0",
            "id": "customer:2172"
          },
          {
            "series": "0",
            "index": "438",
            "xExact": "439",
            "x": "439",
            "yExact": "17/29",
            "y": "0.586206897",
            "id": "customer:2173"
          },
          {
            "series": "1",
            "index": "438",
            "xExact": "439",
            "x": "439",
            "yExact": "1",
            "y": "1",
            "id": "customer:2173"
          },
          {
            "series": "0",
            "index": "439",
            "xExact": "440",
            "x": "440",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:2175"
          },
          {
            "series": "1",
            "index": "439",
            "xExact": "440",
            "x": "440",
            "yExact": "0",
            "y": "0",
            "id": "customer:2175"
          },
          {
            "series": "0",
            "index": "440",
            "xExact": "441",
            "x": "441",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:2176"
          },
          {
            "series": "1",
            "index": "440",
            "xExact": "441",
            "x": "441",
            "yExact": "0",
            "y": "0",
            "id": "customer:2176"
          },
          {
            "series": "0",
            "index": "441",
            "xExact": "442",
            "x": "442",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:2186"
          },
          {
            "series": "1",
            "index": "441",
            "xExact": "442",
            "x": "442",
            "yExact": "0",
            "y": "0",
            "id": "customer:2186"
          },
          {
            "series": "0",
            "index": "442",
            "xExact": "443",
            "x": "443",
            "yExact": "4/23",
            "y": "0.173913043",
            "id": "customer:2189"
          },
          {
            "series": "1",
            "index": "442",
            "xExact": "443",
            "x": "443",
            "yExact": "0",
            "y": "0",
            "id": "customer:2189"
          },
          {
            "series": "0",
            "index": "443",
            "xExact": "444",
            "x": "444",
            "yExact": "43/218",
            "y": "0.197247706",
            "id": "customer:2202"
          },
          {
            "series": "1",
            "index": "443",
            "xExact": "444",
            "x": "444",
            "yExact": "0",
            "y": "0",
            "id": "customer:2202"
          },
          {
            "series": "0",
            "index": "444",
            "xExact": "445",
            "x": "445",
            "yExact": "17/112",
            "y": "0.151785714",
            "id": "customer:2203"
          },
          {
            "series": "1",
            "index": "444",
            "xExact": "445",
            "x": "445",
            "yExact": "0",
            "y": "0",
            "id": "customer:2203"
          },
          {
            "series": "0",
            "index": "445",
            "xExact": "446",
            "x": "446",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:2209"
          },
          {
            "series": "1",
            "index": "445",
            "xExact": "446",
            "x": "446",
            "yExact": "0",
            "y": "0",
            "id": "customer:2209"
          },
          {
            "series": "0",
            "index": "446",
            "xExact": "447",
            "x": "447",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:2210"
          },
          {
            "series": "1",
            "index": "446",
            "xExact": "447",
            "x": "447",
            "yExact": "0",
            "y": "0",
            "id": "customer:2210"
          },
          {
            "series": "0",
            "index": "447",
            "xExact": "448",
            "x": "448",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:2211"
          },
          {
            "series": "1",
            "index": "447",
            "xExact": "448",
            "x": "448",
            "yExact": "0",
            "y": "0",
            "id": "customer:2211"
          },
          {
            "series": "0",
            "index": "448",
            "xExact": "449",
            "x": "449",
            "yExact": "17/112",
            "y": "0.151785714",
            "id": "customer:2212"
          },
          {
            "series": "1",
            "index": "448",
            "xExact": "449",
            "x": "449",
            "yExact": "0",
            "y": "0",
            "id": "customer:2212"
          },
          {
            "series": "0",
            "index": "449",
            "xExact": "450",
            "x": "450",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:2213"
          },
          {
            "series": "1",
            "index": "449",
            "xExact": "450",
            "x": "450",
            "yExact": "0",
            "y": "0",
            "id": "customer:2213"
          },
          {
            "series": "0",
            "index": "450",
            "xExact": "451",
            "x": "451",
            "yExact": "1/139",
            "y": "0.0071942446",
            "id": "customer:2216"
          },
          {
            "series": "1",
            "index": "450",
            "xExact": "451",
            "x": "451",
            "yExact": "0",
            "y": "0",
            "id": "customer:2216"
          },
          {
            "series": "0",
            "index": "451",
            "xExact": "452",
            "x": "452",
            "yExact": "43/218",
            "y": "0.197247706",
            "id": "customer:2217"
          },
          {
            "series": "1",
            "index": "451",
            "xExact": "452",
            "x": "452",
            "yExact": "0",
            "y": "0",
            "id": "customer:2217"
          },
          {
            "series": "0",
            "index": "452",
            "xExact": "453",
            "x": "453",
            "yExact": "43/218",
            "y": "0.197247706",
            "id": "customer:2219"
          },
          {
            "series": "1",
            "index": "452",
            "xExact": "453",
            "x": "453",
            "yExact": "1",
            "y": "1",
            "id": "customer:2219"
          },
          {
            "series": "0",
            "index": "453",
            "xExact": "454",
            "x": "454",
            "yExact": "43/218",
            "y": "0.197247706",
            "id": "customer:2233"
          },
          {
            "series": "1",
            "index": "453",
            "xExact": "454",
            "x": "454",
            "yExact": "0",
            "y": "0",
            "id": "customer:2233"
          },
          {
            "series": "0",
            "index": "454",
            "xExact": "455",
            "x": "455",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:2239"
          },
          {
            "series": "1",
            "index": "454",
            "xExact": "455",
            "x": "455",
            "yExact": "0",
            "y": "0",
            "id": "customer:2239"
          },
          {
            "series": "0",
            "index": "455",
            "xExact": "456",
            "x": "456",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:2245"
          },
          {
            "series": "1",
            "index": "455",
            "xExact": "456",
            "x": "456",
            "yExact": "0",
            "y": "0",
            "id": "customer:2245"
          },
          {
            "series": "0",
            "index": "456",
            "xExact": "457",
            "x": "457",
            "yExact": "2/53",
            "y": "0.0377358491",
            "id": "customer:2246"
          },
          {
            "series": "1",
            "index": "456",
            "xExact": "457",
            "x": "457",
            "yExact": "0",
            "y": "0",
            "id": "customer:2246"
          },
          {
            "series": "0",
            "index": "457",
            "xExact": "458",
            "x": "458",
            "yExact": "43/218",
            "y": "0.197247706",
            "id": "customer:2252"
          },
          {
            "series": "1",
            "index": "457",
            "xExact": "458",
            "x": "458",
            "yExact": "0",
            "y": "0",
            "id": "customer:2252"
          },
          {
            "series": "0",
            "index": "458",
            "xExact": "459",
            "x": "459",
            "yExact": "17/112",
            "y": "0.151785714",
            "id": "customer:2257"
          },
          {
            "series": "1",
            "index": "458",
            "xExact": "459",
            "x": "459",
            "yExact": "0",
            "y": "0",
            "id": "customer:2257"
          },
          {
            "series": "0",
            "index": "459",
            "xExact": "460",
            "x": "460",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:2258"
          },
          {
            "series": "1",
            "index": "459",
            "xExact": "460",
            "x": "460",
            "yExact": "0",
            "y": "0",
            "id": "customer:2258"
          },
          {
            "series": "0",
            "index": "460",
            "xExact": "461",
            "x": "461",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:2263"
          },
          {
            "series": "1",
            "index": "460",
            "xExact": "461",
            "x": "461",
            "yExact": "0",
            "y": "0",
            "id": "customer:2263"
          },
          {
            "series": "0",
            "index": "461",
            "xExact": "462",
            "x": "462",
            "yExact": "17/112",
            "y": "0.151785714",
            "id": "customer:2268"
          },
          {
            "series": "1",
            "index": "461",
            "xExact": "462",
            "x": "462",
            "yExact": "0",
            "y": "0",
            "id": "customer:2268"
          },
          {
            "series": "0",
            "index": "462",
            "xExact": "463",
            "x": "463",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:2275"
          },
          {
            "series": "1",
            "index": "462",
            "xExact": "463",
            "x": "463",
            "yExact": "0",
            "y": "0",
            "id": "customer:2275"
          },
          {
            "series": "0",
            "index": "463",
            "xExact": "464",
            "x": "464",
            "yExact": "17/29",
            "y": "0.586206897",
            "id": "customer:2277"
          },
          {
            "series": "1",
            "index": "463",
            "xExact": "464",
            "x": "464",
            "yExact": "1",
            "y": "1",
            "id": "customer:2277"
          },
          {
            "series": "0",
            "index": "464",
            "xExact": "465",
            "x": "465",
            "yExact": "17/29",
            "y": "0.586206897",
            "id": "customer:2278"
          },
          {
            "series": "1",
            "index": "464",
            "xExact": "465",
            "x": "465",
            "yExact": "1",
            "y": "1",
            "id": "customer:2278"
          },
          {
            "series": "0",
            "index": "465",
            "xExact": "466",
            "x": "466",
            "yExact": "4/23",
            "y": "0.173913043",
            "id": "customer:2289"
          },
          {
            "series": "1",
            "index": "465",
            "xExact": "466",
            "x": "466",
            "yExact": "0",
            "y": "0",
            "id": "customer:2289"
          },
          {
            "series": "0",
            "index": "466",
            "xExact": "467",
            "x": "467",
            "yExact": "4/23",
            "y": "0.173913043",
            "id": "customer:2290"
          },
          {
            "series": "1",
            "index": "466",
            "xExact": "467",
            "x": "467",
            "yExact": "0",
            "y": "0",
            "id": "customer:2290"
          },
          {
            "series": "0",
            "index": "467",
            "xExact": "468",
            "x": "468",
            "yExact": "2/53",
            "y": "0.0377358491",
            "id": "customer:2298"
          },
          {
            "series": "1",
            "index": "467",
            "xExact": "468",
            "x": "468",
            "yExact": "0",
            "y": "0",
            "id": "customer:2298"
          },
          {
            "series": "0",
            "index": "468",
            "xExact": "469",
            "x": "469",
            "yExact": "2/53",
            "y": "0.0377358491",
            "id": "customer:2299"
          },
          {
            "series": "1",
            "index": "468",
            "xExact": "469",
            "x": "469",
            "yExact": "0",
            "y": "0",
            "id": "customer:2299"
          },
          {
            "series": "0",
            "index": "469",
            "xExact": "470",
            "x": "470",
            "yExact": "18/19",
            "y": "0.947368421",
            "id": "customer:2300"
          },
          {
            "series": "1",
            "index": "469",
            "xExact": "470",
            "x": "470",
            "yExact": "1",
            "y": "1",
            "id": "customer:2300"
          },
          {
            "series": "0",
            "index": "470",
            "xExact": "471",
            "x": "471",
            "yExact": "43/218",
            "y": "0.197247706",
            "id": "customer:2302"
          },
          {
            "series": "1",
            "index": "470",
            "xExact": "471",
            "x": "471",
            "yExact": "0",
            "y": "0",
            "id": "customer:2302"
          },
          {
            "series": "0",
            "index": "471",
            "xExact": "472",
            "x": "472",
            "yExact": "17/112",
            "y": "0.151785714",
            "id": "customer:2305"
          },
          {
            "series": "1",
            "index": "471",
            "xExact": "472",
            "x": "472",
            "yExact": "0",
            "y": "0",
            "id": "customer:2305"
          },
          {
            "series": "0",
            "index": "472",
            "xExact": "473",
            "x": "473",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:2306"
          },
          {
            "series": "1",
            "index": "472",
            "xExact": "473",
            "x": "473",
            "yExact": "0",
            "y": "0",
            "id": "customer:2306"
          },
          {
            "series": "0",
            "index": "473",
            "xExact": "474",
            "x": "474",
            "yExact": "17/112",
            "y": "0.151785714",
            "id": "customer:2312"
          },
          {
            "series": "1",
            "index": "473",
            "xExact": "474",
            "x": "474",
            "yExact": "0",
            "y": "0",
            "id": "customer:2312"
          },
          {
            "series": "0",
            "index": "474",
            "xExact": "475",
            "x": "475",
            "yExact": "18/19",
            "y": "0.947368421",
            "id": "customer:2323"
          },
          {
            "series": "1",
            "index": "474",
            "xExact": "475",
            "x": "475",
            "yExact": "1",
            "y": "1",
            "id": "customer:2323"
          },
          {
            "series": "0",
            "index": "475",
            "xExact": "476",
            "x": "476",
            "yExact": "3/205",
            "y": "0.0146341463",
            "id": "customer:2326"
          },
          {
            "series": "1",
            "index": "475",
            "xExact": "476",
            "x": "476",
            "yExact": "0",
            "y": "0",
            "id": "customer:2326"
          },
          {
            "series": "0",
            "index": "476",
            "xExact": "477",
            "x": "477",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:2330"
          },
          {
            "series": "1",
            "index": "476",
            "xExact": "477",
            "x": "477",
            "yExact": "0",
            "y": "0",
            "id": "customer:2330"
          },
          {
            "series": "0",
            "index": "477",
            "xExact": "478",
            "x": "478",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:2332"
          },
          {
            "series": "1",
            "index": "477",
            "xExact": "478",
            "x": "478",
            "yExact": "1",
            "y": "1",
            "id": "customer:2332"
          },
          {
            "series": "0",
            "index": "478",
            "xExact": "479",
            "x": "479",
            "yExact": "2/53",
            "y": "0.0377358491",
            "id": "customer:2334"
          },
          {
            "series": "1",
            "index": "478",
            "xExact": "479",
            "x": "479",
            "yExact": "0",
            "y": "0",
            "id": "customer:2334"
          },
          {
            "series": "0",
            "index": "479",
            "xExact": "480",
            "x": "480",
            "yExact": "2/53",
            "y": "0.0377358491",
            "id": "customer:2335"
          },
          {
            "series": "1",
            "index": "479",
            "xExact": "480",
            "x": "480",
            "yExact": "0",
            "y": "0",
            "id": "customer:2335"
          },
          {
            "series": "0",
            "index": "480",
            "xExact": "481",
            "x": "481",
            "yExact": "4/23",
            "y": "0.173913043",
            "id": "customer:2337"
          },
          {
            "series": "1",
            "index": "480",
            "xExact": "481",
            "x": "481",
            "yExact": "0",
            "y": "0",
            "id": "customer:2337"
          },
          {
            "series": "0",
            "index": "481",
            "xExact": "482",
            "x": "482",
            "yExact": "2/53",
            "y": "0.0377358491",
            "id": "customer:2346"
          },
          {
            "series": "1",
            "index": "481",
            "xExact": "482",
            "x": "482",
            "yExact": "0",
            "y": "0",
            "id": "customer:2346"
          },
          {
            "series": "0",
            "index": "482",
            "xExact": "483",
            "x": "483",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:2354"
          },
          {
            "series": "1",
            "index": "482",
            "xExact": "483",
            "x": "483",
            "yExact": "0",
            "y": "0",
            "id": "customer:2354"
          },
          {
            "series": "0",
            "index": "483",
            "xExact": "484",
            "x": "484",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:2355"
          },
          {
            "series": "1",
            "index": "483",
            "xExact": "484",
            "x": "484",
            "yExact": "0",
            "y": "0",
            "id": "customer:2355"
          },
          {
            "series": "0",
            "index": "484",
            "xExact": "485",
            "x": "485",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:2365"
          },
          {
            "series": "1",
            "index": "484",
            "xExact": "485",
            "x": "485",
            "yExact": "0",
            "y": "0",
            "id": "customer:2365"
          },
          {
            "series": "0",
            "index": "485",
            "xExact": "486",
            "x": "486",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:2374"
          },
          {
            "series": "1",
            "index": "485",
            "xExact": "486",
            "x": "486",
            "yExact": "0",
            "y": "0",
            "id": "customer:2374"
          },
          {
            "series": "0",
            "index": "486",
            "xExact": "487",
            "x": "487",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:2381"
          },
          {
            "series": "1",
            "index": "486",
            "xExact": "487",
            "x": "487",
            "yExact": "0",
            "y": "0",
            "id": "customer:2381"
          },
          {
            "series": "0",
            "index": "487",
            "xExact": "488",
            "x": "488",
            "yExact": "4/23",
            "y": "0.173913043",
            "id": "customer:2390"
          },
          {
            "series": "1",
            "index": "487",
            "xExact": "488",
            "x": "488",
            "yExact": "0",
            "y": "0",
            "id": "customer:2390"
          },
          {
            "series": "0",
            "index": "488",
            "xExact": "489",
            "x": "489",
            "yExact": "4/23",
            "y": "0.173913043",
            "id": "customer:2392"
          },
          {
            "series": "1",
            "index": "488",
            "xExact": "489",
            "x": "489",
            "yExact": "0",
            "y": "0",
            "id": "customer:2392"
          },
          {
            "series": "0",
            "index": "489",
            "xExact": "490",
            "x": "490",
            "yExact": "2/53",
            "y": "0.0377358491",
            "id": "customer:2406"
          },
          {
            "series": "1",
            "index": "489",
            "xExact": "490",
            "x": "490",
            "yExact": "0",
            "y": "0",
            "id": "customer:2406"
          },
          {
            "series": "0",
            "index": "490",
            "xExact": "491",
            "x": "491",
            "yExact": "2/53",
            "y": "0.0377358491",
            "id": "customer:2410"
          },
          {
            "series": "1",
            "index": "490",
            "xExact": "491",
            "x": "491",
            "yExact": "0",
            "y": "0",
            "id": "customer:2410"
          },
          {
            "series": "0",
            "index": "491",
            "xExact": "492",
            "x": "492",
            "yExact": "3/205",
            "y": "0.0146341463",
            "id": "customer:2411"
          },
          {
            "series": "1",
            "index": "491",
            "xExact": "492",
            "x": "492",
            "yExact": "0",
            "y": "0",
            "id": "customer:2411"
          },
          {
            "series": "0",
            "index": "492",
            "xExact": "493",
            "x": "493",
            "yExact": "4/23",
            "y": "0.173913043",
            "id": "customer:2412"
          },
          {
            "series": "1",
            "index": "492",
            "xExact": "493",
            "x": "493",
            "yExact": "0",
            "y": "0",
            "id": "customer:2412"
          },
          {
            "series": "0",
            "index": "493",
            "xExact": "494",
            "x": "494",
            "yExact": "2/53",
            "y": "0.0377358491",
            "id": "customer:2413"
          },
          {
            "series": "1",
            "index": "493",
            "xExact": "494",
            "x": "494",
            "yExact": "0",
            "y": "0",
            "id": "customer:2413"
          },
          {
            "series": "0",
            "index": "494",
            "xExact": "495",
            "x": "495",
            "yExact": "4/23",
            "y": "0.173913043",
            "id": "customer:2423"
          },
          {
            "series": "1",
            "index": "494",
            "xExact": "495",
            "x": "495",
            "yExact": "1",
            "y": "1",
            "id": "customer:2423"
          },
          {
            "series": "0",
            "index": "495",
            "xExact": "496",
            "x": "496",
            "yExact": "2/53",
            "y": "0.0377358491",
            "id": "customer:2425"
          },
          {
            "series": "1",
            "index": "495",
            "xExact": "496",
            "x": "496",
            "yExact": "1",
            "y": "1",
            "id": "customer:2425"
          },
          {
            "series": "0",
            "index": "496",
            "xExact": "497",
            "x": "497",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:2437"
          },
          {
            "series": "1",
            "index": "496",
            "xExact": "497",
            "x": "497",
            "yExact": "0",
            "y": "0",
            "id": "customer:2437"
          },
          {
            "series": "0",
            "index": "497",
            "xExact": "498",
            "x": "498",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:2439"
          },
          {
            "series": "1",
            "index": "497",
            "xExact": "498",
            "x": "498",
            "yExact": "0",
            "y": "0",
            "id": "customer:2439"
          },
          {
            "series": "0",
            "index": "498",
            "xExact": "499",
            "x": "499",
            "yExact": "4/23",
            "y": "0.173913043",
            "id": "customer:2443"
          },
          {
            "series": "1",
            "index": "498",
            "xExact": "499",
            "x": "499",
            "yExact": "0",
            "y": "0",
            "id": "customer:2443"
          },
          {
            "series": "0",
            "index": "499",
            "xExact": "500",
            "x": "500",
            "yExact": "2/53",
            "y": "0.0377358491",
            "id": "customer:2447"
          },
          {
            "series": "1",
            "index": "499",
            "xExact": "500",
            "x": "500",
            "yExact": "0",
            "y": "0",
            "id": "customer:2447"
          },
          {
            "series": "0",
            "index": "500",
            "xExact": "501",
            "x": "501",
            "yExact": "4/23",
            "y": "0.173913043",
            "id": "customer:2448"
          },
          {
            "series": "1",
            "index": "500",
            "xExact": "501",
            "x": "501",
            "yExact": "0",
            "y": "0",
            "id": "customer:2448"
          },
          {
            "series": "0",
            "index": "501",
            "xExact": "502",
            "x": "502",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:2465"
          },
          {
            "series": "1",
            "index": "501",
            "xExact": "502",
            "x": "502",
            "yExact": "0",
            "y": "0",
            "id": "customer:2465"
          },
          {
            "series": "0",
            "index": "502",
            "xExact": "503",
            "x": "503",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:2466"
          },
          {
            "series": "1",
            "index": "502",
            "xExact": "503",
            "x": "503",
            "yExact": "0",
            "y": "0",
            "id": "customer:2466"
          },
          {
            "series": "0",
            "index": "503",
            "xExact": "504",
            "x": "504",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:2470"
          },
          {
            "series": "1",
            "index": "503",
            "xExact": "504",
            "x": "504",
            "yExact": "0",
            "y": "0",
            "id": "customer:2470"
          },
          {
            "series": "0",
            "index": "504",
            "xExact": "505",
            "x": "505",
            "yExact": "17/112",
            "y": "0.151785714",
            "id": "customer:2482"
          },
          {
            "series": "1",
            "index": "504",
            "xExact": "505",
            "x": "505",
            "yExact": "1",
            "y": "1",
            "id": "customer:2482"
          },
          {
            "series": "0",
            "index": "505",
            "xExact": "506",
            "x": "506",
            "yExact": "17/112",
            "y": "0.151785714",
            "id": "customer:2483"
          },
          {
            "series": "1",
            "index": "505",
            "xExact": "506",
            "x": "506",
            "yExact": "0",
            "y": "0",
            "id": "customer:2483"
          },
          {
            "series": "0",
            "index": "506",
            "xExact": "507",
            "x": "507",
            "yExact": "4/23",
            "y": "0.173913043",
            "id": "customer:2492"
          },
          {
            "series": "1",
            "index": "506",
            "xExact": "507",
            "x": "507",
            "yExact": "0",
            "y": "0",
            "id": "customer:2492"
          },
          {
            "series": "0",
            "index": "507",
            "xExact": "508",
            "x": "508",
            "yExact": "2/53",
            "y": "0.0377358491",
            "id": "customer:2494"
          },
          {
            "series": "1",
            "index": "507",
            "xExact": "508",
            "x": "508",
            "yExact": "0",
            "y": "0",
            "id": "customer:2494"
          },
          {
            "series": "0",
            "index": "508",
            "xExact": "509",
            "x": "509",
            "yExact": "2/53",
            "y": "0.0377358491",
            "id": "customer:2498"
          },
          {
            "series": "1",
            "index": "508",
            "xExact": "509",
            "x": "509",
            "yExact": "0",
            "y": "0",
            "id": "customer:2498"
          },
          {
            "series": "0",
            "index": "509",
            "xExact": "510",
            "x": "510",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:2504"
          },
          {
            "series": "1",
            "index": "509",
            "xExact": "510",
            "x": "510",
            "yExact": "0",
            "y": "0",
            "id": "customer:2504"
          },
          {
            "series": "0",
            "index": "510",
            "xExact": "511",
            "x": "511",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:2511"
          },
          {
            "series": "1",
            "index": "510",
            "xExact": "511",
            "x": "511",
            "yExact": "0",
            "y": "0",
            "id": "customer:2511"
          },
          {
            "series": "0",
            "index": "511",
            "xExact": "512",
            "x": "512",
            "yExact": "4/23",
            "y": "0.173913043",
            "id": "customer:2541"
          },
          {
            "series": "1",
            "index": "511",
            "xExact": "512",
            "x": "512",
            "yExact": "0",
            "y": "0",
            "id": "customer:2541"
          },
          {
            "series": "0",
            "index": "512",
            "xExact": "513",
            "x": "513",
            "yExact": "3/205",
            "y": "0.0146341463",
            "id": "customer:2544"
          },
          {
            "series": "1",
            "index": "512",
            "xExact": "513",
            "x": "513",
            "yExact": "0",
            "y": "0",
            "id": "customer:2544"
          },
          {
            "series": "0",
            "index": "513",
            "xExact": "514",
            "x": "514",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:2545"
          },
          {
            "series": "1",
            "index": "513",
            "xExact": "514",
            "x": "514",
            "yExact": "0",
            "y": "0",
            "id": "customer:2545"
          },
          {
            "series": "0",
            "index": "514",
            "xExact": "515",
            "x": "515",
            "yExact": "2/53",
            "y": "0.0377358491",
            "id": "customer:2547"
          },
          {
            "series": "1",
            "index": "514",
            "xExact": "515",
            "x": "515",
            "yExact": "0",
            "y": "0",
            "id": "customer:2547"
          },
          {
            "series": "0",
            "index": "515",
            "xExact": "516",
            "x": "516",
            "yExact": "23/24",
            "y": "0.958333333",
            "id": "customer:2550"
          },
          {
            "series": "1",
            "index": "515",
            "xExact": "516",
            "x": "516",
            "yExact": "1",
            "y": "1",
            "id": "customer:2550"
          },
          {
            "series": "0",
            "index": "516",
            "xExact": "517",
            "x": "517",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:2554"
          },
          {
            "series": "1",
            "index": "516",
            "xExact": "517",
            "x": "517",
            "yExact": "0",
            "y": "0",
            "id": "customer:2554"
          },
          {
            "series": "0",
            "index": "517",
            "xExact": "518",
            "x": "518",
            "yExact": "17/29",
            "y": "0.586206897",
            "id": "customer:2563"
          },
          {
            "series": "1",
            "index": "517",
            "xExact": "518",
            "x": "518",
            "yExact": "0",
            "y": "0",
            "id": "customer:2563"
          },
          {
            "series": "0",
            "index": "518",
            "xExact": "519",
            "x": "519",
            "yExact": "17/29",
            "y": "0.586206897",
            "id": "customer:2569"
          },
          {
            "series": "1",
            "index": "518",
            "xExact": "519",
            "x": "519",
            "yExact": "1",
            "y": "1",
            "id": "customer:2569"
          },
          {
            "series": "0",
            "index": "519",
            "xExact": "520",
            "x": "520",
            "yExact": "17/29",
            "y": "0.586206897",
            "id": "customer:2577"
          },
          {
            "series": "1",
            "index": "519",
            "xExact": "520",
            "x": "520",
            "yExact": "1",
            "y": "1",
            "id": "customer:2577"
          },
          {
            "series": "0",
            "index": "520",
            "xExact": "521",
            "x": "521",
            "yExact": "4/23",
            "y": "0.173913043",
            "id": "customer:2590"
          },
          {
            "series": "1",
            "index": "520",
            "xExact": "521",
            "x": "521",
            "yExact": "0",
            "y": "0",
            "id": "customer:2590"
          },
          {
            "series": "0",
            "index": "521",
            "xExact": "522",
            "x": "522",
            "yExact": "4/23",
            "y": "0.173913043",
            "id": "customer:2593"
          },
          {
            "series": "1",
            "index": "521",
            "xExact": "522",
            "x": "522",
            "yExact": "0",
            "y": "0",
            "id": "customer:2593"
          },
          {
            "series": "0",
            "index": "522",
            "xExact": "523",
            "x": "523",
            "yExact": "2/53",
            "y": "0.0377358491",
            "id": "customer:2597"
          },
          {
            "series": "1",
            "index": "522",
            "xExact": "523",
            "x": "523",
            "yExact": "0",
            "y": "0",
            "id": "customer:2597"
          },
          {
            "series": "0",
            "index": "523",
            "xExact": "524",
            "x": "524",
            "yExact": "43/218",
            "y": "0.197247706",
            "id": "customer:2607"
          },
          {
            "series": "1",
            "index": "523",
            "xExact": "524",
            "x": "524",
            "yExact": "0",
            "y": "0",
            "id": "customer:2607"
          },
          {
            "series": "0",
            "index": "524",
            "xExact": "525",
            "x": "525",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:2609"
          },
          {
            "series": "1",
            "index": "524",
            "xExact": "525",
            "x": "525",
            "yExact": "0",
            "y": "0",
            "id": "customer:2609"
          },
          {
            "series": "0",
            "index": "525",
            "xExact": "526",
            "x": "526",
            "yExact": "1/139",
            "y": "0.0071942446",
            "id": "customer:2616"
          },
          {
            "series": "1",
            "index": "525",
            "xExact": "526",
            "x": "526",
            "yExact": "0",
            "y": "0",
            "id": "customer:2616"
          },
          {
            "series": "0",
            "index": "526",
            "xExact": "527",
            "x": "527",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:2624"
          },
          {
            "series": "1",
            "index": "526",
            "xExact": "527",
            "x": "527",
            "yExact": "0",
            "y": "0",
            "id": "customer:2624"
          },
          {
            "series": "0",
            "index": "527",
            "xExact": "528",
            "x": "528",
            "yExact": "4/23",
            "y": "0.173913043",
            "id": "customer:2643"
          },
          {
            "series": "1",
            "index": "527",
            "xExact": "528",
            "x": "528",
            "yExact": "0",
            "y": "0",
            "id": "customer:2643"
          },
          {
            "series": "0",
            "index": "528",
            "xExact": "529",
            "x": "529",
            "yExact": "4/23",
            "y": "0.173913043",
            "id": "customer:2648"
          },
          {
            "series": "1",
            "index": "528",
            "xExact": "529",
            "x": "529",
            "yExact": "0",
            "y": "0",
            "id": "customer:2648"
          },
          {
            "series": "0",
            "index": "529",
            "xExact": "530",
            "x": "530",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:2659"
          },
          {
            "series": "1",
            "index": "529",
            "xExact": "530",
            "x": "530",
            "yExact": "0",
            "y": "0",
            "id": "customer:2659"
          },
          {
            "series": "0",
            "index": "530",
            "xExact": "531",
            "x": "531",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:2666"
          },
          {
            "series": "1",
            "index": "530",
            "xExact": "531",
            "x": "531",
            "yExact": "0",
            "y": "0",
            "id": "customer:2666"
          },
          {
            "series": "0",
            "index": "531",
            "xExact": "532",
            "x": "532",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:2670"
          },
          {
            "series": "1",
            "index": "531",
            "xExact": "532",
            "x": "532",
            "yExact": "0",
            "y": "0",
            "id": "customer:2670"
          },
          {
            "series": "0",
            "index": "532",
            "xExact": "533",
            "x": "533",
            "yExact": "17/29",
            "y": "0.586206897",
            "id": "customer:2673"
          },
          {
            "series": "1",
            "index": "532",
            "xExact": "533",
            "x": "533",
            "yExact": "1",
            "y": "1",
            "id": "customer:2673"
          },
          {
            "series": "0",
            "index": "533",
            "xExact": "534",
            "x": "534",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:2675"
          },
          {
            "series": "1",
            "index": "533",
            "xExact": "534",
            "x": "534",
            "yExact": "0",
            "y": "0",
            "id": "customer:2675"
          },
          {
            "series": "0",
            "index": "534",
            "xExact": "535",
            "x": "535",
            "yExact": "17/29",
            "y": "0.586206897",
            "id": "customer:2678"
          },
          {
            "series": "1",
            "index": "534",
            "xExact": "535",
            "x": "535",
            "yExact": "1",
            "y": "1",
            "id": "customer:2678"
          },
          {
            "series": "0",
            "index": "535",
            "xExact": "536",
            "x": "536",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:2685"
          },
          {
            "series": "1",
            "index": "535",
            "xExact": "536",
            "x": "536",
            "yExact": "0",
            "y": "0",
            "id": "customer:2685"
          },
          {
            "series": "0",
            "index": "536",
            "xExact": "537",
            "x": "537",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:2688"
          },
          {
            "series": "1",
            "index": "536",
            "xExact": "537",
            "x": "537",
            "yExact": "0",
            "y": "0",
            "id": "customer:2688"
          },
          {
            "series": "0",
            "index": "537",
            "xExact": "538",
            "x": "538",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:2692"
          },
          {
            "series": "1",
            "index": "537",
            "xExact": "538",
            "x": "538",
            "yExact": "0",
            "y": "0",
            "id": "customer:2692"
          },
          {
            "series": "0",
            "index": "538",
            "xExact": "539",
            "x": "539",
            "yExact": "4/23",
            "y": "0.173913043",
            "id": "customer:2695"
          },
          {
            "series": "1",
            "index": "538",
            "xExact": "539",
            "x": "539",
            "yExact": "0",
            "y": "0",
            "id": "customer:2695"
          },
          {
            "series": "0",
            "index": "539",
            "xExact": "540",
            "x": "540",
            "yExact": "2/53",
            "y": "0.0377358491",
            "id": "customer:2699"
          },
          {
            "series": "1",
            "index": "539",
            "xExact": "540",
            "x": "540",
            "yExact": "0",
            "y": "0",
            "id": "customer:2699"
          },
          {
            "series": "0",
            "index": "540",
            "xExact": "541",
            "x": "541",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:2704"
          },
          {
            "series": "1",
            "index": "540",
            "xExact": "541",
            "x": "541",
            "yExact": "0",
            "y": "0",
            "id": "customer:2704"
          },
          {
            "series": "0",
            "index": "541",
            "xExact": "542",
            "x": "542",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:2709"
          },
          {
            "series": "1",
            "index": "541",
            "xExact": "542",
            "x": "542",
            "yExact": "0",
            "y": "0",
            "id": "customer:2709"
          },
          {
            "series": "0",
            "index": "542",
            "xExact": "543",
            "x": "543",
            "yExact": "17/29",
            "y": "0.586206897",
            "id": "customer:2712"
          },
          {
            "series": "1",
            "index": "542",
            "xExact": "543",
            "x": "543",
            "yExact": "0",
            "y": "0",
            "id": "customer:2712"
          },
          {
            "series": "0",
            "index": "543",
            "xExact": "544",
            "x": "544",
            "yExact": "17/112",
            "y": "0.151785714",
            "id": "customer:2718"
          },
          {
            "series": "1",
            "index": "543",
            "xExact": "544",
            "x": "544",
            "yExact": "0",
            "y": "0",
            "id": "customer:2718"
          },
          {
            "series": "0",
            "index": "544",
            "xExact": "545",
            "x": "545",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:2722"
          },
          {
            "series": "1",
            "index": "544",
            "xExact": "545",
            "x": "545",
            "yExact": "0",
            "y": "0",
            "id": "customer:2722"
          },
          {
            "series": "0",
            "index": "545",
            "xExact": "546",
            "x": "546",
            "yExact": "17/112",
            "y": "0.151785714",
            "id": "customer:2728"
          },
          {
            "series": "1",
            "index": "545",
            "xExact": "546",
            "x": "546",
            "yExact": "1",
            "y": "1",
            "id": "customer:2728"
          },
          {
            "series": "0",
            "index": "546",
            "xExact": "547",
            "x": "547",
            "yExact": "6/7",
            "y": "0.857142857",
            "id": "customer:2729"
          },
          {
            "series": "1",
            "index": "546",
            "xExact": "547",
            "x": "547",
            "yExact": "1",
            "y": "1",
            "id": "customer:2729"
          },
          {
            "series": "0",
            "index": "547",
            "xExact": "548",
            "x": "548",
            "yExact": "43/218",
            "y": "0.197247706",
            "id": "customer:2730"
          },
          {
            "series": "1",
            "index": "547",
            "xExact": "548",
            "x": "548",
            "yExact": "0",
            "y": "0",
            "id": "customer:2730"
          },
          {
            "series": "0",
            "index": "548",
            "xExact": "549",
            "x": "549",
            "yExact": "2/53",
            "y": "0.0377358491",
            "id": "customer:2734"
          },
          {
            "series": "1",
            "index": "548",
            "xExact": "549",
            "x": "549",
            "yExact": "0",
            "y": "0",
            "id": "customer:2734"
          },
          {
            "series": "0",
            "index": "549",
            "xExact": "550",
            "x": "550",
            "yExact": "17/112",
            "y": "0.151785714",
            "id": "customer:2737"
          },
          {
            "series": "1",
            "index": "549",
            "xExact": "550",
            "x": "550",
            "yExact": "0",
            "y": "0",
            "id": "customer:2737"
          },
          {
            "series": "0",
            "index": "550",
            "xExact": "551",
            "x": "551",
            "yExact": "4/23",
            "y": "0.173913043",
            "id": "customer:2741"
          },
          {
            "series": "1",
            "index": "550",
            "xExact": "551",
            "x": "551",
            "yExact": "0",
            "y": "0",
            "id": "customer:2741"
          },
          {
            "series": "0",
            "index": "551",
            "xExact": "552",
            "x": "552",
            "yExact": "4/23",
            "y": "0.173913043",
            "id": "customer:2750"
          },
          {
            "series": "1",
            "index": "551",
            "xExact": "552",
            "x": "552",
            "yExact": "1",
            "y": "1",
            "id": "customer:2750"
          },
          {
            "series": "0",
            "index": "552",
            "xExact": "553",
            "x": "553",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:2751"
          },
          {
            "series": "1",
            "index": "552",
            "xExact": "553",
            "x": "553",
            "yExact": "0",
            "y": "0",
            "id": "customer:2751"
          },
          {
            "series": "0",
            "index": "553",
            "xExact": "554",
            "x": "554",
            "yExact": "17/112",
            "y": "0.151785714",
            "id": "customer:2752"
          },
          {
            "series": "1",
            "index": "553",
            "xExact": "554",
            "x": "554",
            "yExact": "0",
            "y": "0",
            "id": "customer:2752"
          },
          {
            "series": "0",
            "index": "554",
            "xExact": "555",
            "x": "555",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:2754"
          },
          {
            "series": "1",
            "index": "554",
            "xExact": "555",
            "x": "555",
            "yExact": "0",
            "y": "0",
            "id": "customer:2754"
          },
          {
            "series": "0",
            "index": "555",
            "xExact": "556",
            "x": "556",
            "yExact": "17/112",
            "y": "0.151785714",
            "id": "customer:2755"
          },
          {
            "series": "1",
            "index": "555",
            "xExact": "556",
            "x": "556",
            "yExact": "0",
            "y": "0",
            "id": "customer:2755"
          },
          {
            "series": "0",
            "index": "556",
            "xExact": "557",
            "x": "557",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:2756"
          },
          {
            "series": "1",
            "index": "556",
            "xExact": "557",
            "x": "557",
            "yExact": "0",
            "y": "0",
            "id": "customer:2756"
          },
          {
            "series": "0",
            "index": "557",
            "xExact": "558",
            "x": "558",
            "yExact": "17/112",
            "y": "0.151785714",
            "id": "customer:2757"
          },
          {
            "series": "1",
            "index": "557",
            "xExact": "558",
            "x": "558",
            "yExact": "0",
            "y": "0",
            "id": "customer:2757"
          },
          {
            "series": "0",
            "index": "558",
            "xExact": "559",
            "x": "559",
            "yExact": "17/112",
            "y": "0.151785714",
            "id": "customer:2767"
          },
          {
            "series": "1",
            "index": "558",
            "xExact": "559",
            "x": "559",
            "yExact": "0",
            "y": "0",
            "id": "customer:2767"
          },
          {
            "series": "0",
            "index": "559",
            "xExact": "560",
            "x": "560",
            "yExact": "4/23",
            "y": "0.173913043",
            "id": "customer:2792"
          },
          {
            "series": "1",
            "index": "559",
            "xExact": "560",
            "x": "560",
            "yExact": "0",
            "y": "0",
            "id": "customer:2792"
          },
          {
            "series": "0",
            "index": "560",
            "xExact": "561",
            "x": "561",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:2810"
          },
          {
            "series": "1",
            "index": "560",
            "xExact": "561",
            "x": "561",
            "yExact": "0",
            "y": "0",
            "id": "customer:2810"
          },
          {
            "series": "0",
            "index": "561",
            "xExact": "562",
            "x": "562",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:2814"
          },
          {
            "series": "1",
            "index": "561",
            "xExact": "562",
            "x": "562",
            "yExact": "0",
            "y": "0",
            "id": "customer:2814"
          },
          {
            "series": "0",
            "index": "562",
            "xExact": "563",
            "x": "563",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:2815"
          },
          {
            "series": "1",
            "index": "562",
            "xExact": "563",
            "x": "563",
            "yExact": "0",
            "y": "0",
            "id": "customer:2815"
          },
          {
            "series": "0",
            "index": "563",
            "xExact": "564",
            "x": "564",
            "yExact": "43/218",
            "y": "0.197247706",
            "id": "customer:2819"
          },
          {
            "series": "1",
            "index": "563",
            "xExact": "564",
            "x": "564",
            "yExact": "1",
            "y": "1",
            "id": "customer:2819"
          },
          {
            "series": "0",
            "index": "564",
            "xExact": "565",
            "x": "565",
            "yExact": "1/139",
            "y": "0.0071942446",
            "id": "customer:2826"
          },
          {
            "series": "1",
            "index": "564",
            "xExact": "565",
            "x": "565",
            "yExact": "0",
            "y": "0",
            "id": "customer:2826"
          },
          {
            "series": "0",
            "index": "565",
            "xExact": "566",
            "x": "566",
            "yExact": "17/112",
            "y": "0.151785714",
            "id": "customer:2828"
          },
          {
            "series": "1",
            "index": "565",
            "xExact": "566",
            "x": "566",
            "yExact": "1",
            "y": "1",
            "id": "customer:2828"
          },
          {
            "series": "0",
            "index": "566",
            "xExact": "567",
            "x": "567",
            "yExact": "43/218",
            "y": "0.197247706",
            "id": "customer:2833"
          },
          {
            "series": "1",
            "index": "566",
            "xExact": "567",
            "x": "567",
            "yExact": "0",
            "y": "0",
            "id": "customer:2833"
          },
          {
            "series": "0",
            "index": "567",
            "xExact": "568",
            "x": "568",
            "yExact": "1/139",
            "y": "0.0071942446",
            "id": "customer:2836"
          },
          {
            "series": "1",
            "index": "567",
            "xExact": "568",
            "x": "568",
            "yExact": "0",
            "y": "0",
            "id": "customer:2836"
          },
          {
            "series": "0",
            "index": "568",
            "xExact": "569",
            "x": "569",
            "yExact": "17/112",
            "y": "0.151785714",
            "id": "customer:2838"
          },
          {
            "series": "1",
            "index": "568",
            "xExact": "569",
            "x": "569",
            "yExact": "0",
            "y": "0",
            "id": "customer:2838"
          },
          {
            "series": "0",
            "index": "569",
            "xExact": "570",
            "x": "570",
            "yExact": "3/205",
            "y": "0.0146341463",
            "id": "customer:2844"
          },
          {
            "series": "1",
            "index": "569",
            "xExact": "570",
            "x": "570",
            "yExact": "0",
            "y": "0",
            "id": "customer:2844"
          },
          {
            "series": "0",
            "index": "570",
            "xExact": "571",
            "x": "571",
            "yExact": "4/23",
            "y": "0.173913043",
            "id": "customer:2853"
          },
          {
            "series": "1",
            "index": "570",
            "xExact": "571",
            "x": "571",
            "yExact": "0",
            "y": "0",
            "id": "customer:2853"
          },
          {
            "series": "0",
            "index": "571",
            "xExact": "572",
            "x": "572",
            "yExact": "2/53",
            "y": "0.0377358491",
            "id": "customer:2871"
          },
          {
            "series": "1",
            "index": "571",
            "xExact": "572",
            "x": "572",
            "yExact": "0",
            "y": "0",
            "id": "customer:2871"
          },
          {
            "series": "0",
            "index": "572",
            "xExact": "573",
            "x": "573",
            "yExact": "2/53",
            "y": "0.0377358491",
            "id": "customer:2874"
          },
          {
            "series": "1",
            "index": "572",
            "xExact": "573",
            "x": "573",
            "yExact": "0",
            "y": "0",
            "id": "customer:2874"
          },
          {
            "series": "0",
            "index": "573",
            "xExact": "574",
            "x": "574",
            "yExact": "3/205",
            "y": "0.0146341463",
            "id": "customer:2876"
          },
          {
            "series": "1",
            "index": "573",
            "xExact": "574",
            "x": "574",
            "yExact": "0",
            "y": "0",
            "id": "customer:2876"
          },
          {
            "series": "0",
            "index": "574",
            "xExact": "575",
            "x": "575",
            "yExact": "4/23",
            "y": "0.173913043",
            "id": "customer:2878"
          },
          {
            "series": "1",
            "index": "574",
            "xExact": "575",
            "x": "575",
            "yExact": "1",
            "y": "1",
            "id": "customer:2878"
          },
          {
            "series": "0",
            "index": "575",
            "xExact": "576",
            "x": "576",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:2880"
          },
          {
            "series": "1",
            "index": "575",
            "xExact": "576",
            "x": "576",
            "yExact": "0",
            "y": "0",
            "id": "customer:2880"
          },
          {
            "series": "0",
            "index": "576",
            "xExact": "577",
            "x": "577",
            "yExact": "3/205",
            "y": "0.0146341463",
            "id": "customer:2886"
          },
          {
            "series": "1",
            "index": "576",
            "xExact": "577",
            "x": "577",
            "yExact": "0",
            "y": "0",
            "id": "customer:2886"
          },
          {
            "series": "0",
            "index": "577",
            "xExact": "578",
            "x": "578",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:2887"
          },
          {
            "series": "1",
            "index": "577",
            "xExact": "578",
            "x": "578",
            "yExact": "0",
            "y": "0",
            "id": "customer:2887"
          },
          {
            "series": "0",
            "index": "578",
            "xExact": "579",
            "x": "579",
            "yExact": "2/53",
            "y": "0.0377358491",
            "id": "customer:2888"
          },
          {
            "series": "1",
            "index": "578",
            "xExact": "579",
            "x": "579",
            "yExact": "0",
            "y": "0",
            "id": "customer:2888"
          },
          {
            "series": "0",
            "index": "579",
            "xExact": "580",
            "x": "580",
            "yExact": "4/23",
            "y": "0.173913043",
            "id": "customer:2893"
          },
          {
            "series": "1",
            "index": "579",
            "xExact": "580",
            "x": "580",
            "yExact": "0",
            "y": "0",
            "id": "customer:2893"
          },
          {
            "series": "0",
            "index": "580",
            "xExact": "581",
            "x": "581",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:2895"
          },
          {
            "series": "1",
            "index": "580",
            "xExact": "581",
            "x": "581",
            "yExact": "0",
            "y": "0",
            "id": "customer:2895"
          },
          {
            "series": "0",
            "index": "581",
            "xExact": "582",
            "x": "582",
            "yExact": "17/112",
            "y": "0.151785714",
            "id": "customer:2905"
          },
          {
            "series": "1",
            "index": "581",
            "xExact": "582",
            "x": "582",
            "yExact": "0",
            "y": "0",
            "id": "customer:2905"
          },
          {
            "series": "0",
            "index": "582",
            "xExact": "583",
            "x": "583",
            "yExact": "17/112",
            "y": "0.151785714",
            "id": "customer:2907"
          },
          {
            "series": "1",
            "index": "582",
            "xExact": "583",
            "x": "583",
            "yExact": "0",
            "y": "0",
            "id": "customer:2907"
          },
          {
            "series": "0",
            "index": "583",
            "xExact": "584",
            "x": "584",
            "yExact": "17/112",
            "y": "0.151785714",
            "id": "customer:2918"
          },
          {
            "series": "1",
            "index": "583",
            "xExact": "584",
            "x": "584",
            "yExact": "0",
            "y": "0",
            "id": "customer:2918"
          },
          {
            "series": "0",
            "index": "584",
            "xExact": "585",
            "x": "585",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:2924"
          },
          {
            "series": "1",
            "index": "584",
            "xExact": "585",
            "x": "585",
            "yExact": "0",
            "y": "0",
            "id": "customer:2924"
          },
          {
            "series": "0",
            "index": "585",
            "xExact": "586",
            "x": "586",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:2926"
          },
          {
            "series": "1",
            "index": "585",
            "xExact": "586",
            "x": "586",
            "yExact": "0",
            "y": "0",
            "id": "customer:2926"
          },
          {
            "series": "0",
            "index": "586",
            "xExact": "587",
            "x": "587",
            "yExact": "17/112",
            "y": "0.151785714",
            "id": "customer:2930"
          },
          {
            "series": "1",
            "index": "586",
            "xExact": "587",
            "x": "587",
            "yExact": "0",
            "y": "0",
            "id": "customer:2930"
          },
          {
            "series": "0",
            "index": "587",
            "xExact": "588",
            "x": "588",
            "yExact": "17/112",
            "y": "0.151785714",
            "id": "customer:2937"
          },
          {
            "series": "1",
            "index": "587",
            "xExact": "588",
            "x": "588",
            "yExact": "0",
            "y": "0",
            "id": "customer:2937"
          },
          {
            "series": "0",
            "index": "588",
            "xExact": "589",
            "x": "589",
            "yExact": "4/23",
            "y": "0.173913043",
            "id": "customer:2943"
          },
          {
            "series": "1",
            "index": "588",
            "xExact": "589",
            "x": "589",
            "yExact": "0",
            "y": "0",
            "id": "customer:2943"
          },
          {
            "series": "0",
            "index": "589",
            "xExact": "590",
            "x": "590",
            "yExact": "4/23",
            "y": "0.173913043",
            "id": "customer:2945"
          },
          {
            "series": "1",
            "index": "589",
            "xExact": "590",
            "x": "590",
            "yExact": "0",
            "y": "0",
            "id": "customer:2945"
          },
          {
            "series": "0",
            "index": "590",
            "xExact": "591",
            "x": "591",
            "yExact": "2/53",
            "y": "0.0377358491",
            "id": "customer:2947"
          },
          {
            "series": "1",
            "index": "590",
            "xExact": "591",
            "x": "591",
            "yExact": "0",
            "y": "0",
            "id": "customer:2947"
          },
          {
            "series": "0",
            "index": "591",
            "xExact": "592",
            "x": "592",
            "yExact": "2/53",
            "y": "0.0377358491",
            "id": "customer:2948"
          },
          {
            "series": "1",
            "index": "591",
            "xExact": "592",
            "x": "592",
            "yExact": "0",
            "y": "0",
            "id": "customer:2948"
          },
          {
            "series": "0",
            "index": "592",
            "xExact": "593",
            "x": "593",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:2957"
          },
          {
            "series": "1",
            "index": "592",
            "xExact": "593",
            "x": "593",
            "yExact": "0",
            "y": "0",
            "id": "customer:2957"
          },
          {
            "series": "0",
            "index": "593",
            "xExact": "594",
            "x": "594",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:2959"
          },
          {
            "series": "1",
            "index": "593",
            "xExact": "594",
            "x": "594",
            "yExact": "0",
            "y": "0",
            "id": "customer:2959"
          },
          {
            "series": "0",
            "index": "594",
            "xExact": "595",
            "x": "595",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:2961"
          },
          {
            "series": "1",
            "index": "594",
            "xExact": "595",
            "x": "595",
            "yExact": "0",
            "y": "0",
            "id": "customer:2961"
          },
          {
            "series": "0",
            "index": "595",
            "xExact": "596",
            "x": "596",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:2963"
          },
          {
            "series": "1",
            "index": "595",
            "xExact": "596",
            "x": "596",
            "yExact": "0",
            "y": "0",
            "id": "customer:2963"
          },
          {
            "series": "0",
            "index": "596",
            "xExact": "597",
            "x": "597",
            "yExact": "17/112",
            "y": "0.151785714",
            "id": "customer:2968"
          },
          {
            "series": "1",
            "index": "596",
            "xExact": "597",
            "x": "597",
            "yExact": "0",
            "y": "0",
            "id": "customer:2968"
          },
          {
            "series": "0",
            "index": "597",
            "xExact": "598",
            "x": "598",
            "yExact": "4/23",
            "y": "0.173913043",
            "id": "customer:2989"
          },
          {
            "series": "1",
            "index": "597",
            "xExact": "598",
            "x": "598",
            "yExact": "0",
            "y": "0",
            "id": "customer:2989"
          },
          {
            "series": "0",
            "index": "598",
            "xExact": "599",
            "x": "599",
            "yExact": "2/53",
            "y": "0.0377358491",
            "id": "customer:2994"
          },
          {
            "series": "1",
            "index": "598",
            "xExact": "599",
            "x": "599",
            "yExact": "0",
            "y": "0",
            "id": "customer:2994"
          },
          {
            "series": "0",
            "index": "599",
            "xExact": "600",
            "x": "600",
            "yExact": "43/218",
            "y": "0.197247706",
            "id": "customer:3002"
          },
          {
            "series": "1",
            "index": "599",
            "xExact": "600",
            "x": "600",
            "yExact": "0",
            "y": "0",
            "id": "customer:3002"
          },
          {
            "series": "0",
            "index": "600",
            "xExact": "601",
            "x": "601",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:3006"
          },
          {
            "series": "1",
            "index": "600",
            "xExact": "601",
            "x": "601",
            "yExact": "0",
            "y": "0",
            "id": "customer:3006"
          },
          {
            "series": "0",
            "index": "601",
            "xExact": "602",
            "x": "602",
            "yExact": "1/139",
            "y": "0.0071942446",
            "id": "customer:3011"
          },
          {
            "series": "1",
            "index": "601",
            "xExact": "602",
            "x": "602",
            "yExact": "0",
            "y": "0",
            "id": "customer:3011"
          },
          {
            "series": "0",
            "index": "602",
            "xExact": "603",
            "x": "603",
            "yExact": "1/139",
            "y": "0.0071942446",
            "id": "customer:3016"
          },
          {
            "series": "1",
            "index": "602",
            "xExact": "603",
            "x": "603",
            "yExact": "0",
            "y": "0",
            "id": "customer:3016"
          },
          {
            "series": "0",
            "index": "603",
            "xExact": "604",
            "x": "604",
            "yExact": "43/218",
            "y": "0.197247706",
            "id": "customer:3017"
          },
          {
            "series": "1",
            "index": "603",
            "xExact": "604",
            "x": "604",
            "yExact": "0",
            "y": "0",
            "id": "customer:3017"
          },
          {
            "series": "0",
            "index": "604",
            "xExact": "605",
            "x": "605",
            "yExact": "1/139",
            "y": "0.0071942446",
            "id": "customer:3020"
          },
          {
            "series": "1",
            "index": "604",
            "xExact": "605",
            "x": "605",
            "yExact": "0",
            "y": "0",
            "id": "customer:3020"
          },
          {
            "series": "0",
            "index": "605",
            "xExact": "606",
            "x": "606",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:3022"
          },
          {
            "series": "1",
            "index": "605",
            "xExact": "606",
            "x": "606",
            "yExact": "0",
            "y": "0",
            "id": "customer:3022"
          },
          {
            "series": "0",
            "index": "606",
            "xExact": "607",
            "x": "607",
            "yExact": "4/23",
            "y": "0.173913043",
            "id": "customer:3023"
          },
          {
            "series": "1",
            "index": "606",
            "xExact": "607",
            "x": "607",
            "yExact": "1",
            "y": "1",
            "id": "customer:3023"
          },
          {
            "series": "0",
            "index": "607",
            "xExact": "608",
            "x": "608",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:3025"
          },
          {
            "series": "1",
            "index": "607",
            "xExact": "608",
            "x": "608",
            "yExact": "1",
            "y": "1",
            "id": "customer:3025"
          },
          {
            "series": "0",
            "index": "608",
            "xExact": "609",
            "x": "609",
            "yExact": "17/29",
            "y": "0.586206897",
            "id": "customer:3027"
          },
          {
            "series": "1",
            "index": "608",
            "xExact": "609",
            "x": "609",
            "yExact": "1",
            "y": "1",
            "id": "customer:3027"
          },
          {
            "series": "0",
            "index": "609",
            "xExact": "610",
            "x": "610",
            "yExact": "1/139",
            "y": "0.0071942446",
            "id": "customer:3036"
          },
          {
            "series": "1",
            "index": "609",
            "xExact": "610",
            "x": "610",
            "yExact": "0",
            "y": "0",
            "id": "customer:3036"
          },
          {
            "series": "0",
            "index": "610",
            "xExact": "611",
            "x": "611",
            "yExact": "69/364",
            "y": "0.18956044",
            "id": "customer:3039"
          },
          {
            "series": "1",
            "index": "610",
            "xExact": "611",
            "x": "611",
            "yExact": "0",
            "y": "0",
            "id": "customer:3039"
          },
          {
            "series": "0",
            "index": "611",
            "xExact": "612",
            "x": "612",
            "yExact": "4/23",
            "y": "0.173913043",
            "id": "customer:3041"
          },
          {
            "series": "1",
            "index": "611",
            "xExact": "612",
            "x": "612",
            "yExact": "0",
            "y": "0",
            "id": "customer:3041"
          },
          {
            "series": "0",
            "index": "612",
            "xExact": "613",
            "x": "613",
            "yExact": "2/53",
            "y": "0.0377358491",
            "id": "customer:3047"
          },
          {
            "series": "1",
            "index": "612",
            "xExact": "613",
            "x": "613",
            "yExact": "0",
            "y": "0",
            "id": "customer:3047"
          },
          {
            "series": "0",
            "index": "613",
            "xExact": "614",
            "x": "614",
            "yExact": "23/24",
            "y": "0.958333333",
            "id": "customer:3050"
          },
          {
            "series": "1",
            "index": "613",
            "xExact": "614",
            "x": "614",
            "yExact": "1",
            "y": "1",
            "id": "customer:3050"
          },
          {
            "series": "0",
            "index": "614",
            "xExact": "615",
            "x": "615",
            "yExact": "17/112",
            "y": "0.151785714",
            "id": "customer:3055"
          },
          {
            "series": "1",
            "index": "614",
            "xExact": "615",
            "x": "615",
            "yExact": "0",
            "y": "0",
            "id": "customer:3055"
          },
          {
            "series": "0",
            "index": "615",
            "xExact": "616",
            "x": "616",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:3059"
          },
          {
            "series": "1",
            "index": "615",
            "xExact": "616",
            "x": "616",
            "yExact": "0",
            "y": "0",
            "id": "customer:3059"
          },
          {
            "series": "0",
            "index": "616",
            "xExact": "617",
            "x": "617",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:3061"
          },
          {
            "series": "1",
            "index": "616",
            "xExact": "617",
            "x": "617",
            "yExact": "0",
            "y": "0",
            "id": "customer:3061"
          },
          {
            "series": "0",
            "index": "617",
            "xExact": "618",
            "x": "618",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:3063"
          },
          {
            "series": "1",
            "index": "617",
            "xExact": "618",
            "x": "618",
            "yExact": "0",
            "y": "0",
            "id": "customer:3063"
          },
          {
            "series": "0",
            "index": "618",
            "xExact": "619",
            "x": "619",
            "yExact": "17/112",
            "y": "0.151785714",
            "id": "customer:3078"
          },
          {
            "series": "1",
            "index": "618",
            "xExact": "619",
            "x": "619",
            "yExact": "1",
            "y": "1",
            "id": "customer:3078"
          },
          {
            "series": "0",
            "index": "619",
            "xExact": "620",
            "x": "620",
            "yExact": "43/218",
            "y": "0.197247706",
            "id": "customer:3079"
          },
          {
            "series": "1",
            "index": "619",
            "xExact": "620",
            "x": "620",
            "yExact": "1",
            "y": "1",
            "id": "customer:3079"
          },
          {
            "series": "0",
            "index": "620",
            "xExact": "621",
            "x": "621",
            "yExact": "2/53",
            "y": "0.0377358491",
            "id": "customer:3084"
          },
          {
            "series": "1",
            "index": "620",
            "xExact": "621",
            "x": "621",
            "yExact": "0",
            "y": "0",
            "id": "customer:3084"
          },
          {
            "series": "0",
            "index": "621",
            "xExact": "622",
            "x": "622",
            "yExact": "4/23",
            "y": "0.173913043",
            "id": "customer:3091"
          },
          {
            "series": "1",
            "index": "621",
            "xExact": "622",
            "x": "622",
            "yExact": "0",
            "y": "0",
            "id": "customer:3091"
          },
          {
            "series": "0",
            "index": "622",
            "xExact": "623",
            "x": "623",
            "yExact": "4/23",
            "y": "0.173913043",
            "id": "customer:3093"
          },
          {
            "series": "1",
            "index": "622",
            "xExact": "623",
            "x": "623",
            "yExact": "0",
            "y": "0",
            "id": "customer:3093"
          },
          {
            "series": "0",
            "index": "623",
            "xExact": "624",
            "x": "624",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:3109"
          },
          {
            "series": "1",
            "index": "623",
            "xExact": "624",
            "x": "624",
            "yExact": "0",
            "y": "0",
            "id": "customer:3109"
          },
          {
            "series": "0",
            "index": "624",
            "xExact": "625",
            "x": "625",
            "yExact": "43/218",
            "y": "0.197247706",
            "id": "customer:3119"
          },
          {
            "series": "1",
            "index": "624",
            "xExact": "625",
            "x": "625",
            "yExact": "1",
            "y": "1",
            "id": "customer:3119"
          },
          {
            "series": "0",
            "index": "625",
            "xExact": "626",
            "x": "626",
            "yExact": "4/177",
            "y": "0.0225988701",
            "id": "customer:3122"
          },
          {
            "series": "1",
            "index": "625",
            "xExact": "626",
            "x": "626",
            "yExact": "0",
            "y": "0",
            "id": "customer:3122"
          },
          {
            "series": "0",
            "index": "626",
            "xExact": "627",
            "x": "627",
            "yExact": "17/29",
            "y": "0.586206897",
            "id": "customer:3128"
          },
          {
            "series": "1",
            "index": "626",
            "xExact": "627",
            "x": "627",
            "yExact": "1",
            "y": "1",
            "id": "customer:3128"
          },
          {
            "series": "0",
            "index": "627",
            "xExact": "628",
            "x": "628",
            "yExact": "2/53",
            "y": "0.0377358491",
            "id": "customer:3134"
          },
          {
            "series": "1",
            "index": "627",
            "xExact": "628",
            "x": "628",
            "yExact": "0",
            "y": "0",
            "id": "customer:3134"
          },
          {
            "series": "0",
            "index": "628",
            "xExact": "629",
            "x": "629",
            "yExact": "4/23",
            "y": "0.173913043",
            "id": "customer:3140"
          },
          {
            "series": "1",
            "index": "628",
            "xExact": "629",
            "x": "629",
            "yExact": "0",
            "y": "0",
            "id": "customer:3140"
          },
          {
            "series": "0",
            "index": "629",
            "xExact": "630",
            "x": "630",
            "yExact": "4/23",
            "y": "0.173913043",
            "id": "customer:3145"
          },
          {
            "series": "1",
            "index": "629",
            "xExact": "630",
            "x": "630",
            "yExact": "0",
            "y": "0",
            "id": "customer:3145"
          }
        ],
        "plotFile": "ml14-fixed-results/realdata-company-python/plot.svg",
        "plotSHA256": "4ba45ab970692f476224532b8841b66147059ce4a62d1898ef405d8754193c15",
        "files": [
          {
            "file": "ml14-fixed-results/realdata-company-python/full.json",
            "sha256": "de01fd140c7ac6aa2d6ba17cfb4e2dda69ef42fd696c5dc9c489ac1253f4d634",
            "bytes": 18511774
          },
          {
            "file": "ml14-fixed-results/realdata-company-python/plot-points.csv",
            "sha256": "c379108c8fd1cf87d51420fd1093e9cc5f6dc120575cc1502769a22ddc8cde56",
            "bytes": 49598
          },
          {
            "file": "ml14-fixed-results/realdata-company-python/plot.svg",
            "sha256": "4ba45ab970692f476224532b8841b66147059ce4a62d1898ef405d8754193c15",
            "bytes": 74655
          },
          {
            "file": "ml14-fixed-results/realdata-company-python/summary.csv",
            "sha256": "3eda2f8db024a7be4530ce140becc1819d86ced822c1981e72e0517c47550343",
            "bytes": 663
          }
        ],
        "scope": "Actually executed standalone fixed example, Python exact Fraction versus base-R binary64. Approximate R residuals retained; not universal exact arithmetic/web validation/native UI. Source programs read factual3CSV only."
      }
    },
    "r": {
      "country": {
        "api": "realdata",
        "variant": "country",
        "language": "r",
        "title": "Actual country fixed train/validation/test procedure",
        "codeFile": "ml14-code/realdata-country.R",
        "codeSHA256": "8582985a18cf1b302e82f54d4d2f5dc208579c2e013f5501a70f88f97963f0ab",
        "code": "# ML14 standalone public counterpart, base R only.\n# Inputs are only the three factual CSVs; derived columns/previous model answers unused.\n# Binary64 arithmetic, not arbitrary-precision Fraction. At numerical cost ties\n# within 1e-12 retain the earliest candidate. Exact claims belong to Python/web.\n# SHA256 infrastructure below is reused verbatim from the previous public study.\nargs<-commandArgs(trailingOnly=TRUE);filearg<-grep(\"^--file=\",commandArgs(),value=TRUE)\nhere<-if(dir.exists(\"ml14-sources\"))getwd()else if(length(filearg))dirname(normalizePath(sub(\"^--file=\",\"\",filearg[1])))else getwd()\noption<-function(key,default){i<-match(key,args);if(is.na(i))default else args[i+1]}\nsourceDir<-option(\"--source\",file.path(here,\"ml14-sources\"));outDir<-option(\"--out\",file.path(getwd(),\"ml14-r-results\"));dir.create(outDir,recursive=TRUE,showWarnings=FALSE)\nnum<-function(x){x[x%in%c(\"\",\".\")]<-NA_character_;as.numeric(x)}\nfmt<-function(x)ifelse(is.na(x),\"\",sprintf(\"%.17g\",x))\nratio<-function(a,b)if(b==0)NA_real_ else a/b\nreadnative<-function(name)read.csv(file.path(sourceDir,name),check.names=FALSE,colClasses=\"character\",na.strings=character(),stringsAsFactors=FALSE)\n# Vectorized SHA256 for the short ASCII keys used in this study.\n# Unsigned words use exact integer-valued doubles; bit operations use safe\n# 16-bit halves, avoiding R's reserved signed-INT_MIN/NA representation.\nMOD<-2^32\nxor32<-function(a,b) as.double(bitwXor(as.integer(floor(a/65536)),as.integer(floor(b/65536))))*65536+as.double(bitwXor(as.integer(a%%65536),as.integer(b%%65536)))\nand32<-function(a,b) as.double(bitwAnd(as.integer(floor(a/65536)),as.integer(floor(b/65536))))*65536+as.double(bitwAnd(as.integer(a%%65536),as.integer(b%%65536)))\nrot<-function(x,n) floor(x/2^n)+(x%%2^n)*2^(32-n)\nxor3<-function(a,b,c) xor32(xor32(a,b),c)\nK<-c(0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5,0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967,0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070,0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3,0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2)\nsha256<-function(strings) {\n n<-length(strings);bytes<-matrix(0,n,64)\n for(i in seq_len(n)) {v<-utf8ToInt(strings[i]);stopifnot(length(v)<56,all(v<128));if(length(v)) bytes[i,seq_along(v)]<-v;bytes[i,length(v)+1]<-128;bits<-length(v)*8;bytes[i,61:64]<-c(floor(bits/2^24)%%256,floor(bits/2^16)%%256,floor(bits/256)%%256,bits%%256)}\n w<-matrix(0,n,64)\n for(j in 1:16) {b<-4*(j-1)+1;w[,j]<-bytes[,b]*2^24+bytes[,b+1]*2^16+bytes[,b+2]*256+bytes[,b+3]}\n for(j in 17:64) {s0<-xor3(rot(w[,j-15],7),rot(w[,j-15],18),floor(w[,j-15]/8));s1<-xor3(rot(w[,j-2],17),rot(w[,j-2],19),floor(w[,j-2]/1024));w[,j]<-(w[,j-16]+s0+w[,j-7]+s1)%%MOD}\n init<-c(0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19)\n state<-lapply(init,function(v) rep(v,n));a<-state[[1]];b<-state[[2]];c<-state[[3]];d<-state[[4]];e<-state[[5]];f<-state[[6]];g<-state[[7]];h<-state[[8]]\n for(j in 1:64) {S1<-xor3(rot(e,6),rot(e,11),rot(e,25));ch<-xor32(and32(e,f),and32(MOD-1-e,g));t1<-(h+S1+ch+K[j]+w[,j])%%MOD;S0<-xor3(rot(a,2),rot(a,13),rot(a,22));maj<-xor3(and32(a,b),and32(a,c),and32(b,c));t2<-(S0+maj)%%MOD;h<-g;g<-f;f<-e;e<-(d+t1)%%MOD;d<-c;c<-b;b<-a;a<-(t1+t2)%%MOD}\n end<-list(a,b,c,d,e,f,g,h);hex<-lapply(1:8,function(j){v<-(end[[j]]+init[j])%%MOD;paste0(sprintf(\"%04x\",as.integer(floor(v/65536))),sprintf(\"%04x\",as.integer(v%%65536)))})\n do.call(paste0,hex)\n}\nstopifnot(identical(sha256(c(\"abc\",\"\")),c(\"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad\",\"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855\")))\n\nloadData<-function(){\n wb<-readnative(\"actual64-country-four-indicators-original-2024.csv\");codes<-c(\"NY.GDP.PCAP.KD\",\"NY.GDP.MKTP.KD.ZG\",\"FP.CPI.TOTL.ZG\",\"SP.DYN.LE00.IN\");iso<-sort(unique(wb$countryISO3));stopifnot(nrow(wb)==64,length(iso)==16)\n tokens<-t(vapply(iso,function(s)wb$originalValueToken[match(paste(s,codes),paste(wb$countryISO3,wb$indicatorID))],character(4)));vals<-matrix(num(as.vector(tokens)),nrow=nrow(tokens))\n country<-list(id=paste0(iso,\":2024\"),sourceRow=1:16,originalID=iso,x=vals[,1:3,drop=FALSE],rawX=tokens[,1:3,drop=FALSE],nativeTarget=tokens[,4],y=as.integer(vals[,4]>=80),group=ifelse(is.na(vals[,1]),NA_character_,as.character(as.integer(vals[,1]>=25000))),lineage=vapply(iso,function(s)paste(wb$sourceRow[match(paste(s,codes),paste(wb$countryISO3,wb$indicatorID))],collapse=\";\"),character(1)),cat=integer(),units=c(\"constant2015USD/person\",\"annualPercent\",\"annualPercent\"))\n nls<-readnative(\"actual3613-NLS-original52-fields-groups-roles.csv\");raw<-cbind(nls$ed76,nls$age76,nls$nearc4)\n person<-list(id=paste0(\"person:\",nls$sourceRow),sourceRow=as.integer(nls$sourceRow),originalID=nls$id,x=matrix(num(as.vector(raw)),nrow=nrow(raw)),rawX=raw,nativeTarget=nls$wage76,y=as.integer(num(nls$wage76)>=500),group=ifelse(nls$black%in%c(\"\",\".\"),NA_character_,nls$black),lineage=nls$sourceRow,cat=2L,units=c(\"years\",\"years\",\"nativeCategory\"))\n ch<-readnative(\"actual3150-churn-original14-fields-groups-roles.csv\");raw<-cbind(ch[[\"Call  Failure\"]],ch$Complains,ch[[\"Subscription  Length\"]],ch[[\"Seconds of Use\"]])\n company<-list(id=paste0(\"customer:\",ch$sourceRow),sourceRow=as.integer(ch$sourceRow),originalID=rep(\"\",nrow(ch)),x=matrix(num(as.vector(raw)),nrow=nrow(raw)),rawX=raw,nativeTarget=ch$Churn,y=as.integer(ch$Churn),group=ifelse(ch[[\"Tariff Plan\"]]%in%c(\"\",\".\"),NA_character_,ch[[\"Tariff Plan\"]]),lineage=ch$sourceRow,cat=1L,units=c(\"count\",\"nativeCategory\",\"months\",\"seconds\"))\n stopifnot(nrow(nls)==3613,nrow(ch)==3150,identical(as.integer(ch$sourceRow[ch[[\"Charge  Amount\"]]==\"10\"]),c(474L,2174L,2274L,2374L,2674L,2924L,2974L)))\n result<-list(country=country,person=person,company=company)\n for(k in names(result)){d<-result[[k]];n<-length(d$id);d$eligible<-!is.na(d$y)&rowSums(is.na(d$x))==0;hash<-sha256(paste0(\"ML14-role|\",k,\"|\",d$id));rank<-integer(n);rank[order(hash,seq_len(n))]<-seq_len(n)-1L;d$plannedRole<-ifelse(rank%%5==0,\"test\",ifelse(rank%%5==1,\"validation\",\"train\"));d$role<-ifelse(d$eligible,d$plannedRole,\"excluded\");result[[k]]<-d}\n stopifnot(sum(result$person$eligible)==3017);result\n}\nfitmodel<-function(d){\n ids<-which(d$role==\"train\");p<-ncol(d$x);m<-vapply(seq_len(p),function(j)if((j-1)%in%d$cat)NA_real_ else median(d$x[ids,j]),numeric(1));z<-d$x\n for(j in seq_len(p))if(!((j-1)%in%d$cat))z[,j]<-as.numeric(z[,j]>m[j])\n keys<-apply(z,1,function(v)paste(fmt(v),collapse=\"|\"));lev<-unique(keys[ids]);mass<-vapply(lev,function(k)sum(keys[ids]==k),integer(1));positive<-vapply(lev,function(k)sum(d$y[ids][keys[ids]==k]),integer(1));prob<-(positive+1)/(mass+2);fallback<-(sum(d$y[ids])+1)/(length(ids)+2);pred<-prob[match(keys,lev)];unseen<-is.na(pred);pred[unseen]<-fallback;pred[!d$eligible]<-NA_real_;unseen[!d$eligible]<-NA\n list(ids=ids,medians=m,z=z,keys=keys,lev=lev,mass=mass,positive=positive,prob=prob,fallback=fallback,pred=pred,unseen=unseen)\n}\nmeasure<-function(d,p,ids,t=.5,cost=c(1,1)){\n use<-ids[d$eligible[ids]&!is.na(p[ids])];y<-d$y[use];a<-if(is.character(t))rep(t==\"always-positive\",length(use))else p[use]>=t\n TP<-sum(a&y==1);FP<-sum(a&y==0);FN<-sum(!a&y==1);TN<-sum(!a&y==0);P<-TP+FN;N<-FP+TN;W<-P+N;PP<-TP+FP;PN<-TN+FN;TPR<-ratio(TP,P);TNR<-ratio(TN,N);bs<-sum((p[use]-y)^2);tc<-FP*cost[1]+FN*cost[2]\n list(TP=TP,FP=FP,FN=FN,TN=TN,mass=W,positiveTargetMass=P,negativeTargetMass=N,predictedPositiveMass=PP,predictedNegativeMass=PN,prevalence=ratio(P,W),selectionRate=ratio(PP,W),accuracy=ratio(TP+TN,W),precision=ratio(TP,PP),negativePredictiveValue=ratio(TN,PN),TPR=TPR,FPR=ratio(FP,N),TNR=TNR,FNR=ratio(FN,P),F1=ratio(2*TP,2*TP+FP+FN),balancedAccuracy=if(is.na(TPR)||is.na(TNR))NA_real_ else(TPR+TNR)/2,Brier=ratio(bs,W),BrierSum=bs,totalCost=tc,meanCost=ratio(tc,W))\n}\ncurves<-function(d,p,ids){\n use<-ids[d$eligible[ids]&!is.na(p[ids])];scores<-sort(unique(p[use]),decreasing=TRUE);policies<-c(list(\"always-negative\"),as.list(scores));points<-lapply(policies,function(t){m<-measure(d,p,ids,t);c(list(policy=t),m[c(\"TP\",\"FP\",\"FN\",\"TN\",\"TPR\",\"FPR\",\"precision\")],list(recall=m$TPR))})\n pos<-use[d$y[use]==1];neg<-use[d$y[use]==0];U<-0;for(i in pos)U<-U+sum(p[i]>p[neg])+.5*sum(p[i]==p[neg])\n AP<-0;trap<-0;lastR<-0;lastP<-1\n if(length(pos)&&length(scores))for(j in seq_along(scores)){z<-points[[j+1]];AP<-AP+(z$recall-lastR)*z$precision;trap<-trap+(z$recall-lastR)*(z$precision+lastP)/2;lastR<-z$recall;lastP<-z$precision}\n list(points=points,ROC_AUC=ratio(U,length(pos)*length(neg)),averagePrecision=if(length(pos))AP else NA_real_,PRTrapezoidWithInitialPrecisionOne=if(length(pos))trap else NA_real_)\n}\ncalibrate<-function(d,p,ids){\n use<-ids[d$eligible[ids]&!is.na(p[ids])];W<-length(use);pi<-if(W)mean(d$y[use])else NA_real_;bins<-list();ECE<-rel<-res<-correction<-0\n whichbin<-findInterval(p[use],seq(0,1,.2),rightmost.closed=TRUE,all.inside=TRUE)\n for(b in 1:5){rr<-use[whichbin==b];w<-length(rr);mp<-if(w)mean(p[rr])else NA_real_;o<-if(w)mean(d$y[rr])else NA_real_;variance<-if(w)mean((p[rr]-mp)^2)else NA_real_;covariance<-if(w)mean((p[rr]-mp)*(d$y[rr]-o))else NA_real_;bc<-variance-2*covariance;gap<-mp-o\n  bins[[b]]<-list(mass=w,meanPrediction=mp,eventRate=o,gap=gap,absoluteGap=abs(gap),scoreVariance=variance,scoreTargetCovariance=covariance,withinBinCorrection=bc,rows=w,ids=d$id[rr])\n  if(w){share<-w/W;ECE<-ECE+share*abs(gap);rel<-rel+share*gap^2;res<-res+share*(o-pi)^2;correction<-correction+share*bc}\n };bs<-if(W)mean((p[use]-d$y[use])^2)else NA_real_;unc<-pi*(1-pi)\n list(bins=bins,ECE=if(W)ECE else NA_real_,Brier=bs,reliability=if(W)rel else NA_real_,resolution=if(W)res else NA_real_,uncertainty=unc,withinBinCorrection=if(W)correction else NA_real_,BrierIdentityResidual=bs-(unc-res+rel+correction))\n}\ncounts<-c(\"mass\",\"positiveTargetMass\",\"negativeTargetMass\",\"predictedPositiveMass\",\"predictedNegativeMass\");rates<-c(\"prevalence\",\"selectionRate\",\"accuracy\",\"precision\",\"negativePredictiveValue\",\"TPR\",\"FPR\",\"TNR\",\"FNR\",\"F1\",\"balancedAccuracy\",\"Brier\",\"BrierSum\",\"totalCost\",\"meanCost\")\ntables<-setNames(lapply(1:10,function(i)list()),c(\"predictions\",\"lineage\",\"fit-medians\",\"fit-cells\",\"validation-candidates\",\"test-metrics\",\"test-curves\",\"calibration-bins\",\"group-metrics\",\"chart-points\"))\nadd<-function(name,row)tables[[name]][[length(tables[[name]])+1L]]<<-row\nscalars<-function(m,keys){out<-list();for(k in keys){out[[paste0(k,\"Exact\")]]<-\"\";out[[paste0(k,\"Approx\")]]<-fmt(m[[k]])};out}\ntagrow<-function(kind,...)c(list(kind=kind),list(...))\npoint<-function(kind,chart,series,index,x,y,xunit=\"dimensionless\",yunit=\"dimensionless\",role=\"test\",tag=\"\"){add(\"chart-points\",tagrow(kind,chart=chart,series=series,index=index,xExact=\"\",xApprox=fmt(x),yExact=\"\",yApprox=fmt(y),xUnit=xunit,yUnit=yunit,role=role,tag=tag))}\nstudy<-function(kind,d){\n f<-fitmodel(d);n<-length(d$id);train<-which(d$role==\"train\");validation<-which(d$role==\"validation\");test<-which(d$role==\"test\");p<-f$pred;cv<-curves(d,p,test);cal<-calibrate(d,p,test)\n for(i in seq_len(n)){\n  reason<-if(d$eligible[i])\"\"else\"required-X-or-Y-missing\";transformed<-if(d$eligible[i])paste(fmt(f$z[i,]),collapse=\"|\")else\"\"\n  add(\"predictions\",tagrow(kind,id=d$id[i],sourceRow=d$sourceRow[i],originalID=d$originalID[i],plannedRole=d$plannedRole[i],role=d$role[i],group=ifelse(is.na(d$group[i]),\"\",d$group[i]),eligible=as.integer(d$eligible[i]),targetExact=fmt(d$y[i]),probabilityExact=\"\",probabilityApprox=fmt(p[i]),unseenCell=ifelse(is.na(f$unseen[i]),\"\",as.character(as.integer(f$unseen[i]))),transformedX=transformed,reason=reason))\n  raw<-d$rawX[i,];raw[raw%in%c(\"\",\".\")]<-\"\";nativeY<-d$nativeTarget[i];if(nativeY%in%c(\"\",\".\"))nativeY<-\"\"\n  add(\"lineage\",tagrow(kind,id=d$id[i],sourceRow=d$sourceRow[i],originalID=d$originalID[i],nativeSourceRows=d$lineage[i],rawX=paste(raw,collapse=\"|\"),nativeTarget=nativeY,derivedTarget=fmt(d$y[i]),nativeGroup=ifelse(is.na(d$group[i]),\"\",d$group[i]),plannedRole=d$plannedRole[i],role=d$role[i],eligible=as.integer(d$eligible[i]),analyticalMass=\"1\",reason=reason))\n }\n for(j in seq_len(ncol(d$x)))add(\"fit-medians\",tagrow(kind,feature=j-1,categorical=as.integer((j-1)%in%d$cat),fitRows=length(train),medianExact=\"\",medianApprox=fmt(f$medians[j]),unit=d$units[j]))\n for(j in seq_along(f$lev))add(\"fit-cells\",tagrow(kind,cell=f$lev[j],trainingRows=f$mass[j],positiveRows=f$positive[j],probabilityExact=\"\",probabilityApprox=fmt(f$prob[j]),fallbackExact=\"\",fallbackApprox=fmt(f$fallback)))\n for(j in seq_along(cv$points)){\n  z<-cv$points[[j]];t<-z$policy;add(\"test-curves\",c(tagrow(kind,point=j-1,policy=if(is.character(t))t else\"threshold\",thresholdExact=\"\",thresholdApprox=if(is.character(t))\"\"else fmt(t)),scalars(z,c(\"TP\",\"FP\",\"FN\",\"TN\",\"TPR\",\"FPR\",\"precision\",\"recall\"))))\n  point(kind,\"roc\",\"ROC\",j-1,z$FPR,z$TPR);point(kind,\"pr\",\"PR-observed\",j-1,z$recall,z$precision)\n }\n for(b in 1:5){z<-cal$bins[[b]];add(\"calibration-bins\",c(tagrow(kind,bin=b-1,leftExact=c(\"0\",\"1/5\",\"2/5\",\"3/5\",\"4/5\")[b],rightExact=c(\"1/5\",\"2/5\",\"3/5\",\"4/5\",\"1\")[b],rightClosed=as.integer(b==5),rows=z$rows,ids=paste(z$ids,collapse=\";\")),scalars(z,c(\"mass\",\"meanPrediction\",\"eventRate\",\"gap\",\"absoluteGap\",\"scoreVariance\",\"scoreTargetCovariance\",\"withinBinCorrection\"))));point(kind,\"reliability\",\"Binary event rate\",b-1,z$meanPrediction,z$eventRate,tag=paste0(\"rows=\",z$rows))}\n for(j in seq_along(test)){i<-test[j];point(kind,\"test-scores\",\"Training-fitted probability\",j-1,j,p[i],\"test-row position\",\"probability\",tag=d$id[i]);point(kind,\"test-scores\",\"Observed Y\",j-1,j,d$y[i],\"test-row position\",\"binary target\",tag=d$id[i])}\n scenarioNames<-c(\"equal\",\"miss-five\",\"alarm-five\");costs<-list(c(1,1),c(1,5),c(5,1))\n for(s in 1:3){name<-scenarioNames[s];cost<-costs[[s]];grid<-c(list(\"always-negative\"),as.list(sort(unique(p[validation]),decreasing=TRUE)));candidates<-lapply(grid,function(t)measure(d,p,validation,t,cost));values<-vapply(candidates,function(m)m$meanCost,numeric(1));best<-which(values<=min(values)+1e-12)[1];chosen<-grid[[best]];ev<-measure(d,p,test,chosen,cost)\n  for(j in seq_along(grid)){t<-grid[[j]];m<-candidates[[j]];cell<-setNames(lapply(c(\"TP\",\"FP\",\"FN\",\"TN\"),function(k)fmt(m[[k]])),paste0(c(\"TP\",\"FP\",\"FN\",\"TN\"),\"Exact\"));add(\"validation-candidates\",c(tagrow(kind,scenario=name,candidate=j-1,selected=as.integer(j==best),policy=if(is.character(t))t else\"threshold\",thresholdExact=\"\",thresholdApprox=if(is.character(t))\"\"else fmt(t),feasible=1,reasons=\"\"),cell,scalars(m,c(counts,\"TPR\",\"FPR\",\"precision\",\"meanCost\",\"totalCost\"))));point(kind,\"validation-cost\",name,j-1,j-1,m$meanCost,\"candidate index\",\"hypothetical cost units/mass\",\"validation\",if(is.character(t))t else fmt(t))}\n  m<-c(ev,cv[c(\"ROC_AUC\",\"averagePrecision\",\"PRTrapezoidWithInitialPrecisionOne\")],cal[c(\"ECE\",\"reliability\",\"resolution\",\"uncertainty\",\"withinBinCorrection\",\"BrierIdentityResidual\")])\n  for(k in c(\"TP\",\"FP\",\"FN\",\"TN\",counts,rates,\"ROC_AUC\",\"averagePrecision\",\"PRTrapezoidWithInitialPrecisionOne\",\"ECE\",\"reliability\",\"resolution\",\"uncertainty\",\"withinBinCorrection\",\"BrierIdentityResidual\")){\n   unit<-if(k%in%c(\"TP\",\"FP\",\"FN\",\"TN\",counts))\"rows\"else if(k==\"totalCost\")\"hypothetical cost units\"else if(k==\"meanCost\")\"hypothetical cost units/mass\"else if(k==\"BrierSum\")\"sum squared-probability loss\"else\"dimensionless\"\n   add(\"test-metrics\",tagrow(kind,scenario=name,metric=k,valueExact=\"\",valueApprox=fmt(m[[k]]),unit=unit))\n  }\n  lev<-unique(d$group[test][!is.na(d$group[test])]);sets<-c(list(test),lapply(lev,function(g)test[!is.na(d$group[test])&d$group[test]==g]),list(test[is.na(d$group[test])]))\n  types<-c(\"overall\",rep(\"known\",length(lev)),\"unknown\");tokens<-c(\"all\",lev,\"\")\n  for(j in seq_along(sets)){ids<-sets[[j]];m<-measure(d,p,ids,chosen,cost);cell<-setNames(lapply(c(\"TP\",\"FP\",\"FN\",\"TN\"),function(k)fmt(m[[k]])),paste0(c(\"TP\",\"FP\",\"FN\",\"TN\"),\"Exact\"));add(\"group-metrics\",c(tagrow(kind,scenario=name,groupType=types[j],groupToken=tokens[j],retainedRows=length(ids)),cell,scalars(m,c(counts,rates))));if(types[j]==\"known\")point(kind,\"group-TPR\",name,j-2,j-2,m$TPR,\"declared group position\",\"TPR\",tag=tokens[j])}\n }\n invisible(NULL)\n}\n\n# Fixed finite inputs only; not the complete web input/budget validator.\nqnum<-function(v){if(is.null(v))return(NA_real_);if(is.logical(v))return(as.numeric(v));s<-as.character(v);if(grepl(\"/\",s,fixed=TRUE)){a<-strsplit(s,\"/\",fixed=TRUE)[[1]];return(as.numeric(a[1])/as.numeric(a[2]))};as.numeric(s)}\nrowsG<-function(raw){\n n<-length(raw);get<-function(r,k,default=NULL)if(is.null(r[[k]]))default else r[[k]]\n id<-vapply(raw,function(r)as.character(r$id),character(1));p<-vapply(raw,function(r)qnum(r$score),numeric(1));y<-vapply(raw,function(r)qnum(r$y),numeric(1));w<-vapply(raw,function(r)qnum(get(r,\"weight\",\"1\")),numeric(1));role<-vapply(raw,function(r)get(r,\"role\",\"evaluation\"),character(1));group<-vapply(raw,function(r)as.character(get(r,\"group\",NA_character_)),character(1))\n stopifnot(all(w>=0),all(is.na(p)|(p>=0&p<=1)),all(is.na(y)|y%in%c(0,1)),!anyDuplicated(id));list(id=id,p=p,y=y,w=w,role=role,group=group,eligible=!is.na(p)&!is.na(y)&w>0&role!=\"excluded\")\n}\nscopeG<-function(d,role=\"all\")if(role==\"all\")seq_along(d$id)else which(d$role==role)\nmetricsG<-function(d,ids,t=.5,cost=c(1,1)){\n use<-ids[d$eligible[ids]];p<-d$p[use];y<-d$y[use];w<-d$w[use];a<-if(is.character(t))rep(t==\"always-positive\",length(use))else p>=t\n TP<-sum(w[a&y==1]);FP<-sum(w[a&y==0]);FN<-sum(w[!a&y==1]);TN<-sum(w[!a&y==0]);P<-TP+FN;N<-FP+TN;W<-P+N;PP<-TP+FP;PN<-TN+FN;TPR<-ratio(TP,P);TNR<-ratio(TN,N);bs<-sum(w*(p-y)^2);tc<-FP*cost[1]+FN*cost[2]\n list(confusion=list(TP=TP,FP=FP,FN=FN,TN=TN),mass=W,positiveTargetMass=P,negativeTargetMass=N,predictedPositiveMass=PP,predictedNegativeMass=PN,prevalence=ratio(P,W),selectionRate=ratio(PP,W),accuracy=ratio(TP+TN,W),precision=ratio(TP,PP),negativePredictiveValue=ratio(TN,PN),TPR=TPR,FPR=ratio(FP,N),TNR=TNR,FNR=ratio(FN,P),F1=ratio(2*TP,2*TP+FP+FN),balancedAccuracy=if(is.na(TPR)||is.na(TNR))NA_real_ else(TPR+TNR)/2,Brier=ratio(bs,W),BrierSum=bs,totalCost=tc,meanCost=ratio(tc,W),bayesThreshold=ratio(cost[1],sum(cost)))\n}\ncurvesG<-function(d,ids){\n use<-ids[d$eligible[ids]];grid<-c(list(\"always-negative\"),as.list(sort(unique(d$p[use]),decreasing=TRUE)));points<-lapply(grid,function(t){m<-metricsG(d,ids,t);c(list(policy=t),m$confusion,m[c(\"TPR\",\"FPR\",\"precision\")],list(recall=m$TPR))});pos<-use[d$y[use]==1];neg<-use[d$y[use]==0];P<-sum(d$w[pos]);N<-sum(d$w[neg]);U<-0\n for(i in pos)U<-U+d$w[i]*sum(d$w[neg]*((d$p[i]>d$p[neg])+.5*(d$p[i]==d$p[neg])))\n AP<-trap<-lastR<-0;lastP<-1\n if(P&&length(grid)>1)for(j in 2:length(grid)){z<-points[[j]];AP<-AP+(z$recall-lastR)*z$precision;trap<-trap+(z$recall-lastR)*(z$precision+lastP)/2;lastR<-z$recall;lastP<-z$precision}\n list(points=points,ROC_AUC=ratio(U,P*N),averagePrecision=if(P)AP else NA_real_,PRTrapezoidWithInitialPrecisionOne=if(P)trap else NA_real_)\n}\nchooseG<-function(d,a,cost){\n role<-if(is.null(a$selectionRole))\"validation\"else a$selectionRole;er<-if(is.null(a$evaluationRole))\"test\"else a$evaluationRole;ids<-scopeG(d,role);use<-ids[d$eligible[ids]];stopifnot(length(use)>0);grid<-if(is.null(a$thresholds))c(list(\"always-negative\"),as.list(sort(unique(d$p[use]),decreasing=TRUE)))else lapply(a$thresholds,function(t)if(t%in%c(\"always-negative\",\"always-positive\"))t else qnum(t))\n candidates<-lapply(seq_along(grid),function(j){m<-metricsG(d,ids,grid[[j]],cost);feasible<-TRUE;if(!is.null(a$minTPR))feasible<-feasible&&!is.na(m$TPR)&&m$TPR>=qnum(a$minTPR);if(!is.null(a$maxFPR))feasible<-feasible&&!is.na(m$FPR)&&m$FPR<=qnum(a$maxFPR);list(index=j-1,policy=grid[[j]],metrics=m,feasible=feasible)})\n good<-which(vapply(candidates,function(c)c$feasible,logical(1)));best<-NA_integer_;if(length(good)){v<-vapply(candidates[good],function(c)c$metrics$meanCost,numeric(1));best<-good[which(v<=min(v)+1e-12)[1]]}\n list(selectedIndex=if(is.na(best))NA_integer_ else best-1,selectedPolicy=if(is.na(best))NULL else grid[[best]],selectedValidation=if(is.na(best))NULL else candidates[[best]]$metrics,candidates=candidates,evaluation=if(is.na(best)||er==\"none\")NULL else metricsG(d,scopeG(d,er),grid[[best]],cost))\n}\ncalibrateG<-function(d,ids,edges){\n use<-ids[d$eligible[ids]];W<-sum(d$w[use]);pi<-ratio(sum(d$w[use]*d$y[use]),W);bins<-list();ECE<-rel<-res<-correction<-0;assign<-findInterval(d$p[use],edges,rightmost.closed=TRUE,all.inside=TRUE)\n for(b in seq_len(length(edges)-1)){rr<-use[assign==b];w<-sum(d$w[rr]);mp<-ratio(sum(d$w[rr]*d$p[rr]),w);o<-ratio(sum(d$w[rr]*d$y[rr]),w);variance<-if(w)sum(d$w[rr]*(d$p[rr]-mp)^2)/w else NA_real_;covariance<-if(w)sum(d$w[rr]*(d$p[rr]-mp)*(d$y[rr]-o))/w else NA_real_;bc<-variance-2*covariance;gap<-mp-o;bins[[b]]<-list(index=b-1,mass=w,meanPrediction=mp,eventRate=o,scoreVariance=variance,scoreTargetCovariance=covariance,withinBinCorrection=bc,ids=d$id[rr])\n  if(w){s<-w/W;ECE<-ECE+s*abs(gap);rel<-rel+s*gap^2;res<-res+s*(o-pi)^2;correction<-correction+s*bc}\n };bs<-ratio(sum(d$w[use]*(d$p[use]-d$y[use])^2),W);unc<-pi*(1-pi);list(bins=bins,Brier=bs,ECE=if(W)ECE else NA_real_,uncertainty=unc,reliability=if(W)rel else NA_real_,resolution=if(W)res else NA_real_,withinBinCorrection=if(W)correction else NA_real_,BrierIdentityResidual=bs-(unc-res+rel+correction))\n}\ngroupsG<-function(d,ids,t,cost){\n lev<-unique(d$group[ids][!is.na(d$group[ids])]);groups<-lapply(lev,function(g)list(group=g,metrics=metricsG(d,ids[!is.na(d$group[ids])&d$group[ids]==g],t,cost)));overall<-metricsG(d,ids,t,cost);unknown<-metricsG(d,ids[is.na(d$group[ids])],t,cost);gaps<-list()\n for(k in c(\"prevalence\",\"selectionRate\",\"TPR\",\"FPR\",\"precision\",\"accuracy\",\"meanCost\")){use<-Filter(function(g)g$metrics$mass>0,groups);v<-vapply(use,function(g)g$metrics[[k]],numeric(1));gaps[[k]]<-if(length(use)<2||anyNA(v))NA_real_ else max(v)-min(v)}\n list(overall=overall,groups=groups,unknownGroup=unknown,gaps=gaps,partitionMassResidual=overall$mass-unknown$mass-sum(vapply(groups,function(g)g$metrics$mass,numeric(1))))\n}\nsvgFixed<-function(file,points,title,xlabel,ylabel,legend){\n finite<-points[points$y!=\"undefined\"&points$x!=\"undefined\",,drop=FALSE];x<-as.numeric(finite$x);y<-as.numeric(finite$y);xmin<-if(length(x))min(x)else 0;xmax<-if(length(x))max(x)else 1;ymin<-min(c(0,y));ymax<-max(c(0,y));if(xmin==xmax){xmin<-xmin-.5;xmax<-xmax+.5};if(ymin==ymax)ymax<-ymin+1;X<-function(v)85+(v-xmin)/(xmax-xmin)*480;Y<-function(v)278-(v-ymin)/(ymax-ymin)*175\n esc<-function(s){s<-gsub(\"&\",\"&amp;\",s,fixed=TRUE);s<-gsub(\"<\",\"&lt;\",s,fixed=TRUE);gsub(\">\",\"&gt;\",s,fixed=TRUE)};s<-'<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"620\" height=\"360\" viewBox=\"0 0 620 360\"><rect width=\"620\" height=\"360\" fill=\"white\"/><g font-family=\"Arial, sans-serif\" font-size=\"13\" fill=\"#17324d\">'\n lines<-strwrap(title,width=65);for(i in seq_along(lines))s<-paste0(s,'<text x=\"25\" y=\"',24+(i-1)*18,'\">',esc(lines[i]),'</text>');colors<-c(\"#176b9b\",\"#b85e18\",\"#437e4d\")\n for(i in seq_along(legend))s<-paste0(s,'<circle cx=\"',30+(i-1)*250,'\" cy=\"76\" r=\"4\" fill=\"',colors[(i-1)%%3+1],'\"/><text x=\"',42+(i-1)*250,'\" y=\"80\">',esc(legend[i]),'</text>')\n s<-paste0(s,'<path d=\"M85 98V278H575\" fill=\"none\" stroke=\"#52677d\"/><text text-anchor=\"middle\" x=\"325\" y=\"338\">',esc(xlabel),'</text><text text-anchor=\"middle\" transform=\"translate(21,190) rotate(-90)\">',esc(ylabel),'</text>')\n for(i in 0:4){xx<-xmin+(xmax-xmin)*i/4;yy<-ymin+(ymax-ymin)*i/4;s<-paste0(s,'<text text-anchor=\"middle\" x=\"',sprintf(\"%.9g\",X(xx)),'\" y=\"305\">',sprintf(\"%.4g\",xx),'</text><text text-anchor=\"end\" x=\"77\" y=\"',sprintf(\"%.9g\",Y(yy)+4),'\">',sprintf(\"%.4g\",yy),'</text>')}\n for(i in seq_len(nrow(finite)))s<-paste0(s,'<circle cx=\"',sprintf(\"%.9g\",X(x[i])),'\" cy=\"',sprintf(\"%.9g\",Y(y[i])),'\" r=\"3\" fill=\"',colors[as.integer(finite$series[i])%%3+1],'\"/>');writeLines(paste0(s,'</g></svg>'),file,useBytes=TRUE)\n}\nfixedRun<-function(){\n api<-FIXED$api;a<-FIXED$args;summary<-list();points<-list();xlabel<-\"Declared index\";ylabel<-\"Value\";legend<-\"Declared result\"\n metric<-function(name,v,unit=\"dimensionless\"){if(is.null(v))v<-NA_real_;summary[[length(summary)+1L]]<<-data.frame(metric=name,value=if(is.na(v))\"undefined\"else sprintf(\"%.9g\",v),exactValue=\"\",unit=unit,defined=as.integer(!is.na(v)),stringsAsFactors=FALSE)}\n pt<-function(i,x,y,id=\"\",series=0){points[[length(points)+1L]]<<-data.frame(series=series,index=i,xExact=\"\",x=if(is.na(x))\"undefined\"else sprintf(\"%.9g\",x),yExact=\"\",y=if(is.na(y))\"undefined\"else sprintf(\"%.9g\",y),id=as.character(id),stringsAsFactors=FALSE)}\n if(api==\"realdata\"){\n  native<-loadData()[[a$kind]];fit<-fitmodel(native);d<-list(id=native$id,p=fit$pred,y=native$y,w=rep(1,length(native$id)),role=native$role,group=native$group,eligible=native$eligible);scenarios<-list()\n  for(j in 1:3){name<-c(\"equal\",\"miss-five\",\"alarm-five\")[j];cst<-list(c(1,1),c(1,5),c(5,1))[[j]];sel<-chooseG(d,list(),cst);scenarios[[j]]<-list(name=name,selection=sel);metric(paste0(name,\"Threshold\"),sel$selectedPolicy);metric(paste0(name,\"TestCost\"),sel$evaluation$meanCost,\"hypothetical cost units/mass\")}\n  ids<-scopeG(d,\"test\");cv<-curvesG(d,ids);cal<-calibrateG(d,ids,seq(0,1,.2));metric(\"testAUC\",cv$ROC_AUC);metric(\"testAP\",cv$averagePrecision);metric(\"testBrier\",cal$Brier);metric(\"eligibleRows\",sum(d$eligible),\"rows\")\n  for(j in seq_along(ids)){i<-ids[j];pt(j-1,j,d$p[i],d$id[i],0);pt(j-1,j,d$y[i],d$id[i],1)}\n  full<-list(kind=a$kind,fit=fit,scenarios=scenarios,testCurves=cv,testCalibration=cal,rowsScored=d);xlabel<-\"Test row, native order\";ylabel<-\"Y or probability\";legend<-c(\"Training-fitted probability\",\"Observed Y\")\n }else{\n  d<-rowsG(a$rows);role<-if(is.null(a$role))\"all\"else a$role;ids<-scopeG(d,role);cost<-if(is.null(a$costs))c(1,1)else c(qnum(a$costs$falsePositive),qnum(a$costs$falseNegative));t<-if(is.null(a$threshold)).5 else if(a$threshold%in%c(\"always-positive\",\"always-negative\"))a$threshold else qnum(a$threshold)\n  if(api==\"metrics\"){\n   full<-metricsG(d,ids,t,cost);for(k in c(\"mass\",\"accuracy\",\"precision\",\"TPR\",\"FPR\",\"F1\",\"Brier\",\"meanCost\"))metric(k,full[[k]],if(k==\"mass\")\"mass\"else if(k==\"meanCost\")\"hypothetical cost units/mass\"else\"dimensionless\");metric(\"BayesThreshold\",full$bayesThreshold)\n   for(i in 1:4)pt(i-1,i-1,full$confusion[[i]],names(full$confusion)[i]);xlabel<-\"TP / FP / FN / TN positions\";ylabel<-\"Analytical mass\"\n  }else if(api==\"curves\"){\n   full<-curvesG(d,ids);for(k in c(\"ROC_AUC\",\"averagePrecision\",\"PRTrapezoidWithInitialPrecisionOne\"))metric(k,full[[k]])\n   for(j in seq_along(full$points)){p<-full$points[[j]];pt(j-1,p$FPR,p$TPR,if(is.character(p$policy))p$policy else sprintf(\"%.17g\",p$policy))};xlabel<-\"False positive rate\";ylabel<-\"True positive rate\";legend<-\"Observed ROC operating points\"\n  }else if(api==\"choose\"){\n   full<-chooseG(d,a,cost);metric(\"selectedIndex\",full$selectedIndex,\"candidate index\");metric(\"minimumCost\",if(is.null(full$selectedValidation))NULL else full$selectedValidation$meanCost,\"hypothetical cost units/mass\");metric(\"feasible\",as.integer(!is.na(full$selectedIndex)),\"indicator\")\n   for(c in full$candidates)pt(c$index,c$index,c$metrics$meanCost,if(is.character(c$policy))c$policy else sprintf(\"%.17g\",c$policy));xlabel<-\"Validation candidate\";ylabel<-\"Assumed cost / mass\";legend<-\"Validation candidate costs\"\n  }else if(api==\"calibrate\"){\n   edges<-if(is.null(a$binEdges))seq(0,1,.2)else vapply(a$binEdges,qnum,numeric(1));full<-calibrateG(d,ids,edges);for(k in c(\"ECE\",\"Brier\",\"uncertainty\",\"resolution\",\"reliability\",\"withinBinCorrection\",\"BrierIdentityResidual\"))metric(k,full[[k]])\n   for(b in full$bins)pt(b$index,b$meanPrediction,b$eventRate,paste0(\"bin:\",b$index));xlabel<-\"Bin mean forecast\";ylabel<-\"Bin event rate\";legend<-\"Binary-event reliability\"\n  }else if(api==\"groups\"){\n   full<-groupsG(d,ids,t,cost);metric(\"overallTPR\",full$overall$TPR);metric(\"TPRGap\",full$gaps$TPR);metric(\"precisionGap\",full$gaps$precision);metric(\"unknownMass\",full$unknownGroup$mass,\"mass\");metric(\"partitionResidual\",full$partitionMassResidual,\"mass\")\n   for(j in seq_along(full$groups))pt(j-1,j-1,full$groups[[j]]$metrics$TPR,full$groups[[j]]$group);xlabel<-\"Declared group position\";ylabel<-\"True positive rate\";legend<-\"Known-group TPR\"\n  }else stop(\"unknown declared fixed API\")\n }\n sm<-do.call(rbind,summary);pp<-do.call(rbind,points);write.csv(sm,file.path(outDir,\"summary.csv\"),row.names=FALSE,na=\"\");write.csv(pp,file.path(outDir,\"plot-points.csv\"),row.names=FALSE,na=\"\");svgFixed(file.path(outDir,\"plot.svg\"),pp,FIXED$title,xlabel,ylabel,legend);dput(list(api=api,variant=FIXED$variant,input=FIXED$args,arithmetic=\"Base-R binary64 fixed example; not an exact rational general validator\",result=full),file=file.path(outDir,\"full.txt\"));cat(\"PASS\",api,FIXED$variant,\"summary\",nrow(sm),\"points\",nrow(pp),\"\\n\")\n}\n\nFIXED<-list(api=\"realdata\",variant=\"country\",args=list(kind=\"country\"),title=\"Actual country fixed train/validation/test procedure\")\nfixedRun()\n",
        "codeText": "# ML14 standalone public counterpart, base R only.\n# Inputs are only the three factual CSVs; derived columns/previous model answers unused.\n# Binary64 arithmetic, not arbitrary-precision Fraction. At numerical cost ties\n# within 1e-12 retain the earliest candidate. Exact claims belong to Python/web.\n# SHA256 infrastructure below is reused verbatim from the previous public study.\nargs<-commandArgs(trailingOnly=TRUE);filearg<-grep(\"^--file=\",commandArgs(),value=TRUE)\nhere<-if(dir.exists(\"ml14-sources\"))getwd()else if(length(filearg))dirname(normalizePath(sub(\"^--file=\",\"\",filearg[1])))else getwd()\noption<-function(key,default){i<-match(key,args);if(is.na(i))default else args[i+1]}\nsourceDir<-option(\"--source\",file.path(here,\"ml14-sources\"));outDir<-option(\"--out\",file.path(getwd(),\"ml14-r-results\"));dir.create(outDir,recursive=TRUE,showWarnings=FALSE)\nnum<-function(x){x[x%in%c(\"\",\".\")]<-NA_character_;as.numeric(x)}\nfmt<-function(x)ifelse(is.na(x),\"\",sprintf(\"%.17g\",x))\nratio<-function(a,b)if(b==0)NA_real_ else a/b\nreadnative<-function(name)read.csv(file.path(sourceDir,name),check.names=FALSE,colClasses=\"character\",na.strings=character(),stringsAsFactors=FALSE)\n# Vectorized SHA256 for the short ASCII keys used in this study.\n# Unsigned words use exact integer-valued doubles; bit operations use safe\n# 16-bit halves, avoiding R's reserved signed-INT_MIN/NA representation.\nMOD<-2^32\nxor32<-function(a,b) as.double(bitwXor(as.integer(floor(a/65536)),as.integer(floor(b/65536))))*65536+as.double(bitwXor(as.integer(a%%65536),as.integer(b%%65536)))\nand32<-function(a,b) as.double(bitwAnd(as.integer(floor(a/65536)),as.integer(floor(b/65536))))*65536+as.double(bitwAnd(as.integer(a%%65536),as.integer(b%%65536)))\nrot<-function(x,n) floor(x/2^n)+(x%%2^n)*2^(32-n)\nxor3<-function(a,b,c) xor32(xor32(a,b),c)\nK<-c(0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5,0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967,0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070,0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3,0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2)\nsha256<-function(strings) {\n n<-length(strings);bytes<-matrix(0,n,64)\n for(i in seq_len(n)) {v<-utf8ToInt(strings[i]);stopifnot(length(v)<56,all(v<128));if(length(v)) bytes[i,seq_along(v)]<-v;bytes[i,length(v)+1]<-128;bits<-length(v)*8;bytes[i,61:64]<-c(floor(bits/2^24)%%256,floor(bits/2^16)%%256,floor(bits/256)%%256,bits%%256)}\n w<-matrix(0,n,64)\n for(j in 1:16) {b<-4*(j-1)+1;w[,j]<-bytes[,b]*2^24+bytes[,b+1]*2^16+bytes[,b+2]*256+bytes[,b+3]}\n for(j in 17:64) {s0<-xor3(rot(w[,j-15],7),rot(w[,j-15],18),floor(w[,j-15]/8));s1<-xor3(rot(w[,j-2],17),rot(w[,j-2],19),floor(w[,j-2]/1024));w[,j]<-(w[,j-16]+s0+w[,j-7]+s1)%%MOD}\n init<-c(0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19)\n state<-lapply(init,function(v) rep(v,n));a<-state[[1]];b<-state[[2]];c<-state[[3]];d<-state[[4]];e<-state[[5]];f<-state[[6]];g<-state[[7]];h<-state[[8]]\n for(j in 1:64) {S1<-xor3(rot(e,6),rot(e,11),rot(e,25));ch<-xor32(and32(e,f),and32(MOD-1-e,g));t1<-(h+S1+ch+K[j]+w[,j])%%MOD;S0<-xor3(rot(a,2),rot(a,13),rot(a,22));maj<-xor3(and32(a,b),and32(a,c),and32(b,c));t2<-(S0+maj)%%MOD;h<-g;g<-f;f<-e;e<-(d+t1)%%MOD;d<-c;c<-b;b<-a;a<-(t1+t2)%%MOD}\n end<-list(a,b,c,d,e,f,g,h);hex<-lapply(1:8,function(j){v<-(end[[j]]+init[j])%%MOD;paste0(sprintf(\"%04x\",as.integer(floor(v/65536))),sprintf(\"%04x\",as.integer(v%%65536)))})\n do.call(paste0,hex)\n}\nstopifnot(identical(sha256(c(\"abc\",\"\")),c(\"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad\",\"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855\")))\n\nloadData<-function(){\n wb<-readnative(\"actual64-country-four-indicators-original-2024.csv\");codes<-c(\"NY.GDP.PCAP.KD\",\"NY.GDP.MKTP.KD.ZG\",\"FP.CPI.TOTL.ZG\",\"SP.DYN.LE00.IN\");iso<-sort(unique(wb$countryISO3));stopifnot(nrow(wb)==64,length(iso)==16)\n tokens<-t(vapply(iso,function(s)wb$originalValueToken[match(paste(s,codes),paste(wb$countryISO3,wb$indicatorID))],character(4)));vals<-matrix(num(as.vector(tokens)),nrow=nrow(tokens))\n country<-list(id=paste0(iso,\":2024\"),sourceRow=1:16,originalID=iso,x=vals[,1:3,drop=FALSE],rawX=tokens[,1:3,drop=FALSE],nativeTarget=tokens[,4],y=as.integer(vals[,4]>=80),group=ifelse(is.na(vals[,1]),NA_character_,as.character(as.integer(vals[,1]>=25000))),lineage=vapply(iso,function(s)paste(wb$sourceRow[match(paste(s,codes),paste(wb$countryISO3,wb$indicatorID))],collapse=\";\"),character(1)),cat=integer(),units=c(\"constant2015USD/person\",\"annualPercent\",\"annualPercent\"))\n nls<-readnative(\"actual3613-NLS-original52-fields-groups-roles.csv\");raw<-cbind(nls$ed76,nls$age76,nls$nearc4)\n person<-list(id=paste0(\"person:\",nls$sourceRow),sourceRow=as.integer(nls$sourceRow),originalID=nls$id,x=matrix(num(as.vector(raw)),nrow=nrow(raw)),rawX=raw,nativeTarget=nls$wage76,y=as.integer(num(nls$wage76)>=500),group=ifelse(nls$black%in%c(\"\",\".\"),NA_character_,nls$black),lineage=nls$sourceRow,cat=2L,units=c(\"years\",\"years\",\"nativeCategory\"))\n ch<-readnative(\"actual3150-churn-original14-fields-groups-roles.csv\");raw<-cbind(ch[[\"Call  Failure\"]],ch$Complains,ch[[\"Subscription  Length\"]],ch[[\"Seconds of Use\"]])\n company<-list(id=paste0(\"customer:\",ch$sourceRow),sourceRow=as.integer(ch$sourceRow),originalID=rep(\"\",nrow(ch)),x=matrix(num(as.vector(raw)),nrow=nrow(raw)),rawX=raw,nativeTarget=ch$Churn,y=as.integer(ch$Churn),group=ifelse(ch[[\"Tariff Plan\"]]%in%c(\"\",\".\"),NA_character_,ch[[\"Tariff Plan\"]]),lineage=ch$sourceRow,cat=1L,units=c(\"count\",\"nativeCategory\",\"months\",\"seconds\"))\n stopifnot(nrow(nls)==3613,nrow(ch)==3150,identical(as.integer(ch$sourceRow[ch[[\"Charge  Amount\"]]==\"10\"]),c(474L,2174L,2274L,2374L,2674L,2924L,2974L)))\n result<-list(country=country,person=person,company=company)\n for(k in names(result)){d<-result[[k]];n<-length(d$id);d$eligible<-!is.na(d$y)&rowSums(is.na(d$x))==0;hash<-sha256(paste0(\"ML14-role|\",k,\"|\",d$id));rank<-integer(n);rank[order(hash,seq_len(n))]<-seq_len(n)-1L;d$plannedRole<-ifelse(rank%%5==0,\"test\",ifelse(rank%%5==1,\"validation\",\"train\"));d$role<-ifelse(d$eligible,d$plannedRole,\"excluded\");result[[k]]<-d}\n stopifnot(sum(result$person$eligible)==3017);result\n}\nfitmodel<-function(d){\n ids<-which(d$role==\"train\");p<-ncol(d$x);m<-vapply(seq_len(p),function(j)if((j-1)%in%d$cat)NA_real_ else median(d$x[ids,j]),numeric(1));z<-d$x\n for(j in seq_len(p))if(!((j-1)%in%d$cat))z[,j]<-as.numeric(z[,j]>m[j])\n keys<-apply(z,1,function(v)paste(fmt(v),collapse=\"|\"));lev<-unique(keys[ids]);mass<-vapply(lev,function(k)sum(keys[ids]==k),integer(1));positive<-vapply(lev,function(k)sum(d$y[ids][keys[ids]==k]),integer(1));prob<-(positive+1)/(mass+2);fallback<-(sum(d$y[ids])+1)/(length(ids)+2);pred<-prob[match(keys,lev)];unseen<-is.na(pred);pred[unseen]<-fallback;pred[!d$eligible]<-NA_real_;unseen[!d$eligible]<-NA\n list(ids=ids,medians=m,z=z,keys=keys,lev=lev,mass=mass,positive=positive,prob=prob,fallback=fallback,pred=pred,unseen=unseen)\n}\nmeasure<-function(d,p,ids,t=.5,cost=c(1,1)){\n use<-ids[d$eligible[ids]&!is.na(p[ids])];y<-d$y[use];a<-if(is.character(t))rep(t==\"always-positive\",length(use))else p[use]>=t\n TP<-sum(a&y==1);FP<-sum(a&y==0);FN<-sum(!a&y==1);TN<-sum(!a&y==0);P<-TP+FN;N<-FP+TN;W<-P+N;PP<-TP+FP;PN<-TN+FN;TPR<-ratio(TP,P);TNR<-ratio(TN,N);bs<-sum((p[use]-y)^2);tc<-FP*cost[1]+FN*cost[2]\n list(TP=TP,FP=FP,FN=FN,TN=TN,mass=W,positiveTargetMass=P,negativeTargetMass=N,predictedPositiveMass=PP,predictedNegativeMass=PN,prevalence=ratio(P,W),selectionRate=ratio(PP,W),accuracy=ratio(TP+TN,W),precision=ratio(TP,PP),negativePredictiveValue=ratio(TN,PN),TPR=TPR,FPR=ratio(FP,N),TNR=TNR,FNR=ratio(FN,P),F1=ratio(2*TP,2*TP+FP+FN),balancedAccuracy=if(is.na(TPR)||is.na(TNR))NA_real_ else(TPR+TNR)/2,Brier=ratio(bs,W),BrierSum=bs,totalCost=tc,meanCost=ratio(tc,W))\n}\ncurves<-function(d,p,ids){\n use<-ids[d$eligible[ids]&!is.na(p[ids])];scores<-sort(unique(p[use]),decreasing=TRUE);policies<-c(list(\"always-negative\"),as.list(scores));points<-lapply(policies,function(t){m<-measure(d,p,ids,t);c(list(policy=t),m[c(\"TP\",\"FP\",\"FN\",\"TN\",\"TPR\",\"FPR\",\"precision\")],list(recall=m$TPR))})\n pos<-use[d$y[use]==1];neg<-use[d$y[use]==0];U<-0;for(i in pos)U<-U+sum(p[i]>p[neg])+.5*sum(p[i]==p[neg])\n AP<-0;trap<-0;lastR<-0;lastP<-1\n if(length(pos)&&length(scores))for(j in seq_along(scores)){z<-points[[j+1]];AP<-AP+(z$recall-lastR)*z$precision;trap<-trap+(z$recall-lastR)*(z$precision+lastP)/2;lastR<-z$recall;lastP<-z$precision}\n list(points=points,ROC_AUC=ratio(U,length(pos)*length(neg)),averagePrecision=if(length(pos))AP else NA_real_,PRTrapezoidWithInitialPrecisionOne=if(length(pos))trap else NA_real_)\n}\ncalibrate<-function(d,p,ids){\n use<-ids[d$eligible[ids]&!is.na(p[ids])];W<-length(use);pi<-if(W)mean(d$y[use])else NA_real_;bins<-list();ECE<-rel<-res<-correction<-0\n whichbin<-findInterval(p[use],seq(0,1,.2),rightmost.closed=TRUE,all.inside=TRUE)\n for(b in 1:5){rr<-use[whichbin==b];w<-length(rr);mp<-if(w)mean(p[rr])else NA_real_;o<-if(w)mean(d$y[rr])else NA_real_;variance<-if(w)mean((p[rr]-mp)^2)else NA_real_;covariance<-if(w)mean((p[rr]-mp)*(d$y[rr]-o))else NA_real_;bc<-variance-2*covariance;gap<-mp-o\n  bins[[b]]<-list(mass=w,meanPrediction=mp,eventRate=o,gap=gap,absoluteGap=abs(gap),scoreVariance=variance,scoreTargetCovariance=covariance,withinBinCorrection=bc,rows=w,ids=d$id[rr])\n  if(w){share<-w/W;ECE<-ECE+share*abs(gap);rel<-rel+share*gap^2;res<-res+share*(o-pi)^2;correction<-correction+share*bc}\n };bs<-if(W)mean((p[use]-d$y[use])^2)else NA_real_;unc<-pi*(1-pi)\n list(bins=bins,ECE=if(W)ECE else NA_real_,Brier=bs,reliability=if(W)rel else NA_real_,resolution=if(W)res else NA_real_,uncertainty=unc,withinBinCorrection=if(W)correction else NA_real_,BrierIdentityResidual=bs-(unc-res+rel+correction))\n}\ncounts<-c(\"mass\",\"positiveTargetMass\",\"negativeTargetMass\",\"predictedPositiveMass\",\"predictedNegativeMass\");rates<-c(\"prevalence\",\"selectionRate\",\"accuracy\",\"precision\",\"negativePredictiveValue\",\"TPR\",\"FPR\",\"TNR\",\"FNR\",\"F1\",\"balancedAccuracy\",\"Brier\",\"BrierSum\",\"totalCost\",\"meanCost\")\ntables<-setNames(lapply(1:10,function(i)list()),c(\"predictions\",\"lineage\",\"fit-medians\",\"fit-cells\",\"validation-candidates\",\"test-metrics\",\"test-curves\",\"calibration-bins\",\"group-metrics\",\"chart-points\"))\nadd<-function(name,row)tables[[name]][[length(tables[[name]])+1L]]<<-row\nscalars<-function(m,keys){out<-list();for(k in keys){out[[paste0(k,\"Exact\")]]<-\"\";out[[paste0(k,\"Approx\")]]<-fmt(m[[k]])};out}\ntagrow<-function(kind,...)c(list(kind=kind),list(...))\npoint<-function(kind,chart,series,index,x,y,xunit=\"dimensionless\",yunit=\"dimensionless\",role=\"test\",tag=\"\"){add(\"chart-points\",tagrow(kind,chart=chart,series=series,index=index,xExact=\"\",xApprox=fmt(x),yExact=\"\",yApprox=fmt(y),xUnit=xunit,yUnit=yunit,role=role,tag=tag))}\nstudy<-function(kind,d){\n f<-fitmodel(d);n<-length(d$id);train<-which(d$role==\"train\");validation<-which(d$role==\"validation\");test<-which(d$role==\"test\");p<-f$pred;cv<-curves(d,p,test);cal<-calibrate(d,p,test)\n for(i in seq_len(n)){\n  reason<-if(d$eligible[i])\"\"else\"required-X-or-Y-missing\";transformed<-if(d$eligible[i])paste(fmt(f$z[i,]),collapse=\"|\")else\"\"\n  add(\"predictions\",tagrow(kind,id=d$id[i],sourceRow=d$sourceRow[i],originalID=d$originalID[i],plannedRole=d$plannedRole[i],role=d$role[i],group=ifelse(is.na(d$group[i]),\"\",d$group[i]),eligible=as.integer(d$eligible[i]),targetExact=fmt(d$y[i]),probabilityExact=\"\",probabilityApprox=fmt(p[i]),unseenCell=ifelse(is.na(f$unseen[i]),\"\",as.character(as.integer(f$unseen[i]))),transformedX=transformed,reason=reason))\n  raw<-d$rawX[i,];raw[raw%in%c(\"\",\".\")]<-\"\";nativeY<-d$nativeTarget[i];if(nativeY%in%c(\"\",\".\"))nativeY<-\"\"\n  add(\"lineage\",tagrow(kind,id=d$id[i],sourceRow=d$sourceRow[i],originalID=d$originalID[i],nativeSourceRows=d$lineage[i],rawX=paste(raw,collapse=\"|\"),nativeTarget=nativeY,derivedTarget=fmt(d$y[i]),nativeGroup=ifelse(is.na(d$group[i]),\"\",d$group[i]),plannedRole=d$plannedRole[i],role=d$role[i],eligible=as.integer(d$eligible[i]),analyticalMass=\"1\",reason=reason))\n }\n for(j in seq_len(ncol(d$x)))add(\"fit-medians\",tagrow(kind,feature=j-1,categorical=as.integer((j-1)%in%d$cat),fitRows=length(train),medianExact=\"\",medianApprox=fmt(f$medians[j]),unit=d$units[j]))\n for(j in seq_along(f$lev))add(\"fit-cells\",tagrow(kind,cell=f$lev[j],trainingRows=f$mass[j],positiveRows=f$positive[j],probabilityExact=\"\",probabilityApprox=fmt(f$prob[j]),fallbackExact=\"\",fallbackApprox=fmt(f$fallback)))\n for(j in seq_along(cv$points)){\n  z<-cv$points[[j]];t<-z$policy;add(\"test-curves\",c(tagrow(kind,point=j-1,policy=if(is.character(t))t else\"threshold\",thresholdExact=\"\",thresholdApprox=if(is.character(t))\"\"else fmt(t)),scalars(z,c(\"TP\",\"FP\",\"FN\",\"TN\",\"TPR\",\"FPR\",\"precision\",\"recall\"))))\n  point(kind,\"roc\",\"ROC\",j-1,z$FPR,z$TPR);point(kind,\"pr\",\"PR-observed\",j-1,z$recall,z$precision)\n }\n for(b in 1:5){z<-cal$bins[[b]];add(\"calibration-bins\",c(tagrow(kind,bin=b-1,leftExact=c(\"0\",\"1/5\",\"2/5\",\"3/5\",\"4/5\")[b],rightExact=c(\"1/5\",\"2/5\",\"3/5\",\"4/5\",\"1\")[b],rightClosed=as.integer(b==5),rows=z$rows,ids=paste(z$ids,collapse=\";\")),scalars(z,c(\"mass\",\"meanPrediction\",\"eventRate\",\"gap\",\"absoluteGap\",\"scoreVariance\",\"scoreTargetCovariance\",\"withinBinCorrection\"))));point(kind,\"reliability\",\"Binary event rate\",b-1,z$meanPrediction,z$eventRate,tag=paste0(\"rows=\",z$rows))}\n for(j in seq_along(test)){i<-test[j];point(kind,\"test-scores\",\"Training-fitted probability\",j-1,j,p[i],\"test-row position\",\"probability\",tag=d$id[i]);point(kind,\"test-scores\",\"Observed Y\",j-1,j,d$y[i],\"test-row position\",\"binary target\",tag=d$id[i])}\n scenarioNames<-c(\"equal\",\"miss-five\",\"alarm-five\");costs<-list(c(1,1),c(1,5),c(5,1))\n for(s in 1:3){name<-scenarioNames[s];cost<-costs[[s]];grid<-c(list(\"always-negative\"),as.list(sort(unique(p[validation]),decreasing=TRUE)));candidates<-lapply(grid,function(t)measure(d,p,validation,t,cost));values<-vapply(candidates,function(m)m$meanCost,numeric(1));best<-which(values<=min(values)+1e-12)[1];chosen<-grid[[best]];ev<-measure(d,p,test,chosen,cost)\n  for(j in seq_along(grid)){t<-grid[[j]];m<-candidates[[j]];cell<-setNames(lapply(c(\"TP\",\"FP\",\"FN\",\"TN\"),function(k)fmt(m[[k]])),paste0(c(\"TP\",\"FP\",\"FN\",\"TN\"),\"Exact\"));add(\"validation-candidates\",c(tagrow(kind,scenario=name,candidate=j-1,selected=as.integer(j==best),policy=if(is.character(t))t else\"threshold\",thresholdExact=\"\",thresholdApprox=if(is.character(t))\"\"else fmt(t),feasible=1,reasons=\"\"),cell,scalars(m,c(counts,\"TPR\",\"FPR\",\"precision\",\"meanCost\",\"totalCost\"))));point(kind,\"validation-cost\",name,j-1,j-1,m$meanCost,\"candidate index\",\"hypothetical cost units/mass\",\"validation\",if(is.character(t))t else fmt(t))}\n  m<-c(ev,cv[c(\"ROC_AUC\",\"averagePrecision\",\"PRTrapezoidWithInitialPrecisionOne\")],cal[c(\"ECE\",\"reliability\",\"resolution\",\"uncertainty\",\"withinBinCorrection\",\"BrierIdentityResidual\")])\n  for(k in c(\"TP\",\"FP\",\"FN\",\"TN\",counts,rates,\"ROC_AUC\",\"averagePrecision\",\"PRTrapezoidWithInitialPrecisionOne\",\"ECE\",\"reliability\",\"resolution\",\"uncertainty\",\"withinBinCorrection\",\"BrierIdentityResidual\")){\n   unit<-if(k%in%c(\"TP\",\"FP\",\"FN\",\"TN\",counts))\"rows\"else if(k==\"totalCost\")\"hypothetical cost units\"else if(k==\"meanCost\")\"hypothetical cost units/mass\"else if(k==\"BrierSum\")\"sum squared-probability loss\"else\"dimensionless\"\n   add(\"test-metrics\",tagrow(kind,scenario=name,metric=k,valueExact=\"\",valueApprox=fmt(m[[k]]),unit=unit))\n  }\n  lev<-unique(d$group[test][!is.na(d$group[test])]);sets<-c(list(test),lapply(lev,function(g)test[!is.na(d$group[test])&d$group[test]==g]),list(test[is.na(d$group[test])]))\n  types<-c(\"overall\",rep(\"known\",length(lev)),\"unknown\");tokens<-c(\"all\",lev,\"\")\n  for(j in seq_along(sets)){ids<-sets[[j]];m<-measure(d,p,ids,chosen,cost);cell<-setNames(lapply(c(\"TP\",\"FP\",\"FN\",\"TN\"),function(k)fmt(m[[k]])),paste0(c(\"TP\",\"FP\",\"FN\",\"TN\"),\"Exact\"));add(\"group-metrics\",c(tagrow(kind,scenario=name,groupType=types[j],groupToken=tokens[j],retainedRows=length(ids)),cell,scalars(m,c(counts,rates))));if(types[j]==\"known\")point(kind,\"group-TPR\",name,j-2,j-2,m$TPR,\"declared group position\",\"TPR\",tag=tokens[j])}\n }\n invisible(NULL)\n}\n\n# Fixed finite inputs only; not the complete web input/budget validator.\nqnum<-function(v){if(is.null(v))return(NA_real_);if(is.logical(v))return(as.numeric(v));s<-as.character(v);if(grepl(\"/\",s,fixed=TRUE)){a<-strsplit(s,\"/\",fixed=TRUE)[[1]];return(as.numeric(a[1])/as.numeric(a[2]))};as.numeric(s)}\nrowsG<-function(raw){\n n<-length(raw);get<-function(r,k,default=NULL)if(is.null(r[[k]]))default else r[[k]]\n id<-vapply(raw,function(r)as.character(r$id),character(1));p<-vapply(raw,function(r)qnum(r$score),numeric(1));y<-vapply(raw,function(r)qnum(r$y),numeric(1));w<-vapply(raw,function(r)qnum(get(r,\"weight\",\"1\")),numeric(1));role<-vapply(raw,function(r)get(r,\"role\",\"evaluation\"),character(1));group<-vapply(raw,function(r)as.character(get(r,\"group\",NA_character_)),character(1))\n stopifnot(all(w>=0),all(is.na(p)|(p>=0&p<=1)),all(is.na(y)|y%in%c(0,1)),!anyDuplicated(id));list(id=id,p=p,y=y,w=w,role=role,group=group,eligible=!is.na(p)&!is.na(y)&w>0&role!=\"excluded\")\n}\nscopeG<-function(d,role=\"all\")if(role==\"all\")seq_along(d$id)else which(d$role==role)\nmetricsG<-function(d,ids,t=.5,cost=c(1,1)){\n use<-ids[d$eligible[ids]];p<-d$p[use];y<-d$y[use];w<-d$w[use];a<-if(is.character(t))rep(t==\"always-positive\",length(use))else p>=t\n TP<-sum(w[a&y==1]);FP<-sum(w[a&y==0]);FN<-sum(w[!a&y==1]);TN<-sum(w[!a&y==0]);P<-TP+FN;N<-FP+TN;W<-P+N;PP<-TP+FP;PN<-TN+FN;TPR<-ratio(TP,P);TNR<-ratio(TN,N);bs<-sum(w*(p-y)^2);tc<-FP*cost[1]+FN*cost[2]\n list(confusion=list(TP=TP,FP=FP,FN=FN,TN=TN),mass=W,positiveTargetMass=P,negativeTargetMass=N,predictedPositiveMass=PP,predictedNegativeMass=PN,prevalence=ratio(P,W),selectionRate=ratio(PP,W),accuracy=ratio(TP+TN,W),precision=ratio(TP,PP),negativePredictiveValue=ratio(TN,PN),TPR=TPR,FPR=ratio(FP,N),TNR=TNR,FNR=ratio(FN,P),F1=ratio(2*TP,2*TP+FP+FN),balancedAccuracy=if(is.na(TPR)||is.na(TNR))NA_real_ else(TPR+TNR)/2,Brier=ratio(bs,W),BrierSum=bs,totalCost=tc,meanCost=ratio(tc,W),bayesThreshold=ratio(cost[1],sum(cost)))\n}\ncurvesG<-function(d,ids){\n use<-ids[d$eligible[ids]];grid<-c(list(\"always-negative\"),as.list(sort(unique(d$p[use]),decreasing=TRUE)));points<-lapply(grid,function(t){m<-metricsG(d,ids,t);c(list(policy=t),m$confusion,m[c(\"TPR\",\"FPR\",\"precision\")],list(recall=m$TPR))});pos<-use[d$y[use]==1];neg<-use[d$y[use]==0];P<-sum(d$w[pos]);N<-sum(d$w[neg]);U<-0\n for(i in pos)U<-U+d$w[i]*sum(d$w[neg]*((d$p[i]>d$p[neg])+.5*(d$p[i]==d$p[neg])))\n AP<-trap<-lastR<-0;lastP<-1\n if(P&&length(grid)>1)for(j in 2:length(grid)){z<-points[[j]];AP<-AP+(z$recall-lastR)*z$precision;trap<-trap+(z$recall-lastR)*(z$precision+lastP)/2;lastR<-z$recall;lastP<-z$precision}\n list(points=points,ROC_AUC=ratio(U,P*N),averagePrecision=if(P)AP else NA_real_,PRTrapezoidWithInitialPrecisionOne=if(P)trap else NA_real_)\n}\nchooseG<-function(d,a,cost){\n role<-if(is.null(a$selectionRole))\"validation\"else a$selectionRole;er<-if(is.null(a$evaluationRole))\"test\"else a$evaluationRole;ids<-scopeG(d,role);use<-ids[d$eligible[ids]];stopifnot(length(use)>0);grid<-if(is.null(a$thresholds))c(list(\"always-negative\"),as.list(sort(unique(d$p[use]),decreasing=TRUE)))else lapply(a$thresholds,function(t)if(t%in%c(\"always-negative\",\"always-positive\"))t else qnum(t))\n candidates<-lapply(seq_along(grid),function(j){m<-metricsG(d,ids,grid[[j]],cost);feasible<-TRUE;if(!is.null(a$minTPR))feasible<-feasible&&!is.na(m$TPR)&&m$TPR>=qnum(a$minTPR);if(!is.null(a$maxFPR))feasible<-feasible&&!is.na(m$FPR)&&m$FPR<=qnum(a$maxFPR);list(index=j-1,policy=grid[[j]],metrics=m,feasible=feasible)})\n good<-which(vapply(candidates,function(c)c$feasible,logical(1)));best<-NA_integer_;if(length(good)){v<-vapply(candidates[good],function(c)c$metrics$meanCost,numeric(1));best<-good[which(v<=min(v)+1e-12)[1]]}\n list(selectedIndex=if(is.na(best))NA_integer_ else best-1,selectedPolicy=if(is.na(best))NULL else grid[[best]],selectedValidation=if(is.na(best))NULL else candidates[[best]]$metrics,candidates=candidates,evaluation=if(is.na(best)||er==\"none\")NULL else metricsG(d,scopeG(d,er),grid[[best]],cost))\n}\ncalibrateG<-function(d,ids,edges){\n use<-ids[d$eligible[ids]];W<-sum(d$w[use]);pi<-ratio(sum(d$w[use]*d$y[use]),W);bins<-list();ECE<-rel<-res<-correction<-0;assign<-findInterval(d$p[use],edges,rightmost.closed=TRUE,all.inside=TRUE)\n for(b in seq_len(length(edges)-1)){rr<-use[assign==b];w<-sum(d$w[rr]);mp<-ratio(sum(d$w[rr]*d$p[rr]),w);o<-ratio(sum(d$w[rr]*d$y[rr]),w);variance<-if(w)sum(d$w[rr]*(d$p[rr]-mp)^2)/w else NA_real_;covariance<-if(w)sum(d$w[rr]*(d$p[rr]-mp)*(d$y[rr]-o))/w else NA_real_;bc<-variance-2*covariance;gap<-mp-o;bins[[b]]<-list(index=b-1,mass=w,meanPrediction=mp,eventRate=o,scoreVariance=variance,scoreTargetCovariance=covariance,withinBinCorrection=bc,ids=d$id[rr])\n  if(w){s<-w/W;ECE<-ECE+s*abs(gap);rel<-rel+s*gap^2;res<-res+s*(o-pi)^2;correction<-correction+s*bc}\n };bs<-ratio(sum(d$w[use]*(d$p[use]-d$y[use])^2),W);unc<-pi*(1-pi);list(bins=bins,Brier=bs,ECE=if(W)ECE else NA_real_,uncertainty=unc,reliability=if(W)rel else NA_real_,resolution=if(W)res else NA_real_,withinBinCorrection=if(W)correction else NA_real_,BrierIdentityResidual=bs-(unc-res+rel+correction))\n}\ngroupsG<-function(d,ids,t,cost){\n lev<-unique(d$group[ids][!is.na(d$group[ids])]);groups<-lapply(lev,function(g)list(group=g,metrics=metricsG(d,ids[!is.na(d$group[ids])&d$group[ids]==g],t,cost)));overall<-metricsG(d,ids,t,cost);unknown<-metricsG(d,ids[is.na(d$group[ids])],t,cost);gaps<-list()\n for(k in c(\"prevalence\",\"selectionRate\",\"TPR\",\"FPR\",\"precision\",\"accuracy\",\"meanCost\")){use<-Filter(function(g)g$metrics$mass>0,groups);v<-vapply(use,function(g)g$metrics[[k]],numeric(1));gaps[[k]]<-if(length(use)<2||anyNA(v))NA_real_ else max(v)-min(v)}\n list(overall=overall,groups=groups,unknownGroup=unknown,gaps=gaps,partitionMassResidual=overall$mass-unknown$mass-sum(vapply(groups,function(g)g$metrics$mass,numeric(1))))\n}\nsvgFixed<-function(file,points,title,xlabel,ylabel,legend){\n finite<-points[points$y!=\"undefined\"&points$x!=\"undefined\",,drop=FALSE];x<-as.numeric(finite$x);y<-as.numeric(finite$y);xmin<-if(length(x))min(x)else 0;xmax<-if(length(x))max(x)else 1;ymin<-min(c(0,y));ymax<-max(c(0,y));if(xmin==xmax){xmin<-xmin-.5;xmax<-xmax+.5};if(ymin==ymax)ymax<-ymin+1;X<-function(v)85+(v-xmin)/(xmax-xmin)*480;Y<-function(v)278-(v-ymin)/(ymax-ymin)*175\n esc<-function(s){s<-gsub(\"&\",\"&amp;\",s,fixed=TRUE);s<-gsub(\"<\",\"&lt;\",s,fixed=TRUE);gsub(\">\",\"&gt;\",s,fixed=TRUE)};s<-'<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"620\" height=\"360\" viewBox=\"0 0 620 360\"><rect width=\"620\" height=\"360\" fill=\"white\"/><g font-family=\"Arial, sans-serif\" font-size=\"13\" fill=\"#17324d\">'\n lines<-strwrap(title,width=65);for(i in seq_along(lines))s<-paste0(s,'<text x=\"25\" y=\"',24+(i-1)*18,'\">',esc(lines[i]),'</text>');colors<-c(\"#176b9b\",\"#b85e18\",\"#437e4d\")\n for(i in seq_along(legend))s<-paste0(s,'<circle cx=\"',30+(i-1)*250,'\" cy=\"76\" r=\"4\" fill=\"',colors[(i-1)%%3+1],'\"/><text x=\"',42+(i-1)*250,'\" y=\"80\">',esc(legend[i]),'</text>')\n s<-paste0(s,'<path d=\"M85 98V278H575\" fill=\"none\" stroke=\"#52677d\"/><text text-anchor=\"middle\" x=\"325\" y=\"338\">',esc(xlabel),'</text><text text-anchor=\"middle\" transform=\"translate(21,190) rotate(-90)\">',esc(ylabel),'</text>')\n for(i in 0:4){xx<-xmin+(xmax-xmin)*i/4;yy<-ymin+(ymax-ymin)*i/4;s<-paste0(s,'<text text-anchor=\"middle\" x=\"',sprintf(\"%.9g\",X(xx)),'\" y=\"305\">',sprintf(\"%.4g\",xx),'</text><text text-anchor=\"end\" x=\"77\" y=\"',sprintf(\"%.9g\",Y(yy)+4),'\">',sprintf(\"%.4g\",yy),'</text>')}\n for(i in seq_len(nrow(finite)))s<-paste0(s,'<circle cx=\"',sprintf(\"%.9g\",X(x[i])),'\" cy=\"',sprintf(\"%.9g\",Y(y[i])),'\" r=\"3\" fill=\"',colors[as.integer(finite$series[i])%%3+1],'\"/>');writeLines(paste0(s,'</g></svg>'),file,useBytes=TRUE)\n}\nfixedRun<-function(){\n api<-FIXED$api;a<-FIXED$args;summary<-list();points<-list();xlabel<-\"Declared index\";ylabel<-\"Value\";legend<-\"Declared result\"\n metric<-function(name,v,unit=\"dimensionless\"){if(is.null(v))v<-NA_real_;summary[[length(summary)+1L]]<<-data.frame(metric=name,value=if(is.na(v))\"undefined\"else sprintf(\"%.9g\",v),exactValue=\"\",unit=unit,defined=as.integer(!is.na(v)),stringsAsFactors=FALSE)}\n pt<-function(i,x,y,id=\"\",series=0){points[[length(points)+1L]]<<-data.frame(series=series,index=i,xExact=\"\",x=if(is.na(x))\"undefined\"else sprintf(\"%.9g\",x),yExact=\"\",y=if(is.na(y))\"undefined\"else sprintf(\"%.9g\",y),id=as.character(id),stringsAsFactors=FALSE)}\n if(api==\"realdata\"){\n  native<-loadData()[[a$kind]];fit<-fitmodel(native);d<-list(id=native$id,p=fit$pred,y=native$y,w=rep(1,length(native$id)),role=native$role,group=native$group,eligible=native$eligible);scenarios<-list()\n  for(j in 1:3){name<-c(\"equal\",\"miss-five\",\"alarm-five\")[j];cst<-list(c(1,1),c(1,5),c(5,1))[[j]];sel<-chooseG(d,list(),cst);scenarios[[j]]<-list(name=name,selection=sel);metric(paste0(name,\"Threshold\"),sel$selectedPolicy);metric(paste0(name,\"TestCost\"),sel$evaluation$meanCost,\"hypothetical cost units/mass\")}\n  ids<-scopeG(d,\"test\");cv<-curvesG(d,ids);cal<-calibrateG(d,ids,seq(0,1,.2));metric(\"testAUC\",cv$ROC_AUC);metric(\"testAP\",cv$averagePrecision);metric(\"testBrier\",cal$Brier);metric(\"eligibleRows\",sum(d$eligible),\"rows\")\n  for(j in seq_along(ids)){i<-ids[j];pt(j-1,j,d$p[i],d$id[i],0);pt(j-1,j,d$y[i],d$id[i],1)}\n  full<-list(kind=a$kind,fit=fit,scenarios=scenarios,testCurves=cv,testCalibration=cal,rowsScored=d);xlabel<-\"Test row, native order\";ylabel<-\"Y or probability\";legend<-c(\"Training-fitted probability\",\"Observed Y\")\n }else{\n  d<-rowsG(a$rows);role<-if(is.null(a$role))\"all\"else a$role;ids<-scopeG(d,role);cost<-if(is.null(a$costs))c(1,1)else c(qnum(a$costs$falsePositive),qnum(a$costs$falseNegative));t<-if(is.null(a$threshold)).5 else if(a$threshold%in%c(\"always-positive\",\"always-negative\"))a$threshold else qnum(a$threshold)\n  if(api==\"metrics\"){\n   full<-metricsG(d,ids,t,cost);for(k in c(\"mass\",\"accuracy\",\"precision\",\"TPR\",\"FPR\",\"F1\",\"Brier\",\"meanCost\"))metric(k,full[[k]],if(k==\"mass\")\"mass\"else if(k==\"meanCost\")\"hypothetical cost units/mass\"else\"dimensionless\");metric(\"BayesThreshold\",full$bayesThreshold)\n   for(i in 1:4)pt(i-1,i-1,full$confusion[[i]],names(full$confusion)[i]);xlabel<-\"TP / FP / FN / TN positions\";ylabel<-\"Analytical mass\"\n  }else if(api==\"curves\"){\n   full<-curvesG(d,ids);for(k in c(\"ROC_AUC\",\"averagePrecision\",\"PRTrapezoidWithInitialPrecisionOne\"))metric(k,full[[k]])\n   for(j in seq_along(full$points)){p<-full$points[[j]];pt(j-1,p$FPR,p$TPR,if(is.character(p$policy))p$policy else sprintf(\"%.17g\",p$policy))};xlabel<-\"False positive rate\";ylabel<-\"True positive rate\";legend<-\"Observed ROC operating points\"\n  }else if(api==\"choose\"){\n   full<-chooseG(d,a,cost);metric(\"selectedIndex\",full$selectedIndex,\"candidate index\");metric(\"minimumCost\",if(is.null(full$selectedValidation))NULL else full$selectedValidation$meanCost,\"hypothetical cost units/mass\");metric(\"feasible\",as.integer(!is.na(full$selectedIndex)),\"indicator\")\n   for(c in full$candidates)pt(c$index,c$index,c$metrics$meanCost,if(is.character(c$policy))c$policy else sprintf(\"%.17g\",c$policy));xlabel<-\"Validation candidate\";ylabel<-\"Assumed cost / mass\";legend<-\"Validation candidate costs\"\n  }else if(api==\"calibrate\"){\n   edges<-if(is.null(a$binEdges))seq(0,1,.2)else vapply(a$binEdges,qnum,numeric(1));full<-calibrateG(d,ids,edges);for(k in c(\"ECE\",\"Brier\",\"uncertainty\",\"resolution\",\"reliability\",\"withinBinCorrection\",\"BrierIdentityResidual\"))metric(k,full[[k]])\n   for(b in full$bins)pt(b$index,b$meanPrediction,b$eventRate,paste0(\"bin:\",b$index));xlabel<-\"Bin mean forecast\";ylabel<-\"Bin event rate\";legend<-\"Binary-event reliability\"\n  }else if(api==\"groups\"){\n   full<-groupsG(d,ids,t,cost);metric(\"overallTPR\",full$overall$TPR);metric(\"TPRGap\",full$gaps$TPR);metric(\"precisionGap\",full$gaps$precision);metric(\"unknownMass\",full$unknownGroup$mass,\"mass\");metric(\"partitionResidual\",full$partitionMassResidual,\"mass\")\n   for(j in seq_along(full$groups))pt(j-1,j-1,full$groups[[j]]$metrics$TPR,full$groups[[j]]$group);xlabel<-\"Declared group position\";ylabel<-\"True positive rate\";legend<-\"Known-group TPR\"\n  }else stop(\"unknown declared fixed API\")\n }\n sm<-do.call(rbind,summary);pp<-do.call(rbind,points);write.csv(sm,file.path(outDir,\"summary.csv\"),row.names=FALSE,na=\"\");write.csv(pp,file.path(outDir,\"plot-points.csv\"),row.names=FALSE,na=\"\");svgFixed(file.path(outDir,\"plot.svg\"),pp,FIXED$title,xlabel,ylabel,legend);dput(list(api=api,variant=FIXED$variant,input=FIXED$args,arithmetic=\"Base-R binary64 fixed example; not an exact rational general validator\",result=full),file=file.path(outDir,\"full.txt\"));cat(\"PASS\",api,FIXED$variant,\"summary\",nrow(sm),\"points\",nrow(pp),\"\\n\")\n}\n\nFIXED<-list(api=\"realdata\",variant=\"country\",args=list(kind=\"country\"),title=\"Actual country fixed train/validation/test procedure\")\nfixedRun()\n",
        "input": {
          "kind": "country"
        },
        "inputFiles": [
          {
            "file": "../ml14-sources/actual64-country-four-indicators-original-2024.csv",
            "sha256": "3d2b655cf807bf3ff049af187a9b7484b4e637f441f6f1925aba7acc5b0c861c"
          },
          {
            "file": "../ml14-sources/actual3613-NLS-original52-fields-groups-roles.csv",
            "sha256": "df404c3ce0336ab3ae2bfdd6b246c6e8acc058fd526ebf950dde270787bcd600"
          },
          {
            "file": "../ml14-sources/actual3150-churn-original14-fields-groups-roles.csv",
            "sha256": "d8af1f4905af8699e3ea024a6998319c82ac97b33ba1dec182391c0b30795023"
          }
        ],
        "returnCode": 0,
        "expectedFailure": false,
        "stdout": "PASS realdata country summary 10 points 8 \n",
        "stderr": "During startup - Warning messages:\n1: Setting LC_COLLATE=C.UTF-8 failed \n2: Setting LC_CTYPE=C.UTF-8 failed \n3: Setting LC_MONETARY=C.UTF-8 failed \n4: Setting LC_TIME=C.UTF-8 failed \n",
        "summary": {
          "equalThreshold": "0.75",
          "equalTestCost": "0.25",
          "miss-fiveThreshold": "0.75",
          "miss-fiveTestCost": "0.25",
          "alarm-fiveThreshold": "0.75",
          "alarm-fiveTestCost": "1.25",
          "testAUC": "0.75",
          "testAP": "0.666666667",
          "testBrier": "0.1875",
          "eligibleRows": "16"
        },
        "summaryRows": [
          {
            "metric": "equalThreshold",
            "value": "0.75",
            "exactValue": "",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "equalTestCost",
            "value": "0.25",
            "exactValue": "",
            "unit": "hypothetical cost units/mass",
            "defined": "1"
          },
          {
            "metric": "miss-fiveThreshold",
            "value": "0.75",
            "exactValue": "",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "miss-fiveTestCost",
            "value": "0.25",
            "exactValue": "",
            "unit": "hypothetical cost units/mass",
            "defined": "1"
          },
          {
            "metric": "alarm-fiveThreshold",
            "value": "0.75",
            "exactValue": "",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "alarm-fiveTestCost",
            "value": "1.25",
            "exactValue": "",
            "unit": "hypothetical cost units/mass",
            "defined": "1"
          },
          {
            "metric": "testAUC",
            "value": "0.75",
            "exactValue": "",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "testAP",
            "value": "0.666666667",
            "exactValue": "",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "testBrier",
            "value": "0.1875",
            "exactValue": "",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "eligibleRows",
            "value": "16",
            "exactValue": "",
            "unit": "rows",
            "defined": "1"
          }
        ],
        "plotPoints": [
          {
            "series": "0",
            "index": "0",
            "xExact": "",
            "x": "1",
            "yExact": "",
            "y": "0.75",
            "id": "CAN:2024"
          },
          {
            "series": "1",
            "index": "0",
            "xExact": "",
            "x": "1",
            "yExact": "",
            "y": "1",
            "id": "CAN:2024"
          },
          {
            "series": "0",
            "index": "1",
            "xExact": "",
            "x": "2",
            "yExact": "",
            "y": "0.75",
            "id": "JPN:2024"
          },
          {
            "series": "1",
            "index": "1",
            "xExact": "",
            "x": "2",
            "yExact": "",
            "y": "1",
            "id": "JPN:2024"
          },
          {
            "series": "0",
            "index": "2",
            "xExact": "",
            "x": "3",
            "yExact": "",
            "y": "0.25",
            "id": "MEX:2024"
          },
          {
            "series": "1",
            "index": "2",
            "xExact": "",
            "x": "3",
            "yExact": "",
            "y": "0",
            "id": "MEX:2024"
          },
          {
            "series": "0",
            "index": "3",
            "xExact": "",
            "x": "4",
            "yExact": "",
            "y": "0.75",
            "id": "USA:2024"
          },
          {
            "series": "1",
            "index": "3",
            "xExact": "",
            "x": "4",
            "yExact": "",
            "y": "0",
            "id": "USA:2024"
          }
        ],
        "plotFile": "ml14-fixed-results/realdata-country-r/plot.svg",
        "plotSHA256": "a6faf49f1bc411dbdd3c795e0854acf61fa605d4f7204319ef97678512a382e6",
        "files": [
          {
            "file": "ml14-fixed-results/realdata-country-r/full.txt",
            "sha256": "c8a40055b53f0b4d9ec42ddfedd082ae975b7373068cdc2cd6c1e7fac8b3a226",
            "bytes": 16455
          },
          {
            "file": "ml14-fixed-results/realdata-country-r/plot-points.csv",
            "sha256": "082427e226118d0761b53a65c72deb500dbf83ff3d14e64d84598ba8958369a0",
            "bytes": 301
          },
          {
            "file": "ml14-fixed-results/realdata-country-r/plot.svg",
            "sha256": "a6faf49f1bc411dbdd3c795e0854acf61fa605d4f7204319ef97678512a382e6",
            "bytes": 1599
          },
          {
            "file": "ml14-fixed-results/realdata-country-r/summary.csv",
            "sha256": "665ac519b1c4d562877d697ed588da8e25fe03d84b0867510115f27eba42dd5e",
            "bytes": 544
          }
        ],
        "scope": "Actually executed standalone fixed example, Python exact Fraction versus base-R binary64. Approximate R residuals retained; not universal exact arithmetic/web validation/native UI. Source programs read factual3CSV only."
      },
      "person": {
        "api": "realdata",
        "variant": "person",
        "language": "r",
        "title": "Actual person fixed train/validation/test procedure",
        "codeFile": "ml14-code/realdata-person.R",
        "codeSHA256": "daecff4a51b1815a8d3c8be39f613129b011df69d376726ac528275a9dfbe480",
        "code": "# ML14 standalone public counterpart, base R only.\n# Inputs are only the three factual CSVs; derived columns/previous model answers unused.\n# Binary64 arithmetic, not arbitrary-precision Fraction. At numerical cost ties\n# within 1e-12 retain the earliest candidate. Exact claims belong to Python/web.\n# SHA256 infrastructure below is reused verbatim from the previous public study.\nargs<-commandArgs(trailingOnly=TRUE);filearg<-grep(\"^--file=\",commandArgs(),value=TRUE)\nhere<-if(dir.exists(\"ml14-sources\"))getwd()else if(length(filearg))dirname(normalizePath(sub(\"^--file=\",\"\",filearg[1])))else getwd()\noption<-function(key,default){i<-match(key,args);if(is.na(i))default else args[i+1]}\nsourceDir<-option(\"--source\",file.path(here,\"ml14-sources\"));outDir<-option(\"--out\",file.path(getwd(),\"ml14-r-results\"));dir.create(outDir,recursive=TRUE,showWarnings=FALSE)\nnum<-function(x){x[x%in%c(\"\",\".\")]<-NA_character_;as.numeric(x)}\nfmt<-function(x)ifelse(is.na(x),\"\",sprintf(\"%.17g\",x))\nratio<-function(a,b)if(b==0)NA_real_ else a/b\nreadnative<-function(name)read.csv(file.path(sourceDir,name),check.names=FALSE,colClasses=\"character\",na.strings=character(),stringsAsFactors=FALSE)\n# Vectorized SHA256 for the short ASCII keys used in this study.\n# Unsigned words use exact integer-valued doubles; bit operations use safe\n# 16-bit halves, avoiding R's reserved signed-INT_MIN/NA representation.\nMOD<-2^32\nxor32<-function(a,b) as.double(bitwXor(as.integer(floor(a/65536)),as.integer(floor(b/65536))))*65536+as.double(bitwXor(as.integer(a%%65536),as.integer(b%%65536)))\nand32<-function(a,b) as.double(bitwAnd(as.integer(floor(a/65536)),as.integer(floor(b/65536))))*65536+as.double(bitwAnd(as.integer(a%%65536),as.integer(b%%65536)))\nrot<-function(x,n) floor(x/2^n)+(x%%2^n)*2^(32-n)\nxor3<-function(a,b,c) xor32(xor32(a,b),c)\nK<-c(0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5,0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967,0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070,0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3,0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2)\nsha256<-function(strings) {\n n<-length(strings);bytes<-matrix(0,n,64)\n for(i in seq_len(n)) {v<-utf8ToInt(strings[i]);stopifnot(length(v)<56,all(v<128));if(length(v)) bytes[i,seq_along(v)]<-v;bytes[i,length(v)+1]<-128;bits<-length(v)*8;bytes[i,61:64]<-c(floor(bits/2^24)%%256,floor(bits/2^16)%%256,floor(bits/256)%%256,bits%%256)}\n w<-matrix(0,n,64)\n for(j in 1:16) {b<-4*(j-1)+1;w[,j]<-bytes[,b]*2^24+bytes[,b+1]*2^16+bytes[,b+2]*256+bytes[,b+3]}\n for(j in 17:64) {s0<-xor3(rot(w[,j-15],7),rot(w[,j-15],18),floor(w[,j-15]/8));s1<-xor3(rot(w[,j-2],17),rot(w[,j-2],19),floor(w[,j-2]/1024));w[,j]<-(w[,j-16]+s0+w[,j-7]+s1)%%MOD}\n init<-c(0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19)\n state<-lapply(init,function(v) rep(v,n));a<-state[[1]];b<-state[[2]];c<-state[[3]];d<-state[[4]];e<-state[[5]];f<-state[[6]];g<-state[[7]];h<-state[[8]]\n for(j in 1:64) {S1<-xor3(rot(e,6),rot(e,11),rot(e,25));ch<-xor32(and32(e,f),and32(MOD-1-e,g));t1<-(h+S1+ch+K[j]+w[,j])%%MOD;S0<-xor3(rot(a,2),rot(a,13),rot(a,22));maj<-xor3(and32(a,b),and32(a,c),and32(b,c));t2<-(S0+maj)%%MOD;h<-g;g<-f;f<-e;e<-(d+t1)%%MOD;d<-c;c<-b;b<-a;a<-(t1+t2)%%MOD}\n end<-list(a,b,c,d,e,f,g,h);hex<-lapply(1:8,function(j){v<-(end[[j]]+init[j])%%MOD;paste0(sprintf(\"%04x\",as.integer(floor(v/65536))),sprintf(\"%04x\",as.integer(v%%65536)))})\n do.call(paste0,hex)\n}\nstopifnot(identical(sha256(c(\"abc\",\"\")),c(\"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad\",\"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855\")))\n\nloadData<-function(){\n wb<-readnative(\"actual64-country-four-indicators-original-2024.csv\");codes<-c(\"NY.GDP.PCAP.KD\",\"NY.GDP.MKTP.KD.ZG\",\"FP.CPI.TOTL.ZG\",\"SP.DYN.LE00.IN\");iso<-sort(unique(wb$countryISO3));stopifnot(nrow(wb)==64,length(iso)==16)\n tokens<-t(vapply(iso,function(s)wb$originalValueToken[match(paste(s,codes),paste(wb$countryISO3,wb$indicatorID))],character(4)));vals<-matrix(num(as.vector(tokens)),nrow=nrow(tokens))\n country<-list(id=paste0(iso,\":2024\"),sourceRow=1:16,originalID=iso,x=vals[,1:3,drop=FALSE],rawX=tokens[,1:3,drop=FALSE],nativeTarget=tokens[,4],y=as.integer(vals[,4]>=80),group=ifelse(is.na(vals[,1]),NA_character_,as.character(as.integer(vals[,1]>=25000))),lineage=vapply(iso,function(s)paste(wb$sourceRow[match(paste(s,codes),paste(wb$countryISO3,wb$indicatorID))],collapse=\";\"),character(1)),cat=integer(),units=c(\"constant2015USD/person\",\"annualPercent\",\"annualPercent\"))\n nls<-readnative(\"actual3613-NLS-original52-fields-groups-roles.csv\");raw<-cbind(nls$ed76,nls$age76,nls$nearc4)\n person<-list(id=paste0(\"person:\",nls$sourceRow),sourceRow=as.integer(nls$sourceRow),originalID=nls$id,x=matrix(num(as.vector(raw)),nrow=nrow(raw)),rawX=raw,nativeTarget=nls$wage76,y=as.integer(num(nls$wage76)>=500),group=ifelse(nls$black%in%c(\"\",\".\"),NA_character_,nls$black),lineage=nls$sourceRow,cat=2L,units=c(\"years\",\"years\",\"nativeCategory\"))\n ch<-readnative(\"actual3150-churn-original14-fields-groups-roles.csv\");raw<-cbind(ch[[\"Call  Failure\"]],ch$Complains,ch[[\"Subscription  Length\"]],ch[[\"Seconds of Use\"]])\n company<-list(id=paste0(\"customer:\",ch$sourceRow),sourceRow=as.integer(ch$sourceRow),originalID=rep(\"\",nrow(ch)),x=matrix(num(as.vector(raw)),nrow=nrow(raw)),rawX=raw,nativeTarget=ch$Churn,y=as.integer(ch$Churn),group=ifelse(ch[[\"Tariff Plan\"]]%in%c(\"\",\".\"),NA_character_,ch[[\"Tariff Plan\"]]),lineage=ch$sourceRow,cat=1L,units=c(\"count\",\"nativeCategory\",\"months\",\"seconds\"))\n stopifnot(nrow(nls)==3613,nrow(ch)==3150,identical(as.integer(ch$sourceRow[ch[[\"Charge  Amount\"]]==\"10\"]),c(474L,2174L,2274L,2374L,2674L,2924L,2974L)))\n result<-list(country=country,person=person,company=company)\n for(k in names(result)){d<-result[[k]];n<-length(d$id);d$eligible<-!is.na(d$y)&rowSums(is.na(d$x))==0;hash<-sha256(paste0(\"ML14-role|\",k,\"|\",d$id));rank<-integer(n);rank[order(hash,seq_len(n))]<-seq_len(n)-1L;d$plannedRole<-ifelse(rank%%5==0,\"test\",ifelse(rank%%5==1,\"validation\",\"train\"));d$role<-ifelse(d$eligible,d$plannedRole,\"excluded\");result[[k]]<-d}\n stopifnot(sum(result$person$eligible)==3017);result\n}\nfitmodel<-function(d){\n ids<-which(d$role==\"train\");p<-ncol(d$x);m<-vapply(seq_len(p),function(j)if((j-1)%in%d$cat)NA_real_ else median(d$x[ids,j]),numeric(1));z<-d$x\n for(j in seq_len(p))if(!((j-1)%in%d$cat))z[,j]<-as.numeric(z[,j]>m[j])\n keys<-apply(z,1,function(v)paste(fmt(v),collapse=\"|\"));lev<-unique(keys[ids]);mass<-vapply(lev,function(k)sum(keys[ids]==k),integer(1));positive<-vapply(lev,function(k)sum(d$y[ids][keys[ids]==k]),integer(1));prob<-(positive+1)/(mass+2);fallback<-(sum(d$y[ids])+1)/(length(ids)+2);pred<-prob[match(keys,lev)];unseen<-is.na(pred);pred[unseen]<-fallback;pred[!d$eligible]<-NA_real_;unseen[!d$eligible]<-NA\n list(ids=ids,medians=m,z=z,keys=keys,lev=lev,mass=mass,positive=positive,prob=prob,fallback=fallback,pred=pred,unseen=unseen)\n}\nmeasure<-function(d,p,ids,t=.5,cost=c(1,1)){\n use<-ids[d$eligible[ids]&!is.na(p[ids])];y<-d$y[use];a<-if(is.character(t))rep(t==\"always-positive\",length(use))else p[use]>=t\n TP<-sum(a&y==1);FP<-sum(a&y==0);FN<-sum(!a&y==1);TN<-sum(!a&y==0);P<-TP+FN;N<-FP+TN;W<-P+N;PP<-TP+FP;PN<-TN+FN;TPR<-ratio(TP,P);TNR<-ratio(TN,N);bs<-sum((p[use]-y)^2);tc<-FP*cost[1]+FN*cost[2]\n list(TP=TP,FP=FP,FN=FN,TN=TN,mass=W,positiveTargetMass=P,negativeTargetMass=N,predictedPositiveMass=PP,predictedNegativeMass=PN,prevalence=ratio(P,W),selectionRate=ratio(PP,W),accuracy=ratio(TP+TN,W),precision=ratio(TP,PP),negativePredictiveValue=ratio(TN,PN),TPR=TPR,FPR=ratio(FP,N),TNR=TNR,FNR=ratio(FN,P),F1=ratio(2*TP,2*TP+FP+FN),balancedAccuracy=if(is.na(TPR)||is.na(TNR))NA_real_ else(TPR+TNR)/2,Brier=ratio(bs,W),BrierSum=bs,totalCost=tc,meanCost=ratio(tc,W))\n}\ncurves<-function(d,p,ids){\n use<-ids[d$eligible[ids]&!is.na(p[ids])];scores<-sort(unique(p[use]),decreasing=TRUE);policies<-c(list(\"always-negative\"),as.list(scores));points<-lapply(policies,function(t){m<-measure(d,p,ids,t);c(list(policy=t),m[c(\"TP\",\"FP\",\"FN\",\"TN\",\"TPR\",\"FPR\",\"precision\")],list(recall=m$TPR))})\n pos<-use[d$y[use]==1];neg<-use[d$y[use]==0];U<-0;for(i in pos)U<-U+sum(p[i]>p[neg])+.5*sum(p[i]==p[neg])\n AP<-0;trap<-0;lastR<-0;lastP<-1\n if(length(pos)&&length(scores))for(j in seq_along(scores)){z<-points[[j+1]];AP<-AP+(z$recall-lastR)*z$precision;trap<-trap+(z$recall-lastR)*(z$precision+lastP)/2;lastR<-z$recall;lastP<-z$precision}\n list(points=points,ROC_AUC=ratio(U,length(pos)*length(neg)),averagePrecision=if(length(pos))AP else NA_real_,PRTrapezoidWithInitialPrecisionOne=if(length(pos))trap else NA_real_)\n}\ncalibrate<-function(d,p,ids){\n use<-ids[d$eligible[ids]&!is.na(p[ids])];W<-length(use);pi<-if(W)mean(d$y[use])else NA_real_;bins<-list();ECE<-rel<-res<-correction<-0\n whichbin<-findInterval(p[use],seq(0,1,.2),rightmost.closed=TRUE,all.inside=TRUE)\n for(b in 1:5){rr<-use[whichbin==b];w<-length(rr);mp<-if(w)mean(p[rr])else NA_real_;o<-if(w)mean(d$y[rr])else NA_real_;variance<-if(w)mean((p[rr]-mp)^2)else NA_real_;covariance<-if(w)mean((p[rr]-mp)*(d$y[rr]-o))else NA_real_;bc<-variance-2*covariance;gap<-mp-o\n  bins[[b]]<-list(mass=w,meanPrediction=mp,eventRate=o,gap=gap,absoluteGap=abs(gap),scoreVariance=variance,scoreTargetCovariance=covariance,withinBinCorrection=bc,rows=w,ids=d$id[rr])\n  if(w){share<-w/W;ECE<-ECE+share*abs(gap);rel<-rel+share*gap^2;res<-res+share*(o-pi)^2;correction<-correction+share*bc}\n };bs<-if(W)mean((p[use]-d$y[use])^2)else NA_real_;unc<-pi*(1-pi)\n list(bins=bins,ECE=if(W)ECE else NA_real_,Brier=bs,reliability=if(W)rel else NA_real_,resolution=if(W)res else NA_real_,uncertainty=unc,withinBinCorrection=if(W)correction else NA_real_,BrierIdentityResidual=bs-(unc-res+rel+correction))\n}\ncounts<-c(\"mass\",\"positiveTargetMass\",\"negativeTargetMass\",\"predictedPositiveMass\",\"predictedNegativeMass\");rates<-c(\"prevalence\",\"selectionRate\",\"accuracy\",\"precision\",\"negativePredictiveValue\",\"TPR\",\"FPR\",\"TNR\",\"FNR\",\"F1\",\"balancedAccuracy\",\"Brier\",\"BrierSum\",\"totalCost\",\"meanCost\")\ntables<-setNames(lapply(1:10,function(i)list()),c(\"predictions\",\"lineage\",\"fit-medians\",\"fit-cells\",\"validation-candidates\",\"test-metrics\",\"test-curves\",\"calibration-bins\",\"group-metrics\",\"chart-points\"))\nadd<-function(name,row)tables[[name]][[length(tables[[name]])+1L]]<<-row\nscalars<-function(m,keys){out<-list();for(k in keys){out[[paste0(k,\"Exact\")]]<-\"\";out[[paste0(k,\"Approx\")]]<-fmt(m[[k]])};out}\ntagrow<-function(kind,...)c(list(kind=kind),list(...))\npoint<-function(kind,chart,series,index,x,y,xunit=\"dimensionless\",yunit=\"dimensionless\",role=\"test\",tag=\"\"){add(\"chart-points\",tagrow(kind,chart=chart,series=series,index=index,xExact=\"\",xApprox=fmt(x),yExact=\"\",yApprox=fmt(y),xUnit=xunit,yUnit=yunit,role=role,tag=tag))}\nstudy<-function(kind,d){\n f<-fitmodel(d);n<-length(d$id);train<-which(d$role==\"train\");validation<-which(d$role==\"validation\");test<-which(d$role==\"test\");p<-f$pred;cv<-curves(d,p,test);cal<-calibrate(d,p,test)\n for(i in seq_len(n)){\n  reason<-if(d$eligible[i])\"\"else\"required-X-or-Y-missing\";transformed<-if(d$eligible[i])paste(fmt(f$z[i,]),collapse=\"|\")else\"\"\n  add(\"predictions\",tagrow(kind,id=d$id[i],sourceRow=d$sourceRow[i],originalID=d$originalID[i],plannedRole=d$plannedRole[i],role=d$role[i],group=ifelse(is.na(d$group[i]),\"\",d$group[i]),eligible=as.integer(d$eligible[i]),targetExact=fmt(d$y[i]),probabilityExact=\"\",probabilityApprox=fmt(p[i]),unseenCell=ifelse(is.na(f$unseen[i]),\"\",as.character(as.integer(f$unseen[i]))),transformedX=transformed,reason=reason))\n  raw<-d$rawX[i,];raw[raw%in%c(\"\",\".\")]<-\"\";nativeY<-d$nativeTarget[i];if(nativeY%in%c(\"\",\".\"))nativeY<-\"\"\n  add(\"lineage\",tagrow(kind,id=d$id[i],sourceRow=d$sourceRow[i],originalID=d$originalID[i],nativeSourceRows=d$lineage[i],rawX=paste(raw,collapse=\"|\"),nativeTarget=nativeY,derivedTarget=fmt(d$y[i]),nativeGroup=ifelse(is.na(d$group[i]),\"\",d$group[i]),plannedRole=d$plannedRole[i],role=d$role[i],eligible=as.integer(d$eligible[i]),analyticalMass=\"1\",reason=reason))\n }\n for(j in seq_len(ncol(d$x)))add(\"fit-medians\",tagrow(kind,feature=j-1,categorical=as.integer((j-1)%in%d$cat),fitRows=length(train),medianExact=\"\",medianApprox=fmt(f$medians[j]),unit=d$units[j]))\n for(j in seq_along(f$lev))add(\"fit-cells\",tagrow(kind,cell=f$lev[j],trainingRows=f$mass[j],positiveRows=f$positive[j],probabilityExact=\"\",probabilityApprox=fmt(f$prob[j]),fallbackExact=\"\",fallbackApprox=fmt(f$fallback)))\n for(j in seq_along(cv$points)){\n  z<-cv$points[[j]];t<-z$policy;add(\"test-curves\",c(tagrow(kind,point=j-1,policy=if(is.character(t))t else\"threshold\",thresholdExact=\"\",thresholdApprox=if(is.character(t))\"\"else fmt(t)),scalars(z,c(\"TP\",\"FP\",\"FN\",\"TN\",\"TPR\",\"FPR\",\"precision\",\"recall\"))))\n  point(kind,\"roc\",\"ROC\",j-1,z$FPR,z$TPR);point(kind,\"pr\",\"PR-observed\",j-1,z$recall,z$precision)\n }\n for(b in 1:5){z<-cal$bins[[b]];add(\"calibration-bins\",c(tagrow(kind,bin=b-1,leftExact=c(\"0\",\"1/5\",\"2/5\",\"3/5\",\"4/5\")[b],rightExact=c(\"1/5\",\"2/5\",\"3/5\",\"4/5\",\"1\")[b],rightClosed=as.integer(b==5),rows=z$rows,ids=paste(z$ids,collapse=\";\")),scalars(z,c(\"mass\",\"meanPrediction\",\"eventRate\",\"gap\",\"absoluteGap\",\"scoreVariance\",\"scoreTargetCovariance\",\"withinBinCorrection\"))));point(kind,\"reliability\",\"Binary event rate\",b-1,z$meanPrediction,z$eventRate,tag=paste0(\"rows=\",z$rows))}\n for(j in seq_along(test)){i<-test[j];point(kind,\"test-scores\",\"Training-fitted probability\",j-1,j,p[i],\"test-row position\",\"probability\",tag=d$id[i]);point(kind,\"test-scores\",\"Observed Y\",j-1,j,d$y[i],\"test-row position\",\"binary target\",tag=d$id[i])}\n scenarioNames<-c(\"equal\",\"miss-five\",\"alarm-five\");costs<-list(c(1,1),c(1,5),c(5,1))\n for(s in 1:3){name<-scenarioNames[s];cost<-costs[[s]];grid<-c(list(\"always-negative\"),as.list(sort(unique(p[validation]),decreasing=TRUE)));candidates<-lapply(grid,function(t)measure(d,p,validation,t,cost));values<-vapply(candidates,function(m)m$meanCost,numeric(1));best<-which(values<=min(values)+1e-12)[1];chosen<-grid[[best]];ev<-measure(d,p,test,chosen,cost)\n  for(j in seq_along(grid)){t<-grid[[j]];m<-candidates[[j]];cell<-setNames(lapply(c(\"TP\",\"FP\",\"FN\",\"TN\"),function(k)fmt(m[[k]])),paste0(c(\"TP\",\"FP\",\"FN\",\"TN\"),\"Exact\"));add(\"validation-candidates\",c(tagrow(kind,scenario=name,candidate=j-1,selected=as.integer(j==best),policy=if(is.character(t))t else\"threshold\",thresholdExact=\"\",thresholdApprox=if(is.character(t))\"\"else fmt(t),feasible=1,reasons=\"\"),cell,scalars(m,c(counts,\"TPR\",\"FPR\",\"precision\",\"meanCost\",\"totalCost\"))));point(kind,\"validation-cost\",name,j-1,j-1,m$meanCost,\"candidate index\",\"hypothetical cost units/mass\",\"validation\",if(is.character(t))t else fmt(t))}\n  m<-c(ev,cv[c(\"ROC_AUC\",\"averagePrecision\",\"PRTrapezoidWithInitialPrecisionOne\")],cal[c(\"ECE\",\"reliability\",\"resolution\",\"uncertainty\",\"withinBinCorrection\",\"BrierIdentityResidual\")])\n  for(k in c(\"TP\",\"FP\",\"FN\",\"TN\",counts,rates,\"ROC_AUC\",\"averagePrecision\",\"PRTrapezoidWithInitialPrecisionOne\",\"ECE\",\"reliability\",\"resolution\",\"uncertainty\",\"withinBinCorrection\",\"BrierIdentityResidual\")){\n   unit<-if(k%in%c(\"TP\",\"FP\",\"FN\",\"TN\",counts))\"rows\"else if(k==\"totalCost\")\"hypothetical cost units\"else if(k==\"meanCost\")\"hypothetical cost units/mass\"else if(k==\"BrierSum\")\"sum squared-probability loss\"else\"dimensionless\"\n   add(\"test-metrics\",tagrow(kind,scenario=name,metric=k,valueExact=\"\",valueApprox=fmt(m[[k]]),unit=unit))\n  }\n  lev<-unique(d$group[test][!is.na(d$group[test])]);sets<-c(list(test),lapply(lev,function(g)test[!is.na(d$group[test])&d$group[test]==g]),list(test[is.na(d$group[test])]))\n  types<-c(\"overall\",rep(\"known\",length(lev)),\"unknown\");tokens<-c(\"all\",lev,\"\")\n  for(j in seq_along(sets)){ids<-sets[[j]];m<-measure(d,p,ids,chosen,cost);cell<-setNames(lapply(c(\"TP\",\"FP\",\"FN\",\"TN\"),function(k)fmt(m[[k]])),paste0(c(\"TP\",\"FP\",\"FN\",\"TN\"),\"Exact\"));add(\"group-metrics\",c(tagrow(kind,scenario=name,groupType=types[j],groupToken=tokens[j],retainedRows=length(ids)),cell,scalars(m,c(counts,rates))));if(types[j]==\"known\")point(kind,\"group-TPR\",name,j-2,j-2,m$TPR,\"declared group position\",\"TPR\",tag=tokens[j])}\n }\n invisible(NULL)\n}\n\n# Fixed finite inputs only; not the complete web input/budget validator.\nqnum<-function(v){if(is.null(v))return(NA_real_);if(is.logical(v))return(as.numeric(v));s<-as.character(v);if(grepl(\"/\",s,fixed=TRUE)){a<-strsplit(s,\"/\",fixed=TRUE)[[1]];return(as.numeric(a[1])/as.numeric(a[2]))};as.numeric(s)}\nrowsG<-function(raw){\n n<-length(raw);get<-function(r,k,default=NULL)if(is.null(r[[k]]))default else r[[k]]\n id<-vapply(raw,function(r)as.character(r$id),character(1));p<-vapply(raw,function(r)qnum(r$score),numeric(1));y<-vapply(raw,function(r)qnum(r$y),numeric(1));w<-vapply(raw,function(r)qnum(get(r,\"weight\",\"1\")),numeric(1));role<-vapply(raw,function(r)get(r,\"role\",\"evaluation\"),character(1));group<-vapply(raw,function(r)as.character(get(r,\"group\",NA_character_)),character(1))\n stopifnot(all(w>=0),all(is.na(p)|(p>=0&p<=1)),all(is.na(y)|y%in%c(0,1)),!anyDuplicated(id));list(id=id,p=p,y=y,w=w,role=role,group=group,eligible=!is.na(p)&!is.na(y)&w>0&role!=\"excluded\")\n}\nscopeG<-function(d,role=\"all\")if(role==\"all\")seq_along(d$id)else which(d$role==role)\nmetricsG<-function(d,ids,t=.5,cost=c(1,1)){\n use<-ids[d$eligible[ids]];p<-d$p[use];y<-d$y[use];w<-d$w[use];a<-if(is.character(t))rep(t==\"always-positive\",length(use))else p>=t\n TP<-sum(w[a&y==1]);FP<-sum(w[a&y==0]);FN<-sum(w[!a&y==1]);TN<-sum(w[!a&y==0]);P<-TP+FN;N<-FP+TN;W<-P+N;PP<-TP+FP;PN<-TN+FN;TPR<-ratio(TP,P);TNR<-ratio(TN,N);bs<-sum(w*(p-y)^2);tc<-FP*cost[1]+FN*cost[2]\n list(confusion=list(TP=TP,FP=FP,FN=FN,TN=TN),mass=W,positiveTargetMass=P,negativeTargetMass=N,predictedPositiveMass=PP,predictedNegativeMass=PN,prevalence=ratio(P,W),selectionRate=ratio(PP,W),accuracy=ratio(TP+TN,W),precision=ratio(TP,PP),negativePredictiveValue=ratio(TN,PN),TPR=TPR,FPR=ratio(FP,N),TNR=TNR,FNR=ratio(FN,P),F1=ratio(2*TP,2*TP+FP+FN),balancedAccuracy=if(is.na(TPR)||is.na(TNR))NA_real_ else(TPR+TNR)/2,Brier=ratio(bs,W),BrierSum=bs,totalCost=tc,meanCost=ratio(tc,W),bayesThreshold=ratio(cost[1],sum(cost)))\n}\ncurvesG<-function(d,ids){\n use<-ids[d$eligible[ids]];grid<-c(list(\"always-negative\"),as.list(sort(unique(d$p[use]),decreasing=TRUE)));points<-lapply(grid,function(t){m<-metricsG(d,ids,t);c(list(policy=t),m$confusion,m[c(\"TPR\",\"FPR\",\"precision\")],list(recall=m$TPR))});pos<-use[d$y[use]==1];neg<-use[d$y[use]==0];P<-sum(d$w[pos]);N<-sum(d$w[neg]);U<-0\n for(i in pos)U<-U+d$w[i]*sum(d$w[neg]*((d$p[i]>d$p[neg])+.5*(d$p[i]==d$p[neg])))\n AP<-trap<-lastR<-0;lastP<-1\n if(P&&length(grid)>1)for(j in 2:length(grid)){z<-points[[j]];AP<-AP+(z$recall-lastR)*z$precision;trap<-trap+(z$recall-lastR)*(z$precision+lastP)/2;lastR<-z$recall;lastP<-z$precision}\n list(points=points,ROC_AUC=ratio(U,P*N),averagePrecision=if(P)AP else NA_real_,PRTrapezoidWithInitialPrecisionOne=if(P)trap else NA_real_)\n}\nchooseG<-function(d,a,cost){\n role<-if(is.null(a$selectionRole))\"validation\"else a$selectionRole;er<-if(is.null(a$evaluationRole))\"test\"else a$evaluationRole;ids<-scopeG(d,role);use<-ids[d$eligible[ids]];stopifnot(length(use)>0);grid<-if(is.null(a$thresholds))c(list(\"always-negative\"),as.list(sort(unique(d$p[use]),decreasing=TRUE)))else lapply(a$thresholds,function(t)if(t%in%c(\"always-negative\",\"always-positive\"))t else qnum(t))\n candidates<-lapply(seq_along(grid),function(j){m<-metricsG(d,ids,grid[[j]],cost);feasible<-TRUE;if(!is.null(a$minTPR))feasible<-feasible&&!is.na(m$TPR)&&m$TPR>=qnum(a$minTPR);if(!is.null(a$maxFPR))feasible<-feasible&&!is.na(m$FPR)&&m$FPR<=qnum(a$maxFPR);list(index=j-1,policy=grid[[j]],metrics=m,feasible=feasible)})\n good<-which(vapply(candidates,function(c)c$feasible,logical(1)));best<-NA_integer_;if(length(good)){v<-vapply(candidates[good],function(c)c$metrics$meanCost,numeric(1));best<-good[which(v<=min(v)+1e-12)[1]]}\n list(selectedIndex=if(is.na(best))NA_integer_ else best-1,selectedPolicy=if(is.na(best))NULL else grid[[best]],selectedValidation=if(is.na(best))NULL else candidates[[best]]$metrics,candidates=candidates,evaluation=if(is.na(best)||er==\"none\")NULL else metricsG(d,scopeG(d,er),grid[[best]],cost))\n}\ncalibrateG<-function(d,ids,edges){\n use<-ids[d$eligible[ids]];W<-sum(d$w[use]);pi<-ratio(sum(d$w[use]*d$y[use]),W);bins<-list();ECE<-rel<-res<-correction<-0;assign<-findInterval(d$p[use],edges,rightmost.closed=TRUE,all.inside=TRUE)\n for(b in seq_len(length(edges)-1)){rr<-use[assign==b];w<-sum(d$w[rr]);mp<-ratio(sum(d$w[rr]*d$p[rr]),w);o<-ratio(sum(d$w[rr]*d$y[rr]),w);variance<-if(w)sum(d$w[rr]*(d$p[rr]-mp)^2)/w else NA_real_;covariance<-if(w)sum(d$w[rr]*(d$p[rr]-mp)*(d$y[rr]-o))/w else NA_real_;bc<-variance-2*covariance;gap<-mp-o;bins[[b]]<-list(index=b-1,mass=w,meanPrediction=mp,eventRate=o,scoreVariance=variance,scoreTargetCovariance=covariance,withinBinCorrection=bc,ids=d$id[rr])\n  if(w){s<-w/W;ECE<-ECE+s*abs(gap);rel<-rel+s*gap^2;res<-res+s*(o-pi)^2;correction<-correction+s*bc}\n };bs<-ratio(sum(d$w[use]*(d$p[use]-d$y[use])^2),W);unc<-pi*(1-pi);list(bins=bins,Brier=bs,ECE=if(W)ECE else NA_real_,uncertainty=unc,reliability=if(W)rel else NA_real_,resolution=if(W)res else NA_real_,withinBinCorrection=if(W)correction else NA_real_,BrierIdentityResidual=bs-(unc-res+rel+correction))\n}\ngroupsG<-function(d,ids,t,cost){\n lev<-unique(d$group[ids][!is.na(d$group[ids])]);groups<-lapply(lev,function(g)list(group=g,metrics=metricsG(d,ids[!is.na(d$group[ids])&d$group[ids]==g],t,cost)));overall<-metricsG(d,ids,t,cost);unknown<-metricsG(d,ids[is.na(d$group[ids])],t,cost);gaps<-list()\n for(k in c(\"prevalence\",\"selectionRate\",\"TPR\",\"FPR\",\"precision\",\"accuracy\",\"meanCost\")){use<-Filter(function(g)g$metrics$mass>0,groups);v<-vapply(use,function(g)g$metrics[[k]],numeric(1));gaps[[k]]<-if(length(use)<2||anyNA(v))NA_real_ else max(v)-min(v)}\n list(overall=overall,groups=groups,unknownGroup=unknown,gaps=gaps,partitionMassResidual=overall$mass-unknown$mass-sum(vapply(groups,function(g)g$metrics$mass,numeric(1))))\n}\nsvgFixed<-function(file,points,title,xlabel,ylabel,legend){\n finite<-points[points$y!=\"undefined\"&points$x!=\"undefined\",,drop=FALSE];x<-as.numeric(finite$x);y<-as.numeric(finite$y);xmin<-if(length(x))min(x)else 0;xmax<-if(length(x))max(x)else 1;ymin<-min(c(0,y));ymax<-max(c(0,y));if(xmin==xmax){xmin<-xmin-.5;xmax<-xmax+.5};if(ymin==ymax)ymax<-ymin+1;X<-function(v)85+(v-xmin)/(xmax-xmin)*480;Y<-function(v)278-(v-ymin)/(ymax-ymin)*175\n esc<-function(s){s<-gsub(\"&\",\"&amp;\",s,fixed=TRUE);s<-gsub(\"<\",\"&lt;\",s,fixed=TRUE);gsub(\">\",\"&gt;\",s,fixed=TRUE)};s<-'<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"620\" height=\"360\" viewBox=\"0 0 620 360\"><rect width=\"620\" height=\"360\" fill=\"white\"/><g font-family=\"Arial, sans-serif\" font-size=\"13\" fill=\"#17324d\">'\n lines<-strwrap(title,width=65);for(i in seq_along(lines))s<-paste0(s,'<text x=\"25\" y=\"',24+(i-1)*18,'\">',esc(lines[i]),'</text>');colors<-c(\"#176b9b\",\"#b85e18\",\"#437e4d\")\n for(i in seq_along(legend))s<-paste0(s,'<circle cx=\"',30+(i-1)*250,'\" cy=\"76\" r=\"4\" fill=\"',colors[(i-1)%%3+1],'\"/><text x=\"',42+(i-1)*250,'\" y=\"80\">',esc(legend[i]),'</text>')\n s<-paste0(s,'<path d=\"M85 98V278H575\" fill=\"none\" stroke=\"#52677d\"/><text text-anchor=\"middle\" x=\"325\" y=\"338\">',esc(xlabel),'</text><text text-anchor=\"middle\" transform=\"translate(21,190) rotate(-90)\">',esc(ylabel),'</text>')\n for(i in 0:4){xx<-xmin+(xmax-xmin)*i/4;yy<-ymin+(ymax-ymin)*i/4;s<-paste0(s,'<text text-anchor=\"middle\" x=\"',sprintf(\"%.9g\",X(xx)),'\" y=\"305\">',sprintf(\"%.4g\",xx),'</text><text text-anchor=\"end\" x=\"77\" y=\"',sprintf(\"%.9g\",Y(yy)+4),'\">',sprintf(\"%.4g\",yy),'</text>')}\n for(i in seq_len(nrow(finite)))s<-paste0(s,'<circle cx=\"',sprintf(\"%.9g\",X(x[i])),'\" cy=\"',sprintf(\"%.9g\",Y(y[i])),'\" r=\"3\" fill=\"',colors[as.integer(finite$series[i])%%3+1],'\"/>');writeLines(paste0(s,'</g></svg>'),file,useBytes=TRUE)\n}\nfixedRun<-function(){\n api<-FIXED$api;a<-FIXED$args;summary<-list();points<-list();xlabel<-\"Declared index\";ylabel<-\"Value\";legend<-\"Declared result\"\n metric<-function(name,v,unit=\"dimensionless\"){if(is.null(v))v<-NA_real_;summary[[length(summary)+1L]]<<-data.frame(metric=name,value=if(is.na(v))\"undefined\"else sprintf(\"%.9g\",v),exactValue=\"\",unit=unit,defined=as.integer(!is.na(v)),stringsAsFactors=FALSE)}\n pt<-function(i,x,y,id=\"\",series=0){points[[length(points)+1L]]<<-data.frame(series=series,index=i,xExact=\"\",x=if(is.na(x))\"undefined\"else sprintf(\"%.9g\",x),yExact=\"\",y=if(is.na(y))\"undefined\"else sprintf(\"%.9g\",y),id=as.character(id),stringsAsFactors=FALSE)}\n if(api==\"realdata\"){\n  native<-loadData()[[a$kind]];fit<-fitmodel(native);d<-list(id=native$id,p=fit$pred,y=native$y,w=rep(1,length(native$id)),role=native$role,group=native$group,eligible=native$eligible);scenarios<-list()\n  for(j in 1:3){name<-c(\"equal\",\"miss-five\",\"alarm-five\")[j];cst<-list(c(1,1),c(1,5),c(5,1))[[j]];sel<-chooseG(d,list(),cst);scenarios[[j]]<-list(name=name,selection=sel);metric(paste0(name,\"Threshold\"),sel$selectedPolicy);metric(paste0(name,\"TestCost\"),sel$evaluation$meanCost,\"hypothetical cost units/mass\")}\n  ids<-scopeG(d,\"test\");cv<-curvesG(d,ids);cal<-calibrateG(d,ids,seq(0,1,.2));metric(\"testAUC\",cv$ROC_AUC);metric(\"testAP\",cv$averagePrecision);metric(\"testBrier\",cal$Brier);metric(\"eligibleRows\",sum(d$eligible),\"rows\")\n  for(j in seq_along(ids)){i<-ids[j];pt(j-1,j,d$p[i],d$id[i],0);pt(j-1,j,d$y[i],d$id[i],1)}\n  full<-list(kind=a$kind,fit=fit,scenarios=scenarios,testCurves=cv,testCalibration=cal,rowsScored=d);xlabel<-\"Test row, native order\";ylabel<-\"Y or probability\";legend<-c(\"Training-fitted probability\",\"Observed Y\")\n }else{\n  d<-rowsG(a$rows);role<-if(is.null(a$role))\"all\"else a$role;ids<-scopeG(d,role);cost<-if(is.null(a$costs))c(1,1)else c(qnum(a$costs$falsePositive),qnum(a$costs$falseNegative));t<-if(is.null(a$threshold)).5 else if(a$threshold%in%c(\"always-positive\",\"always-negative\"))a$threshold else qnum(a$threshold)\n  if(api==\"metrics\"){\n   full<-metricsG(d,ids,t,cost);for(k in c(\"mass\",\"accuracy\",\"precision\",\"TPR\",\"FPR\",\"F1\",\"Brier\",\"meanCost\"))metric(k,full[[k]],if(k==\"mass\")\"mass\"else if(k==\"meanCost\")\"hypothetical cost units/mass\"else\"dimensionless\");metric(\"BayesThreshold\",full$bayesThreshold)\n   for(i in 1:4)pt(i-1,i-1,full$confusion[[i]],names(full$confusion)[i]);xlabel<-\"TP / FP / FN / TN positions\";ylabel<-\"Analytical mass\"\n  }else if(api==\"curves\"){\n   full<-curvesG(d,ids);for(k in c(\"ROC_AUC\",\"averagePrecision\",\"PRTrapezoidWithInitialPrecisionOne\"))metric(k,full[[k]])\n   for(j in seq_along(full$points)){p<-full$points[[j]];pt(j-1,p$FPR,p$TPR,if(is.character(p$policy))p$policy else sprintf(\"%.17g\",p$policy))};xlabel<-\"False positive rate\";ylabel<-\"True positive rate\";legend<-\"Observed ROC operating points\"\n  }else if(api==\"choose\"){\n   full<-chooseG(d,a,cost);metric(\"selectedIndex\",full$selectedIndex,\"candidate index\");metric(\"minimumCost\",if(is.null(full$selectedValidation))NULL else full$selectedValidation$meanCost,\"hypothetical cost units/mass\");metric(\"feasible\",as.integer(!is.na(full$selectedIndex)),\"indicator\")\n   for(c in full$candidates)pt(c$index,c$index,c$metrics$meanCost,if(is.character(c$policy))c$policy else sprintf(\"%.17g\",c$policy));xlabel<-\"Validation candidate\";ylabel<-\"Assumed cost / mass\";legend<-\"Validation candidate costs\"\n  }else if(api==\"calibrate\"){\n   edges<-if(is.null(a$binEdges))seq(0,1,.2)else vapply(a$binEdges,qnum,numeric(1));full<-calibrateG(d,ids,edges);for(k in c(\"ECE\",\"Brier\",\"uncertainty\",\"resolution\",\"reliability\",\"withinBinCorrection\",\"BrierIdentityResidual\"))metric(k,full[[k]])\n   for(b in full$bins)pt(b$index,b$meanPrediction,b$eventRate,paste0(\"bin:\",b$index));xlabel<-\"Bin mean forecast\";ylabel<-\"Bin event rate\";legend<-\"Binary-event reliability\"\n  }else if(api==\"groups\"){\n   full<-groupsG(d,ids,t,cost);metric(\"overallTPR\",full$overall$TPR);metric(\"TPRGap\",full$gaps$TPR);metric(\"precisionGap\",full$gaps$precision);metric(\"unknownMass\",full$unknownGroup$mass,\"mass\");metric(\"partitionResidual\",full$partitionMassResidual,\"mass\")\n   for(j in seq_along(full$groups))pt(j-1,j-1,full$groups[[j]]$metrics$TPR,full$groups[[j]]$group);xlabel<-\"Declared group position\";ylabel<-\"True positive rate\";legend<-\"Known-group TPR\"\n  }else stop(\"unknown declared fixed API\")\n }\n sm<-do.call(rbind,summary);pp<-do.call(rbind,points);write.csv(sm,file.path(outDir,\"summary.csv\"),row.names=FALSE,na=\"\");write.csv(pp,file.path(outDir,\"plot-points.csv\"),row.names=FALSE,na=\"\");svgFixed(file.path(outDir,\"plot.svg\"),pp,FIXED$title,xlabel,ylabel,legend);dput(list(api=api,variant=FIXED$variant,input=FIXED$args,arithmetic=\"Base-R binary64 fixed example; not an exact rational general validator\",result=full),file=file.path(outDir,\"full.txt\"));cat(\"PASS\",api,FIXED$variant,\"summary\",nrow(sm),\"points\",nrow(pp),\"\\n\")\n}\n\nFIXED<-list(api=\"realdata\",variant=\"person\",args=list(kind=\"person\"),title=\"Actual person fixed train/validation/test procedure\")\nfixedRun()\n",
        "codeText": "# ML14 standalone public counterpart, base R only.\n# Inputs are only the three factual CSVs; derived columns/previous model answers unused.\n# Binary64 arithmetic, not arbitrary-precision Fraction. At numerical cost ties\n# within 1e-12 retain the earliest candidate. Exact claims belong to Python/web.\n# SHA256 infrastructure below is reused verbatim from the previous public study.\nargs<-commandArgs(trailingOnly=TRUE);filearg<-grep(\"^--file=\",commandArgs(),value=TRUE)\nhere<-if(dir.exists(\"ml14-sources\"))getwd()else if(length(filearg))dirname(normalizePath(sub(\"^--file=\",\"\",filearg[1])))else getwd()\noption<-function(key,default){i<-match(key,args);if(is.na(i))default else args[i+1]}\nsourceDir<-option(\"--source\",file.path(here,\"ml14-sources\"));outDir<-option(\"--out\",file.path(getwd(),\"ml14-r-results\"));dir.create(outDir,recursive=TRUE,showWarnings=FALSE)\nnum<-function(x){x[x%in%c(\"\",\".\")]<-NA_character_;as.numeric(x)}\nfmt<-function(x)ifelse(is.na(x),\"\",sprintf(\"%.17g\",x))\nratio<-function(a,b)if(b==0)NA_real_ else a/b\nreadnative<-function(name)read.csv(file.path(sourceDir,name),check.names=FALSE,colClasses=\"character\",na.strings=character(),stringsAsFactors=FALSE)\n# Vectorized SHA256 for the short ASCII keys used in this study.\n# Unsigned words use exact integer-valued doubles; bit operations use safe\n# 16-bit halves, avoiding R's reserved signed-INT_MIN/NA representation.\nMOD<-2^32\nxor32<-function(a,b) as.double(bitwXor(as.integer(floor(a/65536)),as.integer(floor(b/65536))))*65536+as.double(bitwXor(as.integer(a%%65536),as.integer(b%%65536)))\nand32<-function(a,b) as.double(bitwAnd(as.integer(floor(a/65536)),as.integer(floor(b/65536))))*65536+as.double(bitwAnd(as.integer(a%%65536),as.integer(b%%65536)))\nrot<-function(x,n) floor(x/2^n)+(x%%2^n)*2^(32-n)\nxor3<-function(a,b,c) xor32(xor32(a,b),c)\nK<-c(0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5,0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967,0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070,0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3,0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2)\nsha256<-function(strings) {\n n<-length(strings);bytes<-matrix(0,n,64)\n for(i in seq_len(n)) {v<-utf8ToInt(strings[i]);stopifnot(length(v)<56,all(v<128));if(length(v)) bytes[i,seq_along(v)]<-v;bytes[i,length(v)+1]<-128;bits<-length(v)*8;bytes[i,61:64]<-c(floor(bits/2^24)%%256,floor(bits/2^16)%%256,floor(bits/256)%%256,bits%%256)}\n w<-matrix(0,n,64)\n for(j in 1:16) {b<-4*(j-1)+1;w[,j]<-bytes[,b]*2^24+bytes[,b+1]*2^16+bytes[,b+2]*256+bytes[,b+3]}\n for(j in 17:64) {s0<-xor3(rot(w[,j-15],7),rot(w[,j-15],18),floor(w[,j-15]/8));s1<-xor3(rot(w[,j-2],17),rot(w[,j-2],19),floor(w[,j-2]/1024));w[,j]<-(w[,j-16]+s0+w[,j-7]+s1)%%MOD}\n init<-c(0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19)\n state<-lapply(init,function(v) rep(v,n));a<-state[[1]];b<-state[[2]];c<-state[[3]];d<-state[[4]];e<-state[[5]];f<-state[[6]];g<-state[[7]];h<-state[[8]]\n for(j in 1:64) {S1<-xor3(rot(e,6),rot(e,11),rot(e,25));ch<-xor32(and32(e,f),and32(MOD-1-e,g));t1<-(h+S1+ch+K[j]+w[,j])%%MOD;S0<-xor3(rot(a,2),rot(a,13),rot(a,22));maj<-xor3(and32(a,b),and32(a,c),and32(b,c));t2<-(S0+maj)%%MOD;h<-g;g<-f;f<-e;e<-(d+t1)%%MOD;d<-c;c<-b;b<-a;a<-(t1+t2)%%MOD}\n end<-list(a,b,c,d,e,f,g,h);hex<-lapply(1:8,function(j){v<-(end[[j]]+init[j])%%MOD;paste0(sprintf(\"%04x\",as.integer(floor(v/65536))),sprintf(\"%04x\",as.integer(v%%65536)))})\n do.call(paste0,hex)\n}\nstopifnot(identical(sha256(c(\"abc\",\"\")),c(\"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad\",\"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855\")))\n\nloadData<-function(){\n wb<-readnative(\"actual64-country-four-indicators-original-2024.csv\");codes<-c(\"NY.GDP.PCAP.KD\",\"NY.GDP.MKTP.KD.ZG\",\"FP.CPI.TOTL.ZG\",\"SP.DYN.LE00.IN\");iso<-sort(unique(wb$countryISO3));stopifnot(nrow(wb)==64,length(iso)==16)\n tokens<-t(vapply(iso,function(s)wb$originalValueToken[match(paste(s,codes),paste(wb$countryISO3,wb$indicatorID))],character(4)));vals<-matrix(num(as.vector(tokens)),nrow=nrow(tokens))\n country<-list(id=paste0(iso,\":2024\"),sourceRow=1:16,originalID=iso,x=vals[,1:3,drop=FALSE],rawX=tokens[,1:3,drop=FALSE],nativeTarget=tokens[,4],y=as.integer(vals[,4]>=80),group=ifelse(is.na(vals[,1]),NA_character_,as.character(as.integer(vals[,1]>=25000))),lineage=vapply(iso,function(s)paste(wb$sourceRow[match(paste(s,codes),paste(wb$countryISO3,wb$indicatorID))],collapse=\";\"),character(1)),cat=integer(),units=c(\"constant2015USD/person\",\"annualPercent\",\"annualPercent\"))\n nls<-readnative(\"actual3613-NLS-original52-fields-groups-roles.csv\");raw<-cbind(nls$ed76,nls$age76,nls$nearc4)\n person<-list(id=paste0(\"person:\",nls$sourceRow),sourceRow=as.integer(nls$sourceRow),originalID=nls$id,x=matrix(num(as.vector(raw)),nrow=nrow(raw)),rawX=raw,nativeTarget=nls$wage76,y=as.integer(num(nls$wage76)>=500),group=ifelse(nls$black%in%c(\"\",\".\"),NA_character_,nls$black),lineage=nls$sourceRow,cat=2L,units=c(\"years\",\"years\",\"nativeCategory\"))\n ch<-readnative(\"actual3150-churn-original14-fields-groups-roles.csv\");raw<-cbind(ch[[\"Call  Failure\"]],ch$Complains,ch[[\"Subscription  Length\"]],ch[[\"Seconds of Use\"]])\n company<-list(id=paste0(\"customer:\",ch$sourceRow),sourceRow=as.integer(ch$sourceRow),originalID=rep(\"\",nrow(ch)),x=matrix(num(as.vector(raw)),nrow=nrow(raw)),rawX=raw,nativeTarget=ch$Churn,y=as.integer(ch$Churn),group=ifelse(ch[[\"Tariff Plan\"]]%in%c(\"\",\".\"),NA_character_,ch[[\"Tariff Plan\"]]),lineage=ch$sourceRow,cat=1L,units=c(\"count\",\"nativeCategory\",\"months\",\"seconds\"))\n stopifnot(nrow(nls)==3613,nrow(ch)==3150,identical(as.integer(ch$sourceRow[ch[[\"Charge  Amount\"]]==\"10\"]),c(474L,2174L,2274L,2374L,2674L,2924L,2974L)))\n result<-list(country=country,person=person,company=company)\n for(k in names(result)){d<-result[[k]];n<-length(d$id);d$eligible<-!is.na(d$y)&rowSums(is.na(d$x))==0;hash<-sha256(paste0(\"ML14-role|\",k,\"|\",d$id));rank<-integer(n);rank[order(hash,seq_len(n))]<-seq_len(n)-1L;d$plannedRole<-ifelse(rank%%5==0,\"test\",ifelse(rank%%5==1,\"validation\",\"train\"));d$role<-ifelse(d$eligible,d$plannedRole,\"excluded\");result[[k]]<-d}\n stopifnot(sum(result$person$eligible)==3017);result\n}\nfitmodel<-function(d){\n ids<-which(d$role==\"train\");p<-ncol(d$x);m<-vapply(seq_len(p),function(j)if((j-1)%in%d$cat)NA_real_ else median(d$x[ids,j]),numeric(1));z<-d$x\n for(j in seq_len(p))if(!((j-1)%in%d$cat))z[,j]<-as.numeric(z[,j]>m[j])\n keys<-apply(z,1,function(v)paste(fmt(v),collapse=\"|\"));lev<-unique(keys[ids]);mass<-vapply(lev,function(k)sum(keys[ids]==k),integer(1));positive<-vapply(lev,function(k)sum(d$y[ids][keys[ids]==k]),integer(1));prob<-(positive+1)/(mass+2);fallback<-(sum(d$y[ids])+1)/(length(ids)+2);pred<-prob[match(keys,lev)];unseen<-is.na(pred);pred[unseen]<-fallback;pred[!d$eligible]<-NA_real_;unseen[!d$eligible]<-NA\n list(ids=ids,medians=m,z=z,keys=keys,lev=lev,mass=mass,positive=positive,prob=prob,fallback=fallback,pred=pred,unseen=unseen)\n}\nmeasure<-function(d,p,ids,t=.5,cost=c(1,1)){\n use<-ids[d$eligible[ids]&!is.na(p[ids])];y<-d$y[use];a<-if(is.character(t))rep(t==\"always-positive\",length(use))else p[use]>=t\n TP<-sum(a&y==1);FP<-sum(a&y==0);FN<-sum(!a&y==1);TN<-sum(!a&y==0);P<-TP+FN;N<-FP+TN;W<-P+N;PP<-TP+FP;PN<-TN+FN;TPR<-ratio(TP,P);TNR<-ratio(TN,N);bs<-sum((p[use]-y)^2);tc<-FP*cost[1]+FN*cost[2]\n list(TP=TP,FP=FP,FN=FN,TN=TN,mass=W,positiveTargetMass=P,negativeTargetMass=N,predictedPositiveMass=PP,predictedNegativeMass=PN,prevalence=ratio(P,W),selectionRate=ratio(PP,W),accuracy=ratio(TP+TN,W),precision=ratio(TP,PP),negativePredictiveValue=ratio(TN,PN),TPR=TPR,FPR=ratio(FP,N),TNR=TNR,FNR=ratio(FN,P),F1=ratio(2*TP,2*TP+FP+FN),balancedAccuracy=if(is.na(TPR)||is.na(TNR))NA_real_ else(TPR+TNR)/2,Brier=ratio(bs,W),BrierSum=bs,totalCost=tc,meanCost=ratio(tc,W))\n}\ncurves<-function(d,p,ids){\n use<-ids[d$eligible[ids]&!is.na(p[ids])];scores<-sort(unique(p[use]),decreasing=TRUE);policies<-c(list(\"always-negative\"),as.list(scores));points<-lapply(policies,function(t){m<-measure(d,p,ids,t);c(list(policy=t),m[c(\"TP\",\"FP\",\"FN\",\"TN\",\"TPR\",\"FPR\",\"precision\")],list(recall=m$TPR))})\n pos<-use[d$y[use]==1];neg<-use[d$y[use]==0];U<-0;for(i in pos)U<-U+sum(p[i]>p[neg])+.5*sum(p[i]==p[neg])\n AP<-0;trap<-0;lastR<-0;lastP<-1\n if(length(pos)&&length(scores))for(j in seq_along(scores)){z<-points[[j+1]];AP<-AP+(z$recall-lastR)*z$precision;trap<-trap+(z$recall-lastR)*(z$precision+lastP)/2;lastR<-z$recall;lastP<-z$precision}\n list(points=points,ROC_AUC=ratio(U,length(pos)*length(neg)),averagePrecision=if(length(pos))AP else NA_real_,PRTrapezoidWithInitialPrecisionOne=if(length(pos))trap else NA_real_)\n}\ncalibrate<-function(d,p,ids){\n use<-ids[d$eligible[ids]&!is.na(p[ids])];W<-length(use);pi<-if(W)mean(d$y[use])else NA_real_;bins<-list();ECE<-rel<-res<-correction<-0\n whichbin<-findInterval(p[use],seq(0,1,.2),rightmost.closed=TRUE,all.inside=TRUE)\n for(b in 1:5){rr<-use[whichbin==b];w<-length(rr);mp<-if(w)mean(p[rr])else NA_real_;o<-if(w)mean(d$y[rr])else NA_real_;variance<-if(w)mean((p[rr]-mp)^2)else NA_real_;covariance<-if(w)mean((p[rr]-mp)*(d$y[rr]-o))else NA_real_;bc<-variance-2*covariance;gap<-mp-o\n  bins[[b]]<-list(mass=w,meanPrediction=mp,eventRate=o,gap=gap,absoluteGap=abs(gap),scoreVariance=variance,scoreTargetCovariance=covariance,withinBinCorrection=bc,rows=w,ids=d$id[rr])\n  if(w){share<-w/W;ECE<-ECE+share*abs(gap);rel<-rel+share*gap^2;res<-res+share*(o-pi)^2;correction<-correction+share*bc}\n };bs<-if(W)mean((p[use]-d$y[use])^2)else NA_real_;unc<-pi*(1-pi)\n list(bins=bins,ECE=if(W)ECE else NA_real_,Brier=bs,reliability=if(W)rel else NA_real_,resolution=if(W)res else NA_real_,uncertainty=unc,withinBinCorrection=if(W)correction else NA_real_,BrierIdentityResidual=bs-(unc-res+rel+correction))\n}\ncounts<-c(\"mass\",\"positiveTargetMass\",\"negativeTargetMass\",\"predictedPositiveMass\",\"predictedNegativeMass\");rates<-c(\"prevalence\",\"selectionRate\",\"accuracy\",\"precision\",\"negativePredictiveValue\",\"TPR\",\"FPR\",\"TNR\",\"FNR\",\"F1\",\"balancedAccuracy\",\"Brier\",\"BrierSum\",\"totalCost\",\"meanCost\")\ntables<-setNames(lapply(1:10,function(i)list()),c(\"predictions\",\"lineage\",\"fit-medians\",\"fit-cells\",\"validation-candidates\",\"test-metrics\",\"test-curves\",\"calibration-bins\",\"group-metrics\",\"chart-points\"))\nadd<-function(name,row)tables[[name]][[length(tables[[name]])+1L]]<<-row\nscalars<-function(m,keys){out<-list();for(k in keys){out[[paste0(k,\"Exact\")]]<-\"\";out[[paste0(k,\"Approx\")]]<-fmt(m[[k]])};out}\ntagrow<-function(kind,...)c(list(kind=kind),list(...))\npoint<-function(kind,chart,series,index,x,y,xunit=\"dimensionless\",yunit=\"dimensionless\",role=\"test\",tag=\"\"){add(\"chart-points\",tagrow(kind,chart=chart,series=series,index=index,xExact=\"\",xApprox=fmt(x),yExact=\"\",yApprox=fmt(y),xUnit=xunit,yUnit=yunit,role=role,tag=tag))}\nstudy<-function(kind,d){\n f<-fitmodel(d);n<-length(d$id);train<-which(d$role==\"train\");validation<-which(d$role==\"validation\");test<-which(d$role==\"test\");p<-f$pred;cv<-curves(d,p,test);cal<-calibrate(d,p,test)\n for(i in seq_len(n)){\n  reason<-if(d$eligible[i])\"\"else\"required-X-or-Y-missing\";transformed<-if(d$eligible[i])paste(fmt(f$z[i,]),collapse=\"|\")else\"\"\n  add(\"predictions\",tagrow(kind,id=d$id[i],sourceRow=d$sourceRow[i],originalID=d$originalID[i],plannedRole=d$plannedRole[i],role=d$role[i],group=ifelse(is.na(d$group[i]),\"\",d$group[i]),eligible=as.integer(d$eligible[i]),targetExact=fmt(d$y[i]),probabilityExact=\"\",probabilityApprox=fmt(p[i]),unseenCell=ifelse(is.na(f$unseen[i]),\"\",as.character(as.integer(f$unseen[i]))),transformedX=transformed,reason=reason))\n  raw<-d$rawX[i,];raw[raw%in%c(\"\",\".\")]<-\"\";nativeY<-d$nativeTarget[i];if(nativeY%in%c(\"\",\".\"))nativeY<-\"\"\n  add(\"lineage\",tagrow(kind,id=d$id[i],sourceRow=d$sourceRow[i],originalID=d$originalID[i],nativeSourceRows=d$lineage[i],rawX=paste(raw,collapse=\"|\"),nativeTarget=nativeY,derivedTarget=fmt(d$y[i]),nativeGroup=ifelse(is.na(d$group[i]),\"\",d$group[i]),plannedRole=d$plannedRole[i],role=d$role[i],eligible=as.integer(d$eligible[i]),analyticalMass=\"1\",reason=reason))\n }\n for(j in seq_len(ncol(d$x)))add(\"fit-medians\",tagrow(kind,feature=j-1,categorical=as.integer((j-1)%in%d$cat),fitRows=length(train),medianExact=\"\",medianApprox=fmt(f$medians[j]),unit=d$units[j]))\n for(j in seq_along(f$lev))add(\"fit-cells\",tagrow(kind,cell=f$lev[j],trainingRows=f$mass[j],positiveRows=f$positive[j],probabilityExact=\"\",probabilityApprox=fmt(f$prob[j]),fallbackExact=\"\",fallbackApprox=fmt(f$fallback)))\n for(j in seq_along(cv$points)){\n  z<-cv$points[[j]];t<-z$policy;add(\"test-curves\",c(tagrow(kind,point=j-1,policy=if(is.character(t))t else\"threshold\",thresholdExact=\"\",thresholdApprox=if(is.character(t))\"\"else fmt(t)),scalars(z,c(\"TP\",\"FP\",\"FN\",\"TN\",\"TPR\",\"FPR\",\"precision\",\"recall\"))))\n  point(kind,\"roc\",\"ROC\",j-1,z$FPR,z$TPR);point(kind,\"pr\",\"PR-observed\",j-1,z$recall,z$precision)\n }\n for(b in 1:5){z<-cal$bins[[b]];add(\"calibration-bins\",c(tagrow(kind,bin=b-1,leftExact=c(\"0\",\"1/5\",\"2/5\",\"3/5\",\"4/5\")[b],rightExact=c(\"1/5\",\"2/5\",\"3/5\",\"4/5\",\"1\")[b],rightClosed=as.integer(b==5),rows=z$rows,ids=paste(z$ids,collapse=\";\")),scalars(z,c(\"mass\",\"meanPrediction\",\"eventRate\",\"gap\",\"absoluteGap\",\"scoreVariance\",\"scoreTargetCovariance\",\"withinBinCorrection\"))));point(kind,\"reliability\",\"Binary event rate\",b-1,z$meanPrediction,z$eventRate,tag=paste0(\"rows=\",z$rows))}\n for(j in seq_along(test)){i<-test[j];point(kind,\"test-scores\",\"Training-fitted probability\",j-1,j,p[i],\"test-row position\",\"probability\",tag=d$id[i]);point(kind,\"test-scores\",\"Observed Y\",j-1,j,d$y[i],\"test-row position\",\"binary target\",tag=d$id[i])}\n scenarioNames<-c(\"equal\",\"miss-five\",\"alarm-five\");costs<-list(c(1,1),c(1,5),c(5,1))\n for(s in 1:3){name<-scenarioNames[s];cost<-costs[[s]];grid<-c(list(\"always-negative\"),as.list(sort(unique(p[validation]),decreasing=TRUE)));candidates<-lapply(grid,function(t)measure(d,p,validation,t,cost));values<-vapply(candidates,function(m)m$meanCost,numeric(1));best<-which(values<=min(values)+1e-12)[1];chosen<-grid[[best]];ev<-measure(d,p,test,chosen,cost)\n  for(j in seq_along(grid)){t<-grid[[j]];m<-candidates[[j]];cell<-setNames(lapply(c(\"TP\",\"FP\",\"FN\",\"TN\"),function(k)fmt(m[[k]])),paste0(c(\"TP\",\"FP\",\"FN\",\"TN\"),\"Exact\"));add(\"validation-candidates\",c(tagrow(kind,scenario=name,candidate=j-1,selected=as.integer(j==best),policy=if(is.character(t))t else\"threshold\",thresholdExact=\"\",thresholdApprox=if(is.character(t))\"\"else fmt(t),feasible=1,reasons=\"\"),cell,scalars(m,c(counts,\"TPR\",\"FPR\",\"precision\",\"meanCost\",\"totalCost\"))));point(kind,\"validation-cost\",name,j-1,j-1,m$meanCost,\"candidate index\",\"hypothetical cost units/mass\",\"validation\",if(is.character(t))t else fmt(t))}\n  m<-c(ev,cv[c(\"ROC_AUC\",\"averagePrecision\",\"PRTrapezoidWithInitialPrecisionOne\")],cal[c(\"ECE\",\"reliability\",\"resolution\",\"uncertainty\",\"withinBinCorrection\",\"BrierIdentityResidual\")])\n  for(k in c(\"TP\",\"FP\",\"FN\",\"TN\",counts,rates,\"ROC_AUC\",\"averagePrecision\",\"PRTrapezoidWithInitialPrecisionOne\",\"ECE\",\"reliability\",\"resolution\",\"uncertainty\",\"withinBinCorrection\",\"BrierIdentityResidual\")){\n   unit<-if(k%in%c(\"TP\",\"FP\",\"FN\",\"TN\",counts))\"rows\"else if(k==\"totalCost\")\"hypothetical cost units\"else if(k==\"meanCost\")\"hypothetical cost units/mass\"else if(k==\"BrierSum\")\"sum squared-probability loss\"else\"dimensionless\"\n   add(\"test-metrics\",tagrow(kind,scenario=name,metric=k,valueExact=\"\",valueApprox=fmt(m[[k]]),unit=unit))\n  }\n  lev<-unique(d$group[test][!is.na(d$group[test])]);sets<-c(list(test),lapply(lev,function(g)test[!is.na(d$group[test])&d$group[test]==g]),list(test[is.na(d$group[test])]))\n  types<-c(\"overall\",rep(\"known\",length(lev)),\"unknown\");tokens<-c(\"all\",lev,\"\")\n  for(j in seq_along(sets)){ids<-sets[[j]];m<-measure(d,p,ids,chosen,cost);cell<-setNames(lapply(c(\"TP\",\"FP\",\"FN\",\"TN\"),function(k)fmt(m[[k]])),paste0(c(\"TP\",\"FP\",\"FN\",\"TN\"),\"Exact\"));add(\"group-metrics\",c(tagrow(kind,scenario=name,groupType=types[j],groupToken=tokens[j],retainedRows=length(ids)),cell,scalars(m,c(counts,rates))));if(types[j]==\"known\")point(kind,\"group-TPR\",name,j-2,j-2,m$TPR,\"declared group position\",\"TPR\",tag=tokens[j])}\n }\n invisible(NULL)\n}\n\n# Fixed finite inputs only; not the complete web input/budget validator.\nqnum<-function(v){if(is.null(v))return(NA_real_);if(is.logical(v))return(as.numeric(v));s<-as.character(v);if(grepl(\"/\",s,fixed=TRUE)){a<-strsplit(s,\"/\",fixed=TRUE)[[1]];return(as.numeric(a[1])/as.numeric(a[2]))};as.numeric(s)}\nrowsG<-function(raw){\n n<-length(raw);get<-function(r,k,default=NULL)if(is.null(r[[k]]))default else r[[k]]\n id<-vapply(raw,function(r)as.character(r$id),character(1));p<-vapply(raw,function(r)qnum(r$score),numeric(1));y<-vapply(raw,function(r)qnum(r$y),numeric(1));w<-vapply(raw,function(r)qnum(get(r,\"weight\",\"1\")),numeric(1));role<-vapply(raw,function(r)get(r,\"role\",\"evaluation\"),character(1));group<-vapply(raw,function(r)as.character(get(r,\"group\",NA_character_)),character(1))\n stopifnot(all(w>=0),all(is.na(p)|(p>=0&p<=1)),all(is.na(y)|y%in%c(0,1)),!anyDuplicated(id));list(id=id,p=p,y=y,w=w,role=role,group=group,eligible=!is.na(p)&!is.na(y)&w>0&role!=\"excluded\")\n}\nscopeG<-function(d,role=\"all\")if(role==\"all\")seq_along(d$id)else which(d$role==role)\nmetricsG<-function(d,ids,t=.5,cost=c(1,1)){\n use<-ids[d$eligible[ids]];p<-d$p[use];y<-d$y[use];w<-d$w[use];a<-if(is.character(t))rep(t==\"always-positive\",length(use))else p>=t\n TP<-sum(w[a&y==1]);FP<-sum(w[a&y==0]);FN<-sum(w[!a&y==1]);TN<-sum(w[!a&y==0]);P<-TP+FN;N<-FP+TN;W<-P+N;PP<-TP+FP;PN<-TN+FN;TPR<-ratio(TP,P);TNR<-ratio(TN,N);bs<-sum(w*(p-y)^2);tc<-FP*cost[1]+FN*cost[2]\n list(confusion=list(TP=TP,FP=FP,FN=FN,TN=TN),mass=W,positiveTargetMass=P,negativeTargetMass=N,predictedPositiveMass=PP,predictedNegativeMass=PN,prevalence=ratio(P,W),selectionRate=ratio(PP,W),accuracy=ratio(TP+TN,W),precision=ratio(TP,PP),negativePredictiveValue=ratio(TN,PN),TPR=TPR,FPR=ratio(FP,N),TNR=TNR,FNR=ratio(FN,P),F1=ratio(2*TP,2*TP+FP+FN),balancedAccuracy=if(is.na(TPR)||is.na(TNR))NA_real_ else(TPR+TNR)/2,Brier=ratio(bs,W),BrierSum=bs,totalCost=tc,meanCost=ratio(tc,W),bayesThreshold=ratio(cost[1],sum(cost)))\n}\ncurvesG<-function(d,ids){\n use<-ids[d$eligible[ids]];grid<-c(list(\"always-negative\"),as.list(sort(unique(d$p[use]),decreasing=TRUE)));points<-lapply(grid,function(t){m<-metricsG(d,ids,t);c(list(policy=t),m$confusion,m[c(\"TPR\",\"FPR\",\"precision\")],list(recall=m$TPR))});pos<-use[d$y[use]==1];neg<-use[d$y[use]==0];P<-sum(d$w[pos]);N<-sum(d$w[neg]);U<-0\n for(i in pos)U<-U+d$w[i]*sum(d$w[neg]*((d$p[i]>d$p[neg])+.5*(d$p[i]==d$p[neg])))\n AP<-trap<-lastR<-0;lastP<-1\n if(P&&length(grid)>1)for(j in 2:length(grid)){z<-points[[j]];AP<-AP+(z$recall-lastR)*z$precision;trap<-trap+(z$recall-lastR)*(z$precision+lastP)/2;lastR<-z$recall;lastP<-z$precision}\n list(points=points,ROC_AUC=ratio(U,P*N),averagePrecision=if(P)AP else NA_real_,PRTrapezoidWithInitialPrecisionOne=if(P)trap else NA_real_)\n}\nchooseG<-function(d,a,cost){\n role<-if(is.null(a$selectionRole))\"validation\"else a$selectionRole;er<-if(is.null(a$evaluationRole))\"test\"else a$evaluationRole;ids<-scopeG(d,role);use<-ids[d$eligible[ids]];stopifnot(length(use)>0);grid<-if(is.null(a$thresholds))c(list(\"always-negative\"),as.list(sort(unique(d$p[use]),decreasing=TRUE)))else lapply(a$thresholds,function(t)if(t%in%c(\"always-negative\",\"always-positive\"))t else qnum(t))\n candidates<-lapply(seq_along(grid),function(j){m<-metricsG(d,ids,grid[[j]],cost);feasible<-TRUE;if(!is.null(a$minTPR))feasible<-feasible&&!is.na(m$TPR)&&m$TPR>=qnum(a$minTPR);if(!is.null(a$maxFPR))feasible<-feasible&&!is.na(m$FPR)&&m$FPR<=qnum(a$maxFPR);list(index=j-1,policy=grid[[j]],metrics=m,feasible=feasible)})\n good<-which(vapply(candidates,function(c)c$feasible,logical(1)));best<-NA_integer_;if(length(good)){v<-vapply(candidates[good],function(c)c$metrics$meanCost,numeric(1));best<-good[which(v<=min(v)+1e-12)[1]]}\n list(selectedIndex=if(is.na(best))NA_integer_ else best-1,selectedPolicy=if(is.na(best))NULL else grid[[best]],selectedValidation=if(is.na(best))NULL else candidates[[best]]$metrics,candidates=candidates,evaluation=if(is.na(best)||er==\"none\")NULL else metricsG(d,scopeG(d,er),grid[[best]],cost))\n}\ncalibrateG<-function(d,ids,edges){\n use<-ids[d$eligible[ids]];W<-sum(d$w[use]);pi<-ratio(sum(d$w[use]*d$y[use]),W);bins<-list();ECE<-rel<-res<-correction<-0;assign<-findInterval(d$p[use],edges,rightmost.closed=TRUE,all.inside=TRUE)\n for(b in seq_len(length(edges)-1)){rr<-use[assign==b];w<-sum(d$w[rr]);mp<-ratio(sum(d$w[rr]*d$p[rr]),w);o<-ratio(sum(d$w[rr]*d$y[rr]),w);variance<-if(w)sum(d$w[rr]*(d$p[rr]-mp)^2)/w else NA_real_;covariance<-if(w)sum(d$w[rr]*(d$p[rr]-mp)*(d$y[rr]-o))/w else NA_real_;bc<-variance-2*covariance;gap<-mp-o;bins[[b]]<-list(index=b-1,mass=w,meanPrediction=mp,eventRate=o,scoreVariance=variance,scoreTargetCovariance=covariance,withinBinCorrection=bc,ids=d$id[rr])\n  if(w){s<-w/W;ECE<-ECE+s*abs(gap);rel<-rel+s*gap^2;res<-res+s*(o-pi)^2;correction<-correction+s*bc}\n };bs<-ratio(sum(d$w[use]*(d$p[use]-d$y[use])^2),W);unc<-pi*(1-pi);list(bins=bins,Brier=bs,ECE=if(W)ECE else NA_real_,uncertainty=unc,reliability=if(W)rel else NA_real_,resolution=if(W)res else NA_real_,withinBinCorrection=if(W)correction else NA_real_,BrierIdentityResidual=bs-(unc-res+rel+correction))\n}\ngroupsG<-function(d,ids,t,cost){\n lev<-unique(d$group[ids][!is.na(d$group[ids])]);groups<-lapply(lev,function(g)list(group=g,metrics=metricsG(d,ids[!is.na(d$group[ids])&d$group[ids]==g],t,cost)));overall<-metricsG(d,ids,t,cost);unknown<-metricsG(d,ids[is.na(d$group[ids])],t,cost);gaps<-list()\n for(k in c(\"prevalence\",\"selectionRate\",\"TPR\",\"FPR\",\"precision\",\"accuracy\",\"meanCost\")){use<-Filter(function(g)g$metrics$mass>0,groups);v<-vapply(use,function(g)g$metrics[[k]],numeric(1));gaps[[k]]<-if(length(use)<2||anyNA(v))NA_real_ else max(v)-min(v)}\n list(overall=overall,groups=groups,unknownGroup=unknown,gaps=gaps,partitionMassResidual=overall$mass-unknown$mass-sum(vapply(groups,function(g)g$metrics$mass,numeric(1))))\n}\nsvgFixed<-function(file,points,title,xlabel,ylabel,legend){\n finite<-points[points$y!=\"undefined\"&points$x!=\"undefined\",,drop=FALSE];x<-as.numeric(finite$x);y<-as.numeric(finite$y);xmin<-if(length(x))min(x)else 0;xmax<-if(length(x))max(x)else 1;ymin<-min(c(0,y));ymax<-max(c(0,y));if(xmin==xmax){xmin<-xmin-.5;xmax<-xmax+.5};if(ymin==ymax)ymax<-ymin+1;X<-function(v)85+(v-xmin)/(xmax-xmin)*480;Y<-function(v)278-(v-ymin)/(ymax-ymin)*175\n esc<-function(s){s<-gsub(\"&\",\"&amp;\",s,fixed=TRUE);s<-gsub(\"<\",\"&lt;\",s,fixed=TRUE);gsub(\">\",\"&gt;\",s,fixed=TRUE)};s<-'<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"620\" height=\"360\" viewBox=\"0 0 620 360\"><rect width=\"620\" height=\"360\" fill=\"white\"/><g font-family=\"Arial, sans-serif\" font-size=\"13\" fill=\"#17324d\">'\n lines<-strwrap(title,width=65);for(i in seq_along(lines))s<-paste0(s,'<text x=\"25\" y=\"',24+(i-1)*18,'\">',esc(lines[i]),'</text>');colors<-c(\"#176b9b\",\"#b85e18\",\"#437e4d\")\n for(i in seq_along(legend))s<-paste0(s,'<circle cx=\"',30+(i-1)*250,'\" cy=\"76\" r=\"4\" fill=\"',colors[(i-1)%%3+1],'\"/><text x=\"',42+(i-1)*250,'\" y=\"80\">',esc(legend[i]),'</text>')\n s<-paste0(s,'<path d=\"M85 98V278H575\" fill=\"none\" stroke=\"#52677d\"/><text text-anchor=\"middle\" x=\"325\" y=\"338\">',esc(xlabel),'</text><text text-anchor=\"middle\" transform=\"translate(21,190) rotate(-90)\">',esc(ylabel),'</text>')\n for(i in 0:4){xx<-xmin+(xmax-xmin)*i/4;yy<-ymin+(ymax-ymin)*i/4;s<-paste0(s,'<text text-anchor=\"middle\" x=\"',sprintf(\"%.9g\",X(xx)),'\" y=\"305\">',sprintf(\"%.4g\",xx),'</text><text text-anchor=\"end\" x=\"77\" y=\"',sprintf(\"%.9g\",Y(yy)+4),'\">',sprintf(\"%.4g\",yy),'</text>')}\n for(i in seq_len(nrow(finite)))s<-paste0(s,'<circle cx=\"',sprintf(\"%.9g\",X(x[i])),'\" cy=\"',sprintf(\"%.9g\",Y(y[i])),'\" r=\"3\" fill=\"',colors[as.integer(finite$series[i])%%3+1],'\"/>');writeLines(paste0(s,'</g></svg>'),file,useBytes=TRUE)\n}\nfixedRun<-function(){\n api<-FIXED$api;a<-FIXED$args;summary<-list();points<-list();xlabel<-\"Declared index\";ylabel<-\"Value\";legend<-\"Declared result\"\n metric<-function(name,v,unit=\"dimensionless\"){if(is.null(v))v<-NA_real_;summary[[length(summary)+1L]]<<-data.frame(metric=name,value=if(is.na(v))\"undefined\"else sprintf(\"%.9g\",v),exactValue=\"\",unit=unit,defined=as.integer(!is.na(v)),stringsAsFactors=FALSE)}\n pt<-function(i,x,y,id=\"\",series=0){points[[length(points)+1L]]<<-data.frame(series=series,index=i,xExact=\"\",x=if(is.na(x))\"undefined\"else sprintf(\"%.9g\",x),yExact=\"\",y=if(is.na(y))\"undefined\"else sprintf(\"%.9g\",y),id=as.character(id),stringsAsFactors=FALSE)}\n if(api==\"realdata\"){\n  native<-loadData()[[a$kind]];fit<-fitmodel(native);d<-list(id=native$id,p=fit$pred,y=native$y,w=rep(1,length(native$id)),role=native$role,group=native$group,eligible=native$eligible);scenarios<-list()\n  for(j in 1:3){name<-c(\"equal\",\"miss-five\",\"alarm-five\")[j];cst<-list(c(1,1),c(1,5),c(5,1))[[j]];sel<-chooseG(d,list(),cst);scenarios[[j]]<-list(name=name,selection=sel);metric(paste0(name,\"Threshold\"),sel$selectedPolicy);metric(paste0(name,\"TestCost\"),sel$evaluation$meanCost,\"hypothetical cost units/mass\")}\n  ids<-scopeG(d,\"test\");cv<-curvesG(d,ids);cal<-calibrateG(d,ids,seq(0,1,.2));metric(\"testAUC\",cv$ROC_AUC);metric(\"testAP\",cv$averagePrecision);metric(\"testBrier\",cal$Brier);metric(\"eligibleRows\",sum(d$eligible),\"rows\")\n  for(j in seq_along(ids)){i<-ids[j];pt(j-1,j,d$p[i],d$id[i],0);pt(j-1,j,d$y[i],d$id[i],1)}\n  full<-list(kind=a$kind,fit=fit,scenarios=scenarios,testCurves=cv,testCalibration=cal,rowsScored=d);xlabel<-\"Test row, native order\";ylabel<-\"Y or probability\";legend<-c(\"Training-fitted probability\",\"Observed Y\")\n }else{\n  d<-rowsG(a$rows);role<-if(is.null(a$role))\"all\"else a$role;ids<-scopeG(d,role);cost<-if(is.null(a$costs))c(1,1)else c(qnum(a$costs$falsePositive),qnum(a$costs$falseNegative));t<-if(is.null(a$threshold)).5 else if(a$threshold%in%c(\"always-positive\",\"always-negative\"))a$threshold else qnum(a$threshold)\n  if(api==\"metrics\"){\n   full<-metricsG(d,ids,t,cost);for(k in c(\"mass\",\"accuracy\",\"precision\",\"TPR\",\"FPR\",\"F1\",\"Brier\",\"meanCost\"))metric(k,full[[k]],if(k==\"mass\")\"mass\"else if(k==\"meanCost\")\"hypothetical cost units/mass\"else\"dimensionless\");metric(\"BayesThreshold\",full$bayesThreshold)\n   for(i in 1:4)pt(i-1,i-1,full$confusion[[i]],names(full$confusion)[i]);xlabel<-\"TP / FP / FN / TN positions\";ylabel<-\"Analytical mass\"\n  }else if(api==\"curves\"){\n   full<-curvesG(d,ids);for(k in c(\"ROC_AUC\",\"averagePrecision\",\"PRTrapezoidWithInitialPrecisionOne\"))metric(k,full[[k]])\n   for(j in seq_along(full$points)){p<-full$points[[j]];pt(j-1,p$FPR,p$TPR,if(is.character(p$policy))p$policy else sprintf(\"%.17g\",p$policy))};xlabel<-\"False positive rate\";ylabel<-\"True positive rate\";legend<-\"Observed ROC operating points\"\n  }else if(api==\"choose\"){\n   full<-chooseG(d,a,cost);metric(\"selectedIndex\",full$selectedIndex,\"candidate index\");metric(\"minimumCost\",if(is.null(full$selectedValidation))NULL else full$selectedValidation$meanCost,\"hypothetical cost units/mass\");metric(\"feasible\",as.integer(!is.na(full$selectedIndex)),\"indicator\")\n   for(c in full$candidates)pt(c$index,c$index,c$metrics$meanCost,if(is.character(c$policy))c$policy else sprintf(\"%.17g\",c$policy));xlabel<-\"Validation candidate\";ylabel<-\"Assumed cost / mass\";legend<-\"Validation candidate costs\"\n  }else if(api==\"calibrate\"){\n   edges<-if(is.null(a$binEdges))seq(0,1,.2)else vapply(a$binEdges,qnum,numeric(1));full<-calibrateG(d,ids,edges);for(k in c(\"ECE\",\"Brier\",\"uncertainty\",\"resolution\",\"reliability\",\"withinBinCorrection\",\"BrierIdentityResidual\"))metric(k,full[[k]])\n   for(b in full$bins)pt(b$index,b$meanPrediction,b$eventRate,paste0(\"bin:\",b$index));xlabel<-\"Bin mean forecast\";ylabel<-\"Bin event rate\";legend<-\"Binary-event reliability\"\n  }else if(api==\"groups\"){\n   full<-groupsG(d,ids,t,cost);metric(\"overallTPR\",full$overall$TPR);metric(\"TPRGap\",full$gaps$TPR);metric(\"precisionGap\",full$gaps$precision);metric(\"unknownMass\",full$unknownGroup$mass,\"mass\");metric(\"partitionResidual\",full$partitionMassResidual,\"mass\")\n   for(j in seq_along(full$groups))pt(j-1,j-1,full$groups[[j]]$metrics$TPR,full$groups[[j]]$group);xlabel<-\"Declared group position\";ylabel<-\"True positive rate\";legend<-\"Known-group TPR\"\n  }else stop(\"unknown declared fixed API\")\n }\n sm<-do.call(rbind,summary);pp<-do.call(rbind,points);write.csv(sm,file.path(outDir,\"summary.csv\"),row.names=FALSE,na=\"\");write.csv(pp,file.path(outDir,\"plot-points.csv\"),row.names=FALSE,na=\"\");svgFixed(file.path(outDir,\"plot.svg\"),pp,FIXED$title,xlabel,ylabel,legend);dput(list(api=api,variant=FIXED$variant,input=FIXED$args,arithmetic=\"Base-R binary64 fixed example; not an exact rational general validator\",result=full),file=file.path(outDir,\"full.txt\"));cat(\"PASS\",api,FIXED$variant,\"summary\",nrow(sm),\"points\",nrow(pp),\"\\n\")\n}\n\nFIXED<-list(api=\"realdata\",variant=\"person\",args=list(kind=\"person\"),title=\"Actual person fixed train/validation/test procedure\")\nfixedRun()\n",
        "input": {
          "kind": "person"
        },
        "inputFiles": [
          {
            "file": "../ml14-sources/actual64-country-four-indicators-original-2024.csv",
            "sha256": "3d2b655cf807bf3ff049af187a9b7484b4e637f441f6f1925aba7acc5b0c861c"
          },
          {
            "file": "../ml14-sources/actual3613-NLS-original52-fields-groups-roles.csv",
            "sha256": "df404c3ce0336ab3ae2bfdd6b246c6e8acc058fd526ebf950dde270787bcd600"
          },
          {
            "file": "../ml14-sources/actual3150-churn-original14-fields-groups-roles.csv",
            "sha256": "d8af1f4905af8699e3ea024a6998319c82ac97b33ba1dec182391c0b30795023"
          }
        ],
        "returnCode": 0,
        "expectedFailure": false,
        "stdout": "PASS realdata person summary 10 points 1214 \n",
        "stderr": "During startup - Warning messages:\n1: Setting LC_COLLATE=C.UTF-8 failed \n2: Setting LC_CTYPE=C.UTF-8 failed \n3: Setting LC_MONETARY=C.UTF-8 failed \n4: Setting LC_TIME=C.UTF-8 failed \n",
        "summary": {
          "equalThreshold": "0.616564417",
          "equalTestCost": "0.380560132",
          "miss-fiveThreshold": "0.362068966",
          "miss-fiveTestCost": "0.441515651",
          "alarm-fiveThreshold": "0.757575758",
          "alarm-fiveTestCost": "0.477759473",
          "testAUC": "0.674085326",
          "testAP": "0.720385902",
          "testBrier": "0.222886072",
          "eligibleRows": "3017"
        },
        "summaryRows": [
          {
            "metric": "equalThreshold",
            "value": "0.616564417",
            "exactValue": "",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "equalTestCost",
            "value": "0.380560132",
            "exactValue": "",
            "unit": "hypothetical cost units/mass",
            "defined": "1"
          },
          {
            "metric": "miss-fiveThreshold",
            "value": "0.362068966",
            "exactValue": "",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "miss-fiveTestCost",
            "value": "0.441515651",
            "exactValue": "",
            "unit": "hypothetical cost units/mass",
            "defined": "1"
          },
          {
            "metric": "alarm-fiveThreshold",
            "value": "0.757575758",
            "exactValue": "",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "alarm-fiveTestCost",
            "value": "0.477759473",
            "exactValue": "",
            "unit": "hypothetical cost units/mass",
            "defined": "1"
          },
          {
            "metric": "testAUC",
            "value": "0.674085326",
            "exactValue": "",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "testAP",
            "value": "0.720385902",
            "exactValue": "",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "testBrier",
            "value": "0.222886072",
            "exactValue": "",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "eligibleRows",
            "value": "3017",
            "exactValue": "",
            "unit": "rows",
            "defined": "1"
          }
        ],
        "plotPoints": [
          {
            "series": "0",
            "index": "0",
            "xExact": "",
            "x": "1",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:4"
          },
          {
            "series": "1",
            "index": "0",
            "xExact": "",
            "x": "1",
            "yExact": "",
            "y": "0",
            "id": "person:4"
          },
          {
            "series": "0",
            "index": "1",
            "xExact": "",
            "x": "2",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:6"
          },
          {
            "series": "1",
            "index": "1",
            "xExact": "",
            "x": "2",
            "yExact": "",
            "y": "1",
            "id": "person:6"
          },
          {
            "series": "0",
            "index": "2",
            "xExact": "",
            "x": "3",
            "yExact": "",
            "y": "0.667910448",
            "id": "person:18"
          },
          {
            "series": "1",
            "index": "2",
            "xExact": "",
            "x": "3",
            "yExact": "",
            "y": "0",
            "id": "person:18"
          },
          {
            "series": "0",
            "index": "3",
            "xExact": "",
            "x": "4",
            "yExact": "",
            "y": "0.824267782",
            "id": "person:19"
          },
          {
            "series": "1",
            "index": "3",
            "xExact": "",
            "x": "4",
            "yExact": "",
            "y": "1",
            "id": "person:19"
          },
          {
            "series": "0",
            "index": "4",
            "xExact": "",
            "x": "5",
            "yExact": "",
            "y": "0.824267782",
            "id": "person:25"
          },
          {
            "series": "1",
            "index": "4",
            "xExact": "",
            "x": "5",
            "yExact": "",
            "y": "1",
            "id": "person:25"
          },
          {
            "series": "0",
            "index": "5",
            "xExact": "",
            "x": "6",
            "yExact": "",
            "y": "0.667910448",
            "id": "person:27"
          },
          {
            "series": "1",
            "index": "5",
            "xExact": "",
            "x": "6",
            "yExact": "",
            "y": "1",
            "id": "person:27"
          },
          {
            "series": "0",
            "index": "6",
            "xExact": "",
            "x": "7",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:35"
          },
          {
            "series": "1",
            "index": "6",
            "xExact": "",
            "x": "7",
            "yExact": "",
            "y": "0",
            "id": "person:35"
          },
          {
            "series": "0",
            "index": "7",
            "xExact": "",
            "x": "8",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:45"
          },
          {
            "series": "1",
            "index": "7",
            "xExact": "",
            "x": "8",
            "yExact": "",
            "y": "0",
            "id": "person:45"
          },
          {
            "series": "0",
            "index": "8",
            "xExact": "",
            "x": "9",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:46"
          },
          {
            "series": "1",
            "index": "8",
            "xExact": "",
            "x": "9",
            "yExact": "",
            "y": "0",
            "id": "person:46"
          },
          {
            "series": "0",
            "index": "9",
            "xExact": "",
            "x": "10",
            "yExact": "",
            "y": "0.667910448",
            "id": "person:47"
          },
          {
            "series": "1",
            "index": "9",
            "xExact": "",
            "x": "10",
            "yExact": "",
            "y": "1",
            "id": "person:47"
          },
          {
            "series": "0",
            "index": "10",
            "xExact": "",
            "x": "11",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:52"
          },
          {
            "series": "1",
            "index": "10",
            "xExact": "",
            "x": "11",
            "yExact": "",
            "y": "0",
            "id": "person:52"
          },
          {
            "series": "0",
            "index": "11",
            "xExact": "",
            "x": "12",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:61"
          },
          {
            "series": "1",
            "index": "11",
            "xExact": "",
            "x": "12",
            "yExact": "",
            "y": "0",
            "id": "person:61"
          },
          {
            "series": "0",
            "index": "12",
            "xExact": "",
            "x": "13",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:62"
          },
          {
            "series": "1",
            "index": "12",
            "xExact": "",
            "x": "13",
            "yExact": "",
            "y": "1",
            "id": "person:62"
          },
          {
            "series": "0",
            "index": "13",
            "xExact": "",
            "x": "14",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:63"
          },
          {
            "series": "1",
            "index": "13",
            "xExact": "",
            "x": "14",
            "yExact": "",
            "y": "0",
            "id": "person:63"
          },
          {
            "series": "0",
            "index": "14",
            "xExact": "",
            "x": "15",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:64"
          },
          {
            "series": "1",
            "index": "14",
            "xExact": "",
            "x": "15",
            "yExact": "",
            "y": "1",
            "id": "person:64"
          },
          {
            "series": "0",
            "index": "15",
            "xExact": "",
            "x": "16",
            "yExact": "",
            "y": "0.824267782",
            "id": "person:65"
          },
          {
            "series": "1",
            "index": "15",
            "xExact": "",
            "x": "16",
            "yExact": "",
            "y": "1",
            "id": "person:65"
          },
          {
            "series": "0",
            "index": "16",
            "xExact": "",
            "x": "17",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:90"
          },
          {
            "series": "1",
            "index": "16",
            "xExact": "",
            "x": "17",
            "yExact": "",
            "y": "0",
            "id": "person:90"
          },
          {
            "series": "0",
            "index": "17",
            "xExact": "",
            "x": "18",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:92"
          },
          {
            "series": "1",
            "index": "17",
            "xExact": "",
            "x": "18",
            "yExact": "",
            "y": "0",
            "id": "person:92"
          },
          {
            "series": "0",
            "index": "18",
            "xExact": "",
            "x": "19",
            "yExact": "",
            "y": "0.667910448",
            "id": "person:95"
          },
          {
            "series": "1",
            "index": "18",
            "xExact": "",
            "x": "19",
            "yExact": "",
            "y": "1",
            "id": "person:95"
          },
          {
            "series": "0",
            "index": "19",
            "xExact": "",
            "x": "20",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:96"
          },
          {
            "series": "1",
            "index": "19",
            "xExact": "",
            "x": "20",
            "yExact": "",
            "y": "1",
            "id": "person:96"
          },
          {
            "series": "0",
            "index": "20",
            "xExact": "",
            "x": "21",
            "yExact": "",
            "y": "0.824267782",
            "id": "person:97"
          },
          {
            "series": "1",
            "index": "20",
            "xExact": "",
            "x": "21",
            "yExact": "",
            "y": "1",
            "id": "person:97"
          },
          {
            "series": "0",
            "index": "21",
            "xExact": "",
            "x": "22",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:106"
          },
          {
            "series": "1",
            "index": "21",
            "xExact": "",
            "x": "22",
            "yExact": "",
            "y": "0",
            "id": "person:106"
          },
          {
            "series": "0",
            "index": "22",
            "xExact": "",
            "x": "23",
            "yExact": "",
            "y": "0.667910448",
            "id": "person:108"
          },
          {
            "series": "1",
            "index": "22",
            "xExact": "",
            "x": "23",
            "yExact": "",
            "y": "1",
            "id": "person:108"
          },
          {
            "series": "0",
            "index": "23",
            "xExact": "",
            "x": "24",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:113"
          },
          {
            "series": "1",
            "index": "23",
            "xExact": "",
            "x": "24",
            "yExact": "",
            "y": "1",
            "id": "person:113"
          },
          {
            "series": "0",
            "index": "24",
            "xExact": "",
            "x": "25",
            "yExact": "",
            "y": "0.824267782",
            "id": "person:120"
          },
          {
            "series": "1",
            "index": "24",
            "xExact": "",
            "x": "25",
            "yExact": "",
            "y": "1",
            "id": "person:120"
          },
          {
            "series": "0",
            "index": "25",
            "xExact": "",
            "x": "26",
            "yExact": "",
            "y": "0.824267782",
            "id": "person:122"
          },
          {
            "series": "1",
            "index": "25",
            "xExact": "",
            "x": "26",
            "yExact": "",
            "y": "1",
            "id": "person:122"
          },
          {
            "series": "0",
            "index": "26",
            "xExact": "",
            "x": "27",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:132"
          },
          {
            "series": "1",
            "index": "26",
            "xExact": "",
            "x": "27",
            "yExact": "",
            "y": "0",
            "id": "person:132"
          },
          {
            "series": "0",
            "index": "27",
            "xExact": "",
            "x": "28",
            "yExact": "",
            "y": "0.824267782",
            "id": "person:140"
          },
          {
            "series": "1",
            "index": "27",
            "xExact": "",
            "x": "28",
            "yExact": "",
            "y": "1",
            "id": "person:140"
          },
          {
            "series": "0",
            "index": "28",
            "xExact": "",
            "x": "29",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:146"
          },
          {
            "series": "1",
            "index": "28",
            "xExact": "",
            "x": "29",
            "yExact": "",
            "y": "0",
            "id": "person:146"
          },
          {
            "series": "0",
            "index": "29",
            "xExact": "",
            "x": "30",
            "yExact": "",
            "y": "0.667910448",
            "id": "person:148"
          },
          {
            "series": "1",
            "index": "29",
            "xExact": "",
            "x": "30",
            "yExact": "",
            "y": "1",
            "id": "person:148"
          },
          {
            "series": "0",
            "index": "30",
            "xExact": "",
            "x": "31",
            "yExact": "",
            "y": "0.824267782",
            "id": "person:150"
          },
          {
            "series": "1",
            "index": "30",
            "xExact": "",
            "x": "31",
            "yExact": "",
            "y": "1",
            "id": "person:150"
          },
          {
            "series": "0",
            "index": "31",
            "xExact": "",
            "x": "32",
            "yExact": "",
            "y": "0.824267782",
            "id": "person:151"
          },
          {
            "series": "1",
            "index": "31",
            "xExact": "",
            "x": "32",
            "yExact": "",
            "y": "1",
            "id": "person:151"
          },
          {
            "series": "0",
            "index": "32",
            "xExact": "",
            "x": "33",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:156"
          },
          {
            "series": "1",
            "index": "32",
            "xExact": "",
            "x": "33",
            "yExact": "",
            "y": "1",
            "id": "person:156"
          },
          {
            "series": "0",
            "index": "33",
            "xExact": "",
            "x": "34",
            "yExact": "",
            "y": "0.824267782",
            "id": "person:160"
          },
          {
            "series": "1",
            "index": "33",
            "xExact": "",
            "x": "34",
            "yExact": "",
            "y": "1",
            "id": "person:160"
          },
          {
            "series": "0",
            "index": "34",
            "xExact": "",
            "x": "35",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:164"
          },
          {
            "series": "1",
            "index": "34",
            "xExact": "",
            "x": "35",
            "yExact": "",
            "y": "1",
            "id": "person:164"
          },
          {
            "series": "0",
            "index": "35",
            "xExact": "",
            "x": "36",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:170"
          },
          {
            "series": "1",
            "index": "35",
            "xExact": "",
            "x": "36",
            "yExact": "",
            "y": "1",
            "id": "person:170"
          },
          {
            "series": "0",
            "index": "36",
            "xExact": "",
            "x": "37",
            "yExact": "",
            "y": "0.667910448",
            "id": "person:171"
          },
          {
            "series": "1",
            "index": "36",
            "xExact": "",
            "x": "37",
            "yExact": "",
            "y": "1",
            "id": "person:171"
          },
          {
            "series": "0",
            "index": "37",
            "xExact": "",
            "x": "38",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:176"
          },
          {
            "series": "1",
            "index": "37",
            "xExact": "",
            "x": "38",
            "yExact": "",
            "y": "0",
            "id": "person:176"
          },
          {
            "series": "0",
            "index": "38",
            "xExact": "",
            "x": "39",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:183"
          },
          {
            "series": "1",
            "index": "38",
            "xExact": "",
            "x": "39",
            "yExact": "",
            "y": "0",
            "id": "person:183"
          },
          {
            "series": "0",
            "index": "39",
            "xExact": "",
            "x": "40",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:185"
          },
          {
            "series": "1",
            "index": "39",
            "xExact": "",
            "x": "40",
            "yExact": "",
            "y": "0",
            "id": "person:185"
          },
          {
            "series": "0",
            "index": "40",
            "xExact": "",
            "x": "41",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:188"
          },
          {
            "series": "1",
            "index": "40",
            "xExact": "",
            "x": "41",
            "yExact": "",
            "y": "1",
            "id": "person:188"
          },
          {
            "series": "0",
            "index": "41",
            "xExact": "",
            "x": "42",
            "yExact": "",
            "y": "0.667910448",
            "id": "person:191"
          },
          {
            "series": "1",
            "index": "41",
            "xExact": "",
            "x": "42",
            "yExact": "",
            "y": "1",
            "id": "person:191"
          },
          {
            "series": "0",
            "index": "42",
            "xExact": "",
            "x": "43",
            "yExact": "",
            "y": "0.667910448",
            "id": "person:204"
          },
          {
            "series": "1",
            "index": "42",
            "xExact": "",
            "x": "43",
            "yExact": "",
            "y": "0",
            "id": "person:204"
          },
          {
            "series": "0",
            "index": "43",
            "xExact": "",
            "x": "44",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:206"
          },
          {
            "series": "1",
            "index": "43",
            "xExact": "",
            "x": "44",
            "yExact": "",
            "y": "1",
            "id": "person:206"
          },
          {
            "series": "0",
            "index": "44",
            "xExact": "",
            "x": "45",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:212"
          },
          {
            "series": "1",
            "index": "44",
            "xExact": "",
            "x": "45",
            "yExact": "",
            "y": "0",
            "id": "person:212"
          },
          {
            "series": "0",
            "index": "45",
            "xExact": "",
            "x": "46",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:227"
          },
          {
            "series": "1",
            "index": "45",
            "xExact": "",
            "x": "46",
            "yExact": "",
            "y": "0",
            "id": "person:227"
          },
          {
            "series": "0",
            "index": "46",
            "xExact": "",
            "x": "47",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:230"
          },
          {
            "series": "1",
            "index": "46",
            "xExact": "",
            "x": "47",
            "yExact": "",
            "y": "1",
            "id": "person:230"
          },
          {
            "series": "0",
            "index": "47",
            "xExact": "",
            "x": "48",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:254"
          },
          {
            "series": "1",
            "index": "47",
            "xExact": "",
            "x": "48",
            "yExact": "",
            "y": "1",
            "id": "person:254"
          },
          {
            "series": "0",
            "index": "48",
            "xExact": "",
            "x": "49",
            "yExact": "",
            "y": "0.667910448",
            "id": "person:256"
          },
          {
            "series": "1",
            "index": "48",
            "xExact": "",
            "x": "49",
            "yExact": "",
            "y": "1",
            "id": "person:256"
          },
          {
            "series": "0",
            "index": "49",
            "xExact": "",
            "x": "50",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:265"
          },
          {
            "series": "1",
            "index": "49",
            "xExact": "",
            "x": "50",
            "yExact": "",
            "y": "1",
            "id": "person:265"
          },
          {
            "series": "0",
            "index": "50",
            "xExact": "",
            "x": "51",
            "yExact": "",
            "y": "0.824267782",
            "id": "person:270"
          },
          {
            "series": "1",
            "index": "50",
            "xExact": "",
            "x": "51",
            "yExact": "",
            "y": "1",
            "id": "person:270"
          },
          {
            "series": "0",
            "index": "51",
            "xExact": "",
            "x": "52",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:272"
          },
          {
            "series": "1",
            "index": "51",
            "xExact": "",
            "x": "52",
            "yExact": "",
            "y": "0",
            "id": "person:272"
          },
          {
            "series": "0",
            "index": "52",
            "xExact": "",
            "x": "53",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:275"
          },
          {
            "series": "1",
            "index": "52",
            "xExact": "",
            "x": "53",
            "yExact": "",
            "y": "0",
            "id": "person:275"
          },
          {
            "series": "0",
            "index": "53",
            "xExact": "",
            "x": "54",
            "yExact": "",
            "y": "0.667910448",
            "id": "person:278"
          },
          {
            "series": "1",
            "index": "53",
            "xExact": "",
            "x": "54",
            "yExact": "",
            "y": "1",
            "id": "person:278"
          },
          {
            "series": "0",
            "index": "54",
            "xExact": "",
            "x": "55",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:279"
          },
          {
            "series": "1",
            "index": "54",
            "xExact": "",
            "x": "55",
            "yExact": "",
            "y": "0",
            "id": "person:279"
          },
          {
            "series": "0",
            "index": "55",
            "xExact": "",
            "x": "56",
            "yExact": "",
            "y": "0.824267782",
            "id": "person:297"
          },
          {
            "series": "1",
            "index": "55",
            "xExact": "",
            "x": "56",
            "yExact": "",
            "y": "1",
            "id": "person:297"
          },
          {
            "series": "0",
            "index": "56",
            "xExact": "",
            "x": "57",
            "yExact": "",
            "y": "0.667910448",
            "id": "person:298"
          },
          {
            "series": "1",
            "index": "56",
            "xExact": "",
            "x": "57",
            "yExact": "",
            "y": "1",
            "id": "person:298"
          },
          {
            "series": "0",
            "index": "57",
            "xExact": "",
            "x": "58",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:300"
          },
          {
            "series": "1",
            "index": "57",
            "xExact": "",
            "x": "58",
            "yExact": "",
            "y": "1",
            "id": "person:300"
          },
          {
            "series": "0",
            "index": "58",
            "xExact": "",
            "x": "59",
            "yExact": "",
            "y": "0.667910448",
            "id": "person:318"
          },
          {
            "series": "1",
            "index": "58",
            "xExact": "",
            "x": "59",
            "yExact": "",
            "y": "1",
            "id": "person:318"
          },
          {
            "series": "0",
            "index": "59",
            "xExact": "",
            "x": "60",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:324"
          },
          {
            "series": "1",
            "index": "59",
            "xExact": "",
            "x": "60",
            "yExact": "",
            "y": "1",
            "id": "person:324"
          },
          {
            "series": "0",
            "index": "60",
            "xExact": "",
            "x": "61",
            "yExact": "",
            "y": "0.667910448",
            "id": "person:325"
          },
          {
            "series": "1",
            "index": "60",
            "xExact": "",
            "x": "61",
            "yExact": "",
            "y": "1",
            "id": "person:325"
          },
          {
            "series": "0",
            "index": "61",
            "xExact": "",
            "x": "62",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:328"
          },
          {
            "series": "1",
            "index": "61",
            "xExact": "",
            "x": "62",
            "yExact": "",
            "y": "0",
            "id": "person:328"
          },
          {
            "series": "0",
            "index": "62",
            "xExact": "",
            "x": "63",
            "yExact": "",
            "y": "0.362068966",
            "id": "person:341"
          },
          {
            "series": "1",
            "index": "62",
            "xExact": "",
            "x": "63",
            "yExact": "",
            "y": "1",
            "id": "person:341"
          },
          {
            "series": "0",
            "index": "63",
            "xExact": "",
            "x": "64",
            "yExact": "",
            "y": "0.487804878",
            "id": "person:346"
          },
          {
            "series": "1",
            "index": "63",
            "xExact": "",
            "x": "64",
            "yExact": "",
            "y": "1",
            "id": "person:346"
          },
          {
            "series": "0",
            "index": "64",
            "xExact": "",
            "x": "65",
            "yExact": "",
            "y": "0.487804878",
            "id": "person:352"
          },
          {
            "series": "1",
            "index": "64",
            "xExact": "",
            "x": "65",
            "yExact": "",
            "y": "0",
            "id": "person:352"
          },
          {
            "series": "0",
            "index": "65",
            "xExact": "",
            "x": "66",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:354"
          },
          {
            "series": "1",
            "index": "65",
            "xExact": "",
            "x": "66",
            "yExact": "",
            "y": "0",
            "id": "person:354"
          },
          {
            "series": "0",
            "index": "66",
            "xExact": "",
            "x": "67",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:355"
          },
          {
            "series": "1",
            "index": "66",
            "xExact": "",
            "x": "67",
            "yExact": "",
            "y": "0",
            "id": "person:355"
          },
          {
            "series": "0",
            "index": "67",
            "xExact": "",
            "x": "68",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:366"
          },
          {
            "series": "1",
            "index": "67",
            "xExact": "",
            "x": "68",
            "yExact": "",
            "y": "1",
            "id": "person:366"
          },
          {
            "series": "0",
            "index": "68",
            "xExact": "",
            "x": "69",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:368"
          },
          {
            "series": "1",
            "index": "68",
            "xExact": "",
            "x": "69",
            "yExact": "",
            "y": "0",
            "id": "person:368"
          },
          {
            "series": "0",
            "index": "69",
            "xExact": "",
            "x": "70",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:369"
          },
          {
            "series": "1",
            "index": "69",
            "xExact": "",
            "x": "70",
            "yExact": "",
            "y": "1",
            "id": "person:369"
          },
          {
            "series": "0",
            "index": "70",
            "xExact": "",
            "x": "71",
            "yExact": "",
            "y": "0.824267782",
            "id": "person:407"
          },
          {
            "series": "1",
            "index": "70",
            "xExact": "",
            "x": "71",
            "yExact": "",
            "y": "1",
            "id": "person:407"
          },
          {
            "series": "0",
            "index": "71",
            "xExact": "",
            "x": "72",
            "yExact": "",
            "y": "0.667910448",
            "id": "person:414"
          },
          {
            "series": "1",
            "index": "71",
            "xExact": "",
            "x": "72",
            "yExact": "",
            "y": "1",
            "id": "person:414"
          },
          {
            "series": "0",
            "index": "72",
            "xExact": "",
            "x": "73",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:423"
          },
          {
            "series": "1",
            "index": "72",
            "xExact": "",
            "x": "73",
            "yExact": "",
            "y": "0",
            "id": "person:423"
          },
          {
            "series": "0",
            "index": "73",
            "xExact": "",
            "x": "74",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:426"
          },
          {
            "series": "1",
            "index": "73",
            "xExact": "",
            "x": "74",
            "yExact": "",
            "y": "0",
            "id": "person:426"
          },
          {
            "series": "0",
            "index": "74",
            "xExact": "",
            "x": "75",
            "yExact": "",
            "y": "0.667910448",
            "id": "person:439"
          },
          {
            "series": "1",
            "index": "74",
            "xExact": "",
            "x": "75",
            "yExact": "",
            "y": "0",
            "id": "person:439"
          },
          {
            "series": "0",
            "index": "75",
            "xExact": "",
            "x": "76",
            "yExact": "",
            "y": "0.824267782",
            "id": "person:440"
          },
          {
            "series": "1",
            "index": "75",
            "xExact": "",
            "x": "76",
            "yExact": "",
            "y": "1",
            "id": "person:440"
          },
          {
            "series": "0",
            "index": "76",
            "xExact": "",
            "x": "77",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:457"
          },
          {
            "series": "1",
            "index": "76",
            "xExact": "",
            "x": "77",
            "yExact": "",
            "y": "1",
            "id": "person:457"
          },
          {
            "series": "0",
            "index": "77",
            "xExact": "",
            "x": "78",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:464"
          },
          {
            "series": "1",
            "index": "77",
            "xExact": "",
            "x": "78",
            "yExact": "",
            "y": "1",
            "id": "person:464"
          },
          {
            "series": "0",
            "index": "78",
            "xExact": "",
            "x": "79",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:480"
          },
          {
            "series": "1",
            "index": "78",
            "xExact": "",
            "x": "79",
            "yExact": "",
            "y": "1",
            "id": "person:480"
          },
          {
            "series": "0",
            "index": "79",
            "xExact": "",
            "x": "80",
            "yExact": "",
            "y": "0.824267782",
            "id": "person:489"
          },
          {
            "series": "1",
            "index": "79",
            "xExact": "",
            "x": "80",
            "yExact": "",
            "y": "1",
            "id": "person:489"
          },
          {
            "series": "0",
            "index": "80",
            "xExact": "",
            "x": "81",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:494"
          },
          {
            "series": "1",
            "index": "80",
            "xExact": "",
            "x": "81",
            "yExact": "",
            "y": "1",
            "id": "person:494"
          },
          {
            "series": "0",
            "index": "81",
            "xExact": "",
            "x": "82",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:497"
          },
          {
            "series": "1",
            "index": "81",
            "xExact": "",
            "x": "82",
            "yExact": "",
            "y": "0",
            "id": "person:497"
          },
          {
            "series": "0",
            "index": "82",
            "xExact": "",
            "x": "83",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:502"
          },
          {
            "series": "1",
            "index": "82",
            "xExact": "",
            "x": "83",
            "yExact": "",
            "y": "1",
            "id": "person:502"
          },
          {
            "series": "0",
            "index": "83",
            "xExact": "",
            "x": "84",
            "yExact": "",
            "y": "0.824267782",
            "id": "person:504"
          },
          {
            "series": "1",
            "index": "83",
            "xExact": "",
            "x": "84",
            "yExact": "",
            "y": "1",
            "id": "person:504"
          },
          {
            "series": "0",
            "index": "84",
            "xExact": "",
            "x": "85",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:506"
          },
          {
            "series": "1",
            "index": "84",
            "xExact": "",
            "x": "85",
            "yExact": "",
            "y": "0",
            "id": "person:506"
          },
          {
            "series": "0",
            "index": "85",
            "xExact": "",
            "x": "86",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:508"
          },
          {
            "series": "1",
            "index": "85",
            "xExact": "",
            "x": "86",
            "yExact": "",
            "y": "1",
            "id": "person:508"
          },
          {
            "series": "0",
            "index": "86",
            "xExact": "",
            "x": "87",
            "yExact": "",
            "y": "0.824267782",
            "id": "person:510"
          },
          {
            "series": "1",
            "index": "86",
            "xExact": "",
            "x": "87",
            "yExact": "",
            "y": "1",
            "id": "person:510"
          },
          {
            "series": "0",
            "index": "87",
            "xExact": "",
            "x": "88",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:513"
          },
          {
            "series": "1",
            "index": "87",
            "xExact": "",
            "x": "88",
            "yExact": "",
            "y": "0",
            "id": "person:513"
          },
          {
            "series": "0",
            "index": "88",
            "xExact": "",
            "x": "89",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:526"
          },
          {
            "series": "1",
            "index": "88",
            "xExact": "",
            "x": "89",
            "yExact": "",
            "y": "0",
            "id": "person:526"
          },
          {
            "series": "0",
            "index": "89",
            "xExact": "",
            "x": "90",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:528"
          },
          {
            "series": "1",
            "index": "89",
            "xExact": "",
            "x": "90",
            "yExact": "",
            "y": "1",
            "id": "person:528"
          },
          {
            "series": "0",
            "index": "90",
            "xExact": "",
            "x": "91",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:537"
          },
          {
            "series": "1",
            "index": "90",
            "xExact": "",
            "x": "91",
            "yExact": "",
            "y": "0",
            "id": "person:537"
          },
          {
            "series": "0",
            "index": "91",
            "xExact": "",
            "x": "92",
            "yExact": "",
            "y": "0.824267782",
            "id": "person:543"
          },
          {
            "series": "1",
            "index": "91",
            "xExact": "",
            "x": "92",
            "yExact": "",
            "y": "1",
            "id": "person:543"
          },
          {
            "series": "0",
            "index": "92",
            "xExact": "",
            "x": "93",
            "yExact": "",
            "y": "0.824267782",
            "id": "person:554"
          },
          {
            "series": "1",
            "index": "92",
            "xExact": "",
            "x": "93",
            "yExact": "",
            "y": "1",
            "id": "person:554"
          },
          {
            "series": "0",
            "index": "93",
            "xExact": "",
            "x": "94",
            "yExact": "",
            "y": "0.667910448",
            "id": "person:574"
          },
          {
            "series": "1",
            "index": "93",
            "xExact": "",
            "x": "94",
            "yExact": "",
            "y": "1",
            "id": "person:574"
          },
          {
            "series": "0",
            "index": "94",
            "xExact": "",
            "x": "95",
            "yExact": "",
            "y": "0.362068966",
            "id": "person:583"
          },
          {
            "series": "1",
            "index": "94",
            "xExact": "",
            "x": "95",
            "yExact": "",
            "y": "1",
            "id": "person:583"
          },
          {
            "series": "0",
            "index": "95",
            "xExact": "",
            "x": "96",
            "yExact": "",
            "y": "0.757575758",
            "id": "person:594"
          },
          {
            "series": "1",
            "index": "95",
            "xExact": "",
            "x": "96",
            "yExact": "",
            "y": "1",
            "id": "person:594"
          },
          {
            "series": "0",
            "index": "96",
            "xExact": "",
            "x": "97",
            "yExact": "",
            "y": "0.362068966",
            "id": "person:601"
          },
          {
            "series": "1",
            "index": "96",
            "xExact": "",
            "x": "97",
            "yExact": "",
            "y": "0",
            "id": "person:601"
          },
          {
            "series": "0",
            "index": "97",
            "xExact": "",
            "x": "98",
            "yExact": "",
            "y": "0.362068966",
            "id": "person:613"
          },
          {
            "series": "1",
            "index": "97",
            "xExact": "",
            "x": "98",
            "yExact": "",
            "y": "1",
            "id": "person:613"
          },
          {
            "series": "0",
            "index": "98",
            "xExact": "",
            "x": "99",
            "yExact": "",
            "y": "0.757575758",
            "id": "person:614"
          },
          {
            "series": "1",
            "index": "98",
            "xExact": "",
            "x": "99",
            "yExact": "",
            "y": "1",
            "id": "person:614"
          },
          {
            "series": "0",
            "index": "99",
            "xExact": "",
            "x": "100",
            "yExact": "",
            "y": "0.667910448",
            "id": "person:625"
          },
          {
            "series": "1",
            "index": "99",
            "xExact": "",
            "x": "100",
            "yExact": "",
            "y": "1",
            "id": "person:625"
          },
          {
            "series": "0",
            "index": "100",
            "xExact": "",
            "x": "101",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:630"
          },
          {
            "series": "1",
            "index": "100",
            "xExact": "",
            "x": "101",
            "yExact": "",
            "y": "0",
            "id": "person:630"
          },
          {
            "series": "0",
            "index": "101",
            "xExact": "",
            "x": "102",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:638"
          },
          {
            "series": "1",
            "index": "101",
            "xExact": "",
            "x": "102",
            "yExact": "",
            "y": "1",
            "id": "person:638"
          },
          {
            "series": "0",
            "index": "102",
            "xExact": "",
            "x": "103",
            "yExact": "",
            "y": "0.667910448",
            "id": "person:648"
          },
          {
            "series": "1",
            "index": "102",
            "xExact": "",
            "x": "103",
            "yExact": "",
            "y": "0",
            "id": "person:648"
          },
          {
            "series": "0",
            "index": "103",
            "xExact": "",
            "x": "104",
            "yExact": "",
            "y": "0.824267782",
            "id": "person:656"
          },
          {
            "series": "1",
            "index": "103",
            "xExact": "",
            "x": "104",
            "yExact": "",
            "y": "1",
            "id": "person:656"
          },
          {
            "series": "0",
            "index": "104",
            "xExact": "",
            "x": "105",
            "yExact": "",
            "y": "0.824267782",
            "id": "person:659"
          },
          {
            "series": "1",
            "index": "104",
            "xExact": "",
            "x": "105",
            "yExact": "",
            "y": "1",
            "id": "person:659"
          },
          {
            "series": "0",
            "index": "105",
            "xExact": "",
            "x": "106",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:678"
          },
          {
            "series": "1",
            "index": "105",
            "xExact": "",
            "x": "106",
            "yExact": "",
            "y": "0",
            "id": "person:678"
          },
          {
            "series": "0",
            "index": "106",
            "xExact": "",
            "x": "107",
            "yExact": "",
            "y": "0.362068966",
            "id": "person:686"
          },
          {
            "series": "1",
            "index": "106",
            "xExact": "",
            "x": "107",
            "yExact": "",
            "y": "0",
            "id": "person:686"
          },
          {
            "series": "0",
            "index": "107",
            "xExact": "",
            "x": "108",
            "yExact": "",
            "y": "0.487804878",
            "id": "person:689"
          },
          {
            "series": "1",
            "index": "107",
            "xExact": "",
            "x": "108",
            "yExact": "",
            "y": "1",
            "id": "person:689"
          },
          {
            "series": "0",
            "index": "108",
            "xExact": "",
            "x": "109",
            "yExact": "",
            "y": "0.48",
            "id": "person:696"
          },
          {
            "series": "1",
            "index": "108",
            "xExact": "",
            "x": "109",
            "yExact": "",
            "y": "0",
            "id": "person:696"
          },
          {
            "series": "0",
            "index": "109",
            "xExact": "",
            "x": "110",
            "yExact": "",
            "y": "0.362068966",
            "id": "person:700"
          },
          {
            "series": "1",
            "index": "109",
            "xExact": "",
            "x": "110",
            "yExact": "",
            "y": "0",
            "id": "person:700"
          },
          {
            "series": "0",
            "index": "110",
            "xExact": "",
            "x": "111",
            "yExact": "",
            "y": "0.48",
            "id": "person:706"
          },
          {
            "series": "1",
            "index": "110",
            "xExact": "",
            "x": "111",
            "yExact": "",
            "y": "0",
            "id": "person:706"
          },
          {
            "series": "0",
            "index": "111",
            "xExact": "",
            "x": "112",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:707"
          },
          {
            "series": "1",
            "index": "111",
            "xExact": "",
            "x": "112",
            "yExact": "",
            "y": "0",
            "id": "person:707"
          },
          {
            "series": "0",
            "index": "112",
            "xExact": "",
            "x": "113",
            "yExact": "",
            "y": "0.667910448",
            "id": "person:724"
          },
          {
            "series": "1",
            "index": "112",
            "xExact": "",
            "x": "113",
            "yExact": "",
            "y": "0",
            "id": "person:724"
          },
          {
            "series": "0",
            "index": "113",
            "xExact": "",
            "x": "114",
            "yExact": "",
            "y": "0.667910448",
            "id": "person:727"
          },
          {
            "series": "1",
            "index": "113",
            "xExact": "",
            "x": "114",
            "yExact": "",
            "y": "1",
            "id": "person:727"
          },
          {
            "series": "0",
            "index": "114",
            "xExact": "",
            "x": "115",
            "yExact": "",
            "y": "0.667910448",
            "id": "person:730"
          },
          {
            "series": "1",
            "index": "114",
            "xExact": "",
            "x": "115",
            "yExact": "",
            "y": "0",
            "id": "person:730"
          },
          {
            "series": "0",
            "index": "115",
            "xExact": "",
            "x": "116",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:733"
          },
          {
            "series": "1",
            "index": "115",
            "xExact": "",
            "x": "116",
            "yExact": "",
            "y": "0",
            "id": "person:733"
          },
          {
            "series": "0",
            "index": "116",
            "xExact": "",
            "x": "117",
            "yExact": "",
            "y": "0.824267782",
            "id": "person:737"
          },
          {
            "series": "1",
            "index": "116",
            "xExact": "",
            "x": "117",
            "yExact": "",
            "y": "1",
            "id": "person:737"
          },
          {
            "series": "0",
            "index": "117",
            "xExact": "",
            "x": "118",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:739"
          },
          {
            "series": "1",
            "index": "117",
            "xExact": "",
            "x": "118",
            "yExact": "",
            "y": "0",
            "id": "person:739"
          },
          {
            "series": "0",
            "index": "118",
            "xExact": "",
            "x": "119",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:745"
          },
          {
            "series": "1",
            "index": "118",
            "xExact": "",
            "x": "119",
            "yExact": "",
            "y": "0",
            "id": "person:745"
          },
          {
            "series": "0",
            "index": "119",
            "xExact": "",
            "x": "120",
            "yExact": "",
            "y": "0.667910448",
            "id": "person:755"
          },
          {
            "series": "1",
            "index": "119",
            "xExact": "",
            "x": "120",
            "yExact": "",
            "y": "1",
            "id": "person:755"
          },
          {
            "series": "0",
            "index": "120",
            "xExact": "",
            "x": "121",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:765"
          },
          {
            "series": "1",
            "index": "120",
            "xExact": "",
            "x": "121",
            "yExact": "",
            "y": "1",
            "id": "person:765"
          },
          {
            "series": "0",
            "index": "121",
            "xExact": "",
            "x": "122",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:771"
          },
          {
            "series": "1",
            "index": "121",
            "xExact": "",
            "x": "122",
            "yExact": "",
            "y": "1",
            "id": "person:771"
          },
          {
            "series": "0",
            "index": "122",
            "xExact": "",
            "x": "123",
            "yExact": "",
            "y": "0.667910448",
            "id": "person:779"
          },
          {
            "series": "1",
            "index": "122",
            "xExact": "",
            "x": "123",
            "yExact": "",
            "y": "1",
            "id": "person:779"
          },
          {
            "series": "0",
            "index": "123",
            "xExact": "",
            "x": "124",
            "yExact": "",
            "y": "0.824267782",
            "id": "person:781"
          },
          {
            "series": "1",
            "index": "123",
            "xExact": "",
            "x": "124",
            "yExact": "",
            "y": "1",
            "id": "person:781"
          },
          {
            "series": "0",
            "index": "124",
            "xExact": "",
            "x": "125",
            "yExact": "",
            "y": "0.824267782",
            "id": "person:782"
          },
          {
            "series": "1",
            "index": "124",
            "xExact": "",
            "x": "125",
            "yExact": "",
            "y": "1",
            "id": "person:782"
          },
          {
            "series": "0",
            "index": "125",
            "xExact": "",
            "x": "126",
            "yExact": "",
            "y": "0.667910448",
            "id": "person:787"
          },
          {
            "series": "1",
            "index": "125",
            "xExact": "",
            "x": "126",
            "yExact": "",
            "y": "1",
            "id": "person:787"
          },
          {
            "series": "0",
            "index": "126",
            "xExact": "",
            "x": "127",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:791"
          },
          {
            "series": "1",
            "index": "126",
            "xExact": "",
            "x": "127",
            "yExact": "",
            "y": "1",
            "id": "person:791"
          },
          {
            "series": "0",
            "index": "127",
            "xExact": "",
            "x": "128",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:796"
          },
          {
            "series": "1",
            "index": "127",
            "xExact": "",
            "x": "128",
            "yExact": "",
            "y": "0",
            "id": "person:796"
          },
          {
            "series": "0",
            "index": "128",
            "xExact": "",
            "x": "129",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:801"
          },
          {
            "series": "1",
            "index": "128",
            "xExact": "",
            "x": "129",
            "yExact": "",
            "y": "1",
            "id": "person:801"
          },
          {
            "series": "0",
            "index": "129",
            "xExact": "",
            "x": "130",
            "yExact": "",
            "y": "0.667910448",
            "id": "person:805"
          },
          {
            "series": "1",
            "index": "129",
            "xExact": "",
            "x": "130",
            "yExact": "",
            "y": "0",
            "id": "person:805"
          },
          {
            "series": "0",
            "index": "130",
            "xExact": "",
            "x": "131",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:809"
          },
          {
            "series": "1",
            "index": "130",
            "xExact": "",
            "x": "131",
            "yExact": "",
            "y": "1",
            "id": "person:809"
          },
          {
            "series": "0",
            "index": "131",
            "xExact": "",
            "x": "132",
            "yExact": "",
            "y": "0.667910448",
            "id": "person:810"
          },
          {
            "series": "1",
            "index": "131",
            "xExact": "",
            "x": "132",
            "yExact": "",
            "y": "1",
            "id": "person:810"
          },
          {
            "series": "0",
            "index": "132",
            "xExact": "",
            "x": "133",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:820"
          },
          {
            "series": "1",
            "index": "132",
            "xExact": "",
            "x": "133",
            "yExact": "",
            "y": "1",
            "id": "person:820"
          },
          {
            "series": "0",
            "index": "133",
            "xExact": "",
            "x": "134",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:824"
          },
          {
            "series": "1",
            "index": "133",
            "xExact": "",
            "x": "134",
            "yExact": "",
            "y": "0",
            "id": "person:824"
          },
          {
            "series": "0",
            "index": "134",
            "xExact": "",
            "x": "135",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:829"
          },
          {
            "series": "1",
            "index": "134",
            "xExact": "",
            "x": "135",
            "yExact": "",
            "y": "0",
            "id": "person:829"
          },
          {
            "series": "0",
            "index": "135",
            "xExact": "",
            "x": "136",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:840"
          },
          {
            "series": "1",
            "index": "135",
            "xExact": "",
            "x": "136",
            "yExact": "",
            "y": "1",
            "id": "person:840"
          },
          {
            "series": "0",
            "index": "136",
            "xExact": "",
            "x": "137",
            "yExact": "",
            "y": "0.824267782",
            "id": "person:851"
          },
          {
            "series": "1",
            "index": "136",
            "xExact": "",
            "x": "137",
            "yExact": "",
            "y": "1",
            "id": "person:851"
          },
          {
            "series": "0",
            "index": "137",
            "xExact": "",
            "x": "138",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:879"
          },
          {
            "series": "1",
            "index": "137",
            "xExact": "",
            "x": "138",
            "yExact": "",
            "y": "0",
            "id": "person:879"
          },
          {
            "series": "0",
            "index": "138",
            "xExact": "",
            "x": "139",
            "yExact": "",
            "y": "0.824267782",
            "id": "person:880"
          },
          {
            "series": "1",
            "index": "138",
            "xExact": "",
            "x": "139",
            "yExact": "",
            "y": "1",
            "id": "person:880"
          },
          {
            "series": "0",
            "index": "139",
            "xExact": "",
            "x": "140",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:887"
          },
          {
            "series": "1",
            "index": "139",
            "xExact": "",
            "x": "140",
            "yExact": "",
            "y": "1",
            "id": "person:887"
          },
          {
            "series": "0",
            "index": "140",
            "xExact": "",
            "x": "141",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:899"
          },
          {
            "series": "1",
            "index": "140",
            "xExact": "",
            "x": "141",
            "yExact": "",
            "y": "0",
            "id": "person:899"
          },
          {
            "series": "0",
            "index": "141",
            "xExact": "",
            "x": "142",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:900"
          },
          {
            "series": "1",
            "index": "141",
            "xExact": "",
            "x": "142",
            "yExact": "",
            "y": "1",
            "id": "person:900"
          },
          {
            "series": "0",
            "index": "142",
            "xExact": "",
            "x": "143",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:916"
          },
          {
            "series": "1",
            "index": "142",
            "xExact": "",
            "x": "143",
            "yExact": "",
            "y": "1",
            "id": "person:916"
          },
          {
            "series": "0",
            "index": "143",
            "xExact": "",
            "x": "144",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:926"
          },
          {
            "series": "1",
            "index": "143",
            "xExact": "",
            "x": "144",
            "yExact": "",
            "y": "0",
            "id": "person:926"
          },
          {
            "series": "0",
            "index": "144",
            "xExact": "",
            "x": "145",
            "yExact": "",
            "y": "0.667910448",
            "id": "person:931"
          },
          {
            "series": "1",
            "index": "144",
            "xExact": "",
            "x": "145",
            "yExact": "",
            "y": "1",
            "id": "person:931"
          },
          {
            "series": "0",
            "index": "145",
            "xExact": "",
            "x": "146",
            "yExact": "",
            "y": "0.824267782",
            "id": "person:943"
          },
          {
            "series": "1",
            "index": "145",
            "xExact": "",
            "x": "146",
            "yExact": "",
            "y": "1",
            "id": "person:943"
          },
          {
            "series": "0",
            "index": "146",
            "xExact": "",
            "x": "147",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:949"
          },
          {
            "series": "1",
            "index": "146",
            "xExact": "",
            "x": "147",
            "yExact": "",
            "y": "0",
            "id": "person:949"
          },
          {
            "series": "0",
            "index": "147",
            "xExact": "",
            "x": "148",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:952"
          },
          {
            "series": "1",
            "index": "147",
            "xExact": "",
            "x": "148",
            "yExact": "",
            "y": "1",
            "id": "person:952"
          },
          {
            "series": "0",
            "index": "148",
            "xExact": "",
            "x": "149",
            "yExact": "",
            "y": "0.667910448",
            "id": "person:966"
          },
          {
            "series": "1",
            "index": "148",
            "xExact": "",
            "x": "149",
            "yExact": "",
            "y": "1",
            "id": "person:966"
          },
          {
            "series": "0",
            "index": "149",
            "xExact": "",
            "x": "150",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:969"
          },
          {
            "series": "1",
            "index": "149",
            "xExact": "",
            "x": "150",
            "yExact": "",
            "y": "0",
            "id": "person:969"
          },
          {
            "series": "0",
            "index": "150",
            "xExact": "",
            "x": "151",
            "yExact": "",
            "y": "0.824267782",
            "id": "person:977"
          },
          {
            "series": "1",
            "index": "150",
            "xExact": "",
            "x": "151",
            "yExact": "",
            "y": "1",
            "id": "person:977"
          },
          {
            "series": "0",
            "index": "151",
            "xExact": "",
            "x": "152",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:979"
          },
          {
            "series": "1",
            "index": "151",
            "xExact": "",
            "x": "152",
            "yExact": "",
            "y": "1",
            "id": "person:979"
          },
          {
            "series": "0",
            "index": "152",
            "xExact": "",
            "x": "153",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:983"
          },
          {
            "series": "1",
            "index": "152",
            "xExact": "",
            "x": "153",
            "yExact": "",
            "y": "1",
            "id": "person:983"
          },
          {
            "series": "0",
            "index": "153",
            "xExact": "",
            "x": "154",
            "yExact": "",
            "y": "0.667910448",
            "id": "person:987"
          },
          {
            "series": "1",
            "index": "153",
            "xExact": "",
            "x": "154",
            "yExact": "",
            "y": "1",
            "id": "person:987"
          },
          {
            "series": "0",
            "index": "154",
            "xExact": "",
            "x": "155",
            "yExact": "",
            "y": "0.667910448",
            "id": "person:988"
          },
          {
            "series": "1",
            "index": "154",
            "xExact": "",
            "x": "155",
            "yExact": "",
            "y": "1",
            "id": "person:988"
          },
          {
            "series": "0",
            "index": "155",
            "xExact": "",
            "x": "156",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:989"
          },
          {
            "series": "1",
            "index": "155",
            "xExact": "",
            "x": "156",
            "yExact": "",
            "y": "1",
            "id": "person:989"
          },
          {
            "series": "0",
            "index": "156",
            "xExact": "",
            "x": "157",
            "yExact": "",
            "y": "0.824267782",
            "id": "person:1001"
          },
          {
            "series": "1",
            "index": "156",
            "xExact": "",
            "x": "157",
            "yExact": "",
            "y": "1",
            "id": "person:1001"
          },
          {
            "series": "0",
            "index": "157",
            "xExact": "",
            "x": "158",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:1005"
          },
          {
            "series": "1",
            "index": "157",
            "xExact": "",
            "x": "158",
            "yExact": "",
            "y": "0",
            "id": "person:1005"
          },
          {
            "series": "0",
            "index": "158",
            "xExact": "",
            "x": "159",
            "yExact": "",
            "y": "0.824267782",
            "id": "person:1008"
          },
          {
            "series": "1",
            "index": "158",
            "xExact": "",
            "x": "159",
            "yExact": "",
            "y": "0",
            "id": "person:1008"
          },
          {
            "series": "0",
            "index": "159",
            "xExact": "",
            "x": "160",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:1010"
          },
          {
            "series": "1",
            "index": "159",
            "xExact": "",
            "x": "160",
            "yExact": "",
            "y": "1",
            "id": "person:1010"
          },
          {
            "series": "0",
            "index": "160",
            "xExact": "",
            "x": "161",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:1011"
          },
          {
            "series": "1",
            "index": "160",
            "xExact": "",
            "x": "161",
            "yExact": "",
            "y": "1",
            "id": "person:1011"
          },
          {
            "series": "0",
            "index": "161",
            "xExact": "",
            "x": "162",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:1026"
          },
          {
            "series": "1",
            "index": "161",
            "xExact": "",
            "x": "162",
            "yExact": "",
            "y": "1",
            "id": "person:1026"
          },
          {
            "series": "0",
            "index": "162",
            "xExact": "",
            "x": "163",
            "yExact": "",
            "y": "0.824267782",
            "id": "person:1034"
          },
          {
            "series": "1",
            "index": "162",
            "xExact": "",
            "x": "163",
            "yExact": "",
            "y": "1",
            "id": "person:1034"
          },
          {
            "series": "0",
            "index": "163",
            "xExact": "",
            "x": "164",
            "yExact": "",
            "y": "0.824267782",
            "id": "person:1035"
          },
          {
            "series": "1",
            "index": "163",
            "xExact": "",
            "x": "164",
            "yExact": "",
            "y": "1",
            "id": "person:1035"
          },
          {
            "series": "0",
            "index": "164",
            "xExact": "",
            "x": "165",
            "yExact": "",
            "y": "0.667910448",
            "id": "person:1036"
          },
          {
            "series": "1",
            "index": "164",
            "xExact": "",
            "x": "165",
            "yExact": "",
            "y": "0",
            "id": "person:1036"
          },
          {
            "series": "0",
            "index": "165",
            "xExact": "",
            "x": "166",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:1041"
          },
          {
            "series": "1",
            "index": "165",
            "xExact": "",
            "x": "166",
            "yExact": "",
            "y": "1",
            "id": "person:1041"
          },
          {
            "series": "0",
            "index": "166",
            "xExact": "",
            "x": "167",
            "yExact": "",
            "y": "0.667910448",
            "id": "person:1046"
          },
          {
            "series": "1",
            "index": "166",
            "xExact": "",
            "x": "167",
            "yExact": "",
            "y": "1",
            "id": "person:1046"
          },
          {
            "series": "0",
            "index": "167",
            "xExact": "",
            "x": "168",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:1049"
          },
          {
            "series": "1",
            "index": "167",
            "xExact": "",
            "x": "168",
            "yExact": "",
            "y": "0",
            "id": "person:1049"
          },
          {
            "series": "0",
            "index": "168",
            "xExact": "",
            "x": "169",
            "yExact": "",
            "y": "0.824267782",
            "id": "person:1055"
          },
          {
            "series": "1",
            "index": "168",
            "xExact": "",
            "x": "169",
            "yExact": "",
            "y": "1",
            "id": "person:1055"
          },
          {
            "series": "0",
            "index": "169",
            "xExact": "",
            "x": "170",
            "yExact": "",
            "y": "0.824267782",
            "id": "person:1057"
          },
          {
            "series": "1",
            "index": "169",
            "xExact": "",
            "x": "170",
            "yExact": "",
            "y": "1",
            "id": "person:1057"
          },
          {
            "series": "0",
            "index": "170",
            "xExact": "",
            "x": "171",
            "yExact": "",
            "y": "0.487804878",
            "id": "person:1063"
          },
          {
            "series": "1",
            "index": "170",
            "xExact": "",
            "x": "171",
            "yExact": "",
            "y": "1",
            "id": "person:1063"
          },
          {
            "series": "0",
            "index": "171",
            "xExact": "",
            "x": "172",
            "yExact": "",
            "y": "0.362068966",
            "id": "person:1071"
          },
          {
            "series": "1",
            "index": "171",
            "xExact": "",
            "x": "172",
            "yExact": "",
            "y": "1",
            "id": "person:1071"
          },
          {
            "series": "0",
            "index": "172",
            "xExact": "",
            "x": "173",
            "yExact": "",
            "y": "0.667910448",
            "id": "person:1073"
          },
          {
            "series": "1",
            "index": "172",
            "xExact": "",
            "x": "173",
            "yExact": "",
            "y": "1",
            "id": "person:1073"
          },
          {
            "series": "0",
            "index": "173",
            "xExact": "",
            "x": "174",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:1083"
          },
          {
            "series": "1",
            "index": "173",
            "xExact": "",
            "x": "174",
            "yExact": "",
            "y": "1",
            "id": "person:1083"
          },
          {
            "series": "0",
            "index": "174",
            "xExact": "",
            "x": "175",
            "yExact": "",
            "y": "0.48",
            "id": "person:1094"
          },
          {
            "series": "1",
            "index": "174",
            "xExact": "",
            "x": "175",
            "yExact": "",
            "y": "1",
            "id": "person:1094"
          },
          {
            "series": "0",
            "index": "175",
            "xExact": "",
            "x": "176",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:1099"
          },
          {
            "series": "1",
            "index": "175",
            "xExact": "",
            "x": "176",
            "yExact": "",
            "y": "1",
            "id": "person:1099"
          },
          {
            "series": "0",
            "index": "176",
            "xExact": "",
            "x": "177",
            "yExact": "",
            "y": "0.824267782",
            "id": "person:1104"
          },
          {
            "series": "1",
            "index": "176",
            "xExact": "",
            "x": "177",
            "yExact": "",
            "y": "1",
            "id": "person:1104"
          },
          {
            "series": "0",
            "index": "177",
            "xExact": "",
            "x": "178",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:1108"
          },
          {
            "series": "1",
            "index": "177",
            "xExact": "",
            "x": "178",
            "yExact": "",
            "y": "0",
            "id": "person:1108"
          },
          {
            "series": "0",
            "index": "178",
            "xExact": "",
            "x": "179",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:1122"
          },
          {
            "series": "1",
            "index": "178",
            "xExact": "",
            "x": "179",
            "yExact": "",
            "y": "1",
            "id": "person:1122"
          },
          {
            "series": "0",
            "index": "179",
            "xExact": "",
            "x": "180",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:1123"
          },
          {
            "series": "1",
            "index": "179",
            "xExact": "",
            "x": "180",
            "yExact": "",
            "y": "1",
            "id": "person:1123"
          },
          {
            "series": "0",
            "index": "180",
            "xExact": "",
            "x": "181",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:1138"
          },
          {
            "series": "1",
            "index": "180",
            "xExact": "",
            "x": "181",
            "yExact": "",
            "y": "0",
            "id": "person:1138"
          },
          {
            "series": "0",
            "index": "181",
            "xExact": "",
            "x": "182",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:1147"
          },
          {
            "series": "1",
            "index": "181",
            "xExact": "",
            "x": "182",
            "yExact": "",
            "y": "1",
            "id": "person:1147"
          },
          {
            "series": "0",
            "index": "182",
            "xExact": "",
            "x": "183",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:1163"
          },
          {
            "series": "1",
            "index": "182",
            "xExact": "",
            "x": "183",
            "yExact": "",
            "y": "1",
            "id": "person:1163"
          },
          {
            "series": "0",
            "index": "183",
            "xExact": "",
            "x": "184",
            "yExact": "",
            "y": "0.824267782",
            "id": "person:1165"
          },
          {
            "series": "1",
            "index": "183",
            "xExact": "",
            "x": "184",
            "yExact": "",
            "y": "1",
            "id": "person:1165"
          },
          {
            "series": "0",
            "index": "184",
            "xExact": "",
            "x": "185",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:1166"
          },
          {
            "series": "1",
            "index": "184",
            "xExact": "",
            "x": "185",
            "yExact": "",
            "y": "1",
            "id": "person:1166"
          },
          {
            "series": "0",
            "index": "185",
            "xExact": "",
            "x": "186",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:1169"
          },
          {
            "series": "1",
            "index": "185",
            "xExact": "",
            "x": "186",
            "yExact": "",
            "y": "1",
            "id": "person:1169"
          },
          {
            "series": "0",
            "index": "186",
            "xExact": "",
            "x": "187",
            "yExact": "",
            "y": "0.667910448",
            "id": "person:1171"
          },
          {
            "series": "1",
            "index": "186",
            "xExact": "",
            "x": "187",
            "yExact": "",
            "y": "1",
            "id": "person:1171"
          },
          {
            "series": "0",
            "index": "187",
            "xExact": "",
            "x": "188",
            "yExact": "",
            "y": "0.362068966",
            "id": "person:1175"
          },
          {
            "series": "1",
            "index": "187",
            "xExact": "",
            "x": "188",
            "yExact": "",
            "y": "0",
            "id": "person:1175"
          },
          {
            "series": "0",
            "index": "188",
            "xExact": "",
            "x": "189",
            "yExact": "",
            "y": "0.487804878",
            "id": "person:1189"
          },
          {
            "series": "1",
            "index": "188",
            "xExact": "",
            "x": "189",
            "yExact": "",
            "y": "0",
            "id": "person:1189"
          },
          {
            "series": "0",
            "index": "189",
            "xExact": "",
            "x": "190",
            "yExact": "",
            "y": "0.362068966",
            "id": "person:1194"
          },
          {
            "series": "1",
            "index": "189",
            "xExact": "",
            "x": "190",
            "yExact": "",
            "y": "1",
            "id": "person:1194"
          },
          {
            "series": "0",
            "index": "190",
            "xExact": "",
            "x": "191",
            "yExact": "",
            "y": "0.362068966",
            "id": "person:1196"
          },
          {
            "series": "1",
            "index": "190",
            "xExact": "",
            "x": "191",
            "yExact": "",
            "y": "0",
            "id": "person:1196"
          },
          {
            "series": "0",
            "index": "191",
            "xExact": "",
            "x": "192",
            "yExact": "",
            "y": "0.487804878",
            "id": "person:1200"
          },
          {
            "series": "1",
            "index": "191",
            "xExact": "",
            "x": "192",
            "yExact": "",
            "y": "0",
            "id": "person:1200"
          },
          {
            "series": "0",
            "index": "192",
            "xExact": "",
            "x": "193",
            "yExact": "",
            "y": "0.487804878",
            "id": "person:1213"
          },
          {
            "series": "1",
            "index": "192",
            "xExact": "",
            "x": "193",
            "yExact": "",
            "y": "0",
            "id": "person:1213"
          },
          {
            "series": "0",
            "index": "193",
            "xExact": "",
            "x": "194",
            "yExact": "",
            "y": "0.48",
            "id": "person:1219"
          },
          {
            "series": "1",
            "index": "193",
            "xExact": "",
            "x": "194",
            "yExact": "",
            "y": "0",
            "id": "person:1219"
          },
          {
            "series": "0",
            "index": "194",
            "xExact": "",
            "x": "195",
            "yExact": "",
            "y": "0.362068966",
            "id": "person:1220"
          },
          {
            "series": "1",
            "index": "194",
            "xExact": "",
            "x": "195",
            "yExact": "",
            "y": "1",
            "id": "person:1220"
          },
          {
            "series": "0",
            "index": "195",
            "xExact": "",
            "x": "196",
            "yExact": "",
            "y": "0.48",
            "id": "person:1223"
          },
          {
            "series": "1",
            "index": "195",
            "xExact": "",
            "x": "196",
            "yExact": "",
            "y": "1",
            "id": "person:1223"
          },
          {
            "series": "0",
            "index": "196",
            "xExact": "",
            "x": "197",
            "yExact": "",
            "y": "0.667910448",
            "id": "person:1231"
          },
          {
            "series": "1",
            "index": "196",
            "xExact": "",
            "x": "197",
            "yExact": "",
            "y": "0",
            "id": "person:1231"
          },
          {
            "series": "0",
            "index": "197",
            "xExact": "",
            "x": "198",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:1233"
          },
          {
            "series": "1",
            "index": "197",
            "xExact": "",
            "x": "198",
            "yExact": "",
            "y": "1",
            "id": "person:1233"
          },
          {
            "series": "0",
            "index": "198",
            "xExact": "",
            "x": "199",
            "yExact": "",
            "y": "0.48",
            "id": "person:1236"
          },
          {
            "series": "1",
            "index": "198",
            "xExact": "",
            "x": "199",
            "yExact": "",
            "y": "0",
            "id": "person:1236"
          },
          {
            "series": "0",
            "index": "199",
            "xExact": "",
            "x": "200",
            "yExact": "",
            "y": "0.487804878",
            "id": "person:1252"
          },
          {
            "series": "1",
            "index": "199",
            "xExact": "",
            "x": "200",
            "yExact": "",
            "y": "1",
            "id": "person:1252"
          },
          {
            "series": "0",
            "index": "200",
            "xExact": "",
            "x": "201",
            "yExact": "",
            "y": "0.757575758",
            "id": "person:1257"
          },
          {
            "series": "1",
            "index": "200",
            "xExact": "",
            "x": "201",
            "yExact": "",
            "y": "1",
            "id": "person:1257"
          },
          {
            "series": "0",
            "index": "201",
            "xExact": "",
            "x": "202",
            "yExact": "",
            "y": "0.362068966",
            "id": "person:1259"
          },
          {
            "series": "1",
            "index": "201",
            "xExact": "",
            "x": "202",
            "yExact": "",
            "y": "0",
            "id": "person:1259"
          },
          {
            "series": "0",
            "index": "202",
            "xExact": "",
            "x": "203",
            "yExact": "",
            "y": "0.362068966",
            "id": "person:1277"
          },
          {
            "series": "1",
            "index": "202",
            "xExact": "",
            "x": "203",
            "yExact": "",
            "y": "1",
            "id": "person:1277"
          },
          {
            "series": "0",
            "index": "203",
            "xExact": "",
            "x": "204",
            "yExact": "",
            "y": "0.48",
            "id": "person:1279"
          },
          {
            "series": "1",
            "index": "203",
            "xExact": "",
            "x": "204",
            "yExact": "",
            "y": "1",
            "id": "person:1279"
          },
          {
            "series": "0",
            "index": "204",
            "xExact": "",
            "x": "205",
            "yExact": "",
            "y": "0.487804878",
            "id": "person:1281"
          },
          {
            "series": "1",
            "index": "204",
            "xExact": "",
            "x": "205",
            "yExact": "",
            "y": "0",
            "id": "person:1281"
          },
          {
            "series": "0",
            "index": "205",
            "xExact": "",
            "x": "206",
            "yExact": "",
            "y": "0.48",
            "id": "person:1284"
          },
          {
            "series": "1",
            "index": "205",
            "xExact": "",
            "x": "206",
            "yExact": "",
            "y": "1",
            "id": "person:1284"
          },
          {
            "series": "0",
            "index": "206",
            "xExact": "",
            "x": "207",
            "yExact": "",
            "y": "0.48",
            "id": "person:1288"
          },
          {
            "series": "1",
            "index": "206",
            "xExact": "",
            "x": "207",
            "yExact": "",
            "y": "1",
            "id": "person:1288"
          },
          {
            "series": "0",
            "index": "207",
            "xExact": "",
            "x": "208",
            "yExact": "",
            "y": "0.487804878",
            "id": "person:1294"
          },
          {
            "series": "1",
            "index": "207",
            "xExact": "",
            "x": "208",
            "yExact": "",
            "y": "1",
            "id": "person:1294"
          },
          {
            "series": "0",
            "index": "208",
            "xExact": "",
            "x": "209",
            "yExact": "",
            "y": "0.487804878",
            "id": "person:1296"
          },
          {
            "series": "1",
            "index": "208",
            "xExact": "",
            "x": "209",
            "yExact": "",
            "y": "1",
            "id": "person:1296"
          },
          {
            "series": "0",
            "index": "209",
            "xExact": "",
            "x": "210",
            "yExact": "",
            "y": "0.362068966",
            "id": "person:1304"
          },
          {
            "series": "1",
            "index": "209",
            "xExact": "",
            "x": "210",
            "yExact": "",
            "y": "0",
            "id": "person:1304"
          },
          {
            "series": "0",
            "index": "210",
            "xExact": "",
            "x": "211",
            "yExact": "",
            "y": "0.362068966",
            "id": "person:1310"
          },
          {
            "series": "1",
            "index": "210",
            "xExact": "",
            "x": "211",
            "yExact": "",
            "y": "1",
            "id": "person:1310"
          },
          {
            "series": "0",
            "index": "211",
            "xExact": "",
            "x": "212",
            "yExact": "",
            "y": "0.667910448",
            "id": "person:1314"
          },
          {
            "series": "1",
            "index": "211",
            "xExact": "",
            "x": "212",
            "yExact": "",
            "y": "1",
            "id": "person:1314"
          },
          {
            "series": "0",
            "index": "212",
            "xExact": "",
            "x": "213",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:1321"
          },
          {
            "series": "1",
            "index": "212",
            "xExact": "",
            "x": "213",
            "yExact": "",
            "y": "1",
            "id": "person:1321"
          },
          {
            "series": "0",
            "index": "213",
            "xExact": "",
            "x": "214",
            "yExact": "",
            "y": "0.824267782",
            "id": "person:1332"
          },
          {
            "series": "1",
            "index": "213",
            "xExact": "",
            "x": "214",
            "yExact": "",
            "y": "1",
            "id": "person:1332"
          },
          {
            "series": "0",
            "index": "214",
            "xExact": "",
            "x": "215",
            "yExact": "",
            "y": "0.667910448",
            "id": "person:1345"
          },
          {
            "series": "1",
            "index": "214",
            "xExact": "",
            "x": "215",
            "yExact": "",
            "y": "0",
            "id": "person:1345"
          },
          {
            "series": "0",
            "index": "215",
            "xExact": "",
            "x": "216",
            "yExact": "",
            "y": "0.824267782",
            "id": "person:1352"
          },
          {
            "series": "1",
            "index": "215",
            "xExact": "",
            "x": "216",
            "yExact": "",
            "y": "1",
            "id": "person:1352"
          },
          {
            "series": "0",
            "index": "216",
            "xExact": "",
            "x": "217",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:1358"
          },
          {
            "series": "1",
            "index": "216",
            "xExact": "",
            "x": "217",
            "yExact": "",
            "y": "0",
            "id": "person:1358"
          },
          {
            "series": "0",
            "index": "217",
            "xExact": "",
            "x": "218",
            "yExact": "",
            "y": "0.824267782",
            "id": "person:1365"
          },
          {
            "series": "1",
            "index": "217",
            "xExact": "",
            "x": "218",
            "yExact": "",
            "y": "1",
            "id": "person:1365"
          },
          {
            "series": "0",
            "index": "218",
            "xExact": "",
            "x": "219",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:1366"
          },
          {
            "series": "1",
            "index": "218",
            "xExact": "",
            "x": "219",
            "yExact": "",
            "y": "1",
            "id": "person:1366"
          },
          {
            "series": "0",
            "index": "219",
            "xExact": "",
            "x": "220",
            "yExact": "",
            "y": "0.667910448",
            "id": "person:1368"
          },
          {
            "series": "1",
            "index": "219",
            "xExact": "",
            "x": "220",
            "yExact": "",
            "y": "1",
            "id": "person:1368"
          },
          {
            "series": "0",
            "index": "220",
            "xExact": "",
            "x": "221",
            "yExact": "",
            "y": "0.824267782",
            "id": "person:1372"
          },
          {
            "series": "1",
            "index": "220",
            "xExact": "",
            "x": "221",
            "yExact": "",
            "y": "1",
            "id": "person:1372"
          },
          {
            "series": "0",
            "index": "221",
            "xExact": "",
            "x": "222",
            "yExact": "",
            "y": "0.667910448",
            "id": "person:1377"
          },
          {
            "series": "1",
            "index": "221",
            "xExact": "",
            "x": "222",
            "yExact": "",
            "y": "1",
            "id": "person:1377"
          },
          {
            "series": "0",
            "index": "222",
            "xExact": "",
            "x": "223",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:1378"
          },
          {
            "series": "1",
            "index": "222",
            "xExact": "",
            "x": "223",
            "yExact": "",
            "y": "1",
            "id": "person:1378"
          },
          {
            "series": "0",
            "index": "223",
            "xExact": "",
            "x": "224",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:1384"
          },
          {
            "series": "1",
            "index": "223",
            "xExact": "",
            "x": "224",
            "yExact": "",
            "y": "1",
            "id": "person:1384"
          },
          {
            "series": "0",
            "index": "224",
            "xExact": "",
            "x": "225",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:1388"
          },
          {
            "series": "1",
            "index": "224",
            "xExact": "",
            "x": "225",
            "yExact": "",
            "y": "0",
            "id": "person:1388"
          },
          {
            "series": "0",
            "index": "225",
            "xExact": "",
            "x": "226",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:1404"
          },
          {
            "series": "1",
            "index": "225",
            "xExact": "",
            "x": "226",
            "yExact": "",
            "y": "1",
            "id": "person:1404"
          },
          {
            "series": "0",
            "index": "226",
            "xExact": "",
            "x": "227",
            "yExact": "",
            "y": "0.667910448",
            "id": "person:1408"
          },
          {
            "series": "1",
            "index": "226",
            "xExact": "",
            "x": "227",
            "yExact": "",
            "y": "0",
            "id": "person:1408"
          },
          {
            "series": "0",
            "index": "227",
            "xExact": "",
            "x": "228",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:1409"
          },
          {
            "series": "1",
            "index": "227",
            "xExact": "",
            "x": "228",
            "yExact": "",
            "y": "1",
            "id": "person:1409"
          },
          {
            "series": "0",
            "index": "228",
            "xExact": "",
            "x": "229",
            "yExact": "",
            "y": "0.667910448",
            "id": "person:1412"
          },
          {
            "series": "1",
            "index": "228",
            "xExact": "",
            "x": "229",
            "yExact": "",
            "y": "1",
            "id": "person:1412"
          },
          {
            "series": "0",
            "index": "229",
            "xExact": "",
            "x": "230",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:1415"
          },
          {
            "series": "1",
            "index": "229",
            "xExact": "",
            "x": "230",
            "yExact": "",
            "y": "1",
            "id": "person:1415"
          },
          {
            "series": "0",
            "index": "230",
            "xExact": "",
            "x": "231",
            "yExact": "",
            "y": "0.48",
            "id": "person:1433"
          },
          {
            "series": "1",
            "index": "230",
            "xExact": "",
            "x": "231",
            "yExact": "",
            "y": "0",
            "id": "person:1433"
          },
          {
            "series": "0",
            "index": "231",
            "xExact": "",
            "x": "232",
            "yExact": "",
            "y": "0.362068966",
            "id": "person:1434"
          },
          {
            "series": "1",
            "index": "231",
            "xExact": "",
            "x": "232",
            "yExact": "",
            "y": "1",
            "id": "person:1434"
          },
          {
            "series": "0",
            "index": "232",
            "xExact": "",
            "x": "233",
            "yExact": "",
            "y": "0.362068966",
            "id": "person:1439"
          },
          {
            "series": "1",
            "index": "232",
            "xExact": "",
            "x": "233",
            "yExact": "",
            "y": "0",
            "id": "person:1439"
          },
          {
            "series": "0",
            "index": "233",
            "xExact": "",
            "x": "234",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:1444"
          },
          {
            "series": "1",
            "index": "233",
            "xExact": "",
            "x": "234",
            "yExact": "",
            "y": "0",
            "id": "person:1444"
          },
          {
            "series": "0",
            "index": "234",
            "xExact": "",
            "x": "235",
            "yExact": "",
            "y": "0.667910448",
            "id": "person:1447"
          },
          {
            "series": "1",
            "index": "234",
            "xExact": "",
            "x": "235",
            "yExact": "",
            "y": "1",
            "id": "person:1447"
          },
          {
            "series": "0",
            "index": "235",
            "xExact": "",
            "x": "236",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:1471"
          },
          {
            "series": "1",
            "index": "235",
            "xExact": "",
            "x": "236",
            "yExact": "",
            "y": "1",
            "id": "person:1471"
          },
          {
            "series": "0",
            "index": "236",
            "xExact": "",
            "x": "237",
            "yExact": "",
            "y": "0.824267782",
            "id": "person:1479"
          },
          {
            "series": "1",
            "index": "236",
            "xExact": "",
            "x": "237",
            "yExact": "",
            "y": "0",
            "id": "person:1479"
          },
          {
            "series": "0",
            "index": "237",
            "xExact": "",
            "x": "238",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:1484"
          },
          {
            "series": "1",
            "index": "237",
            "xExact": "",
            "x": "238",
            "yExact": "",
            "y": "0",
            "id": "person:1484"
          },
          {
            "series": "0",
            "index": "238",
            "xExact": "",
            "x": "239",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:1488"
          },
          {
            "series": "1",
            "index": "238",
            "xExact": "",
            "x": "239",
            "yExact": "",
            "y": "0",
            "id": "person:1488"
          },
          {
            "series": "0",
            "index": "239",
            "xExact": "",
            "x": "240",
            "yExact": "",
            "y": "0.667910448",
            "id": "person:1497"
          },
          {
            "series": "1",
            "index": "239",
            "xExact": "",
            "x": "240",
            "yExact": "",
            "y": "1",
            "id": "person:1497"
          },
          {
            "series": "0",
            "index": "240",
            "xExact": "",
            "x": "241",
            "yExact": "",
            "y": "0.667910448",
            "id": "person:1498"
          },
          {
            "series": "1",
            "index": "240",
            "xExact": "",
            "x": "241",
            "yExact": "",
            "y": "0",
            "id": "person:1498"
          },
          {
            "series": "0",
            "index": "241",
            "xExact": "",
            "x": "242",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:1515"
          },
          {
            "series": "1",
            "index": "241",
            "xExact": "",
            "x": "242",
            "yExact": "",
            "y": "0",
            "id": "person:1515"
          },
          {
            "series": "0",
            "index": "242",
            "xExact": "",
            "x": "243",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:1516"
          },
          {
            "series": "1",
            "index": "242",
            "xExact": "",
            "x": "243",
            "yExact": "",
            "y": "0",
            "id": "person:1516"
          },
          {
            "series": "0",
            "index": "243",
            "xExact": "",
            "x": "244",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:1518"
          },
          {
            "series": "1",
            "index": "243",
            "xExact": "",
            "x": "244",
            "yExact": "",
            "y": "0",
            "id": "person:1518"
          },
          {
            "series": "0",
            "index": "244",
            "xExact": "",
            "x": "245",
            "yExact": "",
            "y": "0.824267782",
            "id": "person:1522"
          },
          {
            "series": "1",
            "index": "244",
            "xExact": "",
            "x": "245",
            "yExact": "",
            "y": "1",
            "id": "person:1522"
          },
          {
            "series": "0",
            "index": "245",
            "xExact": "",
            "x": "246",
            "yExact": "",
            "y": "0.487804878",
            "id": "person:1527"
          },
          {
            "series": "1",
            "index": "245",
            "xExact": "",
            "x": "246",
            "yExact": "",
            "y": "0",
            "id": "person:1527"
          },
          {
            "series": "0",
            "index": "246",
            "xExact": "",
            "x": "247",
            "yExact": "",
            "y": "0.757575758",
            "id": "person:1528"
          },
          {
            "series": "1",
            "index": "246",
            "xExact": "",
            "x": "247",
            "yExact": "",
            "y": "1",
            "id": "person:1528"
          },
          {
            "series": "0",
            "index": "247",
            "xExact": "",
            "x": "248",
            "yExact": "",
            "y": "0.487804878",
            "id": "person:1538"
          },
          {
            "series": "1",
            "index": "247",
            "xExact": "",
            "x": "248",
            "yExact": "",
            "y": "0",
            "id": "person:1538"
          },
          {
            "series": "0",
            "index": "248",
            "xExact": "",
            "x": "249",
            "yExact": "",
            "y": "0.48",
            "id": "person:1539"
          },
          {
            "series": "1",
            "index": "248",
            "xExact": "",
            "x": "249",
            "yExact": "",
            "y": "0",
            "id": "person:1539"
          },
          {
            "series": "0",
            "index": "249",
            "xExact": "",
            "x": "250",
            "yExact": "",
            "y": "0.757575758",
            "id": "person:1551"
          },
          {
            "series": "1",
            "index": "249",
            "xExact": "",
            "x": "250",
            "yExact": "",
            "y": "1",
            "id": "person:1551"
          },
          {
            "series": "0",
            "index": "250",
            "xExact": "",
            "x": "251",
            "yExact": "",
            "y": "0.757575758",
            "id": "person:1552"
          },
          {
            "series": "1",
            "index": "250",
            "xExact": "",
            "x": "251",
            "yExact": "",
            "y": "1",
            "id": "person:1552"
          },
          {
            "series": "0",
            "index": "251",
            "xExact": "",
            "x": "252",
            "yExact": "",
            "y": "0.362068966",
            "id": "person:1556"
          },
          {
            "series": "1",
            "index": "251",
            "xExact": "",
            "x": "252",
            "yExact": "",
            "y": "1",
            "id": "person:1556"
          },
          {
            "series": "0",
            "index": "252",
            "xExact": "",
            "x": "253",
            "yExact": "",
            "y": "0.487804878",
            "id": "person:1561"
          },
          {
            "series": "1",
            "index": "252",
            "xExact": "",
            "x": "253",
            "yExact": "",
            "y": "1",
            "id": "person:1561"
          },
          {
            "series": "0",
            "index": "253",
            "xExact": "",
            "x": "254",
            "yExact": "",
            "y": "0.757575758",
            "id": "person:1562"
          },
          {
            "series": "1",
            "index": "253",
            "xExact": "",
            "x": "254",
            "yExact": "",
            "y": "1",
            "id": "person:1562"
          },
          {
            "series": "0",
            "index": "254",
            "xExact": "",
            "x": "255",
            "yExact": "",
            "y": "0.48",
            "id": "person:1563"
          },
          {
            "series": "1",
            "index": "254",
            "xExact": "",
            "x": "255",
            "yExact": "",
            "y": "0",
            "id": "person:1563"
          },
          {
            "series": "0",
            "index": "255",
            "xExact": "",
            "x": "256",
            "yExact": "",
            "y": "0.362068966",
            "id": "person:1564"
          },
          {
            "series": "1",
            "index": "255",
            "xExact": "",
            "x": "256",
            "yExact": "",
            "y": "1",
            "id": "person:1564"
          },
          {
            "series": "0",
            "index": "256",
            "xExact": "",
            "x": "257",
            "yExact": "",
            "y": "0.824267782",
            "id": "person:1566"
          },
          {
            "series": "1",
            "index": "256",
            "xExact": "",
            "x": "257",
            "yExact": "",
            "y": "1",
            "id": "person:1566"
          },
          {
            "series": "0",
            "index": "257",
            "xExact": "",
            "x": "258",
            "yExact": "",
            "y": "0.362068966",
            "id": "person:1571"
          },
          {
            "series": "1",
            "index": "257",
            "xExact": "",
            "x": "258",
            "yExact": "",
            "y": "1",
            "id": "person:1571"
          },
          {
            "series": "0",
            "index": "258",
            "xExact": "",
            "x": "259",
            "yExact": "",
            "y": "0.362068966",
            "id": "person:1573"
          },
          {
            "series": "1",
            "index": "258",
            "xExact": "",
            "x": "259",
            "yExact": "",
            "y": "0",
            "id": "person:1573"
          },
          {
            "series": "0",
            "index": "259",
            "xExact": "",
            "x": "260",
            "yExact": "",
            "y": "0.48",
            "id": "person:1574"
          },
          {
            "series": "1",
            "index": "259",
            "xExact": "",
            "x": "260",
            "yExact": "",
            "y": "1",
            "id": "person:1574"
          },
          {
            "series": "0",
            "index": "260",
            "xExact": "",
            "x": "261",
            "yExact": "",
            "y": "0.48",
            "id": "person:1575"
          },
          {
            "series": "1",
            "index": "260",
            "xExact": "",
            "x": "261",
            "yExact": "",
            "y": "0",
            "id": "person:1575"
          },
          {
            "series": "0",
            "index": "261",
            "xExact": "",
            "x": "262",
            "yExact": "",
            "y": "0.362068966",
            "id": "person:1580"
          },
          {
            "series": "1",
            "index": "261",
            "xExact": "",
            "x": "262",
            "yExact": "",
            "y": "1",
            "id": "person:1580"
          },
          {
            "series": "0",
            "index": "262",
            "xExact": "",
            "x": "263",
            "yExact": "",
            "y": "0.362068966",
            "id": "person:1588"
          },
          {
            "series": "1",
            "index": "262",
            "xExact": "",
            "x": "263",
            "yExact": "",
            "y": "1",
            "id": "person:1588"
          },
          {
            "series": "0",
            "index": "263",
            "xExact": "",
            "x": "264",
            "yExact": "",
            "y": "0.757575758",
            "id": "person:1596"
          },
          {
            "series": "1",
            "index": "263",
            "xExact": "",
            "x": "264",
            "yExact": "",
            "y": "1",
            "id": "person:1596"
          },
          {
            "series": "0",
            "index": "264",
            "xExact": "",
            "x": "265",
            "yExact": "",
            "y": "0.362068966",
            "id": "person:1603"
          },
          {
            "series": "1",
            "index": "264",
            "xExact": "",
            "x": "265",
            "yExact": "",
            "y": "1",
            "id": "person:1603"
          },
          {
            "series": "0",
            "index": "265",
            "xExact": "",
            "x": "266",
            "yExact": "",
            "y": "0.757575758",
            "id": "person:1609"
          },
          {
            "series": "1",
            "index": "265",
            "xExact": "",
            "x": "266",
            "yExact": "",
            "y": "1",
            "id": "person:1609"
          },
          {
            "series": "0",
            "index": "266",
            "xExact": "",
            "x": "267",
            "yExact": "",
            "y": "0.487804878",
            "id": "person:1625"
          },
          {
            "series": "1",
            "index": "266",
            "xExact": "",
            "x": "267",
            "yExact": "",
            "y": "0",
            "id": "person:1625"
          },
          {
            "series": "0",
            "index": "267",
            "xExact": "",
            "x": "268",
            "yExact": "",
            "y": "0.362068966",
            "id": "person:1630"
          },
          {
            "series": "1",
            "index": "267",
            "xExact": "",
            "x": "268",
            "yExact": "",
            "y": "1",
            "id": "person:1630"
          },
          {
            "series": "0",
            "index": "268",
            "xExact": "",
            "x": "269",
            "yExact": "",
            "y": "0.48",
            "id": "person:1634"
          },
          {
            "series": "1",
            "index": "268",
            "xExact": "",
            "x": "269",
            "yExact": "",
            "y": "1",
            "id": "person:1634"
          },
          {
            "series": "0",
            "index": "269",
            "xExact": "",
            "x": "270",
            "yExact": "",
            "y": "0.362068966",
            "id": "person:1635"
          },
          {
            "series": "1",
            "index": "269",
            "xExact": "",
            "x": "270",
            "yExact": "",
            "y": "1",
            "id": "person:1635"
          },
          {
            "series": "0",
            "index": "270",
            "xExact": "",
            "x": "271",
            "yExact": "",
            "y": "0.667910448",
            "id": "person:1638"
          },
          {
            "series": "1",
            "index": "270",
            "xExact": "",
            "x": "271",
            "yExact": "",
            "y": "0",
            "id": "person:1638"
          },
          {
            "series": "0",
            "index": "271",
            "xExact": "",
            "x": "272",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:1641"
          },
          {
            "series": "1",
            "index": "271",
            "xExact": "",
            "x": "272",
            "yExact": "",
            "y": "1",
            "id": "person:1641"
          },
          {
            "series": "0",
            "index": "272",
            "xExact": "",
            "x": "273",
            "yExact": "",
            "y": "0.667910448",
            "id": "person:1653"
          },
          {
            "series": "1",
            "index": "272",
            "xExact": "",
            "x": "273",
            "yExact": "",
            "y": "0",
            "id": "person:1653"
          },
          {
            "series": "0",
            "index": "273",
            "xExact": "",
            "x": "274",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:1656"
          },
          {
            "series": "1",
            "index": "273",
            "xExact": "",
            "x": "274",
            "yExact": "",
            "y": "1",
            "id": "person:1656"
          },
          {
            "series": "0",
            "index": "274",
            "xExact": "",
            "x": "275",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:1658"
          },
          {
            "series": "1",
            "index": "274",
            "xExact": "",
            "x": "275",
            "yExact": "",
            "y": "1",
            "id": "person:1658"
          },
          {
            "series": "0",
            "index": "275",
            "xExact": "",
            "x": "276",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:1673"
          },
          {
            "series": "1",
            "index": "275",
            "xExact": "",
            "x": "276",
            "yExact": "",
            "y": "1",
            "id": "person:1673"
          },
          {
            "series": "0",
            "index": "276",
            "xExact": "",
            "x": "277",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:1684"
          },
          {
            "series": "1",
            "index": "276",
            "xExact": "",
            "x": "277",
            "yExact": "",
            "y": "1",
            "id": "person:1684"
          },
          {
            "series": "0",
            "index": "277",
            "xExact": "",
            "x": "278",
            "yExact": "",
            "y": "0.824267782",
            "id": "person:1686"
          },
          {
            "series": "1",
            "index": "277",
            "xExact": "",
            "x": "278",
            "yExact": "",
            "y": "1",
            "id": "person:1686"
          },
          {
            "series": "0",
            "index": "278",
            "xExact": "",
            "x": "279",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:1692"
          },
          {
            "series": "1",
            "index": "278",
            "xExact": "",
            "x": "279",
            "yExact": "",
            "y": "0",
            "id": "person:1692"
          },
          {
            "series": "0",
            "index": "279",
            "xExact": "",
            "x": "280",
            "yExact": "",
            "y": "0.667910448",
            "id": "person:1720"
          },
          {
            "series": "1",
            "index": "279",
            "xExact": "",
            "x": "280",
            "yExact": "",
            "y": "1",
            "id": "person:1720"
          },
          {
            "series": "0",
            "index": "280",
            "xExact": "",
            "x": "281",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:1722"
          },
          {
            "series": "1",
            "index": "280",
            "xExact": "",
            "x": "281",
            "yExact": "",
            "y": "1",
            "id": "person:1722"
          },
          {
            "series": "0",
            "index": "281",
            "xExact": "",
            "x": "282",
            "yExact": "",
            "y": "0.667910448",
            "id": "person:1740"
          },
          {
            "series": "1",
            "index": "281",
            "xExact": "",
            "x": "282",
            "yExact": "",
            "y": "1",
            "id": "person:1740"
          },
          {
            "series": "0",
            "index": "282",
            "xExact": "",
            "x": "283",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:1742"
          },
          {
            "series": "1",
            "index": "282",
            "xExact": "",
            "x": "283",
            "yExact": "",
            "y": "1",
            "id": "person:1742"
          },
          {
            "series": "0",
            "index": "283",
            "xExact": "",
            "x": "284",
            "yExact": "",
            "y": "0.667910448",
            "id": "person:1744"
          },
          {
            "series": "1",
            "index": "283",
            "xExact": "",
            "x": "284",
            "yExact": "",
            "y": "0",
            "id": "person:1744"
          },
          {
            "series": "0",
            "index": "284",
            "xExact": "",
            "x": "285",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:1745"
          },
          {
            "series": "1",
            "index": "284",
            "xExact": "",
            "x": "285",
            "yExact": "",
            "y": "0",
            "id": "person:1745"
          },
          {
            "series": "0",
            "index": "285",
            "xExact": "",
            "x": "286",
            "yExact": "",
            "y": "0.667910448",
            "id": "person:1755"
          },
          {
            "series": "1",
            "index": "285",
            "xExact": "",
            "x": "286",
            "yExact": "",
            "y": "1",
            "id": "person:1755"
          },
          {
            "series": "0",
            "index": "286",
            "xExact": "",
            "x": "287",
            "yExact": "",
            "y": "0.667910448",
            "id": "person:1760"
          },
          {
            "series": "1",
            "index": "286",
            "xExact": "",
            "x": "287",
            "yExact": "",
            "y": "0",
            "id": "person:1760"
          },
          {
            "series": "0",
            "index": "287",
            "xExact": "",
            "x": "288",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:1765"
          },
          {
            "series": "1",
            "index": "287",
            "xExact": "",
            "x": "288",
            "yExact": "",
            "y": "0",
            "id": "person:1765"
          },
          {
            "series": "0",
            "index": "288",
            "xExact": "",
            "x": "289",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:1771"
          },
          {
            "series": "1",
            "index": "288",
            "xExact": "",
            "x": "289",
            "yExact": "",
            "y": "1",
            "id": "person:1771"
          },
          {
            "series": "0",
            "index": "289",
            "xExact": "",
            "x": "290",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:1777"
          },
          {
            "series": "1",
            "index": "289",
            "xExact": "",
            "x": "290",
            "yExact": "",
            "y": "1",
            "id": "person:1777"
          },
          {
            "series": "0",
            "index": "290",
            "xExact": "",
            "x": "291",
            "yExact": "",
            "y": "0.667910448",
            "id": "person:1781"
          },
          {
            "series": "1",
            "index": "290",
            "xExact": "",
            "x": "291",
            "yExact": "",
            "y": "0",
            "id": "person:1781"
          },
          {
            "series": "0",
            "index": "291",
            "xExact": "",
            "x": "292",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:1785"
          },
          {
            "series": "1",
            "index": "291",
            "xExact": "",
            "x": "292",
            "yExact": "",
            "y": "0",
            "id": "person:1785"
          },
          {
            "series": "0",
            "index": "292",
            "xExact": "",
            "x": "293",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:1800"
          },
          {
            "series": "1",
            "index": "292",
            "xExact": "",
            "x": "293",
            "yExact": "",
            "y": "1",
            "id": "person:1800"
          },
          {
            "series": "0",
            "index": "293",
            "xExact": "",
            "x": "294",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:1801"
          },
          {
            "series": "1",
            "index": "293",
            "xExact": "",
            "x": "294",
            "yExact": "",
            "y": "0",
            "id": "person:1801"
          },
          {
            "series": "0",
            "index": "294",
            "xExact": "",
            "x": "295",
            "yExact": "",
            "y": "0.667910448",
            "id": "person:1804"
          },
          {
            "series": "1",
            "index": "294",
            "xExact": "",
            "x": "295",
            "yExact": "",
            "y": "1",
            "id": "person:1804"
          },
          {
            "series": "0",
            "index": "295",
            "xExact": "",
            "x": "296",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:1808"
          },
          {
            "series": "1",
            "index": "295",
            "xExact": "",
            "x": "296",
            "yExact": "",
            "y": "0",
            "id": "person:1808"
          },
          {
            "series": "0",
            "index": "296",
            "xExact": "",
            "x": "297",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:1811"
          },
          {
            "series": "1",
            "index": "296",
            "xExact": "",
            "x": "297",
            "yExact": "",
            "y": "1",
            "id": "person:1811"
          },
          {
            "series": "0",
            "index": "297",
            "xExact": "",
            "x": "298",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:1823"
          },
          {
            "series": "1",
            "index": "297",
            "xExact": "",
            "x": "298",
            "yExact": "",
            "y": "1",
            "id": "person:1823"
          },
          {
            "series": "0",
            "index": "298",
            "xExact": "",
            "x": "299",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:1825"
          },
          {
            "series": "1",
            "index": "298",
            "xExact": "",
            "x": "299",
            "yExact": "",
            "y": "1",
            "id": "person:1825"
          },
          {
            "series": "0",
            "index": "299",
            "xExact": "",
            "x": "300",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:1826"
          },
          {
            "series": "1",
            "index": "299",
            "xExact": "",
            "x": "300",
            "yExact": "",
            "y": "1",
            "id": "person:1826"
          },
          {
            "series": "0",
            "index": "300",
            "xExact": "",
            "x": "301",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:1828"
          },
          {
            "series": "1",
            "index": "300",
            "xExact": "",
            "x": "301",
            "yExact": "",
            "y": "0",
            "id": "person:1828"
          },
          {
            "series": "0",
            "index": "301",
            "xExact": "",
            "x": "302",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:1837"
          },
          {
            "series": "1",
            "index": "301",
            "xExact": "",
            "x": "302",
            "yExact": "",
            "y": "1",
            "id": "person:1837"
          },
          {
            "series": "0",
            "index": "302",
            "xExact": "",
            "x": "303",
            "yExact": "",
            "y": "0.824267782",
            "id": "person:1842"
          },
          {
            "series": "1",
            "index": "302",
            "xExact": "",
            "x": "303",
            "yExact": "",
            "y": "0",
            "id": "person:1842"
          },
          {
            "series": "0",
            "index": "303",
            "xExact": "",
            "x": "304",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:1852"
          },
          {
            "series": "1",
            "index": "303",
            "xExact": "",
            "x": "304",
            "yExact": "",
            "y": "1",
            "id": "person:1852"
          },
          {
            "series": "0",
            "index": "304",
            "xExact": "",
            "x": "305",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:1853"
          },
          {
            "series": "1",
            "index": "304",
            "xExact": "",
            "x": "305",
            "yExact": "",
            "y": "1",
            "id": "person:1853"
          },
          {
            "series": "0",
            "index": "305",
            "xExact": "",
            "x": "306",
            "yExact": "",
            "y": "0.824267782",
            "id": "person:1859"
          },
          {
            "series": "1",
            "index": "305",
            "xExact": "",
            "x": "306",
            "yExact": "",
            "y": "1",
            "id": "person:1859"
          },
          {
            "series": "0",
            "index": "306",
            "xExact": "",
            "x": "307",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:1861"
          },
          {
            "series": "1",
            "index": "306",
            "xExact": "",
            "x": "307",
            "yExact": "",
            "y": "1",
            "id": "person:1861"
          },
          {
            "series": "0",
            "index": "307",
            "xExact": "",
            "x": "308",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:1864"
          },
          {
            "series": "1",
            "index": "307",
            "xExact": "",
            "x": "308",
            "yExact": "",
            "y": "1",
            "id": "person:1864"
          },
          {
            "series": "0",
            "index": "308",
            "xExact": "",
            "x": "309",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:1867"
          },
          {
            "series": "1",
            "index": "308",
            "xExact": "",
            "x": "309",
            "yExact": "",
            "y": "1",
            "id": "person:1867"
          },
          {
            "series": "0",
            "index": "309",
            "xExact": "",
            "x": "310",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:1871"
          },
          {
            "series": "1",
            "index": "309",
            "xExact": "",
            "x": "310",
            "yExact": "",
            "y": "1",
            "id": "person:1871"
          },
          {
            "series": "0",
            "index": "310",
            "xExact": "",
            "x": "311",
            "yExact": "",
            "y": "0.667910448",
            "id": "person:1881"
          },
          {
            "series": "1",
            "index": "310",
            "xExact": "",
            "x": "311",
            "yExact": "",
            "y": "0",
            "id": "person:1881"
          },
          {
            "series": "0",
            "index": "311",
            "xExact": "",
            "x": "312",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:1886"
          },
          {
            "series": "1",
            "index": "311",
            "xExact": "",
            "x": "312",
            "yExact": "",
            "y": "1",
            "id": "person:1886"
          },
          {
            "series": "0",
            "index": "312",
            "xExact": "",
            "x": "313",
            "yExact": "",
            "y": "0.824267782",
            "id": "person:1890"
          },
          {
            "series": "1",
            "index": "312",
            "xExact": "",
            "x": "313",
            "yExact": "",
            "y": "1",
            "id": "person:1890"
          },
          {
            "series": "0",
            "index": "313",
            "xExact": "",
            "x": "314",
            "yExact": "",
            "y": "0.667910448",
            "id": "person:1898"
          },
          {
            "series": "1",
            "index": "313",
            "xExact": "",
            "x": "314",
            "yExact": "",
            "y": "0",
            "id": "person:1898"
          },
          {
            "series": "0",
            "index": "314",
            "xExact": "",
            "x": "315",
            "yExact": "",
            "y": "0.362068966",
            "id": "person:1900"
          },
          {
            "series": "1",
            "index": "314",
            "xExact": "",
            "x": "315",
            "yExact": "",
            "y": "1",
            "id": "person:1900"
          },
          {
            "series": "0",
            "index": "315",
            "xExact": "",
            "x": "316",
            "yExact": "",
            "y": "0.487804878",
            "id": "person:1902"
          },
          {
            "series": "1",
            "index": "315",
            "xExact": "",
            "x": "316",
            "yExact": "",
            "y": "1",
            "id": "person:1902"
          },
          {
            "series": "0",
            "index": "316",
            "xExact": "",
            "x": "317",
            "yExact": "",
            "y": "0.487804878",
            "id": "person:1909"
          },
          {
            "series": "1",
            "index": "316",
            "xExact": "",
            "x": "317",
            "yExact": "",
            "y": "1",
            "id": "person:1909"
          },
          {
            "series": "0",
            "index": "317",
            "xExact": "",
            "x": "318",
            "yExact": "",
            "y": "0.487804878",
            "id": "person:1912"
          },
          {
            "series": "1",
            "index": "317",
            "xExact": "",
            "x": "318",
            "yExact": "",
            "y": "0",
            "id": "person:1912"
          },
          {
            "series": "0",
            "index": "318",
            "xExact": "",
            "x": "319",
            "yExact": "",
            "y": "0.362068966",
            "id": "person:1916"
          },
          {
            "series": "1",
            "index": "318",
            "xExact": "",
            "x": "319",
            "yExact": "",
            "y": "1",
            "id": "person:1916"
          },
          {
            "series": "0",
            "index": "319",
            "xExact": "",
            "x": "320",
            "yExact": "",
            "y": "0.362068966",
            "id": "person:1918"
          },
          {
            "series": "1",
            "index": "319",
            "xExact": "",
            "x": "320",
            "yExact": "",
            "y": "1",
            "id": "person:1918"
          },
          {
            "series": "0",
            "index": "320",
            "xExact": "",
            "x": "321",
            "yExact": "",
            "y": "0.362068966",
            "id": "person:1922"
          },
          {
            "series": "1",
            "index": "320",
            "xExact": "",
            "x": "321",
            "yExact": "",
            "y": "0",
            "id": "person:1922"
          },
          {
            "series": "0",
            "index": "321",
            "xExact": "",
            "x": "322",
            "yExact": "",
            "y": "0.362068966",
            "id": "person:1923"
          },
          {
            "series": "1",
            "index": "321",
            "xExact": "",
            "x": "322",
            "yExact": "",
            "y": "0",
            "id": "person:1923"
          },
          {
            "series": "0",
            "index": "322",
            "xExact": "",
            "x": "323",
            "yExact": "",
            "y": "0.362068966",
            "id": "person:1929"
          },
          {
            "series": "1",
            "index": "322",
            "xExact": "",
            "x": "323",
            "yExact": "",
            "y": "1",
            "id": "person:1929"
          },
          {
            "series": "0",
            "index": "323",
            "xExact": "",
            "x": "324",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:1933"
          },
          {
            "series": "1",
            "index": "323",
            "xExact": "",
            "x": "324",
            "yExact": "",
            "y": "0",
            "id": "person:1933"
          },
          {
            "series": "0",
            "index": "324",
            "xExact": "",
            "x": "325",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:1934"
          },
          {
            "series": "1",
            "index": "324",
            "xExact": "",
            "x": "325",
            "yExact": "",
            "y": "0",
            "id": "person:1934"
          },
          {
            "series": "0",
            "index": "325",
            "xExact": "",
            "x": "326",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:1935"
          },
          {
            "series": "1",
            "index": "325",
            "xExact": "",
            "x": "326",
            "yExact": "",
            "y": "0",
            "id": "person:1935"
          },
          {
            "series": "0",
            "index": "326",
            "xExact": "",
            "x": "327",
            "yExact": "",
            "y": "0.667910448",
            "id": "person:1943"
          },
          {
            "series": "1",
            "index": "326",
            "xExact": "",
            "x": "327",
            "yExact": "",
            "y": "0",
            "id": "person:1943"
          },
          {
            "series": "0",
            "index": "327",
            "xExact": "",
            "x": "328",
            "yExact": "",
            "y": "0.667910448",
            "id": "person:1945"
          },
          {
            "series": "1",
            "index": "327",
            "xExact": "",
            "x": "328",
            "yExact": "",
            "y": "1",
            "id": "person:1945"
          },
          {
            "series": "0",
            "index": "328",
            "xExact": "",
            "x": "329",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:1958"
          },
          {
            "series": "1",
            "index": "328",
            "xExact": "",
            "x": "329",
            "yExact": "",
            "y": "0",
            "id": "person:1958"
          },
          {
            "series": "0",
            "index": "329",
            "xExact": "",
            "x": "330",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:1971"
          },
          {
            "series": "1",
            "index": "329",
            "xExact": "",
            "x": "330",
            "yExact": "",
            "y": "0",
            "id": "person:1971"
          },
          {
            "series": "0",
            "index": "330",
            "xExact": "",
            "x": "331",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:1980"
          },
          {
            "series": "1",
            "index": "330",
            "xExact": "",
            "x": "331",
            "yExact": "",
            "y": "0",
            "id": "person:1980"
          },
          {
            "series": "0",
            "index": "331",
            "xExact": "",
            "x": "332",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:1989"
          },
          {
            "series": "1",
            "index": "331",
            "xExact": "",
            "x": "332",
            "yExact": "",
            "y": "1",
            "id": "person:1989"
          },
          {
            "series": "0",
            "index": "332",
            "xExact": "",
            "x": "333",
            "yExact": "",
            "y": "0.667910448",
            "id": "person:1996"
          },
          {
            "series": "1",
            "index": "332",
            "xExact": "",
            "x": "333",
            "yExact": "",
            "y": "1",
            "id": "person:1996"
          },
          {
            "series": "0",
            "index": "333",
            "xExact": "",
            "x": "334",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:1999"
          },
          {
            "series": "1",
            "index": "333",
            "xExact": "",
            "x": "334",
            "yExact": "",
            "y": "0",
            "id": "person:1999"
          },
          {
            "series": "0",
            "index": "334",
            "xExact": "",
            "x": "335",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:2007"
          },
          {
            "series": "1",
            "index": "334",
            "xExact": "",
            "x": "335",
            "yExact": "",
            "y": "0",
            "id": "person:2007"
          },
          {
            "series": "0",
            "index": "335",
            "xExact": "",
            "x": "336",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:2015"
          },
          {
            "series": "1",
            "index": "335",
            "xExact": "",
            "x": "336",
            "yExact": "",
            "y": "0",
            "id": "person:2015"
          },
          {
            "series": "0",
            "index": "336",
            "xExact": "",
            "x": "337",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:2018"
          },
          {
            "series": "1",
            "index": "336",
            "xExact": "",
            "x": "337",
            "yExact": "",
            "y": "0",
            "id": "person:2018"
          },
          {
            "series": "0",
            "index": "337",
            "xExact": "",
            "x": "338",
            "yExact": "",
            "y": "0.667910448",
            "id": "person:2021"
          },
          {
            "series": "1",
            "index": "337",
            "xExact": "",
            "x": "338",
            "yExact": "",
            "y": "0",
            "id": "person:2021"
          },
          {
            "series": "0",
            "index": "338",
            "xExact": "",
            "x": "339",
            "yExact": "",
            "y": "0.824267782",
            "id": "person:2026"
          },
          {
            "series": "1",
            "index": "338",
            "xExact": "",
            "x": "339",
            "yExact": "",
            "y": "1",
            "id": "person:2026"
          },
          {
            "series": "0",
            "index": "339",
            "xExact": "",
            "x": "340",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:2034"
          },
          {
            "series": "1",
            "index": "339",
            "xExact": "",
            "x": "340",
            "yExact": "",
            "y": "0",
            "id": "person:2034"
          },
          {
            "series": "0",
            "index": "340",
            "xExact": "",
            "x": "341",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:2038"
          },
          {
            "series": "1",
            "index": "340",
            "xExact": "",
            "x": "341",
            "yExact": "",
            "y": "1",
            "id": "person:2038"
          },
          {
            "series": "0",
            "index": "341",
            "xExact": "",
            "x": "342",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:2040"
          },
          {
            "series": "1",
            "index": "341",
            "xExact": "",
            "x": "342",
            "yExact": "",
            "y": "0",
            "id": "person:2040"
          },
          {
            "series": "0",
            "index": "342",
            "xExact": "",
            "x": "343",
            "yExact": "",
            "y": "0.824267782",
            "id": "person:2048"
          },
          {
            "series": "1",
            "index": "342",
            "xExact": "",
            "x": "343",
            "yExact": "",
            "y": "1",
            "id": "person:2048"
          },
          {
            "series": "0",
            "index": "343",
            "xExact": "",
            "x": "344",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:2049"
          },
          {
            "series": "1",
            "index": "343",
            "xExact": "",
            "x": "344",
            "yExact": "",
            "y": "0",
            "id": "person:2049"
          },
          {
            "series": "0",
            "index": "344",
            "xExact": "",
            "x": "345",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:2058"
          },
          {
            "series": "1",
            "index": "344",
            "xExact": "",
            "x": "345",
            "yExact": "",
            "y": "1",
            "id": "person:2058"
          },
          {
            "series": "0",
            "index": "345",
            "xExact": "",
            "x": "346",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:2076"
          },
          {
            "series": "1",
            "index": "345",
            "xExact": "",
            "x": "346",
            "yExact": "",
            "y": "0",
            "id": "person:2076"
          },
          {
            "series": "0",
            "index": "346",
            "xExact": "",
            "x": "347",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:2077"
          },
          {
            "series": "1",
            "index": "346",
            "xExact": "",
            "x": "347",
            "yExact": "",
            "y": "0",
            "id": "person:2077"
          },
          {
            "series": "0",
            "index": "347",
            "xExact": "",
            "x": "348",
            "yExact": "",
            "y": "0.48",
            "id": "person:2084"
          },
          {
            "series": "1",
            "index": "347",
            "xExact": "",
            "x": "348",
            "yExact": "",
            "y": "1",
            "id": "person:2084"
          },
          {
            "series": "0",
            "index": "348",
            "xExact": "",
            "x": "349",
            "yExact": "",
            "y": "0.487804878",
            "id": "person:2091"
          },
          {
            "series": "1",
            "index": "348",
            "xExact": "",
            "x": "349",
            "yExact": "",
            "y": "1",
            "id": "person:2091"
          },
          {
            "series": "0",
            "index": "349",
            "xExact": "",
            "x": "350",
            "yExact": "",
            "y": "0.48",
            "id": "person:2100"
          },
          {
            "series": "1",
            "index": "349",
            "xExact": "",
            "x": "350",
            "yExact": "",
            "y": "1",
            "id": "person:2100"
          },
          {
            "series": "0",
            "index": "350",
            "xExact": "",
            "x": "351",
            "yExact": "",
            "y": "0.362068966",
            "id": "person:2103"
          },
          {
            "series": "1",
            "index": "350",
            "xExact": "",
            "x": "351",
            "yExact": "",
            "y": "1",
            "id": "person:2103"
          },
          {
            "series": "0",
            "index": "351",
            "xExact": "",
            "x": "352",
            "yExact": "",
            "y": "0.757575758",
            "id": "person:2106"
          },
          {
            "series": "1",
            "index": "351",
            "xExact": "",
            "x": "352",
            "yExact": "",
            "y": "1",
            "id": "person:2106"
          },
          {
            "series": "0",
            "index": "352",
            "xExact": "",
            "x": "353",
            "yExact": "",
            "y": "0.487804878",
            "id": "person:2110"
          },
          {
            "series": "1",
            "index": "352",
            "xExact": "",
            "x": "353",
            "yExact": "",
            "y": "1",
            "id": "person:2110"
          },
          {
            "series": "0",
            "index": "353",
            "xExact": "",
            "x": "354",
            "yExact": "",
            "y": "0.667910448",
            "id": "person:2127"
          },
          {
            "series": "1",
            "index": "353",
            "xExact": "",
            "x": "354",
            "yExact": "",
            "y": "1",
            "id": "person:2127"
          },
          {
            "series": "0",
            "index": "354",
            "xExact": "",
            "x": "355",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:2132"
          },
          {
            "series": "1",
            "index": "354",
            "xExact": "",
            "x": "355",
            "yExact": "",
            "y": "1",
            "id": "person:2132"
          },
          {
            "series": "0",
            "index": "355",
            "xExact": "",
            "x": "356",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:2135"
          },
          {
            "series": "1",
            "index": "355",
            "xExact": "",
            "x": "356",
            "yExact": "",
            "y": "0",
            "id": "person:2135"
          },
          {
            "series": "0",
            "index": "356",
            "xExact": "",
            "x": "357",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:2138"
          },
          {
            "series": "1",
            "index": "356",
            "xExact": "",
            "x": "357",
            "yExact": "",
            "y": "0",
            "id": "person:2138"
          },
          {
            "series": "0",
            "index": "357",
            "xExact": "",
            "x": "358",
            "yExact": "",
            "y": "0.667910448",
            "id": "person:2143"
          },
          {
            "series": "1",
            "index": "357",
            "xExact": "",
            "x": "358",
            "yExact": "",
            "y": "0",
            "id": "person:2143"
          },
          {
            "series": "0",
            "index": "358",
            "xExact": "",
            "x": "359",
            "yExact": "",
            "y": "0.48",
            "id": "person:2156"
          },
          {
            "series": "1",
            "index": "358",
            "xExact": "",
            "x": "359",
            "yExact": "",
            "y": "0",
            "id": "person:2156"
          },
          {
            "series": "0",
            "index": "359",
            "xExact": "",
            "x": "360",
            "yExact": "",
            "y": "0.48",
            "id": "person:2170"
          },
          {
            "series": "1",
            "index": "359",
            "xExact": "",
            "x": "360",
            "yExact": "",
            "y": "0",
            "id": "person:2170"
          },
          {
            "series": "0",
            "index": "360",
            "xExact": "",
            "x": "361",
            "yExact": "",
            "y": "0.362068966",
            "id": "person:2172"
          },
          {
            "series": "1",
            "index": "360",
            "xExact": "",
            "x": "361",
            "yExact": "",
            "y": "0",
            "id": "person:2172"
          },
          {
            "series": "0",
            "index": "361",
            "xExact": "",
            "x": "362",
            "yExact": "",
            "y": "0.487804878",
            "id": "person:2173"
          },
          {
            "series": "1",
            "index": "361",
            "xExact": "",
            "x": "362",
            "yExact": "",
            "y": "0",
            "id": "person:2173"
          },
          {
            "series": "0",
            "index": "362",
            "xExact": "",
            "x": "363",
            "yExact": "",
            "y": "0.48",
            "id": "person:2182"
          },
          {
            "series": "1",
            "index": "362",
            "xExact": "",
            "x": "363",
            "yExact": "",
            "y": "0",
            "id": "person:2182"
          },
          {
            "series": "0",
            "index": "363",
            "xExact": "",
            "x": "364",
            "yExact": "",
            "y": "0.487804878",
            "id": "person:2194"
          },
          {
            "series": "1",
            "index": "363",
            "xExact": "",
            "x": "364",
            "yExact": "",
            "y": "1",
            "id": "person:2194"
          },
          {
            "series": "0",
            "index": "364",
            "xExact": "",
            "x": "365",
            "yExact": "",
            "y": "0.667910448",
            "id": "person:2199"
          },
          {
            "series": "1",
            "index": "364",
            "xExact": "",
            "x": "365",
            "yExact": "",
            "y": "0",
            "id": "person:2199"
          },
          {
            "series": "0",
            "index": "365",
            "xExact": "",
            "x": "366",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:2201"
          },
          {
            "series": "1",
            "index": "365",
            "xExact": "",
            "x": "366",
            "yExact": "",
            "y": "0",
            "id": "person:2201"
          },
          {
            "series": "0",
            "index": "366",
            "xExact": "",
            "x": "367",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:2203"
          },
          {
            "series": "1",
            "index": "366",
            "xExact": "",
            "x": "367",
            "yExact": "",
            "y": "0",
            "id": "person:2203"
          },
          {
            "series": "0",
            "index": "367",
            "xExact": "",
            "x": "368",
            "yExact": "",
            "y": "0.667910448",
            "id": "person:2214"
          },
          {
            "series": "1",
            "index": "367",
            "xExact": "",
            "x": "368",
            "yExact": "",
            "y": "1",
            "id": "person:2214"
          },
          {
            "series": "0",
            "index": "368",
            "xExact": "",
            "x": "369",
            "yExact": "",
            "y": "0.362068966",
            "id": "person:2216"
          },
          {
            "series": "1",
            "index": "368",
            "xExact": "",
            "x": "369",
            "yExact": "",
            "y": "0",
            "id": "person:2216"
          },
          {
            "series": "0",
            "index": "369",
            "xExact": "",
            "x": "370",
            "yExact": "",
            "y": "0.362068966",
            "id": "person:2224"
          },
          {
            "series": "1",
            "index": "369",
            "xExact": "",
            "x": "370",
            "yExact": "",
            "y": "1",
            "id": "person:2224"
          },
          {
            "series": "0",
            "index": "370",
            "xExact": "",
            "x": "371",
            "yExact": "",
            "y": "0.824267782",
            "id": "person:2235"
          },
          {
            "series": "1",
            "index": "370",
            "xExact": "",
            "x": "371",
            "yExact": "",
            "y": "1",
            "id": "person:2235"
          },
          {
            "series": "0",
            "index": "371",
            "xExact": "",
            "x": "372",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:2237"
          },
          {
            "series": "1",
            "index": "371",
            "xExact": "",
            "x": "372",
            "yExact": "",
            "y": "0",
            "id": "person:2237"
          },
          {
            "series": "0",
            "index": "372",
            "xExact": "",
            "x": "373",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:2243"
          },
          {
            "series": "1",
            "index": "372",
            "xExact": "",
            "x": "373",
            "yExact": "",
            "y": "0",
            "id": "person:2243"
          },
          {
            "series": "0",
            "index": "373",
            "xExact": "",
            "x": "374",
            "yExact": "",
            "y": "0.48",
            "id": "person:2249"
          },
          {
            "series": "1",
            "index": "373",
            "xExact": "",
            "x": "374",
            "yExact": "",
            "y": "1",
            "id": "person:2249"
          },
          {
            "series": "0",
            "index": "374",
            "xExact": "",
            "x": "375",
            "yExact": "",
            "y": "0.362068966",
            "id": "person:2251"
          },
          {
            "series": "1",
            "index": "374",
            "xExact": "",
            "x": "375",
            "yExact": "",
            "y": "0",
            "id": "person:2251"
          },
          {
            "series": "0",
            "index": "375",
            "xExact": "",
            "x": "376",
            "yExact": "",
            "y": "0.757575758",
            "id": "person:2254"
          },
          {
            "series": "1",
            "index": "375",
            "xExact": "",
            "x": "376",
            "yExact": "",
            "y": "1",
            "id": "person:2254"
          },
          {
            "series": "0",
            "index": "376",
            "xExact": "",
            "x": "377",
            "yExact": "",
            "y": "0.667910448",
            "id": "person:2266"
          },
          {
            "series": "1",
            "index": "376",
            "xExact": "",
            "x": "377",
            "yExact": "",
            "y": "1",
            "id": "person:2266"
          },
          {
            "series": "0",
            "index": "377",
            "xExact": "",
            "x": "378",
            "yExact": "",
            "y": "0.667910448",
            "id": "person:2268"
          },
          {
            "series": "1",
            "index": "377",
            "xExact": "",
            "x": "378",
            "yExact": "",
            "y": "0",
            "id": "person:2268"
          },
          {
            "series": "0",
            "index": "378",
            "xExact": "",
            "x": "379",
            "yExact": "",
            "y": "0.667910448",
            "id": "person:2275"
          },
          {
            "series": "1",
            "index": "378",
            "xExact": "",
            "x": "379",
            "yExact": "",
            "y": "1",
            "id": "person:2275"
          },
          {
            "series": "0",
            "index": "379",
            "xExact": "",
            "x": "380",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:2277"
          },
          {
            "series": "1",
            "index": "379",
            "xExact": "",
            "x": "380",
            "yExact": "",
            "y": "0",
            "id": "person:2277"
          },
          {
            "series": "0",
            "index": "380",
            "xExact": "",
            "x": "381",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:2282"
          },
          {
            "series": "1",
            "index": "380",
            "xExact": "",
            "x": "381",
            "yExact": "",
            "y": "0",
            "id": "person:2282"
          },
          {
            "series": "0",
            "index": "381",
            "xExact": "",
            "x": "382",
            "yExact": "",
            "y": "0.667910448",
            "id": "person:2286"
          },
          {
            "series": "1",
            "index": "381",
            "xExact": "",
            "x": "382",
            "yExact": "",
            "y": "0",
            "id": "person:2286"
          },
          {
            "series": "0",
            "index": "382",
            "xExact": "",
            "x": "383",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:2287"
          },
          {
            "series": "1",
            "index": "382",
            "xExact": "",
            "x": "383",
            "yExact": "",
            "y": "1",
            "id": "person:2287"
          },
          {
            "series": "0",
            "index": "383",
            "xExact": "",
            "x": "384",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:2293"
          },
          {
            "series": "1",
            "index": "383",
            "xExact": "",
            "x": "384",
            "yExact": "",
            "y": "0",
            "id": "person:2293"
          },
          {
            "series": "0",
            "index": "384",
            "xExact": "",
            "x": "385",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:2303"
          },
          {
            "series": "1",
            "index": "384",
            "xExact": "",
            "x": "385",
            "yExact": "",
            "y": "0",
            "id": "person:2303"
          },
          {
            "series": "0",
            "index": "385",
            "xExact": "",
            "x": "386",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:2307"
          },
          {
            "series": "1",
            "index": "385",
            "xExact": "",
            "x": "386",
            "yExact": "",
            "y": "1",
            "id": "person:2307"
          },
          {
            "series": "0",
            "index": "386",
            "xExact": "",
            "x": "387",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:2313"
          },
          {
            "series": "1",
            "index": "386",
            "xExact": "",
            "x": "387",
            "yExact": "",
            "y": "0",
            "id": "person:2313"
          },
          {
            "series": "0",
            "index": "387",
            "xExact": "",
            "x": "388",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:2318"
          },
          {
            "series": "1",
            "index": "387",
            "xExact": "",
            "x": "388",
            "yExact": "",
            "y": "0",
            "id": "person:2318"
          },
          {
            "series": "0",
            "index": "388",
            "xExact": "",
            "x": "389",
            "yExact": "",
            "y": "0.667910448",
            "id": "person:2320"
          },
          {
            "series": "1",
            "index": "388",
            "xExact": "",
            "x": "389",
            "yExact": "",
            "y": "0",
            "id": "person:2320"
          },
          {
            "series": "0",
            "index": "389",
            "xExact": "",
            "x": "390",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:2321"
          },
          {
            "series": "1",
            "index": "389",
            "xExact": "",
            "x": "390",
            "yExact": "",
            "y": "0",
            "id": "person:2321"
          },
          {
            "series": "0",
            "index": "390",
            "xExact": "",
            "x": "391",
            "yExact": "",
            "y": "0.667910448",
            "id": "person:2334"
          },
          {
            "series": "1",
            "index": "390",
            "xExact": "",
            "x": "391",
            "yExact": "",
            "y": "1",
            "id": "person:2334"
          },
          {
            "series": "0",
            "index": "391",
            "xExact": "",
            "x": "392",
            "yExact": "",
            "y": "0.667910448",
            "id": "person:2335"
          },
          {
            "series": "1",
            "index": "391",
            "xExact": "",
            "x": "392",
            "yExact": "",
            "y": "1",
            "id": "person:2335"
          },
          {
            "series": "0",
            "index": "392",
            "xExact": "",
            "x": "393",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:2340"
          },
          {
            "series": "1",
            "index": "392",
            "xExact": "",
            "x": "393",
            "yExact": "",
            "y": "0",
            "id": "person:2340"
          },
          {
            "series": "0",
            "index": "393",
            "xExact": "",
            "x": "394",
            "yExact": "",
            "y": "0.667910448",
            "id": "person:2353"
          },
          {
            "series": "1",
            "index": "393",
            "xExact": "",
            "x": "394",
            "yExact": "",
            "y": "0",
            "id": "person:2353"
          },
          {
            "series": "0",
            "index": "394",
            "xExact": "",
            "x": "395",
            "yExact": "",
            "y": "0.824267782",
            "id": "person:2359"
          },
          {
            "series": "1",
            "index": "394",
            "xExact": "",
            "x": "395",
            "yExact": "",
            "y": "1",
            "id": "person:2359"
          },
          {
            "series": "0",
            "index": "395",
            "xExact": "",
            "x": "396",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:2370"
          },
          {
            "series": "1",
            "index": "395",
            "xExact": "",
            "x": "396",
            "yExact": "",
            "y": "0",
            "id": "person:2370"
          },
          {
            "series": "0",
            "index": "396",
            "xExact": "",
            "x": "397",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:2385"
          },
          {
            "series": "1",
            "index": "396",
            "xExact": "",
            "x": "397",
            "yExact": "",
            "y": "0",
            "id": "person:2385"
          },
          {
            "series": "0",
            "index": "397",
            "xExact": "",
            "x": "398",
            "yExact": "",
            "y": "0.757575758",
            "id": "person:2392"
          },
          {
            "series": "1",
            "index": "397",
            "xExact": "",
            "x": "398",
            "yExact": "",
            "y": "1",
            "id": "person:2392"
          },
          {
            "series": "0",
            "index": "398",
            "xExact": "",
            "x": "399",
            "yExact": "",
            "y": "0.362068966",
            "id": "person:2395"
          },
          {
            "series": "1",
            "index": "398",
            "xExact": "",
            "x": "399",
            "yExact": "",
            "y": "0",
            "id": "person:2395"
          },
          {
            "series": "0",
            "index": "399",
            "xExact": "",
            "x": "400",
            "yExact": "",
            "y": "0.48",
            "id": "person:2397"
          },
          {
            "series": "1",
            "index": "399",
            "xExact": "",
            "x": "400",
            "yExact": "",
            "y": "1",
            "id": "person:2397"
          },
          {
            "series": "0",
            "index": "400",
            "xExact": "",
            "x": "401",
            "yExact": "",
            "y": "0.667910448",
            "id": "person:2400"
          },
          {
            "series": "1",
            "index": "400",
            "xExact": "",
            "x": "401",
            "yExact": "",
            "y": "1",
            "id": "person:2400"
          },
          {
            "series": "0",
            "index": "401",
            "xExact": "",
            "x": "402",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:2409"
          },
          {
            "series": "1",
            "index": "401",
            "xExact": "",
            "x": "402",
            "yExact": "",
            "y": "1",
            "id": "person:2409"
          },
          {
            "series": "0",
            "index": "402",
            "xExact": "",
            "x": "403",
            "yExact": "",
            "y": "0.667910448",
            "id": "person:2412"
          },
          {
            "series": "1",
            "index": "402",
            "xExact": "",
            "x": "403",
            "yExact": "",
            "y": "0",
            "id": "person:2412"
          },
          {
            "series": "0",
            "index": "403",
            "xExact": "",
            "x": "404",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:2416"
          },
          {
            "series": "1",
            "index": "403",
            "xExact": "",
            "x": "404",
            "yExact": "",
            "y": "0",
            "id": "person:2416"
          },
          {
            "series": "0",
            "index": "404",
            "xExact": "",
            "x": "405",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:2423"
          },
          {
            "series": "1",
            "index": "404",
            "xExact": "",
            "x": "405",
            "yExact": "",
            "y": "0",
            "id": "person:2423"
          },
          {
            "series": "0",
            "index": "405",
            "xExact": "",
            "x": "406",
            "yExact": "",
            "y": "0.487804878",
            "id": "person:2447"
          },
          {
            "series": "1",
            "index": "405",
            "xExact": "",
            "x": "406",
            "yExact": "",
            "y": "1",
            "id": "person:2447"
          },
          {
            "series": "0",
            "index": "406",
            "xExact": "",
            "x": "407",
            "yExact": "",
            "y": "0.757575758",
            "id": "person:2451"
          },
          {
            "series": "1",
            "index": "406",
            "xExact": "",
            "x": "407",
            "yExact": "",
            "y": "1",
            "id": "person:2451"
          },
          {
            "series": "0",
            "index": "407",
            "xExact": "",
            "x": "408",
            "yExact": "",
            "y": "0.487804878",
            "id": "person:2454"
          },
          {
            "series": "1",
            "index": "407",
            "xExact": "",
            "x": "408",
            "yExact": "",
            "y": "1",
            "id": "person:2454"
          },
          {
            "series": "0",
            "index": "408",
            "xExact": "",
            "x": "409",
            "yExact": "",
            "y": "0.48",
            "id": "person:2459"
          },
          {
            "series": "1",
            "index": "408",
            "xExact": "",
            "x": "409",
            "yExact": "",
            "y": "1",
            "id": "person:2459"
          },
          {
            "series": "0",
            "index": "409",
            "xExact": "",
            "x": "410",
            "yExact": "",
            "y": "0.48",
            "id": "person:2460"
          },
          {
            "series": "1",
            "index": "409",
            "xExact": "",
            "x": "410",
            "yExact": "",
            "y": "0",
            "id": "person:2460"
          },
          {
            "series": "0",
            "index": "410",
            "xExact": "",
            "x": "411",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:2467"
          },
          {
            "series": "1",
            "index": "410",
            "xExact": "",
            "x": "411",
            "yExact": "",
            "y": "1",
            "id": "person:2467"
          },
          {
            "series": "0",
            "index": "411",
            "xExact": "",
            "x": "412",
            "yExact": "",
            "y": "0.824267782",
            "id": "person:2470"
          },
          {
            "series": "1",
            "index": "411",
            "xExact": "",
            "x": "412",
            "yExact": "",
            "y": "1",
            "id": "person:2470"
          },
          {
            "series": "0",
            "index": "412",
            "xExact": "",
            "x": "413",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:2502"
          },
          {
            "series": "1",
            "index": "412",
            "xExact": "",
            "x": "413",
            "yExact": "",
            "y": "0",
            "id": "person:2502"
          },
          {
            "series": "0",
            "index": "413",
            "xExact": "",
            "x": "414",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:2504"
          },
          {
            "series": "1",
            "index": "413",
            "xExact": "",
            "x": "414",
            "yExact": "",
            "y": "0",
            "id": "person:2504"
          },
          {
            "series": "0",
            "index": "414",
            "xExact": "",
            "x": "415",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:2512"
          },
          {
            "series": "1",
            "index": "414",
            "xExact": "",
            "x": "415",
            "yExact": "",
            "y": "0",
            "id": "person:2512"
          },
          {
            "series": "0",
            "index": "415",
            "xExact": "",
            "x": "416",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:2517"
          },
          {
            "series": "1",
            "index": "415",
            "xExact": "",
            "x": "416",
            "yExact": "",
            "y": "1",
            "id": "person:2517"
          },
          {
            "series": "0",
            "index": "416",
            "xExact": "",
            "x": "417",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:2521"
          },
          {
            "series": "1",
            "index": "416",
            "xExact": "",
            "x": "417",
            "yExact": "",
            "y": "0",
            "id": "person:2521"
          },
          {
            "series": "0",
            "index": "417",
            "xExact": "",
            "x": "418",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:2531"
          },
          {
            "series": "1",
            "index": "417",
            "xExact": "",
            "x": "418",
            "yExact": "",
            "y": "1",
            "id": "person:2531"
          },
          {
            "series": "0",
            "index": "418",
            "xExact": "",
            "x": "419",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:2533"
          },
          {
            "series": "1",
            "index": "418",
            "xExact": "",
            "x": "419",
            "yExact": "",
            "y": "1",
            "id": "person:2533"
          },
          {
            "series": "0",
            "index": "419",
            "xExact": "",
            "x": "420",
            "yExact": "",
            "y": "0.824267782",
            "id": "person:2537"
          },
          {
            "series": "1",
            "index": "419",
            "xExact": "",
            "x": "420",
            "yExact": "",
            "y": "1",
            "id": "person:2537"
          },
          {
            "series": "0",
            "index": "420",
            "xExact": "",
            "x": "421",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:2543"
          },
          {
            "series": "1",
            "index": "420",
            "xExact": "",
            "x": "421",
            "yExact": "",
            "y": "1",
            "id": "person:2543"
          },
          {
            "series": "0",
            "index": "421",
            "xExact": "",
            "x": "422",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:2544"
          },
          {
            "series": "1",
            "index": "421",
            "xExact": "",
            "x": "422",
            "yExact": "",
            "y": "1",
            "id": "person:2544"
          },
          {
            "series": "0",
            "index": "422",
            "xExact": "",
            "x": "423",
            "yExact": "",
            "y": "0.824267782",
            "id": "person:2546"
          },
          {
            "series": "1",
            "index": "422",
            "xExact": "",
            "x": "423",
            "yExact": "",
            "y": "1",
            "id": "person:2546"
          },
          {
            "series": "0",
            "index": "423",
            "xExact": "",
            "x": "424",
            "yExact": "",
            "y": "0.824267782",
            "id": "person:2550"
          },
          {
            "series": "1",
            "index": "423",
            "xExact": "",
            "x": "424",
            "yExact": "",
            "y": "1",
            "id": "person:2550"
          },
          {
            "series": "0",
            "index": "424",
            "xExact": "",
            "x": "425",
            "yExact": "",
            "y": "0.824267782",
            "id": "person:2555"
          },
          {
            "series": "1",
            "index": "424",
            "xExact": "",
            "x": "425",
            "yExact": "",
            "y": "1",
            "id": "person:2555"
          },
          {
            "series": "0",
            "index": "425",
            "xExact": "",
            "x": "426",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:2563"
          },
          {
            "series": "1",
            "index": "425",
            "xExact": "",
            "x": "426",
            "yExact": "",
            "y": "1",
            "id": "person:2563"
          },
          {
            "series": "0",
            "index": "426",
            "xExact": "",
            "x": "427",
            "yExact": "",
            "y": "0.667910448",
            "id": "person:2564"
          },
          {
            "series": "1",
            "index": "426",
            "xExact": "",
            "x": "427",
            "yExact": "",
            "y": "1",
            "id": "person:2564"
          },
          {
            "series": "0",
            "index": "427",
            "xExact": "",
            "x": "428",
            "yExact": "",
            "y": "0.667910448",
            "id": "person:2568"
          },
          {
            "series": "1",
            "index": "427",
            "xExact": "",
            "x": "428",
            "yExact": "",
            "y": "1",
            "id": "person:2568"
          },
          {
            "series": "0",
            "index": "428",
            "xExact": "",
            "x": "429",
            "yExact": "",
            "y": "0.824267782",
            "id": "person:2575"
          },
          {
            "series": "1",
            "index": "428",
            "xExact": "",
            "x": "429",
            "yExact": "",
            "y": "0",
            "id": "person:2575"
          },
          {
            "series": "0",
            "index": "429",
            "xExact": "",
            "x": "430",
            "yExact": "",
            "y": "0.667910448",
            "id": "person:2580"
          },
          {
            "series": "1",
            "index": "429",
            "xExact": "",
            "x": "430",
            "yExact": "",
            "y": "1",
            "id": "person:2580"
          },
          {
            "series": "0",
            "index": "430",
            "xExact": "",
            "x": "431",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:2582"
          },
          {
            "series": "1",
            "index": "430",
            "xExact": "",
            "x": "431",
            "yExact": "",
            "y": "0",
            "id": "person:2582"
          },
          {
            "series": "0",
            "index": "431",
            "xExact": "",
            "x": "432",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:2585"
          },
          {
            "series": "1",
            "index": "431",
            "xExact": "",
            "x": "432",
            "yExact": "",
            "y": "1",
            "id": "person:2585"
          },
          {
            "series": "0",
            "index": "432",
            "xExact": "",
            "x": "433",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:2589"
          },
          {
            "series": "1",
            "index": "432",
            "xExact": "",
            "x": "433",
            "yExact": "",
            "y": "0",
            "id": "person:2589"
          },
          {
            "series": "0",
            "index": "433",
            "xExact": "",
            "x": "434",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:2600"
          },
          {
            "series": "1",
            "index": "433",
            "xExact": "",
            "x": "434",
            "yExact": "",
            "y": "1",
            "id": "person:2600"
          },
          {
            "series": "0",
            "index": "434",
            "xExact": "",
            "x": "435",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:2605"
          },
          {
            "series": "1",
            "index": "434",
            "xExact": "",
            "x": "435",
            "yExact": "",
            "y": "0",
            "id": "person:2605"
          },
          {
            "series": "0",
            "index": "435",
            "xExact": "",
            "x": "436",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:2608"
          },
          {
            "series": "1",
            "index": "435",
            "xExact": "",
            "x": "436",
            "yExact": "",
            "y": "1",
            "id": "person:2608"
          },
          {
            "series": "0",
            "index": "436",
            "xExact": "",
            "x": "437",
            "yExact": "",
            "y": "0.824267782",
            "id": "person:2614"
          },
          {
            "series": "1",
            "index": "436",
            "xExact": "",
            "x": "437",
            "yExact": "",
            "y": "1",
            "id": "person:2614"
          },
          {
            "series": "0",
            "index": "437",
            "xExact": "",
            "x": "438",
            "yExact": "",
            "y": "0.824267782",
            "id": "person:2619"
          },
          {
            "series": "1",
            "index": "437",
            "xExact": "",
            "x": "438",
            "yExact": "",
            "y": "1",
            "id": "person:2619"
          },
          {
            "series": "0",
            "index": "438",
            "xExact": "",
            "x": "439",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:2628"
          },
          {
            "series": "1",
            "index": "438",
            "xExact": "",
            "x": "439",
            "yExact": "",
            "y": "0",
            "id": "person:2628"
          },
          {
            "series": "0",
            "index": "439",
            "xExact": "",
            "x": "440",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:2642"
          },
          {
            "series": "1",
            "index": "439",
            "xExact": "",
            "x": "440",
            "yExact": "",
            "y": "0",
            "id": "person:2642"
          },
          {
            "series": "0",
            "index": "440",
            "xExact": "",
            "x": "441",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:2650"
          },
          {
            "series": "1",
            "index": "440",
            "xExact": "",
            "x": "441",
            "yExact": "",
            "y": "0",
            "id": "person:2650"
          },
          {
            "series": "0",
            "index": "441",
            "xExact": "",
            "x": "442",
            "yExact": "",
            "y": "0.824267782",
            "id": "person:2655"
          },
          {
            "series": "1",
            "index": "441",
            "xExact": "",
            "x": "442",
            "yExact": "",
            "y": "1",
            "id": "person:2655"
          },
          {
            "series": "0",
            "index": "442",
            "xExact": "",
            "x": "443",
            "yExact": "",
            "y": "0.824267782",
            "id": "person:2656"
          },
          {
            "series": "1",
            "index": "442",
            "xExact": "",
            "x": "443",
            "yExact": "",
            "y": "1",
            "id": "person:2656"
          },
          {
            "series": "0",
            "index": "443",
            "xExact": "",
            "x": "444",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:2661"
          },
          {
            "series": "1",
            "index": "443",
            "xExact": "",
            "x": "444",
            "yExact": "",
            "y": "0",
            "id": "person:2661"
          },
          {
            "series": "0",
            "index": "444",
            "xExact": "",
            "x": "445",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:2663"
          },
          {
            "series": "1",
            "index": "444",
            "xExact": "",
            "x": "445",
            "yExact": "",
            "y": "0",
            "id": "person:2663"
          },
          {
            "series": "0",
            "index": "445",
            "xExact": "",
            "x": "446",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:2671"
          },
          {
            "series": "1",
            "index": "445",
            "xExact": "",
            "x": "446",
            "yExact": "",
            "y": "1",
            "id": "person:2671"
          },
          {
            "series": "0",
            "index": "446",
            "xExact": "",
            "x": "447",
            "yExact": "",
            "y": "0.824267782",
            "id": "person:2676"
          },
          {
            "series": "1",
            "index": "446",
            "xExact": "",
            "x": "447",
            "yExact": "",
            "y": "0",
            "id": "person:2676"
          },
          {
            "series": "0",
            "index": "447",
            "xExact": "",
            "x": "448",
            "yExact": "",
            "y": "0.824267782",
            "id": "person:2693"
          },
          {
            "series": "1",
            "index": "447",
            "xExact": "",
            "x": "448",
            "yExact": "",
            "y": "1",
            "id": "person:2693"
          },
          {
            "series": "0",
            "index": "448",
            "xExact": "",
            "x": "449",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:2696"
          },
          {
            "series": "1",
            "index": "448",
            "xExact": "",
            "x": "449",
            "yExact": "",
            "y": "1",
            "id": "person:2696"
          },
          {
            "series": "0",
            "index": "449",
            "xExact": "",
            "x": "450",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:2703"
          },
          {
            "series": "1",
            "index": "449",
            "xExact": "",
            "x": "450",
            "yExact": "",
            "y": "1",
            "id": "person:2703"
          },
          {
            "series": "0",
            "index": "450",
            "xExact": "",
            "x": "451",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:2707"
          },
          {
            "series": "1",
            "index": "450",
            "xExact": "",
            "x": "451",
            "yExact": "",
            "y": "1",
            "id": "person:2707"
          },
          {
            "series": "0",
            "index": "451",
            "xExact": "",
            "x": "452",
            "yExact": "",
            "y": "0.667910448",
            "id": "person:2734"
          },
          {
            "series": "1",
            "index": "451",
            "xExact": "",
            "x": "452",
            "yExact": "",
            "y": "1",
            "id": "person:2734"
          },
          {
            "series": "0",
            "index": "452",
            "xExact": "",
            "x": "453",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:2737"
          },
          {
            "series": "1",
            "index": "452",
            "xExact": "",
            "x": "453",
            "yExact": "",
            "y": "1",
            "id": "person:2737"
          },
          {
            "series": "0",
            "index": "453",
            "xExact": "",
            "x": "454",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:2745"
          },
          {
            "series": "1",
            "index": "453",
            "xExact": "",
            "x": "454",
            "yExact": "",
            "y": "1",
            "id": "person:2745"
          },
          {
            "series": "0",
            "index": "454",
            "xExact": "",
            "x": "455",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:2747"
          },
          {
            "series": "1",
            "index": "454",
            "xExact": "",
            "x": "455",
            "yExact": "",
            "y": "1",
            "id": "person:2747"
          },
          {
            "series": "0",
            "index": "455",
            "xExact": "",
            "x": "456",
            "yExact": "",
            "y": "0.824267782",
            "id": "person:2750"
          },
          {
            "series": "1",
            "index": "455",
            "xExact": "",
            "x": "456",
            "yExact": "",
            "y": "1",
            "id": "person:2750"
          },
          {
            "series": "0",
            "index": "456",
            "xExact": "",
            "x": "457",
            "yExact": "",
            "y": "0.824267782",
            "id": "person:2752"
          },
          {
            "series": "1",
            "index": "456",
            "xExact": "",
            "x": "457",
            "yExact": "",
            "y": "1",
            "id": "person:2752"
          },
          {
            "series": "0",
            "index": "457",
            "xExact": "",
            "x": "458",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:2755"
          },
          {
            "series": "1",
            "index": "457",
            "xExact": "",
            "x": "458",
            "yExact": "",
            "y": "0",
            "id": "person:2755"
          },
          {
            "series": "0",
            "index": "458",
            "xExact": "",
            "x": "459",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:2756"
          },
          {
            "series": "1",
            "index": "458",
            "xExact": "",
            "x": "459",
            "yExact": "",
            "y": "0",
            "id": "person:2756"
          },
          {
            "series": "0",
            "index": "459",
            "xExact": "",
            "x": "460",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:2758"
          },
          {
            "series": "1",
            "index": "459",
            "xExact": "",
            "x": "460",
            "yExact": "",
            "y": "1",
            "id": "person:2758"
          },
          {
            "series": "0",
            "index": "460",
            "xExact": "",
            "x": "461",
            "yExact": "",
            "y": "0.667910448",
            "id": "person:2759"
          },
          {
            "series": "1",
            "index": "460",
            "xExact": "",
            "x": "461",
            "yExact": "",
            "y": "0",
            "id": "person:2759"
          },
          {
            "series": "0",
            "index": "461",
            "xExact": "",
            "x": "462",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:2771"
          },
          {
            "series": "1",
            "index": "461",
            "xExact": "",
            "x": "462",
            "yExact": "",
            "y": "1",
            "id": "person:2771"
          },
          {
            "series": "0",
            "index": "462",
            "xExact": "",
            "x": "463",
            "yExact": "",
            "y": "0.667910448",
            "id": "person:2773"
          },
          {
            "series": "1",
            "index": "462",
            "xExact": "",
            "x": "463",
            "yExact": "",
            "y": "1",
            "id": "person:2773"
          },
          {
            "series": "0",
            "index": "463",
            "xExact": "",
            "x": "464",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:2778"
          },
          {
            "series": "1",
            "index": "463",
            "xExact": "",
            "x": "464",
            "yExact": "",
            "y": "1",
            "id": "person:2778"
          },
          {
            "series": "0",
            "index": "464",
            "xExact": "",
            "x": "465",
            "yExact": "",
            "y": "0.362068966",
            "id": "person:2792"
          },
          {
            "series": "1",
            "index": "464",
            "xExact": "",
            "x": "465",
            "yExact": "",
            "y": "1",
            "id": "person:2792"
          },
          {
            "series": "0",
            "index": "465",
            "xExact": "",
            "x": "466",
            "yExact": "",
            "y": "0.487804878",
            "id": "person:2793"
          },
          {
            "series": "1",
            "index": "465",
            "xExact": "",
            "x": "466",
            "yExact": "",
            "y": "0",
            "id": "person:2793"
          },
          {
            "series": "0",
            "index": "466",
            "xExact": "",
            "x": "467",
            "yExact": "",
            "y": "0.757575758",
            "id": "person:2794"
          },
          {
            "series": "1",
            "index": "466",
            "xExact": "",
            "x": "467",
            "yExact": "",
            "y": "1",
            "id": "person:2794"
          },
          {
            "series": "0",
            "index": "467",
            "xExact": "",
            "x": "468",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:2798"
          },
          {
            "series": "1",
            "index": "467",
            "xExact": "",
            "x": "468",
            "yExact": "",
            "y": "1",
            "id": "person:2798"
          },
          {
            "series": "0",
            "index": "468",
            "xExact": "",
            "x": "469",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:2802"
          },
          {
            "series": "1",
            "index": "468",
            "xExact": "",
            "x": "469",
            "yExact": "",
            "y": "1",
            "id": "person:2802"
          },
          {
            "series": "0",
            "index": "469",
            "xExact": "",
            "x": "470",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:2821"
          },
          {
            "series": "1",
            "index": "469",
            "xExact": "",
            "x": "470",
            "yExact": "",
            "y": "0",
            "id": "person:2821"
          },
          {
            "series": "0",
            "index": "470",
            "xExact": "",
            "x": "471",
            "yExact": "",
            "y": "0.667910448",
            "id": "person:2835"
          },
          {
            "series": "1",
            "index": "470",
            "xExact": "",
            "x": "471",
            "yExact": "",
            "y": "1",
            "id": "person:2835"
          },
          {
            "series": "0",
            "index": "471",
            "xExact": "",
            "x": "472",
            "yExact": "",
            "y": "0.487804878",
            "id": "person:2850"
          },
          {
            "series": "1",
            "index": "471",
            "xExact": "",
            "x": "472",
            "yExact": "",
            "y": "1",
            "id": "person:2850"
          },
          {
            "series": "0",
            "index": "472",
            "xExact": "",
            "x": "473",
            "yExact": "",
            "y": "0.757575758",
            "id": "person:2851"
          },
          {
            "series": "1",
            "index": "472",
            "xExact": "",
            "x": "473",
            "yExact": "",
            "y": "1",
            "id": "person:2851"
          },
          {
            "series": "0",
            "index": "473",
            "xExact": "",
            "x": "474",
            "yExact": "",
            "y": "0.48",
            "id": "person:2859"
          },
          {
            "series": "1",
            "index": "473",
            "xExact": "",
            "x": "474",
            "yExact": "",
            "y": "1",
            "id": "person:2859"
          },
          {
            "series": "0",
            "index": "474",
            "xExact": "",
            "x": "475",
            "yExact": "",
            "y": "0.757575758",
            "id": "person:2863"
          },
          {
            "series": "1",
            "index": "474",
            "xExact": "",
            "x": "475",
            "yExact": "",
            "y": "1",
            "id": "person:2863"
          },
          {
            "series": "0",
            "index": "475",
            "xExact": "",
            "x": "476",
            "yExact": "",
            "y": "0.757575758",
            "id": "person:2865"
          },
          {
            "series": "1",
            "index": "475",
            "xExact": "",
            "x": "476",
            "yExact": "",
            "y": "1",
            "id": "person:2865"
          },
          {
            "series": "0",
            "index": "476",
            "xExact": "",
            "x": "477",
            "yExact": "",
            "y": "0.487804878",
            "id": "person:2868"
          },
          {
            "series": "1",
            "index": "476",
            "xExact": "",
            "x": "477",
            "yExact": "",
            "y": "1",
            "id": "person:2868"
          },
          {
            "series": "0",
            "index": "477",
            "xExact": "",
            "x": "478",
            "yExact": "",
            "y": "0.48",
            "id": "person:2887"
          },
          {
            "series": "1",
            "index": "477",
            "xExact": "",
            "x": "478",
            "yExact": "",
            "y": "0",
            "id": "person:2887"
          },
          {
            "series": "0",
            "index": "478",
            "xExact": "",
            "x": "479",
            "yExact": "",
            "y": "0.757575758",
            "id": "person:2894"
          },
          {
            "series": "1",
            "index": "478",
            "xExact": "",
            "x": "479",
            "yExact": "",
            "y": "1",
            "id": "person:2894"
          },
          {
            "series": "0",
            "index": "479",
            "xExact": "",
            "x": "480",
            "yExact": "",
            "y": "0.48",
            "id": "person:2897"
          },
          {
            "series": "1",
            "index": "479",
            "xExact": "",
            "x": "480",
            "yExact": "",
            "y": "0",
            "id": "person:2897"
          },
          {
            "series": "0",
            "index": "480",
            "xExact": "",
            "x": "481",
            "yExact": "",
            "y": "0.487804878",
            "id": "person:2902"
          },
          {
            "series": "1",
            "index": "480",
            "xExact": "",
            "x": "481",
            "yExact": "",
            "y": "0",
            "id": "person:2902"
          },
          {
            "series": "0",
            "index": "481",
            "xExact": "",
            "x": "482",
            "yExact": "",
            "y": "0.487804878",
            "id": "person:2909"
          },
          {
            "series": "1",
            "index": "481",
            "xExact": "",
            "x": "482",
            "yExact": "",
            "y": "1",
            "id": "person:2909"
          },
          {
            "series": "0",
            "index": "482",
            "xExact": "",
            "x": "483",
            "yExact": "",
            "y": "0.362068966",
            "id": "person:2910"
          },
          {
            "series": "1",
            "index": "482",
            "xExact": "",
            "x": "483",
            "yExact": "",
            "y": "1",
            "id": "person:2910"
          },
          {
            "series": "0",
            "index": "483",
            "xExact": "",
            "x": "484",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:2925"
          },
          {
            "series": "1",
            "index": "483",
            "xExact": "",
            "x": "484",
            "yExact": "",
            "y": "0",
            "id": "person:2925"
          },
          {
            "series": "0",
            "index": "484",
            "xExact": "",
            "x": "485",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:2928"
          },
          {
            "series": "1",
            "index": "484",
            "xExact": "",
            "x": "485",
            "yExact": "",
            "y": "1",
            "id": "person:2928"
          },
          {
            "series": "0",
            "index": "485",
            "xExact": "",
            "x": "486",
            "yExact": "",
            "y": "0.667910448",
            "id": "person:2930"
          },
          {
            "series": "1",
            "index": "485",
            "xExact": "",
            "x": "486",
            "yExact": "",
            "y": "1",
            "id": "person:2930"
          },
          {
            "series": "0",
            "index": "486",
            "xExact": "",
            "x": "487",
            "yExact": "",
            "y": "0.824267782",
            "id": "person:2941"
          },
          {
            "series": "1",
            "index": "486",
            "xExact": "",
            "x": "487",
            "yExact": "",
            "y": "1",
            "id": "person:2941"
          },
          {
            "series": "0",
            "index": "487",
            "xExact": "",
            "x": "488",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:2942"
          },
          {
            "series": "1",
            "index": "487",
            "xExact": "",
            "x": "488",
            "yExact": "",
            "y": "1",
            "id": "person:2942"
          },
          {
            "series": "0",
            "index": "488",
            "xExact": "",
            "x": "489",
            "yExact": "",
            "y": "0.667910448",
            "id": "person:2947"
          },
          {
            "series": "1",
            "index": "488",
            "xExact": "",
            "x": "489",
            "yExact": "",
            "y": "1",
            "id": "person:2947"
          },
          {
            "series": "0",
            "index": "489",
            "xExact": "",
            "x": "490",
            "yExact": "",
            "y": "0.667910448",
            "id": "person:2948"
          },
          {
            "series": "1",
            "index": "489",
            "xExact": "",
            "x": "490",
            "yExact": "",
            "y": "1",
            "id": "person:2948"
          },
          {
            "series": "0",
            "index": "490",
            "xExact": "",
            "x": "491",
            "yExact": "",
            "y": "0.824267782",
            "id": "person:2951"
          },
          {
            "series": "1",
            "index": "490",
            "xExact": "",
            "x": "491",
            "yExact": "",
            "y": "1",
            "id": "person:2951"
          },
          {
            "series": "0",
            "index": "491",
            "xExact": "",
            "x": "492",
            "yExact": "",
            "y": "0.487804878",
            "id": "person:2955"
          },
          {
            "series": "1",
            "index": "491",
            "xExact": "",
            "x": "492",
            "yExact": "",
            "y": "0",
            "id": "person:2955"
          },
          {
            "series": "0",
            "index": "492",
            "xExact": "",
            "x": "493",
            "yExact": "",
            "y": "0.487804878",
            "id": "person:2956"
          },
          {
            "series": "1",
            "index": "492",
            "xExact": "",
            "x": "493",
            "yExact": "",
            "y": "1",
            "id": "person:2956"
          },
          {
            "series": "0",
            "index": "493",
            "xExact": "",
            "x": "494",
            "yExact": "",
            "y": "0.362068966",
            "id": "person:2957"
          },
          {
            "series": "1",
            "index": "493",
            "xExact": "",
            "x": "494",
            "yExact": "",
            "y": "1",
            "id": "person:2957"
          },
          {
            "series": "0",
            "index": "494",
            "xExact": "",
            "x": "495",
            "yExact": "",
            "y": "0.362068966",
            "id": "person:2959"
          },
          {
            "series": "1",
            "index": "494",
            "xExact": "",
            "x": "495",
            "yExact": "",
            "y": "0",
            "id": "person:2959"
          },
          {
            "series": "0",
            "index": "495",
            "xExact": "",
            "x": "496",
            "yExact": "",
            "y": "0.362068966",
            "id": "person:2962"
          },
          {
            "series": "1",
            "index": "495",
            "xExact": "",
            "x": "496",
            "yExact": "",
            "y": "0",
            "id": "person:2962"
          },
          {
            "series": "0",
            "index": "496",
            "xExact": "",
            "x": "497",
            "yExact": "",
            "y": "0.362068966",
            "id": "person:2974"
          },
          {
            "series": "1",
            "index": "496",
            "xExact": "",
            "x": "497",
            "yExact": "",
            "y": "0",
            "id": "person:2974"
          },
          {
            "series": "0",
            "index": "497",
            "xExact": "",
            "x": "498",
            "yExact": "",
            "y": "0.757575758",
            "id": "person:2980"
          },
          {
            "series": "1",
            "index": "497",
            "xExact": "",
            "x": "498",
            "yExact": "",
            "y": "1",
            "id": "person:2980"
          },
          {
            "series": "0",
            "index": "498",
            "xExact": "",
            "x": "499",
            "yExact": "",
            "y": "0.362068966",
            "id": "person:2981"
          },
          {
            "series": "1",
            "index": "498",
            "xExact": "",
            "x": "499",
            "yExact": "",
            "y": "0",
            "id": "person:2981"
          },
          {
            "series": "0",
            "index": "499",
            "xExact": "",
            "x": "500",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:2994"
          },
          {
            "series": "1",
            "index": "499",
            "xExact": "",
            "x": "500",
            "yExact": "",
            "y": "1",
            "id": "person:2994"
          },
          {
            "series": "0",
            "index": "500",
            "xExact": "",
            "x": "501",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:2998"
          },
          {
            "series": "1",
            "index": "500",
            "xExact": "",
            "x": "501",
            "yExact": "",
            "y": "0",
            "id": "person:2998"
          },
          {
            "series": "0",
            "index": "501",
            "xExact": "",
            "x": "502",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:3009"
          },
          {
            "series": "1",
            "index": "501",
            "xExact": "",
            "x": "502",
            "yExact": "",
            "y": "0",
            "id": "person:3009"
          },
          {
            "series": "0",
            "index": "502",
            "xExact": "",
            "x": "503",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:3018"
          },
          {
            "series": "1",
            "index": "502",
            "xExact": "",
            "x": "503",
            "yExact": "",
            "y": "0",
            "id": "person:3018"
          },
          {
            "series": "0",
            "index": "503",
            "xExact": "",
            "x": "504",
            "yExact": "",
            "y": "0.667910448",
            "id": "person:3019"
          },
          {
            "series": "1",
            "index": "503",
            "xExact": "",
            "x": "504",
            "yExact": "",
            "y": "0",
            "id": "person:3019"
          },
          {
            "series": "0",
            "index": "504",
            "xExact": "",
            "x": "505",
            "yExact": "",
            "y": "0.757575758",
            "id": "person:3027"
          },
          {
            "series": "1",
            "index": "504",
            "xExact": "",
            "x": "505",
            "yExact": "",
            "y": "1",
            "id": "person:3027"
          },
          {
            "series": "0",
            "index": "505",
            "xExact": "",
            "x": "506",
            "yExact": "",
            "y": "0.362068966",
            "id": "person:3044"
          },
          {
            "series": "1",
            "index": "505",
            "xExact": "",
            "x": "506",
            "yExact": "",
            "y": "0",
            "id": "person:3044"
          },
          {
            "series": "0",
            "index": "506",
            "xExact": "",
            "x": "507",
            "yExact": "",
            "y": "0.362068966",
            "id": "person:3050"
          },
          {
            "series": "1",
            "index": "506",
            "xExact": "",
            "x": "507",
            "yExact": "",
            "y": "1",
            "id": "person:3050"
          },
          {
            "series": "0",
            "index": "507",
            "xExact": "",
            "x": "508",
            "yExact": "",
            "y": "0.362068966",
            "id": "person:3051"
          },
          {
            "series": "1",
            "index": "507",
            "xExact": "",
            "x": "508",
            "yExact": "",
            "y": "0",
            "id": "person:3051"
          },
          {
            "series": "0",
            "index": "508",
            "xExact": "",
            "x": "509",
            "yExact": "",
            "y": "0.362068966",
            "id": "person:3052"
          },
          {
            "series": "1",
            "index": "508",
            "xExact": "",
            "x": "509",
            "yExact": "",
            "y": "0",
            "id": "person:3052"
          },
          {
            "series": "0",
            "index": "509",
            "xExact": "",
            "x": "510",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:3061"
          },
          {
            "series": "1",
            "index": "509",
            "xExact": "",
            "x": "510",
            "yExact": "",
            "y": "1",
            "id": "person:3061"
          },
          {
            "series": "0",
            "index": "510",
            "xExact": "",
            "x": "511",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:3064"
          },
          {
            "series": "1",
            "index": "510",
            "xExact": "",
            "x": "511",
            "yExact": "",
            "y": "0",
            "id": "person:3064"
          },
          {
            "series": "0",
            "index": "511",
            "xExact": "",
            "x": "512",
            "yExact": "",
            "y": "0.667910448",
            "id": "person:3065"
          },
          {
            "series": "1",
            "index": "511",
            "xExact": "",
            "x": "512",
            "yExact": "",
            "y": "0",
            "id": "person:3065"
          },
          {
            "series": "0",
            "index": "512",
            "xExact": "",
            "x": "513",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:3067"
          },
          {
            "series": "1",
            "index": "512",
            "xExact": "",
            "x": "513",
            "yExact": "",
            "y": "0",
            "id": "person:3067"
          },
          {
            "series": "0",
            "index": "513",
            "xExact": "",
            "x": "514",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:3068"
          },
          {
            "series": "1",
            "index": "513",
            "xExact": "",
            "x": "514",
            "yExact": "",
            "y": "0",
            "id": "person:3068"
          },
          {
            "series": "0",
            "index": "514",
            "xExact": "",
            "x": "515",
            "yExact": "",
            "y": "0.667910448",
            "id": "person:3069"
          },
          {
            "series": "1",
            "index": "514",
            "xExact": "",
            "x": "515",
            "yExact": "",
            "y": "1",
            "id": "person:3069"
          },
          {
            "series": "0",
            "index": "515",
            "xExact": "",
            "x": "516",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:3072"
          },
          {
            "series": "1",
            "index": "515",
            "xExact": "",
            "x": "516",
            "yExact": "",
            "y": "0",
            "id": "person:3072"
          },
          {
            "series": "0",
            "index": "516",
            "xExact": "",
            "x": "517",
            "yExact": "",
            "y": "0.824267782",
            "id": "person:3077"
          },
          {
            "series": "1",
            "index": "516",
            "xExact": "",
            "x": "517",
            "yExact": "",
            "y": "0",
            "id": "person:3077"
          },
          {
            "series": "0",
            "index": "517",
            "xExact": "",
            "x": "518",
            "yExact": "",
            "y": "0.824267782",
            "id": "person:3079"
          },
          {
            "series": "1",
            "index": "517",
            "xExact": "",
            "x": "518",
            "yExact": "",
            "y": "0",
            "id": "person:3079"
          },
          {
            "series": "0",
            "index": "518",
            "xExact": "",
            "x": "519",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:3080"
          },
          {
            "series": "1",
            "index": "518",
            "xExact": "",
            "x": "519",
            "yExact": "",
            "y": "0",
            "id": "person:3080"
          },
          {
            "series": "0",
            "index": "519",
            "xExact": "",
            "x": "520",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:3083"
          },
          {
            "series": "1",
            "index": "519",
            "xExact": "",
            "x": "520",
            "yExact": "",
            "y": "0",
            "id": "person:3083"
          },
          {
            "series": "0",
            "index": "520",
            "xExact": "",
            "x": "521",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:3084"
          },
          {
            "series": "1",
            "index": "520",
            "xExact": "",
            "x": "521",
            "yExact": "",
            "y": "0",
            "id": "person:3084"
          },
          {
            "series": "0",
            "index": "521",
            "xExact": "",
            "x": "522",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:3085"
          },
          {
            "series": "1",
            "index": "521",
            "xExact": "",
            "x": "522",
            "yExact": "",
            "y": "1",
            "id": "person:3085"
          },
          {
            "series": "0",
            "index": "522",
            "xExact": "",
            "x": "523",
            "yExact": "",
            "y": "0.667910448",
            "id": "person:3087"
          },
          {
            "series": "1",
            "index": "522",
            "xExact": "",
            "x": "523",
            "yExact": "",
            "y": "1",
            "id": "person:3087"
          },
          {
            "series": "0",
            "index": "523",
            "xExact": "",
            "x": "524",
            "yExact": "",
            "y": "0.362068966",
            "id": "person:3102"
          },
          {
            "series": "1",
            "index": "523",
            "xExact": "",
            "x": "524",
            "yExact": "",
            "y": "0",
            "id": "person:3102"
          },
          {
            "series": "0",
            "index": "524",
            "xExact": "",
            "x": "525",
            "yExact": "",
            "y": "0.362068966",
            "id": "person:3103"
          },
          {
            "series": "1",
            "index": "524",
            "xExact": "",
            "x": "525",
            "yExact": "",
            "y": "0",
            "id": "person:3103"
          },
          {
            "series": "0",
            "index": "525",
            "xExact": "",
            "x": "526",
            "yExact": "",
            "y": "0.48",
            "id": "person:3106"
          },
          {
            "series": "1",
            "index": "525",
            "xExact": "",
            "x": "526",
            "yExact": "",
            "y": "0",
            "id": "person:3106"
          },
          {
            "series": "0",
            "index": "526",
            "xExact": "",
            "x": "527",
            "yExact": "",
            "y": "0.362068966",
            "id": "person:3114"
          },
          {
            "series": "1",
            "index": "526",
            "xExact": "",
            "x": "527",
            "yExact": "",
            "y": "0",
            "id": "person:3114"
          },
          {
            "series": "0",
            "index": "527",
            "xExact": "",
            "x": "528",
            "yExact": "",
            "y": "0.487804878",
            "id": "person:3120"
          },
          {
            "series": "1",
            "index": "527",
            "xExact": "",
            "x": "528",
            "yExact": "",
            "y": "1",
            "id": "person:3120"
          },
          {
            "series": "0",
            "index": "528",
            "xExact": "",
            "x": "529",
            "yExact": "",
            "y": "0.362068966",
            "id": "person:3123"
          },
          {
            "series": "1",
            "index": "528",
            "xExact": "",
            "x": "529",
            "yExact": "",
            "y": "0",
            "id": "person:3123"
          },
          {
            "series": "0",
            "index": "529",
            "xExact": "",
            "x": "530",
            "yExact": "",
            "y": "0.48",
            "id": "person:3129"
          },
          {
            "series": "1",
            "index": "529",
            "xExact": "",
            "x": "530",
            "yExact": "",
            "y": "0",
            "id": "person:3129"
          },
          {
            "series": "0",
            "index": "530",
            "xExact": "",
            "x": "531",
            "yExact": "",
            "y": "0.362068966",
            "id": "person:3131"
          },
          {
            "series": "1",
            "index": "530",
            "xExact": "",
            "x": "531",
            "yExact": "",
            "y": "1",
            "id": "person:3131"
          },
          {
            "series": "0",
            "index": "531",
            "xExact": "",
            "x": "532",
            "yExact": "",
            "y": "0.48",
            "id": "person:3133"
          },
          {
            "series": "1",
            "index": "531",
            "xExact": "",
            "x": "532",
            "yExact": "",
            "y": "0",
            "id": "person:3133"
          },
          {
            "series": "0",
            "index": "532",
            "xExact": "",
            "x": "533",
            "yExact": "",
            "y": "0.48",
            "id": "person:3140"
          },
          {
            "series": "1",
            "index": "532",
            "xExact": "",
            "x": "533",
            "yExact": "",
            "y": "0",
            "id": "person:3140"
          },
          {
            "series": "0",
            "index": "533",
            "xExact": "",
            "x": "534",
            "yExact": "",
            "y": "0.48",
            "id": "person:3146"
          },
          {
            "series": "1",
            "index": "533",
            "xExact": "",
            "x": "534",
            "yExact": "",
            "y": "0",
            "id": "person:3146"
          },
          {
            "series": "0",
            "index": "534",
            "xExact": "",
            "x": "535",
            "yExact": "",
            "y": "0.757575758",
            "id": "person:3154"
          },
          {
            "series": "1",
            "index": "534",
            "xExact": "",
            "x": "535",
            "yExact": "",
            "y": "1",
            "id": "person:3154"
          },
          {
            "series": "0",
            "index": "535",
            "xExact": "",
            "x": "536",
            "yExact": "",
            "y": "0.48",
            "id": "person:3156"
          },
          {
            "series": "1",
            "index": "535",
            "xExact": "",
            "x": "536",
            "yExact": "",
            "y": "1",
            "id": "person:3156"
          },
          {
            "series": "0",
            "index": "536",
            "xExact": "",
            "x": "537",
            "yExact": "",
            "y": "0.362068966",
            "id": "person:3163"
          },
          {
            "series": "1",
            "index": "536",
            "xExact": "",
            "x": "537",
            "yExact": "",
            "y": "0",
            "id": "person:3163"
          },
          {
            "series": "0",
            "index": "537",
            "xExact": "",
            "x": "538",
            "yExact": "",
            "y": "0.48",
            "id": "person:3164"
          },
          {
            "series": "1",
            "index": "537",
            "xExact": "",
            "x": "538",
            "yExact": "",
            "y": "1",
            "id": "person:3164"
          },
          {
            "series": "0",
            "index": "538",
            "xExact": "",
            "x": "539",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:3181"
          },
          {
            "series": "1",
            "index": "538",
            "xExact": "",
            "x": "539",
            "yExact": "",
            "y": "1",
            "id": "person:3181"
          },
          {
            "series": "0",
            "index": "539",
            "xExact": "",
            "x": "540",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:3182"
          },
          {
            "series": "1",
            "index": "539",
            "xExact": "",
            "x": "540",
            "yExact": "",
            "y": "1",
            "id": "person:3182"
          },
          {
            "series": "0",
            "index": "540",
            "xExact": "",
            "x": "541",
            "yExact": "",
            "y": "0.667910448",
            "id": "person:3183"
          },
          {
            "series": "1",
            "index": "540",
            "xExact": "",
            "x": "541",
            "yExact": "",
            "y": "1",
            "id": "person:3183"
          },
          {
            "series": "0",
            "index": "541",
            "xExact": "",
            "x": "542",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:3184"
          },
          {
            "series": "1",
            "index": "541",
            "xExact": "",
            "x": "542",
            "yExact": "",
            "y": "0",
            "id": "person:3184"
          },
          {
            "series": "0",
            "index": "542",
            "xExact": "",
            "x": "543",
            "yExact": "",
            "y": "0.362068966",
            "id": "person:3194"
          },
          {
            "series": "1",
            "index": "542",
            "xExact": "",
            "x": "543",
            "yExact": "",
            "y": "0",
            "id": "person:3194"
          },
          {
            "series": "0",
            "index": "543",
            "xExact": "",
            "x": "544",
            "yExact": "",
            "y": "0.362068966",
            "id": "person:3199"
          },
          {
            "series": "1",
            "index": "543",
            "xExact": "",
            "x": "544",
            "yExact": "",
            "y": "0",
            "id": "person:3199"
          },
          {
            "series": "0",
            "index": "544",
            "xExact": "",
            "x": "545",
            "yExact": "",
            "y": "0.362068966",
            "id": "person:3201"
          },
          {
            "series": "1",
            "index": "544",
            "xExact": "",
            "x": "545",
            "yExact": "",
            "y": "0",
            "id": "person:3201"
          },
          {
            "series": "0",
            "index": "545",
            "xExact": "",
            "x": "546",
            "yExact": "",
            "y": "0.362068966",
            "id": "person:3202"
          },
          {
            "series": "1",
            "index": "545",
            "xExact": "",
            "x": "546",
            "yExact": "",
            "y": "0",
            "id": "person:3202"
          },
          {
            "series": "0",
            "index": "546",
            "xExact": "",
            "x": "547",
            "yExact": "",
            "y": "0.362068966",
            "id": "person:3213"
          },
          {
            "series": "1",
            "index": "546",
            "xExact": "",
            "x": "547",
            "yExact": "",
            "y": "0",
            "id": "person:3213"
          },
          {
            "series": "0",
            "index": "547",
            "xExact": "",
            "x": "548",
            "yExact": "",
            "y": "0.48",
            "id": "person:3215"
          },
          {
            "series": "1",
            "index": "547",
            "xExact": "",
            "x": "548",
            "yExact": "",
            "y": "0",
            "id": "person:3215"
          },
          {
            "series": "0",
            "index": "548",
            "xExact": "",
            "x": "549",
            "yExact": "",
            "y": "0.362068966",
            "id": "person:3228"
          },
          {
            "series": "1",
            "index": "548",
            "xExact": "",
            "x": "549",
            "yExact": "",
            "y": "1",
            "id": "person:3228"
          },
          {
            "series": "0",
            "index": "549",
            "xExact": "",
            "x": "550",
            "yExact": "",
            "y": "0.48",
            "id": "person:3231"
          },
          {
            "series": "1",
            "index": "549",
            "xExact": "",
            "x": "550",
            "yExact": "",
            "y": "1",
            "id": "person:3231"
          },
          {
            "series": "0",
            "index": "550",
            "xExact": "",
            "x": "551",
            "yExact": "",
            "y": "0.362068966",
            "id": "person:3234"
          },
          {
            "series": "1",
            "index": "550",
            "xExact": "",
            "x": "551",
            "yExact": "",
            "y": "0",
            "id": "person:3234"
          },
          {
            "series": "0",
            "index": "551",
            "xExact": "",
            "x": "552",
            "yExact": "",
            "y": "0.362068966",
            "id": "person:3239"
          },
          {
            "series": "1",
            "index": "551",
            "xExact": "",
            "x": "552",
            "yExact": "",
            "y": "0",
            "id": "person:3239"
          },
          {
            "series": "0",
            "index": "552",
            "xExact": "",
            "x": "553",
            "yExact": "",
            "y": "0.362068966",
            "id": "person:3246"
          },
          {
            "series": "1",
            "index": "552",
            "xExact": "",
            "x": "553",
            "yExact": "",
            "y": "0",
            "id": "person:3246"
          },
          {
            "series": "0",
            "index": "553",
            "xExact": "",
            "x": "554",
            "yExact": "",
            "y": "0.362068966",
            "id": "person:3249"
          },
          {
            "series": "1",
            "index": "553",
            "xExact": "",
            "x": "554",
            "yExact": "",
            "y": "0",
            "id": "person:3249"
          },
          {
            "series": "0",
            "index": "554",
            "xExact": "",
            "x": "555",
            "yExact": "",
            "y": "0.48",
            "id": "person:3251"
          },
          {
            "series": "1",
            "index": "554",
            "xExact": "",
            "x": "555",
            "yExact": "",
            "y": "0",
            "id": "person:3251"
          },
          {
            "series": "0",
            "index": "555",
            "xExact": "",
            "x": "556",
            "yExact": "",
            "y": "0.362068966",
            "id": "person:3257"
          },
          {
            "series": "1",
            "index": "555",
            "xExact": "",
            "x": "556",
            "yExact": "",
            "y": "0",
            "id": "person:3257"
          },
          {
            "series": "0",
            "index": "556",
            "xExact": "",
            "x": "557",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:3259"
          },
          {
            "series": "1",
            "index": "556",
            "xExact": "",
            "x": "557",
            "yExact": "",
            "y": "0",
            "id": "person:3259"
          },
          {
            "series": "0",
            "index": "557",
            "xExact": "",
            "x": "558",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:3262"
          },
          {
            "series": "1",
            "index": "557",
            "xExact": "",
            "x": "558",
            "yExact": "",
            "y": "0",
            "id": "person:3262"
          },
          {
            "series": "0",
            "index": "558",
            "xExact": "",
            "x": "559",
            "yExact": "",
            "y": "0.667910448",
            "id": "person:3264"
          },
          {
            "series": "1",
            "index": "558",
            "xExact": "",
            "x": "559",
            "yExact": "",
            "y": "0",
            "id": "person:3264"
          },
          {
            "series": "0",
            "index": "559",
            "xExact": "",
            "x": "560",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:3265"
          },
          {
            "series": "1",
            "index": "559",
            "xExact": "",
            "x": "560",
            "yExact": "",
            "y": "0",
            "id": "person:3265"
          },
          {
            "series": "0",
            "index": "560",
            "xExact": "",
            "x": "561",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:3268"
          },
          {
            "series": "1",
            "index": "560",
            "xExact": "",
            "x": "561",
            "yExact": "",
            "y": "1",
            "id": "person:3268"
          },
          {
            "series": "0",
            "index": "561",
            "xExact": "",
            "x": "562",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:3269"
          },
          {
            "series": "1",
            "index": "561",
            "xExact": "",
            "x": "562",
            "yExact": "",
            "y": "0",
            "id": "person:3269"
          },
          {
            "series": "0",
            "index": "562",
            "xExact": "",
            "x": "563",
            "yExact": "",
            "y": "0.362068966",
            "id": "person:3298"
          },
          {
            "series": "1",
            "index": "562",
            "xExact": "",
            "x": "563",
            "yExact": "",
            "y": "0",
            "id": "person:3298"
          },
          {
            "series": "0",
            "index": "563",
            "xExact": "",
            "x": "564",
            "yExact": "",
            "y": "0.487804878",
            "id": "person:3299"
          },
          {
            "series": "1",
            "index": "563",
            "xExact": "",
            "x": "564",
            "yExact": "",
            "y": "0",
            "id": "person:3299"
          },
          {
            "series": "0",
            "index": "564",
            "xExact": "",
            "x": "565",
            "yExact": "",
            "y": "0.362068966",
            "id": "person:3300"
          },
          {
            "series": "1",
            "index": "564",
            "xExact": "",
            "x": "565",
            "yExact": "",
            "y": "0",
            "id": "person:3300"
          },
          {
            "series": "0",
            "index": "565",
            "xExact": "",
            "x": "566",
            "yExact": "",
            "y": "0.362068966",
            "id": "person:3309"
          },
          {
            "series": "1",
            "index": "565",
            "xExact": "",
            "x": "566",
            "yExact": "",
            "y": "1",
            "id": "person:3309"
          },
          {
            "series": "0",
            "index": "566",
            "xExact": "",
            "x": "567",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:3313"
          },
          {
            "series": "1",
            "index": "566",
            "xExact": "",
            "x": "567",
            "yExact": "",
            "y": "1",
            "id": "person:3313"
          },
          {
            "series": "0",
            "index": "567",
            "xExact": "",
            "x": "568",
            "yExact": "",
            "y": "0.667910448",
            "id": "person:3319"
          },
          {
            "series": "1",
            "index": "567",
            "xExact": "",
            "x": "568",
            "yExact": "",
            "y": "1",
            "id": "person:3319"
          },
          {
            "series": "0",
            "index": "568",
            "xExact": "",
            "x": "569",
            "yExact": "",
            "y": "0.667910448",
            "id": "person:3320"
          },
          {
            "series": "1",
            "index": "568",
            "xExact": "",
            "x": "569",
            "yExact": "",
            "y": "1",
            "id": "person:3320"
          },
          {
            "series": "0",
            "index": "569",
            "xExact": "",
            "x": "570",
            "yExact": "",
            "y": "0.48",
            "id": "person:3332"
          },
          {
            "series": "1",
            "index": "569",
            "xExact": "",
            "x": "570",
            "yExact": "",
            "y": "1",
            "id": "person:3332"
          },
          {
            "series": "0",
            "index": "570",
            "xExact": "",
            "x": "571",
            "yExact": "",
            "y": "0.362068966",
            "id": "person:3344"
          },
          {
            "series": "1",
            "index": "570",
            "xExact": "",
            "x": "571",
            "yExact": "",
            "y": "0",
            "id": "person:3344"
          },
          {
            "series": "0",
            "index": "571",
            "xExact": "",
            "x": "572",
            "yExact": "",
            "y": "0.48",
            "id": "person:3351"
          },
          {
            "series": "1",
            "index": "571",
            "xExact": "",
            "x": "572",
            "yExact": "",
            "y": "0",
            "id": "person:3351"
          },
          {
            "series": "0",
            "index": "572",
            "xExact": "",
            "x": "573",
            "yExact": "",
            "y": "0.362068966",
            "id": "person:3355"
          },
          {
            "series": "1",
            "index": "572",
            "xExact": "",
            "x": "573",
            "yExact": "",
            "y": "0",
            "id": "person:3355"
          },
          {
            "series": "0",
            "index": "573",
            "xExact": "",
            "x": "574",
            "yExact": "",
            "y": "0.48",
            "id": "person:3356"
          },
          {
            "series": "1",
            "index": "573",
            "xExact": "",
            "x": "574",
            "yExact": "",
            "y": "0",
            "id": "person:3356"
          },
          {
            "series": "0",
            "index": "574",
            "xExact": "",
            "x": "575",
            "yExact": "",
            "y": "0.362068966",
            "id": "person:3362"
          },
          {
            "series": "1",
            "index": "574",
            "xExact": "",
            "x": "575",
            "yExact": "",
            "y": "0",
            "id": "person:3362"
          },
          {
            "series": "0",
            "index": "575",
            "xExact": "",
            "x": "576",
            "yExact": "",
            "y": "0.48",
            "id": "person:3370"
          },
          {
            "series": "1",
            "index": "575",
            "xExact": "",
            "x": "576",
            "yExact": "",
            "y": "0",
            "id": "person:3370"
          },
          {
            "series": "0",
            "index": "576",
            "xExact": "",
            "x": "577",
            "yExact": "",
            "y": "0.362068966",
            "id": "person:3380"
          },
          {
            "series": "1",
            "index": "576",
            "xExact": "",
            "x": "577",
            "yExact": "",
            "y": "1",
            "id": "person:3380"
          },
          {
            "series": "0",
            "index": "577",
            "xExact": "",
            "x": "578",
            "yExact": "",
            "y": "0.48",
            "id": "person:3384"
          },
          {
            "series": "1",
            "index": "577",
            "xExact": "",
            "x": "578",
            "yExact": "",
            "y": "0",
            "id": "person:3384"
          },
          {
            "series": "0",
            "index": "578",
            "xExact": "",
            "x": "579",
            "yExact": "",
            "y": "0.48",
            "id": "person:3394"
          },
          {
            "series": "1",
            "index": "578",
            "xExact": "",
            "x": "579",
            "yExact": "",
            "y": "0",
            "id": "person:3394"
          },
          {
            "series": "0",
            "index": "579",
            "xExact": "",
            "x": "580",
            "yExact": "",
            "y": "0.48",
            "id": "person:3399"
          },
          {
            "series": "1",
            "index": "579",
            "xExact": "",
            "x": "580",
            "yExact": "",
            "y": "0",
            "id": "person:3399"
          },
          {
            "series": "0",
            "index": "580",
            "xExact": "",
            "x": "581",
            "yExact": "",
            "y": "0.362068966",
            "id": "person:3402"
          },
          {
            "series": "1",
            "index": "580",
            "xExact": "",
            "x": "581",
            "yExact": "",
            "y": "1",
            "id": "person:3402"
          },
          {
            "series": "0",
            "index": "581",
            "xExact": "",
            "x": "582",
            "yExact": "",
            "y": "0.362068966",
            "id": "person:3404"
          },
          {
            "series": "1",
            "index": "581",
            "xExact": "",
            "x": "582",
            "yExact": "",
            "y": "1",
            "id": "person:3404"
          },
          {
            "series": "0",
            "index": "582",
            "xExact": "",
            "x": "583",
            "yExact": "",
            "y": "0.48",
            "id": "person:3412"
          },
          {
            "series": "1",
            "index": "582",
            "xExact": "",
            "x": "583",
            "yExact": "",
            "y": "0",
            "id": "person:3412"
          },
          {
            "series": "0",
            "index": "583",
            "xExact": "",
            "x": "584",
            "yExact": "",
            "y": "0.362068966",
            "id": "person:3436"
          },
          {
            "series": "1",
            "index": "583",
            "xExact": "",
            "x": "584",
            "yExact": "",
            "y": "0",
            "id": "person:3436"
          },
          {
            "series": "0",
            "index": "584",
            "xExact": "",
            "x": "585",
            "yExact": "",
            "y": "0.48",
            "id": "person:3456"
          },
          {
            "series": "1",
            "index": "584",
            "xExact": "",
            "x": "585",
            "yExact": "",
            "y": "0",
            "id": "person:3456"
          },
          {
            "series": "0",
            "index": "585",
            "xExact": "",
            "x": "586",
            "yExact": "",
            "y": "0.362068966",
            "id": "person:3463"
          },
          {
            "series": "1",
            "index": "585",
            "xExact": "",
            "x": "586",
            "yExact": "",
            "y": "0",
            "id": "person:3463"
          },
          {
            "series": "0",
            "index": "586",
            "xExact": "",
            "x": "587",
            "yExact": "",
            "y": "0.362068966",
            "id": "person:3473"
          },
          {
            "series": "1",
            "index": "586",
            "xExact": "",
            "x": "587",
            "yExact": "",
            "y": "0",
            "id": "person:3473"
          },
          {
            "series": "0",
            "index": "587",
            "xExact": "",
            "x": "588",
            "yExact": "",
            "y": "0.48",
            "id": "person:3486"
          },
          {
            "series": "1",
            "index": "587",
            "xExact": "",
            "x": "588",
            "yExact": "",
            "y": "0",
            "id": "person:3486"
          },
          {
            "series": "0",
            "index": "588",
            "xExact": "",
            "x": "589",
            "yExact": "",
            "y": "0.48",
            "id": "person:3487"
          },
          {
            "series": "1",
            "index": "588",
            "xExact": "",
            "x": "589",
            "yExact": "",
            "y": "0",
            "id": "person:3487"
          },
          {
            "series": "0",
            "index": "589",
            "xExact": "",
            "x": "590",
            "yExact": "",
            "y": "0.487804878",
            "id": "person:3490"
          },
          {
            "series": "1",
            "index": "589",
            "xExact": "",
            "x": "590",
            "yExact": "",
            "y": "1",
            "id": "person:3490"
          },
          {
            "series": "0",
            "index": "590",
            "xExact": "",
            "x": "591",
            "yExact": "",
            "y": "0.362068966",
            "id": "person:3493"
          },
          {
            "series": "1",
            "index": "590",
            "xExact": "",
            "x": "591",
            "yExact": "",
            "y": "0",
            "id": "person:3493"
          },
          {
            "series": "0",
            "index": "591",
            "xExact": "",
            "x": "592",
            "yExact": "",
            "y": "0.487804878",
            "id": "person:3509"
          },
          {
            "series": "1",
            "index": "591",
            "xExact": "",
            "x": "592",
            "yExact": "",
            "y": "0",
            "id": "person:3509"
          },
          {
            "series": "0",
            "index": "592",
            "xExact": "",
            "x": "593",
            "yExact": "",
            "y": "0.48",
            "id": "person:3525"
          },
          {
            "series": "1",
            "index": "592",
            "xExact": "",
            "x": "593",
            "yExact": "",
            "y": "1",
            "id": "person:3525"
          },
          {
            "series": "0",
            "index": "593",
            "xExact": "",
            "x": "594",
            "yExact": "",
            "y": "0.48",
            "id": "person:3536"
          },
          {
            "series": "1",
            "index": "593",
            "xExact": "",
            "x": "594",
            "yExact": "",
            "y": "1",
            "id": "person:3536"
          },
          {
            "series": "0",
            "index": "594",
            "xExact": "",
            "x": "595",
            "yExact": "",
            "y": "0.362068966",
            "id": "person:3555"
          },
          {
            "series": "1",
            "index": "594",
            "xExact": "",
            "x": "595",
            "yExact": "",
            "y": "0",
            "id": "person:3555"
          },
          {
            "series": "0",
            "index": "595",
            "xExact": "",
            "x": "596",
            "yExact": "",
            "y": "0.487804878",
            "id": "person:3558"
          },
          {
            "series": "1",
            "index": "595",
            "xExact": "",
            "x": "596",
            "yExact": "",
            "y": "1",
            "id": "person:3558"
          },
          {
            "series": "0",
            "index": "596",
            "xExact": "",
            "x": "597",
            "yExact": "",
            "y": "0.362068966",
            "id": "person:3566"
          },
          {
            "series": "1",
            "index": "596",
            "xExact": "",
            "x": "597",
            "yExact": "",
            "y": "0",
            "id": "person:3566"
          },
          {
            "series": "0",
            "index": "597",
            "xExact": "",
            "x": "598",
            "yExact": "",
            "y": "0.362068966",
            "id": "person:3569"
          },
          {
            "series": "1",
            "index": "597",
            "xExact": "",
            "x": "598",
            "yExact": "",
            "y": "0",
            "id": "person:3569"
          },
          {
            "series": "0",
            "index": "598",
            "xExact": "",
            "x": "599",
            "yExact": "",
            "y": "0.757575758",
            "id": "person:3575"
          },
          {
            "series": "1",
            "index": "598",
            "xExact": "",
            "x": "599",
            "yExact": "",
            "y": "1",
            "id": "person:3575"
          },
          {
            "series": "0",
            "index": "599",
            "xExact": "",
            "x": "600",
            "yExact": "",
            "y": "0.48",
            "id": "person:3576"
          },
          {
            "series": "1",
            "index": "599",
            "xExact": "",
            "x": "600",
            "yExact": "",
            "y": "0",
            "id": "person:3576"
          },
          {
            "series": "0",
            "index": "600",
            "xExact": "",
            "x": "601",
            "yExact": "",
            "y": "0.362068966",
            "id": "person:3577"
          },
          {
            "series": "1",
            "index": "600",
            "xExact": "",
            "x": "601",
            "yExact": "",
            "y": "0",
            "id": "person:3577"
          },
          {
            "series": "0",
            "index": "601",
            "xExact": "",
            "x": "602",
            "yExact": "",
            "y": "0.362068966",
            "id": "person:3580"
          },
          {
            "series": "1",
            "index": "601",
            "xExact": "",
            "x": "602",
            "yExact": "",
            "y": "0",
            "id": "person:3580"
          },
          {
            "series": "0",
            "index": "602",
            "xExact": "",
            "x": "603",
            "yExact": "",
            "y": "0.487804878",
            "id": "person:3583"
          },
          {
            "series": "1",
            "index": "602",
            "xExact": "",
            "x": "603",
            "yExact": "",
            "y": "1",
            "id": "person:3583"
          },
          {
            "series": "0",
            "index": "603",
            "xExact": "",
            "x": "604",
            "yExact": "",
            "y": "0.48",
            "id": "person:3584"
          },
          {
            "series": "1",
            "index": "603",
            "xExact": "",
            "x": "604",
            "yExact": "",
            "y": "0",
            "id": "person:3584"
          },
          {
            "series": "0",
            "index": "604",
            "xExact": "",
            "x": "605",
            "yExact": "",
            "y": "0.616564417",
            "id": "person:3600"
          },
          {
            "series": "1",
            "index": "604",
            "xExact": "",
            "x": "605",
            "yExact": "",
            "y": "0",
            "id": "person:3600"
          },
          {
            "series": "0",
            "index": "605",
            "xExact": "",
            "x": "606",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:3602"
          },
          {
            "series": "1",
            "index": "605",
            "xExact": "",
            "x": "606",
            "yExact": "",
            "y": "1",
            "id": "person:3602"
          },
          {
            "series": "0",
            "index": "606",
            "xExact": "",
            "x": "607",
            "yExact": "",
            "y": "0.527363184",
            "id": "person:3608"
          },
          {
            "series": "1",
            "index": "606",
            "xExact": "",
            "x": "607",
            "yExact": "",
            "y": "0",
            "id": "person:3608"
          }
        ],
        "plotFile": "ml14-fixed-results/realdata-person-r/plot.svg",
        "plotSHA256": "03045106eaffc3733d567edec58decb4da61276575b75e486c639967af61c35f",
        "files": [
          {
            "file": "ml14-fixed-results/realdata-person-r/full.txt",
            "sha256": "f77f8069ec82323defad55d1b8019dc65be9f11107a143640d39b33c77221855",
            "bytes": 598384
          },
          {
            "file": "ml14-fixed-results/realdata-person-r/plot-points.csv",
            "sha256": "19b111f944f2dba8932b97d51118021ff8e70d5af85dbe405efe93d7691b5421",
            "bytes": 49879
          },
          {
            "file": "ml14-fixed-results/realdata-person-r/plot.svg",
            "sha256": "03045106eaffc3733d567edec58decb4da61276575b75e486c639967af61c35f",
            "bytes": 71645
          },
          {
            "file": "ml14-fixed-results/realdata-person-r/summary.csv",
            "sha256": "59a57e52c3ddf8ce6bbd37b1fe2ec54b75f018f68f7c5894b446c0b748fdabf6",
            "bytes": 600
          }
        ],
        "scope": "Actually executed standalone fixed example, Python exact Fraction versus base-R binary64. Approximate R residuals retained; not universal exact arithmetic/web validation/native UI. Source programs read factual3CSV only."
      },
      "company": {
        "api": "realdata",
        "variant": "company",
        "language": "r",
        "title": "Actual company fixed train/validation/test procedure",
        "codeFile": "ml14-code/realdata-company.R",
        "codeSHA256": "a3529cf3430104c6cbd4cd6fa0a7bb4d4e32661b1def1919b43592d17c1b3f33",
        "code": "# ML14 standalone public counterpart, base R only.\n# Inputs are only the three factual CSVs; derived columns/previous model answers unused.\n# Binary64 arithmetic, not arbitrary-precision Fraction. At numerical cost ties\n# within 1e-12 retain the earliest candidate. Exact claims belong to Python/web.\n# SHA256 infrastructure below is reused verbatim from the previous public study.\nargs<-commandArgs(trailingOnly=TRUE);filearg<-grep(\"^--file=\",commandArgs(),value=TRUE)\nhere<-if(dir.exists(\"ml14-sources\"))getwd()else if(length(filearg))dirname(normalizePath(sub(\"^--file=\",\"\",filearg[1])))else getwd()\noption<-function(key,default){i<-match(key,args);if(is.na(i))default else args[i+1]}\nsourceDir<-option(\"--source\",file.path(here,\"ml14-sources\"));outDir<-option(\"--out\",file.path(getwd(),\"ml14-r-results\"));dir.create(outDir,recursive=TRUE,showWarnings=FALSE)\nnum<-function(x){x[x%in%c(\"\",\".\")]<-NA_character_;as.numeric(x)}\nfmt<-function(x)ifelse(is.na(x),\"\",sprintf(\"%.17g\",x))\nratio<-function(a,b)if(b==0)NA_real_ else a/b\nreadnative<-function(name)read.csv(file.path(sourceDir,name),check.names=FALSE,colClasses=\"character\",na.strings=character(),stringsAsFactors=FALSE)\n# Vectorized SHA256 for the short ASCII keys used in this study.\n# Unsigned words use exact integer-valued doubles; bit operations use safe\n# 16-bit halves, avoiding R's reserved signed-INT_MIN/NA representation.\nMOD<-2^32\nxor32<-function(a,b) as.double(bitwXor(as.integer(floor(a/65536)),as.integer(floor(b/65536))))*65536+as.double(bitwXor(as.integer(a%%65536),as.integer(b%%65536)))\nand32<-function(a,b) as.double(bitwAnd(as.integer(floor(a/65536)),as.integer(floor(b/65536))))*65536+as.double(bitwAnd(as.integer(a%%65536),as.integer(b%%65536)))\nrot<-function(x,n) floor(x/2^n)+(x%%2^n)*2^(32-n)\nxor3<-function(a,b,c) xor32(xor32(a,b),c)\nK<-c(0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5,0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967,0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070,0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3,0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2)\nsha256<-function(strings) {\n n<-length(strings);bytes<-matrix(0,n,64)\n for(i in seq_len(n)) {v<-utf8ToInt(strings[i]);stopifnot(length(v)<56,all(v<128));if(length(v)) bytes[i,seq_along(v)]<-v;bytes[i,length(v)+1]<-128;bits<-length(v)*8;bytes[i,61:64]<-c(floor(bits/2^24)%%256,floor(bits/2^16)%%256,floor(bits/256)%%256,bits%%256)}\n w<-matrix(0,n,64)\n for(j in 1:16) {b<-4*(j-1)+1;w[,j]<-bytes[,b]*2^24+bytes[,b+1]*2^16+bytes[,b+2]*256+bytes[,b+3]}\n for(j in 17:64) {s0<-xor3(rot(w[,j-15],7),rot(w[,j-15],18),floor(w[,j-15]/8));s1<-xor3(rot(w[,j-2],17),rot(w[,j-2],19),floor(w[,j-2]/1024));w[,j]<-(w[,j-16]+s0+w[,j-7]+s1)%%MOD}\n init<-c(0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19)\n state<-lapply(init,function(v) rep(v,n));a<-state[[1]];b<-state[[2]];c<-state[[3]];d<-state[[4]];e<-state[[5]];f<-state[[6]];g<-state[[7]];h<-state[[8]]\n for(j in 1:64) {S1<-xor3(rot(e,6),rot(e,11),rot(e,25));ch<-xor32(and32(e,f),and32(MOD-1-e,g));t1<-(h+S1+ch+K[j]+w[,j])%%MOD;S0<-xor3(rot(a,2),rot(a,13),rot(a,22));maj<-xor3(and32(a,b),and32(a,c),and32(b,c));t2<-(S0+maj)%%MOD;h<-g;g<-f;f<-e;e<-(d+t1)%%MOD;d<-c;c<-b;b<-a;a<-(t1+t2)%%MOD}\n end<-list(a,b,c,d,e,f,g,h);hex<-lapply(1:8,function(j){v<-(end[[j]]+init[j])%%MOD;paste0(sprintf(\"%04x\",as.integer(floor(v/65536))),sprintf(\"%04x\",as.integer(v%%65536)))})\n do.call(paste0,hex)\n}\nstopifnot(identical(sha256(c(\"abc\",\"\")),c(\"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad\",\"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855\")))\n\nloadData<-function(){\n wb<-readnative(\"actual64-country-four-indicators-original-2024.csv\");codes<-c(\"NY.GDP.PCAP.KD\",\"NY.GDP.MKTP.KD.ZG\",\"FP.CPI.TOTL.ZG\",\"SP.DYN.LE00.IN\");iso<-sort(unique(wb$countryISO3));stopifnot(nrow(wb)==64,length(iso)==16)\n tokens<-t(vapply(iso,function(s)wb$originalValueToken[match(paste(s,codes),paste(wb$countryISO3,wb$indicatorID))],character(4)));vals<-matrix(num(as.vector(tokens)),nrow=nrow(tokens))\n country<-list(id=paste0(iso,\":2024\"),sourceRow=1:16,originalID=iso,x=vals[,1:3,drop=FALSE],rawX=tokens[,1:3,drop=FALSE],nativeTarget=tokens[,4],y=as.integer(vals[,4]>=80),group=ifelse(is.na(vals[,1]),NA_character_,as.character(as.integer(vals[,1]>=25000))),lineage=vapply(iso,function(s)paste(wb$sourceRow[match(paste(s,codes),paste(wb$countryISO3,wb$indicatorID))],collapse=\";\"),character(1)),cat=integer(),units=c(\"constant2015USD/person\",\"annualPercent\",\"annualPercent\"))\n nls<-readnative(\"actual3613-NLS-original52-fields-groups-roles.csv\");raw<-cbind(nls$ed76,nls$age76,nls$nearc4)\n person<-list(id=paste0(\"person:\",nls$sourceRow),sourceRow=as.integer(nls$sourceRow),originalID=nls$id,x=matrix(num(as.vector(raw)),nrow=nrow(raw)),rawX=raw,nativeTarget=nls$wage76,y=as.integer(num(nls$wage76)>=500),group=ifelse(nls$black%in%c(\"\",\".\"),NA_character_,nls$black),lineage=nls$sourceRow,cat=2L,units=c(\"years\",\"years\",\"nativeCategory\"))\n ch<-readnative(\"actual3150-churn-original14-fields-groups-roles.csv\");raw<-cbind(ch[[\"Call  Failure\"]],ch$Complains,ch[[\"Subscription  Length\"]],ch[[\"Seconds of Use\"]])\n company<-list(id=paste0(\"customer:\",ch$sourceRow),sourceRow=as.integer(ch$sourceRow),originalID=rep(\"\",nrow(ch)),x=matrix(num(as.vector(raw)),nrow=nrow(raw)),rawX=raw,nativeTarget=ch$Churn,y=as.integer(ch$Churn),group=ifelse(ch[[\"Tariff Plan\"]]%in%c(\"\",\".\"),NA_character_,ch[[\"Tariff Plan\"]]),lineage=ch$sourceRow,cat=1L,units=c(\"count\",\"nativeCategory\",\"months\",\"seconds\"))\n stopifnot(nrow(nls)==3613,nrow(ch)==3150,identical(as.integer(ch$sourceRow[ch[[\"Charge  Amount\"]]==\"10\"]),c(474L,2174L,2274L,2374L,2674L,2924L,2974L)))\n result<-list(country=country,person=person,company=company)\n for(k in names(result)){d<-result[[k]];n<-length(d$id);d$eligible<-!is.na(d$y)&rowSums(is.na(d$x))==0;hash<-sha256(paste0(\"ML14-role|\",k,\"|\",d$id));rank<-integer(n);rank[order(hash,seq_len(n))]<-seq_len(n)-1L;d$plannedRole<-ifelse(rank%%5==0,\"test\",ifelse(rank%%5==1,\"validation\",\"train\"));d$role<-ifelse(d$eligible,d$plannedRole,\"excluded\");result[[k]]<-d}\n stopifnot(sum(result$person$eligible)==3017);result\n}\nfitmodel<-function(d){\n ids<-which(d$role==\"train\");p<-ncol(d$x);m<-vapply(seq_len(p),function(j)if((j-1)%in%d$cat)NA_real_ else median(d$x[ids,j]),numeric(1));z<-d$x\n for(j in seq_len(p))if(!((j-1)%in%d$cat))z[,j]<-as.numeric(z[,j]>m[j])\n keys<-apply(z,1,function(v)paste(fmt(v),collapse=\"|\"));lev<-unique(keys[ids]);mass<-vapply(lev,function(k)sum(keys[ids]==k),integer(1));positive<-vapply(lev,function(k)sum(d$y[ids][keys[ids]==k]),integer(1));prob<-(positive+1)/(mass+2);fallback<-(sum(d$y[ids])+1)/(length(ids)+2);pred<-prob[match(keys,lev)];unseen<-is.na(pred);pred[unseen]<-fallback;pred[!d$eligible]<-NA_real_;unseen[!d$eligible]<-NA\n list(ids=ids,medians=m,z=z,keys=keys,lev=lev,mass=mass,positive=positive,prob=prob,fallback=fallback,pred=pred,unseen=unseen)\n}\nmeasure<-function(d,p,ids,t=.5,cost=c(1,1)){\n use<-ids[d$eligible[ids]&!is.na(p[ids])];y<-d$y[use];a<-if(is.character(t))rep(t==\"always-positive\",length(use))else p[use]>=t\n TP<-sum(a&y==1);FP<-sum(a&y==0);FN<-sum(!a&y==1);TN<-sum(!a&y==0);P<-TP+FN;N<-FP+TN;W<-P+N;PP<-TP+FP;PN<-TN+FN;TPR<-ratio(TP,P);TNR<-ratio(TN,N);bs<-sum((p[use]-y)^2);tc<-FP*cost[1]+FN*cost[2]\n list(TP=TP,FP=FP,FN=FN,TN=TN,mass=W,positiveTargetMass=P,negativeTargetMass=N,predictedPositiveMass=PP,predictedNegativeMass=PN,prevalence=ratio(P,W),selectionRate=ratio(PP,W),accuracy=ratio(TP+TN,W),precision=ratio(TP,PP),negativePredictiveValue=ratio(TN,PN),TPR=TPR,FPR=ratio(FP,N),TNR=TNR,FNR=ratio(FN,P),F1=ratio(2*TP,2*TP+FP+FN),balancedAccuracy=if(is.na(TPR)||is.na(TNR))NA_real_ else(TPR+TNR)/2,Brier=ratio(bs,W),BrierSum=bs,totalCost=tc,meanCost=ratio(tc,W))\n}\ncurves<-function(d,p,ids){\n use<-ids[d$eligible[ids]&!is.na(p[ids])];scores<-sort(unique(p[use]),decreasing=TRUE);policies<-c(list(\"always-negative\"),as.list(scores));points<-lapply(policies,function(t){m<-measure(d,p,ids,t);c(list(policy=t),m[c(\"TP\",\"FP\",\"FN\",\"TN\",\"TPR\",\"FPR\",\"precision\")],list(recall=m$TPR))})\n pos<-use[d$y[use]==1];neg<-use[d$y[use]==0];U<-0;for(i in pos)U<-U+sum(p[i]>p[neg])+.5*sum(p[i]==p[neg])\n AP<-0;trap<-0;lastR<-0;lastP<-1\n if(length(pos)&&length(scores))for(j in seq_along(scores)){z<-points[[j+1]];AP<-AP+(z$recall-lastR)*z$precision;trap<-trap+(z$recall-lastR)*(z$precision+lastP)/2;lastR<-z$recall;lastP<-z$precision}\n list(points=points,ROC_AUC=ratio(U,length(pos)*length(neg)),averagePrecision=if(length(pos))AP else NA_real_,PRTrapezoidWithInitialPrecisionOne=if(length(pos))trap else NA_real_)\n}\ncalibrate<-function(d,p,ids){\n use<-ids[d$eligible[ids]&!is.na(p[ids])];W<-length(use);pi<-if(W)mean(d$y[use])else NA_real_;bins<-list();ECE<-rel<-res<-correction<-0\n whichbin<-findInterval(p[use],seq(0,1,.2),rightmost.closed=TRUE,all.inside=TRUE)\n for(b in 1:5){rr<-use[whichbin==b];w<-length(rr);mp<-if(w)mean(p[rr])else NA_real_;o<-if(w)mean(d$y[rr])else NA_real_;variance<-if(w)mean((p[rr]-mp)^2)else NA_real_;covariance<-if(w)mean((p[rr]-mp)*(d$y[rr]-o))else NA_real_;bc<-variance-2*covariance;gap<-mp-o\n  bins[[b]]<-list(mass=w,meanPrediction=mp,eventRate=o,gap=gap,absoluteGap=abs(gap),scoreVariance=variance,scoreTargetCovariance=covariance,withinBinCorrection=bc,rows=w,ids=d$id[rr])\n  if(w){share<-w/W;ECE<-ECE+share*abs(gap);rel<-rel+share*gap^2;res<-res+share*(o-pi)^2;correction<-correction+share*bc}\n };bs<-if(W)mean((p[use]-d$y[use])^2)else NA_real_;unc<-pi*(1-pi)\n list(bins=bins,ECE=if(W)ECE else NA_real_,Brier=bs,reliability=if(W)rel else NA_real_,resolution=if(W)res else NA_real_,uncertainty=unc,withinBinCorrection=if(W)correction else NA_real_,BrierIdentityResidual=bs-(unc-res+rel+correction))\n}\ncounts<-c(\"mass\",\"positiveTargetMass\",\"negativeTargetMass\",\"predictedPositiveMass\",\"predictedNegativeMass\");rates<-c(\"prevalence\",\"selectionRate\",\"accuracy\",\"precision\",\"negativePredictiveValue\",\"TPR\",\"FPR\",\"TNR\",\"FNR\",\"F1\",\"balancedAccuracy\",\"Brier\",\"BrierSum\",\"totalCost\",\"meanCost\")\ntables<-setNames(lapply(1:10,function(i)list()),c(\"predictions\",\"lineage\",\"fit-medians\",\"fit-cells\",\"validation-candidates\",\"test-metrics\",\"test-curves\",\"calibration-bins\",\"group-metrics\",\"chart-points\"))\nadd<-function(name,row)tables[[name]][[length(tables[[name]])+1L]]<<-row\nscalars<-function(m,keys){out<-list();for(k in keys){out[[paste0(k,\"Exact\")]]<-\"\";out[[paste0(k,\"Approx\")]]<-fmt(m[[k]])};out}\ntagrow<-function(kind,...)c(list(kind=kind),list(...))\npoint<-function(kind,chart,series,index,x,y,xunit=\"dimensionless\",yunit=\"dimensionless\",role=\"test\",tag=\"\"){add(\"chart-points\",tagrow(kind,chart=chart,series=series,index=index,xExact=\"\",xApprox=fmt(x),yExact=\"\",yApprox=fmt(y),xUnit=xunit,yUnit=yunit,role=role,tag=tag))}\nstudy<-function(kind,d){\n f<-fitmodel(d);n<-length(d$id);train<-which(d$role==\"train\");validation<-which(d$role==\"validation\");test<-which(d$role==\"test\");p<-f$pred;cv<-curves(d,p,test);cal<-calibrate(d,p,test)\n for(i in seq_len(n)){\n  reason<-if(d$eligible[i])\"\"else\"required-X-or-Y-missing\";transformed<-if(d$eligible[i])paste(fmt(f$z[i,]),collapse=\"|\")else\"\"\n  add(\"predictions\",tagrow(kind,id=d$id[i],sourceRow=d$sourceRow[i],originalID=d$originalID[i],plannedRole=d$plannedRole[i],role=d$role[i],group=ifelse(is.na(d$group[i]),\"\",d$group[i]),eligible=as.integer(d$eligible[i]),targetExact=fmt(d$y[i]),probabilityExact=\"\",probabilityApprox=fmt(p[i]),unseenCell=ifelse(is.na(f$unseen[i]),\"\",as.character(as.integer(f$unseen[i]))),transformedX=transformed,reason=reason))\n  raw<-d$rawX[i,];raw[raw%in%c(\"\",\".\")]<-\"\";nativeY<-d$nativeTarget[i];if(nativeY%in%c(\"\",\".\"))nativeY<-\"\"\n  add(\"lineage\",tagrow(kind,id=d$id[i],sourceRow=d$sourceRow[i],originalID=d$originalID[i],nativeSourceRows=d$lineage[i],rawX=paste(raw,collapse=\"|\"),nativeTarget=nativeY,derivedTarget=fmt(d$y[i]),nativeGroup=ifelse(is.na(d$group[i]),\"\",d$group[i]),plannedRole=d$plannedRole[i],role=d$role[i],eligible=as.integer(d$eligible[i]),analyticalMass=\"1\",reason=reason))\n }\n for(j in seq_len(ncol(d$x)))add(\"fit-medians\",tagrow(kind,feature=j-1,categorical=as.integer((j-1)%in%d$cat),fitRows=length(train),medianExact=\"\",medianApprox=fmt(f$medians[j]),unit=d$units[j]))\n for(j in seq_along(f$lev))add(\"fit-cells\",tagrow(kind,cell=f$lev[j],trainingRows=f$mass[j],positiveRows=f$positive[j],probabilityExact=\"\",probabilityApprox=fmt(f$prob[j]),fallbackExact=\"\",fallbackApprox=fmt(f$fallback)))\n for(j in seq_along(cv$points)){\n  z<-cv$points[[j]];t<-z$policy;add(\"test-curves\",c(tagrow(kind,point=j-1,policy=if(is.character(t))t else\"threshold\",thresholdExact=\"\",thresholdApprox=if(is.character(t))\"\"else fmt(t)),scalars(z,c(\"TP\",\"FP\",\"FN\",\"TN\",\"TPR\",\"FPR\",\"precision\",\"recall\"))))\n  point(kind,\"roc\",\"ROC\",j-1,z$FPR,z$TPR);point(kind,\"pr\",\"PR-observed\",j-1,z$recall,z$precision)\n }\n for(b in 1:5){z<-cal$bins[[b]];add(\"calibration-bins\",c(tagrow(kind,bin=b-1,leftExact=c(\"0\",\"1/5\",\"2/5\",\"3/5\",\"4/5\")[b],rightExact=c(\"1/5\",\"2/5\",\"3/5\",\"4/5\",\"1\")[b],rightClosed=as.integer(b==5),rows=z$rows,ids=paste(z$ids,collapse=\";\")),scalars(z,c(\"mass\",\"meanPrediction\",\"eventRate\",\"gap\",\"absoluteGap\",\"scoreVariance\",\"scoreTargetCovariance\",\"withinBinCorrection\"))));point(kind,\"reliability\",\"Binary event rate\",b-1,z$meanPrediction,z$eventRate,tag=paste0(\"rows=\",z$rows))}\n for(j in seq_along(test)){i<-test[j];point(kind,\"test-scores\",\"Training-fitted probability\",j-1,j,p[i],\"test-row position\",\"probability\",tag=d$id[i]);point(kind,\"test-scores\",\"Observed Y\",j-1,j,d$y[i],\"test-row position\",\"binary target\",tag=d$id[i])}\n scenarioNames<-c(\"equal\",\"miss-five\",\"alarm-five\");costs<-list(c(1,1),c(1,5),c(5,1))\n for(s in 1:3){name<-scenarioNames[s];cost<-costs[[s]];grid<-c(list(\"always-negative\"),as.list(sort(unique(p[validation]),decreasing=TRUE)));candidates<-lapply(grid,function(t)measure(d,p,validation,t,cost));values<-vapply(candidates,function(m)m$meanCost,numeric(1));best<-which(values<=min(values)+1e-12)[1];chosen<-grid[[best]];ev<-measure(d,p,test,chosen,cost)\n  for(j in seq_along(grid)){t<-grid[[j]];m<-candidates[[j]];cell<-setNames(lapply(c(\"TP\",\"FP\",\"FN\",\"TN\"),function(k)fmt(m[[k]])),paste0(c(\"TP\",\"FP\",\"FN\",\"TN\"),\"Exact\"));add(\"validation-candidates\",c(tagrow(kind,scenario=name,candidate=j-1,selected=as.integer(j==best),policy=if(is.character(t))t else\"threshold\",thresholdExact=\"\",thresholdApprox=if(is.character(t))\"\"else fmt(t),feasible=1,reasons=\"\"),cell,scalars(m,c(counts,\"TPR\",\"FPR\",\"precision\",\"meanCost\",\"totalCost\"))));point(kind,\"validation-cost\",name,j-1,j-1,m$meanCost,\"candidate index\",\"hypothetical cost units/mass\",\"validation\",if(is.character(t))t else fmt(t))}\n  m<-c(ev,cv[c(\"ROC_AUC\",\"averagePrecision\",\"PRTrapezoidWithInitialPrecisionOne\")],cal[c(\"ECE\",\"reliability\",\"resolution\",\"uncertainty\",\"withinBinCorrection\",\"BrierIdentityResidual\")])\n  for(k in c(\"TP\",\"FP\",\"FN\",\"TN\",counts,rates,\"ROC_AUC\",\"averagePrecision\",\"PRTrapezoidWithInitialPrecisionOne\",\"ECE\",\"reliability\",\"resolution\",\"uncertainty\",\"withinBinCorrection\",\"BrierIdentityResidual\")){\n   unit<-if(k%in%c(\"TP\",\"FP\",\"FN\",\"TN\",counts))\"rows\"else if(k==\"totalCost\")\"hypothetical cost units\"else if(k==\"meanCost\")\"hypothetical cost units/mass\"else if(k==\"BrierSum\")\"sum squared-probability loss\"else\"dimensionless\"\n   add(\"test-metrics\",tagrow(kind,scenario=name,metric=k,valueExact=\"\",valueApprox=fmt(m[[k]]),unit=unit))\n  }\n  lev<-unique(d$group[test][!is.na(d$group[test])]);sets<-c(list(test),lapply(lev,function(g)test[!is.na(d$group[test])&d$group[test]==g]),list(test[is.na(d$group[test])]))\n  types<-c(\"overall\",rep(\"known\",length(lev)),\"unknown\");tokens<-c(\"all\",lev,\"\")\n  for(j in seq_along(sets)){ids<-sets[[j]];m<-measure(d,p,ids,chosen,cost);cell<-setNames(lapply(c(\"TP\",\"FP\",\"FN\",\"TN\"),function(k)fmt(m[[k]])),paste0(c(\"TP\",\"FP\",\"FN\",\"TN\"),\"Exact\"));add(\"group-metrics\",c(tagrow(kind,scenario=name,groupType=types[j],groupToken=tokens[j],retainedRows=length(ids)),cell,scalars(m,c(counts,rates))));if(types[j]==\"known\")point(kind,\"group-TPR\",name,j-2,j-2,m$TPR,\"declared group position\",\"TPR\",tag=tokens[j])}\n }\n invisible(NULL)\n}\n\n# Fixed finite inputs only; not the complete web input/budget validator.\nqnum<-function(v){if(is.null(v))return(NA_real_);if(is.logical(v))return(as.numeric(v));s<-as.character(v);if(grepl(\"/\",s,fixed=TRUE)){a<-strsplit(s,\"/\",fixed=TRUE)[[1]];return(as.numeric(a[1])/as.numeric(a[2]))};as.numeric(s)}\nrowsG<-function(raw){\n n<-length(raw);get<-function(r,k,default=NULL)if(is.null(r[[k]]))default else r[[k]]\n id<-vapply(raw,function(r)as.character(r$id),character(1));p<-vapply(raw,function(r)qnum(r$score),numeric(1));y<-vapply(raw,function(r)qnum(r$y),numeric(1));w<-vapply(raw,function(r)qnum(get(r,\"weight\",\"1\")),numeric(1));role<-vapply(raw,function(r)get(r,\"role\",\"evaluation\"),character(1));group<-vapply(raw,function(r)as.character(get(r,\"group\",NA_character_)),character(1))\n stopifnot(all(w>=0),all(is.na(p)|(p>=0&p<=1)),all(is.na(y)|y%in%c(0,1)),!anyDuplicated(id));list(id=id,p=p,y=y,w=w,role=role,group=group,eligible=!is.na(p)&!is.na(y)&w>0&role!=\"excluded\")\n}\nscopeG<-function(d,role=\"all\")if(role==\"all\")seq_along(d$id)else which(d$role==role)\nmetricsG<-function(d,ids,t=.5,cost=c(1,1)){\n use<-ids[d$eligible[ids]];p<-d$p[use];y<-d$y[use];w<-d$w[use];a<-if(is.character(t))rep(t==\"always-positive\",length(use))else p>=t\n TP<-sum(w[a&y==1]);FP<-sum(w[a&y==0]);FN<-sum(w[!a&y==1]);TN<-sum(w[!a&y==0]);P<-TP+FN;N<-FP+TN;W<-P+N;PP<-TP+FP;PN<-TN+FN;TPR<-ratio(TP,P);TNR<-ratio(TN,N);bs<-sum(w*(p-y)^2);tc<-FP*cost[1]+FN*cost[2]\n list(confusion=list(TP=TP,FP=FP,FN=FN,TN=TN),mass=W,positiveTargetMass=P,negativeTargetMass=N,predictedPositiveMass=PP,predictedNegativeMass=PN,prevalence=ratio(P,W),selectionRate=ratio(PP,W),accuracy=ratio(TP+TN,W),precision=ratio(TP,PP),negativePredictiveValue=ratio(TN,PN),TPR=TPR,FPR=ratio(FP,N),TNR=TNR,FNR=ratio(FN,P),F1=ratio(2*TP,2*TP+FP+FN),balancedAccuracy=if(is.na(TPR)||is.na(TNR))NA_real_ else(TPR+TNR)/2,Brier=ratio(bs,W),BrierSum=bs,totalCost=tc,meanCost=ratio(tc,W),bayesThreshold=ratio(cost[1],sum(cost)))\n}\ncurvesG<-function(d,ids){\n use<-ids[d$eligible[ids]];grid<-c(list(\"always-negative\"),as.list(sort(unique(d$p[use]),decreasing=TRUE)));points<-lapply(grid,function(t){m<-metricsG(d,ids,t);c(list(policy=t),m$confusion,m[c(\"TPR\",\"FPR\",\"precision\")],list(recall=m$TPR))});pos<-use[d$y[use]==1];neg<-use[d$y[use]==0];P<-sum(d$w[pos]);N<-sum(d$w[neg]);U<-0\n for(i in pos)U<-U+d$w[i]*sum(d$w[neg]*((d$p[i]>d$p[neg])+.5*(d$p[i]==d$p[neg])))\n AP<-trap<-lastR<-0;lastP<-1\n if(P&&length(grid)>1)for(j in 2:length(grid)){z<-points[[j]];AP<-AP+(z$recall-lastR)*z$precision;trap<-trap+(z$recall-lastR)*(z$precision+lastP)/2;lastR<-z$recall;lastP<-z$precision}\n list(points=points,ROC_AUC=ratio(U,P*N),averagePrecision=if(P)AP else NA_real_,PRTrapezoidWithInitialPrecisionOne=if(P)trap else NA_real_)\n}\nchooseG<-function(d,a,cost){\n role<-if(is.null(a$selectionRole))\"validation\"else a$selectionRole;er<-if(is.null(a$evaluationRole))\"test\"else a$evaluationRole;ids<-scopeG(d,role);use<-ids[d$eligible[ids]];stopifnot(length(use)>0);grid<-if(is.null(a$thresholds))c(list(\"always-negative\"),as.list(sort(unique(d$p[use]),decreasing=TRUE)))else lapply(a$thresholds,function(t)if(t%in%c(\"always-negative\",\"always-positive\"))t else qnum(t))\n candidates<-lapply(seq_along(grid),function(j){m<-metricsG(d,ids,grid[[j]],cost);feasible<-TRUE;if(!is.null(a$minTPR))feasible<-feasible&&!is.na(m$TPR)&&m$TPR>=qnum(a$minTPR);if(!is.null(a$maxFPR))feasible<-feasible&&!is.na(m$FPR)&&m$FPR<=qnum(a$maxFPR);list(index=j-1,policy=grid[[j]],metrics=m,feasible=feasible)})\n good<-which(vapply(candidates,function(c)c$feasible,logical(1)));best<-NA_integer_;if(length(good)){v<-vapply(candidates[good],function(c)c$metrics$meanCost,numeric(1));best<-good[which(v<=min(v)+1e-12)[1]]}\n list(selectedIndex=if(is.na(best))NA_integer_ else best-1,selectedPolicy=if(is.na(best))NULL else grid[[best]],selectedValidation=if(is.na(best))NULL else candidates[[best]]$metrics,candidates=candidates,evaluation=if(is.na(best)||er==\"none\")NULL else metricsG(d,scopeG(d,er),grid[[best]],cost))\n}\ncalibrateG<-function(d,ids,edges){\n use<-ids[d$eligible[ids]];W<-sum(d$w[use]);pi<-ratio(sum(d$w[use]*d$y[use]),W);bins<-list();ECE<-rel<-res<-correction<-0;assign<-findInterval(d$p[use],edges,rightmost.closed=TRUE,all.inside=TRUE)\n for(b in seq_len(length(edges)-1)){rr<-use[assign==b];w<-sum(d$w[rr]);mp<-ratio(sum(d$w[rr]*d$p[rr]),w);o<-ratio(sum(d$w[rr]*d$y[rr]),w);variance<-if(w)sum(d$w[rr]*(d$p[rr]-mp)^2)/w else NA_real_;covariance<-if(w)sum(d$w[rr]*(d$p[rr]-mp)*(d$y[rr]-o))/w else NA_real_;bc<-variance-2*covariance;gap<-mp-o;bins[[b]]<-list(index=b-1,mass=w,meanPrediction=mp,eventRate=o,scoreVariance=variance,scoreTargetCovariance=covariance,withinBinCorrection=bc,ids=d$id[rr])\n  if(w){s<-w/W;ECE<-ECE+s*abs(gap);rel<-rel+s*gap^2;res<-res+s*(o-pi)^2;correction<-correction+s*bc}\n };bs<-ratio(sum(d$w[use]*(d$p[use]-d$y[use])^2),W);unc<-pi*(1-pi);list(bins=bins,Brier=bs,ECE=if(W)ECE else NA_real_,uncertainty=unc,reliability=if(W)rel else NA_real_,resolution=if(W)res else NA_real_,withinBinCorrection=if(W)correction else NA_real_,BrierIdentityResidual=bs-(unc-res+rel+correction))\n}\ngroupsG<-function(d,ids,t,cost){\n lev<-unique(d$group[ids][!is.na(d$group[ids])]);groups<-lapply(lev,function(g)list(group=g,metrics=metricsG(d,ids[!is.na(d$group[ids])&d$group[ids]==g],t,cost)));overall<-metricsG(d,ids,t,cost);unknown<-metricsG(d,ids[is.na(d$group[ids])],t,cost);gaps<-list()\n for(k in c(\"prevalence\",\"selectionRate\",\"TPR\",\"FPR\",\"precision\",\"accuracy\",\"meanCost\")){use<-Filter(function(g)g$metrics$mass>0,groups);v<-vapply(use,function(g)g$metrics[[k]],numeric(1));gaps[[k]]<-if(length(use)<2||anyNA(v))NA_real_ else max(v)-min(v)}\n list(overall=overall,groups=groups,unknownGroup=unknown,gaps=gaps,partitionMassResidual=overall$mass-unknown$mass-sum(vapply(groups,function(g)g$metrics$mass,numeric(1))))\n}\nsvgFixed<-function(file,points,title,xlabel,ylabel,legend){\n finite<-points[points$y!=\"undefined\"&points$x!=\"undefined\",,drop=FALSE];x<-as.numeric(finite$x);y<-as.numeric(finite$y);xmin<-if(length(x))min(x)else 0;xmax<-if(length(x))max(x)else 1;ymin<-min(c(0,y));ymax<-max(c(0,y));if(xmin==xmax){xmin<-xmin-.5;xmax<-xmax+.5};if(ymin==ymax)ymax<-ymin+1;X<-function(v)85+(v-xmin)/(xmax-xmin)*480;Y<-function(v)278-(v-ymin)/(ymax-ymin)*175\n esc<-function(s){s<-gsub(\"&\",\"&amp;\",s,fixed=TRUE);s<-gsub(\"<\",\"&lt;\",s,fixed=TRUE);gsub(\">\",\"&gt;\",s,fixed=TRUE)};s<-'<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"620\" height=\"360\" viewBox=\"0 0 620 360\"><rect width=\"620\" height=\"360\" fill=\"white\"/><g font-family=\"Arial, sans-serif\" font-size=\"13\" fill=\"#17324d\">'\n lines<-strwrap(title,width=65);for(i in seq_along(lines))s<-paste0(s,'<text x=\"25\" y=\"',24+(i-1)*18,'\">',esc(lines[i]),'</text>');colors<-c(\"#176b9b\",\"#b85e18\",\"#437e4d\")\n for(i in seq_along(legend))s<-paste0(s,'<circle cx=\"',30+(i-1)*250,'\" cy=\"76\" r=\"4\" fill=\"',colors[(i-1)%%3+1],'\"/><text x=\"',42+(i-1)*250,'\" y=\"80\">',esc(legend[i]),'</text>')\n s<-paste0(s,'<path d=\"M85 98V278H575\" fill=\"none\" stroke=\"#52677d\"/><text text-anchor=\"middle\" x=\"325\" y=\"338\">',esc(xlabel),'</text><text text-anchor=\"middle\" transform=\"translate(21,190) rotate(-90)\">',esc(ylabel),'</text>')\n for(i in 0:4){xx<-xmin+(xmax-xmin)*i/4;yy<-ymin+(ymax-ymin)*i/4;s<-paste0(s,'<text text-anchor=\"middle\" x=\"',sprintf(\"%.9g\",X(xx)),'\" y=\"305\">',sprintf(\"%.4g\",xx),'</text><text text-anchor=\"end\" x=\"77\" y=\"',sprintf(\"%.9g\",Y(yy)+4),'\">',sprintf(\"%.4g\",yy),'</text>')}\n for(i in seq_len(nrow(finite)))s<-paste0(s,'<circle cx=\"',sprintf(\"%.9g\",X(x[i])),'\" cy=\"',sprintf(\"%.9g\",Y(y[i])),'\" r=\"3\" fill=\"',colors[as.integer(finite$series[i])%%3+1],'\"/>');writeLines(paste0(s,'</g></svg>'),file,useBytes=TRUE)\n}\nfixedRun<-function(){\n api<-FIXED$api;a<-FIXED$args;summary<-list();points<-list();xlabel<-\"Declared index\";ylabel<-\"Value\";legend<-\"Declared result\"\n metric<-function(name,v,unit=\"dimensionless\"){if(is.null(v))v<-NA_real_;summary[[length(summary)+1L]]<<-data.frame(metric=name,value=if(is.na(v))\"undefined\"else sprintf(\"%.9g\",v),exactValue=\"\",unit=unit,defined=as.integer(!is.na(v)),stringsAsFactors=FALSE)}\n pt<-function(i,x,y,id=\"\",series=0){points[[length(points)+1L]]<<-data.frame(series=series,index=i,xExact=\"\",x=if(is.na(x))\"undefined\"else sprintf(\"%.9g\",x),yExact=\"\",y=if(is.na(y))\"undefined\"else sprintf(\"%.9g\",y),id=as.character(id),stringsAsFactors=FALSE)}\n if(api==\"realdata\"){\n  native<-loadData()[[a$kind]];fit<-fitmodel(native);d<-list(id=native$id,p=fit$pred,y=native$y,w=rep(1,length(native$id)),role=native$role,group=native$group,eligible=native$eligible);scenarios<-list()\n  for(j in 1:3){name<-c(\"equal\",\"miss-five\",\"alarm-five\")[j];cst<-list(c(1,1),c(1,5),c(5,1))[[j]];sel<-chooseG(d,list(),cst);scenarios[[j]]<-list(name=name,selection=sel);metric(paste0(name,\"Threshold\"),sel$selectedPolicy);metric(paste0(name,\"TestCost\"),sel$evaluation$meanCost,\"hypothetical cost units/mass\")}\n  ids<-scopeG(d,\"test\");cv<-curvesG(d,ids);cal<-calibrateG(d,ids,seq(0,1,.2));metric(\"testAUC\",cv$ROC_AUC);metric(\"testAP\",cv$averagePrecision);metric(\"testBrier\",cal$Brier);metric(\"eligibleRows\",sum(d$eligible),\"rows\")\n  for(j in seq_along(ids)){i<-ids[j];pt(j-1,j,d$p[i],d$id[i],0);pt(j-1,j,d$y[i],d$id[i],1)}\n  full<-list(kind=a$kind,fit=fit,scenarios=scenarios,testCurves=cv,testCalibration=cal,rowsScored=d);xlabel<-\"Test row, native order\";ylabel<-\"Y or probability\";legend<-c(\"Training-fitted probability\",\"Observed Y\")\n }else{\n  d<-rowsG(a$rows);role<-if(is.null(a$role))\"all\"else a$role;ids<-scopeG(d,role);cost<-if(is.null(a$costs))c(1,1)else c(qnum(a$costs$falsePositive),qnum(a$costs$falseNegative));t<-if(is.null(a$threshold)).5 else if(a$threshold%in%c(\"always-positive\",\"always-negative\"))a$threshold else qnum(a$threshold)\n  if(api==\"metrics\"){\n   full<-metricsG(d,ids,t,cost);for(k in c(\"mass\",\"accuracy\",\"precision\",\"TPR\",\"FPR\",\"F1\",\"Brier\",\"meanCost\"))metric(k,full[[k]],if(k==\"mass\")\"mass\"else if(k==\"meanCost\")\"hypothetical cost units/mass\"else\"dimensionless\");metric(\"BayesThreshold\",full$bayesThreshold)\n   for(i in 1:4)pt(i-1,i-1,full$confusion[[i]],names(full$confusion)[i]);xlabel<-\"TP / FP / FN / TN positions\";ylabel<-\"Analytical mass\"\n  }else if(api==\"curves\"){\n   full<-curvesG(d,ids);for(k in c(\"ROC_AUC\",\"averagePrecision\",\"PRTrapezoidWithInitialPrecisionOne\"))metric(k,full[[k]])\n   for(j in seq_along(full$points)){p<-full$points[[j]];pt(j-1,p$FPR,p$TPR,if(is.character(p$policy))p$policy else sprintf(\"%.17g\",p$policy))};xlabel<-\"False positive rate\";ylabel<-\"True positive rate\";legend<-\"Observed ROC operating points\"\n  }else if(api==\"choose\"){\n   full<-chooseG(d,a,cost);metric(\"selectedIndex\",full$selectedIndex,\"candidate index\");metric(\"minimumCost\",if(is.null(full$selectedValidation))NULL else full$selectedValidation$meanCost,\"hypothetical cost units/mass\");metric(\"feasible\",as.integer(!is.na(full$selectedIndex)),\"indicator\")\n   for(c in full$candidates)pt(c$index,c$index,c$metrics$meanCost,if(is.character(c$policy))c$policy else sprintf(\"%.17g\",c$policy));xlabel<-\"Validation candidate\";ylabel<-\"Assumed cost / mass\";legend<-\"Validation candidate costs\"\n  }else if(api==\"calibrate\"){\n   edges<-if(is.null(a$binEdges))seq(0,1,.2)else vapply(a$binEdges,qnum,numeric(1));full<-calibrateG(d,ids,edges);for(k in c(\"ECE\",\"Brier\",\"uncertainty\",\"resolution\",\"reliability\",\"withinBinCorrection\",\"BrierIdentityResidual\"))metric(k,full[[k]])\n   for(b in full$bins)pt(b$index,b$meanPrediction,b$eventRate,paste0(\"bin:\",b$index));xlabel<-\"Bin mean forecast\";ylabel<-\"Bin event rate\";legend<-\"Binary-event reliability\"\n  }else if(api==\"groups\"){\n   full<-groupsG(d,ids,t,cost);metric(\"overallTPR\",full$overall$TPR);metric(\"TPRGap\",full$gaps$TPR);metric(\"precisionGap\",full$gaps$precision);metric(\"unknownMass\",full$unknownGroup$mass,\"mass\");metric(\"partitionResidual\",full$partitionMassResidual,\"mass\")\n   for(j in seq_along(full$groups))pt(j-1,j-1,full$groups[[j]]$metrics$TPR,full$groups[[j]]$group);xlabel<-\"Declared group position\";ylabel<-\"True positive rate\";legend<-\"Known-group TPR\"\n  }else stop(\"unknown declared fixed API\")\n }\n sm<-do.call(rbind,summary);pp<-do.call(rbind,points);write.csv(sm,file.path(outDir,\"summary.csv\"),row.names=FALSE,na=\"\");write.csv(pp,file.path(outDir,\"plot-points.csv\"),row.names=FALSE,na=\"\");svgFixed(file.path(outDir,\"plot.svg\"),pp,FIXED$title,xlabel,ylabel,legend);dput(list(api=api,variant=FIXED$variant,input=FIXED$args,arithmetic=\"Base-R binary64 fixed example; not an exact rational general validator\",result=full),file=file.path(outDir,\"full.txt\"));cat(\"PASS\",api,FIXED$variant,\"summary\",nrow(sm),\"points\",nrow(pp),\"\\n\")\n}\n\nFIXED<-list(api=\"realdata\",variant=\"company\",args=list(kind=\"company\"),title=\"Actual company fixed train/validation/test procedure\")\nfixedRun()\n",
        "codeText": "# ML14 standalone public counterpart, base R only.\n# Inputs are only the three factual CSVs; derived columns/previous model answers unused.\n# Binary64 arithmetic, not arbitrary-precision Fraction. At numerical cost ties\n# within 1e-12 retain the earliest candidate. Exact claims belong to Python/web.\n# SHA256 infrastructure below is reused verbatim from the previous public study.\nargs<-commandArgs(trailingOnly=TRUE);filearg<-grep(\"^--file=\",commandArgs(),value=TRUE)\nhere<-if(dir.exists(\"ml14-sources\"))getwd()else if(length(filearg))dirname(normalizePath(sub(\"^--file=\",\"\",filearg[1])))else getwd()\noption<-function(key,default){i<-match(key,args);if(is.na(i))default else args[i+1]}\nsourceDir<-option(\"--source\",file.path(here,\"ml14-sources\"));outDir<-option(\"--out\",file.path(getwd(),\"ml14-r-results\"));dir.create(outDir,recursive=TRUE,showWarnings=FALSE)\nnum<-function(x){x[x%in%c(\"\",\".\")]<-NA_character_;as.numeric(x)}\nfmt<-function(x)ifelse(is.na(x),\"\",sprintf(\"%.17g\",x))\nratio<-function(a,b)if(b==0)NA_real_ else a/b\nreadnative<-function(name)read.csv(file.path(sourceDir,name),check.names=FALSE,colClasses=\"character\",na.strings=character(),stringsAsFactors=FALSE)\n# Vectorized SHA256 for the short ASCII keys used in this study.\n# Unsigned words use exact integer-valued doubles; bit operations use safe\n# 16-bit halves, avoiding R's reserved signed-INT_MIN/NA representation.\nMOD<-2^32\nxor32<-function(a,b) as.double(bitwXor(as.integer(floor(a/65536)),as.integer(floor(b/65536))))*65536+as.double(bitwXor(as.integer(a%%65536),as.integer(b%%65536)))\nand32<-function(a,b) as.double(bitwAnd(as.integer(floor(a/65536)),as.integer(floor(b/65536))))*65536+as.double(bitwAnd(as.integer(a%%65536),as.integer(b%%65536)))\nrot<-function(x,n) floor(x/2^n)+(x%%2^n)*2^(32-n)\nxor3<-function(a,b,c) xor32(xor32(a,b),c)\nK<-c(0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5,0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967,0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070,0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3,0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2)\nsha256<-function(strings) {\n n<-length(strings);bytes<-matrix(0,n,64)\n for(i in seq_len(n)) {v<-utf8ToInt(strings[i]);stopifnot(length(v)<56,all(v<128));if(length(v)) bytes[i,seq_along(v)]<-v;bytes[i,length(v)+1]<-128;bits<-length(v)*8;bytes[i,61:64]<-c(floor(bits/2^24)%%256,floor(bits/2^16)%%256,floor(bits/256)%%256,bits%%256)}\n w<-matrix(0,n,64)\n for(j in 1:16) {b<-4*(j-1)+1;w[,j]<-bytes[,b]*2^24+bytes[,b+1]*2^16+bytes[,b+2]*256+bytes[,b+3]}\n for(j in 17:64) {s0<-xor3(rot(w[,j-15],7),rot(w[,j-15],18),floor(w[,j-15]/8));s1<-xor3(rot(w[,j-2],17),rot(w[,j-2],19),floor(w[,j-2]/1024));w[,j]<-(w[,j-16]+s0+w[,j-7]+s1)%%MOD}\n init<-c(0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19)\n state<-lapply(init,function(v) rep(v,n));a<-state[[1]];b<-state[[2]];c<-state[[3]];d<-state[[4]];e<-state[[5]];f<-state[[6]];g<-state[[7]];h<-state[[8]]\n for(j in 1:64) {S1<-xor3(rot(e,6),rot(e,11),rot(e,25));ch<-xor32(and32(e,f),and32(MOD-1-e,g));t1<-(h+S1+ch+K[j]+w[,j])%%MOD;S0<-xor3(rot(a,2),rot(a,13),rot(a,22));maj<-xor3(and32(a,b),and32(a,c),and32(b,c));t2<-(S0+maj)%%MOD;h<-g;g<-f;f<-e;e<-(d+t1)%%MOD;d<-c;c<-b;b<-a;a<-(t1+t2)%%MOD}\n end<-list(a,b,c,d,e,f,g,h);hex<-lapply(1:8,function(j){v<-(end[[j]]+init[j])%%MOD;paste0(sprintf(\"%04x\",as.integer(floor(v/65536))),sprintf(\"%04x\",as.integer(v%%65536)))})\n do.call(paste0,hex)\n}\nstopifnot(identical(sha256(c(\"abc\",\"\")),c(\"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad\",\"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855\")))\n\nloadData<-function(){\n wb<-readnative(\"actual64-country-four-indicators-original-2024.csv\");codes<-c(\"NY.GDP.PCAP.KD\",\"NY.GDP.MKTP.KD.ZG\",\"FP.CPI.TOTL.ZG\",\"SP.DYN.LE00.IN\");iso<-sort(unique(wb$countryISO3));stopifnot(nrow(wb)==64,length(iso)==16)\n tokens<-t(vapply(iso,function(s)wb$originalValueToken[match(paste(s,codes),paste(wb$countryISO3,wb$indicatorID))],character(4)));vals<-matrix(num(as.vector(tokens)),nrow=nrow(tokens))\n country<-list(id=paste0(iso,\":2024\"),sourceRow=1:16,originalID=iso,x=vals[,1:3,drop=FALSE],rawX=tokens[,1:3,drop=FALSE],nativeTarget=tokens[,4],y=as.integer(vals[,4]>=80),group=ifelse(is.na(vals[,1]),NA_character_,as.character(as.integer(vals[,1]>=25000))),lineage=vapply(iso,function(s)paste(wb$sourceRow[match(paste(s,codes),paste(wb$countryISO3,wb$indicatorID))],collapse=\";\"),character(1)),cat=integer(),units=c(\"constant2015USD/person\",\"annualPercent\",\"annualPercent\"))\n nls<-readnative(\"actual3613-NLS-original52-fields-groups-roles.csv\");raw<-cbind(nls$ed76,nls$age76,nls$nearc4)\n person<-list(id=paste0(\"person:\",nls$sourceRow),sourceRow=as.integer(nls$sourceRow),originalID=nls$id,x=matrix(num(as.vector(raw)),nrow=nrow(raw)),rawX=raw,nativeTarget=nls$wage76,y=as.integer(num(nls$wage76)>=500),group=ifelse(nls$black%in%c(\"\",\".\"),NA_character_,nls$black),lineage=nls$sourceRow,cat=2L,units=c(\"years\",\"years\",\"nativeCategory\"))\n ch<-readnative(\"actual3150-churn-original14-fields-groups-roles.csv\");raw<-cbind(ch[[\"Call  Failure\"]],ch$Complains,ch[[\"Subscription  Length\"]],ch[[\"Seconds of Use\"]])\n company<-list(id=paste0(\"customer:\",ch$sourceRow),sourceRow=as.integer(ch$sourceRow),originalID=rep(\"\",nrow(ch)),x=matrix(num(as.vector(raw)),nrow=nrow(raw)),rawX=raw,nativeTarget=ch$Churn,y=as.integer(ch$Churn),group=ifelse(ch[[\"Tariff Plan\"]]%in%c(\"\",\".\"),NA_character_,ch[[\"Tariff Plan\"]]),lineage=ch$sourceRow,cat=1L,units=c(\"count\",\"nativeCategory\",\"months\",\"seconds\"))\n stopifnot(nrow(nls)==3613,nrow(ch)==3150,identical(as.integer(ch$sourceRow[ch[[\"Charge  Amount\"]]==\"10\"]),c(474L,2174L,2274L,2374L,2674L,2924L,2974L)))\n result<-list(country=country,person=person,company=company)\n for(k in names(result)){d<-result[[k]];n<-length(d$id);d$eligible<-!is.na(d$y)&rowSums(is.na(d$x))==0;hash<-sha256(paste0(\"ML14-role|\",k,\"|\",d$id));rank<-integer(n);rank[order(hash,seq_len(n))]<-seq_len(n)-1L;d$plannedRole<-ifelse(rank%%5==0,\"test\",ifelse(rank%%5==1,\"validation\",\"train\"));d$role<-ifelse(d$eligible,d$plannedRole,\"excluded\");result[[k]]<-d}\n stopifnot(sum(result$person$eligible)==3017);result\n}\nfitmodel<-function(d){\n ids<-which(d$role==\"train\");p<-ncol(d$x);m<-vapply(seq_len(p),function(j)if((j-1)%in%d$cat)NA_real_ else median(d$x[ids,j]),numeric(1));z<-d$x\n for(j in seq_len(p))if(!((j-1)%in%d$cat))z[,j]<-as.numeric(z[,j]>m[j])\n keys<-apply(z,1,function(v)paste(fmt(v),collapse=\"|\"));lev<-unique(keys[ids]);mass<-vapply(lev,function(k)sum(keys[ids]==k),integer(1));positive<-vapply(lev,function(k)sum(d$y[ids][keys[ids]==k]),integer(1));prob<-(positive+1)/(mass+2);fallback<-(sum(d$y[ids])+1)/(length(ids)+2);pred<-prob[match(keys,lev)];unseen<-is.na(pred);pred[unseen]<-fallback;pred[!d$eligible]<-NA_real_;unseen[!d$eligible]<-NA\n list(ids=ids,medians=m,z=z,keys=keys,lev=lev,mass=mass,positive=positive,prob=prob,fallback=fallback,pred=pred,unseen=unseen)\n}\nmeasure<-function(d,p,ids,t=.5,cost=c(1,1)){\n use<-ids[d$eligible[ids]&!is.na(p[ids])];y<-d$y[use];a<-if(is.character(t))rep(t==\"always-positive\",length(use))else p[use]>=t\n TP<-sum(a&y==1);FP<-sum(a&y==0);FN<-sum(!a&y==1);TN<-sum(!a&y==0);P<-TP+FN;N<-FP+TN;W<-P+N;PP<-TP+FP;PN<-TN+FN;TPR<-ratio(TP,P);TNR<-ratio(TN,N);bs<-sum((p[use]-y)^2);tc<-FP*cost[1]+FN*cost[2]\n list(TP=TP,FP=FP,FN=FN,TN=TN,mass=W,positiveTargetMass=P,negativeTargetMass=N,predictedPositiveMass=PP,predictedNegativeMass=PN,prevalence=ratio(P,W),selectionRate=ratio(PP,W),accuracy=ratio(TP+TN,W),precision=ratio(TP,PP),negativePredictiveValue=ratio(TN,PN),TPR=TPR,FPR=ratio(FP,N),TNR=TNR,FNR=ratio(FN,P),F1=ratio(2*TP,2*TP+FP+FN),balancedAccuracy=if(is.na(TPR)||is.na(TNR))NA_real_ else(TPR+TNR)/2,Brier=ratio(bs,W),BrierSum=bs,totalCost=tc,meanCost=ratio(tc,W))\n}\ncurves<-function(d,p,ids){\n use<-ids[d$eligible[ids]&!is.na(p[ids])];scores<-sort(unique(p[use]),decreasing=TRUE);policies<-c(list(\"always-negative\"),as.list(scores));points<-lapply(policies,function(t){m<-measure(d,p,ids,t);c(list(policy=t),m[c(\"TP\",\"FP\",\"FN\",\"TN\",\"TPR\",\"FPR\",\"precision\")],list(recall=m$TPR))})\n pos<-use[d$y[use]==1];neg<-use[d$y[use]==0];U<-0;for(i in pos)U<-U+sum(p[i]>p[neg])+.5*sum(p[i]==p[neg])\n AP<-0;trap<-0;lastR<-0;lastP<-1\n if(length(pos)&&length(scores))for(j in seq_along(scores)){z<-points[[j+1]];AP<-AP+(z$recall-lastR)*z$precision;trap<-trap+(z$recall-lastR)*(z$precision+lastP)/2;lastR<-z$recall;lastP<-z$precision}\n list(points=points,ROC_AUC=ratio(U,length(pos)*length(neg)),averagePrecision=if(length(pos))AP else NA_real_,PRTrapezoidWithInitialPrecisionOne=if(length(pos))trap else NA_real_)\n}\ncalibrate<-function(d,p,ids){\n use<-ids[d$eligible[ids]&!is.na(p[ids])];W<-length(use);pi<-if(W)mean(d$y[use])else NA_real_;bins<-list();ECE<-rel<-res<-correction<-0\n whichbin<-findInterval(p[use],seq(0,1,.2),rightmost.closed=TRUE,all.inside=TRUE)\n for(b in 1:5){rr<-use[whichbin==b];w<-length(rr);mp<-if(w)mean(p[rr])else NA_real_;o<-if(w)mean(d$y[rr])else NA_real_;variance<-if(w)mean((p[rr]-mp)^2)else NA_real_;covariance<-if(w)mean((p[rr]-mp)*(d$y[rr]-o))else NA_real_;bc<-variance-2*covariance;gap<-mp-o\n  bins[[b]]<-list(mass=w,meanPrediction=mp,eventRate=o,gap=gap,absoluteGap=abs(gap),scoreVariance=variance,scoreTargetCovariance=covariance,withinBinCorrection=bc,rows=w,ids=d$id[rr])\n  if(w){share<-w/W;ECE<-ECE+share*abs(gap);rel<-rel+share*gap^2;res<-res+share*(o-pi)^2;correction<-correction+share*bc}\n };bs<-if(W)mean((p[use]-d$y[use])^2)else NA_real_;unc<-pi*(1-pi)\n list(bins=bins,ECE=if(W)ECE else NA_real_,Brier=bs,reliability=if(W)rel else NA_real_,resolution=if(W)res else NA_real_,uncertainty=unc,withinBinCorrection=if(W)correction else NA_real_,BrierIdentityResidual=bs-(unc-res+rel+correction))\n}\ncounts<-c(\"mass\",\"positiveTargetMass\",\"negativeTargetMass\",\"predictedPositiveMass\",\"predictedNegativeMass\");rates<-c(\"prevalence\",\"selectionRate\",\"accuracy\",\"precision\",\"negativePredictiveValue\",\"TPR\",\"FPR\",\"TNR\",\"FNR\",\"F1\",\"balancedAccuracy\",\"Brier\",\"BrierSum\",\"totalCost\",\"meanCost\")\ntables<-setNames(lapply(1:10,function(i)list()),c(\"predictions\",\"lineage\",\"fit-medians\",\"fit-cells\",\"validation-candidates\",\"test-metrics\",\"test-curves\",\"calibration-bins\",\"group-metrics\",\"chart-points\"))\nadd<-function(name,row)tables[[name]][[length(tables[[name]])+1L]]<<-row\nscalars<-function(m,keys){out<-list();for(k in keys){out[[paste0(k,\"Exact\")]]<-\"\";out[[paste0(k,\"Approx\")]]<-fmt(m[[k]])};out}\ntagrow<-function(kind,...)c(list(kind=kind),list(...))\npoint<-function(kind,chart,series,index,x,y,xunit=\"dimensionless\",yunit=\"dimensionless\",role=\"test\",tag=\"\"){add(\"chart-points\",tagrow(kind,chart=chart,series=series,index=index,xExact=\"\",xApprox=fmt(x),yExact=\"\",yApprox=fmt(y),xUnit=xunit,yUnit=yunit,role=role,tag=tag))}\nstudy<-function(kind,d){\n f<-fitmodel(d);n<-length(d$id);train<-which(d$role==\"train\");validation<-which(d$role==\"validation\");test<-which(d$role==\"test\");p<-f$pred;cv<-curves(d,p,test);cal<-calibrate(d,p,test)\n for(i in seq_len(n)){\n  reason<-if(d$eligible[i])\"\"else\"required-X-or-Y-missing\";transformed<-if(d$eligible[i])paste(fmt(f$z[i,]),collapse=\"|\")else\"\"\n  add(\"predictions\",tagrow(kind,id=d$id[i],sourceRow=d$sourceRow[i],originalID=d$originalID[i],plannedRole=d$plannedRole[i],role=d$role[i],group=ifelse(is.na(d$group[i]),\"\",d$group[i]),eligible=as.integer(d$eligible[i]),targetExact=fmt(d$y[i]),probabilityExact=\"\",probabilityApprox=fmt(p[i]),unseenCell=ifelse(is.na(f$unseen[i]),\"\",as.character(as.integer(f$unseen[i]))),transformedX=transformed,reason=reason))\n  raw<-d$rawX[i,];raw[raw%in%c(\"\",\".\")]<-\"\";nativeY<-d$nativeTarget[i];if(nativeY%in%c(\"\",\".\"))nativeY<-\"\"\n  add(\"lineage\",tagrow(kind,id=d$id[i],sourceRow=d$sourceRow[i],originalID=d$originalID[i],nativeSourceRows=d$lineage[i],rawX=paste(raw,collapse=\"|\"),nativeTarget=nativeY,derivedTarget=fmt(d$y[i]),nativeGroup=ifelse(is.na(d$group[i]),\"\",d$group[i]),plannedRole=d$plannedRole[i],role=d$role[i],eligible=as.integer(d$eligible[i]),analyticalMass=\"1\",reason=reason))\n }\n for(j in seq_len(ncol(d$x)))add(\"fit-medians\",tagrow(kind,feature=j-1,categorical=as.integer((j-1)%in%d$cat),fitRows=length(train),medianExact=\"\",medianApprox=fmt(f$medians[j]),unit=d$units[j]))\n for(j in seq_along(f$lev))add(\"fit-cells\",tagrow(kind,cell=f$lev[j],trainingRows=f$mass[j],positiveRows=f$positive[j],probabilityExact=\"\",probabilityApprox=fmt(f$prob[j]),fallbackExact=\"\",fallbackApprox=fmt(f$fallback)))\n for(j in seq_along(cv$points)){\n  z<-cv$points[[j]];t<-z$policy;add(\"test-curves\",c(tagrow(kind,point=j-1,policy=if(is.character(t))t else\"threshold\",thresholdExact=\"\",thresholdApprox=if(is.character(t))\"\"else fmt(t)),scalars(z,c(\"TP\",\"FP\",\"FN\",\"TN\",\"TPR\",\"FPR\",\"precision\",\"recall\"))))\n  point(kind,\"roc\",\"ROC\",j-1,z$FPR,z$TPR);point(kind,\"pr\",\"PR-observed\",j-1,z$recall,z$precision)\n }\n for(b in 1:5){z<-cal$bins[[b]];add(\"calibration-bins\",c(tagrow(kind,bin=b-1,leftExact=c(\"0\",\"1/5\",\"2/5\",\"3/5\",\"4/5\")[b],rightExact=c(\"1/5\",\"2/5\",\"3/5\",\"4/5\",\"1\")[b],rightClosed=as.integer(b==5),rows=z$rows,ids=paste(z$ids,collapse=\";\")),scalars(z,c(\"mass\",\"meanPrediction\",\"eventRate\",\"gap\",\"absoluteGap\",\"scoreVariance\",\"scoreTargetCovariance\",\"withinBinCorrection\"))));point(kind,\"reliability\",\"Binary event rate\",b-1,z$meanPrediction,z$eventRate,tag=paste0(\"rows=\",z$rows))}\n for(j in seq_along(test)){i<-test[j];point(kind,\"test-scores\",\"Training-fitted probability\",j-1,j,p[i],\"test-row position\",\"probability\",tag=d$id[i]);point(kind,\"test-scores\",\"Observed Y\",j-1,j,d$y[i],\"test-row position\",\"binary target\",tag=d$id[i])}\n scenarioNames<-c(\"equal\",\"miss-five\",\"alarm-five\");costs<-list(c(1,1),c(1,5),c(5,1))\n for(s in 1:3){name<-scenarioNames[s];cost<-costs[[s]];grid<-c(list(\"always-negative\"),as.list(sort(unique(p[validation]),decreasing=TRUE)));candidates<-lapply(grid,function(t)measure(d,p,validation,t,cost));values<-vapply(candidates,function(m)m$meanCost,numeric(1));best<-which(values<=min(values)+1e-12)[1];chosen<-grid[[best]];ev<-measure(d,p,test,chosen,cost)\n  for(j in seq_along(grid)){t<-grid[[j]];m<-candidates[[j]];cell<-setNames(lapply(c(\"TP\",\"FP\",\"FN\",\"TN\"),function(k)fmt(m[[k]])),paste0(c(\"TP\",\"FP\",\"FN\",\"TN\"),\"Exact\"));add(\"validation-candidates\",c(tagrow(kind,scenario=name,candidate=j-1,selected=as.integer(j==best),policy=if(is.character(t))t else\"threshold\",thresholdExact=\"\",thresholdApprox=if(is.character(t))\"\"else fmt(t),feasible=1,reasons=\"\"),cell,scalars(m,c(counts,\"TPR\",\"FPR\",\"precision\",\"meanCost\",\"totalCost\"))));point(kind,\"validation-cost\",name,j-1,j-1,m$meanCost,\"candidate index\",\"hypothetical cost units/mass\",\"validation\",if(is.character(t))t else fmt(t))}\n  m<-c(ev,cv[c(\"ROC_AUC\",\"averagePrecision\",\"PRTrapezoidWithInitialPrecisionOne\")],cal[c(\"ECE\",\"reliability\",\"resolution\",\"uncertainty\",\"withinBinCorrection\",\"BrierIdentityResidual\")])\n  for(k in c(\"TP\",\"FP\",\"FN\",\"TN\",counts,rates,\"ROC_AUC\",\"averagePrecision\",\"PRTrapezoidWithInitialPrecisionOne\",\"ECE\",\"reliability\",\"resolution\",\"uncertainty\",\"withinBinCorrection\",\"BrierIdentityResidual\")){\n   unit<-if(k%in%c(\"TP\",\"FP\",\"FN\",\"TN\",counts))\"rows\"else if(k==\"totalCost\")\"hypothetical cost units\"else if(k==\"meanCost\")\"hypothetical cost units/mass\"else if(k==\"BrierSum\")\"sum squared-probability loss\"else\"dimensionless\"\n   add(\"test-metrics\",tagrow(kind,scenario=name,metric=k,valueExact=\"\",valueApprox=fmt(m[[k]]),unit=unit))\n  }\n  lev<-unique(d$group[test][!is.na(d$group[test])]);sets<-c(list(test),lapply(lev,function(g)test[!is.na(d$group[test])&d$group[test]==g]),list(test[is.na(d$group[test])]))\n  types<-c(\"overall\",rep(\"known\",length(lev)),\"unknown\");tokens<-c(\"all\",lev,\"\")\n  for(j in seq_along(sets)){ids<-sets[[j]];m<-measure(d,p,ids,chosen,cost);cell<-setNames(lapply(c(\"TP\",\"FP\",\"FN\",\"TN\"),function(k)fmt(m[[k]])),paste0(c(\"TP\",\"FP\",\"FN\",\"TN\"),\"Exact\"));add(\"group-metrics\",c(tagrow(kind,scenario=name,groupType=types[j],groupToken=tokens[j],retainedRows=length(ids)),cell,scalars(m,c(counts,rates))));if(types[j]==\"known\")point(kind,\"group-TPR\",name,j-2,j-2,m$TPR,\"declared group position\",\"TPR\",tag=tokens[j])}\n }\n invisible(NULL)\n}\n\n# Fixed finite inputs only; not the complete web input/budget validator.\nqnum<-function(v){if(is.null(v))return(NA_real_);if(is.logical(v))return(as.numeric(v));s<-as.character(v);if(grepl(\"/\",s,fixed=TRUE)){a<-strsplit(s,\"/\",fixed=TRUE)[[1]];return(as.numeric(a[1])/as.numeric(a[2]))};as.numeric(s)}\nrowsG<-function(raw){\n n<-length(raw);get<-function(r,k,default=NULL)if(is.null(r[[k]]))default else r[[k]]\n id<-vapply(raw,function(r)as.character(r$id),character(1));p<-vapply(raw,function(r)qnum(r$score),numeric(1));y<-vapply(raw,function(r)qnum(r$y),numeric(1));w<-vapply(raw,function(r)qnum(get(r,\"weight\",\"1\")),numeric(1));role<-vapply(raw,function(r)get(r,\"role\",\"evaluation\"),character(1));group<-vapply(raw,function(r)as.character(get(r,\"group\",NA_character_)),character(1))\n stopifnot(all(w>=0),all(is.na(p)|(p>=0&p<=1)),all(is.na(y)|y%in%c(0,1)),!anyDuplicated(id));list(id=id,p=p,y=y,w=w,role=role,group=group,eligible=!is.na(p)&!is.na(y)&w>0&role!=\"excluded\")\n}\nscopeG<-function(d,role=\"all\")if(role==\"all\")seq_along(d$id)else which(d$role==role)\nmetricsG<-function(d,ids,t=.5,cost=c(1,1)){\n use<-ids[d$eligible[ids]];p<-d$p[use];y<-d$y[use];w<-d$w[use];a<-if(is.character(t))rep(t==\"always-positive\",length(use))else p>=t\n TP<-sum(w[a&y==1]);FP<-sum(w[a&y==0]);FN<-sum(w[!a&y==1]);TN<-sum(w[!a&y==0]);P<-TP+FN;N<-FP+TN;W<-P+N;PP<-TP+FP;PN<-TN+FN;TPR<-ratio(TP,P);TNR<-ratio(TN,N);bs<-sum(w*(p-y)^2);tc<-FP*cost[1]+FN*cost[2]\n list(confusion=list(TP=TP,FP=FP,FN=FN,TN=TN),mass=W,positiveTargetMass=P,negativeTargetMass=N,predictedPositiveMass=PP,predictedNegativeMass=PN,prevalence=ratio(P,W),selectionRate=ratio(PP,W),accuracy=ratio(TP+TN,W),precision=ratio(TP,PP),negativePredictiveValue=ratio(TN,PN),TPR=TPR,FPR=ratio(FP,N),TNR=TNR,FNR=ratio(FN,P),F1=ratio(2*TP,2*TP+FP+FN),balancedAccuracy=if(is.na(TPR)||is.na(TNR))NA_real_ else(TPR+TNR)/2,Brier=ratio(bs,W),BrierSum=bs,totalCost=tc,meanCost=ratio(tc,W),bayesThreshold=ratio(cost[1],sum(cost)))\n}\ncurvesG<-function(d,ids){\n use<-ids[d$eligible[ids]];grid<-c(list(\"always-negative\"),as.list(sort(unique(d$p[use]),decreasing=TRUE)));points<-lapply(grid,function(t){m<-metricsG(d,ids,t);c(list(policy=t),m$confusion,m[c(\"TPR\",\"FPR\",\"precision\")],list(recall=m$TPR))});pos<-use[d$y[use]==1];neg<-use[d$y[use]==0];P<-sum(d$w[pos]);N<-sum(d$w[neg]);U<-0\n for(i in pos)U<-U+d$w[i]*sum(d$w[neg]*((d$p[i]>d$p[neg])+.5*(d$p[i]==d$p[neg])))\n AP<-trap<-lastR<-0;lastP<-1\n if(P&&length(grid)>1)for(j in 2:length(grid)){z<-points[[j]];AP<-AP+(z$recall-lastR)*z$precision;trap<-trap+(z$recall-lastR)*(z$precision+lastP)/2;lastR<-z$recall;lastP<-z$precision}\n list(points=points,ROC_AUC=ratio(U,P*N),averagePrecision=if(P)AP else NA_real_,PRTrapezoidWithInitialPrecisionOne=if(P)trap else NA_real_)\n}\nchooseG<-function(d,a,cost){\n role<-if(is.null(a$selectionRole))\"validation\"else a$selectionRole;er<-if(is.null(a$evaluationRole))\"test\"else a$evaluationRole;ids<-scopeG(d,role);use<-ids[d$eligible[ids]];stopifnot(length(use)>0);grid<-if(is.null(a$thresholds))c(list(\"always-negative\"),as.list(sort(unique(d$p[use]),decreasing=TRUE)))else lapply(a$thresholds,function(t)if(t%in%c(\"always-negative\",\"always-positive\"))t else qnum(t))\n candidates<-lapply(seq_along(grid),function(j){m<-metricsG(d,ids,grid[[j]],cost);feasible<-TRUE;if(!is.null(a$minTPR))feasible<-feasible&&!is.na(m$TPR)&&m$TPR>=qnum(a$minTPR);if(!is.null(a$maxFPR))feasible<-feasible&&!is.na(m$FPR)&&m$FPR<=qnum(a$maxFPR);list(index=j-1,policy=grid[[j]],metrics=m,feasible=feasible)})\n good<-which(vapply(candidates,function(c)c$feasible,logical(1)));best<-NA_integer_;if(length(good)){v<-vapply(candidates[good],function(c)c$metrics$meanCost,numeric(1));best<-good[which(v<=min(v)+1e-12)[1]]}\n list(selectedIndex=if(is.na(best))NA_integer_ else best-1,selectedPolicy=if(is.na(best))NULL else grid[[best]],selectedValidation=if(is.na(best))NULL else candidates[[best]]$metrics,candidates=candidates,evaluation=if(is.na(best)||er==\"none\")NULL else metricsG(d,scopeG(d,er),grid[[best]],cost))\n}\ncalibrateG<-function(d,ids,edges){\n use<-ids[d$eligible[ids]];W<-sum(d$w[use]);pi<-ratio(sum(d$w[use]*d$y[use]),W);bins<-list();ECE<-rel<-res<-correction<-0;assign<-findInterval(d$p[use],edges,rightmost.closed=TRUE,all.inside=TRUE)\n for(b in seq_len(length(edges)-1)){rr<-use[assign==b];w<-sum(d$w[rr]);mp<-ratio(sum(d$w[rr]*d$p[rr]),w);o<-ratio(sum(d$w[rr]*d$y[rr]),w);variance<-if(w)sum(d$w[rr]*(d$p[rr]-mp)^2)/w else NA_real_;covariance<-if(w)sum(d$w[rr]*(d$p[rr]-mp)*(d$y[rr]-o))/w else NA_real_;bc<-variance-2*covariance;gap<-mp-o;bins[[b]]<-list(index=b-1,mass=w,meanPrediction=mp,eventRate=o,scoreVariance=variance,scoreTargetCovariance=covariance,withinBinCorrection=bc,ids=d$id[rr])\n  if(w){s<-w/W;ECE<-ECE+s*abs(gap);rel<-rel+s*gap^2;res<-res+s*(o-pi)^2;correction<-correction+s*bc}\n };bs<-ratio(sum(d$w[use]*(d$p[use]-d$y[use])^2),W);unc<-pi*(1-pi);list(bins=bins,Brier=bs,ECE=if(W)ECE else NA_real_,uncertainty=unc,reliability=if(W)rel else NA_real_,resolution=if(W)res else NA_real_,withinBinCorrection=if(W)correction else NA_real_,BrierIdentityResidual=bs-(unc-res+rel+correction))\n}\ngroupsG<-function(d,ids,t,cost){\n lev<-unique(d$group[ids][!is.na(d$group[ids])]);groups<-lapply(lev,function(g)list(group=g,metrics=metricsG(d,ids[!is.na(d$group[ids])&d$group[ids]==g],t,cost)));overall<-metricsG(d,ids,t,cost);unknown<-metricsG(d,ids[is.na(d$group[ids])],t,cost);gaps<-list()\n for(k in c(\"prevalence\",\"selectionRate\",\"TPR\",\"FPR\",\"precision\",\"accuracy\",\"meanCost\")){use<-Filter(function(g)g$metrics$mass>0,groups);v<-vapply(use,function(g)g$metrics[[k]],numeric(1));gaps[[k]]<-if(length(use)<2||anyNA(v))NA_real_ else max(v)-min(v)}\n list(overall=overall,groups=groups,unknownGroup=unknown,gaps=gaps,partitionMassResidual=overall$mass-unknown$mass-sum(vapply(groups,function(g)g$metrics$mass,numeric(1))))\n}\nsvgFixed<-function(file,points,title,xlabel,ylabel,legend){\n finite<-points[points$y!=\"undefined\"&points$x!=\"undefined\",,drop=FALSE];x<-as.numeric(finite$x);y<-as.numeric(finite$y);xmin<-if(length(x))min(x)else 0;xmax<-if(length(x))max(x)else 1;ymin<-min(c(0,y));ymax<-max(c(0,y));if(xmin==xmax){xmin<-xmin-.5;xmax<-xmax+.5};if(ymin==ymax)ymax<-ymin+1;X<-function(v)85+(v-xmin)/(xmax-xmin)*480;Y<-function(v)278-(v-ymin)/(ymax-ymin)*175\n esc<-function(s){s<-gsub(\"&\",\"&amp;\",s,fixed=TRUE);s<-gsub(\"<\",\"&lt;\",s,fixed=TRUE);gsub(\">\",\"&gt;\",s,fixed=TRUE)};s<-'<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"620\" height=\"360\" viewBox=\"0 0 620 360\"><rect width=\"620\" height=\"360\" fill=\"white\"/><g font-family=\"Arial, sans-serif\" font-size=\"13\" fill=\"#17324d\">'\n lines<-strwrap(title,width=65);for(i in seq_along(lines))s<-paste0(s,'<text x=\"25\" y=\"',24+(i-1)*18,'\">',esc(lines[i]),'</text>');colors<-c(\"#176b9b\",\"#b85e18\",\"#437e4d\")\n for(i in seq_along(legend))s<-paste0(s,'<circle cx=\"',30+(i-1)*250,'\" cy=\"76\" r=\"4\" fill=\"',colors[(i-1)%%3+1],'\"/><text x=\"',42+(i-1)*250,'\" y=\"80\">',esc(legend[i]),'</text>')\n s<-paste0(s,'<path d=\"M85 98V278H575\" fill=\"none\" stroke=\"#52677d\"/><text text-anchor=\"middle\" x=\"325\" y=\"338\">',esc(xlabel),'</text><text text-anchor=\"middle\" transform=\"translate(21,190) rotate(-90)\">',esc(ylabel),'</text>')\n for(i in 0:4){xx<-xmin+(xmax-xmin)*i/4;yy<-ymin+(ymax-ymin)*i/4;s<-paste0(s,'<text text-anchor=\"middle\" x=\"',sprintf(\"%.9g\",X(xx)),'\" y=\"305\">',sprintf(\"%.4g\",xx),'</text><text text-anchor=\"end\" x=\"77\" y=\"',sprintf(\"%.9g\",Y(yy)+4),'\">',sprintf(\"%.4g\",yy),'</text>')}\n for(i in seq_len(nrow(finite)))s<-paste0(s,'<circle cx=\"',sprintf(\"%.9g\",X(x[i])),'\" cy=\"',sprintf(\"%.9g\",Y(y[i])),'\" r=\"3\" fill=\"',colors[as.integer(finite$series[i])%%3+1],'\"/>');writeLines(paste0(s,'</g></svg>'),file,useBytes=TRUE)\n}\nfixedRun<-function(){\n api<-FIXED$api;a<-FIXED$args;summary<-list();points<-list();xlabel<-\"Declared index\";ylabel<-\"Value\";legend<-\"Declared result\"\n metric<-function(name,v,unit=\"dimensionless\"){if(is.null(v))v<-NA_real_;summary[[length(summary)+1L]]<<-data.frame(metric=name,value=if(is.na(v))\"undefined\"else sprintf(\"%.9g\",v),exactValue=\"\",unit=unit,defined=as.integer(!is.na(v)),stringsAsFactors=FALSE)}\n pt<-function(i,x,y,id=\"\",series=0){points[[length(points)+1L]]<<-data.frame(series=series,index=i,xExact=\"\",x=if(is.na(x))\"undefined\"else sprintf(\"%.9g\",x),yExact=\"\",y=if(is.na(y))\"undefined\"else sprintf(\"%.9g\",y),id=as.character(id),stringsAsFactors=FALSE)}\n if(api==\"realdata\"){\n  native<-loadData()[[a$kind]];fit<-fitmodel(native);d<-list(id=native$id,p=fit$pred,y=native$y,w=rep(1,length(native$id)),role=native$role,group=native$group,eligible=native$eligible);scenarios<-list()\n  for(j in 1:3){name<-c(\"equal\",\"miss-five\",\"alarm-five\")[j];cst<-list(c(1,1),c(1,5),c(5,1))[[j]];sel<-chooseG(d,list(),cst);scenarios[[j]]<-list(name=name,selection=sel);metric(paste0(name,\"Threshold\"),sel$selectedPolicy);metric(paste0(name,\"TestCost\"),sel$evaluation$meanCost,\"hypothetical cost units/mass\")}\n  ids<-scopeG(d,\"test\");cv<-curvesG(d,ids);cal<-calibrateG(d,ids,seq(0,1,.2));metric(\"testAUC\",cv$ROC_AUC);metric(\"testAP\",cv$averagePrecision);metric(\"testBrier\",cal$Brier);metric(\"eligibleRows\",sum(d$eligible),\"rows\")\n  for(j in seq_along(ids)){i<-ids[j];pt(j-1,j,d$p[i],d$id[i],0);pt(j-1,j,d$y[i],d$id[i],1)}\n  full<-list(kind=a$kind,fit=fit,scenarios=scenarios,testCurves=cv,testCalibration=cal,rowsScored=d);xlabel<-\"Test row, native order\";ylabel<-\"Y or probability\";legend<-c(\"Training-fitted probability\",\"Observed Y\")\n }else{\n  d<-rowsG(a$rows);role<-if(is.null(a$role))\"all\"else a$role;ids<-scopeG(d,role);cost<-if(is.null(a$costs))c(1,1)else c(qnum(a$costs$falsePositive),qnum(a$costs$falseNegative));t<-if(is.null(a$threshold)).5 else if(a$threshold%in%c(\"always-positive\",\"always-negative\"))a$threshold else qnum(a$threshold)\n  if(api==\"metrics\"){\n   full<-metricsG(d,ids,t,cost);for(k in c(\"mass\",\"accuracy\",\"precision\",\"TPR\",\"FPR\",\"F1\",\"Brier\",\"meanCost\"))metric(k,full[[k]],if(k==\"mass\")\"mass\"else if(k==\"meanCost\")\"hypothetical cost units/mass\"else\"dimensionless\");metric(\"BayesThreshold\",full$bayesThreshold)\n   for(i in 1:4)pt(i-1,i-1,full$confusion[[i]],names(full$confusion)[i]);xlabel<-\"TP / FP / FN / TN positions\";ylabel<-\"Analytical mass\"\n  }else if(api==\"curves\"){\n   full<-curvesG(d,ids);for(k in c(\"ROC_AUC\",\"averagePrecision\",\"PRTrapezoidWithInitialPrecisionOne\"))metric(k,full[[k]])\n   for(j in seq_along(full$points)){p<-full$points[[j]];pt(j-1,p$FPR,p$TPR,if(is.character(p$policy))p$policy else sprintf(\"%.17g\",p$policy))};xlabel<-\"False positive rate\";ylabel<-\"True positive rate\";legend<-\"Observed ROC operating points\"\n  }else if(api==\"choose\"){\n   full<-chooseG(d,a,cost);metric(\"selectedIndex\",full$selectedIndex,\"candidate index\");metric(\"minimumCost\",if(is.null(full$selectedValidation))NULL else full$selectedValidation$meanCost,\"hypothetical cost units/mass\");metric(\"feasible\",as.integer(!is.na(full$selectedIndex)),\"indicator\")\n   for(c in full$candidates)pt(c$index,c$index,c$metrics$meanCost,if(is.character(c$policy))c$policy else sprintf(\"%.17g\",c$policy));xlabel<-\"Validation candidate\";ylabel<-\"Assumed cost / mass\";legend<-\"Validation candidate costs\"\n  }else if(api==\"calibrate\"){\n   edges<-if(is.null(a$binEdges))seq(0,1,.2)else vapply(a$binEdges,qnum,numeric(1));full<-calibrateG(d,ids,edges);for(k in c(\"ECE\",\"Brier\",\"uncertainty\",\"resolution\",\"reliability\",\"withinBinCorrection\",\"BrierIdentityResidual\"))metric(k,full[[k]])\n   for(b in full$bins)pt(b$index,b$meanPrediction,b$eventRate,paste0(\"bin:\",b$index));xlabel<-\"Bin mean forecast\";ylabel<-\"Bin event rate\";legend<-\"Binary-event reliability\"\n  }else if(api==\"groups\"){\n   full<-groupsG(d,ids,t,cost);metric(\"overallTPR\",full$overall$TPR);metric(\"TPRGap\",full$gaps$TPR);metric(\"precisionGap\",full$gaps$precision);metric(\"unknownMass\",full$unknownGroup$mass,\"mass\");metric(\"partitionResidual\",full$partitionMassResidual,\"mass\")\n   for(j in seq_along(full$groups))pt(j-1,j-1,full$groups[[j]]$metrics$TPR,full$groups[[j]]$group);xlabel<-\"Declared group position\";ylabel<-\"True positive rate\";legend<-\"Known-group TPR\"\n  }else stop(\"unknown declared fixed API\")\n }\n sm<-do.call(rbind,summary);pp<-do.call(rbind,points);write.csv(sm,file.path(outDir,\"summary.csv\"),row.names=FALSE,na=\"\");write.csv(pp,file.path(outDir,\"plot-points.csv\"),row.names=FALSE,na=\"\");svgFixed(file.path(outDir,\"plot.svg\"),pp,FIXED$title,xlabel,ylabel,legend);dput(list(api=api,variant=FIXED$variant,input=FIXED$args,arithmetic=\"Base-R binary64 fixed example; not an exact rational general validator\",result=full),file=file.path(outDir,\"full.txt\"));cat(\"PASS\",api,FIXED$variant,\"summary\",nrow(sm),\"points\",nrow(pp),\"\\n\")\n}\n\nFIXED<-list(api=\"realdata\",variant=\"company\",args=list(kind=\"company\"),title=\"Actual company fixed train/validation/test procedure\")\nfixedRun()\n",
        "input": {
          "kind": "company"
        },
        "inputFiles": [
          {
            "file": "../ml14-sources/actual64-country-four-indicators-original-2024.csv",
            "sha256": "3d2b655cf807bf3ff049af187a9b7484b4e637f441f6f1925aba7acc5b0c861c"
          },
          {
            "file": "../ml14-sources/actual3613-NLS-original52-fields-groups-roles.csv",
            "sha256": "df404c3ce0336ab3ae2bfdd6b246c6e8acc058fd526ebf950dde270787bcd600"
          },
          {
            "file": "../ml14-sources/actual3150-churn-original14-fields-groups-roles.csv",
            "sha256": "d8af1f4905af8699e3ea024a6998319c82ac97b33ba1dec182391c0b30795023"
          }
        ],
        "returnCode": 0,
        "expectedFailure": false,
        "stdout": "PASS realdata company summary 10 points 1260 \n",
        "stderr": "During startup - Warning messages:\n1: Setting LC_COLLATE=C.UTF-8 failed \n2: Setting LC_CTYPE=C.UTF-8 failed \n3: Setting LC_MONETARY=C.UTF-8 failed \n4: Setting LC_TIME=C.UTF-8 failed \n",
        "summary": {
          "equalThreshold": "0.586206897",
          "equalTestCost": "0.114285714",
          "miss-fiveThreshold": "0.151785714",
          "miss-fiveTestCost": "0.482539683",
          "alarm-fiveThreshold": "0.947368421",
          "alarm-fiveTestCost": "0.142857143",
          "testAUC": "0.815066038",
          "testAP": "0.528392751",
          "testBrier": "0.0968492331",
          "eligibleRows": "3150"
        },
        "summaryRows": [
          {
            "metric": "equalThreshold",
            "value": "0.586206897",
            "exactValue": "",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "equalTestCost",
            "value": "0.114285714",
            "exactValue": "",
            "unit": "hypothetical cost units/mass",
            "defined": "1"
          },
          {
            "metric": "miss-fiveThreshold",
            "value": "0.151785714",
            "exactValue": "",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "miss-fiveTestCost",
            "value": "0.482539683",
            "exactValue": "",
            "unit": "hypothetical cost units/mass",
            "defined": "1"
          },
          {
            "metric": "alarm-fiveThreshold",
            "value": "0.947368421",
            "exactValue": "",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "alarm-fiveTestCost",
            "value": "0.142857143",
            "exactValue": "",
            "unit": "hypothetical cost units/mass",
            "defined": "1"
          },
          {
            "metric": "testAUC",
            "value": "0.815066038",
            "exactValue": "",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "testAP",
            "value": "0.528392751",
            "exactValue": "",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "testBrier",
            "value": "0.0968492331",
            "exactValue": "",
            "unit": "dimensionless",
            "defined": "1"
          },
          {
            "metric": "eligibleRows",
            "value": "3150",
            "exactValue": "",
            "unit": "rows",
            "defined": "1"
          }
        ],
        "plotPoints": [
          {
            "series": "0",
            "index": "0",
            "xExact": "",
            "x": "1",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:1"
          },
          {
            "series": "1",
            "index": "0",
            "xExact": "",
            "x": "1",
            "yExact": "",
            "y": "0",
            "id": "customer:1"
          },
          {
            "series": "0",
            "index": "1",
            "xExact": "",
            "x": "2",
            "yExact": "",
            "y": "0.197247706",
            "id": "customer:7"
          },
          {
            "series": "1",
            "index": "1",
            "xExact": "",
            "x": "2",
            "yExact": "",
            "y": "0",
            "id": "customer:7"
          },
          {
            "series": "0",
            "index": "2",
            "xExact": "",
            "x": "3",
            "yExact": "",
            "y": "0.197247706",
            "id": "customer:19"
          },
          {
            "series": "1",
            "index": "2",
            "xExact": "",
            "x": "3",
            "yExact": "",
            "y": "1",
            "id": "customer:19"
          },
          {
            "series": "0",
            "index": "3",
            "xExact": "",
            "x": "4",
            "yExact": "",
            "y": "0.0377358491",
            "id": "customer:27"
          },
          {
            "series": "1",
            "index": "3",
            "xExact": "",
            "x": "4",
            "yExact": "",
            "y": "1",
            "id": "customer:27"
          },
          {
            "series": "0",
            "index": "4",
            "xExact": "",
            "x": "5",
            "yExact": "",
            "y": "0.586206897",
            "id": "customer:28"
          },
          {
            "series": "1",
            "index": "4",
            "xExact": "",
            "x": "5",
            "yExact": "",
            "y": "1",
            "id": "customer:28"
          },
          {
            "series": "0",
            "index": "5",
            "xExact": "",
            "x": "6",
            "yExact": "",
            "y": "0.197247706",
            "id": "customer:29"
          },
          {
            "series": "1",
            "index": "5",
            "xExact": "",
            "x": "6",
            "yExact": "",
            "y": "1",
            "id": "customer:29"
          },
          {
            "series": "0",
            "index": "6",
            "xExact": "",
            "x": "7",
            "yExact": "",
            "y": "0.197247706",
            "id": "customer:38"
          },
          {
            "series": "1",
            "index": "6",
            "xExact": "",
            "x": "7",
            "yExact": "",
            "y": "0",
            "id": "customer:38"
          },
          {
            "series": "0",
            "index": "7",
            "xExact": "",
            "x": "8",
            "yExact": "",
            "y": "0.0146341463",
            "id": "customer:44"
          },
          {
            "series": "1",
            "index": "7",
            "xExact": "",
            "x": "8",
            "yExact": "",
            "y": "0",
            "id": "customer:44"
          },
          {
            "series": "0",
            "index": "8",
            "xExact": "",
            "x": "9",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:45"
          },
          {
            "series": "1",
            "index": "8",
            "xExact": "",
            "x": "9",
            "yExact": "",
            "y": "0",
            "id": "customer:45"
          },
          {
            "series": "0",
            "index": "9",
            "xExact": "",
            "x": "10",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:54"
          },
          {
            "series": "1",
            "index": "9",
            "xExact": "",
            "x": "10",
            "yExact": "",
            "y": "0",
            "id": "customer:54"
          },
          {
            "series": "0",
            "index": "10",
            "xExact": "",
            "x": "11",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:60"
          },
          {
            "series": "1",
            "index": "10",
            "xExact": "",
            "x": "11",
            "yExact": "",
            "y": "0",
            "id": "customer:60"
          },
          {
            "series": "0",
            "index": "11",
            "xExact": "",
            "x": "12",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:63"
          },
          {
            "series": "1",
            "index": "11",
            "xExact": "",
            "x": "12",
            "yExact": "",
            "y": "0",
            "id": "customer:63"
          },
          {
            "series": "0",
            "index": "12",
            "xExact": "",
            "x": "13",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:65"
          },
          {
            "series": "1",
            "index": "12",
            "xExact": "",
            "x": "13",
            "yExact": "",
            "y": "0",
            "id": "customer:65"
          },
          {
            "series": "0",
            "index": "13",
            "xExact": "",
            "x": "14",
            "yExact": "",
            "y": "0.197247706",
            "id": "customer:82"
          },
          {
            "series": "1",
            "index": "13",
            "xExact": "",
            "x": "14",
            "yExact": "",
            "y": "1",
            "id": "customer:82"
          },
          {
            "series": "0",
            "index": "14",
            "xExact": "",
            "x": "15",
            "yExact": "",
            "y": "0.197247706",
            "id": "customer:83"
          },
          {
            "series": "1",
            "index": "14",
            "xExact": "",
            "x": "15",
            "yExact": "",
            "y": "0",
            "id": "customer:83"
          },
          {
            "series": "0",
            "index": "15",
            "xExact": "",
            "x": "16",
            "yExact": "",
            "y": "0.0377358491",
            "id": "customer:84"
          },
          {
            "series": "1",
            "index": "15",
            "xExact": "",
            "x": "16",
            "yExact": "",
            "y": "0",
            "id": "customer:84"
          },
          {
            "series": "0",
            "index": "16",
            "xExact": "",
            "x": "17",
            "yExact": "",
            "y": "0.0071942446",
            "id": "customer:86"
          },
          {
            "series": "1",
            "index": "16",
            "xExact": "",
            "x": "17",
            "yExact": "",
            "y": "0",
            "id": "customer:86"
          },
          {
            "series": "0",
            "index": "17",
            "xExact": "",
            "x": "18",
            "yExact": "",
            "y": "0.151785714",
            "id": "customer:88"
          },
          {
            "series": "1",
            "index": "17",
            "xExact": "",
            "x": "18",
            "yExact": "",
            "y": "0",
            "id": "customer:88"
          },
          {
            "series": "0",
            "index": "18",
            "xExact": "",
            "x": "19",
            "yExact": "",
            "y": "0.197247706",
            "id": "customer:102"
          },
          {
            "series": "1",
            "index": "18",
            "xExact": "",
            "x": "19",
            "yExact": "",
            "y": "0",
            "id": "customer:102"
          },
          {
            "series": "0",
            "index": "19",
            "xExact": "",
            "x": "20",
            "yExact": "",
            "y": "0.197247706",
            "id": "customer:105"
          },
          {
            "series": "1",
            "index": "19",
            "xExact": "",
            "x": "20",
            "yExact": "",
            "y": "0",
            "id": "customer:105"
          },
          {
            "series": "0",
            "index": "20",
            "xExact": "",
            "x": "21",
            "yExact": "",
            "y": "0.0071942446",
            "id": "customer:111"
          },
          {
            "series": "1",
            "index": "20",
            "xExact": "",
            "x": "21",
            "yExact": "",
            "y": "0",
            "id": "customer:111"
          },
          {
            "series": "0",
            "index": "21",
            "xExact": "",
            "x": "22",
            "yExact": "",
            "y": "0.0146341463",
            "id": "customer:116"
          },
          {
            "series": "1",
            "index": "21",
            "xExact": "",
            "x": "22",
            "yExact": "",
            "y": "0",
            "id": "customer:116"
          },
          {
            "series": "0",
            "index": "22",
            "xExact": "",
            "x": "23",
            "yExact": "",
            "y": "0.0146341463",
            "id": "customer:121"
          },
          {
            "series": "1",
            "index": "22",
            "xExact": "",
            "x": "23",
            "yExact": "",
            "y": "0",
            "id": "customer:121"
          },
          {
            "series": "0",
            "index": "23",
            "xExact": "",
            "x": "24",
            "yExact": "",
            "y": "0.0377358491",
            "id": "customer:125"
          },
          {
            "series": "1",
            "index": "23",
            "xExact": "",
            "x": "24",
            "yExact": "",
            "y": "1",
            "id": "customer:125"
          },
          {
            "series": "0",
            "index": "24",
            "xExact": "",
            "x": "25",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:126"
          },
          {
            "series": "1",
            "index": "24",
            "xExact": "",
            "x": "25",
            "yExact": "",
            "y": "0",
            "id": "customer:126"
          },
          {
            "series": "0",
            "index": "25",
            "xExact": "",
            "x": "26",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:132"
          },
          {
            "series": "1",
            "index": "25",
            "xExact": "",
            "x": "26",
            "yExact": "",
            "y": "1",
            "id": "customer:132"
          },
          {
            "series": "0",
            "index": "26",
            "xExact": "",
            "x": "27",
            "yExact": "",
            "y": "0.0146341463",
            "id": "customer:135"
          },
          {
            "series": "1",
            "index": "26",
            "xExact": "",
            "x": "27",
            "yExact": "",
            "y": "0",
            "id": "customer:135"
          },
          {
            "series": "0",
            "index": "27",
            "xExact": "",
            "x": "28",
            "yExact": "",
            "y": "0.0377358491",
            "id": "customer:146"
          },
          {
            "series": "1",
            "index": "27",
            "xExact": "",
            "x": "28",
            "yExact": "",
            "y": "0",
            "id": "customer:146"
          },
          {
            "series": "0",
            "index": "28",
            "xExact": "",
            "x": "29",
            "yExact": "",
            "y": "0.0146341463",
            "id": "customer:149"
          },
          {
            "series": "1",
            "index": "28",
            "xExact": "",
            "x": "29",
            "yExact": "",
            "y": "0",
            "id": "customer:149"
          },
          {
            "series": "0",
            "index": "29",
            "xExact": "",
            "x": "30",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:156"
          },
          {
            "series": "1",
            "index": "29",
            "xExact": "",
            "x": "30",
            "yExact": "",
            "y": "0",
            "id": "customer:156"
          },
          {
            "series": "0",
            "index": "30",
            "xExact": "",
            "x": "31",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:163"
          },
          {
            "series": "1",
            "index": "30",
            "xExact": "",
            "x": "31",
            "yExact": "",
            "y": "0",
            "id": "customer:163"
          },
          {
            "series": "0",
            "index": "31",
            "xExact": "",
            "x": "32",
            "yExact": "",
            "y": "0.197247706",
            "id": "customer:168"
          },
          {
            "series": "1",
            "index": "31",
            "xExact": "",
            "x": "32",
            "yExact": "",
            "y": "0",
            "id": "customer:168"
          },
          {
            "series": "0",
            "index": "32",
            "xExact": "",
            "x": "33",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:171"
          },
          {
            "series": "1",
            "index": "32",
            "xExact": "",
            "x": "33",
            "yExact": "",
            "y": "0",
            "id": "customer:171"
          },
          {
            "series": "0",
            "index": "33",
            "xExact": "",
            "x": "34",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:172"
          },
          {
            "series": "1",
            "index": "33",
            "xExact": "",
            "x": "34",
            "yExact": "",
            "y": "0",
            "id": "customer:172"
          },
          {
            "series": "0",
            "index": "34",
            "xExact": "",
            "x": "35",
            "yExact": "",
            "y": "0.586206897",
            "id": "customer:174"
          },
          {
            "series": "1",
            "index": "34",
            "xExact": "",
            "x": "35",
            "yExact": "",
            "y": "0",
            "id": "customer:174"
          },
          {
            "series": "0",
            "index": "35",
            "xExact": "",
            "x": "36",
            "yExact": "",
            "y": "0.586206897",
            "id": "customer:178"
          },
          {
            "series": "1",
            "index": "35",
            "xExact": "",
            "x": "36",
            "yExact": "",
            "y": "1",
            "id": "customer:178"
          },
          {
            "series": "0",
            "index": "36",
            "xExact": "",
            "x": "37",
            "yExact": "",
            "y": "0.197247706",
            "id": "customer:179"
          },
          {
            "series": "1",
            "index": "36",
            "xExact": "",
            "x": "37",
            "yExact": "",
            "y": "1",
            "id": "customer:179"
          },
          {
            "series": "0",
            "index": "37",
            "xExact": "",
            "x": "38",
            "yExact": "",
            "y": "0.857142857",
            "id": "customer:182"
          },
          {
            "series": "1",
            "index": "37",
            "xExact": "",
            "x": "38",
            "yExact": "",
            "y": "1",
            "id": "customer:182"
          },
          {
            "series": "0",
            "index": "38",
            "xExact": "",
            "x": "39",
            "yExact": "",
            "y": "0.197247706",
            "id": "customer:183"
          },
          {
            "series": "1",
            "index": "38",
            "xExact": "",
            "x": "39",
            "yExact": "",
            "y": "0",
            "id": "customer:183"
          },
          {
            "series": "0",
            "index": "39",
            "xExact": "",
            "x": "40",
            "yExact": "",
            "y": "0.586206897",
            "id": "customer:185"
          },
          {
            "series": "1",
            "index": "39",
            "xExact": "",
            "x": "40",
            "yExact": "",
            "y": "0",
            "id": "customer:185"
          },
          {
            "series": "0",
            "index": "40",
            "xExact": "",
            "x": "41",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:189"
          },
          {
            "series": "1",
            "index": "40",
            "xExact": "",
            "x": "41",
            "yExact": "",
            "y": "0",
            "id": "customer:189"
          },
          {
            "series": "0",
            "index": "41",
            "xExact": "",
            "x": "42",
            "yExact": "",
            "y": "0.0377358491",
            "id": "customer:197"
          },
          {
            "series": "1",
            "index": "41",
            "xExact": "",
            "x": "42",
            "yExact": "",
            "y": "0",
            "id": "customer:197"
          },
          {
            "series": "0",
            "index": "42",
            "xExact": "",
            "x": "43",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:202"
          },
          {
            "series": "1",
            "index": "42",
            "xExact": "",
            "x": "43",
            "yExact": "",
            "y": "0",
            "id": "customer:202"
          },
          {
            "series": "0",
            "index": "43",
            "xExact": "",
            "x": "44",
            "yExact": "",
            "y": "0.0377358491",
            "id": "customer:204"
          },
          {
            "series": "1",
            "index": "43",
            "xExact": "",
            "x": "44",
            "yExact": "",
            "y": "0",
            "id": "customer:204"
          },
          {
            "series": "0",
            "index": "44",
            "xExact": "",
            "x": "45",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:205"
          },
          {
            "series": "1",
            "index": "44",
            "xExact": "",
            "x": "45",
            "yExact": "",
            "y": "0",
            "id": "customer:205"
          },
          {
            "series": "0",
            "index": "45",
            "xExact": "",
            "x": "46",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:207"
          },
          {
            "series": "1",
            "index": "45",
            "xExact": "",
            "x": "46",
            "yExact": "",
            "y": "0",
            "id": "customer:207"
          },
          {
            "series": "0",
            "index": "46",
            "xExact": "",
            "x": "47",
            "yExact": "",
            "y": "0.0377358491",
            "id": "customer:208"
          },
          {
            "series": "1",
            "index": "46",
            "xExact": "",
            "x": "47",
            "yExact": "",
            "y": "0",
            "id": "customer:208"
          },
          {
            "series": "0",
            "index": "47",
            "xExact": "",
            "x": "48",
            "yExact": "",
            "y": "0.0146341463",
            "id": "customer:209"
          },
          {
            "series": "1",
            "index": "47",
            "xExact": "",
            "x": "48",
            "yExact": "",
            "y": "0",
            "id": "customer:209"
          },
          {
            "series": "0",
            "index": "48",
            "xExact": "",
            "x": "49",
            "yExact": "",
            "y": "0.0146341463",
            "id": "customer:211"
          },
          {
            "series": "1",
            "index": "48",
            "xExact": "",
            "x": "49",
            "yExact": "",
            "y": "0",
            "id": "customer:211"
          },
          {
            "series": "0",
            "index": "49",
            "xExact": "",
            "x": "50",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:217"
          },
          {
            "series": "1",
            "index": "49",
            "xExact": "",
            "x": "50",
            "yExact": "",
            "y": "0",
            "id": "customer:217"
          },
          {
            "series": "0",
            "index": "50",
            "xExact": "",
            "x": "51",
            "yExact": "",
            "y": "0.666666667",
            "id": "customer:225"
          },
          {
            "series": "1",
            "index": "50",
            "xExact": "",
            "x": "51",
            "yExact": "",
            "y": "1",
            "id": "customer:225"
          },
          {
            "series": "0",
            "index": "51",
            "xExact": "",
            "x": "52",
            "yExact": "",
            "y": "0.173913043",
            "id": "customer:228"
          },
          {
            "series": "1",
            "index": "51",
            "xExact": "",
            "x": "52",
            "yExact": "",
            "y": "1",
            "id": "customer:228"
          },
          {
            "series": "0",
            "index": "52",
            "xExact": "",
            "x": "53",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:238"
          },
          {
            "series": "1",
            "index": "52",
            "xExact": "",
            "x": "53",
            "yExact": "",
            "y": "0",
            "id": "customer:238"
          },
          {
            "series": "0",
            "index": "53",
            "xExact": "",
            "x": "54",
            "yExact": "",
            "y": "0.0377358491",
            "id": "customer:246"
          },
          {
            "series": "1",
            "index": "53",
            "xExact": "",
            "x": "54",
            "yExact": "",
            "y": "0",
            "id": "customer:246"
          },
          {
            "series": "0",
            "index": "54",
            "xExact": "",
            "x": "55",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:263"
          },
          {
            "series": "1",
            "index": "54",
            "xExact": "",
            "x": "55",
            "yExact": "",
            "y": "0",
            "id": "customer:263"
          },
          {
            "series": "0",
            "index": "55",
            "xExact": "",
            "x": "56",
            "yExact": "",
            "y": "0.197247706",
            "id": "customer:267"
          },
          {
            "series": "1",
            "index": "55",
            "xExact": "",
            "x": "56",
            "yExact": "",
            "y": "0",
            "id": "customer:267"
          },
          {
            "series": "0",
            "index": "56",
            "xExact": "",
            "x": "57",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:270"
          },
          {
            "series": "1",
            "index": "56",
            "xExact": "",
            "x": "57",
            "yExact": "",
            "y": "0",
            "id": "customer:270"
          },
          {
            "series": "0",
            "index": "57",
            "xExact": "",
            "x": "58",
            "yExact": "",
            "y": "0.586206897",
            "id": "customer:278"
          },
          {
            "series": "1",
            "index": "57",
            "xExact": "",
            "x": "58",
            "yExact": "",
            "y": "1",
            "id": "customer:278"
          },
          {
            "series": "0",
            "index": "58",
            "xExact": "",
            "x": "59",
            "yExact": "",
            "y": "0.197247706",
            "id": "customer:282"
          },
          {
            "series": "1",
            "index": "58",
            "xExact": "",
            "x": "59",
            "yExact": "",
            "y": "1",
            "id": "customer:282"
          },
          {
            "series": "0",
            "index": "59",
            "xExact": "",
            "x": "60",
            "yExact": "",
            "y": "0.197247706",
            "id": "customer:283"
          },
          {
            "series": "1",
            "index": "59",
            "xExact": "",
            "x": "60",
            "yExact": "",
            "y": "0",
            "id": "customer:283"
          },
          {
            "series": "0",
            "index": "60",
            "xExact": "",
            "x": "61",
            "yExact": "",
            "y": "0.173913043",
            "id": "customer:290"
          },
          {
            "series": "1",
            "index": "60",
            "xExact": "",
            "x": "61",
            "yExact": "",
            "y": "0",
            "id": "customer:290"
          },
          {
            "series": "0",
            "index": "61",
            "xExact": "",
            "x": "62",
            "yExact": "",
            "y": "0.0377358491",
            "id": "customer:294"
          },
          {
            "series": "1",
            "index": "61",
            "xExact": "",
            "x": "62",
            "yExact": "",
            "y": "0",
            "id": "customer:294"
          },
          {
            "series": "0",
            "index": "62",
            "xExact": "",
            "x": "63",
            "yExact": "",
            "y": "0.173913043",
            "id": "customer:295"
          },
          {
            "series": "1",
            "index": "62",
            "xExact": "",
            "x": "63",
            "yExact": "",
            "y": "0",
            "id": "customer:295"
          },
          {
            "series": "0",
            "index": "63",
            "xExact": "",
            "x": "64",
            "yExact": "",
            "y": "0.0377358491",
            "id": "customer:298"
          },
          {
            "series": "1",
            "index": "63",
            "xExact": "",
            "x": "64",
            "yExact": "",
            "y": "0",
            "id": "customer:298"
          },
          {
            "series": "0",
            "index": "64",
            "xExact": "",
            "x": "65",
            "yExact": "",
            "y": "0.0146341463",
            "id": "customer:301"
          },
          {
            "series": "1",
            "index": "64",
            "xExact": "",
            "x": "65",
            "yExact": "",
            "y": "0",
            "id": "customer:301"
          },
          {
            "series": "0",
            "index": "65",
            "xExact": "",
            "x": "66",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:305"
          },
          {
            "series": "1",
            "index": "65",
            "xExact": "",
            "x": "66",
            "yExact": "",
            "y": "0",
            "id": "customer:305"
          },
          {
            "series": "0",
            "index": "66",
            "xExact": "",
            "x": "67",
            "yExact": "",
            "y": "0.0146341463",
            "id": "customer:316"
          },
          {
            "series": "1",
            "index": "66",
            "xExact": "",
            "x": "67",
            "yExact": "",
            "y": "0",
            "id": "customer:316"
          },
          {
            "series": "0",
            "index": "67",
            "xExact": "",
            "x": "68",
            "yExact": "",
            "y": "0.0377358491",
            "id": "customer:324"
          },
          {
            "series": "1",
            "index": "67",
            "xExact": "",
            "x": "68",
            "yExact": "",
            "y": "0",
            "id": "customer:324"
          },
          {
            "series": "0",
            "index": "68",
            "xExact": "",
            "x": "69",
            "yExact": "",
            "y": "0.0377358491",
            "id": "customer:334"
          },
          {
            "series": "1",
            "index": "68",
            "xExact": "",
            "x": "69",
            "yExact": "",
            "y": "0",
            "id": "customer:334"
          },
          {
            "series": "0",
            "index": "69",
            "xExact": "",
            "x": "70",
            "yExact": "",
            "y": "0.0146341463",
            "id": "customer:335"
          },
          {
            "series": "1",
            "index": "69",
            "xExact": "",
            "x": "70",
            "yExact": "",
            "y": "0",
            "id": "customer:335"
          },
          {
            "series": "0",
            "index": "70",
            "xExact": "",
            "x": "71",
            "yExact": "",
            "y": "0.0377358491",
            "id": "customer:346"
          },
          {
            "series": "1",
            "index": "70",
            "xExact": "",
            "x": "71",
            "yExact": "",
            "y": "0",
            "id": "customer:346"
          },
          {
            "series": "0",
            "index": "71",
            "xExact": "",
            "x": "72",
            "yExact": "",
            "y": "0.197247706",
            "id": "customer:355"
          },
          {
            "series": "1",
            "index": "71",
            "xExact": "",
            "x": "72",
            "yExact": "",
            "y": "0",
            "id": "customer:355"
          },
          {
            "series": "0",
            "index": "72",
            "xExact": "",
            "x": "73",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:356"
          },
          {
            "series": "1",
            "index": "72",
            "xExact": "",
            "x": "73",
            "yExact": "",
            "y": "0",
            "id": "customer:356"
          },
          {
            "series": "0",
            "index": "73",
            "xExact": "",
            "x": "74",
            "yExact": "",
            "y": "0.197247706",
            "id": "customer:367"
          },
          {
            "series": "1",
            "index": "73",
            "xExact": "",
            "x": "74",
            "yExact": "",
            "y": "0",
            "id": "customer:367"
          },
          {
            "series": "0",
            "index": "74",
            "xExact": "",
            "x": "75",
            "yExact": "",
            "y": "0.197247706",
            "id": "customer:369"
          },
          {
            "series": "1",
            "index": "74",
            "xExact": "",
            "x": "75",
            "yExact": "",
            "y": "1",
            "id": "customer:369"
          },
          {
            "series": "0",
            "index": "75",
            "xExact": "",
            "x": "76",
            "yExact": "",
            "y": "0.0071942446",
            "id": "customer:370"
          },
          {
            "series": "1",
            "index": "75",
            "xExact": "",
            "x": "76",
            "yExact": "",
            "y": "0",
            "id": "customer:370"
          },
          {
            "series": "0",
            "index": "76",
            "xExact": "",
            "x": "77",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:371"
          },
          {
            "series": "1",
            "index": "76",
            "xExact": "",
            "x": "77",
            "yExact": "",
            "y": "0",
            "id": "customer:371"
          },
          {
            "series": "0",
            "index": "77",
            "xExact": "",
            "x": "78",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:375"
          },
          {
            "series": "1",
            "index": "77",
            "xExact": "",
            "x": "78",
            "yExact": "",
            "y": "0",
            "id": "customer:375"
          },
          {
            "series": "0",
            "index": "78",
            "xExact": "",
            "x": "79",
            "yExact": "",
            "y": "0.586206897",
            "id": "customer:377"
          },
          {
            "series": "1",
            "index": "78",
            "xExact": "",
            "x": "79",
            "yExact": "",
            "y": "1",
            "id": "customer:377"
          },
          {
            "series": "0",
            "index": "79",
            "xExact": "",
            "x": "80",
            "yExact": "",
            "y": "0.197247706",
            "id": "customer:387"
          },
          {
            "series": "1",
            "index": "79",
            "xExact": "",
            "x": "80",
            "yExact": "",
            "y": "0",
            "id": "customer:387"
          },
          {
            "series": "0",
            "index": "80",
            "xExact": "",
            "x": "81",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:388"
          },
          {
            "series": "1",
            "index": "80",
            "xExact": "",
            "x": "81",
            "yExact": "",
            "y": "0",
            "id": "customer:388"
          },
          {
            "series": "0",
            "index": "81",
            "xExact": "",
            "x": "82",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:390"
          },
          {
            "series": "1",
            "index": "81",
            "xExact": "",
            "x": "82",
            "yExact": "",
            "y": "0",
            "id": "customer:390"
          },
          {
            "series": "0",
            "index": "82",
            "xExact": "",
            "x": "83",
            "yExact": "",
            "y": "0.0377358491",
            "id": "customer:396"
          },
          {
            "series": "1",
            "index": "82",
            "xExact": "",
            "x": "83",
            "yExact": "",
            "y": "0",
            "id": "customer:396"
          },
          {
            "series": "0",
            "index": "83",
            "xExact": "",
            "x": "84",
            "yExact": "",
            "y": "0.0146341463",
            "id": "customer:401"
          },
          {
            "series": "1",
            "index": "83",
            "xExact": "",
            "x": "84",
            "yExact": "",
            "y": "0",
            "id": "customer:401"
          },
          {
            "series": "0",
            "index": "84",
            "xExact": "",
            "x": "85",
            "yExact": "",
            "y": "0.0377358491",
            "id": "customer:404"
          },
          {
            "series": "1",
            "index": "84",
            "xExact": "",
            "x": "85",
            "yExact": "",
            "y": "0",
            "id": "customer:404"
          },
          {
            "series": "0",
            "index": "85",
            "xExact": "",
            "x": "86",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:405"
          },
          {
            "series": "1",
            "index": "85",
            "xExact": "",
            "x": "86",
            "yExact": "",
            "y": "0",
            "id": "customer:405"
          },
          {
            "series": "0",
            "index": "86",
            "xExact": "",
            "x": "87",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:407"
          },
          {
            "series": "1",
            "index": "86",
            "xExact": "",
            "x": "87",
            "yExact": "",
            "y": "0",
            "id": "customer:407"
          },
          {
            "series": "0",
            "index": "87",
            "xExact": "",
            "x": "88",
            "yExact": "",
            "y": "0.0146341463",
            "id": "customer:410"
          },
          {
            "series": "1",
            "index": "87",
            "xExact": "",
            "x": "88",
            "yExact": "",
            "y": "0",
            "id": "customer:410"
          },
          {
            "series": "0",
            "index": "88",
            "xExact": "",
            "x": "89",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:417"
          },
          {
            "series": "1",
            "index": "88",
            "xExact": "",
            "x": "89",
            "yExact": "",
            "y": "0",
            "id": "customer:417"
          },
          {
            "series": "0",
            "index": "89",
            "xExact": "",
            "x": "90",
            "yExact": "",
            "y": "0.0377358491",
            "id": "customer:424"
          },
          {
            "series": "1",
            "index": "89",
            "xExact": "",
            "x": "90",
            "yExact": "",
            "y": "0",
            "id": "customer:424"
          },
          {
            "series": "0",
            "index": "90",
            "xExact": "",
            "x": "91",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:426"
          },
          {
            "series": "1",
            "index": "90",
            "xExact": "",
            "x": "91",
            "yExact": "",
            "y": "0",
            "id": "customer:426"
          },
          {
            "series": "0",
            "index": "91",
            "xExact": "",
            "x": "92",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:432"
          },
          {
            "series": "1",
            "index": "91",
            "xExact": "",
            "x": "92",
            "yExact": "",
            "y": "1",
            "id": "customer:432"
          },
          {
            "series": "0",
            "index": "92",
            "xExact": "",
            "x": "93",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:451"
          },
          {
            "series": "1",
            "index": "92",
            "xExact": "",
            "x": "93",
            "yExact": "",
            "y": "0",
            "id": "customer:451"
          },
          {
            "series": "0",
            "index": "93",
            "xExact": "",
            "x": "94",
            "yExact": "",
            "y": "0.197247706",
            "id": "customer:452"
          },
          {
            "series": "1",
            "index": "93",
            "xExact": "",
            "x": "94",
            "yExact": "",
            "y": "0",
            "id": "customer:452"
          },
          {
            "series": "0",
            "index": "94",
            "xExact": "",
            "x": "95",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:453"
          },
          {
            "series": "1",
            "index": "94",
            "xExact": "",
            "x": "95",
            "yExact": "",
            "y": "0",
            "id": "customer:453"
          },
          {
            "series": "0",
            "index": "95",
            "xExact": "",
            "x": "96",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:455"
          },
          {
            "series": "1",
            "index": "95",
            "xExact": "",
            "x": "96",
            "yExact": "",
            "y": "0",
            "id": "customer:455"
          },
          {
            "series": "0",
            "index": "96",
            "xExact": "",
            "x": "97",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:463"
          },
          {
            "series": "1",
            "index": "96",
            "xExact": "",
            "x": "97",
            "yExact": "",
            "y": "0",
            "id": "customer:463"
          },
          {
            "series": "0",
            "index": "97",
            "xExact": "",
            "x": "98",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:464"
          },
          {
            "series": "1",
            "index": "97",
            "xExact": "",
            "x": "98",
            "yExact": "",
            "y": "0",
            "id": "customer:464"
          },
          {
            "series": "0",
            "index": "98",
            "xExact": "",
            "x": "99",
            "yExact": "",
            "y": "0.197247706",
            "id": "customer:467"
          },
          {
            "series": "1",
            "index": "98",
            "xExact": "",
            "x": "99",
            "yExact": "",
            "y": "0",
            "id": "customer:467"
          },
          {
            "series": "0",
            "index": "99",
            "xExact": "",
            "x": "100",
            "yExact": "",
            "y": "0.197247706",
            "id": "customer:469"
          },
          {
            "series": "1",
            "index": "99",
            "xExact": "",
            "x": "100",
            "yExact": "",
            "y": "1",
            "id": "customer:469"
          },
          {
            "series": "0",
            "index": "100",
            "xExact": "",
            "x": "101",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:471"
          },
          {
            "series": "1",
            "index": "100",
            "xExact": "",
            "x": "101",
            "yExact": "",
            "y": "0",
            "id": "customer:471"
          },
          {
            "series": "0",
            "index": "101",
            "xExact": "",
            "x": "102",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:472"
          },
          {
            "series": "1",
            "index": "101",
            "xExact": "",
            "x": "102",
            "yExact": "",
            "y": "0",
            "id": "customer:472"
          },
          {
            "series": "0",
            "index": "102",
            "xExact": "",
            "x": "103",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:474"
          },
          {
            "series": "1",
            "index": "102",
            "xExact": "",
            "x": "103",
            "yExact": "",
            "y": "0",
            "id": "customer:474"
          },
          {
            "series": "0",
            "index": "103",
            "xExact": "",
            "x": "104",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:475"
          },
          {
            "series": "1",
            "index": "103",
            "xExact": "",
            "x": "104",
            "yExact": "",
            "y": "0",
            "id": "customer:475"
          },
          {
            "series": "0",
            "index": "104",
            "xExact": "",
            "x": "105",
            "yExact": "",
            "y": "0.0146341463",
            "id": "customer:476"
          },
          {
            "series": "1",
            "index": "104",
            "xExact": "",
            "x": "105",
            "yExact": "",
            "y": "0",
            "id": "customer:476"
          },
          {
            "series": "0",
            "index": "105",
            "xExact": "",
            "x": "106",
            "yExact": "",
            "y": "0.0071942446",
            "id": "customer:486"
          },
          {
            "series": "1",
            "index": "105",
            "xExact": "",
            "x": "106",
            "yExact": "",
            "y": "0",
            "id": "customer:486"
          },
          {
            "series": "0",
            "index": "106",
            "xExact": "",
            "x": "107",
            "yExact": "",
            "y": "0.173913043",
            "id": "customer:493"
          },
          {
            "series": "1",
            "index": "106",
            "xExact": "",
            "x": "107",
            "yExact": "",
            "y": "0",
            "id": "customer:493"
          },
          {
            "series": "0",
            "index": "107",
            "xExact": "",
            "x": "108",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:495"
          },
          {
            "series": "1",
            "index": "107",
            "xExact": "",
            "x": "108",
            "yExact": "",
            "y": "0",
            "id": "customer:495"
          },
          {
            "series": "0",
            "index": "108",
            "xExact": "",
            "x": "109",
            "yExact": "",
            "y": "0.197247706",
            "id": "customer:503"
          },
          {
            "series": "1",
            "index": "108",
            "xExact": "",
            "x": "109",
            "yExact": "",
            "y": "0",
            "id": "customer:503"
          },
          {
            "series": "0",
            "index": "109",
            "xExact": "",
            "x": "110",
            "yExact": "",
            "y": "0.0071942446",
            "id": "customer:504"
          },
          {
            "series": "1",
            "index": "109",
            "xExact": "",
            "x": "110",
            "yExact": "",
            "y": "0",
            "id": "customer:504"
          },
          {
            "series": "0",
            "index": "110",
            "xExact": "",
            "x": "111",
            "yExact": "",
            "y": "0.0071942446",
            "id": "customer:511"
          },
          {
            "series": "1",
            "index": "110",
            "xExact": "",
            "x": "111",
            "yExact": "",
            "y": "0",
            "id": "customer:511"
          },
          {
            "series": "0",
            "index": "111",
            "xExact": "",
            "x": "112",
            "yExact": "",
            "y": "0.197247706",
            "id": "customer:512"
          },
          {
            "series": "1",
            "index": "111",
            "xExact": "",
            "x": "112",
            "yExact": "",
            "y": "0",
            "id": "customer:512"
          },
          {
            "series": "0",
            "index": "112",
            "xExact": "",
            "x": "113",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:526"
          },
          {
            "series": "1",
            "index": "112",
            "xExact": "",
            "x": "113",
            "yExact": "",
            "y": "0",
            "id": "customer:526"
          },
          {
            "series": "0",
            "index": "113",
            "xExact": "",
            "x": "114",
            "yExact": "",
            "y": "0.197247706",
            "id": "customer:533"
          },
          {
            "series": "1",
            "index": "113",
            "xExact": "",
            "x": "114",
            "yExact": "",
            "y": "0",
            "id": "customer:533"
          },
          {
            "series": "0",
            "index": "114",
            "xExact": "",
            "x": "115",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:548"
          },
          {
            "series": "1",
            "index": "114",
            "xExact": "",
            "x": "115",
            "yExact": "",
            "y": "0",
            "id": "customer:548"
          },
          {
            "series": "0",
            "index": "115",
            "xExact": "",
            "x": "116",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:551"
          },
          {
            "series": "1",
            "index": "115",
            "xExact": "",
            "x": "116",
            "yExact": "",
            "y": "0",
            "id": "customer:551"
          },
          {
            "series": "0",
            "index": "116",
            "xExact": "",
            "x": "117",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:559"
          },
          {
            "series": "1",
            "index": "116",
            "xExact": "",
            "x": "117",
            "yExact": "",
            "y": "0",
            "id": "customer:559"
          },
          {
            "series": "0",
            "index": "117",
            "xExact": "",
            "x": "118",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:560"
          },
          {
            "series": "1",
            "index": "117",
            "xExact": "",
            "x": "118",
            "yExact": "",
            "y": "0",
            "id": "customer:560"
          },
          {
            "series": "0",
            "index": "118",
            "xExact": "",
            "x": "119",
            "yExact": "",
            "y": "0.0071942446",
            "id": "customer:561"
          },
          {
            "series": "1",
            "index": "118",
            "xExact": "",
            "x": "119",
            "yExact": "",
            "y": "0",
            "id": "customer:561"
          },
          {
            "series": "0",
            "index": "119",
            "xExact": "",
            "x": "120",
            "yExact": "",
            "y": "0.197247706",
            "id": "customer:567"
          },
          {
            "series": "1",
            "index": "119",
            "xExact": "",
            "x": "120",
            "yExact": "",
            "y": "0",
            "id": "customer:567"
          },
          {
            "series": "0",
            "index": "120",
            "xExact": "",
            "x": "121",
            "yExact": "",
            "y": "0.197247706",
            "id": "customer:569"
          },
          {
            "series": "1",
            "index": "120",
            "xExact": "",
            "x": "121",
            "yExact": "",
            "y": "1",
            "id": "customer:569"
          },
          {
            "series": "0",
            "index": "121",
            "xExact": "",
            "x": "122",
            "yExact": "",
            "y": "0.0071942446",
            "id": "customer:570"
          },
          {
            "series": "1",
            "index": "121",
            "xExact": "",
            "x": "122",
            "yExact": "",
            "y": "0",
            "id": "customer:570"
          },
          {
            "series": "0",
            "index": "122",
            "xExact": "",
            "x": "123",
            "yExact": "",
            "y": "0.0146341463",
            "id": "customer:576"
          },
          {
            "series": "1",
            "index": "122",
            "xExact": "",
            "x": "123",
            "yExact": "",
            "y": "0",
            "id": "customer:576"
          },
          {
            "series": "0",
            "index": "123",
            "xExact": "",
            "x": "124",
            "yExact": "",
            "y": "0.197247706",
            "id": "customer:580"
          },
          {
            "series": "1",
            "index": "123",
            "xExact": "",
            "x": "124",
            "yExact": "",
            "y": "0",
            "id": "customer:580"
          },
          {
            "series": "0",
            "index": "124",
            "xExact": "",
            "x": "125",
            "yExact": "",
            "y": "0.197247706",
            "id": "customer:583"
          },
          {
            "series": "1",
            "index": "124",
            "xExact": "",
            "x": "125",
            "yExact": "",
            "y": "0",
            "id": "customer:583"
          },
          {
            "series": "0",
            "index": "125",
            "xExact": "",
            "x": "126",
            "yExact": "",
            "y": "0.197247706",
            "id": "customer:587"
          },
          {
            "series": "1",
            "index": "125",
            "xExact": "",
            "x": "126",
            "yExact": "",
            "y": "0",
            "id": "customer:587"
          },
          {
            "series": "0",
            "index": "126",
            "xExact": "",
            "x": "127",
            "yExact": "",
            "y": "0.173913043",
            "id": "customer:593"
          },
          {
            "series": "1",
            "index": "126",
            "xExact": "",
            "x": "127",
            "yExact": "",
            "y": "0",
            "id": "customer:593"
          },
          {
            "series": "0",
            "index": "127",
            "xExact": "",
            "x": "128",
            "yExact": "",
            "y": "0.151785714",
            "id": "customer:603"
          },
          {
            "series": "1",
            "index": "127",
            "xExact": "",
            "x": "128",
            "yExact": "",
            "y": "0",
            "id": "customer:603"
          },
          {
            "series": "0",
            "index": "128",
            "xExact": "",
            "x": "129",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:606"
          },
          {
            "series": "1",
            "index": "128",
            "xExact": "",
            "x": "129",
            "yExact": "",
            "y": "0",
            "id": "customer:606"
          },
          {
            "series": "0",
            "index": "129",
            "xExact": "",
            "x": "130",
            "yExact": "",
            "y": "0.197247706",
            "id": "customer:607"
          },
          {
            "series": "1",
            "index": "129",
            "xExact": "",
            "x": "130",
            "yExact": "",
            "y": "0",
            "id": "customer:607"
          },
          {
            "series": "0",
            "index": "130",
            "xExact": "",
            "x": "131",
            "yExact": "",
            "y": "0.0071942446",
            "id": "customer:616"
          },
          {
            "series": "1",
            "index": "130",
            "xExact": "",
            "x": "131",
            "yExact": "",
            "y": "0",
            "id": "customer:616"
          },
          {
            "series": "0",
            "index": "131",
            "xExact": "",
            "x": "132",
            "yExact": "",
            "y": "0.0071942446",
            "id": "customer:620"
          },
          {
            "series": "1",
            "index": "131",
            "xExact": "",
            "x": "132",
            "yExact": "",
            "y": "0",
            "id": "customer:620"
          },
          {
            "series": "0",
            "index": "132",
            "xExact": "",
            "x": "133",
            "yExact": "",
            "y": "0.666666667",
            "id": "customer:625"
          },
          {
            "series": "1",
            "index": "132",
            "xExact": "",
            "x": "133",
            "yExact": "",
            "y": "1",
            "id": "customer:625"
          },
          {
            "series": "0",
            "index": "133",
            "xExact": "",
            "x": "134",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:626"
          },
          {
            "series": "1",
            "index": "133",
            "xExact": "",
            "x": "134",
            "yExact": "",
            "y": "0",
            "id": "customer:626"
          },
          {
            "series": "0",
            "index": "134",
            "xExact": "",
            "x": "135",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:630"
          },
          {
            "series": "1",
            "index": "134",
            "xExact": "",
            "x": "135",
            "yExact": "",
            "y": "0",
            "id": "customer:630"
          },
          {
            "series": "0",
            "index": "135",
            "xExact": "",
            "x": "136",
            "yExact": "",
            "y": "0.0377358491",
            "id": "customer:634"
          },
          {
            "series": "1",
            "index": "135",
            "xExact": "",
            "x": "136",
            "yExact": "",
            "y": "0",
            "id": "customer:634"
          },
          {
            "series": "0",
            "index": "136",
            "xExact": "",
            "x": "137",
            "yExact": "",
            "y": "0.0146341463",
            "id": "customer:636"
          },
          {
            "series": "1",
            "index": "136",
            "xExact": "",
            "x": "137",
            "yExact": "",
            "y": "0",
            "id": "customer:636"
          },
          {
            "series": "0",
            "index": "137",
            "xExact": "",
            "x": "138",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:637"
          },
          {
            "series": "1",
            "index": "137",
            "xExact": "",
            "x": "138",
            "yExact": "",
            "y": "0",
            "id": "customer:637"
          },
          {
            "series": "0",
            "index": "138",
            "xExact": "",
            "x": "139",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:640"
          },
          {
            "series": "1",
            "index": "138",
            "xExact": "",
            "x": "139",
            "yExact": "",
            "y": "0",
            "id": "customer:640"
          },
          {
            "series": "0",
            "index": "139",
            "xExact": "",
            "x": "140",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:642"
          },
          {
            "series": "1",
            "index": "139",
            "xExact": "",
            "x": "140",
            "yExact": "",
            "y": "0",
            "id": "customer:642"
          },
          {
            "series": "0",
            "index": "140",
            "xExact": "",
            "x": "141",
            "yExact": "",
            "y": "0.0377358491",
            "id": "customer:647"
          },
          {
            "series": "1",
            "index": "140",
            "xExact": "",
            "x": "141",
            "yExact": "",
            "y": "0",
            "id": "customer:647"
          },
          {
            "series": "0",
            "index": "141",
            "xExact": "",
            "x": "142",
            "yExact": "",
            "y": "0.197247706",
            "id": "customer:655"
          },
          {
            "series": "1",
            "index": "141",
            "xExact": "",
            "x": "142",
            "yExact": "",
            "y": "0",
            "id": "customer:655"
          },
          {
            "series": "0",
            "index": "142",
            "xExact": "",
            "x": "143",
            "yExact": "",
            "y": "0.197247706",
            "id": "customer:669"
          },
          {
            "series": "1",
            "index": "142",
            "xExact": "",
            "x": "143",
            "yExact": "",
            "y": "1",
            "id": "customer:669"
          },
          {
            "series": "0",
            "index": "143",
            "xExact": "",
            "x": "144",
            "yExact": "",
            "y": "0.0071942446",
            "id": "customer:670"
          },
          {
            "series": "1",
            "index": "143",
            "xExact": "",
            "x": "144",
            "yExact": "",
            "y": "0",
            "id": "customer:670"
          },
          {
            "series": "0",
            "index": "144",
            "xExact": "",
            "x": "145",
            "yExact": "",
            "y": "0.947368421",
            "id": "customer:673"
          },
          {
            "series": "1",
            "index": "144",
            "xExact": "",
            "x": "145",
            "yExact": "",
            "y": "1",
            "id": "customer:673"
          },
          {
            "series": "0",
            "index": "145",
            "xExact": "",
            "x": "146",
            "yExact": "",
            "y": "0.173913043",
            "id": "customer:691"
          },
          {
            "series": "1",
            "index": "145",
            "xExact": "",
            "x": "146",
            "yExact": "",
            "y": "0",
            "id": "customer:691"
          },
          {
            "series": "0",
            "index": "146",
            "xExact": "",
            "x": "147",
            "yExact": "",
            "y": "0.151785714",
            "id": "customer:703"
          },
          {
            "series": "1",
            "index": "146",
            "xExact": "",
            "x": "147",
            "yExact": "",
            "y": "0",
            "id": "customer:703"
          },
          {
            "series": "0",
            "index": "147",
            "xExact": "",
            "x": "148",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:715"
          },
          {
            "series": "1",
            "index": "147",
            "xExact": "",
            "x": "148",
            "yExact": "",
            "y": "0",
            "id": "customer:715"
          },
          {
            "series": "0",
            "index": "148",
            "xExact": "",
            "x": "149",
            "yExact": "",
            "y": "0.197247706",
            "id": "customer:719"
          },
          {
            "series": "1",
            "index": "148",
            "xExact": "",
            "x": "149",
            "yExact": "",
            "y": "1",
            "id": "customer:719"
          },
          {
            "series": "0",
            "index": "149",
            "xExact": "",
            "x": "150",
            "yExact": "",
            "y": "0.0071942446",
            "id": "customer:721"
          },
          {
            "series": "1",
            "index": "149",
            "xExact": "",
            "x": "150",
            "yExact": "",
            "y": "0",
            "id": "customer:721"
          },
          {
            "series": "0",
            "index": "150",
            "xExact": "",
            "x": "151",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:725"
          },
          {
            "series": "1",
            "index": "150",
            "xExact": "",
            "x": "151",
            "yExact": "",
            "y": "1",
            "id": "customer:725"
          },
          {
            "series": "0",
            "index": "151",
            "xExact": "",
            "x": "152",
            "yExact": "",
            "y": "0.0146341463",
            "id": "customer:731"
          },
          {
            "series": "1",
            "index": "151",
            "xExact": "",
            "x": "152",
            "yExact": "",
            "y": "0",
            "id": "customer:731"
          },
          {
            "series": "0",
            "index": "152",
            "xExact": "",
            "x": "153",
            "yExact": "",
            "y": "0.0146341463",
            "id": "customer:735"
          },
          {
            "series": "1",
            "index": "152",
            "xExact": "",
            "x": "153",
            "yExact": "",
            "y": "0",
            "id": "customer:735"
          },
          {
            "series": "0",
            "index": "153",
            "xExact": "",
            "x": "154",
            "yExact": "",
            "y": "0.0146341463",
            "id": "customer:744"
          },
          {
            "series": "1",
            "index": "153",
            "xExact": "",
            "x": "154",
            "yExact": "",
            "y": "0",
            "id": "customer:744"
          },
          {
            "series": "0",
            "index": "154",
            "xExact": "",
            "x": "155",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:745"
          },
          {
            "series": "1",
            "index": "154",
            "xExact": "",
            "x": "155",
            "yExact": "",
            "y": "0",
            "id": "customer:745"
          },
          {
            "series": "0",
            "index": "155",
            "xExact": "",
            "x": "156",
            "yExact": "",
            "y": "0.0146341463",
            "id": "customer:751"
          },
          {
            "series": "1",
            "index": "155",
            "xExact": "",
            "x": "156",
            "yExact": "",
            "y": "0",
            "id": "customer:751"
          },
          {
            "series": "0",
            "index": "156",
            "xExact": "",
            "x": "157",
            "yExact": "",
            "y": "0.0377358491",
            "id": "customer:756"
          },
          {
            "series": "1",
            "index": "156",
            "xExact": "",
            "x": "157",
            "yExact": "",
            "y": "0",
            "id": "customer:756"
          },
          {
            "series": "0",
            "index": "157",
            "xExact": "",
            "x": "158",
            "yExact": "",
            "y": "0.0377358491",
            "id": "customer:763"
          },
          {
            "series": "1",
            "index": "157",
            "xExact": "",
            "x": "158",
            "yExact": "",
            "y": "0",
            "id": "customer:763"
          },
          {
            "series": "0",
            "index": "158",
            "xExact": "",
            "x": "159",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:769"
          },
          {
            "series": "1",
            "index": "158",
            "xExact": "",
            "x": "159",
            "yExact": "",
            "y": "1",
            "id": "customer:769"
          },
          {
            "series": "0",
            "index": "159",
            "xExact": "",
            "x": "160",
            "yExact": "",
            "y": "0.0146341463",
            "id": "customer:770"
          },
          {
            "series": "1",
            "index": "159",
            "xExact": "",
            "x": "160",
            "yExact": "",
            "y": "0",
            "id": "customer:770"
          },
          {
            "series": "0",
            "index": "160",
            "xExact": "",
            "x": "161",
            "yExact": "",
            "y": "0.0377358491",
            "id": "customer:775"
          },
          {
            "series": "1",
            "index": "160",
            "xExact": "",
            "x": "161",
            "yExact": "",
            "y": "1",
            "id": "customer:775"
          },
          {
            "series": "0",
            "index": "161",
            "xExact": "",
            "x": "162",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:776"
          },
          {
            "series": "1",
            "index": "161",
            "xExact": "",
            "x": "162",
            "yExact": "",
            "y": "0",
            "id": "customer:776"
          },
          {
            "series": "0",
            "index": "162",
            "xExact": "",
            "x": "163",
            "yExact": "",
            "y": "0.958333333",
            "id": "customer:779"
          },
          {
            "series": "1",
            "index": "162",
            "xExact": "",
            "x": "163",
            "yExact": "",
            "y": "1",
            "id": "customer:779"
          },
          {
            "series": "0",
            "index": "163",
            "xExact": "",
            "x": "164",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:780"
          },
          {
            "series": "1",
            "index": "163",
            "xExact": "",
            "x": "164",
            "yExact": "",
            "y": "0",
            "id": "customer:780"
          },
          {
            "series": "0",
            "index": "164",
            "xExact": "",
            "x": "165",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:789"
          },
          {
            "series": "1",
            "index": "164",
            "xExact": "",
            "x": "165",
            "yExact": "",
            "y": "0",
            "id": "customer:789"
          },
          {
            "series": "0",
            "index": "165",
            "xExact": "",
            "x": "166",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:790"
          },
          {
            "series": "1",
            "index": "165",
            "xExact": "",
            "x": "166",
            "yExact": "",
            "y": "0",
            "id": "customer:790"
          },
          {
            "series": "0",
            "index": "166",
            "xExact": "",
            "x": "167",
            "yExact": "",
            "y": "0.173913043",
            "id": "customer:793"
          },
          {
            "series": "1",
            "index": "166",
            "xExact": "",
            "x": "167",
            "yExact": "",
            "y": "0",
            "id": "customer:793"
          },
          {
            "series": "0",
            "index": "167",
            "xExact": "",
            "x": "168",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:795"
          },
          {
            "series": "1",
            "index": "167",
            "xExact": "",
            "x": "168",
            "yExact": "",
            "y": "0",
            "id": "customer:795"
          },
          {
            "series": "0",
            "index": "168",
            "xExact": "",
            "x": "169",
            "yExact": "",
            "y": "0.197247706",
            "id": "customer:807"
          },
          {
            "series": "1",
            "index": "168",
            "xExact": "",
            "x": "169",
            "yExact": "",
            "y": "0",
            "id": "customer:807"
          },
          {
            "series": "0",
            "index": "169",
            "xExact": "",
            "x": "170",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:809"
          },
          {
            "series": "1",
            "index": "169",
            "xExact": "",
            "x": "170",
            "yExact": "",
            "y": "0",
            "id": "customer:809"
          },
          {
            "series": "0",
            "index": "170",
            "xExact": "",
            "x": "171",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:815"
          },
          {
            "series": "1",
            "index": "170",
            "xExact": "",
            "x": "171",
            "yExact": "",
            "y": "0",
            "id": "customer:815"
          },
          {
            "series": "0",
            "index": "171",
            "xExact": "",
            "x": "172",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:822"
          },
          {
            "series": "1",
            "index": "171",
            "xExact": "",
            "x": "172",
            "yExact": "",
            "y": "0",
            "id": "customer:822"
          },
          {
            "series": "0",
            "index": "172",
            "xExact": "",
            "x": "173",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:825"
          },
          {
            "series": "1",
            "index": "172",
            "xExact": "",
            "x": "173",
            "yExact": "",
            "y": "0",
            "id": "customer:825"
          },
          {
            "series": "0",
            "index": "173",
            "xExact": "",
            "x": "174",
            "yExact": "",
            "y": "0.586206897",
            "id": "customer:828"
          },
          {
            "series": "1",
            "index": "173",
            "xExact": "",
            "x": "174",
            "yExact": "",
            "y": "1",
            "id": "customer:828"
          },
          {
            "series": "0",
            "index": "174",
            "xExact": "",
            "x": "175",
            "yExact": "",
            "y": "0.197247706",
            "id": "customer:829"
          },
          {
            "series": "1",
            "index": "174",
            "xExact": "",
            "x": "175",
            "yExact": "",
            "y": "1",
            "id": "customer:829"
          },
          {
            "series": "0",
            "index": "175",
            "xExact": "",
            "x": "176",
            "yExact": "",
            "y": "0.197247706",
            "id": "customer:830"
          },
          {
            "series": "1",
            "index": "175",
            "xExact": "",
            "x": "176",
            "yExact": "",
            "y": "0",
            "id": "customer:830"
          },
          {
            "series": "0",
            "index": "176",
            "xExact": "",
            "x": "177",
            "yExact": "",
            "y": "0.0071942446",
            "id": "customer:831"
          },
          {
            "series": "1",
            "index": "176",
            "xExact": "",
            "x": "177",
            "yExact": "",
            "y": "0",
            "id": "customer:831"
          },
          {
            "series": "0",
            "index": "177",
            "xExact": "",
            "x": "178",
            "yExact": "",
            "y": "0.197247706",
            "id": "customer:833"
          },
          {
            "series": "1",
            "index": "177",
            "xExact": "",
            "x": "178",
            "yExact": "",
            "y": "0",
            "id": "customer:833"
          },
          {
            "series": "0",
            "index": "178",
            "xExact": "",
            "x": "179",
            "yExact": "",
            "y": "0.0071942446",
            "id": "customer:836"
          },
          {
            "series": "1",
            "index": "178",
            "xExact": "",
            "x": "179",
            "yExact": "",
            "y": "0",
            "id": "customer:836"
          },
          {
            "series": "0",
            "index": "179",
            "xExact": "",
            "x": "180",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:856"
          },
          {
            "series": "1",
            "index": "179",
            "xExact": "",
            "x": "180",
            "yExact": "",
            "y": "0",
            "id": "customer:856"
          },
          {
            "series": "0",
            "index": "180",
            "xExact": "",
            "x": "181",
            "yExact": "",
            "y": "0.197247706",
            "id": "customer:867"
          },
          {
            "series": "1",
            "index": "180",
            "xExact": "",
            "x": "181",
            "yExact": "",
            "y": "0",
            "id": "customer:867"
          },
          {
            "series": "0",
            "index": "181",
            "xExact": "",
            "x": "182",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:870"
          },
          {
            "series": "1",
            "index": "181",
            "xExact": "",
            "x": "182",
            "yExact": "",
            "y": "0",
            "id": "customer:870"
          },
          {
            "series": "0",
            "index": "182",
            "xExact": "",
            "x": "183",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:871"
          },
          {
            "series": "1",
            "index": "182",
            "xExact": "",
            "x": "183",
            "yExact": "",
            "y": "0",
            "id": "customer:871"
          },
          {
            "series": "0",
            "index": "183",
            "xExact": "",
            "x": "184",
            "yExact": "",
            "y": "0.586206897",
            "id": "customer:877"
          },
          {
            "series": "1",
            "index": "183",
            "xExact": "",
            "x": "184",
            "yExact": "",
            "y": "1",
            "id": "customer:877"
          },
          {
            "series": "0",
            "index": "184",
            "xExact": "",
            "x": "185",
            "yExact": "",
            "y": "0.0377358491",
            "id": "customer:881"
          },
          {
            "series": "1",
            "index": "184",
            "xExact": "",
            "x": "185",
            "yExact": "",
            "y": "0",
            "id": "customer:881"
          },
          {
            "series": "0",
            "index": "185",
            "xExact": "",
            "x": "186",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:892"
          },
          {
            "series": "1",
            "index": "185",
            "xExact": "",
            "x": "186",
            "yExact": "",
            "y": "0",
            "id": "customer:892"
          },
          {
            "series": "0",
            "index": "186",
            "xExact": "",
            "x": "187",
            "yExact": "",
            "y": "0.173913043",
            "id": "customer:895"
          },
          {
            "series": "1",
            "index": "186",
            "xExact": "",
            "x": "187",
            "yExact": "",
            "y": "0",
            "id": "customer:895"
          },
          {
            "series": "0",
            "index": "187",
            "xExact": "",
            "x": "188",
            "yExact": "",
            "y": "0.0377358491",
            "id": "customer:896"
          },
          {
            "series": "1",
            "index": "187",
            "xExact": "",
            "x": "188",
            "yExact": "",
            "y": "0",
            "id": "customer:896"
          },
          {
            "series": "0",
            "index": "188",
            "xExact": "",
            "x": "189",
            "yExact": "",
            "y": "0.0377358491",
            "id": "customer:897"
          },
          {
            "series": "1",
            "index": "188",
            "xExact": "",
            "x": "189",
            "yExact": "",
            "y": "0",
            "id": "customer:897"
          },
          {
            "series": "0",
            "index": "189",
            "xExact": "",
            "x": "190",
            "yExact": "",
            "y": "0.0377358491",
            "id": "customer:899"
          },
          {
            "series": "1",
            "index": "189",
            "xExact": "",
            "x": "190",
            "yExact": "",
            "y": "0",
            "id": "customer:899"
          },
          {
            "series": "0",
            "index": "190",
            "xExact": "",
            "x": "191",
            "yExact": "",
            "y": "0.197247706",
            "id": "customer:903"
          },
          {
            "series": "1",
            "index": "190",
            "xExact": "",
            "x": "191",
            "yExact": "",
            "y": "0",
            "id": "customer:903"
          },
          {
            "series": "0",
            "index": "191",
            "xExact": "",
            "x": "192",
            "yExact": "",
            "y": "0.0071942446",
            "id": "customer:910"
          },
          {
            "series": "1",
            "index": "191",
            "xExact": "",
            "x": "192",
            "yExact": "",
            "y": "0",
            "id": "customer:910"
          },
          {
            "series": "0",
            "index": "192",
            "xExact": "",
            "x": "193",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:913"
          },
          {
            "series": "1",
            "index": "192",
            "xExact": "",
            "x": "193",
            "yExact": "",
            "y": "0",
            "id": "customer:913"
          },
          {
            "series": "0",
            "index": "193",
            "xExact": "",
            "x": "194",
            "yExact": "",
            "y": "0.0071942446",
            "id": "customer:921"
          },
          {
            "series": "1",
            "index": "193",
            "xExact": "",
            "x": "194",
            "yExact": "",
            "y": "0",
            "id": "customer:921"
          },
          {
            "series": "0",
            "index": "194",
            "xExact": "",
            "x": "195",
            "yExact": "",
            "y": "0.0377358491",
            "id": "customer:925"
          },
          {
            "series": "1",
            "index": "194",
            "xExact": "",
            "x": "195",
            "yExact": "",
            "y": "1",
            "id": "customer:925"
          },
          {
            "series": "0",
            "index": "195",
            "xExact": "",
            "x": "196",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:926"
          },
          {
            "series": "1",
            "index": "195",
            "xExact": "",
            "x": "196",
            "yExact": "",
            "y": "0",
            "id": "customer:926"
          },
          {
            "series": "0",
            "index": "196",
            "xExact": "",
            "x": "197",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:930"
          },
          {
            "series": "1",
            "index": "196",
            "xExact": "",
            "x": "197",
            "yExact": "",
            "y": "0",
            "id": "customer:930"
          },
          {
            "series": "0",
            "index": "197",
            "xExact": "",
            "x": "198",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:933"
          },
          {
            "series": "1",
            "index": "197",
            "xExact": "",
            "x": "198",
            "yExact": "",
            "y": "0",
            "id": "customer:933"
          },
          {
            "series": "0",
            "index": "198",
            "xExact": "",
            "x": "199",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:940"
          },
          {
            "series": "1",
            "index": "198",
            "xExact": "",
            "x": "199",
            "yExact": "",
            "y": "0",
            "id": "customer:940"
          },
          {
            "series": "0",
            "index": "199",
            "xExact": "",
            "x": "200",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:941"
          },
          {
            "series": "1",
            "index": "199",
            "xExact": "",
            "x": "200",
            "yExact": "",
            "y": "0",
            "id": "customer:941"
          },
          {
            "series": "0",
            "index": "200",
            "xExact": "",
            "x": "201",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:943"
          },
          {
            "series": "1",
            "index": "200",
            "xExact": "",
            "x": "201",
            "yExact": "",
            "y": "0",
            "id": "customer:943"
          },
          {
            "series": "0",
            "index": "201",
            "xExact": "",
            "x": "202",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:948"
          },
          {
            "series": "1",
            "index": "201",
            "xExact": "",
            "x": "202",
            "yExact": "",
            "y": "0",
            "id": "customer:948"
          },
          {
            "series": "0",
            "index": "202",
            "xExact": "",
            "x": "203",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:951"
          },
          {
            "series": "1",
            "index": "202",
            "xExact": "",
            "x": "203",
            "yExact": "",
            "y": "0",
            "id": "customer:951"
          },
          {
            "series": "0",
            "index": "203",
            "xExact": "",
            "x": "204",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:954"
          },
          {
            "series": "1",
            "index": "203",
            "xExact": "",
            "x": "204",
            "yExact": "",
            "y": "0",
            "id": "customer:954"
          },
          {
            "series": "0",
            "index": "204",
            "xExact": "",
            "x": "205",
            "yExact": "",
            "y": "0.197247706",
            "id": "customer:955"
          },
          {
            "series": "1",
            "index": "204",
            "xExact": "",
            "x": "205",
            "yExact": "",
            "y": "0",
            "id": "customer:955"
          },
          {
            "series": "0",
            "index": "205",
            "xExact": "",
            "x": "206",
            "yExact": "",
            "y": "0.197247706",
            "id": "customer:957"
          },
          {
            "series": "1",
            "index": "205",
            "xExact": "",
            "x": "206",
            "yExact": "",
            "y": "0",
            "id": "customer:957"
          },
          {
            "series": "0",
            "index": "206",
            "xExact": "",
            "x": "207",
            "yExact": "",
            "y": "0.0071942446",
            "id": "customer:966"
          },
          {
            "series": "1",
            "index": "206",
            "xExact": "",
            "x": "207",
            "yExact": "",
            "y": "0",
            "id": "customer:966"
          },
          {
            "series": "0",
            "index": "207",
            "xExact": "",
            "x": "208",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:971"
          },
          {
            "series": "1",
            "index": "207",
            "xExact": "",
            "x": "208",
            "yExact": "",
            "y": "0",
            "id": "customer:971"
          },
          {
            "series": "0",
            "index": "208",
            "xExact": "",
            "x": "209",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:975"
          },
          {
            "series": "1",
            "index": "208",
            "xExact": "",
            "x": "209",
            "yExact": "",
            "y": "1",
            "id": "customer:975"
          },
          {
            "series": "0",
            "index": "209",
            "xExact": "",
            "x": "210",
            "yExact": "",
            "y": "0.666666667",
            "id": "customer:977"
          },
          {
            "series": "1",
            "index": "209",
            "xExact": "",
            "x": "210",
            "yExact": "",
            "y": "1",
            "id": "customer:977"
          },
          {
            "series": "0",
            "index": "210",
            "xExact": "",
            "x": "211",
            "yExact": "",
            "y": "0.197247706",
            "id": "customer:979"
          },
          {
            "series": "1",
            "index": "210",
            "xExact": "",
            "x": "211",
            "yExact": "",
            "y": "1",
            "id": "customer:979"
          },
          {
            "series": "0",
            "index": "211",
            "xExact": "",
            "x": "212",
            "yExact": "",
            "y": "0.197247706",
            "id": "customer:982"
          },
          {
            "series": "1",
            "index": "211",
            "xExact": "",
            "x": "212",
            "yExact": "",
            "y": "1",
            "id": "customer:982"
          },
          {
            "series": "0",
            "index": "212",
            "xExact": "",
            "x": "213",
            "yExact": "",
            "y": "0.0146341463",
            "id": "customer:985"
          },
          {
            "series": "1",
            "index": "212",
            "xExact": "",
            "x": "213",
            "yExact": "",
            "y": "0",
            "id": "customer:985"
          },
          {
            "series": "0",
            "index": "213",
            "xExact": "",
            "x": "214",
            "yExact": "",
            "y": "0.0071942446",
            "id": "customer:986"
          },
          {
            "series": "1",
            "index": "213",
            "xExact": "",
            "x": "214",
            "yExact": "",
            "y": "0",
            "id": "customer:986"
          },
          {
            "series": "0",
            "index": "214",
            "xExact": "",
            "x": "215",
            "yExact": "",
            "y": "0.173913043",
            "id": "customer:991"
          },
          {
            "series": "1",
            "index": "214",
            "xExact": "",
            "x": "215",
            "yExact": "",
            "y": "0",
            "id": "customer:991"
          },
          {
            "series": "0",
            "index": "215",
            "xExact": "",
            "x": "216",
            "yExact": "",
            "y": "0.0146341463",
            "id": "customer:994"
          },
          {
            "series": "1",
            "index": "215",
            "xExact": "",
            "x": "216",
            "yExact": "",
            "y": "0",
            "id": "customer:994"
          },
          {
            "series": "0",
            "index": "216",
            "xExact": "",
            "x": "217",
            "yExact": "",
            "y": "0.173913043",
            "id": "customer:998"
          },
          {
            "series": "1",
            "index": "216",
            "xExact": "",
            "x": "217",
            "yExact": "",
            "y": "0",
            "id": "customer:998"
          },
          {
            "series": "0",
            "index": "217",
            "xExact": "",
            "x": "218",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:1008"
          },
          {
            "series": "1",
            "index": "217",
            "xExact": "",
            "x": "218",
            "yExact": "",
            "y": "0",
            "id": "customer:1008"
          },
          {
            "series": "0",
            "index": "218",
            "xExact": "",
            "x": "219",
            "yExact": "",
            "y": "0.0071942446",
            "id": "customer:1014"
          },
          {
            "series": "1",
            "index": "218",
            "xExact": "",
            "x": "219",
            "yExact": "",
            "y": "0",
            "id": "customer:1014"
          },
          {
            "series": "0",
            "index": "219",
            "xExact": "",
            "x": "220",
            "yExact": "",
            "y": "0.0071942446",
            "id": "customer:1016"
          },
          {
            "series": "1",
            "index": "219",
            "xExact": "",
            "x": "220",
            "yExact": "",
            "y": "0",
            "id": "customer:1016"
          },
          {
            "series": "0",
            "index": "220",
            "xExact": "",
            "x": "221",
            "yExact": "",
            "y": "0.197247706",
            "id": "customer:1017"
          },
          {
            "series": "1",
            "index": "220",
            "xExact": "",
            "x": "221",
            "yExact": "",
            "y": "0",
            "id": "customer:1017"
          },
          {
            "series": "0",
            "index": "221",
            "xExact": "",
            "x": "222",
            "yExact": "",
            "y": "0.197247706",
            "id": "customer:1030"
          },
          {
            "series": "1",
            "index": "221",
            "xExact": "",
            "x": "222",
            "yExact": "",
            "y": "0",
            "id": "customer:1030"
          },
          {
            "series": "0",
            "index": "222",
            "xExact": "",
            "x": "223",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:1037"
          },
          {
            "series": "1",
            "index": "222",
            "xExact": "",
            "x": "223",
            "yExact": "",
            "y": "0",
            "id": "customer:1037"
          },
          {
            "series": "0",
            "index": "223",
            "xExact": "",
            "x": "224",
            "yExact": "",
            "y": "0.197247706",
            "id": "customer:1038"
          },
          {
            "series": "1",
            "index": "223",
            "xExact": "",
            "x": "224",
            "yExact": "",
            "y": "0",
            "id": "customer:1038"
          },
          {
            "series": "0",
            "index": "224",
            "xExact": "",
            "x": "225",
            "yExact": "",
            "y": "0.0146341463",
            "id": "customer:1049"
          },
          {
            "series": "1",
            "index": "224",
            "xExact": "",
            "x": "225",
            "yExact": "",
            "y": "0",
            "id": "customer:1049"
          },
          {
            "series": "0",
            "index": "225",
            "xExact": "",
            "x": "226",
            "yExact": "",
            "y": "0.0071942446",
            "id": "customer:1059"
          },
          {
            "series": "1",
            "index": "225",
            "xExact": "",
            "x": "226",
            "yExact": "",
            "y": "0",
            "id": "customer:1059"
          },
          {
            "series": "0",
            "index": "226",
            "xExact": "",
            "x": "227",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:1063"
          },
          {
            "series": "1",
            "index": "226",
            "xExact": "",
            "x": "227",
            "yExact": "",
            "y": "0",
            "id": "customer:1063"
          },
          {
            "series": "0",
            "index": "227",
            "xExact": "",
            "x": "228",
            "yExact": "",
            "y": "0.197247706",
            "id": "customer:1064"
          },
          {
            "series": "1",
            "index": "227",
            "xExact": "",
            "x": "228",
            "yExact": "",
            "y": "0",
            "id": "customer:1064"
          },
          {
            "series": "0",
            "index": "228",
            "xExact": "",
            "x": "229",
            "yExact": "",
            "y": "0.0146341463",
            "id": "customer:1065"
          },
          {
            "series": "1",
            "index": "228",
            "xExact": "",
            "x": "229",
            "yExact": "",
            "y": "0",
            "id": "customer:1065"
          },
          {
            "series": "0",
            "index": "229",
            "xExact": "",
            "x": "230",
            "yExact": "",
            "y": "0.0146341463",
            "id": "customer:1071"
          },
          {
            "series": "1",
            "index": "229",
            "xExact": "",
            "x": "230",
            "yExact": "",
            "y": "0",
            "id": "customer:1071"
          },
          {
            "series": "0",
            "index": "230",
            "xExact": "",
            "x": "231",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:1076"
          },
          {
            "series": "1",
            "index": "230",
            "xExact": "",
            "x": "231",
            "yExact": "",
            "y": "0",
            "id": "customer:1076"
          },
          {
            "series": "0",
            "index": "231",
            "xExact": "",
            "x": "232",
            "yExact": "",
            "y": "0.0146341463",
            "id": "customer:1081"
          },
          {
            "series": "1",
            "index": "231",
            "xExact": "",
            "x": "232",
            "yExact": "",
            "y": "0",
            "id": "customer:1081"
          },
          {
            "series": "0",
            "index": "232",
            "xExact": "",
            "x": "233",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:1082"
          },
          {
            "series": "1",
            "index": "232",
            "xExact": "",
            "x": "233",
            "yExact": "",
            "y": "1",
            "id": "customer:1082"
          },
          {
            "series": "0",
            "index": "233",
            "xExact": "",
            "x": "234",
            "yExact": "",
            "y": "0.0146341463",
            "id": "customer:1085"
          },
          {
            "series": "1",
            "index": "233",
            "xExact": "",
            "x": "234",
            "yExact": "",
            "y": "0",
            "id": "customer:1085"
          },
          {
            "series": "0",
            "index": "234",
            "xExact": "",
            "x": "235",
            "yExact": "",
            "y": "0.0146341463",
            "id": "customer:1086"
          },
          {
            "series": "1",
            "index": "234",
            "xExact": "",
            "x": "235",
            "yExact": "",
            "y": "0",
            "id": "customer:1086"
          },
          {
            "series": "0",
            "index": "235",
            "xExact": "",
            "x": "236",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:1090"
          },
          {
            "series": "1",
            "index": "235",
            "xExact": "",
            "x": "236",
            "yExact": "",
            "y": "0",
            "id": "customer:1090"
          },
          {
            "series": "0",
            "index": "236",
            "xExact": "",
            "x": "237",
            "yExact": "",
            "y": "0.0377358491",
            "id": "customer:1096"
          },
          {
            "series": "1",
            "index": "236",
            "xExact": "",
            "x": "237",
            "yExact": "",
            "y": "0",
            "id": "customer:1096"
          },
          {
            "series": "0",
            "index": "237",
            "xExact": "",
            "x": "238",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:1108"
          },
          {
            "series": "1",
            "index": "237",
            "xExact": "",
            "x": "238",
            "yExact": "",
            "y": "0",
            "id": "customer:1108"
          },
          {
            "series": "0",
            "index": "238",
            "xExact": "",
            "x": "239",
            "yExact": "",
            "y": "0.197247706",
            "id": "customer:1114"
          },
          {
            "series": "1",
            "index": "238",
            "xExact": "",
            "x": "239",
            "yExact": "",
            "y": "0",
            "id": "customer:1114"
          },
          {
            "series": "0",
            "index": "239",
            "xExact": "",
            "x": "240",
            "yExact": "",
            "y": "0.197247706",
            "id": "customer:1119"
          },
          {
            "series": "1",
            "index": "239",
            "xExact": "",
            "x": "240",
            "yExact": "",
            "y": "1",
            "id": "customer:1119"
          },
          {
            "series": "0",
            "index": "240",
            "xExact": "",
            "x": "241",
            "yExact": "",
            "y": "0.0071942446",
            "id": "customer:1136"
          },
          {
            "series": "1",
            "index": "240",
            "xExact": "",
            "x": "241",
            "yExact": "",
            "y": "0",
            "id": "customer:1136"
          },
          {
            "series": "0",
            "index": "241",
            "xExact": "",
            "x": "242",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:1142"
          },
          {
            "series": "1",
            "index": "241",
            "xExact": "",
            "x": "242",
            "yExact": "",
            "y": "0",
            "id": "customer:1142"
          },
          {
            "series": "0",
            "index": "242",
            "xExact": "",
            "x": "243",
            "yExact": "",
            "y": "0.0146341463",
            "id": "customer:1156"
          },
          {
            "series": "1",
            "index": "242",
            "xExact": "",
            "x": "243",
            "yExact": "",
            "y": "0",
            "id": "customer:1156"
          },
          {
            "series": "0",
            "index": "243",
            "xExact": "",
            "x": "244",
            "yExact": "",
            "y": "0.0146341463",
            "id": "customer:1159"
          },
          {
            "series": "1",
            "index": "243",
            "xExact": "",
            "x": "244",
            "yExact": "",
            "y": "0",
            "id": "customer:1159"
          },
          {
            "series": "0",
            "index": "244",
            "xExact": "",
            "x": "245",
            "yExact": "",
            "y": "0.173913043",
            "id": "customer:1173"
          },
          {
            "series": "1",
            "index": "244",
            "xExact": "",
            "x": "245",
            "yExact": "",
            "y": "1",
            "id": "customer:1173"
          },
          {
            "series": "0",
            "index": "245",
            "xExact": "",
            "x": "246",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:1192"
          },
          {
            "series": "1",
            "index": "245",
            "xExact": "",
            "x": "246",
            "yExact": "",
            "y": "0",
            "id": "customer:1192"
          },
          {
            "series": "0",
            "index": "246",
            "xExact": "",
            "x": "247",
            "yExact": "",
            "y": "0.197247706",
            "id": "customer:1205"
          },
          {
            "series": "1",
            "index": "246",
            "xExact": "",
            "x": "247",
            "yExact": "",
            "y": "0",
            "id": "customer:1205"
          },
          {
            "series": "0",
            "index": "247",
            "xExact": "",
            "x": "248",
            "yExact": "",
            "y": "0.197247706",
            "id": "customer:1218"
          },
          {
            "series": "1",
            "index": "247",
            "xExact": "",
            "x": "248",
            "yExact": "",
            "y": "0",
            "id": "customer:1218"
          },
          {
            "series": "0",
            "index": "248",
            "xExact": "",
            "x": "249",
            "yExact": "",
            "y": "0.197247706",
            "id": "customer:1219"
          },
          {
            "series": "1",
            "index": "248",
            "xExact": "",
            "x": "249",
            "yExact": "",
            "y": "1",
            "id": "customer:1219"
          },
          {
            "series": "0",
            "index": "249",
            "xExact": "",
            "x": "250",
            "yExact": "",
            "y": "0.0071942446",
            "id": "customer:1220"
          },
          {
            "series": "1",
            "index": "249",
            "xExact": "",
            "x": "250",
            "yExact": "",
            "y": "0",
            "id": "customer:1220"
          },
          {
            "series": "0",
            "index": "250",
            "xExact": "",
            "x": "251",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:1225"
          },
          {
            "series": "1",
            "index": "250",
            "xExact": "",
            "x": "251",
            "yExact": "",
            "y": "1",
            "id": "customer:1225"
          },
          {
            "series": "0",
            "index": "251",
            "xExact": "",
            "x": "252",
            "yExact": "",
            "y": "0.197247706",
            "id": "customer:1229"
          },
          {
            "series": "1",
            "index": "251",
            "xExact": "",
            "x": "252",
            "yExact": "",
            "y": "1",
            "id": "customer:1229"
          },
          {
            "series": "0",
            "index": "252",
            "xExact": "",
            "x": "253",
            "yExact": "",
            "y": "0.857142857",
            "id": "customer:1232"
          },
          {
            "series": "1",
            "index": "252",
            "xExact": "",
            "x": "253",
            "yExact": "",
            "y": "1",
            "id": "customer:1232"
          },
          {
            "series": "0",
            "index": "253",
            "xExact": "",
            "x": "254",
            "yExact": "",
            "y": "0.0377358491",
            "id": "customer:1234"
          },
          {
            "series": "1",
            "index": "253",
            "xExact": "",
            "x": "254",
            "yExact": "",
            "y": "0",
            "id": "customer:1234"
          },
          {
            "series": "0",
            "index": "254",
            "xExact": "",
            "x": "255",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:1240"
          },
          {
            "series": "1",
            "index": "254",
            "xExact": "",
            "x": "255",
            "yExact": "",
            "y": "0",
            "id": "customer:1240"
          },
          {
            "series": "0",
            "index": "255",
            "xExact": "",
            "x": "256",
            "yExact": "",
            "y": "0.0146341463",
            "id": "customer:1244"
          },
          {
            "series": "1",
            "index": "255",
            "xExact": "",
            "x": "256",
            "yExact": "",
            "y": "0",
            "id": "customer:1244"
          },
          {
            "series": "0",
            "index": "256",
            "xExact": "",
            "x": "257",
            "yExact": "",
            "y": "0.0377358491",
            "id": "customer:1246"
          },
          {
            "series": "1",
            "index": "256",
            "xExact": "",
            "x": "257",
            "yExact": "",
            "y": "0",
            "id": "customer:1246"
          },
          {
            "series": "0",
            "index": "257",
            "xExact": "",
            "x": "258",
            "yExact": "",
            "y": "0.0377358491",
            "id": "customer:1247"
          },
          {
            "series": "1",
            "index": "257",
            "xExact": "",
            "x": "258",
            "yExact": "",
            "y": "0",
            "id": "customer:1247"
          },
          {
            "series": "0",
            "index": "258",
            "xExact": "",
            "x": "259",
            "yExact": "",
            "y": "0.0146341463",
            "id": "customer:1254"
          },
          {
            "series": "1",
            "index": "258",
            "xExact": "",
            "x": "259",
            "yExact": "",
            "y": "0",
            "id": "customer:1254"
          },
          {
            "series": "0",
            "index": "259",
            "xExact": "",
            "x": "260",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:1255"
          },
          {
            "series": "1",
            "index": "259",
            "xExact": "",
            "x": "260",
            "yExact": "",
            "y": "0",
            "id": "customer:1255"
          },
          {
            "series": "0",
            "index": "260",
            "xExact": "",
            "x": "261",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:1267"
          },
          {
            "series": "1",
            "index": "260",
            "xExact": "",
            "x": "261",
            "yExact": "",
            "y": "0",
            "id": "customer:1267"
          },
          {
            "series": "0",
            "index": "261",
            "xExact": "",
            "x": "262",
            "yExact": "",
            "y": "0.0146341463",
            "id": "customer:1271"
          },
          {
            "series": "1",
            "index": "261",
            "xExact": "",
            "x": "262",
            "yExact": "",
            "y": "0",
            "id": "customer:1271"
          },
          {
            "series": "0",
            "index": "262",
            "xExact": "",
            "x": "263",
            "yExact": "",
            "y": "0.0377358491",
            "id": "customer:1275"
          },
          {
            "series": "1",
            "index": "262",
            "xExact": "",
            "x": "263",
            "yExact": "",
            "y": "1",
            "id": "customer:1275"
          },
          {
            "series": "0",
            "index": "263",
            "xExact": "",
            "x": "264",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:1278"
          },
          {
            "series": "1",
            "index": "263",
            "xExact": "",
            "x": "264",
            "yExact": "",
            "y": "1",
            "id": "customer:1278"
          },
          {
            "series": "0",
            "index": "264",
            "xExact": "",
            "x": "265",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:1283"
          },
          {
            "series": "1",
            "index": "264",
            "xExact": "",
            "x": "265",
            "yExact": "",
            "y": "0",
            "id": "customer:1283"
          },
          {
            "series": "0",
            "index": "265",
            "xExact": "",
            "x": "266",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:1289"
          },
          {
            "series": "1",
            "index": "265",
            "xExact": "",
            "x": "266",
            "yExact": "",
            "y": "0",
            "id": "customer:1289"
          },
          {
            "series": "0",
            "index": "266",
            "xExact": "",
            "x": "267",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:1294"
          },
          {
            "series": "1",
            "index": "266",
            "xExact": "",
            "x": "267",
            "yExact": "",
            "y": "0",
            "id": "customer:1294"
          },
          {
            "series": "0",
            "index": "267",
            "xExact": "",
            "x": "268",
            "yExact": "",
            "y": "0.0146341463",
            "id": "customer:1297"
          },
          {
            "series": "1",
            "index": "267",
            "xExact": "",
            "x": "268",
            "yExact": "",
            "y": "0",
            "id": "customer:1297"
          },
          {
            "series": "0",
            "index": "268",
            "xExact": "",
            "x": "269",
            "yExact": "",
            "y": "0.197247706",
            "id": "customer:1307"
          },
          {
            "series": "1",
            "index": "268",
            "xExact": "",
            "x": "269",
            "yExact": "",
            "y": "0",
            "id": "customer:1307"
          },
          {
            "series": "0",
            "index": "269",
            "xExact": "",
            "x": "270",
            "yExact": "",
            "y": "0.0071942446",
            "id": "customer:1311"
          },
          {
            "series": "1",
            "index": "269",
            "xExact": "",
            "x": "270",
            "yExact": "",
            "y": "0",
            "id": "customer:1311"
          },
          {
            "series": "0",
            "index": "270",
            "xExact": "",
            "x": "271",
            "yExact": "",
            "y": "0.197247706",
            "id": "customer:1317"
          },
          {
            "series": "1",
            "index": "270",
            "xExact": "",
            "x": "271",
            "yExact": "",
            "y": "0",
            "id": "customer:1317"
          },
          {
            "series": "0",
            "index": "271",
            "xExact": "",
            "x": "272",
            "yExact": "",
            "y": "0.197247706",
            "id": "customer:1319"
          },
          {
            "series": "1",
            "index": "271",
            "xExact": "",
            "x": "272",
            "yExact": "",
            "y": "1",
            "id": "customer:1319"
          },
          {
            "series": "0",
            "index": "272",
            "xExact": "",
            "x": "273",
            "yExact": "",
            "y": "0.0071942446",
            "id": "customer:1320"
          },
          {
            "series": "1",
            "index": "272",
            "xExact": "",
            "x": "273",
            "yExact": "",
            "y": "0",
            "id": "customer:1320"
          },
          {
            "series": "0",
            "index": "273",
            "xExact": "",
            "x": "274",
            "yExact": "",
            "y": "0.586206897",
            "id": "customer:1324"
          },
          {
            "series": "1",
            "index": "273",
            "xExact": "",
            "x": "274",
            "yExact": "",
            "y": "0",
            "id": "customer:1324"
          },
          {
            "series": "0",
            "index": "274",
            "xExact": "",
            "x": "275",
            "yExact": "",
            "y": "0.586206897",
            "id": "customer:1327"
          },
          {
            "series": "1",
            "index": "274",
            "xExact": "",
            "x": "275",
            "yExact": "",
            "y": "1",
            "id": "customer:1327"
          },
          {
            "series": "0",
            "index": "275",
            "xExact": "",
            "x": "276",
            "yExact": "",
            "y": "0.151785714",
            "id": "customer:1328"
          },
          {
            "series": "1",
            "index": "275",
            "xExact": "",
            "x": "276",
            "yExact": "",
            "y": "1",
            "id": "customer:1328"
          },
          {
            "series": "0",
            "index": "276",
            "xExact": "",
            "x": "277",
            "yExact": "",
            "y": "0.857142857",
            "id": "customer:1332"
          },
          {
            "series": "1",
            "index": "276",
            "xExact": "",
            "x": "277",
            "yExact": "",
            "y": "1",
            "id": "customer:1332"
          },
          {
            "series": "0",
            "index": "277",
            "xExact": "",
            "x": "278",
            "yExact": "",
            "y": "0.0377358491",
            "id": "customer:1334"
          },
          {
            "series": "1",
            "index": "277",
            "xExact": "",
            "x": "278",
            "yExact": "",
            "y": "0",
            "id": "customer:1334"
          },
          {
            "series": "0",
            "index": "278",
            "xExact": "",
            "x": "279",
            "yExact": "",
            "y": "0.197247706",
            "id": "customer:1337"
          },
          {
            "series": "1",
            "index": "278",
            "xExact": "",
            "x": "279",
            "yExact": "",
            "y": "0",
            "id": "customer:1337"
          },
          {
            "series": "0",
            "index": "279",
            "xExact": "",
            "x": "280",
            "yExact": "",
            "y": "0.197247706",
            "id": "customer:1338"
          },
          {
            "series": "1",
            "index": "279",
            "xExact": "",
            "x": "280",
            "yExact": "",
            "y": "0",
            "id": "customer:1338"
          },
          {
            "series": "0",
            "index": "280",
            "xExact": "",
            "x": "281",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:1339"
          },
          {
            "series": "1",
            "index": "280",
            "xExact": "",
            "x": "281",
            "yExact": "",
            "y": "0",
            "id": "customer:1339"
          },
          {
            "series": "0",
            "index": "281",
            "xExact": "",
            "x": "282",
            "yExact": "",
            "y": "0.0146341463",
            "id": "customer:1351"
          },
          {
            "series": "1",
            "index": "281",
            "xExact": "",
            "x": "282",
            "yExact": "",
            "y": "0",
            "id": "customer:1351"
          },
          {
            "series": "0",
            "index": "282",
            "xExact": "",
            "x": "283",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:1352"
          },
          {
            "series": "1",
            "index": "282",
            "xExact": "",
            "x": "283",
            "yExact": "",
            "y": "0",
            "id": "customer:1352"
          },
          {
            "series": "0",
            "index": "283",
            "xExact": "",
            "x": "284",
            "yExact": "",
            "y": "0.0377358491",
            "id": "customer:1363"
          },
          {
            "series": "1",
            "index": "283",
            "xExact": "",
            "x": "284",
            "yExact": "",
            "y": "0",
            "id": "customer:1363"
          },
          {
            "series": "0",
            "index": "284",
            "xExact": "",
            "x": "285",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:1364"
          },
          {
            "series": "1",
            "index": "284",
            "xExact": "",
            "x": "285",
            "yExact": "",
            "y": "0",
            "id": "customer:1364"
          },
          {
            "series": "0",
            "index": "285",
            "xExact": "",
            "x": "286",
            "yExact": "",
            "y": "0.0146341463",
            "id": "customer:1365"
          },
          {
            "series": "1",
            "index": "285",
            "xExact": "",
            "x": "286",
            "yExact": "",
            "y": "0",
            "id": "customer:1365"
          },
          {
            "series": "0",
            "index": "286",
            "xExact": "",
            "x": "287",
            "yExact": "",
            "y": "0.0146341463",
            "id": "customer:1366"
          },
          {
            "series": "1",
            "index": "286",
            "xExact": "",
            "x": "287",
            "yExact": "",
            "y": "0",
            "id": "customer:1366"
          },
          {
            "series": "0",
            "index": "287",
            "xExact": "",
            "x": "288",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:1367"
          },
          {
            "series": "1",
            "index": "287",
            "xExact": "",
            "x": "288",
            "yExact": "",
            "y": "0",
            "id": "customer:1367"
          },
          {
            "series": "0",
            "index": "288",
            "xExact": "",
            "x": "289",
            "yExact": "",
            "y": "0.0146341463",
            "id": "customer:1372"
          },
          {
            "series": "1",
            "index": "288",
            "xExact": "",
            "x": "289",
            "yExact": "",
            "y": "0",
            "id": "customer:1372"
          },
          {
            "series": "0",
            "index": "289",
            "xExact": "",
            "x": "290",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:1376"
          },
          {
            "series": "1",
            "index": "289",
            "xExact": "",
            "x": "290",
            "yExact": "",
            "y": "0",
            "id": "customer:1376"
          },
          {
            "series": "0",
            "index": "290",
            "xExact": "",
            "x": "291",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:1388"
          },
          {
            "series": "1",
            "index": "290",
            "xExact": "",
            "x": "291",
            "yExact": "",
            "y": "0",
            "id": "customer:1388"
          },
          {
            "series": "0",
            "index": "291",
            "xExact": "",
            "x": "292",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:1389"
          },
          {
            "series": "1",
            "index": "291",
            "xExact": "",
            "x": "292",
            "yExact": "",
            "y": "0",
            "id": "customer:1389"
          },
          {
            "series": "0",
            "index": "292",
            "xExact": "",
            "x": "293",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:1392"
          },
          {
            "series": "1",
            "index": "292",
            "xExact": "",
            "x": "293",
            "yExact": "",
            "y": "0",
            "id": "customer:1392"
          },
          {
            "series": "0",
            "index": "293",
            "xExact": "",
            "x": "294",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:1394"
          },
          {
            "series": "1",
            "index": "293",
            "xExact": "",
            "x": "294",
            "yExact": "",
            "y": "0",
            "id": "customer:1394"
          },
          {
            "series": "0",
            "index": "294",
            "xExact": "",
            "x": "295",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:1395"
          },
          {
            "series": "1",
            "index": "294",
            "xExact": "",
            "x": "295",
            "yExact": "",
            "y": "0",
            "id": "customer:1395"
          },
          {
            "series": "0",
            "index": "295",
            "xExact": "",
            "x": "296",
            "yExact": "",
            "y": "0.0071942446",
            "id": "customer:1401"
          },
          {
            "series": "1",
            "index": "295",
            "xExact": "",
            "x": "296",
            "yExact": "",
            "y": "0",
            "id": "customer:1401"
          },
          {
            "series": "0",
            "index": "296",
            "xExact": "",
            "x": "297",
            "yExact": "",
            "y": "0.197247706",
            "id": "customer:1412"
          },
          {
            "series": "1",
            "index": "296",
            "xExact": "",
            "x": "297",
            "yExact": "",
            "y": "0",
            "id": "customer:1412"
          },
          {
            "series": "0",
            "index": "297",
            "xExact": "",
            "x": "298",
            "yExact": "",
            "y": "0.0071942446",
            "id": "customer:1414"
          },
          {
            "series": "1",
            "index": "297",
            "xExact": "",
            "x": "298",
            "yExact": "",
            "y": "0",
            "id": "customer:1414"
          },
          {
            "series": "0",
            "index": "298",
            "xExact": "",
            "x": "299",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:1426"
          },
          {
            "series": "1",
            "index": "298",
            "xExact": "",
            "x": "299",
            "yExact": "",
            "y": "0",
            "id": "customer:1426"
          },
          {
            "series": "0",
            "index": "299",
            "xExact": "",
            "x": "300",
            "yExact": "",
            "y": "0.197247706",
            "id": "customer:1438"
          },
          {
            "series": "1",
            "index": "299",
            "xExact": "",
            "x": "300",
            "yExact": "",
            "y": "0",
            "id": "customer:1438"
          },
          {
            "series": "0",
            "index": "300",
            "xExact": "",
            "x": "301",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:1440"
          },
          {
            "series": "1",
            "index": "300",
            "xExact": "",
            "x": "301",
            "yExact": "",
            "y": "0",
            "id": "customer:1440"
          },
          {
            "series": "0",
            "index": "301",
            "xExact": "",
            "x": "302",
            "yExact": "",
            "y": "0.0146341463",
            "id": "customer:1449"
          },
          {
            "series": "1",
            "index": "301",
            "xExact": "",
            "x": "302",
            "yExact": "",
            "y": "0",
            "id": "customer:1449"
          },
          {
            "series": "0",
            "index": "302",
            "xExact": "",
            "x": "303",
            "yExact": "",
            "y": "0.0146341463",
            "id": "customer:1458"
          },
          {
            "series": "1",
            "index": "302",
            "xExact": "",
            "x": "303",
            "yExact": "",
            "y": "0",
            "id": "customer:1458"
          },
          {
            "series": "0",
            "index": "303",
            "xExact": "",
            "x": "304",
            "yExact": "",
            "y": "0.0146341463",
            "id": "customer:1459"
          },
          {
            "series": "1",
            "index": "303",
            "xExact": "",
            "x": "304",
            "yExact": "",
            "y": "0",
            "id": "customer:1459"
          },
          {
            "series": "0",
            "index": "304",
            "xExact": "",
            "x": "305",
            "yExact": "",
            "y": "0.0146341463",
            "id": "customer:1472"
          },
          {
            "series": "1",
            "index": "304",
            "xExact": "",
            "x": "305",
            "yExact": "",
            "y": "0",
            "id": "customer:1472"
          },
          {
            "series": "0",
            "index": "305",
            "xExact": "",
            "x": "306",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:1478"
          },
          {
            "series": "1",
            "index": "305",
            "xExact": "",
            "x": "306",
            "yExact": "",
            "y": "1",
            "id": "customer:1478"
          },
          {
            "series": "0",
            "index": "306",
            "xExact": "",
            "x": "307",
            "yExact": "",
            "y": "0.0146341463",
            "id": "customer:1485"
          },
          {
            "series": "1",
            "index": "306",
            "xExact": "",
            "x": "307",
            "yExact": "",
            "y": "0",
            "id": "customer:1485"
          },
          {
            "series": "0",
            "index": "307",
            "xExact": "",
            "x": "308",
            "yExact": "",
            "y": "0.0146341463",
            "id": "customer:1486"
          },
          {
            "series": "1",
            "index": "307",
            "xExact": "",
            "x": "308",
            "yExact": "",
            "y": "0",
            "id": "customer:1486"
          },
          {
            "series": "0",
            "index": "308",
            "xExact": "",
            "x": "309",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:1488"
          },
          {
            "series": "1",
            "index": "308",
            "xExact": "",
            "x": "309",
            "yExact": "",
            "y": "0",
            "id": "customer:1488"
          },
          {
            "series": "0",
            "index": "309",
            "xExact": "",
            "x": "310",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:1490"
          },
          {
            "series": "1",
            "index": "309",
            "xExact": "",
            "x": "310",
            "yExact": "",
            "y": "0",
            "id": "customer:1490"
          },
          {
            "series": "0",
            "index": "310",
            "xExact": "",
            "x": "311",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:1491"
          },
          {
            "series": "1",
            "index": "310",
            "xExact": "",
            "x": "311",
            "yExact": "",
            "y": "0",
            "id": "customer:1491"
          },
          {
            "series": "0",
            "index": "311",
            "xExact": "",
            "x": "312",
            "yExact": "",
            "y": "0.0146341463",
            "id": "customer:1497"
          },
          {
            "series": "1",
            "index": "311",
            "xExact": "",
            "x": "312",
            "yExact": "",
            "y": "0",
            "id": "customer:1497"
          },
          {
            "series": "0",
            "index": "312",
            "xExact": "",
            "x": "313",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:1500"
          },
          {
            "series": "1",
            "index": "312",
            "xExact": "",
            "x": "313",
            "yExact": "",
            "y": "1",
            "id": "customer:1500"
          },
          {
            "series": "0",
            "index": "313",
            "xExact": "",
            "x": "314",
            "yExact": "",
            "y": "0.0071942446",
            "id": "customer:1509"
          },
          {
            "series": "1",
            "index": "313",
            "xExact": "",
            "x": "314",
            "yExact": "",
            "y": "0",
            "id": "customer:1509"
          },
          {
            "series": "0",
            "index": "314",
            "xExact": "",
            "x": "315",
            "yExact": "",
            "y": "0.197247706",
            "id": "customer:1518"
          },
          {
            "series": "1",
            "index": "314",
            "xExact": "",
            "x": "315",
            "yExact": "",
            "y": "0",
            "id": "customer:1518"
          },
          {
            "series": "0",
            "index": "315",
            "xExact": "",
            "x": "316",
            "yExact": "",
            "y": "0.0377358491",
            "id": "customer:1524"
          },
          {
            "series": "1",
            "index": "315",
            "xExact": "",
            "x": "316",
            "yExact": "",
            "y": "0",
            "id": "customer:1524"
          },
          {
            "series": "0",
            "index": "316",
            "xExact": "",
            "x": "317",
            "yExact": "",
            "y": "0.947368421",
            "id": "customer:1528"
          },
          {
            "series": "1",
            "index": "316",
            "xExact": "",
            "x": "317",
            "yExact": "",
            "y": "1",
            "id": "customer:1528"
          },
          {
            "series": "0",
            "index": "317",
            "xExact": "",
            "x": "318",
            "yExact": "",
            "y": "0.0146341463",
            "id": "customer:1531"
          },
          {
            "series": "1",
            "index": "317",
            "xExact": "",
            "x": "318",
            "yExact": "",
            "y": "0",
            "id": "customer:1531"
          },
          {
            "series": "0",
            "index": "318",
            "xExact": "",
            "x": "319",
            "yExact": "",
            "y": "0.0377358491",
            "id": "customer:1547"
          },
          {
            "series": "1",
            "index": "318",
            "xExact": "",
            "x": "319",
            "yExact": "",
            "y": "0",
            "id": "customer:1547"
          },
          {
            "series": "0",
            "index": "319",
            "xExact": "",
            "x": "320",
            "yExact": "",
            "y": "0.0071942446",
            "id": "customer:1560"
          },
          {
            "series": "1",
            "index": "319",
            "xExact": "",
            "x": "320",
            "yExact": "",
            "y": "0",
            "id": "customer:1560"
          },
          {
            "series": "0",
            "index": "320",
            "xExact": "",
            "x": "321",
            "yExact": "",
            "y": "0.197247706",
            "id": "customer:1562"
          },
          {
            "series": "1",
            "index": "320",
            "xExact": "",
            "x": "321",
            "yExact": "",
            "y": "0",
            "id": "customer:1562"
          },
          {
            "series": "0",
            "index": "321",
            "xExact": "",
            "x": "322",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:1563"
          },
          {
            "series": "1",
            "index": "321",
            "xExact": "",
            "x": "322",
            "yExact": "",
            "y": "0",
            "id": "customer:1563"
          },
          {
            "series": "0",
            "index": "322",
            "xExact": "",
            "x": "323",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:1569"
          },
          {
            "series": "1",
            "index": "322",
            "xExact": "",
            "x": "323",
            "yExact": "",
            "y": "1",
            "id": "customer:1569"
          },
          {
            "series": "0",
            "index": "323",
            "xExact": "",
            "x": "324",
            "yExact": "",
            "y": "0.0377358491",
            "id": "customer:1574"
          },
          {
            "series": "1",
            "index": "323",
            "xExact": "",
            "x": "324",
            "yExact": "",
            "y": "0",
            "id": "customer:1574"
          },
          {
            "series": "0",
            "index": "324",
            "xExact": "",
            "x": "325",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:1576"
          },
          {
            "series": "1",
            "index": "324",
            "xExact": "",
            "x": "325",
            "yExact": "",
            "y": "0",
            "id": "customer:1576"
          },
          {
            "series": "0",
            "index": "325",
            "xExact": "",
            "x": "326",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:1579"
          },
          {
            "series": "1",
            "index": "325",
            "xExact": "",
            "x": "326",
            "yExact": "",
            "y": "1",
            "id": "customer:1579"
          },
          {
            "series": "0",
            "index": "326",
            "xExact": "",
            "x": "327",
            "yExact": "",
            "y": "0.958333333",
            "id": "customer:1582"
          },
          {
            "series": "1",
            "index": "326",
            "xExact": "",
            "x": "327",
            "yExact": "",
            "y": "1",
            "id": "customer:1582"
          },
          {
            "series": "0",
            "index": "327",
            "xExact": "",
            "x": "328",
            "yExact": "",
            "y": "0.0377358491",
            "id": "customer:1584"
          },
          {
            "series": "1",
            "index": "327",
            "xExact": "",
            "x": "328",
            "yExact": "",
            "y": "0",
            "id": "customer:1584"
          },
          {
            "series": "0",
            "index": "328",
            "xExact": "",
            "x": "329",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:1586"
          },
          {
            "series": "1",
            "index": "328",
            "xExact": "",
            "x": "329",
            "yExact": "",
            "y": "0",
            "id": "customer:1586"
          },
          {
            "series": "0",
            "index": "329",
            "xExact": "",
            "x": "330",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:1591"
          },
          {
            "series": "1",
            "index": "329",
            "xExact": "",
            "x": "330",
            "yExact": "",
            "y": "0",
            "id": "customer:1591"
          },
          {
            "series": "0",
            "index": "330",
            "xExact": "",
            "x": "331",
            "yExact": "",
            "y": "0.0146341463",
            "id": "customer:1597"
          },
          {
            "series": "1",
            "index": "330",
            "xExact": "",
            "x": "331",
            "yExact": "",
            "y": "0",
            "id": "customer:1597"
          },
          {
            "series": "0",
            "index": "331",
            "xExact": "",
            "x": "332",
            "yExact": "",
            "y": "0.0071942446",
            "id": "customer:1604"
          },
          {
            "series": "1",
            "index": "331",
            "xExact": "",
            "x": "332",
            "yExact": "",
            "y": "0",
            "id": "customer:1604"
          },
          {
            "series": "0",
            "index": "332",
            "xExact": "",
            "x": "333",
            "yExact": "",
            "y": "0.197247706",
            "id": "customer:1619"
          },
          {
            "series": "1",
            "index": "332",
            "xExact": "",
            "x": "333",
            "yExact": "",
            "y": "1",
            "id": "customer:1619"
          },
          {
            "series": "0",
            "index": "333",
            "xExact": "",
            "x": "334",
            "yExact": "",
            "y": "0.0071942446",
            "id": "customer:1622"
          },
          {
            "series": "1",
            "index": "333",
            "xExact": "",
            "x": "334",
            "yExact": "",
            "y": "0",
            "id": "customer:1622"
          },
          {
            "series": "0",
            "index": "334",
            "xExact": "",
            "x": "335",
            "yExact": "",
            "y": "0.958333333",
            "id": "customer:1627"
          },
          {
            "series": "1",
            "index": "334",
            "xExact": "",
            "x": "335",
            "yExact": "",
            "y": "1",
            "id": "customer:1627"
          },
          {
            "series": "0",
            "index": "335",
            "xExact": "",
            "x": "336",
            "yExact": "",
            "y": "0.0377358491",
            "id": "customer:1634"
          },
          {
            "series": "1",
            "index": "335",
            "xExact": "",
            "x": "336",
            "yExact": "",
            "y": "0",
            "id": "customer:1634"
          },
          {
            "series": "0",
            "index": "336",
            "xExact": "",
            "x": "337",
            "yExact": "",
            "y": "0.0146341463",
            "id": "customer:1636"
          },
          {
            "series": "1",
            "index": "336",
            "xExact": "",
            "x": "337",
            "yExact": "",
            "y": "0",
            "id": "customer:1636"
          },
          {
            "series": "0",
            "index": "337",
            "xExact": "",
            "x": "338",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:1645"
          },
          {
            "series": "1",
            "index": "337",
            "xExact": "",
            "x": "338",
            "yExact": "",
            "y": "0",
            "id": "customer:1645"
          },
          {
            "series": "0",
            "index": "338",
            "xExact": "",
            "x": "339",
            "yExact": "",
            "y": "0.0377358491",
            "id": "customer:1646"
          },
          {
            "series": "1",
            "index": "338",
            "xExact": "",
            "x": "339",
            "yExact": "",
            "y": "0",
            "id": "customer:1646"
          },
          {
            "series": "0",
            "index": "339",
            "xExact": "",
            "x": "340",
            "yExact": "",
            "y": "0.0146341463",
            "id": "customer:1649"
          },
          {
            "series": "1",
            "index": "339",
            "xExact": "",
            "x": "340",
            "yExact": "",
            "y": "0",
            "id": "customer:1649"
          },
          {
            "series": "0",
            "index": "340",
            "xExact": "",
            "x": "341",
            "yExact": "",
            "y": "0.0377358491",
            "id": "customer:1658"
          },
          {
            "series": "1",
            "index": "340",
            "xExact": "",
            "x": "341",
            "yExact": "",
            "y": "0",
            "id": "customer:1658"
          },
          {
            "series": "0",
            "index": "341",
            "xExact": "",
            "x": "342",
            "yExact": "",
            "y": "0.0146341463",
            "id": "customer:1661"
          },
          {
            "series": "1",
            "index": "341",
            "xExact": "",
            "x": "342",
            "yExact": "",
            "y": "0",
            "id": "customer:1661"
          },
          {
            "series": "0",
            "index": "342",
            "xExact": "",
            "x": "343",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:1662"
          },
          {
            "series": "1",
            "index": "342",
            "xExact": "",
            "x": "343",
            "yExact": "",
            "y": "0",
            "id": "customer:1662"
          },
          {
            "series": "0",
            "index": "343",
            "xExact": "",
            "x": "344",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:1664"
          },
          {
            "series": "1",
            "index": "343",
            "xExact": "",
            "x": "344",
            "yExact": "",
            "y": "0",
            "id": "customer:1664"
          },
          {
            "series": "0",
            "index": "344",
            "xExact": "",
            "x": "345",
            "yExact": "",
            "y": "0.0146341463",
            "id": "customer:1672"
          },
          {
            "series": "1",
            "index": "344",
            "xExact": "",
            "x": "345",
            "yExact": "",
            "y": "0",
            "id": "customer:1672"
          },
          {
            "series": "0",
            "index": "345",
            "xExact": "",
            "x": "346",
            "yExact": "",
            "y": "0.0377358491",
            "id": "customer:1675"
          },
          {
            "series": "1",
            "index": "345",
            "xExact": "",
            "x": "346",
            "yExact": "",
            "y": "1",
            "id": "customer:1675"
          },
          {
            "series": "0",
            "index": "346",
            "xExact": "",
            "x": "347",
            "yExact": "",
            "y": "0.0146341463",
            "id": "customer:1685"
          },
          {
            "series": "1",
            "index": "346",
            "xExact": "",
            "x": "347",
            "yExact": "",
            "y": "0",
            "id": "customer:1685"
          },
          {
            "series": "0",
            "index": "347",
            "xExact": "",
            "x": "348",
            "yExact": "",
            "y": "0.0146341463",
            "id": "customer:1699"
          },
          {
            "series": "1",
            "index": "347",
            "xExact": "",
            "x": "348",
            "yExact": "",
            "y": "0",
            "id": "customer:1699"
          },
          {
            "series": "0",
            "index": "348",
            "xExact": "",
            "x": "349",
            "yExact": "",
            "y": "0.0146341463",
            "id": "customer:1716"
          },
          {
            "series": "1",
            "index": "348",
            "xExact": "",
            "x": "349",
            "yExact": "",
            "y": "0",
            "id": "customer:1716"
          },
          {
            "series": "0",
            "index": "349",
            "xExact": "",
            "x": "350",
            "yExact": "",
            "y": "0.0146341463",
            "id": "customer:1720"
          },
          {
            "series": "1",
            "index": "349",
            "xExact": "",
            "x": "350",
            "yExact": "",
            "y": "0",
            "id": "customer:1720"
          },
          {
            "series": "0",
            "index": "350",
            "xExact": "",
            "x": "351",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:1729"
          },
          {
            "series": "1",
            "index": "350",
            "xExact": "",
            "x": "351",
            "yExact": "",
            "y": "1",
            "id": "customer:1729"
          },
          {
            "series": "0",
            "index": "351",
            "xExact": "",
            "x": "352",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:1733"
          },
          {
            "series": "1",
            "index": "351",
            "xExact": "",
            "x": "352",
            "yExact": "",
            "y": "0",
            "id": "customer:1733"
          },
          {
            "series": "0",
            "index": "352",
            "xExact": "",
            "x": "353",
            "yExact": "",
            "y": "0.0146341463",
            "id": "customer:1735"
          },
          {
            "series": "1",
            "index": "352",
            "xExact": "",
            "x": "353",
            "yExact": "",
            "y": "0",
            "id": "customer:1735"
          },
          {
            "series": "0",
            "index": "353",
            "xExact": "",
            "x": "354",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:1739"
          },
          {
            "series": "1",
            "index": "353",
            "xExact": "",
            "x": "354",
            "yExact": "",
            "y": "0",
            "id": "customer:1739"
          },
          {
            "series": "0",
            "index": "354",
            "xExact": "",
            "x": "355",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:1745"
          },
          {
            "series": "1",
            "index": "354",
            "xExact": "",
            "x": "355",
            "yExact": "",
            "y": "0",
            "id": "customer:1745"
          },
          {
            "series": "0",
            "index": "355",
            "xExact": "",
            "x": "356",
            "yExact": "",
            "y": "0.0146341463",
            "id": "customer:1749"
          },
          {
            "series": "1",
            "index": "355",
            "xExact": "",
            "x": "356",
            "yExact": "",
            "y": "0",
            "id": "customer:1749"
          },
          {
            "series": "0",
            "index": "356",
            "xExact": "",
            "x": "357",
            "yExact": "",
            "y": "0.958333333",
            "id": "customer:1750"
          },
          {
            "series": "1",
            "index": "356",
            "xExact": "",
            "x": "357",
            "yExact": "",
            "y": "1",
            "id": "customer:1750"
          },
          {
            "series": "0",
            "index": "357",
            "xExact": "",
            "x": "358",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:1753"
          },
          {
            "series": "1",
            "index": "357",
            "xExact": "",
            "x": "358",
            "yExact": "",
            "y": "0",
            "id": "customer:1753"
          },
          {
            "series": "0",
            "index": "358",
            "xExact": "",
            "x": "359",
            "yExact": "",
            "y": "0.0071942446",
            "id": "customer:1759"
          },
          {
            "series": "1",
            "index": "358",
            "xExact": "",
            "x": "359",
            "yExact": "",
            "y": "0",
            "id": "customer:1759"
          },
          {
            "series": "0",
            "index": "359",
            "xExact": "",
            "x": "360",
            "yExact": "",
            "y": "0.0146341463",
            "id": "customer:1765"
          },
          {
            "series": "1",
            "index": "359",
            "xExact": "",
            "x": "360",
            "yExact": "",
            "y": "0",
            "id": "customer:1765"
          },
          {
            "series": "0",
            "index": "360",
            "xExact": "",
            "x": "361",
            "yExact": "",
            "y": "0.197247706",
            "id": "customer:1768"
          },
          {
            "series": "1",
            "index": "360",
            "xExact": "",
            "x": "361",
            "yExact": "",
            "y": "0",
            "id": "customer:1768"
          },
          {
            "series": "0",
            "index": "361",
            "xExact": "",
            "x": "362",
            "yExact": "",
            "y": "0.0146341463",
            "id": "customer:1770"
          },
          {
            "series": "1",
            "index": "361",
            "xExact": "",
            "x": "362",
            "yExact": "",
            "y": "0",
            "id": "customer:1770"
          },
          {
            "series": "0",
            "index": "362",
            "xExact": "",
            "x": "363",
            "yExact": "",
            "y": "0.0146341463",
            "id": "customer:1772"
          },
          {
            "series": "1",
            "index": "362",
            "xExact": "",
            "x": "363",
            "yExact": "",
            "y": "0",
            "id": "customer:1772"
          },
          {
            "series": "0",
            "index": "363",
            "xExact": "",
            "x": "364",
            "yExact": "",
            "y": "0.0377358491",
            "id": "customer:1784"
          },
          {
            "series": "1",
            "index": "363",
            "xExact": "",
            "x": "364",
            "yExact": "",
            "y": "0",
            "id": "customer:1784"
          },
          {
            "series": "0",
            "index": "364",
            "xExact": "",
            "x": "365",
            "yExact": "",
            "y": "0.0146341463",
            "id": "customer:1786"
          },
          {
            "series": "1",
            "index": "364",
            "xExact": "",
            "x": "365",
            "yExact": "",
            "y": "0",
            "id": "customer:1786"
          },
          {
            "series": "0",
            "index": "365",
            "xExact": "",
            "x": "366",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:1787"
          },
          {
            "series": "1",
            "index": "365",
            "xExact": "",
            "x": "366",
            "yExact": "",
            "y": "0",
            "id": "customer:1787"
          },
          {
            "series": "0",
            "index": "366",
            "xExact": "",
            "x": "367",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:1792"
          },
          {
            "series": "1",
            "index": "366",
            "xExact": "",
            "x": "367",
            "yExact": "",
            "y": "0",
            "id": "customer:1792"
          },
          {
            "series": "0",
            "index": "367",
            "xExact": "",
            "x": "368",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:1794"
          },
          {
            "series": "1",
            "index": "367",
            "xExact": "",
            "x": "368",
            "yExact": "",
            "y": "0",
            "id": "customer:1794"
          },
          {
            "series": "0",
            "index": "368",
            "xExact": "",
            "x": "369",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:1795"
          },
          {
            "series": "1",
            "index": "368",
            "xExact": "",
            "x": "369",
            "yExact": "",
            "y": "0",
            "id": "customer:1795"
          },
          {
            "series": "0",
            "index": "369",
            "xExact": "",
            "x": "370",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:1798"
          },
          {
            "series": "1",
            "index": "369",
            "xExact": "",
            "x": "370",
            "yExact": "",
            "y": "0",
            "id": "customer:1798"
          },
          {
            "series": "0",
            "index": "370",
            "xExact": "",
            "x": "371",
            "yExact": "",
            "y": "0.0146341463",
            "id": "customer:1799"
          },
          {
            "series": "1",
            "index": "370",
            "xExact": "",
            "x": "371",
            "yExact": "",
            "y": "0",
            "id": "customer:1799"
          },
          {
            "series": "0",
            "index": "371",
            "xExact": "",
            "x": "372",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:1803"
          },
          {
            "series": "1",
            "index": "371",
            "xExact": "",
            "x": "372",
            "yExact": "",
            "y": "0",
            "id": "customer:1803"
          },
          {
            "series": "0",
            "index": "372",
            "xExact": "",
            "x": "373",
            "yExact": "",
            "y": "0.0146341463",
            "id": "customer:1808"
          },
          {
            "series": "1",
            "index": "372",
            "xExact": "",
            "x": "373",
            "yExact": "",
            "y": "0",
            "id": "customer:1808"
          },
          {
            "series": "0",
            "index": "373",
            "xExact": "",
            "x": "374",
            "yExact": "",
            "y": "0.173913043",
            "id": "customer:1823"
          },
          {
            "series": "1",
            "index": "373",
            "xExact": "",
            "x": "374",
            "yExact": "",
            "y": "1",
            "id": "customer:1823"
          },
          {
            "series": "0",
            "index": "374",
            "xExact": "",
            "x": "375",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:1827"
          },
          {
            "series": "1",
            "index": "374",
            "xExact": "",
            "x": "375",
            "yExact": "",
            "y": "1",
            "id": "customer:1827"
          },
          {
            "series": "0",
            "index": "375",
            "xExact": "",
            "x": "376",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:1828"
          },
          {
            "series": "1",
            "index": "375",
            "xExact": "",
            "x": "376",
            "yExact": "",
            "y": "1",
            "id": "customer:1828"
          },
          {
            "series": "0",
            "index": "376",
            "xExact": "",
            "x": "377",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:1832"
          },
          {
            "series": "1",
            "index": "376",
            "xExact": "",
            "x": "377",
            "yExact": "",
            "y": "1",
            "id": "customer:1832"
          },
          {
            "series": "0",
            "index": "377",
            "xExact": "",
            "x": "378",
            "yExact": "",
            "y": "0.0377358491",
            "id": "customer:1834"
          },
          {
            "series": "1",
            "index": "377",
            "xExact": "",
            "x": "378",
            "yExact": "",
            "y": "0",
            "id": "customer:1834"
          },
          {
            "series": "0",
            "index": "378",
            "xExact": "",
            "x": "379",
            "yExact": "",
            "y": "0.0146341463",
            "id": "customer:1836"
          },
          {
            "series": "1",
            "index": "378",
            "xExact": "",
            "x": "379",
            "yExact": "",
            "y": "0",
            "id": "customer:1836"
          },
          {
            "series": "0",
            "index": "379",
            "xExact": "",
            "x": "380",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:1837"
          },
          {
            "series": "1",
            "index": "379",
            "xExact": "",
            "x": "380",
            "yExact": "",
            "y": "0",
            "id": "customer:1837"
          },
          {
            "series": "0",
            "index": "380",
            "xExact": "",
            "x": "381",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:1839"
          },
          {
            "series": "1",
            "index": "380",
            "xExact": "",
            "x": "381",
            "yExact": "",
            "y": "0",
            "id": "customer:1839"
          },
          {
            "series": "0",
            "index": "381",
            "xExact": "",
            "x": "382",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:1844"
          },
          {
            "series": "1",
            "index": "381",
            "xExact": "",
            "x": "382",
            "yExact": "",
            "y": "0",
            "id": "customer:1844"
          },
          {
            "series": "0",
            "index": "382",
            "xExact": "",
            "x": "383",
            "yExact": "",
            "y": "0.197247706",
            "id": "customer:1852"
          },
          {
            "series": "1",
            "index": "382",
            "xExact": "",
            "x": "383",
            "yExact": "",
            "y": "0",
            "id": "customer:1852"
          },
          {
            "series": "0",
            "index": "383",
            "xExact": "",
            "x": "384",
            "yExact": "",
            "y": "0.151785714",
            "id": "customer:1853"
          },
          {
            "series": "1",
            "index": "383",
            "xExact": "",
            "x": "384",
            "yExact": "",
            "y": "0",
            "id": "customer:1853"
          },
          {
            "series": "0",
            "index": "384",
            "xExact": "",
            "x": "385",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:1858"
          },
          {
            "series": "1",
            "index": "384",
            "xExact": "",
            "x": "385",
            "yExact": "",
            "y": "0",
            "id": "customer:1858"
          },
          {
            "series": "0",
            "index": "385",
            "xExact": "",
            "x": "386",
            "yExact": "",
            "y": "0.0071942446",
            "id": "customer:1861"
          },
          {
            "series": "1",
            "index": "385",
            "xExact": "",
            "x": "386",
            "yExact": "",
            "y": "0",
            "id": "customer:1861"
          },
          {
            "series": "0",
            "index": "386",
            "xExact": "",
            "x": "387",
            "yExact": "",
            "y": "0.197247706",
            "id": "customer:1862"
          },
          {
            "series": "1",
            "index": "386",
            "xExact": "",
            "x": "387",
            "yExact": "",
            "y": "0",
            "id": "customer:1862"
          },
          {
            "series": "0",
            "index": "387",
            "xExact": "",
            "x": "388",
            "yExact": "",
            "y": "0.0071942446",
            "id": "customer:1871"
          },
          {
            "series": "1",
            "index": "387",
            "xExact": "",
            "x": "388",
            "yExact": "",
            "y": "0",
            "id": "customer:1871"
          },
          {
            "series": "0",
            "index": "388",
            "xExact": "",
            "x": "389",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:1875"
          },
          {
            "series": "1",
            "index": "388",
            "xExact": "",
            "x": "389",
            "yExact": "",
            "y": "1",
            "id": "customer:1875"
          },
          {
            "series": "0",
            "index": "389",
            "xExact": "",
            "x": "390",
            "yExact": "",
            "y": "0.197247706",
            "id": "customer:1883"
          },
          {
            "series": "1",
            "index": "389",
            "xExact": "",
            "x": "390",
            "yExact": "",
            "y": "0",
            "id": "customer:1883"
          },
          {
            "series": "0",
            "index": "390",
            "xExact": "",
            "x": "391",
            "yExact": "",
            "y": "0.0071942446",
            "id": "customer:1886"
          },
          {
            "series": "1",
            "index": "390",
            "xExact": "",
            "x": "391",
            "yExact": "",
            "y": "0",
            "id": "customer:1886"
          },
          {
            "series": "0",
            "index": "391",
            "xExact": "",
            "x": "392",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:1892"
          },
          {
            "series": "1",
            "index": "391",
            "xExact": "",
            "x": "392",
            "yExact": "",
            "y": "0",
            "id": "customer:1892"
          },
          {
            "series": "0",
            "index": "392",
            "xExact": "",
            "x": "393",
            "yExact": "",
            "y": "0.173913043",
            "id": "customer:1893"
          },
          {
            "series": "1",
            "index": "392",
            "xExact": "",
            "x": "393",
            "yExact": "",
            "y": "0",
            "id": "customer:1893"
          },
          {
            "series": "0",
            "index": "393",
            "xExact": "",
            "x": "394",
            "yExact": "",
            "y": "0.0377358491",
            "id": "customer:1896"
          },
          {
            "series": "1",
            "index": "393",
            "xExact": "",
            "x": "394",
            "yExact": "",
            "y": "0",
            "id": "customer:1896"
          },
          {
            "series": "0",
            "index": "394",
            "xExact": "",
            "x": "395",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:1898"
          },
          {
            "series": "1",
            "index": "394",
            "xExact": "",
            "x": "395",
            "yExact": "",
            "y": "0",
            "id": "customer:1898"
          },
          {
            "series": "0",
            "index": "395",
            "xExact": "",
            "x": "396",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:1908"
          },
          {
            "series": "1",
            "index": "395",
            "xExact": "",
            "x": "396",
            "yExact": "",
            "y": "0",
            "id": "customer:1908"
          },
          {
            "series": "0",
            "index": "396",
            "xExact": "",
            "x": "397",
            "yExact": "",
            "y": "0.0377358491",
            "id": "customer:1927"
          },
          {
            "series": "1",
            "index": "396",
            "xExact": "",
            "x": "397",
            "yExact": "",
            "y": "1",
            "id": "customer:1927"
          },
          {
            "series": "0",
            "index": "397",
            "xExact": "",
            "x": "398",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:1933"
          },
          {
            "series": "1",
            "index": "397",
            "xExact": "",
            "x": "398",
            "yExact": "",
            "y": "0",
            "id": "customer:1933"
          },
          {
            "series": "0",
            "index": "398",
            "xExact": "",
            "x": "399",
            "yExact": "",
            "y": "0.0377358491",
            "id": "customer:1938"
          },
          {
            "series": "1",
            "index": "398",
            "xExact": "",
            "x": "399",
            "yExact": "",
            "y": "0",
            "id": "customer:1938"
          },
          {
            "series": "0",
            "index": "399",
            "xExact": "",
            "x": "400",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:1940"
          },
          {
            "series": "1",
            "index": "399",
            "xExact": "",
            "x": "400",
            "yExact": "",
            "y": "0",
            "id": "customer:1940"
          },
          {
            "series": "0",
            "index": "400",
            "xExact": "",
            "x": "401",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:1955"
          },
          {
            "series": "1",
            "index": "400",
            "xExact": "",
            "x": "401",
            "yExact": "",
            "y": "0",
            "id": "customer:1955"
          },
          {
            "series": "0",
            "index": "401",
            "xExact": "",
            "x": "402",
            "yExact": "",
            "y": "0.0146341463",
            "id": "customer:1959"
          },
          {
            "series": "1",
            "index": "401",
            "xExact": "",
            "x": "402",
            "yExact": "",
            "y": "0",
            "id": "customer:1959"
          },
          {
            "series": "0",
            "index": "402",
            "xExact": "",
            "x": "403",
            "yExact": "",
            "y": "0.0146341463",
            "id": "customer:1966"
          },
          {
            "series": "1",
            "index": "402",
            "xExact": "",
            "x": "403",
            "yExact": "",
            "y": "0",
            "id": "customer:1966"
          },
          {
            "series": "0",
            "index": "403",
            "xExact": "",
            "x": "404",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:1969"
          },
          {
            "series": "1",
            "index": "403",
            "xExact": "",
            "x": "404",
            "yExact": "",
            "y": "1",
            "id": "customer:1969"
          },
          {
            "series": "0",
            "index": "404",
            "xExact": "",
            "x": "405",
            "yExact": "",
            "y": "0.0377358491",
            "id": "customer:1974"
          },
          {
            "series": "1",
            "index": "404",
            "xExact": "",
            "x": "405",
            "yExact": "",
            "y": "0",
            "id": "customer:1974"
          },
          {
            "series": "0",
            "index": "405",
            "xExact": "",
            "x": "406",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:1980"
          },
          {
            "series": "1",
            "index": "405",
            "xExact": "",
            "x": "406",
            "yExact": "",
            "y": "0",
            "id": "customer:1980"
          },
          {
            "series": "0",
            "index": "406",
            "xExact": "",
            "x": "407",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:1983"
          },
          {
            "series": "1",
            "index": "406",
            "xExact": "",
            "x": "407",
            "yExact": "",
            "y": "0",
            "id": "customer:1983"
          },
          {
            "series": "0",
            "index": "407",
            "xExact": "",
            "x": "408",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:1987"
          },
          {
            "series": "1",
            "index": "407",
            "xExact": "",
            "x": "408",
            "yExact": "",
            "y": "0",
            "id": "customer:1987"
          },
          {
            "series": "0",
            "index": "408",
            "xExact": "",
            "x": "409",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:1991"
          },
          {
            "series": "1",
            "index": "408",
            "xExact": "",
            "x": "409",
            "yExact": "",
            "y": "0",
            "id": "customer:1991"
          },
          {
            "series": "0",
            "index": "409",
            "xExact": "",
            "x": "410",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:1994"
          },
          {
            "series": "1",
            "index": "409",
            "xExact": "",
            "x": "410",
            "yExact": "",
            "y": "0",
            "id": "customer:1994"
          },
          {
            "series": "0",
            "index": "410",
            "xExact": "",
            "x": "411",
            "yExact": "",
            "y": "0.197247706",
            "id": "customer:2007"
          },
          {
            "series": "1",
            "index": "410",
            "xExact": "",
            "x": "411",
            "yExact": "",
            "y": "0",
            "id": "customer:2007"
          },
          {
            "series": "0",
            "index": "411",
            "xExact": "",
            "x": "412",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:2027"
          },
          {
            "series": "1",
            "index": "411",
            "xExact": "",
            "x": "412",
            "yExact": "",
            "y": "1",
            "id": "customer:2027"
          },
          {
            "series": "0",
            "index": "412",
            "xExact": "",
            "x": "413",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:2029"
          },
          {
            "series": "1",
            "index": "412",
            "xExact": "",
            "x": "413",
            "yExact": "",
            "y": "1",
            "id": "customer:2029"
          },
          {
            "series": "0",
            "index": "413",
            "xExact": "",
            "x": "414",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:2053"
          },
          {
            "series": "1",
            "index": "413",
            "xExact": "",
            "x": "414",
            "yExact": "",
            "y": "0",
            "id": "customer:2053"
          },
          {
            "series": "0",
            "index": "414",
            "xExact": "",
            "x": "415",
            "yExact": "",
            "y": "0.197247706",
            "id": "customer:2055"
          },
          {
            "series": "1",
            "index": "414",
            "xExact": "",
            "x": "415",
            "yExact": "",
            "y": "0",
            "id": "customer:2055"
          },
          {
            "series": "0",
            "index": "415",
            "xExact": "",
            "x": "416",
            "yExact": "",
            "y": "0.197247706",
            "id": "customer:2057"
          },
          {
            "series": "1",
            "index": "415",
            "xExact": "",
            "x": "416",
            "yExact": "",
            "y": "0",
            "id": "customer:2057"
          },
          {
            "series": "0",
            "index": "416",
            "xExact": "",
            "x": "417",
            "yExact": "",
            "y": "0.0377358491",
            "id": "customer:2058"
          },
          {
            "series": "1",
            "index": "416",
            "xExact": "",
            "x": "417",
            "yExact": "",
            "y": "0",
            "id": "customer:2058"
          },
          {
            "series": "0",
            "index": "417",
            "xExact": "",
            "x": "418",
            "yExact": "",
            "y": "0.0146341463",
            "id": "customer:2066"
          },
          {
            "series": "1",
            "index": "417",
            "xExact": "",
            "x": "418",
            "yExact": "",
            "y": "0",
            "id": "customer:2066"
          },
          {
            "series": "0",
            "index": "418",
            "xExact": "",
            "x": "419",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:2067"
          },
          {
            "series": "1",
            "index": "418",
            "xExact": "",
            "x": "419",
            "yExact": "",
            "y": "0",
            "id": "customer:2067"
          },
          {
            "series": "0",
            "index": "419",
            "xExact": "",
            "x": "420",
            "yExact": "",
            "y": "0.197247706",
            "id": "customer:2068"
          },
          {
            "series": "1",
            "index": "419",
            "xExact": "",
            "x": "420",
            "yExact": "",
            "y": "0",
            "id": "customer:2068"
          },
          {
            "series": "0",
            "index": "420",
            "xExact": "",
            "x": "421",
            "yExact": "",
            "y": "0.0146341463",
            "id": "customer:2070"
          },
          {
            "series": "1",
            "index": "420",
            "xExact": "",
            "x": "421",
            "yExact": "",
            "y": "0",
            "id": "customer:2070"
          },
          {
            "series": "0",
            "index": "421",
            "xExact": "",
            "x": "422",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:2078"
          },
          {
            "series": "1",
            "index": "421",
            "xExact": "",
            "x": "422",
            "yExact": "",
            "y": "1",
            "id": "customer:2078"
          },
          {
            "series": "0",
            "index": "422",
            "xExact": "",
            "x": "423",
            "yExact": "",
            "y": "0.0146341463",
            "id": "customer:2086"
          },
          {
            "series": "1",
            "index": "422",
            "xExact": "",
            "x": "423",
            "yExact": "",
            "y": "0",
            "id": "customer:2086"
          },
          {
            "series": "0",
            "index": "423",
            "xExact": "",
            "x": "424",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:2089"
          },
          {
            "series": "1",
            "index": "423",
            "xExact": "",
            "x": "424",
            "yExact": "",
            "y": "0",
            "id": "customer:2089"
          },
          {
            "series": "0",
            "index": "424",
            "xExact": "",
            "x": "425",
            "yExact": "",
            "y": "0.0377358491",
            "id": "customer:2097"
          },
          {
            "series": "1",
            "index": "424",
            "xExact": "",
            "x": "425",
            "yExact": "",
            "y": "0",
            "id": "customer:2097"
          },
          {
            "series": "0",
            "index": "425",
            "xExact": "",
            "x": "426",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:2100"
          },
          {
            "series": "1",
            "index": "425",
            "xExact": "",
            "x": "426",
            "yExact": "",
            "y": "1",
            "id": "customer:2100"
          },
          {
            "series": "0",
            "index": "426",
            "xExact": "",
            "x": "427",
            "yExact": "",
            "y": "0.151785714",
            "id": "customer:2103"
          },
          {
            "series": "1",
            "index": "426",
            "xExact": "",
            "x": "427",
            "yExact": "",
            "y": "0",
            "id": "customer:2103"
          },
          {
            "series": "0",
            "index": "427",
            "xExact": "",
            "x": "428",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:2104"
          },
          {
            "series": "1",
            "index": "427",
            "xExact": "",
            "x": "428",
            "yExact": "",
            "y": "0",
            "id": "customer:2104"
          },
          {
            "series": "0",
            "index": "428",
            "xExact": "",
            "x": "429",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:2106"
          },
          {
            "series": "1",
            "index": "428",
            "xExact": "",
            "x": "429",
            "yExact": "",
            "y": "0",
            "id": "customer:2106"
          },
          {
            "series": "0",
            "index": "429",
            "xExact": "",
            "x": "430",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:2110"
          },
          {
            "series": "1",
            "index": "429",
            "xExact": "",
            "x": "430",
            "yExact": "",
            "y": "0",
            "id": "customer:2110"
          },
          {
            "series": "0",
            "index": "430",
            "xExact": "",
            "x": "431",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:2114"
          },
          {
            "series": "1",
            "index": "430",
            "xExact": "",
            "x": "431",
            "yExact": "",
            "y": "0",
            "id": "customer:2114"
          },
          {
            "series": "0",
            "index": "431",
            "xExact": "",
            "x": "432",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:2122"
          },
          {
            "series": "1",
            "index": "431",
            "xExact": "",
            "x": "432",
            "yExact": "",
            "y": "0",
            "id": "customer:2122"
          },
          {
            "series": "0",
            "index": "432",
            "xExact": "",
            "x": "433",
            "yExact": "",
            "y": "0.151785714",
            "id": "customer:2157"
          },
          {
            "series": "1",
            "index": "432",
            "xExact": "",
            "x": "433",
            "yExact": "",
            "y": "0",
            "id": "customer:2157"
          },
          {
            "series": "0",
            "index": "433",
            "xExact": "",
            "x": "434",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:2158"
          },
          {
            "series": "1",
            "index": "433",
            "xExact": "",
            "x": "434",
            "yExact": "",
            "y": "0",
            "id": "customer:2158"
          },
          {
            "series": "0",
            "index": "434",
            "xExact": "",
            "x": "435",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:2161"
          },
          {
            "series": "1",
            "index": "434",
            "xExact": "",
            "x": "435",
            "yExact": "",
            "y": "0",
            "id": "customer:2161"
          },
          {
            "series": "0",
            "index": "435",
            "xExact": "",
            "x": "436",
            "yExact": "",
            "y": "0.151785714",
            "id": "customer:2167"
          },
          {
            "series": "1",
            "index": "435",
            "xExact": "",
            "x": "436",
            "yExact": "",
            "y": "0",
            "id": "customer:2167"
          },
          {
            "series": "0",
            "index": "436",
            "xExact": "",
            "x": "437",
            "yExact": "",
            "y": "0.151785714",
            "id": "customer:2169"
          },
          {
            "series": "1",
            "index": "436",
            "xExact": "",
            "x": "437",
            "yExact": "",
            "y": "1",
            "id": "customer:2169"
          },
          {
            "series": "0",
            "index": "437",
            "xExact": "",
            "x": "438",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:2172"
          },
          {
            "series": "1",
            "index": "437",
            "xExact": "",
            "x": "438",
            "yExact": "",
            "y": "0",
            "id": "customer:2172"
          },
          {
            "series": "0",
            "index": "438",
            "xExact": "",
            "x": "439",
            "yExact": "",
            "y": "0.586206897",
            "id": "customer:2173"
          },
          {
            "series": "1",
            "index": "438",
            "xExact": "",
            "x": "439",
            "yExact": "",
            "y": "1",
            "id": "customer:2173"
          },
          {
            "series": "0",
            "index": "439",
            "xExact": "",
            "x": "440",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:2175"
          },
          {
            "series": "1",
            "index": "439",
            "xExact": "",
            "x": "440",
            "yExact": "",
            "y": "0",
            "id": "customer:2175"
          },
          {
            "series": "0",
            "index": "440",
            "xExact": "",
            "x": "441",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:2176"
          },
          {
            "series": "1",
            "index": "440",
            "xExact": "",
            "x": "441",
            "yExact": "",
            "y": "0",
            "id": "customer:2176"
          },
          {
            "series": "0",
            "index": "441",
            "xExact": "",
            "x": "442",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:2186"
          },
          {
            "series": "1",
            "index": "441",
            "xExact": "",
            "x": "442",
            "yExact": "",
            "y": "0",
            "id": "customer:2186"
          },
          {
            "series": "0",
            "index": "442",
            "xExact": "",
            "x": "443",
            "yExact": "",
            "y": "0.173913043",
            "id": "customer:2189"
          },
          {
            "series": "1",
            "index": "442",
            "xExact": "",
            "x": "443",
            "yExact": "",
            "y": "0",
            "id": "customer:2189"
          },
          {
            "series": "0",
            "index": "443",
            "xExact": "",
            "x": "444",
            "yExact": "",
            "y": "0.197247706",
            "id": "customer:2202"
          },
          {
            "series": "1",
            "index": "443",
            "xExact": "",
            "x": "444",
            "yExact": "",
            "y": "0",
            "id": "customer:2202"
          },
          {
            "series": "0",
            "index": "444",
            "xExact": "",
            "x": "445",
            "yExact": "",
            "y": "0.151785714",
            "id": "customer:2203"
          },
          {
            "series": "1",
            "index": "444",
            "xExact": "",
            "x": "445",
            "yExact": "",
            "y": "0",
            "id": "customer:2203"
          },
          {
            "series": "0",
            "index": "445",
            "xExact": "",
            "x": "446",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:2209"
          },
          {
            "series": "1",
            "index": "445",
            "xExact": "",
            "x": "446",
            "yExact": "",
            "y": "0",
            "id": "customer:2209"
          },
          {
            "series": "0",
            "index": "446",
            "xExact": "",
            "x": "447",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:2210"
          },
          {
            "series": "1",
            "index": "446",
            "xExact": "",
            "x": "447",
            "yExact": "",
            "y": "0",
            "id": "customer:2210"
          },
          {
            "series": "0",
            "index": "447",
            "xExact": "",
            "x": "448",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:2211"
          },
          {
            "series": "1",
            "index": "447",
            "xExact": "",
            "x": "448",
            "yExact": "",
            "y": "0",
            "id": "customer:2211"
          },
          {
            "series": "0",
            "index": "448",
            "xExact": "",
            "x": "449",
            "yExact": "",
            "y": "0.151785714",
            "id": "customer:2212"
          },
          {
            "series": "1",
            "index": "448",
            "xExact": "",
            "x": "449",
            "yExact": "",
            "y": "0",
            "id": "customer:2212"
          },
          {
            "series": "0",
            "index": "449",
            "xExact": "",
            "x": "450",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:2213"
          },
          {
            "series": "1",
            "index": "449",
            "xExact": "",
            "x": "450",
            "yExact": "",
            "y": "0",
            "id": "customer:2213"
          },
          {
            "series": "0",
            "index": "450",
            "xExact": "",
            "x": "451",
            "yExact": "",
            "y": "0.0071942446",
            "id": "customer:2216"
          },
          {
            "series": "1",
            "index": "450",
            "xExact": "",
            "x": "451",
            "yExact": "",
            "y": "0",
            "id": "customer:2216"
          },
          {
            "series": "0",
            "index": "451",
            "xExact": "",
            "x": "452",
            "yExact": "",
            "y": "0.197247706",
            "id": "customer:2217"
          },
          {
            "series": "1",
            "index": "451",
            "xExact": "",
            "x": "452",
            "yExact": "",
            "y": "0",
            "id": "customer:2217"
          },
          {
            "series": "0",
            "index": "452",
            "xExact": "",
            "x": "453",
            "yExact": "",
            "y": "0.197247706",
            "id": "customer:2219"
          },
          {
            "series": "1",
            "index": "452",
            "xExact": "",
            "x": "453",
            "yExact": "",
            "y": "1",
            "id": "customer:2219"
          },
          {
            "series": "0",
            "index": "453",
            "xExact": "",
            "x": "454",
            "yExact": "",
            "y": "0.197247706",
            "id": "customer:2233"
          },
          {
            "series": "1",
            "index": "453",
            "xExact": "",
            "x": "454",
            "yExact": "",
            "y": "0",
            "id": "customer:2233"
          },
          {
            "series": "0",
            "index": "454",
            "xExact": "",
            "x": "455",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:2239"
          },
          {
            "series": "1",
            "index": "454",
            "xExact": "",
            "x": "455",
            "yExact": "",
            "y": "0",
            "id": "customer:2239"
          },
          {
            "series": "0",
            "index": "455",
            "xExact": "",
            "x": "456",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:2245"
          },
          {
            "series": "1",
            "index": "455",
            "xExact": "",
            "x": "456",
            "yExact": "",
            "y": "0",
            "id": "customer:2245"
          },
          {
            "series": "0",
            "index": "456",
            "xExact": "",
            "x": "457",
            "yExact": "",
            "y": "0.0377358491",
            "id": "customer:2246"
          },
          {
            "series": "1",
            "index": "456",
            "xExact": "",
            "x": "457",
            "yExact": "",
            "y": "0",
            "id": "customer:2246"
          },
          {
            "series": "0",
            "index": "457",
            "xExact": "",
            "x": "458",
            "yExact": "",
            "y": "0.197247706",
            "id": "customer:2252"
          },
          {
            "series": "1",
            "index": "457",
            "xExact": "",
            "x": "458",
            "yExact": "",
            "y": "0",
            "id": "customer:2252"
          },
          {
            "series": "0",
            "index": "458",
            "xExact": "",
            "x": "459",
            "yExact": "",
            "y": "0.151785714",
            "id": "customer:2257"
          },
          {
            "series": "1",
            "index": "458",
            "xExact": "",
            "x": "459",
            "yExact": "",
            "y": "0",
            "id": "customer:2257"
          },
          {
            "series": "0",
            "index": "459",
            "xExact": "",
            "x": "460",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:2258"
          },
          {
            "series": "1",
            "index": "459",
            "xExact": "",
            "x": "460",
            "yExact": "",
            "y": "0",
            "id": "customer:2258"
          },
          {
            "series": "0",
            "index": "460",
            "xExact": "",
            "x": "461",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:2263"
          },
          {
            "series": "1",
            "index": "460",
            "xExact": "",
            "x": "461",
            "yExact": "",
            "y": "0",
            "id": "customer:2263"
          },
          {
            "series": "0",
            "index": "461",
            "xExact": "",
            "x": "462",
            "yExact": "",
            "y": "0.151785714",
            "id": "customer:2268"
          },
          {
            "series": "1",
            "index": "461",
            "xExact": "",
            "x": "462",
            "yExact": "",
            "y": "0",
            "id": "customer:2268"
          },
          {
            "series": "0",
            "index": "462",
            "xExact": "",
            "x": "463",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:2275"
          },
          {
            "series": "1",
            "index": "462",
            "xExact": "",
            "x": "463",
            "yExact": "",
            "y": "0",
            "id": "customer:2275"
          },
          {
            "series": "0",
            "index": "463",
            "xExact": "",
            "x": "464",
            "yExact": "",
            "y": "0.586206897",
            "id": "customer:2277"
          },
          {
            "series": "1",
            "index": "463",
            "xExact": "",
            "x": "464",
            "yExact": "",
            "y": "1",
            "id": "customer:2277"
          },
          {
            "series": "0",
            "index": "464",
            "xExact": "",
            "x": "465",
            "yExact": "",
            "y": "0.586206897",
            "id": "customer:2278"
          },
          {
            "series": "1",
            "index": "464",
            "xExact": "",
            "x": "465",
            "yExact": "",
            "y": "1",
            "id": "customer:2278"
          },
          {
            "series": "0",
            "index": "465",
            "xExact": "",
            "x": "466",
            "yExact": "",
            "y": "0.173913043",
            "id": "customer:2289"
          },
          {
            "series": "1",
            "index": "465",
            "xExact": "",
            "x": "466",
            "yExact": "",
            "y": "0",
            "id": "customer:2289"
          },
          {
            "series": "0",
            "index": "466",
            "xExact": "",
            "x": "467",
            "yExact": "",
            "y": "0.173913043",
            "id": "customer:2290"
          },
          {
            "series": "1",
            "index": "466",
            "xExact": "",
            "x": "467",
            "yExact": "",
            "y": "0",
            "id": "customer:2290"
          },
          {
            "series": "0",
            "index": "467",
            "xExact": "",
            "x": "468",
            "yExact": "",
            "y": "0.0377358491",
            "id": "customer:2298"
          },
          {
            "series": "1",
            "index": "467",
            "xExact": "",
            "x": "468",
            "yExact": "",
            "y": "0",
            "id": "customer:2298"
          },
          {
            "series": "0",
            "index": "468",
            "xExact": "",
            "x": "469",
            "yExact": "",
            "y": "0.0377358491",
            "id": "customer:2299"
          },
          {
            "series": "1",
            "index": "468",
            "xExact": "",
            "x": "469",
            "yExact": "",
            "y": "0",
            "id": "customer:2299"
          },
          {
            "series": "0",
            "index": "469",
            "xExact": "",
            "x": "470",
            "yExact": "",
            "y": "0.947368421",
            "id": "customer:2300"
          },
          {
            "series": "1",
            "index": "469",
            "xExact": "",
            "x": "470",
            "yExact": "",
            "y": "1",
            "id": "customer:2300"
          },
          {
            "series": "0",
            "index": "470",
            "xExact": "",
            "x": "471",
            "yExact": "",
            "y": "0.197247706",
            "id": "customer:2302"
          },
          {
            "series": "1",
            "index": "470",
            "xExact": "",
            "x": "471",
            "yExact": "",
            "y": "0",
            "id": "customer:2302"
          },
          {
            "series": "0",
            "index": "471",
            "xExact": "",
            "x": "472",
            "yExact": "",
            "y": "0.151785714",
            "id": "customer:2305"
          },
          {
            "series": "1",
            "index": "471",
            "xExact": "",
            "x": "472",
            "yExact": "",
            "y": "0",
            "id": "customer:2305"
          },
          {
            "series": "0",
            "index": "472",
            "xExact": "",
            "x": "473",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:2306"
          },
          {
            "series": "1",
            "index": "472",
            "xExact": "",
            "x": "473",
            "yExact": "",
            "y": "0",
            "id": "customer:2306"
          },
          {
            "series": "0",
            "index": "473",
            "xExact": "",
            "x": "474",
            "yExact": "",
            "y": "0.151785714",
            "id": "customer:2312"
          },
          {
            "series": "1",
            "index": "473",
            "xExact": "",
            "x": "474",
            "yExact": "",
            "y": "0",
            "id": "customer:2312"
          },
          {
            "series": "0",
            "index": "474",
            "xExact": "",
            "x": "475",
            "yExact": "",
            "y": "0.947368421",
            "id": "customer:2323"
          },
          {
            "series": "1",
            "index": "474",
            "xExact": "",
            "x": "475",
            "yExact": "",
            "y": "1",
            "id": "customer:2323"
          },
          {
            "series": "0",
            "index": "475",
            "xExact": "",
            "x": "476",
            "yExact": "",
            "y": "0.0146341463",
            "id": "customer:2326"
          },
          {
            "series": "1",
            "index": "475",
            "xExact": "",
            "x": "476",
            "yExact": "",
            "y": "0",
            "id": "customer:2326"
          },
          {
            "series": "0",
            "index": "476",
            "xExact": "",
            "x": "477",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:2330"
          },
          {
            "series": "1",
            "index": "476",
            "xExact": "",
            "x": "477",
            "yExact": "",
            "y": "0",
            "id": "customer:2330"
          },
          {
            "series": "0",
            "index": "477",
            "xExact": "",
            "x": "478",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:2332"
          },
          {
            "series": "1",
            "index": "477",
            "xExact": "",
            "x": "478",
            "yExact": "",
            "y": "1",
            "id": "customer:2332"
          },
          {
            "series": "0",
            "index": "478",
            "xExact": "",
            "x": "479",
            "yExact": "",
            "y": "0.0377358491",
            "id": "customer:2334"
          },
          {
            "series": "1",
            "index": "478",
            "xExact": "",
            "x": "479",
            "yExact": "",
            "y": "0",
            "id": "customer:2334"
          },
          {
            "series": "0",
            "index": "479",
            "xExact": "",
            "x": "480",
            "yExact": "",
            "y": "0.0377358491",
            "id": "customer:2335"
          },
          {
            "series": "1",
            "index": "479",
            "xExact": "",
            "x": "480",
            "yExact": "",
            "y": "0",
            "id": "customer:2335"
          },
          {
            "series": "0",
            "index": "480",
            "xExact": "",
            "x": "481",
            "yExact": "",
            "y": "0.173913043",
            "id": "customer:2337"
          },
          {
            "series": "1",
            "index": "480",
            "xExact": "",
            "x": "481",
            "yExact": "",
            "y": "0",
            "id": "customer:2337"
          },
          {
            "series": "0",
            "index": "481",
            "xExact": "",
            "x": "482",
            "yExact": "",
            "y": "0.0377358491",
            "id": "customer:2346"
          },
          {
            "series": "1",
            "index": "481",
            "xExact": "",
            "x": "482",
            "yExact": "",
            "y": "0",
            "id": "customer:2346"
          },
          {
            "series": "0",
            "index": "482",
            "xExact": "",
            "x": "483",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:2354"
          },
          {
            "series": "1",
            "index": "482",
            "xExact": "",
            "x": "483",
            "yExact": "",
            "y": "0",
            "id": "customer:2354"
          },
          {
            "series": "0",
            "index": "483",
            "xExact": "",
            "x": "484",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:2355"
          },
          {
            "series": "1",
            "index": "483",
            "xExact": "",
            "x": "484",
            "yExact": "",
            "y": "0",
            "id": "customer:2355"
          },
          {
            "series": "0",
            "index": "484",
            "xExact": "",
            "x": "485",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:2365"
          },
          {
            "series": "1",
            "index": "484",
            "xExact": "",
            "x": "485",
            "yExact": "",
            "y": "0",
            "id": "customer:2365"
          },
          {
            "series": "0",
            "index": "485",
            "xExact": "",
            "x": "486",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:2374"
          },
          {
            "series": "1",
            "index": "485",
            "xExact": "",
            "x": "486",
            "yExact": "",
            "y": "0",
            "id": "customer:2374"
          },
          {
            "series": "0",
            "index": "486",
            "xExact": "",
            "x": "487",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:2381"
          },
          {
            "series": "1",
            "index": "486",
            "xExact": "",
            "x": "487",
            "yExact": "",
            "y": "0",
            "id": "customer:2381"
          },
          {
            "series": "0",
            "index": "487",
            "xExact": "",
            "x": "488",
            "yExact": "",
            "y": "0.173913043",
            "id": "customer:2390"
          },
          {
            "series": "1",
            "index": "487",
            "xExact": "",
            "x": "488",
            "yExact": "",
            "y": "0",
            "id": "customer:2390"
          },
          {
            "series": "0",
            "index": "488",
            "xExact": "",
            "x": "489",
            "yExact": "",
            "y": "0.173913043",
            "id": "customer:2392"
          },
          {
            "series": "1",
            "index": "488",
            "xExact": "",
            "x": "489",
            "yExact": "",
            "y": "0",
            "id": "customer:2392"
          },
          {
            "series": "0",
            "index": "489",
            "xExact": "",
            "x": "490",
            "yExact": "",
            "y": "0.0377358491",
            "id": "customer:2406"
          },
          {
            "series": "1",
            "index": "489",
            "xExact": "",
            "x": "490",
            "yExact": "",
            "y": "0",
            "id": "customer:2406"
          },
          {
            "series": "0",
            "index": "490",
            "xExact": "",
            "x": "491",
            "yExact": "",
            "y": "0.0377358491",
            "id": "customer:2410"
          },
          {
            "series": "1",
            "index": "490",
            "xExact": "",
            "x": "491",
            "yExact": "",
            "y": "0",
            "id": "customer:2410"
          },
          {
            "series": "0",
            "index": "491",
            "xExact": "",
            "x": "492",
            "yExact": "",
            "y": "0.0146341463",
            "id": "customer:2411"
          },
          {
            "series": "1",
            "index": "491",
            "xExact": "",
            "x": "492",
            "yExact": "",
            "y": "0",
            "id": "customer:2411"
          },
          {
            "series": "0",
            "index": "492",
            "xExact": "",
            "x": "493",
            "yExact": "",
            "y": "0.173913043",
            "id": "customer:2412"
          },
          {
            "series": "1",
            "index": "492",
            "xExact": "",
            "x": "493",
            "yExact": "",
            "y": "0",
            "id": "customer:2412"
          },
          {
            "series": "0",
            "index": "493",
            "xExact": "",
            "x": "494",
            "yExact": "",
            "y": "0.0377358491",
            "id": "customer:2413"
          },
          {
            "series": "1",
            "index": "493",
            "xExact": "",
            "x": "494",
            "yExact": "",
            "y": "0",
            "id": "customer:2413"
          },
          {
            "series": "0",
            "index": "494",
            "xExact": "",
            "x": "495",
            "yExact": "",
            "y": "0.173913043",
            "id": "customer:2423"
          },
          {
            "series": "1",
            "index": "494",
            "xExact": "",
            "x": "495",
            "yExact": "",
            "y": "1",
            "id": "customer:2423"
          },
          {
            "series": "0",
            "index": "495",
            "xExact": "",
            "x": "496",
            "yExact": "",
            "y": "0.0377358491",
            "id": "customer:2425"
          },
          {
            "series": "1",
            "index": "495",
            "xExact": "",
            "x": "496",
            "yExact": "",
            "y": "1",
            "id": "customer:2425"
          },
          {
            "series": "0",
            "index": "496",
            "xExact": "",
            "x": "497",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:2437"
          },
          {
            "series": "1",
            "index": "496",
            "xExact": "",
            "x": "497",
            "yExact": "",
            "y": "0",
            "id": "customer:2437"
          },
          {
            "series": "0",
            "index": "497",
            "xExact": "",
            "x": "498",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:2439"
          },
          {
            "series": "1",
            "index": "497",
            "xExact": "",
            "x": "498",
            "yExact": "",
            "y": "0",
            "id": "customer:2439"
          },
          {
            "series": "0",
            "index": "498",
            "xExact": "",
            "x": "499",
            "yExact": "",
            "y": "0.173913043",
            "id": "customer:2443"
          },
          {
            "series": "1",
            "index": "498",
            "xExact": "",
            "x": "499",
            "yExact": "",
            "y": "0",
            "id": "customer:2443"
          },
          {
            "series": "0",
            "index": "499",
            "xExact": "",
            "x": "500",
            "yExact": "",
            "y": "0.0377358491",
            "id": "customer:2447"
          },
          {
            "series": "1",
            "index": "499",
            "xExact": "",
            "x": "500",
            "yExact": "",
            "y": "0",
            "id": "customer:2447"
          },
          {
            "series": "0",
            "index": "500",
            "xExact": "",
            "x": "501",
            "yExact": "",
            "y": "0.173913043",
            "id": "customer:2448"
          },
          {
            "series": "1",
            "index": "500",
            "xExact": "",
            "x": "501",
            "yExact": "",
            "y": "0",
            "id": "customer:2448"
          },
          {
            "series": "0",
            "index": "501",
            "xExact": "",
            "x": "502",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:2465"
          },
          {
            "series": "1",
            "index": "501",
            "xExact": "",
            "x": "502",
            "yExact": "",
            "y": "0",
            "id": "customer:2465"
          },
          {
            "series": "0",
            "index": "502",
            "xExact": "",
            "x": "503",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:2466"
          },
          {
            "series": "1",
            "index": "502",
            "xExact": "",
            "x": "503",
            "yExact": "",
            "y": "0",
            "id": "customer:2466"
          },
          {
            "series": "0",
            "index": "503",
            "xExact": "",
            "x": "504",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:2470"
          },
          {
            "series": "1",
            "index": "503",
            "xExact": "",
            "x": "504",
            "yExact": "",
            "y": "0",
            "id": "customer:2470"
          },
          {
            "series": "0",
            "index": "504",
            "xExact": "",
            "x": "505",
            "yExact": "",
            "y": "0.151785714",
            "id": "customer:2482"
          },
          {
            "series": "1",
            "index": "504",
            "xExact": "",
            "x": "505",
            "yExact": "",
            "y": "1",
            "id": "customer:2482"
          },
          {
            "series": "0",
            "index": "505",
            "xExact": "",
            "x": "506",
            "yExact": "",
            "y": "0.151785714",
            "id": "customer:2483"
          },
          {
            "series": "1",
            "index": "505",
            "xExact": "",
            "x": "506",
            "yExact": "",
            "y": "0",
            "id": "customer:2483"
          },
          {
            "series": "0",
            "index": "506",
            "xExact": "",
            "x": "507",
            "yExact": "",
            "y": "0.173913043",
            "id": "customer:2492"
          },
          {
            "series": "1",
            "index": "506",
            "xExact": "",
            "x": "507",
            "yExact": "",
            "y": "0",
            "id": "customer:2492"
          },
          {
            "series": "0",
            "index": "507",
            "xExact": "",
            "x": "508",
            "yExact": "",
            "y": "0.0377358491",
            "id": "customer:2494"
          },
          {
            "series": "1",
            "index": "507",
            "xExact": "",
            "x": "508",
            "yExact": "",
            "y": "0",
            "id": "customer:2494"
          },
          {
            "series": "0",
            "index": "508",
            "xExact": "",
            "x": "509",
            "yExact": "",
            "y": "0.0377358491",
            "id": "customer:2498"
          },
          {
            "series": "1",
            "index": "508",
            "xExact": "",
            "x": "509",
            "yExact": "",
            "y": "0",
            "id": "customer:2498"
          },
          {
            "series": "0",
            "index": "509",
            "xExact": "",
            "x": "510",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:2504"
          },
          {
            "series": "1",
            "index": "509",
            "xExact": "",
            "x": "510",
            "yExact": "",
            "y": "0",
            "id": "customer:2504"
          },
          {
            "series": "0",
            "index": "510",
            "xExact": "",
            "x": "511",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:2511"
          },
          {
            "series": "1",
            "index": "510",
            "xExact": "",
            "x": "511",
            "yExact": "",
            "y": "0",
            "id": "customer:2511"
          },
          {
            "series": "0",
            "index": "511",
            "xExact": "",
            "x": "512",
            "yExact": "",
            "y": "0.173913043",
            "id": "customer:2541"
          },
          {
            "series": "1",
            "index": "511",
            "xExact": "",
            "x": "512",
            "yExact": "",
            "y": "0",
            "id": "customer:2541"
          },
          {
            "series": "0",
            "index": "512",
            "xExact": "",
            "x": "513",
            "yExact": "",
            "y": "0.0146341463",
            "id": "customer:2544"
          },
          {
            "series": "1",
            "index": "512",
            "xExact": "",
            "x": "513",
            "yExact": "",
            "y": "0",
            "id": "customer:2544"
          },
          {
            "series": "0",
            "index": "513",
            "xExact": "",
            "x": "514",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:2545"
          },
          {
            "series": "1",
            "index": "513",
            "xExact": "",
            "x": "514",
            "yExact": "",
            "y": "0",
            "id": "customer:2545"
          },
          {
            "series": "0",
            "index": "514",
            "xExact": "",
            "x": "515",
            "yExact": "",
            "y": "0.0377358491",
            "id": "customer:2547"
          },
          {
            "series": "1",
            "index": "514",
            "xExact": "",
            "x": "515",
            "yExact": "",
            "y": "0",
            "id": "customer:2547"
          },
          {
            "series": "0",
            "index": "515",
            "xExact": "",
            "x": "516",
            "yExact": "",
            "y": "0.958333333",
            "id": "customer:2550"
          },
          {
            "series": "1",
            "index": "515",
            "xExact": "",
            "x": "516",
            "yExact": "",
            "y": "1",
            "id": "customer:2550"
          },
          {
            "series": "0",
            "index": "516",
            "xExact": "",
            "x": "517",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:2554"
          },
          {
            "series": "1",
            "index": "516",
            "xExact": "",
            "x": "517",
            "yExact": "",
            "y": "0",
            "id": "customer:2554"
          },
          {
            "series": "0",
            "index": "517",
            "xExact": "",
            "x": "518",
            "yExact": "",
            "y": "0.586206897",
            "id": "customer:2563"
          },
          {
            "series": "1",
            "index": "517",
            "xExact": "",
            "x": "518",
            "yExact": "",
            "y": "0",
            "id": "customer:2563"
          },
          {
            "series": "0",
            "index": "518",
            "xExact": "",
            "x": "519",
            "yExact": "",
            "y": "0.586206897",
            "id": "customer:2569"
          },
          {
            "series": "1",
            "index": "518",
            "xExact": "",
            "x": "519",
            "yExact": "",
            "y": "1",
            "id": "customer:2569"
          },
          {
            "series": "0",
            "index": "519",
            "xExact": "",
            "x": "520",
            "yExact": "",
            "y": "0.586206897",
            "id": "customer:2577"
          },
          {
            "series": "1",
            "index": "519",
            "xExact": "",
            "x": "520",
            "yExact": "",
            "y": "1",
            "id": "customer:2577"
          },
          {
            "series": "0",
            "index": "520",
            "xExact": "",
            "x": "521",
            "yExact": "",
            "y": "0.173913043",
            "id": "customer:2590"
          },
          {
            "series": "1",
            "index": "520",
            "xExact": "",
            "x": "521",
            "yExact": "",
            "y": "0",
            "id": "customer:2590"
          },
          {
            "series": "0",
            "index": "521",
            "xExact": "",
            "x": "522",
            "yExact": "",
            "y": "0.173913043",
            "id": "customer:2593"
          },
          {
            "series": "1",
            "index": "521",
            "xExact": "",
            "x": "522",
            "yExact": "",
            "y": "0",
            "id": "customer:2593"
          },
          {
            "series": "0",
            "index": "522",
            "xExact": "",
            "x": "523",
            "yExact": "",
            "y": "0.0377358491",
            "id": "customer:2597"
          },
          {
            "series": "1",
            "index": "522",
            "xExact": "",
            "x": "523",
            "yExact": "",
            "y": "0",
            "id": "customer:2597"
          },
          {
            "series": "0",
            "index": "523",
            "xExact": "",
            "x": "524",
            "yExact": "",
            "y": "0.197247706",
            "id": "customer:2607"
          },
          {
            "series": "1",
            "index": "523",
            "xExact": "",
            "x": "524",
            "yExact": "",
            "y": "0",
            "id": "customer:2607"
          },
          {
            "series": "0",
            "index": "524",
            "xExact": "",
            "x": "525",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:2609"
          },
          {
            "series": "1",
            "index": "524",
            "xExact": "",
            "x": "525",
            "yExact": "",
            "y": "0",
            "id": "customer:2609"
          },
          {
            "series": "0",
            "index": "525",
            "xExact": "",
            "x": "526",
            "yExact": "",
            "y": "0.0071942446",
            "id": "customer:2616"
          },
          {
            "series": "1",
            "index": "525",
            "xExact": "",
            "x": "526",
            "yExact": "",
            "y": "0",
            "id": "customer:2616"
          },
          {
            "series": "0",
            "index": "526",
            "xExact": "",
            "x": "527",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:2624"
          },
          {
            "series": "1",
            "index": "526",
            "xExact": "",
            "x": "527",
            "yExact": "",
            "y": "0",
            "id": "customer:2624"
          },
          {
            "series": "0",
            "index": "527",
            "xExact": "",
            "x": "528",
            "yExact": "",
            "y": "0.173913043",
            "id": "customer:2643"
          },
          {
            "series": "1",
            "index": "527",
            "xExact": "",
            "x": "528",
            "yExact": "",
            "y": "0",
            "id": "customer:2643"
          },
          {
            "series": "0",
            "index": "528",
            "xExact": "",
            "x": "529",
            "yExact": "",
            "y": "0.173913043",
            "id": "customer:2648"
          },
          {
            "series": "1",
            "index": "528",
            "xExact": "",
            "x": "529",
            "yExact": "",
            "y": "0",
            "id": "customer:2648"
          },
          {
            "series": "0",
            "index": "529",
            "xExact": "",
            "x": "530",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:2659"
          },
          {
            "series": "1",
            "index": "529",
            "xExact": "",
            "x": "530",
            "yExact": "",
            "y": "0",
            "id": "customer:2659"
          },
          {
            "series": "0",
            "index": "530",
            "xExact": "",
            "x": "531",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:2666"
          },
          {
            "series": "1",
            "index": "530",
            "xExact": "",
            "x": "531",
            "yExact": "",
            "y": "0",
            "id": "customer:2666"
          },
          {
            "series": "0",
            "index": "531",
            "xExact": "",
            "x": "532",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:2670"
          },
          {
            "series": "1",
            "index": "531",
            "xExact": "",
            "x": "532",
            "yExact": "",
            "y": "0",
            "id": "customer:2670"
          },
          {
            "series": "0",
            "index": "532",
            "xExact": "",
            "x": "533",
            "yExact": "",
            "y": "0.586206897",
            "id": "customer:2673"
          },
          {
            "series": "1",
            "index": "532",
            "xExact": "",
            "x": "533",
            "yExact": "",
            "y": "1",
            "id": "customer:2673"
          },
          {
            "series": "0",
            "index": "533",
            "xExact": "",
            "x": "534",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:2675"
          },
          {
            "series": "1",
            "index": "533",
            "xExact": "",
            "x": "534",
            "yExact": "",
            "y": "0",
            "id": "customer:2675"
          },
          {
            "series": "0",
            "index": "534",
            "xExact": "",
            "x": "535",
            "yExact": "",
            "y": "0.586206897",
            "id": "customer:2678"
          },
          {
            "series": "1",
            "index": "534",
            "xExact": "",
            "x": "535",
            "yExact": "",
            "y": "1",
            "id": "customer:2678"
          },
          {
            "series": "0",
            "index": "535",
            "xExact": "",
            "x": "536",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:2685"
          },
          {
            "series": "1",
            "index": "535",
            "xExact": "",
            "x": "536",
            "yExact": "",
            "y": "0",
            "id": "customer:2685"
          },
          {
            "series": "0",
            "index": "536",
            "xExact": "",
            "x": "537",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:2688"
          },
          {
            "series": "1",
            "index": "536",
            "xExact": "",
            "x": "537",
            "yExact": "",
            "y": "0",
            "id": "customer:2688"
          },
          {
            "series": "0",
            "index": "537",
            "xExact": "",
            "x": "538",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:2692"
          },
          {
            "series": "1",
            "index": "537",
            "xExact": "",
            "x": "538",
            "yExact": "",
            "y": "0",
            "id": "customer:2692"
          },
          {
            "series": "0",
            "index": "538",
            "xExact": "",
            "x": "539",
            "yExact": "",
            "y": "0.173913043",
            "id": "customer:2695"
          },
          {
            "series": "1",
            "index": "538",
            "xExact": "",
            "x": "539",
            "yExact": "",
            "y": "0",
            "id": "customer:2695"
          },
          {
            "series": "0",
            "index": "539",
            "xExact": "",
            "x": "540",
            "yExact": "",
            "y": "0.0377358491",
            "id": "customer:2699"
          },
          {
            "series": "1",
            "index": "539",
            "xExact": "",
            "x": "540",
            "yExact": "",
            "y": "0",
            "id": "customer:2699"
          },
          {
            "series": "0",
            "index": "540",
            "xExact": "",
            "x": "541",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:2704"
          },
          {
            "series": "1",
            "index": "540",
            "xExact": "",
            "x": "541",
            "yExact": "",
            "y": "0",
            "id": "customer:2704"
          },
          {
            "series": "0",
            "index": "541",
            "xExact": "",
            "x": "542",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:2709"
          },
          {
            "series": "1",
            "index": "541",
            "xExact": "",
            "x": "542",
            "yExact": "",
            "y": "0",
            "id": "customer:2709"
          },
          {
            "series": "0",
            "index": "542",
            "xExact": "",
            "x": "543",
            "yExact": "",
            "y": "0.586206897",
            "id": "customer:2712"
          },
          {
            "series": "1",
            "index": "542",
            "xExact": "",
            "x": "543",
            "yExact": "",
            "y": "0",
            "id": "customer:2712"
          },
          {
            "series": "0",
            "index": "543",
            "xExact": "",
            "x": "544",
            "yExact": "",
            "y": "0.151785714",
            "id": "customer:2718"
          },
          {
            "series": "1",
            "index": "543",
            "xExact": "",
            "x": "544",
            "yExact": "",
            "y": "0",
            "id": "customer:2718"
          },
          {
            "series": "0",
            "index": "544",
            "xExact": "",
            "x": "545",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:2722"
          },
          {
            "series": "1",
            "index": "544",
            "xExact": "",
            "x": "545",
            "yExact": "",
            "y": "0",
            "id": "customer:2722"
          },
          {
            "series": "0",
            "index": "545",
            "xExact": "",
            "x": "546",
            "yExact": "",
            "y": "0.151785714",
            "id": "customer:2728"
          },
          {
            "series": "1",
            "index": "545",
            "xExact": "",
            "x": "546",
            "yExact": "",
            "y": "1",
            "id": "customer:2728"
          },
          {
            "series": "0",
            "index": "546",
            "xExact": "",
            "x": "547",
            "yExact": "",
            "y": "0.857142857",
            "id": "customer:2729"
          },
          {
            "series": "1",
            "index": "546",
            "xExact": "",
            "x": "547",
            "yExact": "",
            "y": "1",
            "id": "customer:2729"
          },
          {
            "series": "0",
            "index": "547",
            "xExact": "",
            "x": "548",
            "yExact": "",
            "y": "0.197247706",
            "id": "customer:2730"
          },
          {
            "series": "1",
            "index": "547",
            "xExact": "",
            "x": "548",
            "yExact": "",
            "y": "0",
            "id": "customer:2730"
          },
          {
            "series": "0",
            "index": "548",
            "xExact": "",
            "x": "549",
            "yExact": "",
            "y": "0.0377358491",
            "id": "customer:2734"
          },
          {
            "series": "1",
            "index": "548",
            "xExact": "",
            "x": "549",
            "yExact": "",
            "y": "0",
            "id": "customer:2734"
          },
          {
            "series": "0",
            "index": "549",
            "xExact": "",
            "x": "550",
            "yExact": "",
            "y": "0.151785714",
            "id": "customer:2737"
          },
          {
            "series": "1",
            "index": "549",
            "xExact": "",
            "x": "550",
            "yExact": "",
            "y": "0",
            "id": "customer:2737"
          },
          {
            "series": "0",
            "index": "550",
            "xExact": "",
            "x": "551",
            "yExact": "",
            "y": "0.173913043",
            "id": "customer:2741"
          },
          {
            "series": "1",
            "index": "550",
            "xExact": "",
            "x": "551",
            "yExact": "",
            "y": "0",
            "id": "customer:2741"
          },
          {
            "series": "0",
            "index": "551",
            "xExact": "",
            "x": "552",
            "yExact": "",
            "y": "0.173913043",
            "id": "customer:2750"
          },
          {
            "series": "1",
            "index": "551",
            "xExact": "",
            "x": "552",
            "yExact": "",
            "y": "1",
            "id": "customer:2750"
          },
          {
            "series": "0",
            "index": "552",
            "xExact": "",
            "x": "553",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:2751"
          },
          {
            "series": "1",
            "index": "552",
            "xExact": "",
            "x": "553",
            "yExact": "",
            "y": "0",
            "id": "customer:2751"
          },
          {
            "series": "0",
            "index": "553",
            "xExact": "",
            "x": "554",
            "yExact": "",
            "y": "0.151785714",
            "id": "customer:2752"
          },
          {
            "series": "1",
            "index": "553",
            "xExact": "",
            "x": "554",
            "yExact": "",
            "y": "0",
            "id": "customer:2752"
          },
          {
            "series": "0",
            "index": "554",
            "xExact": "",
            "x": "555",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:2754"
          },
          {
            "series": "1",
            "index": "554",
            "xExact": "",
            "x": "555",
            "yExact": "",
            "y": "0",
            "id": "customer:2754"
          },
          {
            "series": "0",
            "index": "555",
            "xExact": "",
            "x": "556",
            "yExact": "",
            "y": "0.151785714",
            "id": "customer:2755"
          },
          {
            "series": "1",
            "index": "555",
            "xExact": "",
            "x": "556",
            "yExact": "",
            "y": "0",
            "id": "customer:2755"
          },
          {
            "series": "0",
            "index": "556",
            "xExact": "",
            "x": "557",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:2756"
          },
          {
            "series": "1",
            "index": "556",
            "xExact": "",
            "x": "557",
            "yExact": "",
            "y": "0",
            "id": "customer:2756"
          },
          {
            "series": "0",
            "index": "557",
            "xExact": "",
            "x": "558",
            "yExact": "",
            "y": "0.151785714",
            "id": "customer:2757"
          },
          {
            "series": "1",
            "index": "557",
            "xExact": "",
            "x": "558",
            "yExact": "",
            "y": "0",
            "id": "customer:2757"
          },
          {
            "series": "0",
            "index": "558",
            "xExact": "",
            "x": "559",
            "yExact": "",
            "y": "0.151785714",
            "id": "customer:2767"
          },
          {
            "series": "1",
            "index": "558",
            "xExact": "",
            "x": "559",
            "yExact": "",
            "y": "0",
            "id": "customer:2767"
          },
          {
            "series": "0",
            "index": "559",
            "xExact": "",
            "x": "560",
            "yExact": "",
            "y": "0.173913043",
            "id": "customer:2792"
          },
          {
            "series": "1",
            "index": "559",
            "xExact": "",
            "x": "560",
            "yExact": "",
            "y": "0",
            "id": "customer:2792"
          },
          {
            "series": "0",
            "index": "560",
            "xExact": "",
            "x": "561",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:2810"
          },
          {
            "series": "1",
            "index": "560",
            "xExact": "",
            "x": "561",
            "yExact": "",
            "y": "0",
            "id": "customer:2810"
          },
          {
            "series": "0",
            "index": "561",
            "xExact": "",
            "x": "562",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:2814"
          },
          {
            "series": "1",
            "index": "561",
            "xExact": "",
            "x": "562",
            "yExact": "",
            "y": "0",
            "id": "customer:2814"
          },
          {
            "series": "0",
            "index": "562",
            "xExact": "",
            "x": "563",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:2815"
          },
          {
            "series": "1",
            "index": "562",
            "xExact": "",
            "x": "563",
            "yExact": "",
            "y": "0",
            "id": "customer:2815"
          },
          {
            "series": "0",
            "index": "563",
            "xExact": "",
            "x": "564",
            "yExact": "",
            "y": "0.197247706",
            "id": "customer:2819"
          },
          {
            "series": "1",
            "index": "563",
            "xExact": "",
            "x": "564",
            "yExact": "",
            "y": "1",
            "id": "customer:2819"
          },
          {
            "series": "0",
            "index": "564",
            "xExact": "",
            "x": "565",
            "yExact": "",
            "y": "0.0071942446",
            "id": "customer:2826"
          },
          {
            "series": "1",
            "index": "564",
            "xExact": "",
            "x": "565",
            "yExact": "",
            "y": "0",
            "id": "customer:2826"
          },
          {
            "series": "0",
            "index": "565",
            "xExact": "",
            "x": "566",
            "yExact": "",
            "y": "0.151785714",
            "id": "customer:2828"
          },
          {
            "series": "1",
            "index": "565",
            "xExact": "",
            "x": "566",
            "yExact": "",
            "y": "1",
            "id": "customer:2828"
          },
          {
            "series": "0",
            "index": "566",
            "xExact": "",
            "x": "567",
            "yExact": "",
            "y": "0.197247706",
            "id": "customer:2833"
          },
          {
            "series": "1",
            "index": "566",
            "xExact": "",
            "x": "567",
            "yExact": "",
            "y": "0",
            "id": "customer:2833"
          },
          {
            "series": "0",
            "index": "567",
            "xExact": "",
            "x": "568",
            "yExact": "",
            "y": "0.0071942446",
            "id": "customer:2836"
          },
          {
            "series": "1",
            "index": "567",
            "xExact": "",
            "x": "568",
            "yExact": "",
            "y": "0",
            "id": "customer:2836"
          },
          {
            "series": "0",
            "index": "568",
            "xExact": "",
            "x": "569",
            "yExact": "",
            "y": "0.151785714",
            "id": "customer:2838"
          },
          {
            "series": "1",
            "index": "568",
            "xExact": "",
            "x": "569",
            "yExact": "",
            "y": "0",
            "id": "customer:2838"
          },
          {
            "series": "0",
            "index": "569",
            "xExact": "",
            "x": "570",
            "yExact": "",
            "y": "0.0146341463",
            "id": "customer:2844"
          },
          {
            "series": "1",
            "index": "569",
            "xExact": "",
            "x": "570",
            "yExact": "",
            "y": "0",
            "id": "customer:2844"
          },
          {
            "series": "0",
            "index": "570",
            "xExact": "",
            "x": "571",
            "yExact": "",
            "y": "0.173913043",
            "id": "customer:2853"
          },
          {
            "series": "1",
            "index": "570",
            "xExact": "",
            "x": "571",
            "yExact": "",
            "y": "0",
            "id": "customer:2853"
          },
          {
            "series": "0",
            "index": "571",
            "xExact": "",
            "x": "572",
            "yExact": "",
            "y": "0.0377358491",
            "id": "customer:2871"
          },
          {
            "series": "1",
            "index": "571",
            "xExact": "",
            "x": "572",
            "yExact": "",
            "y": "0",
            "id": "customer:2871"
          },
          {
            "series": "0",
            "index": "572",
            "xExact": "",
            "x": "573",
            "yExact": "",
            "y": "0.0377358491",
            "id": "customer:2874"
          },
          {
            "series": "1",
            "index": "572",
            "xExact": "",
            "x": "573",
            "yExact": "",
            "y": "0",
            "id": "customer:2874"
          },
          {
            "series": "0",
            "index": "573",
            "xExact": "",
            "x": "574",
            "yExact": "",
            "y": "0.0146341463",
            "id": "customer:2876"
          },
          {
            "series": "1",
            "index": "573",
            "xExact": "",
            "x": "574",
            "yExact": "",
            "y": "0",
            "id": "customer:2876"
          },
          {
            "series": "0",
            "index": "574",
            "xExact": "",
            "x": "575",
            "yExact": "",
            "y": "0.173913043",
            "id": "customer:2878"
          },
          {
            "series": "1",
            "index": "574",
            "xExact": "",
            "x": "575",
            "yExact": "",
            "y": "1",
            "id": "customer:2878"
          },
          {
            "series": "0",
            "index": "575",
            "xExact": "",
            "x": "576",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:2880"
          },
          {
            "series": "1",
            "index": "575",
            "xExact": "",
            "x": "576",
            "yExact": "",
            "y": "0",
            "id": "customer:2880"
          },
          {
            "series": "0",
            "index": "576",
            "xExact": "",
            "x": "577",
            "yExact": "",
            "y": "0.0146341463",
            "id": "customer:2886"
          },
          {
            "series": "1",
            "index": "576",
            "xExact": "",
            "x": "577",
            "yExact": "",
            "y": "0",
            "id": "customer:2886"
          },
          {
            "series": "0",
            "index": "577",
            "xExact": "",
            "x": "578",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:2887"
          },
          {
            "series": "1",
            "index": "577",
            "xExact": "",
            "x": "578",
            "yExact": "",
            "y": "0",
            "id": "customer:2887"
          },
          {
            "series": "0",
            "index": "578",
            "xExact": "",
            "x": "579",
            "yExact": "",
            "y": "0.0377358491",
            "id": "customer:2888"
          },
          {
            "series": "1",
            "index": "578",
            "xExact": "",
            "x": "579",
            "yExact": "",
            "y": "0",
            "id": "customer:2888"
          },
          {
            "series": "0",
            "index": "579",
            "xExact": "",
            "x": "580",
            "yExact": "",
            "y": "0.173913043",
            "id": "customer:2893"
          },
          {
            "series": "1",
            "index": "579",
            "xExact": "",
            "x": "580",
            "yExact": "",
            "y": "0",
            "id": "customer:2893"
          },
          {
            "series": "0",
            "index": "580",
            "xExact": "",
            "x": "581",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:2895"
          },
          {
            "series": "1",
            "index": "580",
            "xExact": "",
            "x": "581",
            "yExact": "",
            "y": "0",
            "id": "customer:2895"
          },
          {
            "series": "0",
            "index": "581",
            "xExact": "",
            "x": "582",
            "yExact": "",
            "y": "0.151785714",
            "id": "customer:2905"
          },
          {
            "series": "1",
            "index": "581",
            "xExact": "",
            "x": "582",
            "yExact": "",
            "y": "0",
            "id": "customer:2905"
          },
          {
            "series": "0",
            "index": "582",
            "xExact": "",
            "x": "583",
            "yExact": "",
            "y": "0.151785714",
            "id": "customer:2907"
          },
          {
            "series": "1",
            "index": "582",
            "xExact": "",
            "x": "583",
            "yExact": "",
            "y": "0",
            "id": "customer:2907"
          },
          {
            "series": "0",
            "index": "583",
            "xExact": "",
            "x": "584",
            "yExact": "",
            "y": "0.151785714",
            "id": "customer:2918"
          },
          {
            "series": "1",
            "index": "583",
            "xExact": "",
            "x": "584",
            "yExact": "",
            "y": "0",
            "id": "customer:2918"
          },
          {
            "series": "0",
            "index": "584",
            "xExact": "",
            "x": "585",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:2924"
          },
          {
            "series": "1",
            "index": "584",
            "xExact": "",
            "x": "585",
            "yExact": "",
            "y": "0",
            "id": "customer:2924"
          },
          {
            "series": "0",
            "index": "585",
            "xExact": "",
            "x": "586",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:2926"
          },
          {
            "series": "1",
            "index": "585",
            "xExact": "",
            "x": "586",
            "yExact": "",
            "y": "0",
            "id": "customer:2926"
          },
          {
            "series": "0",
            "index": "586",
            "xExact": "",
            "x": "587",
            "yExact": "",
            "y": "0.151785714",
            "id": "customer:2930"
          },
          {
            "series": "1",
            "index": "586",
            "xExact": "",
            "x": "587",
            "yExact": "",
            "y": "0",
            "id": "customer:2930"
          },
          {
            "series": "0",
            "index": "587",
            "xExact": "",
            "x": "588",
            "yExact": "",
            "y": "0.151785714",
            "id": "customer:2937"
          },
          {
            "series": "1",
            "index": "587",
            "xExact": "",
            "x": "588",
            "yExact": "",
            "y": "0",
            "id": "customer:2937"
          },
          {
            "series": "0",
            "index": "588",
            "xExact": "",
            "x": "589",
            "yExact": "",
            "y": "0.173913043",
            "id": "customer:2943"
          },
          {
            "series": "1",
            "index": "588",
            "xExact": "",
            "x": "589",
            "yExact": "",
            "y": "0",
            "id": "customer:2943"
          },
          {
            "series": "0",
            "index": "589",
            "xExact": "",
            "x": "590",
            "yExact": "",
            "y": "0.173913043",
            "id": "customer:2945"
          },
          {
            "series": "1",
            "index": "589",
            "xExact": "",
            "x": "590",
            "yExact": "",
            "y": "0",
            "id": "customer:2945"
          },
          {
            "series": "0",
            "index": "590",
            "xExact": "",
            "x": "591",
            "yExact": "",
            "y": "0.0377358491",
            "id": "customer:2947"
          },
          {
            "series": "1",
            "index": "590",
            "xExact": "",
            "x": "591",
            "yExact": "",
            "y": "0",
            "id": "customer:2947"
          },
          {
            "series": "0",
            "index": "591",
            "xExact": "",
            "x": "592",
            "yExact": "",
            "y": "0.0377358491",
            "id": "customer:2948"
          },
          {
            "series": "1",
            "index": "591",
            "xExact": "",
            "x": "592",
            "yExact": "",
            "y": "0",
            "id": "customer:2948"
          },
          {
            "series": "0",
            "index": "592",
            "xExact": "",
            "x": "593",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:2957"
          },
          {
            "series": "1",
            "index": "592",
            "xExact": "",
            "x": "593",
            "yExact": "",
            "y": "0",
            "id": "customer:2957"
          },
          {
            "series": "0",
            "index": "593",
            "xExact": "",
            "x": "594",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:2959"
          },
          {
            "series": "1",
            "index": "593",
            "xExact": "",
            "x": "594",
            "yExact": "",
            "y": "0",
            "id": "customer:2959"
          },
          {
            "series": "0",
            "index": "594",
            "xExact": "",
            "x": "595",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:2961"
          },
          {
            "series": "1",
            "index": "594",
            "xExact": "",
            "x": "595",
            "yExact": "",
            "y": "0",
            "id": "customer:2961"
          },
          {
            "series": "0",
            "index": "595",
            "xExact": "",
            "x": "596",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:2963"
          },
          {
            "series": "1",
            "index": "595",
            "xExact": "",
            "x": "596",
            "yExact": "",
            "y": "0",
            "id": "customer:2963"
          },
          {
            "series": "0",
            "index": "596",
            "xExact": "",
            "x": "597",
            "yExact": "",
            "y": "0.151785714",
            "id": "customer:2968"
          },
          {
            "series": "1",
            "index": "596",
            "xExact": "",
            "x": "597",
            "yExact": "",
            "y": "0",
            "id": "customer:2968"
          },
          {
            "series": "0",
            "index": "597",
            "xExact": "",
            "x": "598",
            "yExact": "",
            "y": "0.173913043",
            "id": "customer:2989"
          },
          {
            "series": "1",
            "index": "597",
            "xExact": "",
            "x": "598",
            "yExact": "",
            "y": "0",
            "id": "customer:2989"
          },
          {
            "series": "0",
            "index": "598",
            "xExact": "",
            "x": "599",
            "yExact": "",
            "y": "0.0377358491",
            "id": "customer:2994"
          },
          {
            "series": "1",
            "index": "598",
            "xExact": "",
            "x": "599",
            "yExact": "",
            "y": "0",
            "id": "customer:2994"
          },
          {
            "series": "0",
            "index": "599",
            "xExact": "",
            "x": "600",
            "yExact": "",
            "y": "0.197247706",
            "id": "customer:3002"
          },
          {
            "series": "1",
            "index": "599",
            "xExact": "",
            "x": "600",
            "yExact": "",
            "y": "0",
            "id": "customer:3002"
          },
          {
            "series": "0",
            "index": "600",
            "xExact": "",
            "x": "601",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:3006"
          },
          {
            "series": "1",
            "index": "600",
            "xExact": "",
            "x": "601",
            "yExact": "",
            "y": "0",
            "id": "customer:3006"
          },
          {
            "series": "0",
            "index": "601",
            "xExact": "",
            "x": "602",
            "yExact": "",
            "y": "0.0071942446",
            "id": "customer:3011"
          },
          {
            "series": "1",
            "index": "601",
            "xExact": "",
            "x": "602",
            "yExact": "",
            "y": "0",
            "id": "customer:3011"
          },
          {
            "series": "0",
            "index": "602",
            "xExact": "",
            "x": "603",
            "yExact": "",
            "y": "0.0071942446",
            "id": "customer:3016"
          },
          {
            "series": "1",
            "index": "602",
            "xExact": "",
            "x": "603",
            "yExact": "",
            "y": "0",
            "id": "customer:3016"
          },
          {
            "series": "0",
            "index": "603",
            "xExact": "",
            "x": "604",
            "yExact": "",
            "y": "0.197247706",
            "id": "customer:3017"
          },
          {
            "series": "1",
            "index": "603",
            "xExact": "",
            "x": "604",
            "yExact": "",
            "y": "0",
            "id": "customer:3017"
          },
          {
            "series": "0",
            "index": "604",
            "xExact": "",
            "x": "605",
            "yExact": "",
            "y": "0.0071942446",
            "id": "customer:3020"
          },
          {
            "series": "1",
            "index": "604",
            "xExact": "",
            "x": "605",
            "yExact": "",
            "y": "0",
            "id": "customer:3020"
          },
          {
            "series": "0",
            "index": "605",
            "xExact": "",
            "x": "606",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:3022"
          },
          {
            "series": "1",
            "index": "605",
            "xExact": "",
            "x": "606",
            "yExact": "",
            "y": "0",
            "id": "customer:3022"
          },
          {
            "series": "0",
            "index": "606",
            "xExact": "",
            "x": "607",
            "yExact": "",
            "y": "0.173913043",
            "id": "customer:3023"
          },
          {
            "series": "1",
            "index": "606",
            "xExact": "",
            "x": "607",
            "yExact": "",
            "y": "1",
            "id": "customer:3023"
          },
          {
            "series": "0",
            "index": "607",
            "xExact": "",
            "x": "608",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:3025"
          },
          {
            "series": "1",
            "index": "607",
            "xExact": "",
            "x": "608",
            "yExact": "",
            "y": "1",
            "id": "customer:3025"
          },
          {
            "series": "0",
            "index": "608",
            "xExact": "",
            "x": "609",
            "yExact": "",
            "y": "0.586206897",
            "id": "customer:3027"
          },
          {
            "series": "1",
            "index": "608",
            "xExact": "",
            "x": "609",
            "yExact": "",
            "y": "1",
            "id": "customer:3027"
          },
          {
            "series": "0",
            "index": "609",
            "xExact": "",
            "x": "610",
            "yExact": "",
            "y": "0.0071942446",
            "id": "customer:3036"
          },
          {
            "series": "1",
            "index": "609",
            "xExact": "",
            "x": "610",
            "yExact": "",
            "y": "0",
            "id": "customer:3036"
          },
          {
            "series": "0",
            "index": "610",
            "xExact": "",
            "x": "611",
            "yExact": "",
            "y": "0.18956044",
            "id": "customer:3039"
          },
          {
            "series": "1",
            "index": "610",
            "xExact": "",
            "x": "611",
            "yExact": "",
            "y": "0",
            "id": "customer:3039"
          },
          {
            "series": "0",
            "index": "611",
            "xExact": "",
            "x": "612",
            "yExact": "",
            "y": "0.173913043",
            "id": "customer:3041"
          },
          {
            "series": "1",
            "index": "611",
            "xExact": "",
            "x": "612",
            "yExact": "",
            "y": "0",
            "id": "customer:3041"
          },
          {
            "series": "0",
            "index": "612",
            "xExact": "",
            "x": "613",
            "yExact": "",
            "y": "0.0377358491",
            "id": "customer:3047"
          },
          {
            "series": "1",
            "index": "612",
            "xExact": "",
            "x": "613",
            "yExact": "",
            "y": "0",
            "id": "customer:3047"
          },
          {
            "series": "0",
            "index": "613",
            "xExact": "",
            "x": "614",
            "yExact": "",
            "y": "0.958333333",
            "id": "customer:3050"
          },
          {
            "series": "1",
            "index": "613",
            "xExact": "",
            "x": "614",
            "yExact": "",
            "y": "1",
            "id": "customer:3050"
          },
          {
            "series": "0",
            "index": "614",
            "xExact": "",
            "x": "615",
            "yExact": "",
            "y": "0.151785714",
            "id": "customer:3055"
          },
          {
            "series": "1",
            "index": "614",
            "xExact": "",
            "x": "615",
            "yExact": "",
            "y": "0",
            "id": "customer:3055"
          },
          {
            "series": "0",
            "index": "615",
            "xExact": "",
            "x": "616",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:3059"
          },
          {
            "series": "1",
            "index": "615",
            "xExact": "",
            "x": "616",
            "yExact": "",
            "y": "0",
            "id": "customer:3059"
          },
          {
            "series": "0",
            "index": "616",
            "xExact": "",
            "x": "617",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:3061"
          },
          {
            "series": "1",
            "index": "616",
            "xExact": "",
            "x": "617",
            "yExact": "",
            "y": "0",
            "id": "customer:3061"
          },
          {
            "series": "0",
            "index": "617",
            "xExact": "",
            "x": "618",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:3063"
          },
          {
            "series": "1",
            "index": "617",
            "xExact": "",
            "x": "618",
            "yExact": "",
            "y": "0",
            "id": "customer:3063"
          },
          {
            "series": "0",
            "index": "618",
            "xExact": "",
            "x": "619",
            "yExact": "",
            "y": "0.151785714",
            "id": "customer:3078"
          },
          {
            "series": "1",
            "index": "618",
            "xExact": "",
            "x": "619",
            "yExact": "",
            "y": "1",
            "id": "customer:3078"
          },
          {
            "series": "0",
            "index": "619",
            "xExact": "",
            "x": "620",
            "yExact": "",
            "y": "0.197247706",
            "id": "customer:3079"
          },
          {
            "series": "1",
            "index": "619",
            "xExact": "",
            "x": "620",
            "yExact": "",
            "y": "1",
            "id": "customer:3079"
          },
          {
            "series": "0",
            "index": "620",
            "xExact": "",
            "x": "621",
            "yExact": "",
            "y": "0.0377358491",
            "id": "customer:3084"
          },
          {
            "series": "1",
            "index": "620",
            "xExact": "",
            "x": "621",
            "yExact": "",
            "y": "0",
            "id": "customer:3084"
          },
          {
            "series": "0",
            "index": "621",
            "xExact": "",
            "x": "622",
            "yExact": "",
            "y": "0.173913043",
            "id": "customer:3091"
          },
          {
            "series": "1",
            "index": "621",
            "xExact": "",
            "x": "622",
            "yExact": "",
            "y": "0",
            "id": "customer:3091"
          },
          {
            "series": "0",
            "index": "622",
            "xExact": "",
            "x": "623",
            "yExact": "",
            "y": "0.173913043",
            "id": "customer:3093"
          },
          {
            "series": "1",
            "index": "622",
            "xExact": "",
            "x": "623",
            "yExact": "",
            "y": "0",
            "id": "customer:3093"
          },
          {
            "series": "0",
            "index": "623",
            "xExact": "",
            "x": "624",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:3109"
          },
          {
            "series": "1",
            "index": "623",
            "xExact": "",
            "x": "624",
            "yExact": "",
            "y": "0",
            "id": "customer:3109"
          },
          {
            "series": "0",
            "index": "624",
            "xExact": "",
            "x": "625",
            "yExact": "",
            "y": "0.197247706",
            "id": "customer:3119"
          },
          {
            "series": "1",
            "index": "624",
            "xExact": "",
            "x": "625",
            "yExact": "",
            "y": "1",
            "id": "customer:3119"
          },
          {
            "series": "0",
            "index": "625",
            "xExact": "",
            "x": "626",
            "yExact": "",
            "y": "0.0225988701",
            "id": "customer:3122"
          },
          {
            "series": "1",
            "index": "625",
            "xExact": "",
            "x": "626",
            "yExact": "",
            "y": "0",
            "id": "customer:3122"
          },
          {
            "series": "0",
            "index": "626",
            "xExact": "",
            "x": "627",
            "yExact": "",
            "y": "0.586206897",
            "id": "customer:3128"
          },
          {
            "series": "1",
            "index": "626",
            "xExact": "",
            "x": "627",
            "yExact": "",
            "y": "1",
            "id": "customer:3128"
          },
          {
            "series": "0",
            "index": "627",
            "xExact": "",
            "x": "628",
            "yExact": "",
            "y": "0.0377358491",
            "id": "customer:3134"
          },
          {
            "series": "1",
            "index": "627",
            "xExact": "",
            "x": "628",
            "yExact": "",
            "y": "0",
            "id": "customer:3134"
          },
          {
            "series": "0",
            "index": "628",
            "xExact": "",
            "x": "629",
            "yExact": "",
            "y": "0.173913043",
            "id": "customer:3140"
          },
          {
            "series": "1",
            "index": "628",
            "xExact": "",
            "x": "629",
            "yExact": "",
            "y": "0",
            "id": "customer:3140"
          },
          {
            "series": "0",
            "index": "629",
            "xExact": "",
            "x": "630",
            "yExact": "",
            "y": "0.173913043",
            "id": "customer:3145"
          },
          {
            "series": "1",
            "index": "629",
            "xExact": "",
            "x": "630",
            "yExact": "",
            "y": "0",
            "id": "customer:3145"
          }
        ],
        "plotFile": "ml14-fixed-results/realdata-company-r/plot.svg",
        "plotSHA256": "85d14766558c40eae5e9d527ae549630e25341a7e1f6ce802f7bf6d026d3c222",
        "files": [
          {
            "file": "ml14-fixed-results/realdata-company-r/full.txt",
            "sha256": "5c4f01c866f93ea942c794673f50622b261a7cecf9fd55f8fddc8a9a21263a5b",
            "bytes": 622187
          },
          {
            "file": "ml14-fixed-results/realdata-company-r/plot-points.csv",
            "sha256": "17cfc376b9fa055323b07a973219e98af999114f43e79b8430736ddff804fd26",
            "bytes": 54759
          },
          {
            "file": "ml14-fixed-results/realdata-company-r/plot.svg",
            "sha256": "85d14766558c40eae5e9d527ae549630e25341a7e1f6ce802f7bf6d026d3c222",
            "bytes": 74657
          },
          {
            "file": "ml14-fixed-results/realdata-company-r/summary.csv",
            "sha256": "6602993d0763bdd32e887d071cbc1e7344bed60437e4e193e0bbb6826b69450b",
            "bytes": 601
          }
        ],
        "scope": "Actually executed standalone fixed example, Python exact Fraction versus base-R binary64. Approximate R residuals retained; not universal exact arithmetic/web validation/native UI. Source programs read factual3CSV only."
      }
    }
  }
,
"publicationProjection":{"kind": "recorded-source-and-execution-path-omission", "originalFileSHA256": "5eb39624105ed17edf5d607fc7b3ba0f044902b84b97111ed7d34538646815cf", "changedStringFields": 1, "note": {"ko": "원자료·실행 기록의 시스템별 경로를 생략했습니다. 보관 원본·코드·자료·종료 상태·수치는 유지합니다. 이 경로 표시는 새로 실행한 명령을 뜻하지 않습니다.", "en": "System-specific paths in source and execution metadata are omitted. Archived originals, code, data, return status and numerical values are preserved. These path labels do not claim a new or differently executed command."}}}
