{
  "split": {
    "python": {
      "same-group-roles": {
        "api": "split",
        "variant": "same-group-roles",
        "language": "python",
        "title": "Planned roles for shared groups",
        "titleI18n": {
          "ko": "같은 묶음의 예정 역할",
          "en": "Planned roles for shared groups"
        },
        "input": {
          "rows": [
            {
              "id": "a",
              "group": "G"
            },
            {
              "id": "b",
              "group": "G"
            },
            {
              "id": "c",
              "group": "H"
            },
            {
              "id": "d",
              "group": "I"
            }
          ],
          "seed": 0
        },
        "expectedFailure": false,
        "codeFile": "ml22-code/split-same-group-roles.py",
        "codeSHA256": "baf91dc88e5e853e5bae603a33a6564372c5f47224d2c2c403937e8a6c047467",
        "code": "# ML22 standalone fixed literal. Attribution and arithmetic scope in README.\nimport csv,hashlib,html,json,math,sys,time\nfrom pathlib import Path\nfrom fractions import Fraction as F\nfrom collections import Counter\nsys.set_int_max_str_digits(200000)\nnumber=lambda v:F(str(v))\ndef Q(x):return None if x is None or x in ('','.') else F(str(x))\n\ndef canonical(v):return None if Q(v) is None else str(Q(v))\n\ndef fingerprint(tag,values):return tag+':'+hashlib.sha256(json.dumps([canonical(x)for x in values],separators=(',',':')).encode()).hexdigest()\n\ndef split(rows,seed=20261104,pattern=('test','validation','train','train')):\n order=sorted(set(r['group'] for r in rows));state=seed\n for j in range(len(order)-1,0,-1):state=(1664525*state+1013904223)&0xffffffff;k=state%(j+1);order[k],order[j]=order[j],order[k]\n roles={g:(i,pattern[i%len(pattern)]) for i,g in enumerate(order)}\n return roles,state,order\n\ndef solve(A,b):\n n=len(b);M=[list(row)+[rhs]for row,rhs in zip(A,b)];piv=[];rank=0\n for j in range(n):\n  candidates=[i for i in range(rank,n)if M[i][j]]\n  if not candidates:continue\n  k=max(candidates,key=lambda i:abs(M[i][j]));M[rank],M[k]=M[k],M[rank];v=M[rank][j];M[rank]=[x/v for x in M[rank]]\n  for i in range(n):\n   if i!=rank:\n    v=M[i][j];M[i]=[a-v*b for a,b in zip(M[i],M[rank])]\n  piv.append(j);rank+=1\n x=[F(0)]*n\n for i,j in enumerate(piv):x[j]=M[i][-1]\n null=[]\n for j in range(n):\n  if j not in piv:\n   v=[F(0)]*n;v[j]=F(1)\n   for i,k in enumerate(piv):v[k]=-M[i][j]\n   null.append(v)\n return x,rank,null\n\ndef dot(a,b):return sum((x*y for x,y in zip(a,b)),F(0))\n\ndef fit(rows,method,lam=F(0),minleaf=1,binary=False):\n use=[r for r in rows if r['role']=='train'and r['w']>0 and r['y']is not None and None not in r['x']];p=len(rows[0]['x'])if rows else 0\n if not use:return dict(defined=False,pred=[None]*len(rows),raw=[None]*len(rows),train=[],invariant=[None]*len(rows))\n mass=sum(r['w']for r in use);mu=[sum(r['w']*r['x'][j]for r in use)/mass for j in range(p)];scale=[max(r['x'][j]for r in use)-min(r['x'][j]for r in use)or F(1)for j in range(p)];mean=sum(r['w']*r['y']for r in use)/mass;model={};z=lambda r:[F(1)]+[(x-m)/s for x,m,s in zip(r['x'],mu,scale)]\n if method=='constant':model=dict(mean=mean,parameterCount=1,rank=1,unique=True)\n elif method=='ridge':\n  vectors=[z(r)for r in use];n=p+1;A=[[sum(r['w']*xx[j]*xx[k]for r,xx in zip(use,vectors))/mass+(lam if j==k and j>0 else F(0))for k in range(n)]for j in range(n)];b=[sum(r['w']*r['y']*xx[j]for r,xx in zip(use,vectors))/mass for j in range(n)];theta,rank,null=solve(A,b);objective=sum(r['w']*(dot(xx,theta)-r['y'])**2 for r,xx in zip(use,vectors))/(2*mass)+lam*sum(x*x for x in theta[1:])/2;model=dict(lambdaValue=lam,theta=theta,rank=rank,unique=rank==n,nullspace=null,minimumObjective=objective,parameterCount=n)\n else:\n  best=None;total=sum(r['w']*r['y']for r in use);total2=sum(r['w']*r['y']**2 for r in use);base=total2-total**2/mass\n  for j in range(p):\n   ordered=sorted(enumerate(use),key=lambda v:(v[1]['x'][j],v[0]));leftW=F(0);leftS=F(0)\n   for i,(_idx,r)in enumerate(ordered[:-1]):\n    leftW+=r['w'];leftS+=r['w']*r['y'];rightW=mass-leftW\n    if i+1<minleaf or len(use)-i-1<minleaf or r['x'][j]==ordered[i+1][1]['x'][j]:continue\n    SSE=total2-leftS**2/leftW-(total-leftS)**2/rightW\n    if best is None or SSE<best['weightedSSE']:best=dict(feature=j,threshold=(r['x'][j]+ordered[i+1][1]['x'][j])/2,leftMean=leftS/leftW,rightMean=(total-leftS)/rightW,leftRows=i+1,rightRows=len(use)-i-1,leftWeight=leftW,rightWeight=rightW,weightedSSE=SSE)\n  model=dict(split=False,mean=mean,weightedSSE=base,trainingMSE=base/mass)if best is None or best['weightedSSE']>=base else dict(split=True,**best,trainingMSE=best['weightedSSE']/mass,improvement=(base-best['weightedSSE'])/mass)\n raw=[];invariant=[]\n for r in rows:\n  if None in r['x']:raw.append(None);invariant.append(None);continue\n  if method=='constant':v=mean;iv=True\n  elif method=='ridge':zz=z(r);v=dot(zz,model['theta']);iv=all(dot(zz,nn)==0 for nn in model['nullspace'])\n  else:v=(model['leftMean']if r['x'][model['feature']]<=model['threshold']else model['rightMean'])if model['split']else mean;iv=True\n  raw.append(v);invariant.append(iv)\n pred=[None if x is None else min(F(1),max(F(0),x))if binary else x for x in raw]\n return dict(defined=True,train=[r['id']for r in use],mass=mass,meanX=mu,scales=scale,model=model,pred=pred,raw=raw,invariant=invariant)\n\ndef risk(rows,pred,binary=False,threshold=F(1,2)):\n use=[(r,p)for r,p in zip(rows,pred)if r['w']>0 and r['y']is not None and p is not None and r['role']not in['excluded','unused']];mass=sum((r['w']for r,p in use),F(0));d=dict(rows=len(use),mass=mass)\n if not mass:\n  d.update({k:None for k in ['MSE','MAE','R2']+(['Brier','accuracy','balancedAccuracy','AUROC']if binary else[])});return d\n mean=sum(r['w']*r['y']for r,p in use)/mass;sse=sum(r['w']*(p-r['y'])**2 for r,p in use);sst=sum(r['w']*(r['y']-mean)**2 for r,p in use);d.update(meanY=mean,SSE=sse,SST=sst,MSE=sse/mass,MAE=sum(r['w']*abs(p-r['y'])for r,p in use)/mass,R2=1-sse/sst if sst else None)\n if binary:\n  weights=Counter();num=Counter()\n  for r,p in use:k=('T'if int(p>=threshold)==int(r['y'])else'F')+('P'if p>=threshold else'N');weights[k]+=r['w'];num[k]+=1\n  TP,FP,TN,FN=[weights[k]for k in ['TP','FP','TN','FN']];positive=TP+FN;negative=TN+FP;rate=lambda a,b:a/b if b else None;TPR=rate(TP,positive);TNR=rate(TN,negative)\n  # Pair enumeration is independent of the subject's score-tie-block formula.\n  negatives=[(r,p)for r,p in use if not r['y']];positives=[(r,p)for r,p in use if r['y']];wins=sum((a['w']*b['w']*(F(1)if pa>pb else F(1,2)if pa==pb else F(0))for a,pa in positives for b,pb in negatives),F(0))\n  d.update(Brier=d['MSE'],threshold=threshold,confusionMass={k:weights[k]for k in ['TP','FP','TN','FN']},confusionRows={k:num[k]for k in ['TP','FP','TN','FN']},positiveMass=positive,negativeMass=negative,accuracy=(TP+TN)/mass,positiveRecall=TPR,negativeRecall=TNR,precision=rate(TP,TP+FP),F1=rate(2*TP,2*TP+FP+FN),balancedAccuracy=(TPR+TNR)/2 if TPR is not None and TNR is not None else None,AUROC=rate(wins,positive*negative))\n return d\n\nNATIVE_SHA256={'actual1599-red-wine-original12-fields.csv': '77e9ac73115930d6c43983333a5a57940deefc493affeb17aca478c09c5f6e00', 'actual4898-white-wine-original12-fields.csv': '50d810bbb42b9cc3e87fa4c27a4c0f168e72da09dd812863425ca3873fec28ef', 'actual3613-NLS-original52-fields.csv': '6e1e1895558795435b65f8634252a7589865273a0e69adbd715fcfa04a3c11a1', 'actual3150-churn-original14-fields.csv': '1c0753e434226e769d1015c922121a7d8967df66014e057c4f7543e490f11764'}\n\ndef read_sources(directory,seed):\n def read(name):\n  p=directory/name\n  if hashlib.sha256(p.read_bytes()).hexdigest()!=NATIVE_SHA256[name]:raise ValueError('Native file hash differs: '+name)\n  with p.open(encoding='utf8',newline='')as f:return list(csv.DictReader(f))\n sources={};wine=[]\n for typ,n in [('red',1599),('white',4898)]:\n  table=read(f'actual{n}-{typ}-wine-original12-fields.csv');assert len(table)==n;features=[k for k in table[0]if k not in ['sourceRow','wineType','quality']];assert len(features)==11\n  for r in table:\n   i=int(r['sourceRow']);red='1'if typ=='red'else'0';nativeX=[r[k]for k in features];wine.append(dict(id=f'wine-{typ}-row:{i}',sourceRow=f'{typ}:{i}',originalID=None,group=fingerprint('wine-predictors',[red]+nativeX),cohort=typ,x=list(map(Q,nativeX+[red])),y=Q(r['quality'])))\n sources['country']=wine\n table=read('actual3613-NLS-original52-fields.csv');assert len(table)==3613;sources['person']=[dict(id='nls-row:'+r['sourceRow'],sourceRow=int(r['sourceRow']),originalID=r['id'],group='nls-id:'+r['id'],cohort='schooling-over12'if Q(r['ed76'])>12 else'schooling-at-most12',x=[Q(r['ed76']),Q(r['age76'])],y=Q(r['lwage76']))for r in table]\n table=read('actual3150-churn-original14-fields.csv');assert len(table)==3150;predictors=[k for k in table[0]if k not in ['sourceRow','Churn']];assert len(predictors)==13;sources['company']=[dict(id='customer-row:'+r['sourceRow'],sourceRow=int(r['sourceRow']),originalID=None,group=fingerprint('customer-predictors',[r[k]for k in predictors]),cohort='pay-as-you-go'if r['Tariff Plan']=='1'else'contractual'if r['Tariff Plan']=='2'else'other-native-tariff',x=[Q(r[k])for k in ['Call  Failure','Subscription  Length','Seconds of Use','Age']],y=Q(r['Churn']))for r in table]\n for kind,rows in sources.items():\n  assignments,state,order=split(rows,seed)\n  for r in rows:\n   rank,planned=assignments[r['group']];r.update(w=F(1),splitRank=rank,plannedRole=planned,eligible=r['y']is not None and None not in r['x']);r['role']=planned if r['eligible']else'excluded'\n return sources\n# New ML22 fixed-profile kernels. The public Fraction fitting/source readers are\n# copied by value above this file by the standalone builder; never imported.\ndef fixed_rows(data, prediction_key=None):\n out=[]\n for i,a in enumerate(data):\n  w=Q(a.get('weight','1'))\n  if w is None or w<0:raise ValueError('negative-weight' if w is not None and w<0 else 'missing-weight')\n  out.append(dict(id=a.get('id',str(i)),group=a.get('group',a.get('id',str(i))),cohort=a.get('cohort','all'),role=a.get('role','train'),w=w,x=[Q(v)for v in a.get('x',[])],y=Q(a.get('y'))))\n return out\n\ndef weighted_pair(rows,A,B):\n use=[(r,a,b)for r,a,b in zip(rows,A,B)if r['w']>0 and r['y']is not None and a is not None and b is not None and r['role']not in ['excluded','unused']]\n mass=sum((r['w']for r,a,b in use),F(0));records=[];groups={}\n for r,a,b in use:\n  la=(a-r['y'])**2;lb=(b-r['y'])**2;d=la-lb\n  records.append(dict(id=r['id'],group=r['group'],weight=r['w'],lossA=la,lossB=lb,difference=d))\n  g=groups.setdefault(r['group'],dict(group=r['group'],rows=0,mass=F(0),sum=F(0)));g['rows']+=1;g['mass']+=r['w'];g['sum']+=r['w']*d\n total=sum((g['sum']for g in groups.values()),F(0));mean=total/mass if mass else None;G=len(groups)\n for g in groups.values():g['leaveOut']=(total-g['sum'])/(mass-g['mass'])if mass>g['mass']else None\n leaves=[g['leaveOut']for g in groups.values()if g['leaveOut']is not None]\n proxy=F(G-1,G)*sum((v-sum(leaves,F(0))/G)**2 for v in leaves) if G>1 and len(leaves)==G else None\n return dict(rows=len(use),mass=mass,groupCount=G,meanDifference=mean,minimumLeaveOut=min(leaves)if leaves else None,maximumLeaveOut=max(leaves)if leaves else None,varianceProxy=proxy,groups=list(groups.values()),records=records)\n\ndef run_selection(rows,candidates,criterion,required,binary=False):\n results=[]\n for c,pred in candidates:\n  val=[dict(r,role='excluded')if r['role']!='validation'else r for r in rows]\n  test=[dict(r,role='excluded')if r['role']!='test'else r for r in rows]\n  v=risk(val,pred,binary);t=risk(test,pred,binary);cohort={g:risk([dict(r,role='excluded')if r['role']!='validation'or r['cohort']!=g else r for r in rows],pred,binary)for g in required}\n  values=[cohort[g]['MSE']for g in required]\n  score=v['MSE']if criterion=='mean'else max(values)if values and None not in values else None\n  results.append(dict(id=c,criterion=score,validation=v,test=t,cohorts=cohort))\n eligible=[(i,r['criterion'])for i,r in enumerate(results)if r['criterion']is not None]\n chosen=min(eligible,key=lambda t:(t[1],t[0]))[0]if eligible else None\n return dict(criterion=criterion,selected=results[chosen]['id']if chosen is not None else None,selectedIndex=chosen,candidates=results)\n\ndef fixed_operation(api,a):\n if api=='realdata':\n  kind=a['kind'];rows=read_sources(Path(__file__).parent/'data',a.get('seed',20261104))[kind];binary=kind=='company'\n  defs=[('constant','constant',F(0)),('ridge:1/100','ridge',F(1,100)),('ridge:1/10','ridge',F(1,10)),('ridge:1','ridge',F(1)),('one-split-stump','stump',F(0))]\n  fits=[fit(rows,method,lam,5,binary)for _,method,lam in defs]\n  selection=run_selection(rows,[(d[0],f['pred'])for d,f in zip(defs,fits)],a.get('criterion','mean'),list(dict.fromkeys(r['cohort']for r in rows)),binary)\n  chosen=selection['selectedIndex'];best=fits[chosen];base=fits[0]\n  test=[dict(r,role='excluded')if r['role']!='test'else r for r in rows]\n  paired=weighted_pair(test,best['pred'],base['pred'])\n  records=[dict(id=r['id'],sourceRow=r.get('sourceRow'),originalID=r.get('originalID'),group=r['group'],cohort=r['cohort'],plannedRole=r['plannedRole'],role=r['role'],eligible=r['eligible'],y=r['y'],baselinePrediction=base['pred'][i],selectedPrediction=best['pred'][i],selectedRawPrediction=best['raw'][i],queryInvariant=best['invariant'][i])for i,r in enumerate(rows)]\n  return dict(kind=kind,nativeRows=len(rows),eligibleRows=sum(r['eligible']for r in rows),selection=selection,models=[dict(id=d[0],train=f['train'],mass=f.get('mass'),meanX=f.get('meanX'),scales=f.get('scales'),model=f.get('model'))for d,f in zip(defs,fits)],paired=paired,records=records)\n rows=fixed_rows(a.get('rows',[]));binary=a.get('task')=='binary'\n if api=='split':\n  assignment,state,order=split(rows,a.get('seed',0));records=[dict(id=r['id'],group=r['group'],rank=assignment[r['group']][0],role=assignment[r['group']][1])for r in rows]\n  return dict(state=state,groupOrder=order,records=records,groupCount=len(order))\n if api=='fit':return fit(rows,a.get('method','constant'),Q(a.get('lambda','0')),a.get('minLeafRows',1),binary)\n if api=='evaluate':\n  pred=[Q(r.get('prediction'))for r in a['rows']];threshold=Q(a.get('threshold','1/2'));rr=risk(rows,pred,binary,threshold)\n  records=[]\n  for r,p in zip(rows,pred):\n   valid=r['w']>0 and r['y']is not None and p is not None and r['role']not in ['excluded','unused']\n   records.append(dict(id=r['id'],weight=r['w'],y=r['y'],prediction=p,eligible=valid,loss=(p-r['y'])**2 if valid else None,correct=dict(defined=valid and binary,value=bool(int(p>=threshold)==int(r['y']))if valid and binary else None)))\n  return dict(metrics=rr,records=records)\n if api=='select':return run_selection(rows,[(c['id'],list(map(Q,c['predictions'])))for c in a['candidates']],a.get('criterion','mean'),a.get('requiredCohorts',list(dict.fromkeys(r['cohort']for r in rows))),binary)\n if api=='paired':return weighted_pair(rows,[Q(r.get('predictionA'))for r in a['rows']],[Q(r.get('predictionB'))for r in a['rows']])\n raise ValueError('unknown-api')\n\ndef report_values(api,z):\n summary=[];series=[]\n def add(k,v,u='dimensionless'):summary.append((k,v,u))\n if api=='split':\n  add('groups',z['groupCount'],'groups');add('rows',len(z['records']),'rows');add('finalState',z['state'],'unsigned 32-bit state')\n  series=[('planned role code',[(i,F({'test':0,'validation':1,'train':2}[r['role']]))for i,r in enumerate(z['records'])])]\n elif api=='fit':\n  add('defined',z['defined']);add('trainingRows',len(z['train']),'rows');add('trainingMass',z.get('mass'),'analysis weight mass')\n  model=z.get('model',{});add('modelRank',model.get('rank'),'parameters');add('threshold',model.get('threshold'),'constructed feature units');add('minimumObjective',model.get('minimumObjective'),'constructed squared outcome units')\n  series=[('prediction',list(enumerate(z['pred'])))];\n  if model.get('theta')is not None:\n   for i,v in enumerate(model['theta']):add('theta'+str(i),v,'constructed outcome units per standardized coordinate')\n elif api=='evaluate':\n  for k in ['rows','mass','MSE','MAE','R2','Brier','accuracy','positiveRecall','negativeRecall','precision','F1','balancedAccuracy','AUROC']: \n   if k in z['metrics']:add(k,z['metrics'][k],'rows'if k=='rows'else'analysis weight mass'if k=='mass'else FIXED['unit']if k in ['MSE','Brier']else'constructed outcome units'if k=='MAE'else'dimensionless')\n  series=[('squared loss',[(i,r['loss'])for i,r in enumerate(z['records'])])]\n elif api=='select':\n  add('selectedIndex',z['selectedIndex'],'zero-based candidate index')\n  for i,c in enumerate(z['candidates']):add('criterion'+str(i),c['criterion'],FIXED['unit']);add('testMSE'+str(i),c['test']['MSE'],FIXED['unit'])\n  series=[('validation criterion',[(i,c['criterion'])for i,c in enumerate(z['candidates'])]),('test MSE',[(i,c['test']['MSE'])for i,c in enumerate(z['candidates'])])]\n elif api=='paired':\n  for k in ['rows','mass','groupCount','meanDifference','minimumLeaveOut','maximumLeaveOut','varianceProxy']:add(k,z[k],'rows'if k=='rows'else'groups'if k=='groupCount'else'analysis weight mass'if k=='mass'else FIXED['unit']+' squared'if k=='varianceProxy'else FIXED['unit'])\n  series=[('loss A minus loss B',[(i,r['difference'])for i,r in enumerate(z['records'])])]\n elif api=='realdata':\n  add('nativeRows',z['nativeRows'],'native records');add('eligibleRows',z['eligibleRows'],'complete records');add('selectedIndex',z['selection']['selectedIndex'],'zero-based candidate index')\n  for i,c in enumerate(z['selection']['candidates']):add('validationMSE'+str(i),c['validation']['MSE'],FIXED['unit']);add('testMSE'+str(i),c['test']['MSE'],FIXED['unit'])\n  for k in ['meanDifference','minimumLeaveOut','maximumLeaveOut','varianceProxy']:add(k,z['paired'][k],FIXED['unit']+' squared'if k=='varianceProxy'else FIXED['unit'])\n  best=z['selection']['candidates'][z['selection']['selectedIndex']]['test']\n  for k in ['accuracy','positiveRecall','negativeRecall','precision','balancedAccuracy','AUROC']:\n   if k in best:add(k,best[k])\n  series=[('validation MSE',[(i,c['validation']['MSE'])for i,c in enumerate(z['selection']['candidates'])]),('test MSE',[(i,c['test']['MSE'])for i,c in enumerate(z['selection']['candidates'])])]\n return summary,series\n\n\ndef fixed_svg(points,title):\n good=[p for p in points if p['y'] is not None];xx=[float(p['x'])for p in good];yy=[float(p['y'])for p in good];xmin=min(xx)if xx else 0;xmax=max(xx)if xx else 1;ymin=min([0]+yy);ymax=max([0]+yy)\n if xmin==xmax:xmin-=.5;xmax+=.5\n if ymin==ymax:ymin-=.5;ymax+=.5\n pad=(ymax-ymin)*.08;ymin-=pad;ymax+=pad;X=lambda x:82+(float(x)-xmin)/(xmax-xmin)*608;Y=lambda y:354-(float(y)-ymin)/(ymax-ymin)*290;e=html.escape\n out=['<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"720\" height=\"480\" viewBox=\"0 0 720 480\" role=\"img\" aria-label=\"'+e(title)+'\"><rect width=\"720\" height=\"480\" fill=\"white\"/><g font-family=\"Arial,sans-serif\" font-size=\"13\" fill=\"#18232f\"><text x=\"360\" y=\"25\" text-anchor=\"middle\">'+e(title)+'</text>']\n for j in range(5):\n  y=ymin+(ymax-ymin)*j/4;x=xmin+(xmax-xmin)*j/4;out.append('<line x1=\"82\" y1=\"'+str(Y(y))+'\" x2=\"690\" y2=\"'+str(Y(y))+'\" stroke=\"#e2e8f0\"/><text x=\"73\" y=\"'+str(Y(y)+4)+'\" text-anchor=\"end\">'+format(y,'.3g')+'</text><text x=\"'+str(X(x))+'\" y=\"380\" text-anchor=\"middle\">'+format(x,'.3g')+'</text>')\n series=list(dict.fromkeys(p['series']for p in good))\n for j,s in enumerate(series):\n  pp=[p for p in good if p['series']==s];color=['#0f766e','#c76622','#4f46e5','#b23857'][j%4]\n  for p in pp:out.append('<circle cx=\"'+format(X(p['x']),'.6f')+'\" cy=\"'+format(Y(p['y']),'.6f')+'\" r=\"2.6\" fill=\"'+color+'\"><title>'+e(s+': '+str(p['y']))+'</title></circle>')\n  out.append('<text x=\"'+str(82+(j%2)*310)+'\" y=\"'+str(432+(j//2)*23)+'\" fill=\"'+color+'\">'+e(s)+'</text>')\n out.append('<text x=\"360\" y=\"405\" text-anchor=\"middle\">Declared record / candidate index; units in summary</text></g></svg>');return''.join(out)\n\nFIXED={'api': 'split', 'variant': 'same-group-roles', 'title': 'Planned roles for shared groups', 'input': {'rows': [{'id': 'a', 'group': 'G'}, {'id': 'b', 'group': 'G'}, {'id': 'c', 'group': 'H'}, {'id': 'd', 'group': 'I'}], 'seed': 0}, 'unit': 'Declared role code; not a probability', 'titleI18n': {'ko': '같은 묶음의 예정 역할', 'en': 'Planned roles for shared groups'}}\n\nOUT=Path(sys.argv[1]);OUT.mkdir(parents=True,exist_ok=False)\nresult=fixed_operation(FIXED['api'],FIXED['input']);summary,series=report_values(FIXED['api'],result)\ndef encode(v):\n if isinstance(v,F):return str(v)\n if isinstance(v,dict):return{k:encode(x)for k,x in v.items()}\n if isinstance(v,(list,tuple)):return[encode(x)for x in v]\n return v\n(OUT/'full.json').write_text(json.dumps(dict(arithmetic='Exact rational author implementation; factual rows, declared group split and finite five-candidate comparison',result=encode(result)),ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\nsummaryRows=[dict(metric=m,value=''if v is None else str(int(v))if isinstance(v,bool)else str(v),unit=u,defined=int(v is not None))for m,v,u in summary]\npoints=[dict(series=name,index=i,x=str(x),y=''if y is None else str(y),defined=int(y is not None))for name,pp in series for i,(x,y)in enumerate(pp)]\nfor name,rows in [('summary',summaryRows),('plot-points',points)]:\n with(OUT/(name+'.csv')).open('w',encoding='utf8',newline='')as f:writer=csv.DictWriter(f,fieldnames=list(rows[0]));writer.writeheader();writer.writerows(rows)\n(OUT/'plot.svg').write_text(fixed_svg([dict(p,x=number(p['x']),y=None if not p['defined']else number(p['y']))for p in points],FIXED['title']),encoding='utf8');print(FIXED['api']+'/'+FIXED['variant'])\n",
        "returnCode": 0,
        "stdout": "split/same-group-roles\r\n",
        "stderr": "",
        "diagnosticScope": "Public projection omits private absolute-path/traceback frames; actual exit and warnings/reason retained. Raw complete streams and commands in private execution proof.",
        "resultFolder": "ml22-code/runs/python-split-same-group-roles",
        "kind": null,
        "inputFiles": [
          {
            "file": "ml22-code/split-same-group-roles-input.json",
            "sha256": "e170d98ce7a016e785994454b80d4bd1e71e36ec1ad3cb56cbc658d71cc3f918",
            "scope": "Complete fixed literal input; program embeds the same values"
          }
        ],
        "files": [
          {
            "file": "ml22-code/runs/python-split-same-group-roles/full.json",
            "sha256": "7f4ae8f31daf6b7f28fa97924dfba849b3d469e83d43bc329fda5ff4ea1489e7",
            "bytes": 729
          },
          {
            "file": "ml22-code/runs/python-split-same-group-roles/plot-points.csv",
            "sha256": "cb8fa9112a71595f19a1dd4090cda27805b43c11d8a3b551e53b13248b846caf",
            "bytes": 134
          },
          {
            "file": "ml22-code/runs/python-split-same-group-roles/plot.svg",
            "sha256": "4fe7aa0d8c34d67ebd406d3d9f250dbf965e96c8e63e545e821f142e67a445cb",
            "bytes": 1771
          },
          {
            "file": "ml22-code/runs/python-split-same-group-roles/summary.csv",
            "sha256": "275b6224199feeb45768a82c74585f1037e81edf6264799c4f488ae32645b788",
            "bytes": 108
          }
        ],
        "summaryRows": [
          {
            "metric": "groups",
            "value": "3.0",
            "unit": "groups",
            "defined": "true",
            "rawValue": "3",
            "arithmetic": "Exact Fraction",
            "exactFraction": "3",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "rows",
            "value": "4.0",
            "unit": "rows",
            "defined": "true",
            "rawValue": "4",
            "arithmetic": "Exact Fraction",
            "exactFraction": "4",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "finalState",
            "value": "1196435762.0",
            "unit": "unsigned 32-bit state",
            "defined": "true",
            "rawValue": "1196435762",
            "arithmetic": "Exact Fraction",
            "exactFraction": "1196435762",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          }
        ],
        "plotRows": [
          {
            "series": "planned role code",
            "index": "0",
            "x": "0",
            "y": "1",
            "defined": true,
            "xExact": "0",
            "yExact": "1"
          },
          {
            "series": "planned role code",
            "index": "1",
            "x": "1",
            "y": "1",
            "defined": true,
            "xExact": "1",
            "yExact": "1"
          },
          {
            "series": "planned role code",
            "index": "2",
            "x": "2",
            "y": "2",
            "defined": true,
            "xExact": "2",
            "yExact": "2"
          },
          {
            "series": "planned role code",
            "index": "3",
            "x": "3",
            "y": "0",
            "defined": true,
            "xExact": "3",
            "yExact": "0"
          }
        ],
        "plotFile": "ml22-code/runs/python-split-same-group-roles/plot.svg",
        "fullResultFile": "ml22-code/runs/python-split-same-group-roles/full.json",
        "arithmeticScope": "Python exact rational versus base-R approximate floating algebra; copied author kernels, not independent oracle.",
        "plotScope": "Original scatter vectors plot every defined declared comparison point, with missing points omitted. Source profiles show candidate risks; all source records remain in the full result and source CSV files.",
        "reproductionScope": "Standalone literal program plus four native CSV files for factual source profiles. No answer/engine/checker imports."
      }
    },
    "r": {
      "same-group-roles": {
        "api": "split",
        "variant": "same-group-roles",
        "language": "r",
        "title": "Planned roles for shared groups",
        "titleI18n": {
          "ko": "같은 묶음의 예정 역할",
          "en": "Planned roles for shared groups"
        },
        "input": {
          "rows": [
            {
              "id": "a",
              "group": "G"
            },
            {
              "id": "b",
              "group": "G"
            },
            {
              "id": "c",
              "group": "H"
            },
            {
              "id": "d",
              "group": "I"
            }
          ],
          "seed": 0
        },
        "expectedFailure": false,
        "codeFile": "ml22-code/split-same-group-roles.R",
        "codeSHA256": "860937e813b2f012e36fd62efbaff397fa8aec2ea8fd51ef54fb231a3ae11b81",
        "code": "# ML22 standalone; source/public functions copied by value, no source() dependency.\noptions(stringsAsFactors=FALSE,digits=17,warn=1)\nargs0<-commandArgs(trailingOnly=FALSE);script0<-sub('^--file=','',args0[grepl('^--file=',args0)][1]);source_dir<-file.path(dirname(normalizePath(script0)), 'data');seed<-20261104;leaf_min<-5\nnative_hash <- c(\"actual1599-red-wine-original12-fields.csv\"=\"77e9ac73115930d6c43983333a5a57940deefc493affeb17aca478c09c5f6e00\",\"actual4898-white-wine-original12-fields.csv\"=\"50d810bbb42b9cc3e87fa4c27a4c0f168e72da09dd812863425ca3873fec28ef\",\"actual3613-NLS-original52-fields.csv\"=\"6e1e1895558795435b65f8634252a7589865273a0e69adbd715fcfa04a3c11a1\",\"actual3150-churn-original14-fields.csv\"=\"1c0753e434226e769d1015c922121a7d8967df66014e057c4f7543e490f11764\")\nsha256<-getExportedValue('tools','sha256sum')\nread_native<-function(name){f<-file.path(source_dir,name);if(unname(sha256(f))!=native_hash[[name]])stop(paste('Native hash differs',name));read.csv(f,check.names=FALSE,colClasses='character',na.strings=NULL)}\ngcd_small<-function(a,b){while(b!=0){r<-a%%b;a<-b;b<-r};a}\ncanonical<-function(token){\n if(is.na(token)||token%in%c('','.'))return('null')\n if(!grepl('^[+-]?[0-9]+([.][0-9]*)?$',token))stop('Unsupported native fingerprint token')\n neg<-substr(token,1,1)=='-';s<-sub('^[+-]','',token);parts<-strsplit(s,'.',fixed=TRUE)[[1]];dec<-if(length(parts)==2)nchar(parts[2])else 0;n<-as.numeric(gsub('.','',s,fixed=TRUE));d<-10^dec\n # Every native fingerprint numerator/denominator must remain exactly integral\n # in binary64; reject rather than silently rounding a changed future source.\n if(!is.finite(n)||n>2^53||d>2^53)stop('Native canonical integer range exceeded')\n g<-gcd_small(n,d);n<-n/g;d<-d/g;if(neg)n<--n\n out<-sprintf('%.0f',n);if(d!=1)out<-paste0(out,'/',sprintf('%.0f',d));out\n}\nfp_cache<-new.env(hash=TRUE,parent=emptyenv());hash_file<-tempfile('ml22-hash-')\nfingerprint<-function(tag,values){a<-vapply(values,canonical,'');payload<-paste0('[',paste0('\"',a,'\"',collapse=','),']');key<-paste0(tag,':',payload);if(exists(key,fp_cache,inherits=FALSE))return(get(key,fp_cache,inherits=FALSE));con<-file(hash_file,'wb');writeBin(charToRaw(payload),con);close(con);value<-paste0(tag,':',unname(sha256(hash_file)));assign(key,value,fp_cache);value}\nassign_roles<-function(group){order<-sort(unique(group),method='radix');state<-seed;if(length(order)>1)for(j in seq.int(length(order),2)){state<-(1664525*state+1013904223)%%2^32;k<-state%%j+1;order[c(j,k)]<-order[c(k,j)]};rank<-match(group,order)-1;list(rank=rank,planned=c('test','validation','train','train')[rank%%4+1],state=state)}\n\nfit_model<-function(r,x,method,lambda){\n tr<-which(r$role=='train'&r$eligible);if(!length(tr))stop('No complete positive training rows');y<-r$y[tr];xx<-x[tr,,drop=FALSE];mu<-colMeans(xx);scale<-apply(xx,2,function(v)diff(range(v)));scale[scale==0]<-1;z<-cbind(1,sweep(sweep(x,2,mu,'-'),2,scale,'/'));meanY<-mean(y);model<-list();n<-length(tr)\n if(method=='constant'){model<-list(mean=meanY,parameterCount=1,rank=1,unique=TRUE);raw<-rep(meanY,nrow(r))}\n else if(method=='ridge'){zt<-z[tr,,drop=FALSE];pen<-diag(c(0,rep(lambda,ncol(x))));theta<-drop(solve(crossprod(zt)/n+pen,crossprod(zt,y)/n));raw<-drop(z%*%theta);objective<-mean((y-raw[tr])^2)/2+lambda*sum(theta[-1]^2)/2;model<-list(lambdaValue=lambda,theta=theta,rank=length(theta),unique=TRUE,minimumObjective=objective,parameterCount=length(theta))}\n else{base<-sum((y-meanY)^2);best<-NULL;total<-sum(y);total2<-sum(y*y)\n  for(j in seq_len(ncol(x))){ord<-order(xx[,j],seq_len(n));sx<-xx[ord,j];sy<-y[ord];left<-cumsum(sy)\n   if(n<2*leaf_min)next\n   for(i in seq.int(leaf_min,n-leaf_min)){if(sx[i]==sx[i+1])next;loss<-total2-left[i]^2/i-(total-left[i])^2/(n-i)\n    # Explicit approximate-tie tolerance; exact source JavaScript/Python\n    # contracts are authoritative for general arbitrarily close ties.\n    if(is.null(best)||loss<best$weightedSSE-1e-12*max(1,abs(loss),abs(best$weightedSSE)))best<-list(feature=j-1,threshold=(sx[i]+sx[i+1])/2,leftMean=left[i]/i,rightMean=(total-left[i])/(n-i),leftRows=i,rightRows=n-i,leftWeight=i,rightWeight=n-i,weightedSSE=loss)\n   }\n  }\n  if(is.null(best)||best$weightedSSE>=base-1e-12*max(1,abs(base))){model<-list(split=FALSE,mean=meanY,weightedSSE=base,trainingMSE=base/n);raw<-rep(meanY,nrow(r))}else{model<-c(list(split=TRUE),best,list(trainingMSE=best$weightedSSE/n,improvement=(base-best$weightedSSE)/n));raw<-ifelse(x[,model$feature+1]<=model$threshold,model$leftMean,model$rightMean)}\n }\n pred<-if(r$dataset[1]=='company')pmax(0,pmin(1,raw))else raw;list(meanX=mu,scales=scale,model=model,raw=raw,pred=pred)\n}\n\n# New standalone fixed-profile adapters; native and fit helpers copied by value.\nnum<-function(x){if(is.null(x)||length(x)==0||is.na(x)||x%in%c('','.'))return(NA_real_);if(is.character(x)&&grepl('/',x,fixed=TRUE)){v<-strsplit(x,'/',fixed=TRUE)[[1]];return(as.numeric(v[1])/as.numeric(v[2]))};as.numeric(x)}\nfixedRows<-function(aa){\n rr<-lapply(seq_along(aa),function(i){a<-aa[[i]];w<-num(if(is.null(a$weight))'1'else a$weight);if(is.na(w)||w<0)stop(if(!is.na(w)&&w<0)'negative-weight'else'missing-weight');list(id=if(is.null(a$id))as.character(i-1)else a$id,group=if(is.null(a$group))if(is.null(a$id))as.character(i-1)else a$id else a$group,cohort=if(is.null(a$cohort))'all'else a$cohort,role=if(is.null(a$role))'train'else a$role,w=w,y=num(a$y),x=vapply(a$x,num,0.0))})\n p<-if(length(rr))length(rr[[1]]$x)else 0;xx<-matrix(NA_real_,length(rr),p)\n if(p)for(i in seq_along(rr))xx[i,]<-rr[[i]]$x\n r<-data.frame(id=vapply(rr,`[[`,'','id'),group=vapply(rr,`[[`,'','group'),cohort=vapply(rr,`[[`,'','cohort'),role=vapply(rr,`[[`,'','role'),w=vapply(rr,`[[`,0.0,'w'),y=vapply(rr,`[[`,0.0,'y'));r$eligible<-!is.na(r$y)&rowSums(is.na(xx))==0&r$w>0;list(r=r,x=xx)\n}\nweightedRisk<-function(r,p,binary=FALSE,threshold=.5){\n ii<-which(r$w>0&!is.na(r$y)&!is.na(p)&!r$role%in%c('excluded','unused'));y<-r$y[ii];p<-p[ii];w<-r$w[ii];W<-sum(w);d<-list(rows=length(ii),mass=W,MSE=NA_real_,MAE=NA_real_,R2=NA_real_)\n if(W==0){if(binary)d<-c(d,setNames(rep(list(NA_real_),10),c('Brier','accuracy','positiveRecall','negativeRecall','precision','F1','balancedAccuracy','AUROC','positiveMass','negativeMass')));return(d)}\n mu<-sum(w*y)/W;sse<-sum(w*(p-y)^2);sst<-sum(w*(y-mu)^2);d<-c(d,list(meanY=mu,SSE=sse,SST=sst));d$MSE<-sse/W;d$MAE<-sum(w*abs(p-y))/W;d$R2<-if(sst>0)1-sse/sst else NA_real_\n if(binary){pos<-y==1;yes<-p>=threshold;TP<-sum(w[pos&yes]);FP<-sum(w[!pos&yes]);TN<-sum(w[!pos&!yes]);FN<-sum(w[pos&!yes]);rate<-function(a,b)if(b>0)a/b else NA_real_;tpr<-rate(TP,TP+FN);tnr<-rate(TN,TN+FP);auc<-NA_real_;P<-sum(w[pos]);N<-sum(w[!pos]);if(P>0&&N>0){wins<-sum(vapply(which(pos),function(i)sum(w[i]*w[!pos]*ifelse(p[i]>p[!pos],1,ifelse(p[i]==p[!pos],.5,0))),0.0));auc<-wins/(P*N)};d<-c(d,list(Brier=d$MSE,threshold=threshold,confusionMass=list(TP=TP,FP=FP,TN=TN,FN=FN),confusionRows=list(TP=sum(pos&yes),FP=sum(!pos&yes),TN=sum(!pos&!yes),FN=sum(pos&!yes)),positiveMass=P,negativeMass=N,accuracy=(TP+TN)/W,positiveRecall=tpr,negativeRecall=tnr,precision=rate(TP,TP+FP),F1=rate(2*TP,2*TP+FP+FN),balancedAccuracy=if(is.finite(tpr)&&is.finite(tnr))(tpr+tnr)/2 else NA_real_,AUROC=auc))};d\n}\nweightedPair<-function(r,A,B){\n ii<-which(r$w>0&!is.na(r$y)&!is.na(A)&!is.na(B)&!r$role%in%c('excluded','unused'));rr<-r[ii,,drop=FALSE];la<-(A[ii]-rr$y)^2;lb<-(B[ii]-rr$y)^2;d<-la-lb;W<-sum(rr$w);S<-sum(rr$w*d);mu<-if(W>0)S/W else NA_real_;ids<-unique(rr$group);groups<-lapply(ids,function(g){jj<-which(rr$group==g);wg<-sum(rr$w[jj]);sg<-sum(rr$w[jj]*d[jj]);list(group=g,rows=length(jj),mass=wg,sum=sg,leaveOut=if(W>wg)(S-sg)/(W-wg)else NA_real_)});leaves<-vapply(groups,`[[`,0.0,'leaveOut');G<-length(groups);proxy<-if(G>1&&all(is.finite(leaves)))(G-1)/G*sum((leaves-mean(leaves))^2) else NA_real_\n list(rows=length(ii),mass=W,groupCount=G,meanDifference=mu,minimumLeaveOut=if(any(is.finite(leaves)))min(leaves,na.rm=TRUE)else NA_real_,maximumLeaveOut=if(any(is.finite(leaves)))max(leaves,na.rm=TRUE)else NA_real_,varianceProxy=proxy,groups=groups,records=lapply(seq_along(ii),function(j)list(id=rr$id[j],group=rr$group[j],weight=rr$w[j],lossA=la[j],lossB=lb[j],difference=d[j])))\n}\nrunSelection<-function(r,candidates,criterion,required,binary=FALSE){\n out<-lapply(candidates,function(c){v<-r;t<-r;v$role[v$role!='validation']<-'excluded';t$role[t$role!='test']<-'excluded';val<-weightedRisk(v,c$pred,binary);test<-weightedRisk(t,c$pred,binary);co<-setNames(lapply(required,function(g){z<-v;z$role[z$cohort!=g]<-'excluded';weightedRisk(z,c$pred,binary)}),required);vv<-vapply(co,`[[`,0.0,'MSE');score<-if(criterion=='mean')val$MSE else if(length(vv)&&all(is.finite(vv)))max(vv)else NA_real_;list(id=c$id,criterion=score,validation=val,test=test,cohorts=co)})\n scores<-vapply(out,`[[`,0.0,'criterion');eligible<-which(is.finite(scores));k<-if(length(eligible))eligible[which.min(scores[eligible])]else NA_integer_;list(criterion=criterion,selected=if(!is.na(k))out[[k]]$id else NULL,selectedIndex=if(!is.na(k))k-1 else NA_real_,candidates=out)\n}\nfixedOperation<-function(api,a){\n if(api=='realdata'){\n  kind<-a$kind;r<-rows[[kind]];x<-X[[kind]];asgn<-assign_roles(r$group);r$dataset<-kind;r$splitRank<-asgn$rank;r$plannedRole<-asgn$planned;r$eligible<-!is.na(r$y)&rowSums(is.na(x))==0;r$role<-ifelse(r$eligible,r$plannedRole,'excluded');r$w<-1;binary<-kind=='company';leaf_min<<-5\n  defs<-data.frame(id=c('constant','ridge:1/100','ridge:1/10','ridge:1','one-split-stump'),method=c('constant','ridge','ridge','ridge','stump'),lambda=c(0,.01,.1,1,0));fits<-lapply(seq_len(5),function(i)fit_model(r,x,defs$method[i],defs$lambda[i]));candidates<-lapply(seq_len(5),function(i)list(id=defs$id[i],pred=fits[[i]]$pred));selection<-runSelection(r,candidates,a$criterion,unique(r$cohort),binary);k<-selection$selectedIndex+1;best<-fits[[k]];base<-fits[[1]];test<-r;test$role[test$role!='test']<-'excluded';paired<-weightedPair(test,best$pred,base$pred)\n  records<-lapply(seq_len(nrow(r)),function(i)list(id=r$id[i],sourceRow=r$sourceRow[i],originalID=r$originalID[i],group=r$group[i],cohort=r$cohort[i],plannedRole=r$plannedRole[i],role=r$role[i],eligible=r$eligible[i],y=r$y[i],baselinePrediction=base$pred[i],selectedPrediction=best$pred[i],selectedRawPrediction=best$raw[i],queryInvariant=TRUE))\n  return(list(kind=kind,nativeRows=nrow(r),eligibleRows=sum(r$eligible),selection=selection,models=lapply(seq_len(5),function(i)list(id=defs$id[i],train=as.list(r$id[r$role=='train']),mass=sum(r$role=='train'),meanX=fits[[i]]$meanX,scales=fits[[i]]$scales,model=fits[[i]]$model)),paired=paired,records=records))\n }\n f<-fixedRows(a$rows);r<-f$r;x<-f$x;binary<-identical(a$task,'binary')\n if(api=='split'){seed<<-a$seed;asgn<-assign_roles(r$group);return(list(state=asgn$state,groupCount=length(unique(r$group)),records=lapply(seq_len(nrow(r)),function(i)list(id=r$id[i],group=r$group[i],rank=asgn$rank[i],role=asgn$planned[i]))))}\n if(api=='fit'){\n  r$dataset<-if(binary)'company'else'fixed';leaf_min<<-if(is.null(a$minLeafRows))1 else a$minLeafRows;fit<-fit_model(r,x,a$method,if(is.null(a$lambda))0 else num(a$lambda));bad<-rowSums(is.na(x))>0;fit$raw[bad]<-NA_real_;fit$pred[bad]<-NA_real_;fit$defined<-TRUE;fit$train<-as.list(r$id[r$role=='train'&r$eligible]);fit$mass<-sum(r$w[r$role=='train'&r$eligible]);fit$invariant<-ifelse(bad,NA,TRUE);return(fit)\n }\n if(api=='evaluate'){p<-vapply(a$rows,function(v)num(v$prediction),0.0);threshold<-if(is.null(a$threshold)).5 else num(a$threshold);m<-weightedRisk(r,p,binary,threshold);records<-lapply(seq_len(nrow(r)),function(i){valid<-r$w[i]>0&&!is.na(r$y[i])&&!is.na(p[i])&&!r$role[i]%in%c('excluded','unused');list(id=r$id[i],weight=r$w[i],y=r$y[i],prediction=p[i],eligible=valid,loss=if(valid)(p[i]-r$y[i])^2 else NA_real_,correct=list(defined=valid&&binary,value=if(valid&&binary)(p[i]>=threshold)==r$y[i] else NULL))});return(list(metrics=m,records=records))}\n if(api=='select'){cs<-lapply(a$candidates,function(c)list(id=c$id,pred=vapply(c$predictions,num,0.0)));return(runSelection(r,cs,a$criterion,unlist(a$requiredCohorts),binary))}\n if(api=='paired')return(weightedPair(r,vapply(a$rows,function(v)num(v$predictionA),0.0),vapply(a$rows,function(v)num(v$predictionB),0.0)))\n stop('unknown-api')\n}\nreportValues<-function(api,z){\n ss<-list();pp<-list();add<-function(k,v,u='dimensionless')ss[[length(ss)+1]]<<-list(metric=k,value=if(is.null(v)||length(v)==0||is.na(v))NULL else unname(v),unit=u);series<-function(name,values){for(i in seq_along(values))pp[[length(pp)+1]]<<-list(series=name,index=i-1,x=i-1,y=if(is.null(values[[i]])||is.na(values[[i]]))NULL else unname(values[[i]]))}\n if(api=='split'){add('groups',z$groupCount,'groups');add('rows',length(z$records),'rows');add('finalState',z$state,'unsigned 32-bit state');series('planned role code',lapply(z$records,function(r)switch(r$role,test=0,validation=1,train=2)))}\n if(api=='fit'){add('defined',z$defined);add('trainingRows',length(z$train),'rows');add('trainingMass',z$mass,'analysis weight mass');add('modelRank',z$model$rank,'parameters');add('threshold',z$model$threshold,'constructed feature units');add('minimumObjective',z$model$minimumObjective,'constructed squared outcome units');series('prediction',as.list(z$pred));if(!is.null(z$model$theta))for(i in seq_along(z$model$theta))add(paste0('theta',i-1),z$model$theta[i],'constructed outcome units per standardized coordinate')}\n if(api=='evaluate'){for(k in c('rows','mass','MSE','MAE','R2','Brier','accuracy','positiveRecall','negativeRecall','precision','F1','balancedAccuracy','AUROC'))if(k%in%names(z$metrics))add(k,z$metrics[[k]],if(k=='rows')'rows'else if(k=='mass')'analysis weight mass'else if(k%in%c('MSE','Brier'))FIXED$unit else if(k=='MAE')'constructed outcome units'else'dimensionless');series('squared loss',lapply(z$records,`[[`,'loss'))}\n if(api=='select'){add('selectedIndex',z$selectedIndex,'zero-based candidate index');for(i in seq_along(z$candidates)){c<-z$candidates[[i]];add(paste0('criterion',i-1),c$criterion,FIXED$unit);add(paste0('testMSE',i-1),c$test$MSE,FIXED$unit)};series('validation criterion',lapply(z$candidates,`[[`,'criterion'));series('test MSE',lapply(z$candidates,function(c)c$test$MSE))}\n if(api=='paired'){for(k in c('rows','mass','groupCount','meanDifference','minimumLeaveOut','maximumLeaveOut','varianceProxy'))add(k,z[[k]],if(k=='rows')'rows'else if(k=='groupCount')'groups'else if(k=='mass')'analysis weight mass'else if(k=='varianceProxy')paste(FIXED$unit,'squared')else FIXED$unit);series('loss A minus loss B',lapply(z$records,`[[`,'difference'))}\n if(api=='realdata'){add('nativeRows',z$nativeRows,'native records');add('eligibleRows',z$eligibleRows,'complete records');add('selectedIndex',z$selection$selectedIndex,'zero-based candidate index');for(i in seq_along(z$selection$candidates)){c<-z$selection$candidates[[i]];add(paste0('validationMSE',i-1),c$validation$MSE,FIXED$unit);add(paste0('testMSE',i-1),c$test$MSE,FIXED$unit)};for(k in c('meanDifference','minimumLeaveOut','maximumLeaveOut','varianceProxy'))add(k,z$paired[[k]],if(k=='varianceProxy')paste(FIXED$unit,'squared')else FIXED$unit);best<-z$selection$candidates[[z$selection$selectedIndex+1]]$test;for(k in c('accuracy','positiveRecall','negativeRecall','precision','balancedAccuracy','AUROC'))if(k%in%names(best))add(k,best[[k]]);series('validation MSE',lapply(z$selection$candidates,function(c)c$validation$MSE));series('test MSE',lapply(z$selection$candidates,function(c)c$test$MSE))}\n list(summary=ss,points=pp)\n}\n\nescapeXML<-function(s){s<-gsub('&','&amp;',s,fixed=TRUE);s<-gsub('<','&lt;',s,fixed=TRUE);s<-gsub('>','&gt;',s,fixed=TRUE);gsub('\"','&quot;',s,fixed=TRUE)}\nsvgPlot<-function(pp,title){\n xx<-vapply(pp,function(p)as.numeric(p$x),numeric(1));yy<-vapply(pp,function(p)as.numeric(p$y),numeric(1));xmin<-if(length(xx))min(xx)else 0;xmax<-if(length(xx))max(xx)else 1;ymin<-min(c(0,yy));ymax<-max(c(0,yy));if(xmin==xmax){xmin<-xmin-.5;xmax<-xmax+.5};if(ymin==ymax){ymin<-ymin-.5;ymax<-ymax+.5};pad<-(ymax-ymin)*.08;ymin<-ymin-pad;ymax<-ymax+pad;X<-function(x)82+(as.numeric(x)-xmin)/(xmax-xmin)*608;Y<-function(y)354-(as.numeric(y)-ymin)/(ymax-ymin)*290\n out<-paste0('<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"720\" height=\"480\" viewBox=\"0 0 720 480\" role=\"img\" aria-label=\"',escapeXML(title),'\"><rect width=\"720\" height=\"480\" fill=\"white\"/><g font-family=\"Arial,sans-serif\" font-size=\"13\" fill=\"#18232f\"><text x=\"360\" y=\"25\" text-anchor=\"middle\">',escapeXML(title),'</text>')\n for(j in 0:4){y<-ymin+(ymax-ymin)*j/4;x<-xmin+(xmax-xmin)*j/4;out<-paste0(out,'<line x1=\"82\" y1=\"',Y(y),'\" x2=\"690\" y2=\"',Y(y),'\" stroke=\"#e2e8f0\"/><text x=\"73\" y=\"',Y(y)+4,'\" text-anchor=\"end\">',sprintf('%.3g',y),'</text><text x=\"',X(x),'\" y=\"380\" text-anchor=\"middle\">',sprintf('%.3g',x),'</text>')}\n ss<-unique(vapply(pp,`[[`,character(1),'series'));cols<-c('#0f766e','#c76622','#4f46e5','#b23857')\n for(j in seq_along(ss)){rr<-Filter(function(p)p$series==ss[j],pp);xy<-vapply(rr,function(p)sprintf('%.6f,%.6f',X(p$x),Y(p$y)),character(1));col<-cols[(j-1)%%4+1];for(p in rr)out<-paste0(out,'<circle cx=\"',sprintf('%.6f',X(p$x)),'\" cy=\"',sprintf('%.6f',Y(p$y)),'\" r=\"2.6\" fill=\"',col,'\"><title>',escapeXML(ss[j]),': ',escapeXML(p$y),'</title></circle>');out<-paste0(out,'<text x=\"',82+((j-1)%%2)*310,'\" y=\"',432+floor((j-1)/2)*23,'\" fill=\"',col,'\">',escapeXML(ss[j]),'</text>')}\n paste0(out,'<text x=\"360\" y=\"405\" text-anchor=\"middle\">Declared record / candidate index; fixed example</text></g></svg>')\n}\ntoJSON<-function(x){\n if(is.null(x))return('null');if(is.list(x)){v<-vapply(x,toJSON,character(1));if(!is.null(names(x)))paste0('{',paste(paste0(vapply(names(x),toJSON,character(1)),':',v),collapse=','),'}')else paste0('[',paste(v,collapse=','),']')}\n else if(length(x)!=1){if(!is.numeric(x)&&!is.null(names(x)))toJSON(as.list(x))else paste0('[',paste(vapply(as.list(x),toJSON,character(1)),collapse=','),']')}\n else if(is.na(x))'null'else if(is.logical(x))if(x)'true'else'false'else if(is.numeric(x))if(is.finite(x))sprintf('%.17g',x)else'null'else paste0('\"',gsub('\\n','\\\\n',gsub('\"','\\\\\"',gsub('\\\\','\\\\\\\\',x,fixed=TRUE),fixed=TRUE),fixed=TRUE),'\"')\n}\n\nFIXED<-list(`api`=\"split\",`variant`=\"same-group-roles\",`title`=\"Planned roles for shared groups\",`input`=list(`rows`=list(list(`id`=\"a\",`group`=\"G\"),list(`id`=\"b\",`group`=\"G\"),list(`id`=\"c\",`group`=\"H\"),list(`id`=\"d\",`group`=\"I\")),`seed`=0),`unit`=\"Declared role code; not a probability\",`titleI18n`=list(`ko`=\"같은 묶음의 예정 역할\",`en`=\"Planned roles for shared groups\"))\n\nargs<-commandArgs(trailingOnly=TRUE);out<-if(length(args))args[1]else stop('NEW output directory required');if(dir.exists(out))stop('Preserve previous output directory');dir.create(out,recursive=TRUE)\nz<-fixedOperation(FIXED$api,FIXED$input);rr<-reportValues(FIXED$api,z)\nwriteLines(toJSON(list(arithmetic='BaseR binary64 author counterpart; native group hashing exact within declared integer range, stump approximate tie tolerance1e-12; not an independent exact oracle',result=z)),file.path(out,'full.json'),useBytes=TRUE)\nsums<-do.call(rbind,lapply(rr$summary,function(row)data.frame(metric=row$metric,value=if(is.null(row$value))''else if(is.logical(row$value))as.character(as.integer(row$value))else format(row$value,digits=17,scientific=NA,trim=TRUE),unit=row$unit,defined=as.integer(!is.null(row$value)),stringsAsFactors=FALSE)))\npoints<-do.call(rbind,lapply(rr$points,function(p)data.frame(series=p$series,index=p$index,x=p$x,y=if(is.null(p$y))NA_real_ else p$y,defined=as.integer(!is.null(p$y)),stringsAsFactors=FALSE)))\nwrite.csv(sums,file.path(out,'summary.csv'),row.names=FALSE,na='');write.csv(points,file.path(out,'plot-points.csv'),row.names=FALSE,na='');writeLines(svgPlot(Filter(function(p)!is.null(p$y),rr$points),FIXED$title),file.path(out,'plot.svg'),useBytes=TRUE);cat(FIXED$api,'/',FIXED$variant,'\\n',sep='')\n",
        "returnCode": 0,
        "stdout": "split/same-group-roles\r\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 ",
        "diagnosticScope": "Public projection omits private absolute-path/traceback frames; actual exit and warnings/reason retained. Raw complete streams and commands in private execution proof.",
        "resultFolder": "ml22-code/runs/r-split-same-group-roles",
        "kind": null,
        "inputFiles": [
          {
            "file": "ml22-code/split-same-group-roles-input.json",
            "sha256": "e170d98ce7a016e785994454b80d4bd1e71e36ec1ad3cb56cbc658d71cc3f918",
            "scope": "Complete fixed literal input; program embeds the same values"
          }
        ],
        "files": [
          {
            "file": "ml22-code/runs/r-split-same-group-roles/full.json",
            "sha256": "003f68677f0bf45315bd1a379060ffcca20c6f4097d82cda49c2e515bd10234f",
            "bytes": 435
          },
          {
            "file": "ml22-code/runs/r-split-same-group-roles/plot-points.csv",
            "sha256": "970f9cebd3bee87c19f5b3ea2dfea63a26006679ff6f8eb1b8f2eb2f5a9adf55",
            "bytes": 152
          },
          {
            "file": "ml22-code/runs/r-split-same-group-roles/plot.svg",
            "sha256": "e580336e1c1cbf0ae1a2d34431e94397e428b8a9f1f3e6ab9a6897fdcb9e8234",
            "bytes": 1742
          },
          {
            "file": "ml22-code/runs/r-split-same-group-roles/summary.csv",
            "sha256": "ef5f9fc55ff0b0273ee704eae103094e1752df0e41e37a7af26c4d82955ebe49",
            "bytes": 134
          }
        ],
        "summaryRows": [
          {
            "metric": "groups",
            "value": "3.0",
            "unit": "groups",
            "defined": "true",
            "rawValue": "3",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "rows",
            "value": "4.0",
            "unit": "rows",
            "defined": "true",
            "rawValue": "4",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "finalState",
            "value": "1196435762.0",
            "unit": "unsigned 32-bit state",
            "defined": "true",
            "rawValue": "1196435762",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          }
        ],
        "plotRows": [
          {
            "series": "planned role code",
            "index": "0",
            "x": "0",
            "y": "1",
            "defined": true,
            "xExact": null,
            "yExact": null
          },
          {
            "series": "planned role code",
            "index": "1",
            "x": "1",
            "y": "1",
            "defined": true,
            "xExact": null,
            "yExact": null
          },
          {
            "series": "planned role code",
            "index": "2",
            "x": "2",
            "y": "2",
            "defined": true,
            "xExact": null,
            "yExact": null
          },
          {
            "series": "planned role code",
            "index": "3",
            "x": "3",
            "y": "0",
            "defined": true,
            "xExact": null,
            "yExact": null
          }
        ],
        "plotFile": "ml22-code/runs/r-split-same-group-roles/plot.svg",
        "fullResultFile": "ml22-code/runs/r-split-same-group-roles/full.json",
        "arithmeticScope": "Python exact rational versus base-R approximate floating algebra; copied author kernels, not independent oracle.",
        "plotScope": "Original scatter vectors plot every defined declared comparison point, with missing points omitted. Source profiles show candidate risks; all source records remain in the full result and source CSV files.",
        "reproductionScope": "Standalone literal program plus four native CSV files for factual source profiles. No answer/engine/checker imports."
      }
    }
  },
  "fit": {
    "python": {
      "constant-common-frame": {
        "api": "fit",
        "variant": "constant-common-frame",
        "language": "python",
        "title": "A constant on the same complete training frame",
        "titleI18n": {
          "ko": "상수도 같은 완전 훈련 집합",
          "en": "A constant on the same complete training frame"
        },
        "input": {
          "method": "constant",
          "rows": [
            {
              "id": "a",
              "x": [
                "0"
              ],
              "y": "1"
            },
            {
              "id": "b",
              "x": [
                "2"
              ],
              "y": "5"
            },
            {
              "id": "incomplete",
              "x": [
                null
              ],
              "y": "99"
            },
            {
              "id": "query",
              "x": [
                "1"
              ],
              "y": null,
              "role": "test"
            }
          ]
        },
        "expectedFailure": false,
        "codeFile": "ml22-code/fit-constant-common-frame.py",
        "codeSHA256": "e4d5487366e2ca1dd32bc58715c0d3af4f1b7ef5b18ce959023856aa38d6c9b1",
        "code": "# ML22 standalone fixed literal. Attribution and arithmetic scope in README.\nimport csv,hashlib,html,json,math,sys,time\nfrom pathlib import Path\nfrom fractions import Fraction as F\nfrom collections import Counter\nsys.set_int_max_str_digits(200000)\nnumber=lambda v:F(str(v))\ndef Q(x):return None if x is None or x in ('','.') else F(str(x))\n\ndef canonical(v):return None if Q(v) is None else str(Q(v))\n\ndef fingerprint(tag,values):return tag+':'+hashlib.sha256(json.dumps([canonical(x)for x in values],separators=(',',':')).encode()).hexdigest()\n\ndef split(rows,seed=20261104,pattern=('test','validation','train','train')):\n order=sorted(set(r['group'] for r in rows));state=seed\n for j in range(len(order)-1,0,-1):state=(1664525*state+1013904223)&0xffffffff;k=state%(j+1);order[k],order[j]=order[j],order[k]\n roles={g:(i,pattern[i%len(pattern)]) for i,g in enumerate(order)}\n return roles,state,order\n\ndef solve(A,b):\n n=len(b);M=[list(row)+[rhs]for row,rhs in zip(A,b)];piv=[];rank=0\n for j in range(n):\n  candidates=[i for i in range(rank,n)if M[i][j]]\n  if not candidates:continue\n  k=max(candidates,key=lambda i:abs(M[i][j]));M[rank],M[k]=M[k],M[rank];v=M[rank][j];M[rank]=[x/v for x in M[rank]]\n  for i in range(n):\n   if i!=rank:\n    v=M[i][j];M[i]=[a-v*b for a,b in zip(M[i],M[rank])]\n  piv.append(j);rank+=1\n x=[F(0)]*n\n for i,j in enumerate(piv):x[j]=M[i][-1]\n null=[]\n for j in range(n):\n  if j not in piv:\n   v=[F(0)]*n;v[j]=F(1)\n   for i,k in enumerate(piv):v[k]=-M[i][j]\n   null.append(v)\n return x,rank,null\n\ndef dot(a,b):return sum((x*y for x,y in zip(a,b)),F(0))\n\ndef fit(rows,method,lam=F(0),minleaf=1,binary=False):\n use=[r for r in rows if r['role']=='train'and r['w']>0 and r['y']is not None and None not in r['x']];p=len(rows[0]['x'])if rows else 0\n if not use:return dict(defined=False,pred=[None]*len(rows),raw=[None]*len(rows),train=[],invariant=[None]*len(rows))\n mass=sum(r['w']for r in use);mu=[sum(r['w']*r['x'][j]for r in use)/mass for j in range(p)];scale=[max(r['x'][j]for r in use)-min(r['x'][j]for r in use)or F(1)for j in range(p)];mean=sum(r['w']*r['y']for r in use)/mass;model={};z=lambda r:[F(1)]+[(x-m)/s for x,m,s in zip(r['x'],mu,scale)]\n if method=='constant':model=dict(mean=mean,parameterCount=1,rank=1,unique=True)\n elif method=='ridge':\n  vectors=[z(r)for r in use];n=p+1;A=[[sum(r['w']*xx[j]*xx[k]for r,xx in zip(use,vectors))/mass+(lam if j==k and j>0 else F(0))for k in range(n)]for j in range(n)];b=[sum(r['w']*r['y']*xx[j]for r,xx in zip(use,vectors))/mass for j in range(n)];theta,rank,null=solve(A,b);objective=sum(r['w']*(dot(xx,theta)-r['y'])**2 for r,xx in zip(use,vectors))/(2*mass)+lam*sum(x*x for x in theta[1:])/2;model=dict(lambdaValue=lam,theta=theta,rank=rank,unique=rank==n,nullspace=null,minimumObjective=objective,parameterCount=n)\n else:\n  best=None;total=sum(r['w']*r['y']for r in use);total2=sum(r['w']*r['y']**2 for r in use);base=total2-total**2/mass\n  for j in range(p):\n   ordered=sorted(enumerate(use),key=lambda v:(v[1]['x'][j],v[0]));leftW=F(0);leftS=F(0)\n   for i,(_idx,r)in enumerate(ordered[:-1]):\n    leftW+=r['w'];leftS+=r['w']*r['y'];rightW=mass-leftW\n    if i+1<minleaf or len(use)-i-1<minleaf or r['x'][j]==ordered[i+1][1]['x'][j]:continue\n    SSE=total2-leftS**2/leftW-(total-leftS)**2/rightW\n    if best is None or SSE<best['weightedSSE']:best=dict(feature=j,threshold=(r['x'][j]+ordered[i+1][1]['x'][j])/2,leftMean=leftS/leftW,rightMean=(total-leftS)/rightW,leftRows=i+1,rightRows=len(use)-i-1,leftWeight=leftW,rightWeight=rightW,weightedSSE=SSE)\n  model=dict(split=False,mean=mean,weightedSSE=base,trainingMSE=base/mass)if best is None or best['weightedSSE']>=base else dict(split=True,**best,trainingMSE=best['weightedSSE']/mass,improvement=(base-best['weightedSSE'])/mass)\n raw=[];invariant=[]\n for r in rows:\n  if None in r['x']:raw.append(None);invariant.append(None);continue\n  if method=='constant':v=mean;iv=True\n  elif method=='ridge':zz=z(r);v=dot(zz,model['theta']);iv=all(dot(zz,nn)==0 for nn in model['nullspace'])\n  else:v=(model['leftMean']if r['x'][model['feature']]<=model['threshold']else model['rightMean'])if model['split']else mean;iv=True\n  raw.append(v);invariant.append(iv)\n pred=[None if x is None else min(F(1),max(F(0),x))if binary else x for x in raw]\n return dict(defined=True,train=[r['id']for r in use],mass=mass,meanX=mu,scales=scale,model=model,pred=pred,raw=raw,invariant=invariant)\n\ndef risk(rows,pred,binary=False,threshold=F(1,2)):\n use=[(r,p)for r,p in zip(rows,pred)if r['w']>0 and r['y']is not None and p is not None and r['role']not in['excluded','unused']];mass=sum((r['w']for r,p in use),F(0));d=dict(rows=len(use),mass=mass)\n if not mass:\n  d.update({k:None for k in ['MSE','MAE','R2']+(['Brier','accuracy','balancedAccuracy','AUROC']if binary else[])});return d\n mean=sum(r['w']*r['y']for r,p in use)/mass;sse=sum(r['w']*(p-r['y'])**2 for r,p in use);sst=sum(r['w']*(r['y']-mean)**2 for r,p in use);d.update(meanY=mean,SSE=sse,SST=sst,MSE=sse/mass,MAE=sum(r['w']*abs(p-r['y'])for r,p in use)/mass,R2=1-sse/sst if sst else None)\n if binary:\n  weights=Counter();num=Counter()\n  for r,p in use:k=('T'if int(p>=threshold)==int(r['y'])else'F')+('P'if p>=threshold else'N');weights[k]+=r['w'];num[k]+=1\n  TP,FP,TN,FN=[weights[k]for k in ['TP','FP','TN','FN']];positive=TP+FN;negative=TN+FP;rate=lambda a,b:a/b if b else None;TPR=rate(TP,positive);TNR=rate(TN,negative)\n  # Pair enumeration is independent of the subject's score-tie-block formula.\n  negatives=[(r,p)for r,p in use if not r['y']];positives=[(r,p)for r,p in use if r['y']];wins=sum((a['w']*b['w']*(F(1)if pa>pb else F(1,2)if pa==pb else F(0))for a,pa in positives for b,pb in negatives),F(0))\n  d.update(Brier=d['MSE'],threshold=threshold,confusionMass={k:weights[k]for k in ['TP','FP','TN','FN']},confusionRows={k:num[k]for k in ['TP','FP','TN','FN']},positiveMass=positive,negativeMass=negative,accuracy=(TP+TN)/mass,positiveRecall=TPR,negativeRecall=TNR,precision=rate(TP,TP+FP),F1=rate(2*TP,2*TP+FP+FN),balancedAccuracy=(TPR+TNR)/2 if TPR is not None and TNR is not None else None,AUROC=rate(wins,positive*negative))\n return d\n\nNATIVE_SHA256={'actual1599-red-wine-original12-fields.csv': '77e9ac73115930d6c43983333a5a57940deefc493affeb17aca478c09c5f6e00', 'actual4898-white-wine-original12-fields.csv': '50d810bbb42b9cc3e87fa4c27a4c0f168e72da09dd812863425ca3873fec28ef', 'actual3613-NLS-original52-fields.csv': '6e1e1895558795435b65f8634252a7589865273a0e69adbd715fcfa04a3c11a1', 'actual3150-churn-original14-fields.csv': '1c0753e434226e769d1015c922121a7d8967df66014e057c4f7543e490f11764'}\n\ndef read_sources(directory,seed):\n def read(name):\n  p=directory/name\n  if hashlib.sha256(p.read_bytes()).hexdigest()!=NATIVE_SHA256[name]:raise ValueError('Native file hash differs: '+name)\n  with p.open(encoding='utf8',newline='')as f:return list(csv.DictReader(f))\n sources={};wine=[]\n for typ,n in [('red',1599),('white',4898)]:\n  table=read(f'actual{n}-{typ}-wine-original12-fields.csv');assert len(table)==n;features=[k for k in table[0]if k not in ['sourceRow','wineType','quality']];assert len(features)==11\n  for r in table:\n   i=int(r['sourceRow']);red='1'if typ=='red'else'0';nativeX=[r[k]for k in features];wine.append(dict(id=f'wine-{typ}-row:{i}',sourceRow=f'{typ}:{i}',originalID=None,group=fingerprint('wine-predictors',[red]+nativeX),cohort=typ,x=list(map(Q,nativeX+[red])),y=Q(r['quality'])))\n sources['country']=wine\n table=read('actual3613-NLS-original52-fields.csv');assert len(table)==3613;sources['person']=[dict(id='nls-row:'+r['sourceRow'],sourceRow=int(r['sourceRow']),originalID=r['id'],group='nls-id:'+r['id'],cohort='schooling-over12'if Q(r['ed76'])>12 else'schooling-at-most12',x=[Q(r['ed76']),Q(r['age76'])],y=Q(r['lwage76']))for r in table]\n table=read('actual3150-churn-original14-fields.csv');assert len(table)==3150;predictors=[k for k in table[0]if k not in ['sourceRow','Churn']];assert len(predictors)==13;sources['company']=[dict(id='customer-row:'+r['sourceRow'],sourceRow=int(r['sourceRow']),originalID=None,group=fingerprint('customer-predictors',[r[k]for k in predictors]),cohort='pay-as-you-go'if r['Tariff Plan']=='1'else'contractual'if r['Tariff Plan']=='2'else'other-native-tariff',x=[Q(r[k])for k in ['Call  Failure','Subscription  Length','Seconds of Use','Age']],y=Q(r['Churn']))for r in table]\n for kind,rows in sources.items():\n  assignments,state,order=split(rows,seed)\n  for r in rows:\n   rank,planned=assignments[r['group']];r.update(w=F(1),splitRank=rank,plannedRole=planned,eligible=r['y']is not None and None not in r['x']);r['role']=planned if r['eligible']else'excluded'\n return sources\n# New ML22 fixed-profile kernels. The public Fraction fitting/source readers are\n# copied by value above this file by the standalone builder; never imported.\ndef fixed_rows(data, prediction_key=None):\n out=[]\n for i,a in enumerate(data):\n  w=Q(a.get('weight','1'))\n  if w is None or w<0:raise ValueError('negative-weight' if w is not None and w<0 else 'missing-weight')\n  out.append(dict(id=a.get('id',str(i)),group=a.get('group',a.get('id',str(i))),cohort=a.get('cohort','all'),role=a.get('role','train'),w=w,x=[Q(v)for v in a.get('x',[])],y=Q(a.get('y'))))\n return out\n\ndef weighted_pair(rows,A,B):\n use=[(r,a,b)for r,a,b in zip(rows,A,B)if r['w']>0 and r['y']is not None and a is not None and b is not None and r['role']not in ['excluded','unused']]\n mass=sum((r['w']for r,a,b in use),F(0));records=[];groups={}\n for r,a,b in use:\n  la=(a-r['y'])**2;lb=(b-r['y'])**2;d=la-lb\n  records.append(dict(id=r['id'],group=r['group'],weight=r['w'],lossA=la,lossB=lb,difference=d))\n  g=groups.setdefault(r['group'],dict(group=r['group'],rows=0,mass=F(0),sum=F(0)));g['rows']+=1;g['mass']+=r['w'];g['sum']+=r['w']*d\n total=sum((g['sum']for g in groups.values()),F(0));mean=total/mass if mass else None;G=len(groups)\n for g in groups.values():g['leaveOut']=(total-g['sum'])/(mass-g['mass'])if mass>g['mass']else None\n leaves=[g['leaveOut']for g in groups.values()if g['leaveOut']is not None]\n proxy=F(G-1,G)*sum((v-sum(leaves,F(0))/G)**2 for v in leaves) if G>1 and len(leaves)==G else None\n return dict(rows=len(use),mass=mass,groupCount=G,meanDifference=mean,minimumLeaveOut=min(leaves)if leaves else None,maximumLeaveOut=max(leaves)if leaves else None,varianceProxy=proxy,groups=list(groups.values()),records=records)\n\ndef run_selection(rows,candidates,criterion,required,binary=False):\n results=[]\n for c,pred in candidates:\n  val=[dict(r,role='excluded')if r['role']!='validation'else r for r in rows]\n  test=[dict(r,role='excluded')if r['role']!='test'else r for r in rows]\n  v=risk(val,pred,binary);t=risk(test,pred,binary);cohort={g:risk([dict(r,role='excluded')if r['role']!='validation'or r['cohort']!=g else r for r in rows],pred,binary)for g in required}\n  values=[cohort[g]['MSE']for g in required]\n  score=v['MSE']if criterion=='mean'else max(values)if values and None not in values else None\n  results.append(dict(id=c,criterion=score,validation=v,test=t,cohorts=cohort))\n eligible=[(i,r['criterion'])for i,r in enumerate(results)if r['criterion']is not None]\n chosen=min(eligible,key=lambda t:(t[1],t[0]))[0]if eligible else None\n return dict(criterion=criterion,selected=results[chosen]['id']if chosen is not None else None,selectedIndex=chosen,candidates=results)\n\ndef fixed_operation(api,a):\n if api=='realdata':\n  kind=a['kind'];rows=read_sources(Path(__file__).parent/'data',a.get('seed',20261104))[kind];binary=kind=='company'\n  defs=[('constant','constant',F(0)),('ridge:1/100','ridge',F(1,100)),('ridge:1/10','ridge',F(1,10)),('ridge:1','ridge',F(1)),('one-split-stump','stump',F(0))]\n  fits=[fit(rows,method,lam,5,binary)for _,method,lam in defs]\n  selection=run_selection(rows,[(d[0],f['pred'])for d,f in zip(defs,fits)],a.get('criterion','mean'),list(dict.fromkeys(r['cohort']for r in rows)),binary)\n  chosen=selection['selectedIndex'];best=fits[chosen];base=fits[0]\n  test=[dict(r,role='excluded')if r['role']!='test'else r for r in rows]\n  paired=weighted_pair(test,best['pred'],base['pred'])\n  records=[dict(id=r['id'],sourceRow=r.get('sourceRow'),originalID=r.get('originalID'),group=r['group'],cohort=r['cohort'],plannedRole=r['plannedRole'],role=r['role'],eligible=r['eligible'],y=r['y'],baselinePrediction=base['pred'][i],selectedPrediction=best['pred'][i],selectedRawPrediction=best['raw'][i],queryInvariant=best['invariant'][i])for i,r in enumerate(rows)]\n  return dict(kind=kind,nativeRows=len(rows),eligibleRows=sum(r['eligible']for r in rows),selection=selection,models=[dict(id=d[0],train=f['train'],mass=f.get('mass'),meanX=f.get('meanX'),scales=f.get('scales'),model=f.get('model'))for d,f in zip(defs,fits)],paired=paired,records=records)\n rows=fixed_rows(a.get('rows',[]));binary=a.get('task')=='binary'\n if api=='split':\n  assignment,state,order=split(rows,a.get('seed',0));records=[dict(id=r['id'],group=r['group'],rank=assignment[r['group']][0],role=assignment[r['group']][1])for r in rows]\n  return dict(state=state,groupOrder=order,records=records,groupCount=len(order))\n if api=='fit':return fit(rows,a.get('method','constant'),Q(a.get('lambda','0')),a.get('minLeafRows',1),binary)\n if api=='evaluate':\n  pred=[Q(r.get('prediction'))for r in a['rows']];threshold=Q(a.get('threshold','1/2'));rr=risk(rows,pred,binary,threshold)\n  records=[]\n  for r,p in zip(rows,pred):\n   valid=r['w']>0 and r['y']is not None and p is not None and r['role']not in ['excluded','unused']\n   records.append(dict(id=r['id'],weight=r['w'],y=r['y'],prediction=p,eligible=valid,loss=(p-r['y'])**2 if valid else None,correct=dict(defined=valid and binary,value=bool(int(p>=threshold)==int(r['y']))if valid and binary else None)))\n  return dict(metrics=rr,records=records)\n if api=='select':return run_selection(rows,[(c['id'],list(map(Q,c['predictions'])))for c in a['candidates']],a.get('criterion','mean'),a.get('requiredCohorts',list(dict.fromkeys(r['cohort']for r in rows))),binary)\n if api=='paired':return weighted_pair(rows,[Q(r.get('predictionA'))for r in a['rows']],[Q(r.get('predictionB'))for r in a['rows']])\n raise ValueError('unknown-api')\n\ndef report_values(api,z):\n summary=[];series=[]\n def add(k,v,u='dimensionless'):summary.append((k,v,u))\n if api=='split':\n  add('groups',z['groupCount'],'groups');add('rows',len(z['records']),'rows');add('finalState',z['state'],'unsigned 32-bit state')\n  series=[('planned role code',[(i,F({'test':0,'validation':1,'train':2}[r['role']]))for i,r in enumerate(z['records'])])]\n elif api=='fit':\n  add('defined',z['defined']);add('trainingRows',len(z['train']),'rows');add('trainingMass',z.get('mass'),'analysis weight mass')\n  model=z.get('model',{});add('modelRank',model.get('rank'),'parameters');add('threshold',model.get('threshold'),'constructed feature units');add('minimumObjective',model.get('minimumObjective'),'constructed squared outcome units')\n  series=[('prediction',list(enumerate(z['pred'])))];\n  if model.get('theta')is not None:\n   for i,v in enumerate(model['theta']):add('theta'+str(i),v,'constructed outcome units per standardized coordinate')\n elif api=='evaluate':\n  for k in ['rows','mass','MSE','MAE','R2','Brier','accuracy','positiveRecall','negativeRecall','precision','F1','balancedAccuracy','AUROC']: \n   if k in z['metrics']:add(k,z['metrics'][k],'rows'if k=='rows'else'analysis weight mass'if k=='mass'else FIXED['unit']if k in ['MSE','Brier']else'constructed outcome units'if k=='MAE'else'dimensionless')\n  series=[('squared loss',[(i,r['loss'])for i,r in enumerate(z['records'])])]\n elif api=='select':\n  add('selectedIndex',z['selectedIndex'],'zero-based candidate index')\n  for i,c in enumerate(z['candidates']):add('criterion'+str(i),c['criterion'],FIXED['unit']);add('testMSE'+str(i),c['test']['MSE'],FIXED['unit'])\n  series=[('validation criterion',[(i,c['criterion'])for i,c in enumerate(z['candidates'])]),('test MSE',[(i,c['test']['MSE'])for i,c in enumerate(z['candidates'])])]\n elif api=='paired':\n  for k in ['rows','mass','groupCount','meanDifference','minimumLeaveOut','maximumLeaveOut','varianceProxy']:add(k,z[k],'rows'if k=='rows'else'groups'if k=='groupCount'else'analysis weight mass'if k=='mass'else FIXED['unit']+' squared'if k=='varianceProxy'else FIXED['unit'])\n  series=[('loss A minus loss B',[(i,r['difference'])for i,r in enumerate(z['records'])])]\n elif api=='realdata':\n  add('nativeRows',z['nativeRows'],'native records');add('eligibleRows',z['eligibleRows'],'complete records');add('selectedIndex',z['selection']['selectedIndex'],'zero-based candidate index')\n  for i,c in enumerate(z['selection']['candidates']):add('validationMSE'+str(i),c['validation']['MSE'],FIXED['unit']);add('testMSE'+str(i),c['test']['MSE'],FIXED['unit'])\n  for k in ['meanDifference','minimumLeaveOut','maximumLeaveOut','varianceProxy']:add(k,z['paired'][k],FIXED['unit']+' squared'if k=='varianceProxy'else FIXED['unit'])\n  best=z['selection']['candidates'][z['selection']['selectedIndex']]['test']\n  for k in ['accuracy','positiveRecall','negativeRecall','precision','balancedAccuracy','AUROC']:\n   if k in best:add(k,best[k])\n  series=[('validation MSE',[(i,c['validation']['MSE'])for i,c in enumerate(z['selection']['candidates'])]),('test MSE',[(i,c['test']['MSE'])for i,c in enumerate(z['selection']['candidates'])])]\n return summary,series\n\n\ndef fixed_svg(points,title):\n good=[p for p in points if p['y'] is not None];xx=[float(p['x'])for p in good];yy=[float(p['y'])for p in good];xmin=min(xx)if xx else 0;xmax=max(xx)if xx else 1;ymin=min([0]+yy);ymax=max([0]+yy)\n if xmin==xmax:xmin-=.5;xmax+=.5\n if ymin==ymax:ymin-=.5;ymax+=.5\n pad=(ymax-ymin)*.08;ymin-=pad;ymax+=pad;X=lambda x:82+(float(x)-xmin)/(xmax-xmin)*608;Y=lambda y:354-(float(y)-ymin)/(ymax-ymin)*290;e=html.escape\n out=['<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"720\" height=\"480\" viewBox=\"0 0 720 480\" role=\"img\" aria-label=\"'+e(title)+'\"><rect width=\"720\" height=\"480\" fill=\"white\"/><g font-family=\"Arial,sans-serif\" font-size=\"13\" fill=\"#18232f\"><text x=\"360\" y=\"25\" text-anchor=\"middle\">'+e(title)+'</text>']\n for j in range(5):\n  y=ymin+(ymax-ymin)*j/4;x=xmin+(xmax-xmin)*j/4;out.append('<line x1=\"82\" y1=\"'+str(Y(y))+'\" x2=\"690\" y2=\"'+str(Y(y))+'\" stroke=\"#e2e8f0\"/><text x=\"73\" y=\"'+str(Y(y)+4)+'\" text-anchor=\"end\">'+format(y,'.3g')+'</text><text x=\"'+str(X(x))+'\" y=\"380\" text-anchor=\"middle\">'+format(x,'.3g')+'</text>')\n series=list(dict.fromkeys(p['series']for p in good))\n for j,s in enumerate(series):\n  pp=[p for p in good if p['series']==s];color=['#0f766e','#c76622','#4f46e5','#b23857'][j%4]\n  for p in pp:out.append('<circle cx=\"'+format(X(p['x']),'.6f')+'\" cy=\"'+format(Y(p['y']),'.6f')+'\" r=\"2.6\" fill=\"'+color+'\"><title>'+e(s+': '+str(p['y']))+'</title></circle>')\n  out.append('<text x=\"'+str(82+(j%2)*310)+'\" y=\"'+str(432+(j//2)*23)+'\" fill=\"'+color+'\">'+e(s)+'</text>')\n out.append('<text x=\"360\" y=\"405\" text-anchor=\"middle\">Declared record / candidate index; units in summary</text></g></svg>');return''.join(out)\n\nFIXED={'api': 'fit', 'variant': 'constant-common-frame', 'title': 'A constant on the same complete training frame', 'input': {'method': 'constant', 'rows': [{'id': 'a', 'x': ['0'], 'y': '1'}, {'id': 'b', 'x': ['2'], 'y': '5'}, {'id': 'incomplete', 'x': [None], 'y': '99'}, {'id': 'query', 'x': ['1'], 'y': None, 'role': 'test'}]}, 'unit': 'Constructed outcome units', 'titleI18n': {'ko': '상수도 같은 완전 훈련 집합', 'en': 'A constant on the same complete training frame'}}\n\nOUT=Path(sys.argv[1]);OUT.mkdir(parents=True,exist_ok=False)\nresult=fixed_operation(FIXED['api'],FIXED['input']);summary,series=report_values(FIXED['api'],result)\ndef encode(v):\n if isinstance(v,F):return str(v)\n if isinstance(v,dict):return{k:encode(x)for k,x in v.items()}\n if isinstance(v,(list,tuple)):return[encode(x)for x in v]\n return v\n(OUT/'full.json').write_text(json.dumps(dict(arithmetic='Exact rational author implementation; factual rows, declared group split and finite five-candidate comparison',result=encode(result)),ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\nsummaryRows=[dict(metric=m,value=''if v is None else str(int(v))if isinstance(v,bool)else str(v),unit=u,defined=int(v is not None))for m,v,u in summary]\npoints=[dict(series=name,index=i,x=str(x),y=''if y is None else str(y),defined=int(y is not None))for name,pp in series for i,(x,y)in enumerate(pp)]\nfor name,rows in [('summary',summaryRows),('plot-points',points)]:\n with(OUT/(name+'.csv')).open('w',encoding='utf8',newline='')as f:writer=csv.DictWriter(f,fieldnames=list(rows[0]));writer.writeheader();writer.writerows(rows)\n(OUT/'plot.svg').write_text(fixed_svg([dict(p,x=number(p['x']),y=None if not p['defined']else number(p['y']))for p in points],FIXED['title']),encoding='utf8');print(FIXED['api']+'/'+FIXED['variant'])\n",
        "returnCode": 0,
        "stdout": "fit/constant-common-frame\r\n",
        "stderr": "",
        "diagnosticScope": "Public projection omits private absolute-path/traceback frames; actual exit and warnings/reason retained. Raw complete streams and commands in private execution proof.",
        "resultFolder": "ml22-code/runs/python-fit-constant-common-frame",
        "kind": null,
        "inputFiles": [
          {
            "file": "ml22-code/fit-constant-common-frame-input.json",
            "sha256": "6a036bcf3b604245298032b58ccb69ef76494e2c6fb404b2bb1b6469389de803",
            "scope": "Complete fixed literal input; program embeds the same values"
          }
        ],
        "files": [
          {
            "file": "ml22-code/runs/python-fit-constant-common-frame/full.json",
            "sha256": "08a34ccd00fbbf8b8e875398776e2aef8d95df6d7097bbe3b8116b63ea6a2afa",
            "bytes": 645
          },
          {
            "file": "ml22-code/runs/python-fit-constant-common-frame/plot-points.csv",
            "sha256": "31f1298d4a7e1b2f3d005c77b0d66950fbf689d5f0b25f1892b853bbe9e7ea73",
            "bytes": 105
          },
          {
            "file": "ml22-code/runs/python-fit-constant-common-frame/plot.svg",
            "sha256": "7f16e7d3e9bbe9037826da0b6ef58040e4f4981d4a52ca1c36d5149bc1b31ecf",
            "bytes": 1666
          },
          {
            "file": "ml22-code/runs/python-fit-constant-common-frame/summary.csv",
            "sha256": "d07551c08b092c28b2350e676be1554f75c855086e23205976d14afd2bb5ba8e",
            "bytes": 237
          }
        ],
        "summaryRows": [
          {
            "metric": "defined",
            "value": "1.0",
            "unit": "dimensionless",
            "defined": "true",
            "rawValue": "1",
            "arithmetic": "Exact Fraction",
            "exactFraction": "1",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "trainingRows",
            "value": "2.0",
            "unit": "rows",
            "defined": "true",
            "rawValue": "2",
            "arithmetic": "Exact Fraction",
            "exactFraction": "2",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "trainingMass",
            "value": "2.0",
            "unit": "analysis weight mass",
            "defined": "true",
            "rawValue": "2",
            "arithmetic": "Exact Fraction",
            "exactFraction": "2",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "modelRank",
            "value": "1.0",
            "unit": "parameters",
            "defined": "true",
            "rawValue": "1",
            "arithmetic": "Exact Fraction",
            "exactFraction": "1",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "threshold",
            "value": "",
            "unit": "constructed feature units",
            "defined": "false",
            "rawValue": "",
            "arithmetic": "Exact Fraction",
            "exactFraction": null
          },
          {
            "metric": "minimumObjective",
            "value": "",
            "unit": "constructed squared outcome units",
            "defined": "false",
            "rawValue": "",
            "arithmetic": "Exact Fraction",
            "exactFraction": null
          }
        ],
        "plotRows": [
          {
            "series": "prediction",
            "index": "0",
            "x": "0",
            "y": "3",
            "defined": true,
            "xExact": "0",
            "yExact": "3"
          },
          {
            "series": "prediction",
            "index": "1",
            "x": "1",
            "y": "3",
            "defined": true,
            "xExact": "1",
            "yExact": "3"
          },
          {
            "series": "prediction",
            "index": "2",
            "x": "2",
            "y": "",
            "defined": false,
            "xExact": "2",
            "yExact": null
          },
          {
            "series": "prediction",
            "index": "3",
            "x": "3",
            "y": "3",
            "defined": true,
            "xExact": "3",
            "yExact": "3"
          }
        ],
        "plotFile": "ml22-code/runs/python-fit-constant-common-frame/plot.svg",
        "fullResultFile": "ml22-code/runs/python-fit-constant-common-frame/full.json",
        "arithmeticScope": "Python exact rational versus base-R approximate floating algebra; copied author kernels, not independent oracle.",
        "plotScope": "Original scatter vectors plot every defined declared comparison point, with missing points omitted. Source profiles show candidate risks; all source records remain in the full result and source CSV files.",
        "reproductionScope": "Standalone literal program plus four native CSV files for factual source profiles. No answer/engine/checker imports."
      },
      "ridge-penalty-one": {
        "api": "fit",
        "variant": "ridge-penalty-one",
        "language": "python",
        "title": "Ridge penalty one under mean loss",
        "titleI18n": {
          "ko": "평균 손실의 릿지 벌점 1",
          "en": "Ridge penalty one under mean loss"
        },
        "input": {
          "method": "ridge",
          "lambda": "1",
          "rows": [
            {
              "id": "a",
              "x": [
                "0"
              ],
              "y": "1"
            },
            {
              "id": "b",
              "x": [
                "2"
              ],
              "y": "5"
            },
            {
              "id": "query",
              "x": [
                "1"
              ],
              "y": null,
              "role": "test"
            }
          ]
        },
        "expectedFailure": false,
        "codeFile": "ml22-code/fit-ridge-penalty-one.py",
        "codeSHA256": "4bcef7a08ab52592e677754cb707155f65a8187479c7c6dd412359f92f0afcc2",
        "code": "# ML22 standalone fixed literal. Attribution and arithmetic scope in README.\nimport csv,hashlib,html,json,math,sys,time\nfrom pathlib import Path\nfrom fractions import Fraction as F\nfrom collections import Counter\nsys.set_int_max_str_digits(200000)\nnumber=lambda v:F(str(v))\ndef Q(x):return None if x is None or x in ('','.') else F(str(x))\n\ndef canonical(v):return None if Q(v) is None else str(Q(v))\n\ndef fingerprint(tag,values):return tag+':'+hashlib.sha256(json.dumps([canonical(x)for x in values],separators=(',',':')).encode()).hexdigest()\n\ndef split(rows,seed=20261104,pattern=('test','validation','train','train')):\n order=sorted(set(r['group'] for r in rows));state=seed\n for j in range(len(order)-1,0,-1):state=(1664525*state+1013904223)&0xffffffff;k=state%(j+1);order[k],order[j]=order[j],order[k]\n roles={g:(i,pattern[i%len(pattern)]) for i,g in enumerate(order)}\n return roles,state,order\n\ndef solve(A,b):\n n=len(b);M=[list(row)+[rhs]for row,rhs in zip(A,b)];piv=[];rank=0\n for j in range(n):\n  candidates=[i for i in range(rank,n)if M[i][j]]\n  if not candidates:continue\n  k=max(candidates,key=lambda i:abs(M[i][j]));M[rank],M[k]=M[k],M[rank];v=M[rank][j];M[rank]=[x/v for x in M[rank]]\n  for i in range(n):\n   if i!=rank:\n    v=M[i][j];M[i]=[a-v*b for a,b in zip(M[i],M[rank])]\n  piv.append(j);rank+=1\n x=[F(0)]*n\n for i,j in enumerate(piv):x[j]=M[i][-1]\n null=[]\n for j in range(n):\n  if j not in piv:\n   v=[F(0)]*n;v[j]=F(1)\n   for i,k in enumerate(piv):v[k]=-M[i][j]\n   null.append(v)\n return x,rank,null\n\ndef dot(a,b):return sum((x*y for x,y in zip(a,b)),F(0))\n\ndef fit(rows,method,lam=F(0),minleaf=1,binary=False):\n use=[r for r in rows if r['role']=='train'and r['w']>0 and r['y']is not None and None not in r['x']];p=len(rows[0]['x'])if rows else 0\n if not use:return dict(defined=False,pred=[None]*len(rows),raw=[None]*len(rows),train=[],invariant=[None]*len(rows))\n mass=sum(r['w']for r in use);mu=[sum(r['w']*r['x'][j]for r in use)/mass for j in range(p)];scale=[max(r['x'][j]for r in use)-min(r['x'][j]for r in use)or F(1)for j in range(p)];mean=sum(r['w']*r['y']for r in use)/mass;model={};z=lambda r:[F(1)]+[(x-m)/s for x,m,s in zip(r['x'],mu,scale)]\n if method=='constant':model=dict(mean=mean,parameterCount=1,rank=1,unique=True)\n elif method=='ridge':\n  vectors=[z(r)for r in use];n=p+1;A=[[sum(r['w']*xx[j]*xx[k]for r,xx in zip(use,vectors))/mass+(lam if j==k and j>0 else F(0))for k in range(n)]for j in range(n)];b=[sum(r['w']*r['y']*xx[j]for r,xx in zip(use,vectors))/mass for j in range(n)];theta,rank,null=solve(A,b);objective=sum(r['w']*(dot(xx,theta)-r['y'])**2 for r,xx in zip(use,vectors))/(2*mass)+lam*sum(x*x for x in theta[1:])/2;model=dict(lambdaValue=lam,theta=theta,rank=rank,unique=rank==n,nullspace=null,minimumObjective=objective,parameterCount=n)\n else:\n  best=None;total=sum(r['w']*r['y']for r in use);total2=sum(r['w']*r['y']**2 for r in use);base=total2-total**2/mass\n  for j in range(p):\n   ordered=sorted(enumerate(use),key=lambda v:(v[1]['x'][j],v[0]));leftW=F(0);leftS=F(0)\n   for i,(_idx,r)in enumerate(ordered[:-1]):\n    leftW+=r['w'];leftS+=r['w']*r['y'];rightW=mass-leftW\n    if i+1<minleaf or len(use)-i-1<minleaf or r['x'][j]==ordered[i+1][1]['x'][j]:continue\n    SSE=total2-leftS**2/leftW-(total-leftS)**2/rightW\n    if best is None or SSE<best['weightedSSE']:best=dict(feature=j,threshold=(r['x'][j]+ordered[i+1][1]['x'][j])/2,leftMean=leftS/leftW,rightMean=(total-leftS)/rightW,leftRows=i+1,rightRows=len(use)-i-1,leftWeight=leftW,rightWeight=rightW,weightedSSE=SSE)\n  model=dict(split=False,mean=mean,weightedSSE=base,trainingMSE=base/mass)if best is None or best['weightedSSE']>=base else dict(split=True,**best,trainingMSE=best['weightedSSE']/mass,improvement=(base-best['weightedSSE'])/mass)\n raw=[];invariant=[]\n for r in rows:\n  if None in r['x']:raw.append(None);invariant.append(None);continue\n  if method=='constant':v=mean;iv=True\n  elif method=='ridge':zz=z(r);v=dot(zz,model['theta']);iv=all(dot(zz,nn)==0 for nn in model['nullspace'])\n  else:v=(model['leftMean']if r['x'][model['feature']]<=model['threshold']else model['rightMean'])if model['split']else mean;iv=True\n  raw.append(v);invariant.append(iv)\n pred=[None if x is None else min(F(1),max(F(0),x))if binary else x for x in raw]\n return dict(defined=True,train=[r['id']for r in use],mass=mass,meanX=mu,scales=scale,model=model,pred=pred,raw=raw,invariant=invariant)\n\ndef risk(rows,pred,binary=False,threshold=F(1,2)):\n use=[(r,p)for r,p in zip(rows,pred)if r['w']>0 and r['y']is not None and p is not None and r['role']not in['excluded','unused']];mass=sum((r['w']for r,p in use),F(0));d=dict(rows=len(use),mass=mass)\n if not mass:\n  d.update({k:None for k in ['MSE','MAE','R2']+(['Brier','accuracy','balancedAccuracy','AUROC']if binary else[])});return d\n mean=sum(r['w']*r['y']for r,p in use)/mass;sse=sum(r['w']*(p-r['y'])**2 for r,p in use);sst=sum(r['w']*(r['y']-mean)**2 for r,p in use);d.update(meanY=mean,SSE=sse,SST=sst,MSE=sse/mass,MAE=sum(r['w']*abs(p-r['y'])for r,p in use)/mass,R2=1-sse/sst if sst else None)\n if binary:\n  weights=Counter();num=Counter()\n  for r,p in use:k=('T'if int(p>=threshold)==int(r['y'])else'F')+('P'if p>=threshold else'N');weights[k]+=r['w'];num[k]+=1\n  TP,FP,TN,FN=[weights[k]for k in ['TP','FP','TN','FN']];positive=TP+FN;negative=TN+FP;rate=lambda a,b:a/b if b else None;TPR=rate(TP,positive);TNR=rate(TN,negative)\n  # Pair enumeration is independent of the subject's score-tie-block formula.\n  negatives=[(r,p)for r,p in use if not r['y']];positives=[(r,p)for r,p in use if r['y']];wins=sum((a['w']*b['w']*(F(1)if pa>pb else F(1,2)if pa==pb else F(0))for a,pa in positives for b,pb in negatives),F(0))\n  d.update(Brier=d['MSE'],threshold=threshold,confusionMass={k:weights[k]for k in ['TP','FP','TN','FN']},confusionRows={k:num[k]for k in ['TP','FP','TN','FN']},positiveMass=positive,negativeMass=negative,accuracy=(TP+TN)/mass,positiveRecall=TPR,negativeRecall=TNR,precision=rate(TP,TP+FP),F1=rate(2*TP,2*TP+FP+FN),balancedAccuracy=(TPR+TNR)/2 if TPR is not None and TNR is not None else None,AUROC=rate(wins,positive*negative))\n return d\n\nNATIVE_SHA256={'actual1599-red-wine-original12-fields.csv': '77e9ac73115930d6c43983333a5a57940deefc493affeb17aca478c09c5f6e00', 'actual4898-white-wine-original12-fields.csv': '50d810bbb42b9cc3e87fa4c27a4c0f168e72da09dd812863425ca3873fec28ef', 'actual3613-NLS-original52-fields.csv': '6e1e1895558795435b65f8634252a7589865273a0e69adbd715fcfa04a3c11a1', 'actual3150-churn-original14-fields.csv': '1c0753e434226e769d1015c922121a7d8967df66014e057c4f7543e490f11764'}\n\ndef read_sources(directory,seed):\n def read(name):\n  p=directory/name\n  if hashlib.sha256(p.read_bytes()).hexdigest()!=NATIVE_SHA256[name]:raise ValueError('Native file hash differs: '+name)\n  with p.open(encoding='utf8',newline='')as f:return list(csv.DictReader(f))\n sources={};wine=[]\n for typ,n in [('red',1599),('white',4898)]:\n  table=read(f'actual{n}-{typ}-wine-original12-fields.csv');assert len(table)==n;features=[k for k in table[0]if k not in ['sourceRow','wineType','quality']];assert len(features)==11\n  for r in table:\n   i=int(r['sourceRow']);red='1'if typ=='red'else'0';nativeX=[r[k]for k in features];wine.append(dict(id=f'wine-{typ}-row:{i}',sourceRow=f'{typ}:{i}',originalID=None,group=fingerprint('wine-predictors',[red]+nativeX),cohort=typ,x=list(map(Q,nativeX+[red])),y=Q(r['quality'])))\n sources['country']=wine\n table=read('actual3613-NLS-original52-fields.csv');assert len(table)==3613;sources['person']=[dict(id='nls-row:'+r['sourceRow'],sourceRow=int(r['sourceRow']),originalID=r['id'],group='nls-id:'+r['id'],cohort='schooling-over12'if Q(r['ed76'])>12 else'schooling-at-most12',x=[Q(r['ed76']),Q(r['age76'])],y=Q(r['lwage76']))for r in table]\n table=read('actual3150-churn-original14-fields.csv');assert len(table)==3150;predictors=[k for k in table[0]if k not in ['sourceRow','Churn']];assert len(predictors)==13;sources['company']=[dict(id='customer-row:'+r['sourceRow'],sourceRow=int(r['sourceRow']),originalID=None,group=fingerprint('customer-predictors',[r[k]for k in predictors]),cohort='pay-as-you-go'if r['Tariff Plan']=='1'else'contractual'if r['Tariff Plan']=='2'else'other-native-tariff',x=[Q(r[k])for k in ['Call  Failure','Subscription  Length','Seconds of Use','Age']],y=Q(r['Churn']))for r in table]\n for kind,rows in sources.items():\n  assignments,state,order=split(rows,seed)\n  for r in rows:\n   rank,planned=assignments[r['group']];r.update(w=F(1),splitRank=rank,plannedRole=planned,eligible=r['y']is not None and None not in r['x']);r['role']=planned if r['eligible']else'excluded'\n return sources\n# New ML22 fixed-profile kernels. The public Fraction fitting/source readers are\n# copied by value above this file by the standalone builder; never imported.\ndef fixed_rows(data, prediction_key=None):\n out=[]\n for i,a in enumerate(data):\n  w=Q(a.get('weight','1'))\n  if w is None or w<0:raise ValueError('negative-weight' if w is not None and w<0 else 'missing-weight')\n  out.append(dict(id=a.get('id',str(i)),group=a.get('group',a.get('id',str(i))),cohort=a.get('cohort','all'),role=a.get('role','train'),w=w,x=[Q(v)for v in a.get('x',[])],y=Q(a.get('y'))))\n return out\n\ndef weighted_pair(rows,A,B):\n use=[(r,a,b)for r,a,b in zip(rows,A,B)if r['w']>0 and r['y']is not None and a is not None and b is not None and r['role']not in ['excluded','unused']]\n mass=sum((r['w']for r,a,b in use),F(0));records=[];groups={}\n for r,a,b in use:\n  la=(a-r['y'])**2;lb=(b-r['y'])**2;d=la-lb\n  records.append(dict(id=r['id'],group=r['group'],weight=r['w'],lossA=la,lossB=lb,difference=d))\n  g=groups.setdefault(r['group'],dict(group=r['group'],rows=0,mass=F(0),sum=F(0)));g['rows']+=1;g['mass']+=r['w'];g['sum']+=r['w']*d\n total=sum((g['sum']for g in groups.values()),F(0));mean=total/mass if mass else None;G=len(groups)\n for g in groups.values():g['leaveOut']=(total-g['sum'])/(mass-g['mass'])if mass>g['mass']else None\n leaves=[g['leaveOut']for g in groups.values()if g['leaveOut']is not None]\n proxy=F(G-1,G)*sum((v-sum(leaves,F(0))/G)**2 for v in leaves) if G>1 and len(leaves)==G else None\n return dict(rows=len(use),mass=mass,groupCount=G,meanDifference=mean,minimumLeaveOut=min(leaves)if leaves else None,maximumLeaveOut=max(leaves)if leaves else None,varianceProxy=proxy,groups=list(groups.values()),records=records)\n\ndef run_selection(rows,candidates,criterion,required,binary=False):\n results=[]\n for c,pred in candidates:\n  val=[dict(r,role='excluded')if r['role']!='validation'else r for r in rows]\n  test=[dict(r,role='excluded')if r['role']!='test'else r for r in rows]\n  v=risk(val,pred,binary);t=risk(test,pred,binary);cohort={g:risk([dict(r,role='excluded')if r['role']!='validation'or r['cohort']!=g else r for r in rows],pred,binary)for g in required}\n  values=[cohort[g]['MSE']for g in required]\n  score=v['MSE']if criterion=='mean'else max(values)if values and None not in values else None\n  results.append(dict(id=c,criterion=score,validation=v,test=t,cohorts=cohort))\n eligible=[(i,r['criterion'])for i,r in enumerate(results)if r['criterion']is not None]\n chosen=min(eligible,key=lambda t:(t[1],t[0]))[0]if eligible else None\n return dict(criterion=criterion,selected=results[chosen]['id']if chosen is not None else None,selectedIndex=chosen,candidates=results)\n\ndef fixed_operation(api,a):\n if api=='realdata':\n  kind=a['kind'];rows=read_sources(Path(__file__).parent/'data',a.get('seed',20261104))[kind];binary=kind=='company'\n  defs=[('constant','constant',F(0)),('ridge:1/100','ridge',F(1,100)),('ridge:1/10','ridge',F(1,10)),('ridge:1','ridge',F(1)),('one-split-stump','stump',F(0))]\n  fits=[fit(rows,method,lam,5,binary)for _,method,lam in defs]\n  selection=run_selection(rows,[(d[0],f['pred'])for d,f in zip(defs,fits)],a.get('criterion','mean'),list(dict.fromkeys(r['cohort']for r in rows)),binary)\n  chosen=selection['selectedIndex'];best=fits[chosen];base=fits[0]\n  test=[dict(r,role='excluded')if r['role']!='test'else r for r in rows]\n  paired=weighted_pair(test,best['pred'],base['pred'])\n  records=[dict(id=r['id'],sourceRow=r.get('sourceRow'),originalID=r.get('originalID'),group=r['group'],cohort=r['cohort'],plannedRole=r['plannedRole'],role=r['role'],eligible=r['eligible'],y=r['y'],baselinePrediction=base['pred'][i],selectedPrediction=best['pred'][i],selectedRawPrediction=best['raw'][i],queryInvariant=best['invariant'][i])for i,r in enumerate(rows)]\n  return dict(kind=kind,nativeRows=len(rows),eligibleRows=sum(r['eligible']for r in rows),selection=selection,models=[dict(id=d[0],train=f['train'],mass=f.get('mass'),meanX=f.get('meanX'),scales=f.get('scales'),model=f.get('model'))for d,f in zip(defs,fits)],paired=paired,records=records)\n rows=fixed_rows(a.get('rows',[]));binary=a.get('task')=='binary'\n if api=='split':\n  assignment,state,order=split(rows,a.get('seed',0));records=[dict(id=r['id'],group=r['group'],rank=assignment[r['group']][0],role=assignment[r['group']][1])for r in rows]\n  return dict(state=state,groupOrder=order,records=records,groupCount=len(order))\n if api=='fit':return fit(rows,a.get('method','constant'),Q(a.get('lambda','0')),a.get('minLeafRows',1),binary)\n if api=='evaluate':\n  pred=[Q(r.get('prediction'))for r in a['rows']];threshold=Q(a.get('threshold','1/2'));rr=risk(rows,pred,binary,threshold)\n  records=[]\n  for r,p in zip(rows,pred):\n   valid=r['w']>0 and r['y']is not None and p is not None and r['role']not in ['excluded','unused']\n   records.append(dict(id=r['id'],weight=r['w'],y=r['y'],prediction=p,eligible=valid,loss=(p-r['y'])**2 if valid else None,correct=dict(defined=valid and binary,value=bool(int(p>=threshold)==int(r['y']))if valid and binary else None)))\n  return dict(metrics=rr,records=records)\n if api=='select':return run_selection(rows,[(c['id'],list(map(Q,c['predictions'])))for c in a['candidates']],a.get('criterion','mean'),a.get('requiredCohorts',list(dict.fromkeys(r['cohort']for r in rows))),binary)\n if api=='paired':return weighted_pair(rows,[Q(r.get('predictionA'))for r in a['rows']],[Q(r.get('predictionB'))for r in a['rows']])\n raise ValueError('unknown-api')\n\ndef report_values(api,z):\n summary=[];series=[]\n def add(k,v,u='dimensionless'):summary.append((k,v,u))\n if api=='split':\n  add('groups',z['groupCount'],'groups');add('rows',len(z['records']),'rows');add('finalState',z['state'],'unsigned 32-bit state')\n  series=[('planned role code',[(i,F({'test':0,'validation':1,'train':2}[r['role']]))for i,r in enumerate(z['records'])])]\n elif api=='fit':\n  add('defined',z['defined']);add('trainingRows',len(z['train']),'rows');add('trainingMass',z.get('mass'),'analysis weight mass')\n  model=z.get('model',{});add('modelRank',model.get('rank'),'parameters');add('threshold',model.get('threshold'),'constructed feature units');add('minimumObjective',model.get('minimumObjective'),'constructed squared outcome units')\n  series=[('prediction',list(enumerate(z['pred'])))];\n  if model.get('theta')is not None:\n   for i,v in enumerate(model['theta']):add('theta'+str(i),v,'constructed outcome units per standardized coordinate')\n elif api=='evaluate':\n  for k in ['rows','mass','MSE','MAE','R2','Brier','accuracy','positiveRecall','negativeRecall','precision','F1','balancedAccuracy','AUROC']: \n   if k in z['metrics']:add(k,z['metrics'][k],'rows'if k=='rows'else'analysis weight mass'if k=='mass'else FIXED['unit']if k in ['MSE','Brier']else'constructed outcome units'if k=='MAE'else'dimensionless')\n  series=[('squared loss',[(i,r['loss'])for i,r in enumerate(z['records'])])]\n elif api=='select':\n  add('selectedIndex',z['selectedIndex'],'zero-based candidate index')\n  for i,c in enumerate(z['candidates']):add('criterion'+str(i),c['criterion'],FIXED['unit']);add('testMSE'+str(i),c['test']['MSE'],FIXED['unit'])\n  series=[('validation criterion',[(i,c['criterion'])for i,c in enumerate(z['candidates'])]),('test MSE',[(i,c['test']['MSE'])for i,c in enumerate(z['candidates'])])]\n elif api=='paired':\n  for k in ['rows','mass','groupCount','meanDifference','minimumLeaveOut','maximumLeaveOut','varianceProxy']:add(k,z[k],'rows'if k=='rows'else'groups'if k=='groupCount'else'analysis weight mass'if k=='mass'else FIXED['unit']+' squared'if k=='varianceProxy'else FIXED['unit'])\n  series=[('loss A minus loss B',[(i,r['difference'])for i,r in enumerate(z['records'])])]\n elif api=='realdata':\n  add('nativeRows',z['nativeRows'],'native records');add('eligibleRows',z['eligibleRows'],'complete records');add('selectedIndex',z['selection']['selectedIndex'],'zero-based candidate index')\n  for i,c in enumerate(z['selection']['candidates']):add('validationMSE'+str(i),c['validation']['MSE'],FIXED['unit']);add('testMSE'+str(i),c['test']['MSE'],FIXED['unit'])\n  for k in ['meanDifference','minimumLeaveOut','maximumLeaveOut','varianceProxy']:add(k,z['paired'][k],FIXED['unit']+' squared'if k=='varianceProxy'else FIXED['unit'])\n  best=z['selection']['candidates'][z['selection']['selectedIndex']]['test']\n  for k in ['accuracy','positiveRecall','negativeRecall','precision','balancedAccuracy','AUROC']:\n   if k in best:add(k,best[k])\n  series=[('validation MSE',[(i,c['validation']['MSE'])for i,c in enumerate(z['selection']['candidates'])]),('test MSE',[(i,c['test']['MSE'])for i,c in enumerate(z['selection']['candidates'])])]\n return summary,series\n\n\ndef fixed_svg(points,title):\n good=[p for p in points if p['y'] is not None];xx=[float(p['x'])for p in good];yy=[float(p['y'])for p in good];xmin=min(xx)if xx else 0;xmax=max(xx)if xx else 1;ymin=min([0]+yy);ymax=max([0]+yy)\n if xmin==xmax:xmin-=.5;xmax+=.5\n if ymin==ymax:ymin-=.5;ymax+=.5\n pad=(ymax-ymin)*.08;ymin-=pad;ymax+=pad;X=lambda x:82+(float(x)-xmin)/(xmax-xmin)*608;Y=lambda y:354-(float(y)-ymin)/(ymax-ymin)*290;e=html.escape\n out=['<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"720\" height=\"480\" viewBox=\"0 0 720 480\" role=\"img\" aria-label=\"'+e(title)+'\"><rect width=\"720\" height=\"480\" fill=\"white\"/><g font-family=\"Arial,sans-serif\" font-size=\"13\" fill=\"#18232f\"><text x=\"360\" y=\"25\" text-anchor=\"middle\">'+e(title)+'</text>']\n for j in range(5):\n  y=ymin+(ymax-ymin)*j/4;x=xmin+(xmax-xmin)*j/4;out.append('<line x1=\"82\" y1=\"'+str(Y(y))+'\" x2=\"690\" y2=\"'+str(Y(y))+'\" stroke=\"#e2e8f0\"/><text x=\"73\" y=\"'+str(Y(y)+4)+'\" text-anchor=\"end\">'+format(y,'.3g')+'</text><text x=\"'+str(X(x))+'\" y=\"380\" text-anchor=\"middle\">'+format(x,'.3g')+'</text>')\n series=list(dict.fromkeys(p['series']for p in good))\n for j,s in enumerate(series):\n  pp=[p for p in good if p['series']==s];color=['#0f766e','#c76622','#4f46e5','#b23857'][j%4]\n  for p in pp:out.append('<circle cx=\"'+format(X(p['x']),'.6f')+'\" cy=\"'+format(Y(p['y']),'.6f')+'\" r=\"2.6\" fill=\"'+color+'\"><title>'+e(s+': '+str(p['y']))+'</title></circle>')\n  out.append('<text x=\"'+str(82+(j%2)*310)+'\" y=\"'+str(432+(j//2)*23)+'\" fill=\"'+color+'\">'+e(s)+'</text>')\n out.append('<text x=\"360\" y=\"405\" text-anchor=\"middle\">Declared record / candidate index; units in summary</text></g></svg>');return''.join(out)\n\nFIXED={'api': 'fit', 'variant': 'ridge-penalty-one', 'title': 'Ridge penalty one under mean loss', 'input': {'method': 'ridge', 'lambda': '1', 'rows': [{'id': 'a', 'x': ['0'], 'y': '1'}, {'id': 'b', 'x': ['2'], 'y': '5'}, {'id': 'query', 'x': ['1'], 'y': None, 'role': 'test'}]}, 'unit': 'Constructed outcome units', 'titleI18n': {'ko': '평균 손실의 릿지 벌점 1', 'en': 'Ridge penalty one under mean loss'}}\n\nOUT=Path(sys.argv[1]);OUT.mkdir(parents=True,exist_ok=False)\nresult=fixed_operation(FIXED['api'],FIXED['input']);summary,series=report_values(FIXED['api'],result)\ndef encode(v):\n if isinstance(v,F):return str(v)\n if isinstance(v,dict):return{k:encode(x)for k,x in v.items()}\n if isinstance(v,(list,tuple)):return[encode(x)for x in v]\n return v\n(OUT/'full.json').write_text(json.dumps(dict(arithmetic='Exact rational author implementation; factual rows, declared group split and finite five-candidate comparison',result=encode(result)),ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\nsummaryRows=[dict(metric=m,value=''if v is None else str(int(v))if isinstance(v,bool)else str(v),unit=u,defined=int(v is not None))for m,v,u in summary]\npoints=[dict(series=name,index=i,x=str(x),y=''if y is None else str(y),defined=int(y is not None))for name,pp in series for i,(x,y)in enumerate(pp)]\nfor name,rows in [('summary',summaryRows),('plot-points',points)]:\n with(OUT/(name+'.csv')).open('w',encoding='utf8',newline='')as f:writer=csv.DictWriter(f,fieldnames=list(rows[0]));writer.writeheader();writer.writerows(rows)\n(OUT/'plot.svg').write_text(fixed_svg([dict(p,x=number(p['x']),y=None if not p['defined']else number(p['y']))for p in points],FIXED['title']),encoding='utf8');print(FIXED['api']+'/'+FIXED['variant'])\n",
        "returnCode": 0,
        "stdout": "fit/ridge-penalty-one\r\n",
        "stderr": "",
        "diagnosticScope": "Public projection omits private absolute-path/traceback frames; actual exit and warnings/reason retained. Raw complete streams and commands in private execution proof.",
        "resultFolder": "ml22-code/runs/python-fit-ridge-penalty-one",
        "kind": null,
        "inputFiles": [
          {
            "file": "ml22-code/fit-ridge-penalty-one-input.json",
            "sha256": "7db29be566e21abc7453d5683d9f463b40b3d873a52faf6c346379586a5263ed",
            "scope": "Complete fixed literal input; program embeds the same values"
          }
        ],
        "files": [
          {
            "file": "ml22-code/runs/python-fit-ridge-penalty-one/full.json",
            "sha256": "b25412f8abf4fb435f0f75f997dfbc9eb7acf12a9786db9b113b7c11ba0c4e2c",
            "bytes": 740
          },
          {
            "file": "ml22-code/runs/python-fit-ridge-penalty-one/plot-points.csv",
            "sha256": "3331d779a6549e6a4a2c4903f29f565936f55447d35e7b49dc8c408b36740716",
            "bytes": 92
          },
          {
            "file": "ml22-code/runs/python-fit-ridge-penalty-one/plot.svg",
            "sha256": "631493ca064e483198c779a910e795aea45dda6d54c9a8b0375b5a34e0e15c87",
            "bytes": 1685
          },
          {
            "file": "ml22-code/runs/python-fit-ridge-penalty-one/summary.csv",
            "sha256": "8eb97c950c5361a287c3b1b6b9ec79c37880edd64f8affc8c0a95c42f91c0247",
            "bytes": 374
          }
        ],
        "summaryRows": [
          {
            "metric": "defined",
            "value": "1.0",
            "unit": "dimensionless",
            "defined": "true",
            "rawValue": "1",
            "arithmetic": "Exact Fraction",
            "exactFraction": "1",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "trainingRows",
            "value": "2.0",
            "unit": "rows",
            "defined": "true",
            "rawValue": "2",
            "arithmetic": "Exact Fraction",
            "exactFraction": "2",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "trainingMass",
            "value": "2.0",
            "unit": "analysis weight mass",
            "defined": "true",
            "rawValue": "2",
            "arithmetic": "Exact Fraction",
            "exactFraction": "2",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "modelRank",
            "value": "2.0",
            "unit": "parameters",
            "defined": "true",
            "rawValue": "2",
            "arithmetic": "Exact Fraction",
            "exactFraction": "2",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "threshold",
            "value": "",
            "unit": "constructed feature units",
            "defined": "false",
            "rawValue": "",
            "arithmetic": "Exact Fraction",
            "exactFraction": null
          },
          {
            "metric": "minimumObjective",
            "value": "1.6",
            "unit": "constructed squared outcome units",
            "defined": "true",
            "rawValue": "8/5",
            "arithmetic": "Exact Fraction",
            "exactFraction": "8/5",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "theta0",
            "value": "3.0",
            "unit": "constructed outcome units per standardized coordinate",
            "defined": "true",
            "rawValue": "3",
            "arithmetic": "Exact Fraction",
            "exactFraction": "3",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "theta1",
            "value": "0.8",
            "unit": "constructed outcome units per standardized coordinate",
            "defined": "true",
            "rawValue": "4/5",
            "arithmetic": "Exact Fraction",
            "exactFraction": "4/5",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          }
        ],
        "plotRows": [
          {
            "series": "prediction",
            "index": "0",
            "x": "0",
            "y": "13/5",
            "defined": true,
            "xExact": "0",
            "yExact": "13/5"
          },
          {
            "series": "prediction",
            "index": "1",
            "x": "1",
            "y": "17/5",
            "defined": true,
            "xExact": "1",
            "yExact": "17/5"
          },
          {
            "series": "prediction",
            "index": "2",
            "x": "2",
            "y": "3",
            "defined": true,
            "xExact": "2",
            "yExact": "3"
          }
        ],
        "plotFile": "ml22-code/runs/python-fit-ridge-penalty-one/plot.svg",
        "fullResultFile": "ml22-code/runs/python-fit-ridge-penalty-one/full.json",
        "arithmeticScope": "Python exact rational versus base-R approximate floating algebra; copied author kernels, not independent oracle.",
        "plotScope": "Original scatter vectors plot every defined declared comparison point, with missing points omitted. Source profiles show candidate risks; all source records remain in the full result and source CSV files.",
        "reproductionScope": "Standalone literal program plus four native CSV files for factual source profiles. No answer/engine/checker imports."
      },
      "stump-exact-tie": {
        "api": "fit",
        "variant": "stump-exact-tie",
        "language": "python",
        "title": "An exact one-split tree tie",
        "titleI18n": {
          "ko": "한 단계 나무의 정확한 동률",
          "en": "An exact one-split tree tie"
        },
        "input": {
          "method": "stump",
          "minLeafRows": 1,
          "rows": [
            {
              "x": [
                "0",
                "0"
              ],
              "y": "0"
            },
            {
              "x": [
                "1",
                "1"
              ],
              "y": "1"
            },
            {
              "x": [
                "2",
                "2"
              ],
              "y": "0"
            }
          ]
        },
        "expectedFailure": false,
        "codeFile": "ml22-code/fit-stump-exact-tie.py",
        "codeSHA256": "62e4afa52b472cfc03de2e273c8ffc53eaa709b979c4c392105d81dd200357d0",
        "code": "# ML22 standalone fixed literal. Attribution and arithmetic scope in README.\nimport csv,hashlib,html,json,math,sys,time\nfrom pathlib import Path\nfrom fractions import Fraction as F\nfrom collections import Counter\nsys.set_int_max_str_digits(200000)\nnumber=lambda v:F(str(v))\ndef Q(x):return None if x is None or x in ('','.') else F(str(x))\n\ndef canonical(v):return None if Q(v) is None else str(Q(v))\n\ndef fingerprint(tag,values):return tag+':'+hashlib.sha256(json.dumps([canonical(x)for x in values],separators=(',',':')).encode()).hexdigest()\n\ndef split(rows,seed=20261104,pattern=('test','validation','train','train')):\n order=sorted(set(r['group'] for r in rows));state=seed\n for j in range(len(order)-1,0,-1):state=(1664525*state+1013904223)&0xffffffff;k=state%(j+1);order[k],order[j]=order[j],order[k]\n roles={g:(i,pattern[i%len(pattern)]) for i,g in enumerate(order)}\n return roles,state,order\n\ndef solve(A,b):\n n=len(b);M=[list(row)+[rhs]for row,rhs in zip(A,b)];piv=[];rank=0\n for j in range(n):\n  candidates=[i for i in range(rank,n)if M[i][j]]\n  if not candidates:continue\n  k=max(candidates,key=lambda i:abs(M[i][j]));M[rank],M[k]=M[k],M[rank];v=M[rank][j];M[rank]=[x/v for x in M[rank]]\n  for i in range(n):\n   if i!=rank:\n    v=M[i][j];M[i]=[a-v*b for a,b in zip(M[i],M[rank])]\n  piv.append(j);rank+=1\n x=[F(0)]*n\n for i,j in enumerate(piv):x[j]=M[i][-1]\n null=[]\n for j in range(n):\n  if j not in piv:\n   v=[F(0)]*n;v[j]=F(1)\n   for i,k in enumerate(piv):v[k]=-M[i][j]\n   null.append(v)\n return x,rank,null\n\ndef dot(a,b):return sum((x*y for x,y in zip(a,b)),F(0))\n\ndef fit(rows,method,lam=F(0),minleaf=1,binary=False):\n use=[r for r in rows if r['role']=='train'and r['w']>0 and r['y']is not None and None not in r['x']];p=len(rows[0]['x'])if rows else 0\n if not use:return dict(defined=False,pred=[None]*len(rows),raw=[None]*len(rows),train=[],invariant=[None]*len(rows))\n mass=sum(r['w']for r in use);mu=[sum(r['w']*r['x'][j]for r in use)/mass for j in range(p)];scale=[max(r['x'][j]for r in use)-min(r['x'][j]for r in use)or F(1)for j in range(p)];mean=sum(r['w']*r['y']for r in use)/mass;model={};z=lambda r:[F(1)]+[(x-m)/s for x,m,s in zip(r['x'],mu,scale)]\n if method=='constant':model=dict(mean=mean,parameterCount=1,rank=1,unique=True)\n elif method=='ridge':\n  vectors=[z(r)for r in use];n=p+1;A=[[sum(r['w']*xx[j]*xx[k]for r,xx in zip(use,vectors))/mass+(lam if j==k and j>0 else F(0))for k in range(n)]for j in range(n)];b=[sum(r['w']*r['y']*xx[j]for r,xx in zip(use,vectors))/mass for j in range(n)];theta,rank,null=solve(A,b);objective=sum(r['w']*(dot(xx,theta)-r['y'])**2 for r,xx in zip(use,vectors))/(2*mass)+lam*sum(x*x for x in theta[1:])/2;model=dict(lambdaValue=lam,theta=theta,rank=rank,unique=rank==n,nullspace=null,minimumObjective=objective,parameterCount=n)\n else:\n  best=None;total=sum(r['w']*r['y']for r in use);total2=sum(r['w']*r['y']**2 for r in use);base=total2-total**2/mass\n  for j in range(p):\n   ordered=sorted(enumerate(use),key=lambda v:(v[1]['x'][j],v[0]));leftW=F(0);leftS=F(0)\n   for i,(_idx,r)in enumerate(ordered[:-1]):\n    leftW+=r['w'];leftS+=r['w']*r['y'];rightW=mass-leftW\n    if i+1<minleaf or len(use)-i-1<minleaf or r['x'][j]==ordered[i+1][1]['x'][j]:continue\n    SSE=total2-leftS**2/leftW-(total-leftS)**2/rightW\n    if best is None or SSE<best['weightedSSE']:best=dict(feature=j,threshold=(r['x'][j]+ordered[i+1][1]['x'][j])/2,leftMean=leftS/leftW,rightMean=(total-leftS)/rightW,leftRows=i+1,rightRows=len(use)-i-1,leftWeight=leftW,rightWeight=rightW,weightedSSE=SSE)\n  model=dict(split=False,mean=mean,weightedSSE=base,trainingMSE=base/mass)if best is None or best['weightedSSE']>=base else dict(split=True,**best,trainingMSE=best['weightedSSE']/mass,improvement=(base-best['weightedSSE'])/mass)\n raw=[];invariant=[]\n for r in rows:\n  if None in r['x']:raw.append(None);invariant.append(None);continue\n  if method=='constant':v=mean;iv=True\n  elif method=='ridge':zz=z(r);v=dot(zz,model['theta']);iv=all(dot(zz,nn)==0 for nn in model['nullspace'])\n  else:v=(model['leftMean']if r['x'][model['feature']]<=model['threshold']else model['rightMean'])if model['split']else mean;iv=True\n  raw.append(v);invariant.append(iv)\n pred=[None if x is None else min(F(1),max(F(0),x))if binary else x for x in raw]\n return dict(defined=True,train=[r['id']for r in use],mass=mass,meanX=mu,scales=scale,model=model,pred=pred,raw=raw,invariant=invariant)\n\ndef risk(rows,pred,binary=False,threshold=F(1,2)):\n use=[(r,p)for r,p in zip(rows,pred)if r['w']>0 and r['y']is not None and p is not None and r['role']not in['excluded','unused']];mass=sum((r['w']for r,p in use),F(0));d=dict(rows=len(use),mass=mass)\n if not mass:\n  d.update({k:None for k in ['MSE','MAE','R2']+(['Brier','accuracy','balancedAccuracy','AUROC']if binary else[])});return d\n mean=sum(r['w']*r['y']for r,p in use)/mass;sse=sum(r['w']*(p-r['y'])**2 for r,p in use);sst=sum(r['w']*(r['y']-mean)**2 for r,p in use);d.update(meanY=mean,SSE=sse,SST=sst,MSE=sse/mass,MAE=sum(r['w']*abs(p-r['y'])for r,p in use)/mass,R2=1-sse/sst if sst else None)\n if binary:\n  weights=Counter();num=Counter()\n  for r,p in use:k=('T'if int(p>=threshold)==int(r['y'])else'F')+('P'if p>=threshold else'N');weights[k]+=r['w'];num[k]+=1\n  TP,FP,TN,FN=[weights[k]for k in ['TP','FP','TN','FN']];positive=TP+FN;negative=TN+FP;rate=lambda a,b:a/b if b else None;TPR=rate(TP,positive);TNR=rate(TN,negative)\n  # Pair enumeration is independent of the subject's score-tie-block formula.\n  negatives=[(r,p)for r,p in use if not r['y']];positives=[(r,p)for r,p in use if r['y']];wins=sum((a['w']*b['w']*(F(1)if pa>pb else F(1,2)if pa==pb else F(0))for a,pa in positives for b,pb in negatives),F(0))\n  d.update(Brier=d['MSE'],threshold=threshold,confusionMass={k:weights[k]for k in ['TP','FP','TN','FN']},confusionRows={k:num[k]for k in ['TP','FP','TN','FN']},positiveMass=positive,negativeMass=negative,accuracy=(TP+TN)/mass,positiveRecall=TPR,negativeRecall=TNR,precision=rate(TP,TP+FP),F1=rate(2*TP,2*TP+FP+FN),balancedAccuracy=(TPR+TNR)/2 if TPR is not None and TNR is not None else None,AUROC=rate(wins,positive*negative))\n return d\n\nNATIVE_SHA256={'actual1599-red-wine-original12-fields.csv': '77e9ac73115930d6c43983333a5a57940deefc493affeb17aca478c09c5f6e00', 'actual4898-white-wine-original12-fields.csv': '50d810bbb42b9cc3e87fa4c27a4c0f168e72da09dd812863425ca3873fec28ef', 'actual3613-NLS-original52-fields.csv': '6e1e1895558795435b65f8634252a7589865273a0e69adbd715fcfa04a3c11a1', 'actual3150-churn-original14-fields.csv': '1c0753e434226e769d1015c922121a7d8967df66014e057c4f7543e490f11764'}\n\ndef read_sources(directory,seed):\n def read(name):\n  p=directory/name\n  if hashlib.sha256(p.read_bytes()).hexdigest()!=NATIVE_SHA256[name]:raise ValueError('Native file hash differs: '+name)\n  with p.open(encoding='utf8',newline='')as f:return list(csv.DictReader(f))\n sources={};wine=[]\n for typ,n in [('red',1599),('white',4898)]:\n  table=read(f'actual{n}-{typ}-wine-original12-fields.csv');assert len(table)==n;features=[k for k in table[0]if k not in ['sourceRow','wineType','quality']];assert len(features)==11\n  for r in table:\n   i=int(r['sourceRow']);red='1'if typ=='red'else'0';nativeX=[r[k]for k in features];wine.append(dict(id=f'wine-{typ}-row:{i}',sourceRow=f'{typ}:{i}',originalID=None,group=fingerprint('wine-predictors',[red]+nativeX),cohort=typ,x=list(map(Q,nativeX+[red])),y=Q(r['quality'])))\n sources['country']=wine\n table=read('actual3613-NLS-original52-fields.csv');assert len(table)==3613;sources['person']=[dict(id='nls-row:'+r['sourceRow'],sourceRow=int(r['sourceRow']),originalID=r['id'],group='nls-id:'+r['id'],cohort='schooling-over12'if Q(r['ed76'])>12 else'schooling-at-most12',x=[Q(r['ed76']),Q(r['age76'])],y=Q(r['lwage76']))for r in table]\n table=read('actual3150-churn-original14-fields.csv');assert len(table)==3150;predictors=[k for k in table[0]if k not in ['sourceRow','Churn']];assert len(predictors)==13;sources['company']=[dict(id='customer-row:'+r['sourceRow'],sourceRow=int(r['sourceRow']),originalID=None,group=fingerprint('customer-predictors',[r[k]for k in predictors]),cohort='pay-as-you-go'if r['Tariff Plan']=='1'else'contractual'if r['Tariff Plan']=='2'else'other-native-tariff',x=[Q(r[k])for k in ['Call  Failure','Subscription  Length','Seconds of Use','Age']],y=Q(r['Churn']))for r in table]\n for kind,rows in sources.items():\n  assignments,state,order=split(rows,seed)\n  for r in rows:\n   rank,planned=assignments[r['group']];r.update(w=F(1),splitRank=rank,plannedRole=planned,eligible=r['y']is not None and None not in r['x']);r['role']=planned if r['eligible']else'excluded'\n return sources\n# New ML22 fixed-profile kernels. The public Fraction fitting/source readers are\n# copied by value above this file by the standalone builder; never imported.\ndef fixed_rows(data, prediction_key=None):\n out=[]\n for i,a in enumerate(data):\n  w=Q(a.get('weight','1'))\n  if w is None or w<0:raise ValueError('negative-weight' if w is not None and w<0 else 'missing-weight')\n  out.append(dict(id=a.get('id',str(i)),group=a.get('group',a.get('id',str(i))),cohort=a.get('cohort','all'),role=a.get('role','train'),w=w,x=[Q(v)for v in a.get('x',[])],y=Q(a.get('y'))))\n return out\n\ndef weighted_pair(rows,A,B):\n use=[(r,a,b)for r,a,b in zip(rows,A,B)if r['w']>0 and r['y']is not None and a is not None and b is not None and r['role']not in ['excluded','unused']]\n mass=sum((r['w']for r,a,b in use),F(0));records=[];groups={}\n for r,a,b in use:\n  la=(a-r['y'])**2;lb=(b-r['y'])**2;d=la-lb\n  records.append(dict(id=r['id'],group=r['group'],weight=r['w'],lossA=la,lossB=lb,difference=d))\n  g=groups.setdefault(r['group'],dict(group=r['group'],rows=0,mass=F(0),sum=F(0)));g['rows']+=1;g['mass']+=r['w'];g['sum']+=r['w']*d\n total=sum((g['sum']for g in groups.values()),F(0));mean=total/mass if mass else None;G=len(groups)\n for g in groups.values():g['leaveOut']=(total-g['sum'])/(mass-g['mass'])if mass>g['mass']else None\n leaves=[g['leaveOut']for g in groups.values()if g['leaveOut']is not None]\n proxy=F(G-1,G)*sum((v-sum(leaves,F(0))/G)**2 for v in leaves) if G>1 and len(leaves)==G else None\n return dict(rows=len(use),mass=mass,groupCount=G,meanDifference=mean,minimumLeaveOut=min(leaves)if leaves else None,maximumLeaveOut=max(leaves)if leaves else None,varianceProxy=proxy,groups=list(groups.values()),records=records)\n\ndef run_selection(rows,candidates,criterion,required,binary=False):\n results=[]\n for c,pred in candidates:\n  val=[dict(r,role='excluded')if r['role']!='validation'else r for r in rows]\n  test=[dict(r,role='excluded')if r['role']!='test'else r for r in rows]\n  v=risk(val,pred,binary);t=risk(test,pred,binary);cohort={g:risk([dict(r,role='excluded')if r['role']!='validation'or r['cohort']!=g else r for r in rows],pred,binary)for g in required}\n  values=[cohort[g]['MSE']for g in required]\n  score=v['MSE']if criterion=='mean'else max(values)if values and None not in values else None\n  results.append(dict(id=c,criterion=score,validation=v,test=t,cohorts=cohort))\n eligible=[(i,r['criterion'])for i,r in enumerate(results)if r['criterion']is not None]\n chosen=min(eligible,key=lambda t:(t[1],t[0]))[0]if eligible else None\n return dict(criterion=criterion,selected=results[chosen]['id']if chosen is not None else None,selectedIndex=chosen,candidates=results)\n\ndef fixed_operation(api,a):\n if api=='realdata':\n  kind=a['kind'];rows=read_sources(Path(__file__).parent/'data',a.get('seed',20261104))[kind];binary=kind=='company'\n  defs=[('constant','constant',F(0)),('ridge:1/100','ridge',F(1,100)),('ridge:1/10','ridge',F(1,10)),('ridge:1','ridge',F(1)),('one-split-stump','stump',F(0))]\n  fits=[fit(rows,method,lam,5,binary)for _,method,lam in defs]\n  selection=run_selection(rows,[(d[0],f['pred'])for d,f in zip(defs,fits)],a.get('criterion','mean'),list(dict.fromkeys(r['cohort']for r in rows)),binary)\n  chosen=selection['selectedIndex'];best=fits[chosen];base=fits[0]\n  test=[dict(r,role='excluded')if r['role']!='test'else r for r in rows]\n  paired=weighted_pair(test,best['pred'],base['pred'])\n  records=[dict(id=r['id'],sourceRow=r.get('sourceRow'),originalID=r.get('originalID'),group=r['group'],cohort=r['cohort'],plannedRole=r['plannedRole'],role=r['role'],eligible=r['eligible'],y=r['y'],baselinePrediction=base['pred'][i],selectedPrediction=best['pred'][i],selectedRawPrediction=best['raw'][i],queryInvariant=best['invariant'][i])for i,r in enumerate(rows)]\n  return dict(kind=kind,nativeRows=len(rows),eligibleRows=sum(r['eligible']for r in rows),selection=selection,models=[dict(id=d[0],train=f['train'],mass=f.get('mass'),meanX=f.get('meanX'),scales=f.get('scales'),model=f.get('model'))for d,f in zip(defs,fits)],paired=paired,records=records)\n rows=fixed_rows(a.get('rows',[]));binary=a.get('task')=='binary'\n if api=='split':\n  assignment,state,order=split(rows,a.get('seed',0));records=[dict(id=r['id'],group=r['group'],rank=assignment[r['group']][0],role=assignment[r['group']][1])for r in rows]\n  return dict(state=state,groupOrder=order,records=records,groupCount=len(order))\n if api=='fit':return fit(rows,a.get('method','constant'),Q(a.get('lambda','0')),a.get('minLeafRows',1),binary)\n if api=='evaluate':\n  pred=[Q(r.get('prediction'))for r in a['rows']];threshold=Q(a.get('threshold','1/2'));rr=risk(rows,pred,binary,threshold)\n  records=[]\n  for r,p in zip(rows,pred):\n   valid=r['w']>0 and r['y']is not None and p is not None and r['role']not in ['excluded','unused']\n   records.append(dict(id=r['id'],weight=r['w'],y=r['y'],prediction=p,eligible=valid,loss=(p-r['y'])**2 if valid else None,correct=dict(defined=valid and binary,value=bool(int(p>=threshold)==int(r['y']))if valid and binary else None)))\n  return dict(metrics=rr,records=records)\n if api=='select':return run_selection(rows,[(c['id'],list(map(Q,c['predictions'])))for c in a['candidates']],a.get('criterion','mean'),a.get('requiredCohorts',list(dict.fromkeys(r['cohort']for r in rows))),binary)\n if api=='paired':return weighted_pair(rows,[Q(r.get('predictionA'))for r in a['rows']],[Q(r.get('predictionB'))for r in a['rows']])\n raise ValueError('unknown-api')\n\ndef report_values(api,z):\n summary=[];series=[]\n def add(k,v,u='dimensionless'):summary.append((k,v,u))\n if api=='split':\n  add('groups',z['groupCount'],'groups');add('rows',len(z['records']),'rows');add('finalState',z['state'],'unsigned 32-bit state')\n  series=[('planned role code',[(i,F({'test':0,'validation':1,'train':2}[r['role']]))for i,r in enumerate(z['records'])])]\n elif api=='fit':\n  add('defined',z['defined']);add('trainingRows',len(z['train']),'rows');add('trainingMass',z.get('mass'),'analysis weight mass')\n  model=z.get('model',{});add('modelRank',model.get('rank'),'parameters');add('threshold',model.get('threshold'),'constructed feature units');add('minimumObjective',model.get('minimumObjective'),'constructed squared outcome units')\n  series=[('prediction',list(enumerate(z['pred'])))];\n  if model.get('theta')is not None:\n   for i,v in enumerate(model['theta']):add('theta'+str(i),v,'constructed outcome units per standardized coordinate')\n elif api=='evaluate':\n  for k in ['rows','mass','MSE','MAE','R2','Brier','accuracy','positiveRecall','negativeRecall','precision','F1','balancedAccuracy','AUROC']: \n   if k in z['metrics']:add(k,z['metrics'][k],'rows'if k=='rows'else'analysis weight mass'if k=='mass'else FIXED['unit']if k in ['MSE','Brier']else'constructed outcome units'if k=='MAE'else'dimensionless')\n  series=[('squared loss',[(i,r['loss'])for i,r in enumerate(z['records'])])]\n elif api=='select':\n  add('selectedIndex',z['selectedIndex'],'zero-based candidate index')\n  for i,c in enumerate(z['candidates']):add('criterion'+str(i),c['criterion'],FIXED['unit']);add('testMSE'+str(i),c['test']['MSE'],FIXED['unit'])\n  series=[('validation criterion',[(i,c['criterion'])for i,c in enumerate(z['candidates'])]),('test MSE',[(i,c['test']['MSE'])for i,c in enumerate(z['candidates'])])]\n elif api=='paired':\n  for k in ['rows','mass','groupCount','meanDifference','minimumLeaveOut','maximumLeaveOut','varianceProxy']:add(k,z[k],'rows'if k=='rows'else'groups'if k=='groupCount'else'analysis weight mass'if k=='mass'else FIXED['unit']+' squared'if k=='varianceProxy'else FIXED['unit'])\n  series=[('loss A minus loss B',[(i,r['difference'])for i,r in enumerate(z['records'])])]\n elif api=='realdata':\n  add('nativeRows',z['nativeRows'],'native records');add('eligibleRows',z['eligibleRows'],'complete records');add('selectedIndex',z['selection']['selectedIndex'],'zero-based candidate index')\n  for i,c in enumerate(z['selection']['candidates']):add('validationMSE'+str(i),c['validation']['MSE'],FIXED['unit']);add('testMSE'+str(i),c['test']['MSE'],FIXED['unit'])\n  for k in ['meanDifference','minimumLeaveOut','maximumLeaveOut','varianceProxy']:add(k,z['paired'][k],FIXED['unit']+' squared'if k=='varianceProxy'else FIXED['unit'])\n  best=z['selection']['candidates'][z['selection']['selectedIndex']]['test']\n  for k in ['accuracy','positiveRecall','negativeRecall','precision','balancedAccuracy','AUROC']:\n   if k in best:add(k,best[k])\n  series=[('validation MSE',[(i,c['validation']['MSE'])for i,c in enumerate(z['selection']['candidates'])]),('test MSE',[(i,c['test']['MSE'])for i,c in enumerate(z['selection']['candidates'])])]\n return summary,series\n\n\ndef fixed_svg(points,title):\n good=[p for p in points if p['y'] is not None];xx=[float(p['x'])for p in good];yy=[float(p['y'])for p in good];xmin=min(xx)if xx else 0;xmax=max(xx)if xx else 1;ymin=min([0]+yy);ymax=max([0]+yy)\n if xmin==xmax:xmin-=.5;xmax+=.5\n if ymin==ymax:ymin-=.5;ymax+=.5\n pad=(ymax-ymin)*.08;ymin-=pad;ymax+=pad;X=lambda x:82+(float(x)-xmin)/(xmax-xmin)*608;Y=lambda y:354-(float(y)-ymin)/(ymax-ymin)*290;e=html.escape\n out=['<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"720\" height=\"480\" viewBox=\"0 0 720 480\" role=\"img\" aria-label=\"'+e(title)+'\"><rect width=\"720\" height=\"480\" fill=\"white\"/><g font-family=\"Arial,sans-serif\" font-size=\"13\" fill=\"#18232f\"><text x=\"360\" y=\"25\" text-anchor=\"middle\">'+e(title)+'</text>']\n for j in range(5):\n  y=ymin+(ymax-ymin)*j/4;x=xmin+(xmax-xmin)*j/4;out.append('<line x1=\"82\" y1=\"'+str(Y(y))+'\" x2=\"690\" y2=\"'+str(Y(y))+'\" stroke=\"#e2e8f0\"/><text x=\"73\" y=\"'+str(Y(y)+4)+'\" text-anchor=\"end\">'+format(y,'.3g')+'</text><text x=\"'+str(X(x))+'\" y=\"380\" text-anchor=\"middle\">'+format(x,'.3g')+'</text>')\n series=list(dict.fromkeys(p['series']for p in good))\n for j,s in enumerate(series):\n  pp=[p for p in good if p['series']==s];color=['#0f766e','#c76622','#4f46e5','#b23857'][j%4]\n  for p in pp:out.append('<circle cx=\"'+format(X(p['x']),'.6f')+'\" cy=\"'+format(Y(p['y']),'.6f')+'\" r=\"2.6\" fill=\"'+color+'\"><title>'+e(s+': '+str(p['y']))+'</title></circle>')\n  out.append('<text x=\"'+str(82+(j%2)*310)+'\" y=\"'+str(432+(j//2)*23)+'\" fill=\"'+color+'\">'+e(s)+'</text>')\n out.append('<text x=\"360\" y=\"405\" text-anchor=\"middle\">Declared record / candidate index; units in summary</text></g></svg>');return''.join(out)\n\nFIXED={'api': 'fit', 'variant': 'stump-exact-tie', 'title': 'An exact one-split tree tie', 'input': {'method': 'stump', 'minLeafRows': 1, 'rows': [{'x': ['0', '0'], 'y': '0'}, {'x': ['1', '1'], 'y': '1'}, {'x': ['2', '2'], 'y': '0'}]}, 'unit': 'Constructed outcome units', 'titleI18n': {'ko': '한 단계 나무의 정확한 동률', 'en': 'An exact one-split tree tie'}}\n\nOUT=Path(sys.argv[1]);OUT.mkdir(parents=True,exist_ok=False)\nresult=fixed_operation(FIXED['api'],FIXED['input']);summary,series=report_values(FIXED['api'],result)\ndef encode(v):\n if isinstance(v,F):return str(v)\n if isinstance(v,dict):return{k:encode(x)for k,x in v.items()}\n if isinstance(v,(list,tuple)):return[encode(x)for x in v]\n return v\n(OUT/'full.json').write_text(json.dumps(dict(arithmetic='Exact rational author implementation; factual rows, declared group split and finite five-candidate comparison',result=encode(result)),ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\nsummaryRows=[dict(metric=m,value=''if v is None else str(int(v))if isinstance(v,bool)else str(v),unit=u,defined=int(v is not None))for m,v,u in summary]\npoints=[dict(series=name,index=i,x=str(x),y=''if y is None else str(y),defined=int(y is not None))for name,pp in series for i,(x,y)in enumerate(pp)]\nfor name,rows in [('summary',summaryRows),('plot-points',points)]:\n with(OUT/(name+'.csv')).open('w',encoding='utf8',newline='')as f:writer=csv.DictWriter(f,fieldnames=list(rows[0]));writer.writeheader();writer.writerows(rows)\n(OUT/'plot.svg').write_text(fixed_svg([dict(p,x=number(p['x']),y=None if not p['defined']else number(p['y']))for p in points],FIXED['title']),encoding='utf8');print(FIXED['api']+'/'+FIXED['variant'])\n",
        "returnCode": 0,
        "stdout": "fit/stump-exact-tie\r\n",
        "stderr": "",
        "diagnosticScope": "Public projection omits private absolute-path/traceback frames; actual exit and warnings/reason retained. Raw complete streams and commands in private execution proof.",
        "resultFolder": "ml22-code/runs/python-fit-stump-exact-tie",
        "kind": null,
        "inputFiles": [
          {
            "file": "ml22-code/fit-stump-exact-tie-input.json",
            "sha256": "208b4ba4768c5e7e5ce21a49db871bcc4dbef23dfaaf4e3cd57210ea802195a7",
            "scope": "Complete fixed literal input; program embeds the same values"
          }
        ],
        "files": [
          {
            "file": "ml22-code/runs/python-fit-stump-exact-tie/full.json",
            "sha256": "663f1c2a949ecf8e28515873fe9794011bd4092df6cc32dbc3b7dd5111bf6dbb",
            "bytes": 868
          },
          {
            "file": "ml22-code/runs/python-fit-stump-exact-tie/plot-points.csv",
            "sha256": "2e09d19fb85aceb900cad06d06819976edaa3f46d2c38e4097c12e2fca5b9856",
            "bytes": 90
          },
          {
            "file": "ml22-code/runs/python-fit-stump-exact-tie/plot.svg",
            "sha256": "8a5e5fed75b349f02cbaa39108d5c71aa6a1131c6c899d94aadce718d015ea10",
            "bytes": 1632
          },
          {
            "file": "ml22-code/runs/python-fit-stump-exact-tie/summary.csv",
            "sha256": "b847dea2e37d0b7faa57a36881c9fec85fc0b1b3d90e687dddacb00b3690fc8c",
            "bytes": 239
          }
        ],
        "summaryRows": [
          {
            "metric": "defined",
            "value": "1.0",
            "unit": "dimensionless",
            "defined": "true",
            "rawValue": "1",
            "arithmetic": "Exact Fraction",
            "exactFraction": "1",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "trainingRows",
            "value": "3.0",
            "unit": "rows",
            "defined": "true",
            "rawValue": "3",
            "arithmetic": "Exact Fraction",
            "exactFraction": "3",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "trainingMass",
            "value": "3.0",
            "unit": "analysis weight mass",
            "defined": "true",
            "rawValue": "3",
            "arithmetic": "Exact Fraction",
            "exactFraction": "3",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "modelRank",
            "value": "",
            "unit": "parameters",
            "defined": "false",
            "rawValue": "",
            "arithmetic": "Exact Fraction",
            "exactFraction": null
          },
          {
            "metric": "threshold",
            "value": "0.5",
            "unit": "constructed feature units",
            "defined": "true",
            "rawValue": "1/2",
            "arithmetic": "Exact Fraction",
            "exactFraction": "1/2",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "minimumObjective",
            "value": "",
            "unit": "constructed squared outcome units",
            "defined": "false",
            "rawValue": "",
            "arithmetic": "Exact Fraction",
            "exactFraction": null
          }
        ],
        "plotRows": [
          {
            "series": "prediction",
            "index": "0",
            "x": "0",
            "y": "0",
            "defined": true,
            "xExact": "0",
            "yExact": "0"
          },
          {
            "series": "prediction",
            "index": "1",
            "x": "1",
            "y": "1/2",
            "defined": true,
            "xExact": "1",
            "yExact": "1/2"
          },
          {
            "series": "prediction",
            "index": "2",
            "x": "2",
            "y": "1/2",
            "defined": true,
            "xExact": "2",
            "yExact": "1/2"
          }
        ],
        "plotFile": "ml22-code/runs/python-fit-stump-exact-tie/plot.svg",
        "fullResultFile": "ml22-code/runs/python-fit-stump-exact-tie/full.json",
        "arithmeticScope": "Python exact rational versus base-R approximate floating algebra; copied author kernels, not independent oracle.",
        "plotScope": "Original scatter vectors plot every defined declared comparison point, with missing points omitted. Source profiles show candidate risks; all source records remain in the full result and source CSV files.",
        "reproductionScope": "Standalone literal program plus four native CSV files for factual source profiles. No answer/engine/checker imports."
      }
    },
    "r": {
      "constant-common-frame": {
        "api": "fit",
        "variant": "constant-common-frame",
        "language": "r",
        "title": "A constant on the same complete training frame",
        "titleI18n": {
          "ko": "상수도 같은 완전 훈련 집합",
          "en": "A constant on the same complete training frame"
        },
        "input": {
          "method": "constant",
          "rows": [
            {
              "id": "a",
              "x": [
                "0"
              ],
              "y": "1"
            },
            {
              "id": "b",
              "x": [
                "2"
              ],
              "y": "5"
            },
            {
              "id": "incomplete",
              "x": [
                null
              ],
              "y": "99"
            },
            {
              "id": "query",
              "x": [
                "1"
              ],
              "y": null,
              "role": "test"
            }
          ]
        },
        "expectedFailure": false,
        "codeFile": "ml22-code/fit-constant-common-frame.R",
        "codeSHA256": "149d9a296dcf81705e3dccd08063de293fcffe7232962efa5e0a8a022511cbbc",
        "code": "# ML22 standalone; source/public functions copied by value, no source() dependency.\noptions(stringsAsFactors=FALSE,digits=17,warn=1)\nargs0<-commandArgs(trailingOnly=FALSE);script0<-sub('^--file=','',args0[grepl('^--file=',args0)][1]);source_dir<-file.path(dirname(normalizePath(script0)), 'data');seed<-20261104;leaf_min<-5\nnative_hash <- c(\"actual1599-red-wine-original12-fields.csv\"=\"77e9ac73115930d6c43983333a5a57940deefc493affeb17aca478c09c5f6e00\",\"actual4898-white-wine-original12-fields.csv\"=\"50d810bbb42b9cc3e87fa4c27a4c0f168e72da09dd812863425ca3873fec28ef\",\"actual3613-NLS-original52-fields.csv\"=\"6e1e1895558795435b65f8634252a7589865273a0e69adbd715fcfa04a3c11a1\",\"actual3150-churn-original14-fields.csv\"=\"1c0753e434226e769d1015c922121a7d8967df66014e057c4f7543e490f11764\")\nsha256<-getExportedValue('tools','sha256sum')\nread_native<-function(name){f<-file.path(source_dir,name);if(unname(sha256(f))!=native_hash[[name]])stop(paste('Native hash differs',name));read.csv(f,check.names=FALSE,colClasses='character',na.strings=NULL)}\ngcd_small<-function(a,b){while(b!=0){r<-a%%b;a<-b;b<-r};a}\ncanonical<-function(token){\n if(is.na(token)||token%in%c('','.'))return('null')\n if(!grepl('^[+-]?[0-9]+([.][0-9]*)?$',token))stop('Unsupported native fingerprint token')\n neg<-substr(token,1,1)=='-';s<-sub('^[+-]','',token);parts<-strsplit(s,'.',fixed=TRUE)[[1]];dec<-if(length(parts)==2)nchar(parts[2])else 0;n<-as.numeric(gsub('.','',s,fixed=TRUE));d<-10^dec\n # Every native fingerprint numerator/denominator must remain exactly integral\n # in binary64; reject rather than silently rounding a changed future source.\n if(!is.finite(n)||n>2^53||d>2^53)stop('Native canonical integer range exceeded')\n g<-gcd_small(n,d);n<-n/g;d<-d/g;if(neg)n<--n\n out<-sprintf('%.0f',n);if(d!=1)out<-paste0(out,'/',sprintf('%.0f',d));out\n}\nfp_cache<-new.env(hash=TRUE,parent=emptyenv());hash_file<-tempfile('ml22-hash-')\nfingerprint<-function(tag,values){a<-vapply(values,canonical,'');payload<-paste0('[',paste0('\"',a,'\"',collapse=','),']');key<-paste0(tag,':',payload);if(exists(key,fp_cache,inherits=FALSE))return(get(key,fp_cache,inherits=FALSE));con<-file(hash_file,'wb');writeBin(charToRaw(payload),con);close(con);value<-paste0(tag,':',unname(sha256(hash_file)));assign(key,value,fp_cache);value}\nassign_roles<-function(group){order<-sort(unique(group),method='radix');state<-seed;if(length(order)>1)for(j in seq.int(length(order),2)){state<-(1664525*state+1013904223)%%2^32;k<-state%%j+1;order[c(j,k)]<-order[c(k,j)]};rank<-match(group,order)-1;list(rank=rank,planned=c('test','validation','train','train')[rank%%4+1],state=state)}\n\nfit_model<-function(r,x,method,lambda){\n tr<-which(r$role=='train'&r$eligible);if(!length(tr))stop('No complete positive training rows');y<-r$y[tr];xx<-x[tr,,drop=FALSE];mu<-colMeans(xx);scale<-apply(xx,2,function(v)diff(range(v)));scale[scale==0]<-1;z<-cbind(1,sweep(sweep(x,2,mu,'-'),2,scale,'/'));meanY<-mean(y);model<-list();n<-length(tr)\n if(method=='constant'){model<-list(mean=meanY,parameterCount=1,rank=1,unique=TRUE);raw<-rep(meanY,nrow(r))}\n else if(method=='ridge'){zt<-z[tr,,drop=FALSE];pen<-diag(c(0,rep(lambda,ncol(x))));theta<-drop(solve(crossprod(zt)/n+pen,crossprod(zt,y)/n));raw<-drop(z%*%theta);objective<-mean((y-raw[tr])^2)/2+lambda*sum(theta[-1]^2)/2;model<-list(lambdaValue=lambda,theta=theta,rank=length(theta),unique=TRUE,minimumObjective=objective,parameterCount=length(theta))}\n else{base<-sum((y-meanY)^2);best<-NULL;total<-sum(y);total2<-sum(y*y)\n  for(j in seq_len(ncol(x))){ord<-order(xx[,j],seq_len(n));sx<-xx[ord,j];sy<-y[ord];left<-cumsum(sy)\n   if(n<2*leaf_min)next\n   for(i in seq.int(leaf_min,n-leaf_min)){if(sx[i]==sx[i+1])next;loss<-total2-left[i]^2/i-(total-left[i])^2/(n-i)\n    # Explicit approximate-tie tolerance; exact source JavaScript/Python\n    # contracts are authoritative for general arbitrarily close ties.\n    if(is.null(best)||loss<best$weightedSSE-1e-12*max(1,abs(loss),abs(best$weightedSSE)))best<-list(feature=j-1,threshold=(sx[i]+sx[i+1])/2,leftMean=left[i]/i,rightMean=(total-left[i])/(n-i),leftRows=i,rightRows=n-i,leftWeight=i,rightWeight=n-i,weightedSSE=loss)\n   }\n  }\n  if(is.null(best)||best$weightedSSE>=base-1e-12*max(1,abs(base))){model<-list(split=FALSE,mean=meanY,weightedSSE=base,trainingMSE=base/n);raw<-rep(meanY,nrow(r))}else{model<-c(list(split=TRUE),best,list(trainingMSE=best$weightedSSE/n,improvement=(base-best$weightedSSE)/n));raw<-ifelse(x[,model$feature+1]<=model$threshold,model$leftMean,model$rightMean)}\n }\n pred<-if(r$dataset[1]=='company')pmax(0,pmin(1,raw))else raw;list(meanX=mu,scales=scale,model=model,raw=raw,pred=pred)\n}\n\n# New standalone fixed-profile adapters; native and fit helpers copied by value.\nnum<-function(x){if(is.null(x)||length(x)==0||is.na(x)||x%in%c('','.'))return(NA_real_);if(is.character(x)&&grepl('/',x,fixed=TRUE)){v<-strsplit(x,'/',fixed=TRUE)[[1]];return(as.numeric(v[1])/as.numeric(v[2]))};as.numeric(x)}\nfixedRows<-function(aa){\n rr<-lapply(seq_along(aa),function(i){a<-aa[[i]];w<-num(if(is.null(a$weight))'1'else a$weight);if(is.na(w)||w<0)stop(if(!is.na(w)&&w<0)'negative-weight'else'missing-weight');list(id=if(is.null(a$id))as.character(i-1)else a$id,group=if(is.null(a$group))if(is.null(a$id))as.character(i-1)else a$id else a$group,cohort=if(is.null(a$cohort))'all'else a$cohort,role=if(is.null(a$role))'train'else a$role,w=w,y=num(a$y),x=vapply(a$x,num,0.0))})\n p<-if(length(rr))length(rr[[1]]$x)else 0;xx<-matrix(NA_real_,length(rr),p)\n if(p)for(i in seq_along(rr))xx[i,]<-rr[[i]]$x\n r<-data.frame(id=vapply(rr,`[[`,'','id'),group=vapply(rr,`[[`,'','group'),cohort=vapply(rr,`[[`,'','cohort'),role=vapply(rr,`[[`,'','role'),w=vapply(rr,`[[`,0.0,'w'),y=vapply(rr,`[[`,0.0,'y'));r$eligible<-!is.na(r$y)&rowSums(is.na(xx))==0&r$w>0;list(r=r,x=xx)\n}\nweightedRisk<-function(r,p,binary=FALSE,threshold=.5){\n ii<-which(r$w>0&!is.na(r$y)&!is.na(p)&!r$role%in%c('excluded','unused'));y<-r$y[ii];p<-p[ii];w<-r$w[ii];W<-sum(w);d<-list(rows=length(ii),mass=W,MSE=NA_real_,MAE=NA_real_,R2=NA_real_)\n if(W==0){if(binary)d<-c(d,setNames(rep(list(NA_real_),10),c('Brier','accuracy','positiveRecall','negativeRecall','precision','F1','balancedAccuracy','AUROC','positiveMass','negativeMass')));return(d)}\n mu<-sum(w*y)/W;sse<-sum(w*(p-y)^2);sst<-sum(w*(y-mu)^2);d<-c(d,list(meanY=mu,SSE=sse,SST=sst));d$MSE<-sse/W;d$MAE<-sum(w*abs(p-y))/W;d$R2<-if(sst>0)1-sse/sst else NA_real_\n if(binary){pos<-y==1;yes<-p>=threshold;TP<-sum(w[pos&yes]);FP<-sum(w[!pos&yes]);TN<-sum(w[!pos&!yes]);FN<-sum(w[pos&!yes]);rate<-function(a,b)if(b>0)a/b else NA_real_;tpr<-rate(TP,TP+FN);tnr<-rate(TN,TN+FP);auc<-NA_real_;P<-sum(w[pos]);N<-sum(w[!pos]);if(P>0&&N>0){wins<-sum(vapply(which(pos),function(i)sum(w[i]*w[!pos]*ifelse(p[i]>p[!pos],1,ifelse(p[i]==p[!pos],.5,0))),0.0));auc<-wins/(P*N)};d<-c(d,list(Brier=d$MSE,threshold=threshold,confusionMass=list(TP=TP,FP=FP,TN=TN,FN=FN),confusionRows=list(TP=sum(pos&yes),FP=sum(!pos&yes),TN=sum(!pos&!yes),FN=sum(pos&!yes)),positiveMass=P,negativeMass=N,accuracy=(TP+TN)/W,positiveRecall=tpr,negativeRecall=tnr,precision=rate(TP,TP+FP),F1=rate(2*TP,2*TP+FP+FN),balancedAccuracy=if(is.finite(tpr)&&is.finite(tnr))(tpr+tnr)/2 else NA_real_,AUROC=auc))};d\n}\nweightedPair<-function(r,A,B){\n ii<-which(r$w>0&!is.na(r$y)&!is.na(A)&!is.na(B)&!r$role%in%c('excluded','unused'));rr<-r[ii,,drop=FALSE];la<-(A[ii]-rr$y)^2;lb<-(B[ii]-rr$y)^2;d<-la-lb;W<-sum(rr$w);S<-sum(rr$w*d);mu<-if(W>0)S/W else NA_real_;ids<-unique(rr$group);groups<-lapply(ids,function(g){jj<-which(rr$group==g);wg<-sum(rr$w[jj]);sg<-sum(rr$w[jj]*d[jj]);list(group=g,rows=length(jj),mass=wg,sum=sg,leaveOut=if(W>wg)(S-sg)/(W-wg)else NA_real_)});leaves<-vapply(groups,`[[`,0.0,'leaveOut');G<-length(groups);proxy<-if(G>1&&all(is.finite(leaves)))(G-1)/G*sum((leaves-mean(leaves))^2) else NA_real_\n list(rows=length(ii),mass=W,groupCount=G,meanDifference=mu,minimumLeaveOut=if(any(is.finite(leaves)))min(leaves,na.rm=TRUE)else NA_real_,maximumLeaveOut=if(any(is.finite(leaves)))max(leaves,na.rm=TRUE)else NA_real_,varianceProxy=proxy,groups=groups,records=lapply(seq_along(ii),function(j)list(id=rr$id[j],group=rr$group[j],weight=rr$w[j],lossA=la[j],lossB=lb[j],difference=d[j])))\n}\nrunSelection<-function(r,candidates,criterion,required,binary=FALSE){\n out<-lapply(candidates,function(c){v<-r;t<-r;v$role[v$role!='validation']<-'excluded';t$role[t$role!='test']<-'excluded';val<-weightedRisk(v,c$pred,binary);test<-weightedRisk(t,c$pred,binary);co<-setNames(lapply(required,function(g){z<-v;z$role[z$cohort!=g]<-'excluded';weightedRisk(z,c$pred,binary)}),required);vv<-vapply(co,`[[`,0.0,'MSE');score<-if(criterion=='mean')val$MSE else if(length(vv)&&all(is.finite(vv)))max(vv)else NA_real_;list(id=c$id,criterion=score,validation=val,test=test,cohorts=co)})\n scores<-vapply(out,`[[`,0.0,'criterion');eligible<-which(is.finite(scores));k<-if(length(eligible))eligible[which.min(scores[eligible])]else NA_integer_;list(criterion=criterion,selected=if(!is.na(k))out[[k]]$id else NULL,selectedIndex=if(!is.na(k))k-1 else NA_real_,candidates=out)\n}\nfixedOperation<-function(api,a){\n if(api=='realdata'){\n  kind<-a$kind;r<-rows[[kind]];x<-X[[kind]];asgn<-assign_roles(r$group);r$dataset<-kind;r$splitRank<-asgn$rank;r$plannedRole<-asgn$planned;r$eligible<-!is.na(r$y)&rowSums(is.na(x))==0;r$role<-ifelse(r$eligible,r$plannedRole,'excluded');r$w<-1;binary<-kind=='company';leaf_min<<-5\n  defs<-data.frame(id=c('constant','ridge:1/100','ridge:1/10','ridge:1','one-split-stump'),method=c('constant','ridge','ridge','ridge','stump'),lambda=c(0,.01,.1,1,0));fits<-lapply(seq_len(5),function(i)fit_model(r,x,defs$method[i],defs$lambda[i]));candidates<-lapply(seq_len(5),function(i)list(id=defs$id[i],pred=fits[[i]]$pred));selection<-runSelection(r,candidates,a$criterion,unique(r$cohort),binary);k<-selection$selectedIndex+1;best<-fits[[k]];base<-fits[[1]];test<-r;test$role[test$role!='test']<-'excluded';paired<-weightedPair(test,best$pred,base$pred)\n  records<-lapply(seq_len(nrow(r)),function(i)list(id=r$id[i],sourceRow=r$sourceRow[i],originalID=r$originalID[i],group=r$group[i],cohort=r$cohort[i],plannedRole=r$plannedRole[i],role=r$role[i],eligible=r$eligible[i],y=r$y[i],baselinePrediction=base$pred[i],selectedPrediction=best$pred[i],selectedRawPrediction=best$raw[i],queryInvariant=TRUE))\n  return(list(kind=kind,nativeRows=nrow(r),eligibleRows=sum(r$eligible),selection=selection,models=lapply(seq_len(5),function(i)list(id=defs$id[i],train=as.list(r$id[r$role=='train']),mass=sum(r$role=='train'),meanX=fits[[i]]$meanX,scales=fits[[i]]$scales,model=fits[[i]]$model)),paired=paired,records=records))\n }\n f<-fixedRows(a$rows);r<-f$r;x<-f$x;binary<-identical(a$task,'binary')\n if(api=='split'){seed<<-a$seed;asgn<-assign_roles(r$group);return(list(state=asgn$state,groupCount=length(unique(r$group)),records=lapply(seq_len(nrow(r)),function(i)list(id=r$id[i],group=r$group[i],rank=asgn$rank[i],role=asgn$planned[i]))))}\n if(api=='fit'){\n  r$dataset<-if(binary)'company'else'fixed';leaf_min<<-if(is.null(a$minLeafRows))1 else a$minLeafRows;fit<-fit_model(r,x,a$method,if(is.null(a$lambda))0 else num(a$lambda));bad<-rowSums(is.na(x))>0;fit$raw[bad]<-NA_real_;fit$pred[bad]<-NA_real_;fit$defined<-TRUE;fit$train<-as.list(r$id[r$role=='train'&r$eligible]);fit$mass<-sum(r$w[r$role=='train'&r$eligible]);fit$invariant<-ifelse(bad,NA,TRUE);return(fit)\n }\n if(api=='evaluate'){p<-vapply(a$rows,function(v)num(v$prediction),0.0);threshold<-if(is.null(a$threshold)).5 else num(a$threshold);m<-weightedRisk(r,p,binary,threshold);records<-lapply(seq_len(nrow(r)),function(i){valid<-r$w[i]>0&&!is.na(r$y[i])&&!is.na(p[i])&&!r$role[i]%in%c('excluded','unused');list(id=r$id[i],weight=r$w[i],y=r$y[i],prediction=p[i],eligible=valid,loss=if(valid)(p[i]-r$y[i])^2 else NA_real_,correct=list(defined=valid&&binary,value=if(valid&&binary)(p[i]>=threshold)==r$y[i] else NULL))});return(list(metrics=m,records=records))}\n if(api=='select'){cs<-lapply(a$candidates,function(c)list(id=c$id,pred=vapply(c$predictions,num,0.0)));return(runSelection(r,cs,a$criterion,unlist(a$requiredCohorts),binary))}\n if(api=='paired')return(weightedPair(r,vapply(a$rows,function(v)num(v$predictionA),0.0),vapply(a$rows,function(v)num(v$predictionB),0.0)))\n stop('unknown-api')\n}\nreportValues<-function(api,z){\n ss<-list();pp<-list();add<-function(k,v,u='dimensionless')ss[[length(ss)+1]]<<-list(metric=k,value=if(is.null(v)||length(v)==0||is.na(v))NULL else unname(v),unit=u);series<-function(name,values){for(i in seq_along(values))pp[[length(pp)+1]]<<-list(series=name,index=i-1,x=i-1,y=if(is.null(values[[i]])||is.na(values[[i]]))NULL else unname(values[[i]]))}\n if(api=='split'){add('groups',z$groupCount,'groups');add('rows',length(z$records),'rows');add('finalState',z$state,'unsigned 32-bit state');series('planned role code',lapply(z$records,function(r)switch(r$role,test=0,validation=1,train=2)))}\n if(api=='fit'){add('defined',z$defined);add('trainingRows',length(z$train),'rows');add('trainingMass',z$mass,'analysis weight mass');add('modelRank',z$model$rank,'parameters');add('threshold',z$model$threshold,'constructed feature units');add('minimumObjective',z$model$minimumObjective,'constructed squared outcome units');series('prediction',as.list(z$pred));if(!is.null(z$model$theta))for(i in seq_along(z$model$theta))add(paste0('theta',i-1),z$model$theta[i],'constructed outcome units per standardized coordinate')}\n if(api=='evaluate'){for(k in c('rows','mass','MSE','MAE','R2','Brier','accuracy','positiveRecall','negativeRecall','precision','F1','balancedAccuracy','AUROC'))if(k%in%names(z$metrics))add(k,z$metrics[[k]],if(k=='rows')'rows'else if(k=='mass')'analysis weight mass'else if(k%in%c('MSE','Brier'))FIXED$unit else if(k=='MAE')'constructed outcome units'else'dimensionless');series('squared loss',lapply(z$records,`[[`,'loss'))}\n if(api=='select'){add('selectedIndex',z$selectedIndex,'zero-based candidate index');for(i in seq_along(z$candidates)){c<-z$candidates[[i]];add(paste0('criterion',i-1),c$criterion,FIXED$unit);add(paste0('testMSE',i-1),c$test$MSE,FIXED$unit)};series('validation criterion',lapply(z$candidates,`[[`,'criterion'));series('test MSE',lapply(z$candidates,function(c)c$test$MSE))}\n if(api=='paired'){for(k in c('rows','mass','groupCount','meanDifference','minimumLeaveOut','maximumLeaveOut','varianceProxy'))add(k,z[[k]],if(k=='rows')'rows'else if(k=='groupCount')'groups'else if(k=='mass')'analysis weight mass'else if(k=='varianceProxy')paste(FIXED$unit,'squared')else FIXED$unit);series('loss A minus loss B',lapply(z$records,`[[`,'difference'))}\n if(api=='realdata'){add('nativeRows',z$nativeRows,'native records');add('eligibleRows',z$eligibleRows,'complete records');add('selectedIndex',z$selection$selectedIndex,'zero-based candidate index');for(i in seq_along(z$selection$candidates)){c<-z$selection$candidates[[i]];add(paste0('validationMSE',i-1),c$validation$MSE,FIXED$unit);add(paste0('testMSE',i-1),c$test$MSE,FIXED$unit)};for(k in c('meanDifference','minimumLeaveOut','maximumLeaveOut','varianceProxy'))add(k,z$paired[[k]],if(k=='varianceProxy')paste(FIXED$unit,'squared')else FIXED$unit);best<-z$selection$candidates[[z$selection$selectedIndex+1]]$test;for(k in c('accuracy','positiveRecall','negativeRecall','precision','balancedAccuracy','AUROC'))if(k%in%names(best))add(k,best[[k]]);series('validation MSE',lapply(z$selection$candidates,function(c)c$validation$MSE));series('test MSE',lapply(z$selection$candidates,function(c)c$test$MSE))}\n list(summary=ss,points=pp)\n}\n\nescapeXML<-function(s){s<-gsub('&','&amp;',s,fixed=TRUE);s<-gsub('<','&lt;',s,fixed=TRUE);s<-gsub('>','&gt;',s,fixed=TRUE);gsub('\"','&quot;',s,fixed=TRUE)}\nsvgPlot<-function(pp,title){\n xx<-vapply(pp,function(p)as.numeric(p$x),numeric(1));yy<-vapply(pp,function(p)as.numeric(p$y),numeric(1));xmin<-if(length(xx))min(xx)else 0;xmax<-if(length(xx))max(xx)else 1;ymin<-min(c(0,yy));ymax<-max(c(0,yy));if(xmin==xmax){xmin<-xmin-.5;xmax<-xmax+.5};if(ymin==ymax){ymin<-ymin-.5;ymax<-ymax+.5};pad<-(ymax-ymin)*.08;ymin<-ymin-pad;ymax<-ymax+pad;X<-function(x)82+(as.numeric(x)-xmin)/(xmax-xmin)*608;Y<-function(y)354-(as.numeric(y)-ymin)/(ymax-ymin)*290\n out<-paste0('<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"720\" height=\"480\" viewBox=\"0 0 720 480\" role=\"img\" aria-label=\"',escapeXML(title),'\"><rect width=\"720\" height=\"480\" fill=\"white\"/><g font-family=\"Arial,sans-serif\" font-size=\"13\" fill=\"#18232f\"><text x=\"360\" y=\"25\" text-anchor=\"middle\">',escapeXML(title),'</text>')\n for(j in 0:4){y<-ymin+(ymax-ymin)*j/4;x<-xmin+(xmax-xmin)*j/4;out<-paste0(out,'<line x1=\"82\" y1=\"',Y(y),'\" x2=\"690\" y2=\"',Y(y),'\" stroke=\"#e2e8f0\"/><text x=\"73\" y=\"',Y(y)+4,'\" text-anchor=\"end\">',sprintf('%.3g',y),'</text><text x=\"',X(x),'\" y=\"380\" text-anchor=\"middle\">',sprintf('%.3g',x),'</text>')}\n ss<-unique(vapply(pp,`[[`,character(1),'series'));cols<-c('#0f766e','#c76622','#4f46e5','#b23857')\n for(j in seq_along(ss)){rr<-Filter(function(p)p$series==ss[j],pp);xy<-vapply(rr,function(p)sprintf('%.6f,%.6f',X(p$x),Y(p$y)),character(1));col<-cols[(j-1)%%4+1];for(p in rr)out<-paste0(out,'<circle cx=\"',sprintf('%.6f',X(p$x)),'\" cy=\"',sprintf('%.6f',Y(p$y)),'\" r=\"2.6\" fill=\"',col,'\"><title>',escapeXML(ss[j]),': ',escapeXML(p$y),'</title></circle>');out<-paste0(out,'<text x=\"',82+((j-1)%%2)*310,'\" y=\"',432+floor((j-1)/2)*23,'\" fill=\"',col,'\">',escapeXML(ss[j]),'</text>')}\n paste0(out,'<text x=\"360\" y=\"405\" text-anchor=\"middle\">Declared record / candidate index; fixed example</text></g></svg>')\n}\ntoJSON<-function(x){\n if(is.null(x))return('null');if(is.list(x)){v<-vapply(x,toJSON,character(1));if(!is.null(names(x)))paste0('{',paste(paste0(vapply(names(x),toJSON,character(1)),':',v),collapse=','),'}')else paste0('[',paste(v,collapse=','),']')}\n else if(length(x)!=1){if(!is.numeric(x)&&!is.null(names(x)))toJSON(as.list(x))else paste0('[',paste(vapply(as.list(x),toJSON,character(1)),collapse=','),']')}\n else if(is.na(x))'null'else if(is.logical(x))if(x)'true'else'false'else if(is.numeric(x))if(is.finite(x))sprintf('%.17g',x)else'null'else paste0('\"',gsub('\\n','\\\\n',gsub('\"','\\\\\"',gsub('\\\\','\\\\\\\\',x,fixed=TRUE),fixed=TRUE),fixed=TRUE),'\"')\n}\n\nFIXED<-list(`api`=\"fit\",`variant`=\"constant-common-frame\",`title`=\"A constant on the same complete training frame\",`input`=list(`method`=\"constant\",`rows`=list(list(`id`=\"a\",`x`=list(\"0\"),`y`=\"1\"),list(`id`=\"b\",`x`=list(\"2\"),`y`=\"5\"),list(`id`=\"incomplete\",`x`=list(NULL),`y`=\"99\"),list(`id`=\"query\",`x`=list(\"1\"),`y`=NULL,`role`=\"test\"))),`unit`=\"Constructed outcome units\",`titleI18n`=list(`ko`=\"상수도 같은 완전 훈련 집합\",`en`=\"A constant on the same complete training frame\"))\n\nargs<-commandArgs(trailingOnly=TRUE);out<-if(length(args))args[1]else stop('NEW output directory required');if(dir.exists(out))stop('Preserve previous output directory');dir.create(out,recursive=TRUE)\nz<-fixedOperation(FIXED$api,FIXED$input);rr<-reportValues(FIXED$api,z)\nwriteLines(toJSON(list(arithmetic='BaseR binary64 author counterpart; native group hashing exact within declared integer range, stump approximate tie tolerance1e-12; not an independent exact oracle',result=z)),file.path(out,'full.json'),useBytes=TRUE)\nsums<-do.call(rbind,lapply(rr$summary,function(row)data.frame(metric=row$metric,value=if(is.null(row$value))''else if(is.logical(row$value))as.character(as.integer(row$value))else format(row$value,digits=17,scientific=NA,trim=TRUE),unit=row$unit,defined=as.integer(!is.null(row$value)),stringsAsFactors=FALSE)))\npoints<-do.call(rbind,lapply(rr$points,function(p)data.frame(series=p$series,index=p$index,x=p$x,y=if(is.null(p$y))NA_real_ else p$y,defined=as.integer(!is.null(p$y)),stringsAsFactors=FALSE)))\nwrite.csv(sums,file.path(out,'summary.csv'),row.names=FALSE,na='');write.csv(points,file.path(out,'plot-points.csv'),row.names=FALSE,na='');writeLines(svgPlot(Filter(function(p)!is.null(p$y),rr$points),FIXED$title),file.path(out,'plot.svg'),useBytes=TRUE);cat(FIXED$api,'/',FIXED$variant,'\\n',sep='')\n",
        "returnCode": 0,
        "stdout": "fit/constant-common-frame\r\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 ",
        "diagnosticScope": "Public projection omits private absolute-path/traceback frames; actual exit and warnings/reason retained. Raw complete streams and commands in private execution proof.",
        "resultFolder": "ml22-code/runs/r-fit-constant-common-frame",
        "kind": null,
        "inputFiles": [
          {
            "file": "ml22-code/fit-constant-common-frame-input.json",
            "sha256": "6a036bcf3b604245298032b58ccb69ef76494e2c6fb404b2bb1b6469389de803",
            "scope": "Complete fixed literal input; program embeds the same values"
          }
        ],
        "files": [
          {
            "file": "ml22-code/runs/r-fit-constant-common-frame/full.json",
            "sha256": "8d143b30ce2e8559a64fb71ce4f1a407d84ab6b363eabdd42ff9d490961ee16a",
            "bytes": 389
          },
          {
            "file": "ml22-code/runs/r-fit-constant-common-frame/plot-points.csv",
            "sha256": "57b12024bcd2a5a875f528b5b5e9caf9b0fdd1eedca690c5cde3d5a89f069e8f",
            "bytes": 123
          },
          {
            "file": "ml22-code/runs/r-fit-constant-common-frame/plot.svg",
            "sha256": "158307e936f562a26b9a96c01b613ae4730e83bc63c2b386799126d40f1e7a74",
            "bytes": 1637
          },
          {
            "file": "ml22-code/runs/r-fit-constant-common-frame/summary.csv",
            "sha256": "1e8060efe59eaf0c803ecfc4832af4758093e6c99ce588f389a0eb62ba04a908",
            "bytes": 281
          }
        ],
        "summaryRows": [
          {
            "metric": "defined",
            "value": "1.0",
            "unit": "dimensionless",
            "defined": "true",
            "rawValue": "1",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "trainingRows",
            "value": "2.0",
            "unit": "rows",
            "defined": "true",
            "rawValue": "2",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "trainingMass",
            "value": "2.0",
            "unit": "analysis weight mass",
            "defined": "true",
            "rawValue": "2",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "modelRank",
            "value": "1.0",
            "unit": "parameters",
            "defined": "true",
            "rawValue": "1",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "threshold",
            "value": "",
            "unit": "constructed feature units",
            "defined": "false",
            "rawValue": "",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null
          },
          {
            "metric": "minimumObjective",
            "value": "",
            "unit": "constructed squared outcome units",
            "defined": "false",
            "rawValue": "",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null
          }
        ],
        "plotRows": [
          {
            "series": "prediction",
            "index": "0",
            "x": "0",
            "y": "3",
            "defined": true,
            "xExact": null,
            "yExact": null
          },
          {
            "series": "prediction",
            "index": "1",
            "x": "1",
            "y": "3",
            "defined": true,
            "xExact": null,
            "yExact": null
          },
          {
            "series": "prediction",
            "index": "2",
            "x": "2",
            "y": "",
            "defined": false,
            "xExact": null,
            "yExact": null
          },
          {
            "series": "prediction",
            "index": "3",
            "x": "3",
            "y": "3",
            "defined": true,
            "xExact": null,
            "yExact": null
          }
        ],
        "plotFile": "ml22-code/runs/r-fit-constant-common-frame/plot.svg",
        "fullResultFile": "ml22-code/runs/r-fit-constant-common-frame/full.json",
        "arithmeticScope": "Python exact rational versus base-R approximate floating algebra; copied author kernels, not independent oracle.",
        "plotScope": "Original scatter vectors plot every defined declared comparison point, with missing points omitted. Source profiles show candidate risks; all source records remain in the full result and source CSV files.",
        "reproductionScope": "Standalone literal program plus four native CSV files for factual source profiles. No answer/engine/checker imports."
      },
      "ridge-penalty-one": {
        "api": "fit",
        "variant": "ridge-penalty-one",
        "language": "r",
        "title": "Ridge penalty one under mean loss",
        "titleI18n": {
          "ko": "평균 손실의 릿지 벌점 1",
          "en": "Ridge penalty one under mean loss"
        },
        "input": {
          "method": "ridge",
          "lambda": "1",
          "rows": [
            {
              "id": "a",
              "x": [
                "0"
              ],
              "y": "1"
            },
            {
              "id": "b",
              "x": [
                "2"
              ],
              "y": "5"
            },
            {
              "id": "query",
              "x": [
                "1"
              ],
              "y": null,
              "role": "test"
            }
          ]
        },
        "expectedFailure": false,
        "codeFile": "ml22-code/fit-ridge-penalty-one.R",
        "codeSHA256": "0bb971c79fdeeef798a973944a893e557606fe8612a5bb10cd979567497280f5",
        "code": "# ML22 standalone; source/public functions copied by value, no source() dependency.\noptions(stringsAsFactors=FALSE,digits=17,warn=1)\nargs0<-commandArgs(trailingOnly=FALSE);script0<-sub('^--file=','',args0[grepl('^--file=',args0)][1]);source_dir<-file.path(dirname(normalizePath(script0)), 'data');seed<-20261104;leaf_min<-5\nnative_hash <- c(\"actual1599-red-wine-original12-fields.csv\"=\"77e9ac73115930d6c43983333a5a57940deefc493affeb17aca478c09c5f6e00\",\"actual4898-white-wine-original12-fields.csv\"=\"50d810bbb42b9cc3e87fa4c27a4c0f168e72da09dd812863425ca3873fec28ef\",\"actual3613-NLS-original52-fields.csv\"=\"6e1e1895558795435b65f8634252a7589865273a0e69adbd715fcfa04a3c11a1\",\"actual3150-churn-original14-fields.csv\"=\"1c0753e434226e769d1015c922121a7d8967df66014e057c4f7543e490f11764\")\nsha256<-getExportedValue('tools','sha256sum')\nread_native<-function(name){f<-file.path(source_dir,name);if(unname(sha256(f))!=native_hash[[name]])stop(paste('Native hash differs',name));read.csv(f,check.names=FALSE,colClasses='character',na.strings=NULL)}\ngcd_small<-function(a,b){while(b!=0){r<-a%%b;a<-b;b<-r};a}\ncanonical<-function(token){\n if(is.na(token)||token%in%c('','.'))return('null')\n if(!grepl('^[+-]?[0-9]+([.][0-9]*)?$',token))stop('Unsupported native fingerprint token')\n neg<-substr(token,1,1)=='-';s<-sub('^[+-]','',token);parts<-strsplit(s,'.',fixed=TRUE)[[1]];dec<-if(length(parts)==2)nchar(parts[2])else 0;n<-as.numeric(gsub('.','',s,fixed=TRUE));d<-10^dec\n # Every native fingerprint numerator/denominator must remain exactly integral\n # in binary64; reject rather than silently rounding a changed future source.\n if(!is.finite(n)||n>2^53||d>2^53)stop('Native canonical integer range exceeded')\n g<-gcd_small(n,d);n<-n/g;d<-d/g;if(neg)n<--n\n out<-sprintf('%.0f',n);if(d!=1)out<-paste0(out,'/',sprintf('%.0f',d));out\n}\nfp_cache<-new.env(hash=TRUE,parent=emptyenv());hash_file<-tempfile('ml22-hash-')\nfingerprint<-function(tag,values){a<-vapply(values,canonical,'');payload<-paste0('[',paste0('\"',a,'\"',collapse=','),']');key<-paste0(tag,':',payload);if(exists(key,fp_cache,inherits=FALSE))return(get(key,fp_cache,inherits=FALSE));con<-file(hash_file,'wb');writeBin(charToRaw(payload),con);close(con);value<-paste0(tag,':',unname(sha256(hash_file)));assign(key,value,fp_cache);value}\nassign_roles<-function(group){order<-sort(unique(group),method='radix');state<-seed;if(length(order)>1)for(j in seq.int(length(order),2)){state<-(1664525*state+1013904223)%%2^32;k<-state%%j+1;order[c(j,k)]<-order[c(k,j)]};rank<-match(group,order)-1;list(rank=rank,planned=c('test','validation','train','train')[rank%%4+1],state=state)}\n\nfit_model<-function(r,x,method,lambda){\n tr<-which(r$role=='train'&r$eligible);if(!length(tr))stop('No complete positive training rows');y<-r$y[tr];xx<-x[tr,,drop=FALSE];mu<-colMeans(xx);scale<-apply(xx,2,function(v)diff(range(v)));scale[scale==0]<-1;z<-cbind(1,sweep(sweep(x,2,mu,'-'),2,scale,'/'));meanY<-mean(y);model<-list();n<-length(tr)\n if(method=='constant'){model<-list(mean=meanY,parameterCount=1,rank=1,unique=TRUE);raw<-rep(meanY,nrow(r))}\n else if(method=='ridge'){zt<-z[tr,,drop=FALSE];pen<-diag(c(0,rep(lambda,ncol(x))));theta<-drop(solve(crossprod(zt)/n+pen,crossprod(zt,y)/n));raw<-drop(z%*%theta);objective<-mean((y-raw[tr])^2)/2+lambda*sum(theta[-1]^2)/2;model<-list(lambdaValue=lambda,theta=theta,rank=length(theta),unique=TRUE,minimumObjective=objective,parameterCount=length(theta))}\n else{base<-sum((y-meanY)^2);best<-NULL;total<-sum(y);total2<-sum(y*y)\n  for(j in seq_len(ncol(x))){ord<-order(xx[,j],seq_len(n));sx<-xx[ord,j];sy<-y[ord];left<-cumsum(sy)\n   if(n<2*leaf_min)next\n   for(i in seq.int(leaf_min,n-leaf_min)){if(sx[i]==sx[i+1])next;loss<-total2-left[i]^2/i-(total-left[i])^2/(n-i)\n    # Explicit approximate-tie tolerance; exact source JavaScript/Python\n    # contracts are authoritative for general arbitrarily close ties.\n    if(is.null(best)||loss<best$weightedSSE-1e-12*max(1,abs(loss),abs(best$weightedSSE)))best<-list(feature=j-1,threshold=(sx[i]+sx[i+1])/2,leftMean=left[i]/i,rightMean=(total-left[i])/(n-i),leftRows=i,rightRows=n-i,leftWeight=i,rightWeight=n-i,weightedSSE=loss)\n   }\n  }\n  if(is.null(best)||best$weightedSSE>=base-1e-12*max(1,abs(base))){model<-list(split=FALSE,mean=meanY,weightedSSE=base,trainingMSE=base/n);raw<-rep(meanY,nrow(r))}else{model<-c(list(split=TRUE),best,list(trainingMSE=best$weightedSSE/n,improvement=(base-best$weightedSSE)/n));raw<-ifelse(x[,model$feature+1]<=model$threshold,model$leftMean,model$rightMean)}\n }\n pred<-if(r$dataset[1]=='company')pmax(0,pmin(1,raw))else raw;list(meanX=mu,scales=scale,model=model,raw=raw,pred=pred)\n}\n\n# New standalone fixed-profile adapters; native and fit helpers copied by value.\nnum<-function(x){if(is.null(x)||length(x)==0||is.na(x)||x%in%c('','.'))return(NA_real_);if(is.character(x)&&grepl('/',x,fixed=TRUE)){v<-strsplit(x,'/',fixed=TRUE)[[1]];return(as.numeric(v[1])/as.numeric(v[2]))};as.numeric(x)}\nfixedRows<-function(aa){\n rr<-lapply(seq_along(aa),function(i){a<-aa[[i]];w<-num(if(is.null(a$weight))'1'else a$weight);if(is.na(w)||w<0)stop(if(!is.na(w)&&w<0)'negative-weight'else'missing-weight');list(id=if(is.null(a$id))as.character(i-1)else a$id,group=if(is.null(a$group))if(is.null(a$id))as.character(i-1)else a$id else a$group,cohort=if(is.null(a$cohort))'all'else a$cohort,role=if(is.null(a$role))'train'else a$role,w=w,y=num(a$y),x=vapply(a$x,num,0.0))})\n p<-if(length(rr))length(rr[[1]]$x)else 0;xx<-matrix(NA_real_,length(rr),p)\n if(p)for(i in seq_along(rr))xx[i,]<-rr[[i]]$x\n r<-data.frame(id=vapply(rr,`[[`,'','id'),group=vapply(rr,`[[`,'','group'),cohort=vapply(rr,`[[`,'','cohort'),role=vapply(rr,`[[`,'','role'),w=vapply(rr,`[[`,0.0,'w'),y=vapply(rr,`[[`,0.0,'y'));r$eligible<-!is.na(r$y)&rowSums(is.na(xx))==0&r$w>0;list(r=r,x=xx)\n}\nweightedRisk<-function(r,p,binary=FALSE,threshold=.5){\n ii<-which(r$w>0&!is.na(r$y)&!is.na(p)&!r$role%in%c('excluded','unused'));y<-r$y[ii];p<-p[ii];w<-r$w[ii];W<-sum(w);d<-list(rows=length(ii),mass=W,MSE=NA_real_,MAE=NA_real_,R2=NA_real_)\n if(W==0){if(binary)d<-c(d,setNames(rep(list(NA_real_),10),c('Brier','accuracy','positiveRecall','negativeRecall','precision','F1','balancedAccuracy','AUROC','positiveMass','negativeMass')));return(d)}\n mu<-sum(w*y)/W;sse<-sum(w*(p-y)^2);sst<-sum(w*(y-mu)^2);d<-c(d,list(meanY=mu,SSE=sse,SST=sst));d$MSE<-sse/W;d$MAE<-sum(w*abs(p-y))/W;d$R2<-if(sst>0)1-sse/sst else NA_real_\n if(binary){pos<-y==1;yes<-p>=threshold;TP<-sum(w[pos&yes]);FP<-sum(w[!pos&yes]);TN<-sum(w[!pos&!yes]);FN<-sum(w[pos&!yes]);rate<-function(a,b)if(b>0)a/b else NA_real_;tpr<-rate(TP,TP+FN);tnr<-rate(TN,TN+FP);auc<-NA_real_;P<-sum(w[pos]);N<-sum(w[!pos]);if(P>0&&N>0){wins<-sum(vapply(which(pos),function(i)sum(w[i]*w[!pos]*ifelse(p[i]>p[!pos],1,ifelse(p[i]==p[!pos],.5,0))),0.0));auc<-wins/(P*N)};d<-c(d,list(Brier=d$MSE,threshold=threshold,confusionMass=list(TP=TP,FP=FP,TN=TN,FN=FN),confusionRows=list(TP=sum(pos&yes),FP=sum(!pos&yes),TN=sum(!pos&!yes),FN=sum(pos&!yes)),positiveMass=P,negativeMass=N,accuracy=(TP+TN)/W,positiveRecall=tpr,negativeRecall=tnr,precision=rate(TP,TP+FP),F1=rate(2*TP,2*TP+FP+FN),balancedAccuracy=if(is.finite(tpr)&&is.finite(tnr))(tpr+tnr)/2 else NA_real_,AUROC=auc))};d\n}\nweightedPair<-function(r,A,B){\n ii<-which(r$w>0&!is.na(r$y)&!is.na(A)&!is.na(B)&!r$role%in%c('excluded','unused'));rr<-r[ii,,drop=FALSE];la<-(A[ii]-rr$y)^2;lb<-(B[ii]-rr$y)^2;d<-la-lb;W<-sum(rr$w);S<-sum(rr$w*d);mu<-if(W>0)S/W else NA_real_;ids<-unique(rr$group);groups<-lapply(ids,function(g){jj<-which(rr$group==g);wg<-sum(rr$w[jj]);sg<-sum(rr$w[jj]*d[jj]);list(group=g,rows=length(jj),mass=wg,sum=sg,leaveOut=if(W>wg)(S-sg)/(W-wg)else NA_real_)});leaves<-vapply(groups,`[[`,0.0,'leaveOut');G<-length(groups);proxy<-if(G>1&&all(is.finite(leaves)))(G-1)/G*sum((leaves-mean(leaves))^2) else NA_real_\n list(rows=length(ii),mass=W,groupCount=G,meanDifference=mu,minimumLeaveOut=if(any(is.finite(leaves)))min(leaves,na.rm=TRUE)else NA_real_,maximumLeaveOut=if(any(is.finite(leaves)))max(leaves,na.rm=TRUE)else NA_real_,varianceProxy=proxy,groups=groups,records=lapply(seq_along(ii),function(j)list(id=rr$id[j],group=rr$group[j],weight=rr$w[j],lossA=la[j],lossB=lb[j],difference=d[j])))\n}\nrunSelection<-function(r,candidates,criterion,required,binary=FALSE){\n out<-lapply(candidates,function(c){v<-r;t<-r;v$role[v$role!='validation']<-'excluded';t$role[t$role!='test']<-'excluded';val<-weightedRisk(v,c$pred,binary);test<-weightedRisk(t,c$pred,binary);co<-setNames(lapply(required,function(g){z<-v;z$role[z$cohort!=g]<-'excluded';weightedRisk(z,c$pred,binary)}),required);vv<-vapply(co,`[[`,0.0,'MSE');score<-if(criterion=='mean')val$MSE else if(length(vv)&&all(is.finite(vv)))max(vv)else NA_real_;list(id=c$id,criterion=score,validation=val,test=test,cohorts=co)})\n scores<-vapply(out,`[[`,0.0,'criterion');eligible<-which(is.finite(scores));k<-if(length(eligible))eligible[which.min(scores[eligible])]else NA_integer_;list(criterion=criterion,selected=if(!is.na(k))out[[k]]$id else NULL,selectedIndex=if(!is.na(k))k-1 else NA_real_,candidates=out)\n}\nfixedOperation<-function(api,a){\n if(api=='realdata'){\n  kind<-a$kind;r<-rows[[kind]];x<-X[[kind]];asgn<-assign_roles(r$group);r$dataset<-kind;r$splitRank<-asgn$rank;r$plannedRole<-asgn$planned;r$eligible<-!is.na(r$y)&rowSums(is.na(x))==0;r$role<-ifelse(r$eligible,r$plannedRole,'excluded');r$w<-1;binary<-kind=='company';leaf_min<<-5\n  defs<-data.frame(id=c('constant','ridge:1/100','ridge:1/10','ridge:1','one-split-stump'),method=c('constant','ridge','ridge','ridge','stump'),lambda=c(0,.01,.1,1,0));fits<-lapply(seq_len(5),function(i)fit_model(r,x,defs$method[i],defs$lambda[i]));candidates<-lapply(seq_len(5),function(i)list(id=defs$id[i],pred=fits[[i]]$pred));selection<-runSelection(r,candidates,a$criterion,unique(r$cohort),binary);k<-selection$selectedIndex+1;best<-fits[[k]];base<-fits[[1]];test<-r;test$role[test$role!='test']<-'excluded';paired<-weightedPair(test,best$pred,base$pred)\n  records<-lapply(seq_len(nrow(r)),function(i)list(id=r$id[i],sourceRow=r$sourceRow[i],originalID=r$originalID[i],group=r$group[i],cohort=r$cohort[i],plannedRole=r$plannedRole[i],role=r$role[i],eligible=r$eligible[i],y=r$y[i],baselinePrediction=base$pred[i],selectedPrediction=best$pred[i],selectedRawPrediction=best$raw[i],queryInvariant=TRUE))\n  return(list(kind=kind,nativeRows=nrow(r),eligibleRows=sum(r$eligible),selection=selection,models=lapply(seq_len(5),function(i)list(id=defs$id[i],train=as.list(r$id[r$role=='train']),mass=sum(r$role=='train'),meanX=fits[[i]]$meanX,scales=fits[[i]]$scales,model=fits[[i]]$model)),paired=paired,records=records))\n }\n f<-fixedRows(a$rows);r<-f$r;x<-f$x;binary<-identical(a$task,'binary')\n if(api=='split'){seed<<-a$seed;asgn<-assign_roles(r$group);return(list(state=asgn$state,groupCount=length(unique(r$group)),records=lapply(seq_len(nrow(r)),function(i)list(id=r$id[i],group=r$group[i],rank=asgn$rank[i],role=asgn$planned[i]))))}\n if(api=='fit'){\n  r$dataset<-if(binary)'company'else'fixed';leaf_min<<-if(is.null(a$minLeafRows))1 else a$minLeafRows;fit<-fit_model(r,x,a$method,if(is.null(a$lambda))0 else num(a$lambda));bad<-rowSums(is.na(x))>0;fit$raw[bad]<-NA_real_;fit$pred[bad]<-NA_real_;fit$defined<-TRUE;fit$train<-as.list(r$id[r$role=='train'&r$eligible]);fit$mass<-sum(r$w[r$role=='train'&r$eligible]);fit$invariant<-ifelse(bad,NA,TRUE);return(fit)\n }\n if(api=='evaluate'){p<-vapply(a$rows,function(v)num(v$prediction),0.0);threshold<-if(is.null(a$threshold)).5 else num(a$threshold);m<-weightedRisk(r,p,binary,threshold);records<-lapply(seq_len(nrow(r)),function(i){valid<-r$w[i]>0&&!is.na(r$y[i])&&!is.na(p[i])&&!r$role[i]%in%c('excluded','unused');list(id=r$id[i],weight=r$w[i],y=r$y[i],prediction=p[i],eligible=valid,loss=if(valid)(p[i]-r$y[i])^2 else NA_real_,correct=list(defined=valid&&binary,value=if(valid&&binary)(p[i]>=threshold)==r$y[i] else NULL))});return(list(metrics=m,records=records))}\n if(api=='select'){cs<-lapply(a$candidates,function(c)list(id=c$id,pred=vapply(c$predictions,num,0.0)));return(runSelection(r,cs,a$criterion,unlist(a$requiredCohorts),binary))}\n if(api=='paired')return(weightedPair(r,vapply(a$rows,function(v)num(v$predictionA),0.0),vapply(a$rows,function(v)num(v$predictionB),0.0)))\n stop('unknown-api')\n}\nreportValues<-function(api,z){\n ss<-list();pp<-list();add<-function(k,v,u='dimensionless')ss[[length(ss)+1]]<<-list(metric=k,value=if(is.null(v)||length(v)==0||is.na(v))NULL else unname(v),unit=u);series<-function(name,values){for(i in seq_along(values))pp[[length(pp)+1]]<<-list(series=name,index=i-1,x=i-1,y=if(is.null(values[[i]])||is.na(values[[i]]))NULL else unname(values[[i]]))}\n if(api=='split'){add('groups',z$groupCount,'groups');add('rows',length(z$records),'rows');add('finalState',z$state,'unsigned 32-bit state');series('planned role code',lapply(z$records,function(r)switch(r$role,test=0,validation=1,train=2)))}\n if(api=='fit'){add('defined',z$defined);add('trainingRows',length(z$train),'rows');add('trainingMass',z$mass,'analysis weight mass');add('modelRank',z$model$rank,'parameters');add('threshold',z$model$threshold,'constructed feature units');add('minimumObjective',z$model$minimumObjective,'constructed squared outcome units');series('prediction',as.list(z$pred));if(!is.null(z$model$theta))for(i in seq_along(z$model$theta))add(paste0('theta',i-1),z$model$theta[i],'constructed outcome units per standardized coordinate')}\n if(api=='evaluate'){for(k in c('rows','mass','MSE','MAE','R2','Brier','accuracy','positiveRecall','negativeRecall','precision','F1','balancedAccuracy','AUROC'))if(k%in%names(z$metrics))add(k,z$metrics[[k]],if(k=='rows')'rows'else if(k=='mass')'analysis weight mass'else if(k%in%c('MSE','Brier'))FIXED$unit else if(k=='MAE')'constructed outcome units'else'dimensionless');series('squared loss',lapply(z$records,`[[`,'loss'))}\n if(api=='select'){add('selectedIndex',z$selectedIndex,'zero-based candidate index');for(i in seq_along(z$candidates)){c<-z$candidates[[i]];add(paste0('criterion',i-1),c$criterion,FIXED$unit);add(paste0('testMSE',i-1),c$test$MSE,FIXED$unit)};series('validation criterion',lapply(z$candidates,`[[`,'criterion'));series('test MSE',lapply(z$candidates,function(c)c$test$MSE))}\n if(api=='paired'){for(k in c('rows','mass','groupCount','meanDifference','minimumLeaveOut','maximumLeaveOut','varianceProxy'))add(k,z[[k]],if(k=='rows')'rows'else if(k=='groupCount')'groups'else if(k=='mass')'analysis weight mass'else if(k=='varianceProxy')paste(FIXED$unit,'squared')else FIXED$unit);series('loss A minus loss B',lapply(z$records,`[[`,'difference'))}\n if(api=='realdata'){add('nativeRows',z$nativeRows,'native records');add('eligibleRows',z$eligibleRows,'complete records');add('selectedIndex',z$selection$selectedIndex,'zero-based candidate index');for(i in seq_along(z$selection$candidates)){c<-z$selection$candidates[[i]];add(paste0('validationMSE',i-1),c$validation$MSE,FIXED$unit);add(paste0('testMSE',i-1),c$test$MSE,FIXED$unit)};for(k in c('meanDifference','minimumLeaveOut','maximumLeaveOut','varianceProxy'))add(k,z$paired[[k]],if(k=='varianceProxy')paste(FIXED$unit,'squared')else FIXED$unit);best<-z$selection$candidates[[z$selection$selectedIndex+1]]$test;for(k in c('accuracy','positiveRecall','negativeRecall','precision','balancedAccuracy','AUROC'))if(k%in%names(best))add(k,best[[k]]);series('validation MSE',lapply(z$selection$candidates,function(c)c$validation$MSE));series('test MSE',lapply(z$selection$candidates,function(c)c$test$MSE))}\n list(summary=ss,points=pp)\n}\n\nescapeXML<-function(s){s<-gsub('&','&amp;',s,fixed=TRUE);s<-gsub('<','&lt;',s,fixed=TRUE);s<-gsub('>','&gt;',s,fixed=TRUE);gsub('\"','&quot;',s,fixed=TRUE)}\nsvgPlot<-function(pp,title){\n xx<-vapply(pp,function(p)as.numeric(p$x),numeric(1));yy<-vapply(pp,function(p)as.numeric(p$y),numeric(1));xmin<-if(length(xx))min(xx)else 0;xmax<-if(length(xx))max(xx)else 1;ymin<-min(c(0,yy));ymax<-max(c(0,yy));if(xmin==xmax){xmin<-xmin-.5;xmax<-xmax+.5};if(ymin==ymax){ymin<-ymin-.5;ymax<-ymax+.5};pad<-(ymax-ymin)*.08;ymin<-ymin-pad;ymax<-ymax+pad;X<-function(x)82+(as.numeric(x)-xmin)/(xmax-xmin)*608;Y<-function(y)354-(as.numeric(y)-ymin)/(ymax-ymin)*290\n out<-paste0('<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"720\" height=\"480\" viewBox=\"0 0 720 480\" role=\"img\" aria-label=\"',escapeXML(title),'\"><rect width=\"720\" height=\"480\" fill=\"white\"/><g font-family=\"Arial,sans-serif\" font-size=\"13\" fill=\"#18232f\"><text x=\"360\" y=\"25\" text-anchor=\"middle\">',escapeXML(title),'</text>')\n for(j in 0:4){y<-ymin+(ymax-ymin)*j/4;x<-xmin+(xmax-xmin)*j/4;out<-paste0(out,'<line x1=\"82\" y1=\"',Y(y),'\" x2=\"690\" y2=\"',Y(y),'\" stroke=\"#e2e8f0\"/><text x=\"73\" y=\"',Y(y)+4,'\" text-anchor=\"end\">',sprintf('%.3g',y),'</text><text x=\"',X(x),'\" y=\"380\" text-anchor=\"middle\">',sprintf('%.3g',x),'</text>')}\n ss<-unique(vapply(pp,`[[`,character(1),'series'));cols<-c('#0f766e','#c76622','#4f46e5','#b23857')\n for(j in seq_along(ss)){rr<-Filter(function(p)p$series==ss[j],pp);xy<-vapply(rr,function(p)sprintf('%.6f,%.6f',X(p$x),Y(p$y)),character(1));col<-cols[(j-1)%%4+1];for(p in rr)out<-paste0(out,'<circle cx=\"',sprintf('%.6f',X(p$x)),'\" cy=\"',sprintf('%.6f',Y(p$y)),'\" r=\"2.6\" fill=\"',col,'\"><title>',escapeXML(ss[j]),': ',escapeXML(p$y),'</title></circle>');out<-paste0(out,'<text x=\"',82+((j-1)%%2)*310,'\" y=\"',432+floor((j-1)/2)*23,'\" fill=\"',col,'\">',escapeXML(ss[j]),'</text>')}\n paste0(out,'<text x=\"360\" y=\"405\" text-anchor=\"middle\">Declared record / candidate index; fixed example</text></g></svg>')\n}\ntoJSON<-function(x){\n if(is.null(x))return('null');if(is.list(x)){v<-vapply(x,toJSON,character(1));if(!is.null(names(x)))paste0('{',paste(paste0(vapply(names(x),toJSON,character(1)),':',v),collapse=','),'}')else paste0('[',paste(v,collapse=','),']')}\n else if(length(x)!=1){if(!is.numeric(x)&&!is.null(names(x)))toJSON(as.list(x))else paste0('[',paste(vapply(as.list(x),toJSON,character(1)),collapse=','),']')}\n else if(is.na(x))'null'else if(is.logical(x))if(x)'true'else'false'else if(is.numeric(x))if(is.finite(x))sprintf('%.17g',x)else'null'else paste0('\"',gsub('\\n','\\\\n',gsub('\"','\\\\\"',gsub('\\\\','\\\\\\\\',x,fixed=TRUE),fixed=TRUE),fixed=TRUE),'\"')\n}\n\nFIXED<-list(`api`=\"fit\",`variant`=\"ridge-penalty-one\",`title`=\"Ridge penalty one under mean loss\",`input`=list(`method`=\"ridge\",`lambda`=\"1\",`rows`=list(list(`id`=\"a\",`x`=list(\"0\"),`y`=\"1\"),list(`id`=\"b\",`x`=list(\"2\"),`y`=\"5\"),list(`id`=\"query\",`x`=list(\"1\"),`y`=NULL,`role`=\"test\"))),`unit`=\"Constructed outcome units\",`titleI18n`=list(`ko`=\"평균 손실의 릿지 벌점 1\",`en`=\"Ridge penalty one under mean loss\"))\n\nargs<-commandArgs(trailingOnly=TRUE);out<-if(length(args))args[1]else stop('NEW output directory required');if(dir.exists(out))stop('Preserve previous output directory');dir.create(out,recursive=TRUE)\nz<-fixedOperation(FIXED$api,FIXED$input);rr<-reportValues(FIXED$api,z)\nwriteLines(toJSON(list(arithmetic='BaseR binary64 author counterpart; native group hashing exact within declared integer range, stump approximate tie tolerance1e-12; not an independent exact oracle',result=z)),file.path(out,'full.json'),useBytes=TRUE)\nsums<-do.call(rbind,lapply(rr$summary,function(row)data.frame(metric=row$metric,value=if(is.null(row$value))''else if(is.logical(row$value))as.character(as.integer(row$value))else format(row$value,digits=17,scientific=NA,trim=TRUE),unit=row$unit,defined=as.integer(!is.null(row$value)),stringsAsFactors=FALSE)))\npoints<-do.call(rbind,lapply(rr$points,function(p)data.frame(series=p$series,index=p$index,x=p$x,y=if(is.null(p$y))NA_real_ else p$y,defined=as.integer(!is.null(p$y)),stringsAsFactors=FALSE)))\nwrite.csv(sums,file.path(out,'summary.csv'),row.names=FALSE,na='');write.csv(points,file.path(out,'plot-points.csv'),row.names=FALSE,na='');writeLines(svgPlot(Filter(function(p)!is.null(p$y),rr$points),FIXED$title),file.path(out,'plot.svg'),useBytes=TRUE);cat(FIXED$api,'/',FIXED$variant,'\\n',sep='')\n",
        "returnCode": 0,
        "stdout": "fit/ridge-penalty-one\r\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 ",
        "diagnosticScope": "Public projection omits private absolute-path/traceback frames; actual exit and warnings/reason retained. Raw complete streams and commands in private execution proof.",
        "resultFolder": "ml22-code/runs/r-fit-ridge-penalty-one",
        "kind": null,
        "inputFiles": [
          {
            "file": "ml22-code/fit-ridge-penalty-one-input.json",
            "sha256": "7db29be566e21abc7453d5683d9f463b40b3d873a52faf6c346379586a5263ed",
            "scope": "Complete fixed literal input; program embeds the same values"
          }
        ],
        "files": [
          {
            "file": "ml22-code/runs/r-fit-ridge-penalty-one/full.json",
            "sha256": "cedd27ec2fea24e0dce858d9d30bcbea386c0875038fb0d2f42de152a97f75f4",
            "bytes": 519
          },
          {
            "file": "ml22-code/runs/r-fit-ridge-penalty-one/plot-points.csv",
            "sha256": "9ff0666f23496ed1244217841287996e0a55a99ac3cd3d4ea691b5b442f63e8e",
            "bytes": 106
          },
          {
            "file": "ml22-code/runs/r-fit-ridge-penalty-one/plot.svg",
            "sha256": "50e9843f10401eda5e55dc31f5ca05db3f75c9cb73bc419ef76e6143fe69c7ac",
            "bytes": 1615
          },
          {
            "file": "ml22-code/runs/r-fit-ridge-penalty-one/summary.csv",
            "sha256": "f44b3ef5853f6e86a2784a3d93f2b9ca2331e62ab537f2aef4f64264bcdc83f7",
            "bytes": 461
          }
        ],
        "summaryRows": [
          {
            "metric": "defined",
            "value": "1.0",
            "unit": "dimensionless",
            "defined": "true",
            "rawValue": "1",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "trainingRows",
            "value": "2.0",
            "unit": "rows",
            "defined": "true",
            "rawValue": "2",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "trainingMass",
            "value": "2.0",
            "unit": "analysis weight mass",
            "defined": "true",
            "rawValue": "2",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "modelRank",
            "value": "2.0",
            "unit": "parameters",
            "defined": "true",
            "rawValue": "2",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "threshold",
            "value": "",
            "unit": "constructed feature units",
            "defined": "false",
            "rawValue": "",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null
          },
          {
            "metric": "minimumObjective",
            "value": "1.6000000000000003",
            "unit": "constructed squared outcome units",
            "defined": "true",
            "rawValue": "1.6000000000000003",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "theta0",
            "value": "3.0",
            "unit": "constructed outcome units per standardized coordinate",
            "defined": "true",
            "rawValue": "3",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "theta1",
            "value": "0.8",
            "unit": "constructed outcome units per standardized coordinate",
            "defined": "true",
            "rawValue": "0.80000000000000004",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          }
        ],
        "plotRows": [
          {
            "series": "prediction",
            "index": "0",
            "x": "0",
            "y": "2.6",
            "defined": true,
            "xExact": null,
            "yExact": null
          },
          {
            "series": "prediction",
            "index": "1",
            "x": "1",
            "y": "3.4",
            "defined": true,
            "xExact": null,
            "yExact": null
          },
          {
            "series": "prediction",
            "index": "2",
            "x": "2",
            "y": "3",
            "defined": true,
            "xExact": null,
            "yExact": null
          }
        ],
        "plotFile": "ml22-code/runs/r-fit-ridge-penalty-one/plot.svg",
        "fullResultFile": "ml22-code/runs/r-fit-ridge-penalty-one/full.json",
        "arithmeticScope": "Python exact rational versus base-R approximate floating algebra; copied author kernels, not independent oracle.",
        "plotScope": "Original scatter vectors plot every defined declared comparison point, with missing points omitted. Source profiles show candidate risks; all source records remain in the full result and source CSV files.",
        "reproductionScope": "Standalone literal program plus four native CSV files for factual source profiles. No answer/engine/checker imports."
      },
      "stump-exact-tie": {
        "api": "fit",
        "variant": "stump-exact-tie",
        "language": "r",
        "title": "An exact one-split tree tie",
        "titleI18n": {
          "ko": "한 단계 나무의 정확한 동률",
          "en": "An exact one-split tree tie"
        },
        "input": {
          "method": "stump",
          "minLeafRows": 1,
          "rows": [
            {
              "x": [
                "0",
                "0"
              ],
              "y": "0"
            },
            {
              "x": [
                "1",
                "1"
              ],
              "y": "1"
            },
            {
              "x": [
                "2",
                "2"
              ],
              "y": "0"
            }
          ]
        },
        "expectedFailure": false,
        "codeFile": "ml22-code/fit-stump-exact-tie.R",
        "codeSHA256": "215b87229ac14882f5177546d3dc8246f19d8de2d24f3c5f57ca816591eef9a5",
        "code": "# ML22 standalone; source/public functions copied by value, no source() dependency.\noptions(stringsAsFactors=FALSE,digits=17,warn=1)\nargs0<-commandArgs(trailingOnly=FALSE);script0<-sub('^--file=','',args0[grepl('^--file=',args0)][1]);source_dir<-file.path(dirname(normalizePath(script0)), 'data');seed<-20261104;leaf_min<-5\nnative_hash <- c(\"actual1599-red-wine-original12-fields.csv\"=\"77e9ac73115930d6c43983333a5a57940deefc493affeb17aca478c09c5f6e00\",\"actual4898-white-wine-original12-fields.csv\"=\"50d810bbb42b9cc3e87fa4c27a4c0f168e72da09dd812863425ca3873fec28ef\",\"actual3613-NLS-original52-fields.csv\"=\"6e1e1895558795435b65f8634252a7589865273a0e69adbd715fcfa04a3c11a1\",\"actual3150-churn-original14-fields.csv\"=\"1c0753e434226e769d1015c922121a7d8967df66014e057c4f7543e490f11764\")\nsha256<-getExportedValue('tools','sha256sum')\nread_native<-function(name){f<-file.path(source_dir,name);if(unname(sha256(f))!=native_hash[[name]])stop(paste('Native hash differs',name));read.csv(f,check.names=FALSE,colClasses='character',na.strings=NULL)}\ngcd_small<-function(a,b){while(b!=0){r<-a%%b;a<-b;b<-r};a}\ncanonical<-function(token){\n if(is.na(token)||token%in%c('','.'))return('null')\n if(!grepl('^[+-]?[0-9]+([.][0-9]*)?$',token))stop('Unsupported native fingerprint token')\n neg<-substr(token,1,1)=='-';s<-sub('^[+-]','',token);parts<-strsplit(s,'.',fixed=TRUE)[[1]];dec<-if(length(parts)==2)nchar(parts[2])else 0;n<-as.numeric(gsub('.','',s,fixed=TRUE));d<-10^dec\n # Every native fingerprint numerator/denominator must remain exactly integral\n # in binary64; reject rather than silently rounding a changed future source.\n if(!is.finite(n)||n>2^53||d>2^53)stop('Native canonical integer range exceeded')\n g<-gcd_small(n,d);n<-n/g;d<-d/g;if(neg)n<--n\n out<-sprintf('%.0f',n);if(d!=1)out<-paste0(out,'/',sprintf('%.0f',d));out\n}\nfp_cache<-new.env(hash=TRUE,parent=emptyenv());hash_file<-tempfile('ml22-hash-')\nfingerprint<-function(tag,values){a<-vapply(values,canonical,'');payload<-paste0('[',paste0('\"',a,'\"',collapse=','),']');key<-paste0(tag,':',payload);if(exists(key,fp_cache,inherits=FALSE))return(get(key,fp_cache,inherits=FALSE));con<-file(hash_file,'wb');writeBin(charToRaw(payload),con);close(con);value<-paste0(tag,':',unname(sha256(hash_file)));assign(key,value,fp_cache);value}\nassign_roles<-function(group){order<-sort(unique(group),method='radix');state<-seed;if(length(order)>1)for(j in seq.int(length(order),2)){state<-(1664525*state+1013904223)%%2^32;k<-state%%j+1;order[c(j,k)]<-order[c(k,j)]};rank<-match(group,order)-1;list(rank=rank,planned=c('test','validation','train','train')[rank%%4+1],state=state)}\n\nfit_model<-function(r,x,method,lambda){\n tr<-which(r$role=='train'&r$eligible);if(!length(tr))stop('No complete positive training rows');y<-r$y[tr];xx<-x[tr,,drop=FALSE];mu<-colMeans(xx);scale<-apply(xx,2,function(v)diff(range(v)));scale[scale==0]<-1;z<-cbind(1,sweep(sweep(x,2,mu,'-'),2,scale,'/'));meanY<-mean(y);model<-list();n<-length(tr)\n if(method=='constant'){model<-list(mean=meanY,parameterCount=1,rank=1,unique=TRUE);raw<-rep(meanY,nrow(r))}\n else if(method=='ridge'){zt<-z[tr,,drop=FALSE];pen<-diag(c(0,rep(lambda,ncol(x))));theta<-drop(solve(crossprod(zt)/n+pen,crossprod(zt,y)/n));raw<-drop(z%*%theta);objective<-mean((y-raw[tr])^2)/2+lambda*sum(theta[-1]^2)/2;model<-list(lambdaValue=lambda,theta=theta,rank=length(theta),unique=TRUE,minimumObjective=objective,parameterCount=length(theta))}\n else{base<-sum((y-meanY)^2);best<-NULL;total<-sum(y);total2<-sum(y*y)\n  for(j in seq_len(ncol(x))){ord<-order(xx[,j],seq_len(n));sx<-xx[ord,j];sy<-y[ord];left<-cumsum(sy)\n   if(n<2*leaf_min)next\n   for(i in seq.int(leaf_min,n-leaf_min)){if(sx[i]==sx[i+1])next;loss<-total2-left[i]^2/i-(total-left[i])^2/(n-i)\n    # Explicit approximate-tie tolerance; exact source JavaScript/Python\n    # contracts are authoritative for general arbitrarily close ties.\n    if(is.null(best)||loss<best$weightedSSE-1e-12*max(1,abs(loss),abs(best$weightedSSE)))best<-list(feature=j-1,threshold=(sx[i]+sx[i+1])/2,leftMean=left[i]/i,rightMean=(total-left[i])/(n-i),leftRows=i,rightRows=n-i,leftWeight=i,rightWeight=n-i,weightedSSE=loss)\n   }\n  }\n  if(is.null(best)||best$weightedSSE>=base-1e-12*max(1,abs(base))){model<-list(split=FALSE,mean=meanY,weightedSSE=base,trainingMSE=base/n);raw<-rep(meanY,nrow(r))}else{model<-c(list(split=TRUE),best,list(trainingMSE=best$weightedSSE/n,improvement=(base-best$weightedSSE)/n));raw<-ifelse(x[,model$feature+1]<=model$threshold,model$leftMean,model$rightMean)}\n }\n pred<-if(r$dataset[1]=='company')pmax(0,pmin(1,raw))else raw;list(meanX=mu,scales=scale,model=model,raw=raw,pred=pred)\n}\n\n# New standalone fixed-profile adapters; native and fit helpers copied by value.\nnum<-function(x){if(is.null(x)||length(x)==0||is.na(x)||x%in%c('','.'))return(NA_real_);if(is.character(x)&&grepl('/',x,fixed=TRUE)){v<-strsplit(x,'/',fixed=TRUE)[[1]];return(as.numeric(v[1])/as.numeric(v[2]))};as.numeric(x)}\nfixedRows<-function(aa){\n rr<-lapply(seq_along(aa),function(i){a<-aa[[i]];w<-num(if(is.null(a$weight))'1'else a$weight);if(is.na(w)||w<0)stop(if(!is.na(w)&&w<0)'negative-weight'else'missing-weight');list(id=if(is.null(a$id))as.character(i-1)else a$id,group=if(is.null(a$group))if(is.null(a$id))as.character(i-1)else a$id else a$group,cohort=if(is.null(a$cohort))'all'else a$cohort,role=if(is.null(a$role))'train'else a$role,w=w,y=num(a$y),x=vapply(a$x,num,0.0))})\n p<-if(length(rr))length(rr[[1]]$x)else 0;xx<-matrix(NA_real_,length(rr),p)\n if(p)for(i in seq_along(rr))xx[i,]<-rr[[i]]$x\n r<-data.frame(id=vapply(rr,`[[`,'','id'),group=vapply(rr,`[[`,'','group'),cohort=vapply(rr,`[[`,'','cohort'),role=vapply(rr,`[[`,'','role'),w=vapply(rr,`[[`,0.0,'w'),y=vapply(rr,`[[`,0.0,'y'));r$eligible<-!is.na(r$y)&rowSums(is.na(xx))==0&r$w>0;list(r=r,x=xx)\n}\nweightedRisk<-function(r,p,binary=FALSE,threshold=.5){\n ii<-which(r$w>0&!is.na(r$y)&!is.na(p)&!r$role%in%c('excluded','unused'));y<-r$y[ii];p<-p[ii];w<-r$w[ii];W<-sum(w);d<-list(rows=length(ii),mass=W,MSE=NA_real_,MAE=NA_real_,R2=NA_real_)\n if(W==0){if(binary)d<-c(d,setNames(rep(list(NA_real_),10),c('Brier','accuracy','positiveRecall','negativeRecall','precision','F1','balancedAccuracy','AUROC','positiveMass','negativeMass')));return(d)}\n mu<-sum(w*y)/W;sse<-sum(w*(p-y)^2);sst<-sum(w*(y-mu)^2);d<-c(d,list(meanY=mu,SSE=sse,SST=sst));d$MSE<-sse/W;d$MAE<-sum(w*abs(p-y))/W;d$R2<-if(sst>0)1-sse/sst else NA_real_\n if(binary){pos<-y==1;yes<-p>=threshold;TP<-sum(w[pos&yes]);FP<-sum(w[!pos&yes]);TN<-sum(w[!pos&!yes]);FN<-sum(w[pos&!yes]);rate<-function(a,b)if(b>0)a/b else NA_real_;tpr<-rate(TP,TP+FN);tnr<-rate(TN,TN+FP);auc<-NA_real_;P<-sum(w[pos]);N<-sum(w[!pos]);if(P>0&&N>0){wins<-sum(vapply(which(pos),function(i)sum(w[i]*w[!pos]*ifelse(p[i]>p[!pos],1,ifelse(p[i]==p[!pos],.5,0))),0.0));auc<-wins/(P*N)};d<-c(d,list(Brier=d$MSE,threshold=threshold,confusionMass=list(TP=TP,FP=FP,TN=TN,FN=FN),confusionRows=list(TP=sum(pos&yes),FP=sum(!pos&yes),TN=sum(!pos&!yes),FN=sum(pos&!yes)),positiveMass=P,negativeMass=N,accuracy=(TP+TN)/W,positiveRecall=tpr,negativeRecall=tnr,precision=rate(TP,TP+FP),F1=rate(2*TP,2*TP+FP+FN),balancedAccuracy=if(is.finite(tpr)&&is.finite(tnr))(tpr+tnr)/2 else NA_real_,AUROC=auc))};d\n}\nweightedPair<-function(r,A,B){\n ii<-which(r$w>0&!is.na(r$y)&!is.na(A)&!is.na(B)&!r$role%in%c('excluded','unused'));rr<-r[ii,,drop=FALSE];la<-(A[ii]-rr$y)^2;lb<-(B[ii]-rr$y)^2;d<-la-lb;W<-sum(rr$w);S<-sum(rr$w*d);mu<-if(W>0)S/W else NA_real_;ids<-unique(rr$group);groups<-lapply(ids,function(g){jj<-which(rr$group==g);wg<-sum(rr$w[jj]);sg<-sum(rr$w[jj]*d[jj]);list(group=g,rows=length(jj),mass=wg,sum=sg,leaveOut=if(W>wg)(S-sg)/(W-wg)else NA_real_)});leaves<-vapply(groups,`[[`,0.0,'leaveOut');G<-length(groups);proxy<-if(G>1&&all(is.finite(leaves)))(G-1)/G*sum((leaves-mean(leaves))^2) else NA_real_\n list(rows=length(ii),mass=W,groupCount=G,meanDifference=mu,minimumLeaveOut=if(any(is.finite(leaves)))min(leaves,na.rm=TRUE)else NA_real_,maximumLeaveOut=if(any(is.finite(leaves)))max(leaves,na.rm=TRUE)else NA_real_,varianceProxy=proxy,groups=groups,records=lapply(seq_along(ii),function(j)list(id=rr$id[j],group=rr$group[j],weight=rr$w[j],lossA=la[j],lossB=lb[j],difference=d[j])))\n}\nrunSelection<-function(r,candidates,criterion,required,binary=FALSE){\n out<-lapply(candidates,function(c){v<-r;t<-r;v$role[v$role!='validation']<-'excluded';t$role[t$role!='test']<-'excluded';val<-weightedRisk(v,c$pred,binary);test<-weightedRisk(t,c$pred,binary);co<-setNames(lapply(required,function(g){z<-v;z$role[z$cohort!=g]<-'excluded';weightedRisk(z,c$pred,binary)}),required);vv<-vapply(co,`[[`,0.0,'MSE');score<-if(criterion=='mean')val$MSE else if(length(vv)&&all(is.finite(vv)))max(vv)else NA_real_;list(id=c$id,criterion=score,validation=val,test=test,cohorts=co)})\n scores<-vapply(out,`[[`,0.0,'criterion');eligible<-which(is.finite(scores));k<-if(length(eligible))eligible[which.min(scores[eligible])]else NA_integer_;list(criterion=criterion,selected=if(!is.na(k))out[[k]]$id else NULL,selectedIndex=if(!is.na(k))k-1 else NA_real_,candidates=out)\n}\nfixedOperation<-function(api,a){\n if(api=='realdata'){\n  kind<-a$kind;r<-rows[[kind]];x<-X[[kind]];asgn<-assign_roles(r$group);r$dataset<-kind;r$splitRank<-asgn$rank;r$plannedRole<-asgn$planned;r$eligible<-!is.na(r$y)&rowSums(is.na(x))==0;r$role<-ifelse(r$eligible,r$plannedRole,'excluded');r$w<-1;binary<-kind=='company';leaf_min<<-5\n  defs<-data.frame(id=c('constant','ridge:1/100','ridge:1/10','ridge:1','one-split-stump'),method=c('constant','ridge','ridge','ridge','stump'),lambda=c(0,.01,.1,1,0));fits<-lapply(seq_len(5),function(i)fit_model(r,x,defs$method[i],defs$lambda[i]));candidates<-lapply(seq_len(5),function(i)list(id=defs$id[i],pred=fits[[i]]$pred));selection<-runSelection(r,candidates,a$criterion,unique(r$cohort),binary);k<-selection$selectedIndex+1;best<-fits[[k]];base<-fits[[1]];test<-r;test$role[test$role!='test']<-'excluded';paired<-weightedPair(test,best$pred,base$pred)\n  records<-lapply(seq_len(nrow(r)),function(i)list(id=r$id[i],sourceRow=r$sourceRow[i],originalID=r$originalID[i],group=r$group[i],cohort=r$cohort[i],plannedRole=r$plannedRole[i],role=r$role[i],eligible=r$eligible[i],y=r$y[i],baselinePrediction=base$pred[i],selectedPrediction=best$pred[i],selectedRawPrediction=best$raw[i],queryInvariant=TRUE))\n  return(list(kind=kind,nativeRows=nrow(r),eligibleRows=sum(r$eligible),selection=selection,models=lapply(seq_len(5),function(i)list(id=defs$id[i],train=as.list(r$id[r$role=='train']),mass=sum(r$role=='train'),meanX=fits[[i]]$meanX,scales=fits[[i]]$scales,model=fits[[i]]$model)),paired=paired,records=records))\n }\n f<-fixedRows(a$rows);r<-f$r;x<-f$x;binary<-identical(a$task,'binary')\n if(api=='split'){seed<<-a$seed;asgn<-assign_roles(r$group);return(list(state=asgn$state,groupCount=length(unique(r$group)),records=lapply(seq_len(nrow(r)),function(i)list(id=r$id[i],group=r$group[i],rank=asgn$rank[i],role=asgn$planned[i]))))}\n if(api=='fit'){\n  r$dataset<-if(binary)'company'else'fixed';leaf_min<<-if(is.null(a$minLeafRows))1 else a$minLeafRows;fit<-fit_model(r,x,a$method,if(is.null(a$lambda))0 else num(a$lambda));bad<-rowSums(is.na(x))>0;fit$raw[bad]<-NA_real_;fit$pred[bad]<-NA_real_;fit$defined<-TRUE;fit$train<-as.list(r$id[r$role=='train'&r$eligible]);fit$mass<-sum(r$w[r$role=='train'&r$eligible]);fit$invariant<-ifelse(bad,NA,TRUE);return(fit)\n }\n if(api=='evaluate'){p<-vapply(a$rows,function(v)num(v$prediction),0.0);threshold<-if(is.null(a$threshold)).5 else num(a$threshold);m<-weightedRisk(r,p,binary,threshold);records<-lapply(seq_len(nrow(r)),function(i){valid<-r$w[i]>0&&!is.na(r$y[i])&&!is.na(p[i])&&!r$role[i]%in%c('excluded','unused');list(id=r$id[i],weight=r$w[i],y=r$y[i],prediction=p[i],eligible=valid,loss=if(valid)(p[i]-r$y[i])^2 else NA_real_,correct=list(defined=valid&&binary,value=if(valid&&binary)(p[i]>=threshold)==r$y[i] else NULL))});return(list(metrics=m,records=records))}\n if(api=='select'){cs<-lapply(a$candidates,function(c)list(id=c$id,pred=vapply(c$predictions,num,0.0)));return(runSelection(r,cs,a$criterion,unlist(a$requiredCohorts),binary))}\n if(api=='paired')return(weightedPair(r,vapply(a$rows,function(v)num(v$predictionA),0.0),vapply(a$rows,function(v)num(v$predictionB),0.0)))\n stop('unknown-api')\n}\nreportValues<-function(api,z){\n ss<-list();pp<-list();add<-function(k,v,u='dimensionless')ss[[length(ss)+1]]<<-list(metric=k,value=if(is.null(v)||length(v)==0||is.na(v))NULL else unname(v),unit=u);series<-function(name,values){for(i in seq_along(values))pp[[length(pp)+1]]<<-list(series=name,index=i-1,x=i-1,y=if(is.null(values[[i]])||is.na(values[[i]]))NULL else unname(values[[i]]))}\n if(api=='split'){add('groups',z$groupCount,'groups');add('rows',length(z$records),'rows');add('finalState',z$state,'unsigned 32-bit state');series('planned role code',lapply(z$records,function(r)switch(r$role,test=0,validation=1,train=2)))}\n if(api=='fit'){add('defined',z$defined);add('trainingRows',length(z$train),'rows');add('trainingMass',z$mass,'analysis weight mass');add('modelRank',z$model$rank,'parameters');add('threshold',z$model$threshold,'constructed feature units');add('minimumObjective',z$model$minimumObjective,'constructed squared outcome units');series('prediction',as.list(z$pred));if(!is.null(z$model$theta))for(i in seq_along(z$model$theta))add(paste0('theta',i-1),z$model$theta[i],'constructed outcome units per standardized coordinate')}\n if(api=='evaluate'){for(k in c('rows','mass','MSE','MAE','R2','Brier','accuracy','positiveRecall','negativeRecall','precision','F1','balancedAccuracy','AUROC'))if(k%in%names(z$metrics))add(k,z$metrics[[k]],if(k=='rows')'rows'else if(k=='mass')'analysis weight mass'else if(k%in%c('MSE','Brier'))FIXED$unit else if(k=='MAE')'constructed outcome units'else'dimensionless');series('squared loss',lapply(z$records,`[[`,'loss'))}\n if(api=='select'){add('selectedIndex',z$selectedIndex,'zero-based candidate index');for(i in seq_along(z$candidates)){c<-z$candidates[[i]];add(paste0('criterion',i-1),c$criterion,FIXED$unit);add(paste0('testMSE',i-1),c$test$MSE,FIXED$unit)};series('validation criterion',lapply(z$candidates,`[[`,'criterion'));series('test MSE',lapply(z$candidates,function(c)c$test$MSE))}\n if(api=='paired'){for(k in c('rows','mass','groupCount','meanDifference','minimumLeaveOut','maximumLeaveOut','varianceProxy'))add(k,z[[k]],if(k=='rows')'rows'else if(k=='groupCount')'groups'else if(k=='mass')'analysis weight mass'else if(k=='varianceProxy')paste(FIXED$unit,'squared')else FIXED$unit);series('loss A minus loss B',lapply(z$records,`[[`,'difference'))}\n if(api=='realdata'){add('nativeRows',z$nativeRows,'native records');add('eligibleRows',z$eligibleRows,'complete records');add('selectedIndex',z$selection$selectedIndex,'zero-based candidate index');for(i in seq_along(z$selection$candidates)){c<-z$selection$candidates[[i]];add(paste0('validationMSE',i-1),c$validation$MSE,FIXED$unit);add(paste0('testMSE',i-1),c$test$MSE,FIXED$unit)};for(k in c('meanDifference','minimumLeaveOut','maximumLeaveOut','varianceProxy'))add(k,z$paired[[k]],if(k=='varianceProxy')paste(FIXED$unit,'squared')else FIXED$unit);best<-z$selection$candidates[[z$selection$selectedIndex+1]]$test;for(k in c('accuracy','positiveRecall','negativeRecall','precision','balancedAccuracy','AUROC'))if(k%in%names(best))add(k,best[[k]]);series('validation MSE',lapply(z$selection$candidates,function(c)c$validation$MSE));series('test MSE',lapply(z$selection$candidates,function(c)c$test$MSE))}\n list(summary=ss,points=pp)\n}\n\nescapeXML<-function(s){s<-gsub('&','&amp;',s,fixed=TRUE);s<-gsub('<','&lt;',s,fixed=TRUE);s<-gsub('>','&gt;',s,fixed=TRUE);gsub('\"','&quot;',s,fixed=TRUE)}\nsvgPlot<-function(pp,title){\n xx<-vapply(pp,function(p)as.numeric(p$x),numeric(1));yy<-vapply(pp,function(p)as.numeric(p$y),numeric(1));xmin<-if(length(xx))min(xx)else 0;xmax<-if(length(xx))max(xx)else 1;ymin<-min(c(0,yy));ymax<-max(c(0,yy));if(xmin==xmax){xmin<-xmin-.5;xmax<-xmax+.5};if(ymin==ymax){ymin<-ymin-.5;ymax<-ymax+.5};pad<-(ymax-ymin)*.08;ymin<-ymin-pad;ymax<-ymax+pad;X<-function(x)82+(as.numeric(x)-xmin)/(xmax-xmin)*608;Y<-function(y)354-(as.numeric(y)-ymin)/(ymax-ymin)*290\n out<-paste0('<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"720\" height=\"480\" viewBox=\"0 0 720 480\" role=\"img\" aria-label=\"',escapeXML(title),'\"><rect width=\"720\" height=\"480\" fill=\"white\"/><g font-family=\"Arial,sans-serif\" font-size=\"13\" fill=\"#18232f\"><text x=\"360\" y=\"25\" text-anchor=\"middle\">',escapeXML(title),'</text>')\n for(j in 0:4){y<-ymin+(ymax-ymin)*j/4;x<-xmin+(xmax-xmin)*j/4;out<-paste0(out,'<line x1=\"82\" y1=\"',Y(y),'\" x2=\"690\" y2=\"',Y(y),'\" stroke=\"#e2e8f0\"/><text x=\"73\" y=\"',Y(y)+4,'\" text-anchor=\"end\">',sprintf('%.3g',y),'</text><text x=\"',X(x),'\" y=\"380\" text-anchor=\"middle\">',sprintf('%.3g',x),'</text>')}\n ss<-unique(vapply(pp,`[[`,character(1),'series'));cols<-c('#0f766e','#c76622','#4f46e5','#b23857')\n for(j in seq_along(ss)){rr<-Filter(function(p)p$series==ss[j],pp);xy<-vapply(rr,function(p)sprintf('%.6f,%.6f',X(p$x),Y(p$y)),character(1));col<-cols[(j-1)%%4+1];for(p in rr)out<-paste0(out,'<circle cx=\"',sprintf('%.6f',X(p$x)),'\" cy=\"',sprintf('%.6f',Y(p$y)),'\" r=\"2.6\" fill=\"',col,'\"><title>',escapeXML(ss[j]),': ',escapeXML(p$y),'</title></circle>');out<-paste0(out,'<text x=\"',82+((j-1)%%2)*310,'\" y=\"',432+floor((j-1)/2)*23,'\" fill=\"',col,'\">',escapeXML(ss[j]),'</text>')}\n paste0(out,'<text x=\"360\" y=\"405\" text-anchor=\"middle\">Declared record / candidate index; fixed example</text></g></svg>')\n}\ntoJSON<-function(x){\n if(is.null(x))return('null');if(is.list(x)){v<-vapply(x,toJSON,character(1));if(!is.null(names(x)))paste0('{',paste(paste0(vapply(names(x),toJSON,character(1)),':',v),collapse=','),'}')else paste0('[',paste(v,collapse=','),']')}\n else if(length(x)!=1){if(!is.numeric(x)&&!is.null(names(x)))toJSON(as.list(x))else paste0('[',paste(vapply(as.list(x),toJSON,character(1)),collapse=','),']')}\n else if(is.na(x))'null'else if(is.logical(x))if(x)'true'else'false'else if(is.numeric(x))if(is.finite(x))sprintf('%.17g',x)else'null'else paste0('\"',gsub('\\n','\\\\n',gsub('\"','\\\\\"',gsub('\\\\','\\\\\\\\',x,fixed=TRUE),fixed=TRUE),fixed=TRUE),'\"')\n}\n\nFIXED<-list(`api`=\"fit\",`variant`=\"stump-exact-tie\",`title`=\"An exact one-split tree tie\",`input`=list(`method`=\"stump\",`minLeafRows`=1,`rows`=list(list(`x`=list(\"0\",\"0\"),`y`=\"0\"),list(`x`=list(\"1\",\"1\"),`y`=\"1\"),list(`x`=list(\"2\",\"2\"),`y`=\"0\"))),`unit`=\"Constructed outcome units\",`titleI18n`=list(`ko`=\"한 단계 나무의 정확한 동률\",`en`=\"An exact one-split tree tie\"))\n\nargs<-commandArgs(trailingOnly=TRUE);out<-if(length(args))args[1]else stop('NEW output directory required');if(dir.exists(out))stop('Preserve previous output directory');dir.create(out,recursive=TRUE)\nz<-fixedOperation(FIXED$api,FIXED$input);rr<-reportValues(FIXED$api,z)\nwriteLines(toJSON(list(arithmetic='BaseR binary64 author counterpart; native group hashing exact within declared integer range, stump approximate tie tolerance1e-12; not an independent exact oracle',result=z)),file.path(out,'full.json'),useBytes=TRUE)\nsums<-do.call(rbind,lapply(rr$summary,function(row)data.frame(metric=row$metric,value=if(is.null(row$value))''else if(is.logical(row$value))as.character(as.integer(row$value))else format(row$value,digits=17,scientific=NA,trim=TRUE),unit=row$unit,defined=as.integer(!is.null(row$value)),stringsAsFactors=FALSE)))\npoints<-do.call(rbind,lapply(rr$points,function(p)data.frame(series=p$series,index=p$index,x=p$x,y=if(is.null(p$y))NA_real_ else p$y,defined=as.integer(!is.null(p$y)),stringsAsFactors=FALSE)))\nwrite.csv(sums,file.path(out,'summary.csv'),row.names=FALSE,na='');write.csv(points,file.path(out,'plot-points.csv'),row.names=FALSE,na='');writeLines(svgPlot(Filter(function(p)!is.null(p$y),rr$points),FIXED$title),file.path(out,'plot.svg'),useBytes=TRUE);cat(FIXED$api,'/',FIXED$variant,'\\n',sep='')\n",
        "returnCode": 0,
        "stdout": "fit/stump-exact-tie\r\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 ",
        "diagnosticScope": "Public projection omits private absolute-path/traceback frames; actual exit and warnings/reason retained. Raw complete streams and commands in private execution proof.",
        "resultFolder": "ml22-code/runs/r-fit-stump-exact-tie",
        "kind": null,
        "inputFiles": [
          {
            "file": "ml22-code/fit-stump-exact-tie-input.json",
            "sha256": "208b4ba4768c5e7e5ce21a49db871bcc4dbef23dfaaf4e3cd57210ea802195a7",
            "scope": "Complete fixed literal input; program embeds the same values"
          }
        ],
        "files": [
          {
            "file": "ml22-code/runs/r-fit-stump-exact-tie/full.json",
            "sha256": "4c2ae4c896694a3249e2d217a72079a03160b65e28d01aa9529af34186b5cda7",
            "bytes": 557
          },
          {
            "file": "ml22-code/runs/r-fit-stump-exact-tie/plot-points.csv",
            "sha256": "0aab3c97286e430c6945fda1f47f53ab6c2a5d2e1e90364d399e80b19f13439d",
            "bytes": 106
          },
          {
            "file": "ml22-code/runs/r-fit-stump-exact-tie/plot.svg",
            "sha256": "4b18c8ff74fa34968eb4c8de83d683c552c852441608f633a2b4c0265c41f1a7",
            "bytes": 1603
          },
          {
            "file": "ml22-code/runs/r-fit-stump-exact-tie/summary.csv",
            "sha256": "60e03354eddc14506d11ee6c3c37b20c6c87936b1092bac79357b766da5c5b5e",
            "bytes": 283
          }
        ],
        "summaryRows": [
          {
            "metric": "defined",
            "value": "1.0",
            "unit": "dimensionless",
            "defined": "true",
            "rawValue": "1",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "trainingRows",
            "value": "3.0",
            "unit": "rows",
            "defined": "true",
            "rawValue": "3",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "trainingMass",
            "value": "3.0",
            "unit": "analysis weight mass",
            "defined": "true",
            "rawValue": "3",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "modelRank",
            "value": "",
            "unit": "parameters",
            "defined": "false",
            "rawValue": "",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null
          },
          {
            "metric": "threshold",
            "value": "0.5",
            "unit": "constructed feature units",
            "defined": "true",
            "rawValue": "0.5",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "minimumObjective",
            "value": "",
            "unit": "constructed squared outcome units",
            "defined": "false",
            "rawValue": "",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null
          }
        ],
        "plotRows": [
          {
            "series": "prediction",
            "index": "0",
            "x": "0",
            "y": "0",
            "defined": true,
            "xExact": null,
            "yExact": null
          },
          {
            "series": "prediction",
            "index": "1",
            "x": "1",
            "y": "0.5",
            "defined": true,
            "xExact": null,
            "yExact": null
          },
          {
            "series": "prediction",
            "index": "2",
            "x": "2",
            "y": "0.5",
            "defined": true,
            "xExact": null,
            "yExact": null
          }
        ],
        "plotFile": "ml22-code/runs/r-fit-stump-exact-tie/plot.svg",
        "fullResultFile": "ml22-code/runs/r-fit-stump-exact-tie/full.json",
        "arithmeticScope": "Python exact rational versus base-R approximate floating algebra; copied author kernels, not independent oracle.",
        "plotScope": "Original scatter vectors plot every defined declared comparison point, with missing points omitted. Source profiles show candidate risks; all source records remain in the full result and source CSV files.",
        "reproductionScope": "Standalone literal program plus four native CSV files for factual source profiles. No answer/engine/checker imports."
      }
    }
  },
  "evaluate": {
    "python": {
      "weighted-regression-loss": {
        "api": "evaluate",
        "variant": "weighted-regression-loss",
        "language": "python",
        "title": "Weight mass differs from row count",
        "titleI18n": {
          "ko": "행 수와 다른 비중 질량",
          "en": "Weight mass differs from row count"
        },
        "input": {
          "rows": [
            {
              "id": "a",
              "y": "1",
              "prediction": "2",
              "weight": "1"
            },
            {
              "id": "b",
              "y": "3",
              "prediction": "1",
              "weight": "3"
            }
          ]
        },
        "expectedFailure": false,
        "codeFile": "ml22-code/evaluate-weighted-regression-loss.py",
        "codeSHA256": "64b41aada6480e21e1099d77d6c76975aa48ba87f88ab8139fc23e5a337dfff6",
        "code": "# ML22 standalone fixed literal. Attribution and arithmetic scope in README.\nimport csv,hashlib,html,json,math,sys,time\nfrom pathlib import Path\nfrom fractions import Fraction as F\nfrom collections import Counter\nsys.set_int_max_str_digits(200000)\nnumber=lambda v:F(str(v))\ndef Q(x):return None if x is None or x in ('','.') else F(str(x))\n\ndef canonical(v):return None if Q(v) is None else str(Q(v))\n\ndef fingerprint(tag,values):return tag+':'+hashlib.sha256(json.dumps([canonical(x)for x in values],separators=(',',':')).encode()).hexdigest()\n\ndef split(rows,seed=20261104,pattern=('test','validation','train','train')):\n order=sorted(set(r['group'] for r in rows));state=seed\n for j in range(len(order)-1,0,-1):state=(1664525*state+1013904223)&0xffffffff;k=state%(j+1);order[k],order[j]=order[j],order[k]\n roles={g:(i,pattern[i%len(pattern)]) for i,g in enumerate(order)}\n return roles,state,order\n\ndef solve(A,b):\n n=len(b);M=[list(row)+[rhs]for row,rhs in zip(A,b)];piv=[];rank=0\n for j in range(n):\n  candidates=[i for i in range(rank,n)if M[i][j]]\n  if not candidates:continue\n  k=max(candidates,key=lambda i:abs(M[i][j]));M[rank],M[k]=M[k],M[rank];v=M[rank][j];M[rank]=[x/v for x in M[rank]]\n  for i in range(n):\n   if i!=rank:\n    v=M[i][j];M[i]=[a-v*b for a,b in zip(M[i],M[rank])]\n  piv.append(j);rank+=1\n x=[F(0)]*n\n for i,j in enumerate(piv):x[j]=M[i][-1]\n null=[]\n for j in range(n):\n  if j not in piv:\n   v=[F(0)]*n;v[j]=F(1)\n   for i,k in enumerate(piv):v[k]=-M[i][j]\n   null.append(v)\n return x,rank,null\n\ndef dot(a,b):return sum((x*y for x,y in zip(a,b)),F(0))\n\ndef fit(rows,method,lam=F(0),minleaf=1,binary=False):\n use=[r for r in rows if r['role']=='train'and r['w']>0 and r['y']is not None and None not in r['x']];p=len(rows[0]['x'])if rows else 0\n if not use:return dict(defined=False,pred=[None]*len(rows),raw=[None]*len(rows),train=[],invariant=[None]*len(rows))\n mass=sum(r['w']for r in use);mu=[sum(r['w']*r['x'][j]for r in use)/mass for j in range(p)];scale=[max(r['x'][j]for r in use)-min(r['x'][j]for r in use)or F(1)for j in range(p)];mean=sum(r['w']*r['y']for r in use)/mass;model={};z=lambda r:[F(1)]+[(x-m)/s for x,m,s in zip(r['x'],mu,scale)]\n if method=='constant':model=dict(mean=mean,parameterCount=1,rank=1,unique=True)\n elif method=='ridge':\n  vectors=[z(r)for r in use];n=p+1;A=[[sum(r['w']*xx[j]*xx[k]for r,xx in zip(use,vectors))/mass+(lam if j==k and j>0 else F(0))for k in range(n)]for j in range(n)];b=[sum(r['w']*r['y']*xx[j]for r,xx in zip(use,vectors))/mass for j in range(n)];theta,rank,null=solve(A,b);objective=sum(r['w']*(dot(xx,theta)-r['y'])**2 for r,xx in zip(use,vectors))/(2*mass)+lam*sum(x*x for x in theta[1:])/2;model=dict(lambdaValue=lam,theta=theta,rank=rank,unique=rank==n,nullspace=null,minimumObjective=objective,parameterCount=n)\n else:\n  best=None;total=sum(r['w']*r['y']for r in use);total2=sum(r['w']*r['y']**2 for r in use);base=total2-total**2/mass\n  for j in range(p):\n   ordered=sorted(enumerate(use),key=lambda v:(v[1]['x'][j],v[0]));leftW=F(0);leftS=F(0)\n   for i,(_idx,r)in enumerate(ordered[:-1]):\n    leftW+=r['w'];leftS+=r['w']*r['y'];rightW=mass-leftW\n    if i+1<minleaf or len(use)-i-1<minleaf or r['x'][j]==ordered[i+1][1]['x'][j]:continue\n    SSE=total2-leftS**2/leftW-(total-leftS)**2/rightW\n    if best is None or SSE<best['weightedSSE']:best=dict(feature=j,threshold=(r['x'][j]+ordered[i+1][1]['x'][j])/2,leftMean=leftS/leftW,rightMean=(total-leftS)/rightW,leftRows=i+1,rightRows=len(use)-i-1,leftWeight=leftW,rightWeight=rightW,weightedSSE=SSE)\n  model=dict(split=False,mean=mean,weightedSSE=base,trainingMSE=base/mass)if best is None or best['weightedSSE']>=base else dict(split=True,**best,trainingMSE=best['weightedSSE']/mass,improvement=(base-best['weightedSSE'])/mass)\n raw=[];invariant=[]\n for r in rows:\n  if None in r['x']:raw.append(None);invariant.append(None);continue\n  if method=='constant':v=mean;iv=True\n  elif method=='ridge':zz=z(r);v=dot(zz,model['theta']);iv=all(dot(zz,nn)==0 for nn in model['nullspace'])\n  else:v=(model['leftMean']if r['x'][model['feature']]<=model['threshold']else model['rightMean'])if model['split']else mean;iv=True\n  raw.append(v);invariant.append(iv)\n pred=[None if x is None else min(F(1),max(F(0),x))if binary else x for x in raw]\n return dict(defined=True,train=[r['id']for r in use],mass=mass,meanX=mu,scales=scale,model=model,pred=pred,raw=raw,invariant=invariant)\n\ndef risk(rows,pred,binary=False,threshold=F(1,2)):\n use=[(r,p)for r,p in zip(rows,pred)if r['w']>0 and r['y']is not None and p is not None and r['role']not in['excluded','unused']];mass=sum((r['w']for r,p in use),F(0));d=dict(rows=len(use),mass=mass)\n if not mass:\n  d.update({k:None for k in ['MSE','MAE','R2']+(['Brier','accuracy','balancedAccuracy','AUROC']if binary else[])});return d\n mean=sum(r['w']*r['y']for r,p in use)/mass;sse=sum(r['w']*(p-r['y'])**2 for r,p in use);sst=sum(r['w']*(r['y']-mean)**2 for r,p in use);d.update(meanY=mean,SSE=sse,SST=sst,MSE=sse/mass,MAE=sum(r['w']*abs(p-r['y'])for r,p in use)/mass,R2=1-sse/sst if sst else None)\n if binary:\n  weights=Counter();num=Counter()\n  for r,p in use:k=('T'if int(p>=threshold)==int(r['y'])else'F')+('P'if p>=threshold else'N');weights[k]+=r['w'];num[k]+=1\n  TP,FP,TN,FN=[weights[k]for k in ['TP','FP','TN','FN']];positive=TP+FN;negative=TN+FP;rate=lambda a,b:a/b if b else None;TPR=rate(TP,positive);TNR=rate(TN,negative)\n  # Pair enumeration is independent of the subject's score-tie-block formula.\n  negatives=[(r,p)for r,p in use if not r['y']];positives=[(r,p)for r,p in use if r['y']];wins=sum((a['w']*b['w']*(F(1)if pa>pb else F(1,2)if pa==pb else F(0))for a,pa in positives for b,pb in negatives),F(0))\n  d.update(Brier=d['MSE'],threshold=threshold,confusionMass={k:weights[k]for k in ['TP','FP','TN','FN']},confusionRows={k:num[k]for k in ['TP','FP','TN','FN']},positiveMass=positive,negativeMass=negative,accuracy=(TP+TN)/mass,positiveRecall=TPR,negativeRecall=TNR,precision=rate(TP,TP+FP),F1=rate(2*TP,2*TP+FP+FN),balancedAccuracy=(TPR+TNR)/2 if TPR is not None and TNR is not None else None,AUROC=rate(wins,positive*negative))\n return d\n\nNATIVE_SHA256={'actual1599-red-wine-original12-fields.csv': '77e9ac73115930d6c43983333a5a57940deefc493affeb17aca478c09c5f6e00', 'actual4898-white-wine-original12-fields.csv': '50d810bbb42b9cc3e87fa4c27a4c0f168e72da09dd812863425ca3873fec28ef', 'actual3613-NLS-original52-fields.csv': '6e1e1895558795435b65f8634252a7589865273a0e69adbd715fcfa04a3c11a1', 'actual3150-churn-original14-fields.csv': '1c0753e434226e769d1015c922121a7d8967df66014e057c4f7543e490f11764'}\n\ndef read_sources(directory,seed):\n def read(name):\n  p=directory/name\n  if hashlib.sha256(p.read_bytes()).hexdigest()!=NATIVE_SHA256[name]:raise ValueError('Native file hash differs: '+name)\n  with p.open(encoding='utf8',newline='')as f:return list(csv.DictReader(f))\n sources={};wine=[]\n for typ,n in [('red',1599),('white',4898)]:\n  table=read(f'actual{n}-{typ}-wine-original12-fields.csv');assert len(table)==n;features=[k for k in table[0]if k not in ['sourceRow','wineType','quality']];assert len(features)==11\n  for r in table:\n   i=int(r['sourceRow']);red='1'if typ=='red'else'0';nativeX=[r[k]for k in features];wine.append(dict(id=f'wine-{typ}-row:{i}',sourceRow=f'{typ}:{i}',originalID=None,group=fingerprint('wine-predictors',[red]+nativeX),cohort=typ,x=list(map(Q,nativeX+[red])),y=Q(r['quality'])))\n sources['country']=wine\n table=read('actual3613-NLS-original52-fields.csv');assert len(table)==3613;sources['person']=[dict(id='nls-row:'+r['sourceRow'],sourceRow=int(r['sourceRow']),originalID=r['id'],group='nls-id:'+r['id'],cohort='schooling-over12'if Q(r['ed76'])>12 else'schooling-at-most12',x=[Q(r['ed76']),Q(r['age76'])],y=Q(r['lwage76']))for r in table]\n table=read('actual3150-churn-original14-fields.csv');assert len(table)==3150;predictors=[k for k in table[0]if k not in ['sourceRow','Churn']];assert len(predictors)==13;sources['company']=[dict(id='customer-row:'+r['sourceRow'],sourceRow=int(r['sourceRow']),originalID=None,group=fingerprint('customer-predictors',[r[k]for k in predictors]),cohort='pay-as-you-go'if r['Tariff Plan']=='1'else'contractual'if r['Tariff Plan']=='2'else'other-native-tariff',x=[Q(r[k])for k in ['Call  Failure','Subscription  Length','Seconds of Use','Age']],y=Q(r['Churn']))for r in table]\n for kind,rows in sources.items():\n  assignments,state,order=split(rows,seed)\n  for r in rows:\n   rank,planned=assignments[r['group']];r.update(w=F(1),splitRank=rank,plannedRole=planned,eligible=r['y']is not None and None not in r['x']);r['role']=planned if r['eligible']else'excluded'\n return sources\n# New ML22 fixed-profile kernels. The public Fraction fitting/source readers are\n# copied by value above this file by the standalone builder; never imported.\ndef fixed_rows(data, prediction_key=None):\n out=[]\n for i,a in enumerate(data):\n  w=Q(a.get('weight','1'))\n  if w is None or w<0:raise ValueError('negative-weight' if w is not None and w<0 else 'missing-weight')\n  out.append(dict(id=a.get('id',str(i)),group=a.get('group',a.get('id',str(i))),cohort=a.get('cohort','all'),role=a.get('role','train'),w=w,x=[Q(v)for v in a.get('x',[])],y=Q(a.get('y'))))\n return out\n\ndef weighted_pair(rows,A,B):\n use=[(r,a,b)for r,a,b in zip(rows,A,B)if r['w']>0 and r['y']is not None and a is not None and b is not None and r['role']not in ['excluded','unused']]\n mass=sum((r['w']for r,a,b in use),F(0));records=[];groups={}\n for r,a,b in use:\n  la=(a-r['y'])**2;lb=(b-r['y'])**2;d=la-lb\n  records.append(dict(id=r['id'],group=r['group'],weight=r['w'],lossA=la,lossB=lb,difference=d))\n  g=groups.setdefault(r['group'],dict(group=r['group'],rows=0,mass=F(0),sum=F(0)));g['rows']+=1;g['mass']+=r['w'];g['sum']+=r['w']*d\n total=sum((g['sum']for g in groups.values()),F(0));mean=total/mass if mass else None;G=len(groups)\n for g in groups.values():g['leaveOut']=(total-g['sum'])/(mass-g['mass'])if mass>g['mass']else None\n leaves=[g['leaveOut']for g in groups.values()if g['leaveOut']is not None]\n proxy=F(G-1,G)*sum((v-sum(leaves,F(0))/G)**2 for v in leaves) if G>1 and len(leaves)==G else None\n return dict(rows=len(use),mass=mass,groupCount=G,meanDifference=mean,minimumLeaveOut=min(leaves)if leaves else None,maximumLeaveOut=max(leaves)if leaves else None,varianceProxy=proxy,groups=list(groups.values()),records=records)\n\ndef run_selection(rows,candidates,criterion,required,binary=False):\n results=[]\n for c,pred in candidates:\n  val=[dict(r,role='excluded')if r['role']!='validation'else r for r in rows]\n  test=[dict(r,role='excluded')if r['role']!='test'else r for r in rows]\n  v=risk(val,pred,binary);t=risk(test,pred,binary);cohort={g:risk([dict(r,role='excluded')if r['role']!='validation'or r['cohort']!=g else r for r in rows],pred,binary)for g in required}\n  values=[cohort[g]['MSE']for g in required]\n  score=v['MSE']if criterion=='mean'else max(values)if values and None not in values else None\n  results.append(dict(id=c,criterion=score,validation=v,test=t,cohorts=cohort))\n eligible=[(i,r['criterion'])for i,r in enumerate(results)if r['criterion']is not None]\n chosen=min(eligible,key=lambda t:(t[1],t[0]))[0]if eligible else None\n return dict(criterion=criterion,selected=results[chosen]['id']if chosen is not None else None,selectedIndex=chosen,candidates=results)\n\ndef fixed_operation(api,a):\n if api=='realdata':\n  kind=a['kind'];rows=read_sources(Path(__file__).parent/'data',a.get('seed',20261104))[kind];binary=kind=='company'\n  defs=[('constant','constant',F(0)),('ridge:1/100','ridge',F(1,100)),('ridge:1/10','ridge',F(1,10)),('ridge:1','ridge',F(1)),('one-split-stump','stump',F(0))]\n  fits=[fit(rows,method,lam,5,binary)for _,method,lam in defs]\n  selection=run_selection(rows,[(d[0],f['pred'])for d,f in zip(defs,fits)],a.get('criterion','mean'),list(dict.fromkeys(r['cohort']for r in rows)),binary)\n  chosen=selection['selectedIndex'];best=fits[chosen];base=fits[0]\n  test=[dict(r,role='excluded')if r['role']!='test'else r for r in rows]\n  paired=weighted_pair(test,best['pred'],base['pred'])\n  records=[dict(id=r['id'],sourceRow=r.get('sourceRow'),originalID=r.get('originalID'),group=r['group'],cohort=r['cohort'],plannedRole=r['plannedRole'],role=r['role'],eligible=r['eligible'],y=r['y'],baselinePrediction=base['pred'][i],selectedPrediction=best['pred'][i],selectedRawPrediction=best['raw'][i],queryInvariant=best['invariant'][i])for i,r in enumerate(rows)]\n  return dict(kind=kind,nativeRows=len(rows),eligibleRows=sum(r['eligible']for r in rows),selection=selection,models=[dict(id=d[0],train=f['train'],mass=f.get('mass'),meanX=f.get('meanX'),scales=f.get('scales'),model=f.get('model'))for d,f in zip(defs,fits)],paired=paired,records=records)\n rows=fixed_rows(a.get('rows',[]));binary=a.get('task')=='binary'\n if api=='split':\n  assignment,state,order=split(rows,a.get('seed',0));records=[dict(id=r['id'],group=r['group'],rank=assignment[r['group']][0],role=assignment[r['group']][1])for r in rows]\n  return dict(state=state,groupOrder=order,records=records,groupCount=len(order))\n if api=='fit':return fit(rows,a.get('method','constant'),Q(a.get('lambda','0')),a.get('minLeafRows',1),binary)\n if api=='evaluate':\n  pred=[Q(r.get('prediction'))for r in a['rows']];threshold=Q(a.get('threshold','1/2'));rr=risk(rows,pred,binary,threshold)\n  records=[]\n  for r,p in zip(rows,pred):\n   valid=r['w']>0 and r['y']is not None and p is not None and r['role']not in ['excluded','unused']\n   records.append(dict(id=r['id'],weight=r['w'],y=r['y'],prediction=p,eligible=valid,loss=(p-r['y'])**2 if valid else None,correct=dict(defined=valid and binary,value=bool(int(p>=threshold)==int(r['y']))if valid and binary else None)))\n  return dict(metrics=rr,records=records)\n if api=='select':return run_selection(rows,[(c['id'],list(map(Q,c['predictions'])))for c in a['candidates']],a.get('criterion','mean'),a.get('requiredCohorts',list(dict.fromkeys(r['cohort']for r in rows))),binary)\n if api=='paired':return weighted_pair(rows,[Q(r.get('predictionA'))for r in a['rows']],[Q(r.get('predictionB'))for r in a['rows']])\n raise ValueError('unknown-api')\n\ndef report_values(api,z):\n summary=[];series=[]\n def add(k,v,u='dimensionless'):summary.append((k,v,u))\n if api=='split':\n  add('groups',z['groupCount'],'groups');add('rows',len(z['records']),'rows');add('finalState',z['state'],'unsigned 32-bit state')\n  series=[('planned role code',[(i,F({'test':0,'validation':1,'train':2}[r['role']]))for i,r in enumerate(z['records'])])]\n elif api=='fit':\n  add('defined',z['defined']);add('trainingRows',len(z['train']),'rows');add('trainingMass',z.get('mass'),'analysis weight mass')\n  model=z.get('model',{});add('modelRank',model.get('rank'),'parameters');add('threshold',model.get('threshold'),'constructed feature units');add('minimumObjective',model.get('minimumObjective'),'constructed squared outcome units')\n  series=[('prediction',list(enumerate(z['pred'])))];\n  if model.get('theta')is not None:\n   for i,v in enumerate(model['theta']):add('theta'+str(i),v,'constructed outcome units per standardized coordinate')\n elif api=='evaluate':\n  for k in ['rows','mass','MSE','MAE','R2','Brier','accuracy','positiveRecall','negativeRecall','precision','F1','balancedAccuracy','AUROC']: \n   if k in z['metrics']:add(k,z['metrics'][k],'rows'if k=='rows'else'analysis weight mass'if k=='mass'else FIXED['unit']if k in ['MSE','Brier']else('probability-score units'if FIXED['input'].get('task')=='binary'else'constructed outcome units')if k=='MAE'else'dimensionless')\n  series=[('squared loss',[(i,r['loss'])for i,r in enumerate(z['records'])])]\n elif api=='select':\n  add('selectedIndex',z['selectedIndex'],'zero-based candidate index')\n  for i,c in enumerate(z['candidates']):add('criterion'+str(i),c['criterion'],FIXED['unit']);add('testMSE'+str(i),c['test']['MSE'],FIXED['unit'])\n  series=[('validation criterion',[(i,c['criterion'])for i,c in enumerate(z['candidates'])]),('test MSE',[(i,c['test']['MSE'])for i,c in enumerate(z['candidates'])])]\n elif api=='paired':\n  for k in ['rows','mass','groupCount','meanDifference','minimumLeaveOut','maximumLeaveOut','varianceProxy']:add(k,z[k],'rows'if k=='rows'else'groups'if k=='groupCount'else'analysis weight mass'if k=='mass'else FIXED['unit']+' squared'if k=='varianceProxy'else FIXED['unit'])\n  series=[('loss A minus loss B',[(i,r['difference'])for i,r in enumerate(z['records'])])]\n elif api=='realdata':\n  add('nativeRows',z['nativeRows'],'native records');add('eligibleRows',z['eligibleRows'],'complete records');add('selectedIndex',z['selection']['selectedIndex'],'zero-based candidate index')\n  for i,c in enumerate(z['selection']['candidates']):add('validationMSE'+str(i),c['validation']['MSE'],FIXED['unit']);add('testMSE'+str(i),c['test']['MSE'],FIXED['unit'])\n  for k in ['meanDifference','minimumLeaveOut','maximumLeaveOut','varianceProxy']:add(k,z['paired'][k],FIXED['unit']+' squared'if k=='varianceProxy'else FIXED['unit'])\n  best=z['selection']['candidates'][z['selection']['selectedIndex']]['test']\n  for k in ['accuracy','positiveRecall','negativeRecall','precision','balancedAccuracy','AUROC']:\n   if k in best:add(k,best[k])\n  series=[('validation MSE',[(i,c['validation']['MSE'])for i,c in enumerate(z['selection']['candidates'])]),('test MSE',[(i,c['test']['MSE'])for i,c in enumerate(z['selection']['candidates'])])]\n return summary,series\n\n\ndef fixed_svg(points,title):\n good=[p for p in points if p['y'] is not None];xx=[float(p['x'])for p in good];yy=[float(p['y'])for p in good];xmin=min(xx)if xx else 0;xmax=max(xx)if xx else 1;ymin=min([0]+yy);ymax=max([0]+yy)\n if xmin==xmax:xmin-=.5;xmax+=.5\n if ymin==ymax:ymin-=.5;ymax+=.5\n pad=(ymax-ymin)*.08;ymin-=pad;ymax+=pad;X=lambda x:82+(float(x)-xmin)/(xmax-xmin)*608;Y=lambda y:354-(float(y)-ymin)/(ymax-ymin)*290;e=html.escape\n out=['<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"720\" height=\"480\" viewBox=\"0 0 720 480\" role=\"img\" aria-label=\"'+e(title)+'\"><rect width=\"720\" height=\"480\" fill=\"white\"/><g font-family=\"Arial,sans-serif\" font-size=\"13\" fill=\"#18232f\"><text x=\"360\" y=\"25\" text-anchor=\"middle\">'+e(title)+'</text>']\n for j in range(5):\n  y=ymin+(ymax-ymin)*j/4;x=xmin+(xmax-xmin)*j/4;out.append('<line x1=\"82\" y1=\"'+str(Y(y))+'\" x2=\"690\" y2=\"'+str(Y(y))+'\" stroke=\"#e2e8f0\"/><text x=\"73\" y=\"'+str(Y(y)+4)+'\" text-anchor=\"end\">'+format(y,'.3g')+'</text><text x=\"'+str(X(x))+'\" y=\"380\" text-anchor=\"middle\">'+format(x,'.3g')+'</text>')\n series=list(dict.fromkeys(p['series']for p in good))\n for j,s in enumerate(series):\n  pp=[p for p in good if p['series']==s];color=['#0f766e','#c76622','#4f46e5','#b23857'][j%4]\n  for p in pp:out.append('<circle cx=\"'+format(X(p['x']),'.6f')+'\" cy=\"'+format(Y(p['y']),'.6f')+'\" r=\"2.6\" fill=\"'+color+'\"><title>'+e(s+': '+str(p['y']))+'</title></circle>')\n  out.append('<text x=\"'+str(82+(j%2)*310)+'\" y=\"'+str(432+(j//2)*23)+'\" fill=\"'+color+'\">'+e(s)+'</text>')\n out.append('<text x=\"360\" y=\"405\" text-anchor=\"middle\">Declared record / candidate index; units in summary</text></g></svg>');return''.join(out)\n\nFIXED={'api': 'evaluate', 'variant': 'weighted-regression-loss', 'title': 'Weight mass differs from row count', 'input': {'rows': [{'id': 'a', 'y': '1', 'prediction': '2', 'weight': '1'}, {'id': 'b', 'y': '3', 'prediction': '1', 'weight': '3'}]}, 'unit': 'Constructed squared outcome units', 'titleI18n': {'ko': '행 수와 다른 비중 질량', 'en': 'Weight mass differs from row count'}}\n\nOUT=Path(sys.argv[1]);OUT.mkdir(parents=True,exist_ok=False)\nresult=fixed_operation(FIXED['api'],FIXED['input']);summary,series=report_values(FIXED['api'],result)\ndef encode(v):\n if isinstance(v,F):return str(v)\n if isinstance(v,dict):return{k:encode(x)for k,x in v.items()}\n if isinstance(v,(list,tuple)):return[encode(x)for x in v]\n return v\n(OUT/'full.json').write_text(json.dumps(dict(arithmetic='Exact rational author implementation; factual rows, declared group split and finite five-candidate comparison',result=encode(result)),ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\nsummaryRows=[dict(metric=m,value=''if v is None else str(int(v))if isinstance(v,bool)else str(v),unit=u,defined=int(v is not None))for m,v,u in summary]\npoints=[dict(series=name,index=i,x=str(x),y=''if y is None else str(y),defined=int(y is not None))for name,pp in series for i,(x,y)in enumerate(pp)]\nfor name,rows in [('summary',summaryRows),('plot-points',points)]:\n with(OUT/(name+'.csv')).open('w',encoding='utf8',newline='')as f:writer=csv.DictWriter(f,fieldnames=list(rows[0]));writer.writeheader();writer.writerows(rows)\n(OUT/'plot.svg').write_text(fixed_svg([dict(p,x=number(p['x']),y=None if not p['defined']else number(p['y']))for p in points],FIXED['title']),encoding='utf8');print(FIXED['api']+'/'+FIXED['variant'])\n",
        "returnCode": 0,
        "stdout": "evaluate/weighted-regression-loss\r\n",
        "stderr": "",
        "diagnosticScope": "Public projection omits private absolute-path/traceback frames; actual exit and warnings/reason retained. Raw complete streams and commands in private execution proof.",
        "resultFolder": "ml22-code/runs/python-evaluate-weighted-regression-loss",
        "kind": null,
        "inputFiles": [
          {
            "file": "ml22-code/evaluate-weighted-regression-loss-input.json",
            "sha256": "a75d3f805a5bb31a01cf33e0b219ac32650bc0180cf9beb471347bab828cf170",
            "scope": "Complete fixed literal input; program embeds the same values"
          }
        ],
        "files": [
          {
            "file": "ml22-code/runs/python-evaluate-weighted-regression-loss/full.json",
            "sha256": "5382d8d5cdf6e957a903b3eb7d3e2a019dadf6427819dfa65c4709db712e0972",
            "bytes": 862
          },
          {
            "file": "ml22-code/runs/python-evaluate-weighted-regression-loss/plot-points.csv",
            "sha256": "3ae89c22d1cd07d383bf65ed1a30b279c422265ef6f6f1cf6b7e1ee21e703327",
            "bytes": 70
          },
          {
            "file": "ml22-code/runs/python-evaluate-weighted-regression-loss/plot.svg",
            "sha256": "9b2c47ce5af395a12af0125a729f00a8865ac7c596c46c34c499510bf33f6546",
            "bytes": 1548
          },
          {
            "file": "ml22-code/runs/python-evaluate-weighted-regression-loss/summary.csv",
            "sha256": "d95a2474b9b6729beb77fa97e84a660d446fa6a517ec9ea96a4caeb2e70a1bd8",
            "bytes": 182
          }
        ],
        "summaryRows": [
          {
            "metric": "rows",
            "value": "2.0",
            "unit": "rows",
            "defined": "true",
            "rawValue": "2",
            "arithmetic": "Exact Fraction",
            "exactFraction": "2",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "mass",
            "value": "4.0",
            "unit": "analysis weight mass",
            "defined": "true",
            "rawValue": "4",
            "arithmetic": "Exact Fraction",
            "exactFraction": "4",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "MSE",
            "value": "3.25",
            "unit": "Constructed squared outcome units",
            "defined": "true",
            "rawValue": "13/4",
            "arithmetic": "Exact Fraction",
            "exactFraction": "13/4",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "MAE",
            "value": "1.75",
            "unit": "constructed outcome units",
            "defined": "true",
            "rawValue": "7/4",
            "arithmetic": "Exact Fraction",
            "exactFraction": "7/4",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "R2",
            "value": "-3.3333333333333335",
            "unit": "dimensionless",
            "defined": "true",
            "rawValue": "-10/3",
            "arithmetic": "Exact Fraction",
            "exactFraction": "-10/3",
            "mathematicallyPositive": false,
            "mathematicallyNegative": true,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          }
        ],
        "plotRows": [
          {
            "series": "squared loss",
            "index": "0",
            "x": "0",
            "y": "1",
            "defined": true,
            "xExact": "0",
            "yExact": "1"
          },
          {
            "series": "squared loss",
            "index": "1",
            "x": "1",
            "y": "4",
            "defined": true,
            "xExact": "1",
            "yExact": "4"
          }
        ],
        "plotFile": "ml22-code/runs/python-evaluate-weighted-regression-loss/plot.svg",
        "fullResultFile": "ml22-code/runs/python-evaluate-weighted-regression-loss/full.json",
        "arithmeticScope": "Python exact rational versus base-R approximate floating algebra; copied author kernels, not independent oracle.",
        "plotScope": "Original scatter vectors plot every defined declared comparison point, with missing points omitted. Source profiles show candidate risks; all source records remain in the full result and source CSV files.",
        "reproductionScope": "Standalone literal program plus four native CSV files for factual source profiles. No answer/engine/checker imports."
      },
      "weighted-AUC-tie": {
        "api": "evaluate",
        "variant": "weighted-AUC-tie",
        "language": "python",
        "title": "Weighted AUC with a positive-negative score tie",
        "titleI18n": {
          "ko": "양성·음성 점수 동률의 가중 AUC",
          "en": "Weighted AUC with a positive-negative score tie"
        },
        "input": {
          "task": "binary",
          "rows": [
            {
              "id": "p",
              "y": "1",
              "prediction": "4/5",
              "weight": "2"
            },
            {
              "id": "n1",
              "y": "0",
              "prediction": "3/10"
            },
            {
              "id": "n2",
              "y": "0",
              "prediction": "4/5"
            }
          ]
        },
        "expectedFailure": false,
        "codeFile": "ml22-code/evaluate-weighted-AUC-tie.py",
        "codeSHA256": "d07f1f3b8da8dd2a35f9f6bb41ca951223b938911b58afa2f45fa6d8ab04bd94",
        "code": "# ML22 standalone fixed literal. Attribution and arithmetic scope in README.\nimport csv,hashlib,html,json,math,sys,time\nfrom pathlib import Path\nfrom fractions import Fraction as F\nfrom collections import Counter\nsys.set_int_max_str_digits(200000)\nnumber=lambda v:F(str(v))\ndef Q(x):return None if x is None or x in ('','.') else F(str(x))\n\ndef canonical(v):return None if Q(v) is None else str(Q(v))\n\ndef fingerprint(tag,values):return tag+':'+hashlib.sha256(json.dumps([canonical(x)for x in values],separators=(',',':')).encode()).hexdigest()\n\ndef split(rows,seed=20261104,pattern=('test','validation','train','train')):\n order=sorted(set(r['group'] for r in rows));state=seed\n for j in range(len(order)-1,0,-1):state=(1664525*state+1013904223)&0xffffffff;k=state%(j+1);order[k],order[j]=order[j],order[k]\n roles={g:(i,pattern[i%len(pattern)]) for i,g in enumerate(order)}\n return roles,state,order\n\ndef solve(A,b):\n n=len(b);M=[list(row)+[rhs]for row,rhs in zip(A,b)];piv=[];rank=0\n for j in range(n):\n  candidates=[i for i in range(rank,n)if M[i][j]]\n  if not candidates:continue\n  k=max(candidates,key=lambda i:abs(M[i][j]));M[rank],M[k]=M[k],M[rank];v=M[rank][j];M[rank]=[x/v for x in M[rank]]\n  for i in range(n):\n   if i!=rank:\n    v=M[i][j];M[i]=[a-v*b for a,b in zip(M[i],M[rank])]\n  piv.append(j);rank+=1\n x=[F(0)]*n\n for i,j in enumerate(piv):x[j]=M[i][-1]\n null=[]\n for j in range(n):\n  if j not in piv:\n   v=[F(0)]*n;v[j]=F(1)\n   for i,k in enumerate(piv):v[k]=-M[i][j]\n   null.append(v)\n return x,rank,null\n\ndef dot(a,b):return sum((x*y for x,y in zip(a,b)),F(0))\n\ndef fit(rows,method,lam=F(0),minleaf=1,binary=False):\n use=[r for r in rows if r['role']=='train'and r['w']>0 and r['y']is not None and None not in r['x']];p=len(rows[0]['x'])if rows else 0\n if not use:return dict(defined=False,pred=[None]*len(rows),raw=[None]*len(rows),train=[],invariant=[None]*len(rows))\n mass=sum(r['w']for r in use);mu=[sum(r['w']*r['x'][j]for r in use)/mass for j in range(p)];scale=[max(r['x'][j]for r in use)-min(r['x'][j]for r in use)or F(1)for j in range(p)];mean=sum(r['w']*r['y']for r in use)/mass;model={};z=lambda r:[F(1)]+[(x-m)/s for x,m,s in zip(r['x'],mu,scale)]\n if method=='constant':model=dict(mean=mean,parameterCount=1,rank=1,unique=True)\n elif method=='ridge':\n  vectors=[z(r)for r in use];n=p+1;A=[[sum(r['w']*xx[j]*xx[k]for r,xx in zip(use,vectors))/mass+(lam if j==k and j>0 else F(0))for k in range(n)]for j in range(n)];b=[sum(r['w']*r['y']*xx[j]for r,xx in zip(use,vectors))/mass for j in range(n)];theta,rank,null=solve(A,b);objective=sum(r['w']*(dot(xx,theta)-r['y'])**2 for r,xx in zip(use,vectors))/(2*mass)+lam*sum(x*x for x in theta[1:])/2;model=dict(lambdaValue=lam,theta=theta,rank=rank,unique=rank==n,nullspace=null,minimumObjective=objective,parameterCount=n)\n else:\n  best=None;total=sum(r['w']*r['y']for r in use);total2=sum(r['w']*r['y']**2 for r in use);base=total2-total**2/mass\n  for j in range(p):\n   ordered=sorted(enumerate(use),key=lambda v:(v[1]['x'][j],v[0]));leftW=F(0);leftS=F(0)\n   for i,(_idx,r)in enumerate(ordered[:-1]):\n    leftW+=r['w'];leftS+=r['w']*r['y'];rightW=mass-leftW\n    if i+1<minleaf or len(use)-i-1<minleaf or r['x'][j]==ordered[i+1][1]['x'][j]:continue\n    SSE=total2-leftS**2/leftW-(total-leftS)**2/rightW\n    if best is None or SSE<best['weightedSSE']:best=dict(feature=j,threshold=(r['x'][j]+ordered[i+1][1]['x'][j])/2,leftMean=leftS/leftW,rightMean=(total-leftS)/rightW,leftRows=i+1,rightRows=len(use)-i-1,leftWeight=leftW,rightWeight=rightW,weightedSSE=SSE)\n  model=dict(split=False,mean=mean,weightedSSE=base,trainingMSE=base/mass)if best is None or best['weightedSSE']>=base else dict(split=True,**best,trainingMSE=best['weightedSSE']/mass,improvement=(base-best['weightedSSE'])/mass)\n raw=[];invariant=[]\n for r in rows:\n  if None in r['x']:raw.append(None);invariant.append(None);continue\n  if method=='constant':v=mean;iv=True\n  elif method=='ridge':zz=z(r);v=dot(zz,model['theta']);iv=all(dot(zz,nn)==0 for nn in model['nullspace'])\n  else:v=(model['leftMean']if r['x'][model['feature']]<=model['threshold']else model['rightMean'])if model['split']else mean;iv=True\n  raw.append(v);invariant.append(iv)\n pred=[None if x is None else min(F(1),max(F(0),x))if binary else x for x in raw]\n return dict(defined=True,train=[r['id']for r in use],mass=mass,meanX=mu,scales=scale,model=model,pred=pred,raw=raw,invariant=invariant)\n\ndef risk(rows,pred,binary=False,threshold=F(1,2)):\n use=[(r,p)for r,p in zip(rows,pred)if r['w']>0 and r['y']is not None and p is not None and r['role']not in['excluded','unused']];mass=sum((r['w']for r,p in use),F(0));d=dict(rows=len(use),mass=mass)\n if not mass:\n  d.update({k:None for k in ['MSE','MAE','R2']+(['Brier','accuracy','balancedAccuracy','AUROC']if binary else[])});return d\n mean=sum(r['w']*r['y']for r,p in use)/mass;sse=sum(r['w']*(p-r['y'])**2 for r,p in use);sst=sum(r['w']*(r['y']-mean)**2 for r,p in use);d.update(meanY=mean,SSE=sse,SST=sst,MSE=sse/mass,MAE=sum(r['w']*abs(p-r['y'])for r,p in use)/mass,R2=1-sse/sst if sst else None)\n if binary:\n  weights=Counter();num=Counter()\n  for r,p in use:k=('T'if int(p>=threshold)==int(r['y'])else'F')+('P'if p>=threshold else'N');weights[k]+=r['w'];num[k]+=1\n  TP,FP,TN,FN=[weights[k]for k in ['TP','FP','TN','FN']];positive=TP+FN;negative=TN+FP;rate=lambda a,b:a/b if b else None;TPR=rate(TP,positive);TNR=rate(TN,negative)\n  # Pair enumeration is independent of the subject's score-tie-block formula.\n  negatives=[(r,p)for r,p in use if not r['y']];positives=[(r,p)for r,p in use if r['y']];wins=sum((a['w']*b['w']*(F(1)if pa>pb else F(1,2)if pa==pb else F(0))for a,pa in positives for b,pb in negatives),F(0))\n  d.update(Brier=d['MSE'],threshold=threshold,confusionMass={k:weights[k]for k in ['TP','FP','TN','FN']},confusionRows={k:num[k]for k in ['TP','FP','TN','FN']},positiveMass=positive,negativeMass=negative,accuracy=(TP+TN)/mass,positiveRecall=TPR,negativeRecall=TNR,precision=rate(TP,TP+FP),F1=rate(2*TP,2*TP+FP+FN),balancedAccuracy=(TPR+TNR)/2 if TPR is not None and TNR is not None else None,AUROC=rate(wins,positive*negative))\n return d\n\nNATIVE_SHA256={'actual1599-red-wine-original12-fields.csv': '77e9ac73115930d6c43983333a5a57940deefc493affeb17aca478c09c5f6e00', 'actual4898-white-wine-original12-fields.csv': '50d810bbb42b9cc3e87fa4c27a4c0f168e72da09dd812863425ca3873fec28ef', 'actual3613-NLS-original52-fields.csv': '6e1e1895558795435b65f8634252a7589865273a0e69adbd715fcfa04a3c11a1', 'actual3150-churn-original14-fields.csv': '1c0753e434226e769d1015c922121a7d8967df66014e057c4f7543e490f11764'}\n\ndef read_sources(directory,seed):\n def read(name):\n  p=directory/name\n  if hashlib.sha256(p.read_bytes()).hexdigest()!=NATIVE_SHA256[name]:raise ValueError('Native file hash differs: '+name)\n  with p.open(encoding='utf8',newline='')as f:return list(csv.DictReader(f))\n sources={};wine=[]\n for typ,n in [('red',1599),('white',4898)]:\n  table=read(f'actual{n}-{typ}-wine-original12-fields.csv');assert len(table)==n;features=[k for k in table[0]if k not in ['sourceRow','wineType','quality']];assert len(features)==11\n  for r in table:\n   i=int(r['sourceRow']);red='1'if typ=='red'else'0';nativeX=[r[k]for k in features];wine.append(dict(id=f'wine-{typ}-row:{i}',sourceRow=f'{typ}:{i}',originalID=None,group=fingerprint('wine-predictors',[red]+nativeX),cohort=typ,x=list(map(Q,nativeX+[red])),y=Q(r['quality'])))\n sources['country']=wine\n table=read('actual3613-NLS-original52-fields.csv');assert len(table)==3613;sources['person']=[dict(id='nls-row:'+r['sourceRow'],sourceRow=int(r['sourceRow']),originalID=r['id'],group='nls-id:'+r['id'],cohort='schooling-over12'if Q(r['ed76'])>12 else'schooling-at-most12',x=[Q(r['ed76']),Q(r['age76'])],y=Q(r['lwage76']))for r in table]\n table=read('actual3150-churn-original14-fields.csv');assert len(table)==3150;predictors=[k for k in table[0]if k not in ['sourceRow','Churn']];assert len(predictors)==13;sources['company']=[dict(id='customer-row:'+r['sourceRow'],sourceRow=int(r['sourceRow']),originalID=None,group=fingerprint('customer-predictors',[r[k]for k in predictors]),cohort='pay-as-you-go'if r['Tariff Plan']=='1'else'contractual'if r['Tariff Plan']=='2'else'other-native-tariff',x=[Q(r[k])for k in ['Call  Failure','Subscription  Length','Seconds of Use','Age']],y=Q(r['Churn']))for r in table]\n for kind,rows in sources.items():\n  assignments,state,order=split(rows,seed)\n  for r in rows:\n   rank,planned=assignments[r['group']];r.update(w=F(1),splitRank=rank,plannedRole=planned,eligible=r['y']is not None and None not in r['x']);r['role']=planned if r['eligible']else'excluded'\n return sources\n# New ML22 fixed-profile kernels. The public Fraction fitting/source readers are\n# copied by value above this file by the standalone builder; never imported.\ndef fixed_rows(data, prediction_key=None):\n out=[]\n for i,a in enumerate(data):\n  w=Q(a.get('weight','1'))\n  if w is None or w<0:raise ValueError('negative-weight' if w is not None and w<0 else 'missing-weight')\n  out.append(dict(id=a.get('id',str(i)),group=a.get('group',a.get('id',str(i))),cohort=a.get('cohort','all'),role=a.get('role','train'),w=w,x=[Q(v)for v in a.get('x',[])],y=Q(a.get('y'))))\n return out\n\ndef weighted_pair(rows,A,B):\n use=[(r,a,b)for r,a,b in zip(rows,A,B)if r['w']>0 and r['y']is not None and a is not None and b is not None and r['role']not in ['excluded','unused']]\n mass=sum((r['w']for r,a,b in use),F(0));records=[];groups={}\n for r,a,b in use:\n  la=(a-r['y'])**2;lb=(b-r['y'])**2;d=la-lb\n  records.append(dict(id=r['id'],group=r['group'],weight=r['w'],lossA=la,lossB=lb,difference=d))\n  g=groups.setdefault(r['group'],dict(group=r['group'],rows=0,mass=F(0),sum=F(0)));g['rows']+=1;g['mass']+=r['w'];g['sum']+=r['w']*d\n total=sum((g['sum']for g in groups.values()),F(0));mean=total/mass if mass else None;G=len(groups)\n for g in groups.values():g['leaveOut']=(total-g['sum'])/(mass-g['mass'])if mass>g['mass']else None\n leaves=[g['leaveOut']for g in groups.values()if g['leaveOut']is not None]\n proxy=F(G-1,G)*sum((v-sum(leaves,F(0))/G)**2 for v in leaves) if G>1 and len(leaves)==G else None\n return dict(rows=len(use),mass=mass,groupCount=G,meanDifference=mean,minimumLeaveOut=min(leaves)if leaves else None,maximumLeaveOut=max(leaves)if leaves else None,varianceProxy=proxy,groups=list(groups.values()),records=records)\n\ndef run_selection(rows,candidates,criterion,required,binary=False):\n results=[]\n for c,pred in candidates:\n  val=[dict(r,role='excluded')if r['role']!='validation'else r for r in rows]\n  test=[dict(r,role='excluded')if r['role']!='test'else r for r in rows]\n  v=risk(val,pred,binary);t=risk(test,pred,binary);cohort={g:risk([dict(r,role='excluded')if r['role']!='validation'or r['cohort']!=g else r for r in rows],pred,binary)for g in required}\n  values=[cohort[g]['MSE']for g in required]\n  score=v['MSE']if criterion=='mean'else max(values)if values and None not in values else None\n  results.append(dict(id=c,criterion=score,validation=v,test=t,cohorts=cohort))\n eligible=[(i,r['criterion'])for i,r in enumerate(results)if r['criterion']is not None]\n chosen=min(eligible,key=lambda t:(t[1],t[0]))[0]if eligible else None\n return dict(criterion=criterion,selected=results[chosen]['id']if chosen is not None else None,selectedIndex=chosen,candidates=results)\n\ndef fixed_operation(api,a):\n if api=='realdata':\n  kind=a['kind'];rows=read_sources(Path(__file__).parent/'data',a.get('seed',20261104))[kind];binary=kind=='company'\n  defs=[('constant','constant',F(0)),('ridge:1/100','ridge',F(1,100)),('ridge:1/10','ridge',F(1,10)),('ridge:1','ridge',F(1)),('one-split-stump','stump',F(0))]\n  fits=[fit(rows,method,lam,5,binary)for _,method,lam in defs]\n  selection=run_selection(rows,[(d[0],f['pred'])for d,f in zip(defs,fits)],a.get('criterion','mean'),list(dict.fromkeys(r['cohort']for r in rows)),binary)\n  chosen=selection['selectedIndex'];best=fits[chosen];base=fits[0]\n  test=[dict(r,role='excluded')if r['role']!='test'else r for r in rows]\n  paired=weighted_pair(test,best['pred'],base['pred'])\n  records=[dict(id=r['id'],sourceRow=r.get('sourceRow'),originalID=r.get('originalID'),group=r['group'],cohort=r['cohort'],plannedRole=r['plannedRole'],role=r['role'],eligible=r['eligible'],y=r['y'],baselinePrediction=base['pred'][i],selectedPrediction=best['pred'][i],selectedRawPrediction=best['raw'][i],queryInvariant=best['invariant'][i])for i,r in enumerate(rows)]\n  return dict(kind=kind,nativeRows=len(rows),eligibleRows=sum(r['eligible']for r in rows),selection=selection,models=[dict(id=d[0],train=f['train'],mass=f.get('mass'),meanX=f.get('meanX'),scales=f.get('scales'),model=f.get('model'))for d,f in zip(defs,fits)],paired=paired,records=records)\n rows=fixed_rows(a.get('rows',[]));binary=a.get('task')=='binary'\n if api=='split':\n  assignment,state,order=split(rows,a.get('seed',0));records=[dict(id=r['id'],group=r['group'],rank=assignment[r['group']][0],role=assignment[r['group']][1])for r in rows]\n  return dict(state=state,groupOrder=order,records=records,groupCount=len(order))\n if api=='fit':return fit(rows,a.get('method','constant'),Q(a.get('lambda','0')),a.get('minLeafRows',1),binary)\n if api=='evaluate':\n  pred=[Q(r.get('prediction'))for r in a['rows']];threshold=Q(a.get('threshold','1/2'));rr=risk(rows,pred,binary,threshold)\n  records=[]\n  for r,p in zip(rows,pred):\n   valid=r['w']>0 and r['y']is not None and p is not None and r['role']not in ['excluded','unused']\n   records.append(dict(id=r['id'],weight=r['w'],y=r['y'],prediction=p,eligible=valid,loss=(p-r['y'])**2 if valid else None,correct=dict(defined=valid and binary,value=bool(int(p>=threshold)==int(r['y']))if valid and binary else None)))\n  return dict(metrics=rr,records=records)\n if api=='select':return run_selection(rows,[(c['id'],list(map(Q,c['predictions'])))for c in a['candidates']],a.get('criterion','mean'),a.get('requiredCohorts',list(dict.fromkeys(r['cohort']for r in rows))),binary)\n if api=='paired':return weighted_pair(rows,[Q(r.get('predictionA'))for r in a['rows']],[Q(r.get('predictionB'))for r in a['rows']])\n raise ValueError('unknown-api')\n\ndef report_values(api,z):\n summary=[];series=[]\n def add(k,v,u='dimensionless'):summary.append((k,v,u))\n if api=='split':\n  add('groups',z['groupCount'],'groups');add('rows',len(z['records']),'rows');add('finalState',z['state'],'unsigned 32-bit state')\n  series=[('planned role code',[(i,F({'test':0,'validation':1,'train':2}[r['role']]))for i,r in enumerate(z['records'])])]\n elif api=='fit':\n  add('defined',z['defined']);add('trainingRows',len(z['train']),'rows');add('trainingMass',z.get('mass'),'analysis weight mass')\n  model=z.get('model',{});add('modelRank',model.get('rank'),'parameters');add('threshold',model.get('threshold'),'constructed feature units');add('minimumObjective',model.get('minimumObjective'),'constructed squared outcome units')\n  series=[('prediction',list(enumerate(z['pred'])))];\n  if model.get('theta')is not None:\n   for i,v in enumerate(model['theta']):add('theta'+str(i),v,'constructed outcome units per standardized coordinate')\n elif api=='evaluate':\n  for k in ['rows','mass','MSE','MAE','R2','Brier','accuracy','positiveRecall','negativeRecall','precision','F1','balancedAccuracy','AUROC']: \n   if k in z['metrics']:add(k,z['metrics'][k],'rows'if k=='rows'else'analysis weight mass'if k=='mass'else FIXED['unit']if k in ['MSE','Brier']else('probability-score units'if FIXED['input'].get('task')=='binary'else'constructed outcome units')if k=='MAE'else'dimensionless')\n  series=[('squared loss',[(i,r['loss'])for i,r in enumerate(z['records'])])]\n elif api=='select':\n  add('selectedIndex',z['selectedIndex'],'zero-based candidate index')\n  for i,c in enumerate(z['candidates']):add('criterion'+str(i),c['criterion'],FIXED['unit']);add('testMSE'+str(i),c['test']['MSE'],FIXED['unit'])\n  series=[('validation criterion',[(i,c['criterion'])for i,c in enumerate(z['candidates'])]),('test MSE',[(i,c['test']['MSE'])for i,c in enumerate(z['candidates'])])]\n elif api=='paired':\n  for k in ['rows','mass','groupCount','meanDifference','minimumLeaveOut','maximumLeaveOut','varianceProxy']:add(k,z[k],'rows'if k=='rows'else'groups'if k=='groupCount'else'analysis weight mass'if k=='mass'else FIXED['unit']+' squared'if k=='varianceProxy'else FIXED['unit'])\n  series=[('loss A minus loss B',[(i,r['difference'])for i,r in enumerate(z['records'])])]\n elif api=='realdata':\n  add('nativeRows',z['nativeRows'],'native records');add('eligibleRows',z['eligibleRows'],'complete records');add('selectedIndex',z['selection']['selectedIndex'],'zero-based candidate index')\n  for i,c in enumerate(z['selection']['candidates']):add('validationMSE'+str(i),c['validation']['MSE'],FIXED['unit']);add('testMSE'+str(i),c['test']['MSE'],FIXED['unit'])\n  for k in ['meanDifference','minimumLeaveOut','maximumLeaveOut','varianceProxy']:add(k,z['paired'][k],FIXED['unit']+' squared'if k=='varianceProxy'else FIXED['unit'])\n  best=z['selection']['candidates'][z['selection']['selectedIndex']]['test']\n  for k in ['accuracy','positiveRecall','negativeRecall','precision','balancedAccuracy','AUROC']:\n   if k in best:add(k,best[k])\n  series=[('validation MSE',[(i,c['validation']['MSE'])for i,c in enumerate(z['selection']['candidates'])]),('test MSE',[(i,c['test']['MSE'])for i,c in enumerate(z['selection']['candidates'])])]\n return summary,series\n\n\ndef fixed_svg(points,title):\n good=[p for p in points if p['y'] is not None];xx=[float(p['x'])for p in good];yy=[float(p['y'])for p in good];xmin=min(xx)if xx else 0;xmax=max(xx)if xx else 1;ymin=min([0]+yy);ymax=max([0]+yy)\n if xmin==xmax:xmin-=.5;xmax+=.5\n if ymin==ymax:ymin-=.5;ymax+=.5\n pad=(ymax-ymin)*.08;ymin-=pad;ymax+=pad;X=lambda x:82+(float(x)-xmin)/(xmax-xmin)*608;Y=lambda y:354-(float(y)-ymin)/(ymax-ymin)*290;e=html.escape\n out=['<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"720\" height=\"480\" viewBox=\"0 0 720 480\" role=\"img\" aria-label=\"'+e(title)+'\"><rect width=\"720\" height=\"480\" fill=\"white\"/><g font-family=\"Arial,sans-serif\" font-size=\"13\" fill=\"#18232f\"><text x=\"360\" y=\"25\" text-anchor=\"middle\">'+e(title)+'</text>']\n for j in range(5):\n  y=ymin+(ymax-ymin)*j/4;x=xmin+(xmax-xmin)*j/4;out.append('<line x1=\"82\" y1=\"'+str(Y(y))+'\" x2=\"690\" y2=\"'+str(Y(y))+'\" stroke=\"#e2e8f0\"/><text x=\"73\" y=\"'+str(Y(y)+4)+'\" text-anchor=\"end\">'+format(y,'.3g')+'</text><text x=\"'+str(X(x))+'\" y=\"380\" text-anchor=\"middle\">'+format(x,'.3g')+'</text>')\n series=list(dict.fromkeys(p['series']for p in good))\n for j,s in enumerate(series):\n  pp=[p for p in good if p['series']==s];color=['#0f766e','#c76622','#4f46e5','#b23857'][j%4]\n  for p in pp:out.append('<circle cx=\"'+format(X(p['x']),'.6f')+'\" cy=\"'+format(Y(p['y']),'.6f')+'\" r=\"2.6\" fill=\"'+color+'\"><title>'+e(s+': '+str(p['y']))+'</title></circle>')\n  out.append('<text x=\"'+str(82+(j%2)*310)+'\" y=\"'+str(432+(j//2)*23)+'\" fill=\"'+color+'\">'+e(s)+'</text>')\n out.append('<text x=\"360\" y=\"405\" text-anchor=\"middle\">Declared record / candidate index; units in summary</text></g></svg>');return''.join(out)\n\nFIXED={'api': 'evaluate', 'variant': 'weighted-AUC-tie', 'title': 'Weighted AUC with a positive-negative score tie', 'input': {'task': 'binary', 'rows': [{'id': 'p', 'y': '1', 'prediction': '4/5', 'weight': '2'}, {'id': 'n1', 'y': '0', 'prediction': '3/10'}, {'id': 'n2', 'y': '0', 'prediction': '4/5'}]}, 'unit': 'Squared probability-score units; one-component Brier loss', 'titleI18n': {'ko': '양성·음성 점수 동률의 가중 AUC', 'en': 'Weighted AUC with a positive-negative score tie'}}\n\nOUT=Path(sys.argv[1]);OUT.mkdir(parents=True,exist_ok=False)\nresult=fixed_operation(FIXED['api'],FIXED['input']);summary,series=report_values(FIXED['api'],result)\ndef encode(v):\n if isinstance(v,F):return str(v)\n if isinstance(v,dict):return{k:encode(x)for k,x in v.items()}\n if isinstance(v,(list,tuple)):return[encode(x)for x in v]\n return v\n(OUT/'full.json').write_text(json.dumps(dict(arithmetic='Exact rational author implementation; factual rows, declared group split and finite five-candidate comparison',result=encode(result)),ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\nsummaryRows=[dict(metric=m,value=''if v is None else str(int(v))if isinstance(v,bool)else str(v),unit=u,defined=int(v is not None))for m,v,u in summary]\npoints=[dict(series=name,index=i,x=str(x),y=''if y is None else str(y),defined=int(y is not None))for name,pp in series for i,(x,y)in enumerate(pp)]\nfor name,rows in [('summary',summaryRows),('plot-points',points)]:\n with(OUT/(name+'.csv')).open('w',encoding='utf8',newline='')as f:writer=csv.DictWriter(f,fieldnames=list(rows[0]));writer.writeheader();writer.writerows(rows)\n(OUT/'plot.svg').write_text(fixed_svg([dict(p,x=number(p['x']),y=None if not p['defined']else number(p['y']))for p in points],FIXED['title']),encoding='utf8');print(FIXED['api']+'/'+FIXED['variant'])\n",
        "returnCode": 0,
        "stdout": "evaluate/weighted-AUC-tie\r\n",
        "stderr": "",
        "diagnosticScope": "Public projection omits private absolute-path/traceback frames; actual exit and warnings/reason retained. Raw complete streams and commands in private execution proof.",
        "resultFolder": "ml22-code/runs/python-evaluate-weighted-AUC-tie",
        "kind": null,
        "inputFiles": [
          {
            "file": "ml22-code/evaluate-weighted-AUC-tie-input.json",
            "sha256": "1268c9008fa9802867bb14729863f3bccbedd233243e96e6f2ade25c1c552dac",
            "scope": "Complete fixed literal input; program embeds the same values"
          }
        ],
        "files": [
          {
            "file": "ml22-code/runs/python-evaluate-weighted-AUC-tie/full.json",
            "sha256": "a5a604a9c30838aa36925a7a1f032087a774135f74ff62f3473eefc61461a27d",
            "bytes": 1654
          },
          {
            "file": "ml22-code/runs/python-evaluate-weighted-AUC-tie/plot-points.csv",
            "sha256": "db6c0d49f448bc479c75dbc60789ee8946fecb20cb6e2f3ccbf8da281b5012c2",
            "bytes": 103
          },
          {
            "file": "ml22-code/runs/python-evaluate-weighted-AUC-tie/plot.svg",
            "sha256": "30e712344cb652c3d3996ac1d3357960cabfae1874133bd30443fd2df6531e54",
            "bytes": 1691
          },
          {
            "file": "ml22-code/runs/python-evaluate-weighted-AUC-tie/summary.csv",
            "sha256": "fbc7f0abcec156dee815bc378f157d87273e4a8012ecafb3746a1bcac97d2474",
            "bytes": 501
          }
        ],
        "summaryRows": [
          {
            "metric": "rows",
            "value": "3.0",
            "unit": "rows",
            "defined": "true",
            "rawValue": "3",
            "arithmetic": "Exact Fraction",
            "exactFraction": "3",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "mass",
            "value": "4.0",
            "unit": "analysis weight mass",
            "defined": "true",
            "rawValue": "4",
            "arithmetic": "Exact Fraction",
            "exactFraction": "4",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "MSE",
            "value": "0.2025",
            "unit": "Squared probability-score units; one-component Brier loss",
            "defined": "true",
            "rawValue": "81/400",
            "arithmetic": "Exact Fraction",
            "exactFraction": "81/400",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "MAE",
            "value": "0.375",
            "unit": "probability-score units",
            "defined": "true",
            "rawValue": "3/8",
            "arithmetic": "Exact Fraction",
            "exactFraction": "3/8",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "R2",
            "value": "0.19",
            "unit": "dimensionless",
            "defined": "true",
            "rawValue": "19/100",
            "arithmetic": "Exact Fraction",
            "exactFraction": "19/100",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "Brier",
            "value": "0.2025",
            "unit": "Squared probability-score units; one-component Brier loss",
            "defined": "true",
            "rawValue": "81/400",
            "arithmetic": "Exact Fraction",
            "exactFraction": "81/400",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "accuracy",
            "value": "0.75",
            "unit": "dimensionless",
            "defined": "true",
            "rawValue": "3/4",
            "arithmetic": "Exact Fraction",
            "exactFraction": "3/4",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "positiveRecall",
            "value": "1.0",
            "unit": "dimensionless",
            "defined": "true",
            "rawValue": "1",
            "arithmetic": "Exact Fraction",
            "exactFraction": "1",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "negativeRecall",
            "value": "0.5",
            "unit": "dimensionless",
            "defined": "true",
            "rawValue": "1/2",
            "arithmetic": "Exact Fraction",
            "exactFraction": "1/2",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "precision",
            "value": "0.6666666666666666",
            "unit": "dimensionless",
            "defined": "true",
            "rawValue": "2/3",
            "arithmetic": "Exact Fraction",
            "exactFraction": "2/3",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "F1",
            "value": "0.8",
            "unit": "dimensionless",
            "defined": "true",
            "rawValue": "4/5",
            "arithmetic": "Exact Fraction",
            "exactFraction": "4/5",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "balancedAccuracy",
            "value": "0.75",
            "unit": "dimensionless",
            "defined": "true",
            "rawValue": "3/4",
            "arithmetic": "Exact Fraction",
            "exactFraction": "3/4",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "AUROC",
            "value": "0.75",
            "unit": "dimensionless",
            "defined": "true",
            "rawValue": "3/4",
            "arithmetic": "Exact Fraction",
            "exactFraction": "3/4",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          }
        ],
        "plotRows": [
          {
            "series": "squared loss",
            "index": "0",
            "x": "0",
            "y": "1/25",
            "defined": true,
            "xExact": "0",
            "yExact": "1/25"
          },
          {
            "series": "squared loss",
            "index": "1",
            "x": "1",
            "y": "9/100",
            "defined": true,
            "xExact": "1",
            "yExact": "9/100"
          },
          {
            "series": "squared loss",
            "index": "2",
            "x": "2",
            "y": "16/25",
            "defined": true,
            "xExact": "2",
            "yExact": "16/25"
          }
        ],
        "plotFile": "ml22-code/runs/python-evaluate-weighted-AUC-tie/plot.svg",
        "fullResultFile": "ml22-code/runs/python-evaluate-weighted-AUC-tie/full.json",
        "arithmeticScope": "Python exact rational versus base-R approximate floating algebra; copied author kernels, not independent oracle.",
        "plotScope": "Original scatter vectors plot every defined declared comparison point, with missing points omitted. Source profiles show candidate risks; all source records remain in the full result and source CSV files.",
        "reproductionScope": "Standalone literal program plus four native CSV files for factual source profiles. No answer/engine/checker imports."
      },
      "no-predicted-positive-missing-label": {
        "api": "evaluate",
        "variant": "no-predicted-positive-missing-label",
        "language": "python",
        "title": "No positive predictions and a missing label",
        "titleI18n": {
          "ko": "양성 예측 없음과 결측 정답",
          "en": "No positive predictions and a missing label"
        },
        "input": {
          "task": "binary",
          "rows": [
            {
              "id": "n",
              "y": "0",
              "prediction": "0"
            },
            {
              "id": "p",
              "y": "1",
              "prediction": "1/4"
            },
            {
              "id": "unknown",
              "y": null,
              "prediction": "0"
            }
          ]
        },
        "expectedFailure": false,
        "codeFile": "ml22-code/evaluate-no-predicted-positive-missing-label.py",
        "codeSHA256": "e8c1110a48dffece3e9a3071a05abf1a6a5488eec3fd48b512b7a1b799e09bbe",
        "code": "# ML22 standalone fixed literal. Attribution and arithmetic scope in README.\nimport csv,hashlib,html,json,math,sys,time\nfrom pathlib import Path\nfrom fractions import Fraction as F\nfrom collections import Counter\nsys.set_int_max_str_digits(200000)\nnumber=lambda v:F(str(v))\ndef Q(x):return None if x is None or x in ('','.') else F(str(x))\n\ndef canonical(v):return None if Q(v) is None else str(Q(v))\n\ndef fingerprint(tag,values):return tag+':'+hashlib.sha256(json.dumps([canonical(x)for x in values],separators=(',',':')).encode()).hexdigest()\n\ndef split(rows,seed=20261104,pattern=('test','validation','train','train')):\n order=sorted(set(r['group'] for r in rows));state=seed\n for j in range(len(order)-1,0,-1):state=(1664525*state+1013904223)&0xffffffff;k=state%(j+1);order[k],order[j]=order[j],order[k]\n roles={g:(i,pattern[i%len(pattern)]) for i,g in enumerate(order)}\n return roles,state,order\n\ndef solve(A,b):\n n=len(b);M=[list(row)+[rhs]for row,rhs in zip(A,b)];piv=[];rank=0\n for j in range(n):\n  candidates=[i for i in range(rank,n)if M[i][j]]\n  if not candidates:continue\n  k=max(candidates,key=lambda i:abs(M[i][j]));M[rank],M[k]=M[k],M[rank];v=M[rank][j];M[rank]=[x/v for x in M[rank]]\n  for i in range(n):\n   if i!=rank:\n    v=M[i][j];M[i]=[a-v*b for a,b in zip(M[i],M[rank])]\n  piv.append(j);rank+=1\n x=[F(0)]*n\n for i,j in enumerate(piv):x[j]=M[i][-1]\n null=[]\n for j in range(n):\n  if j not in piv:\n   v=[F(0)]*n;v[j]=F(1)\n   for i,k in enumerate(piv):v[k]=-M[i][j]\n   null.append(v)\n return x,rank,null\n\ndef dot(a,b):return sum((x*y for x,y in zip(a,b)),F(0))\n\ndef fit(rows,method,lam=F(0),minleaf=1,binary=False):\n use=[r for r in rows if r['role']=='train'and r['w']>0 and r['y']is not None and None not in r['x']];p=len(rows[0]['x'])if rows else 0\n if not use:return dict(defined=False,pred=[None]*len(rows),raw=[None]*len(rows),train=[],invariant=[None]*len(rows))\n mass=sum(r['w']for r in use);mu=[sum(r['w']*r['x'][j]for r in use)/mass for j in range(p)];scale=[max(r['x'][j]for r in use)-min(r['x'][j]for r in use)or F(1)for j in range(p)];mean=sum(r['w']*r['y']for r in use)/mass;model={};z=lambda r:[F(1)]+[(x-m)/s for x,m,s in zip(r['x'],mu,scale)]\n if method=='constant':model=dict(mean=mean,parameterCount=1,rank=1,unique=True)\n elif method=='ridge':\n  vectors=[z(r)for r in use];n=p+1;A=[[sum(r['w']*xx[j]*xx[k]for r,xx in zip(use,vectors))/mass+(lam if j==k and j>0 else F(0))for k in range(n)]for j in range(n)];b=[sum(r['w']*r['y']*xx[j]for r,xx in zip(use,vectors))/mass for j in range(n)];theta,rank,null=solve(A,b);objective=sum(r['w']*(dot(xx,theta)-r['y'])**2 for r,xx in zip(use,vectors))/(2*mass)+lam*sum(x*x for x in theta[1:])/2;model=dict(lambdaValue=lam,theta=theta,rank=rank,unique=rank==n,nullspace=null,minimumObjective=objective,parameterCount=n)\n else:\n  best=None;total=sum(r['w']*r['y']for r in use);total2=sum(r['w']*r['y']**2 for r in use);base=total2-total**2/mass\n  for j in range(p):\n   ordered=sorted(enumerate(use),key=lambda v:(v[1]['x'][j],v[0]));leftW=F(0);leftS=F(0)\n   for i,(_idx,r)in enumerate(ordered[:-1]):\n    leftW+=r['w'];leftS+=r['w']*r['y'];rightW=mass-leftW\n    if i+1<minleaf or len(use)-i-1<minleaf or r['x'][j]==ordered[i+1][1]['x'][j]:continue\n    SSE=total2-leftS**2/leftW-(total-leftS)**2/rightW\n    if best is None or SSE<best['weightedSSE']:best=dict(feature=j,threshold=(r['x'][j]+ordered[i+1][1]['x'][j])/2,leftMean=leftS/leftW,rightMean=(total-leftS)/rightW,leftRows=i+1,rightRows=len(use)-i-1,leftWeight=leftW,rightWeight=rightW,weightedSSE=SSE)\n  model=dict(split=False,mean=mean,weightedSSE=base,trainingMSE=base/mass)if best is None or best['weightedSSE']>=base else dict(split=True,**best,trainingMSE=best['weightedSSE']/mass,improvement=(base-best['weightedSSE'])/mass)\n raw=[];invariant=[]\n for r in rows:\n  if None in r['x']:raw.append(None);invariant.append(None);continue\n  if method=='constant':v=mean;iv=True\n  elif method=='ridge':zz=z(r);v=dot(zz,model['theta']);iv=all(dot(zz,nn)==0 for nn in model['nullspace'])\n  else:v=(model['leftMean']if r['x'][model['feature']]<=model['threshold']else model['rightMean'])if model['split']else mean;iv=True\n  raw.append(v);invariant.append(iv)\n pred=[None if x is None else min(F(1),max(F(0),x))if binary else x for x in raw]\n return dict(defined=True,train=[r['id']for r in use],mass=mass,meanX=mu,scales=scale,model=model,pred=pred,raw=raw,invariant=invariant)\n\ndef risk(rows,pred,binary=False,threshold=F(1,2)):\n use=[(r,p)for r,p in zip(rows,pred)if r['w']>0 and r['y']is not None and p is not None and r['role']not in['excluded','unused']];mass=sum((r['w']for r,p in use),F(0));d=dict(rows=len(use),mass=mass)\n if not mass:\n  d.update({k:None for k in ['MSE','MAE','R2']+(['Brier','accuracy','balancedAccuracy','AUROC']if binary else[])});return d\n mean=sum(r['w']*r['y']for r,p in use)/mass;sse=sum(r['w']*(p-r['y'])**2 for r,p in use);sst=sum(r['w']*(r['y']-mean)**2 for r,p in use);d.update(meanY=mean,SSE=sse,SST=sst,MSE=sse/mass,MAE=sum(r['w']*abs(p-r['y'])for r,p in use)/mass,R2=1-sse/sst if sst else None)\n if binary:\n  weights=Counter();num=Counter()\n  for r,p in use:k=('T'if int(p>=threshold)==int(r['y'])else'F')+('P'if p>=threshold else'N');weights[k]+=r['w'];num[k]+=1\n  TP,FP,TN,FN=[weights[k]for k in ['TP','FP','TN','FN']];positive=TP+FN;negative=TN+FP;rate=lambda a,b:a/b if b else None;TPR=rate(TP,positive);TNR=rate(TN,negative)\n  # Pair enumeration is independent of the subject's score-tie-block formula.\n  negatives=[(r,p)for r,p in use if not r['y']];positives=[(r,p)for r,p in use if r['y']];wins=sum((a['w']*b['w']*(F(1)if pa>pb else F(1,2)if pa==pb else F(0))for a,pa in positives for b,pb in negatives),F(0))\n  d.update(Brier=d['MSE'],threshold=threshold,confusionMass={k:weights[k]for k in ['TP','FP','TN','FN']},confusionRows={k:num[k]for k in ['TP','FP','TN','FN']},positiveMass=positive,negativeMass=negative,accuracy=(TP+TN)/mass,positiveRecall=TPR,negativeRecall=TNR,precision=rate(TP,TP+FP),F1=rate(2*TP,2*TP+FP+FN),balancedAccuracy=(TPR+TNR)/2 if TPR is not None and TNR is not None else None,AUROC=rate(wins,positive*negative))\n return d\n\nNATIVE_SHA256={'actual1599-red-wine-original12-fields.csv': '77e9ac73115930d6c43983333a5a57940deefc493affeb17aca478c09c5f6e00', 'actual4898-white-wine-original12-fields.csv': '50d810bbb42b9cc3e87fa4c27a4c0f168e72da09dd812863425ca3873fec28ef', 'actual3613-NLS-original52-fields.csv': '6e1e1895558795435b65f8634252a7589865273a0e69adbd715fcfa04a3c11a1', 'actual3150-churn-original14-fields.csv': '1c0753e434226e769d1015c922121a7d8967df66014e057c4f7543e490f11764'}\n\ndef read_sources(directory,seed):\n def read(name):\n  p=directory/name\n  if hashlib.sha256(p.read_bytes()).hexdigest()!=NATIVE_SHA256[name]:raise ValueError('Native file hash differs: '+name)\n  with p.open(encoding='utf8',newline='')as f:return list(csv.DictReader(f))\n sources={};wine=[]\n for typ,n in [('red',1599),('white',4898)]:\n  table=read(f'actual{n}-{typ}-wine-original12-fields.csv');assert len(table)==n;features=[k for k in table[0]if k not in ['sourceRow','wineType','quality']];assert len(features)==11\n  for r in table:\n   i=int(r['sourceRow']);red='1'if typ=='red'else'0';nativeX=[r[k]for k in features];wine.append(dict(id=f'wine-{typ}-row:{i}',sourceRow=f'{typ}:{i}',originalID=None,group=fingerprint('wine-predictors',[red]+nativeX),cohort=typ,x=list(map(Q,nativeX+[red])),y=Q(r['quality'])))\n sources['country']=wine\n table=read('actual3613-NLS-original52-fields.csv');assert len(table)==3613;sources['person']=[dict(id='nls-row:'+r['sourceRow'],sourceRow=int(r['sourceRow']),originalID=r['id'],group='nls-id:'+r['id'],cohort='schooling-over12'if Q(r['ed76'])>12 else'schooling-at-most12',x=[Q(r['ed76']),Q(r['age76'])],y=Q(r['lwage76']))for r in table]\n table=read('actual3150-churn-original14-fields.csv');assert len(table)==3150;predictors=[k for k in table[0]if k not in ['sourceRow','Churn']];assert len(predictors)==13;sources['company']=[dict(id='customer-row:'+r['sourceRow'],sourceRow=int(r['sourceRow']),originalID=None,group=fingerprint('customer-predictors',[r[k]for k in predictors]),cohort='pay-as-you-go'if r['Tariff Plan']=='1'else'contractual'if r['Tariff Plan']=='2'else'other-native-tariff',x=[Q(r[k])for k in ['Call  Failure','Subscription  Length','Seconds of Use','Age']],y=Q(r['Churn']))for r in table]\n for kind,rows in sources.items():\n  assignments,state,order=split(rows,seed)\n  for r in rows:\n   rank,planned=assignments[r['group']];r.update(w=F(1),splitRank=rank,plannedRole=planned,eligible=r['y']is not None and None not in r['x']);r['role']=planned if r['eligible']else'excluded'\n return sources\n# New ML22 fixed-profile kernels. The public Fraction fitting/source readers are\n# copied by value above this file by the standalone builder; never imported.\ndef fixed_rows(data, prediction_key=None):\n out=[]\n for i,a in enumerate(data):\n  w=Q(a.get('weight','1'))\n  if w is None or w<0:raise ValueError('negative-weight' if w is not None and w<0 else 'missing-weight')\n  out.append(dict(id=a.get('id',str(i)),group=a.get('group',a.get('id',str(i))),cohort=a.get('cohort','all'),role=a.get('role','train'),w=w,x=[Q(v)for v in a.get('x',[])],y=Q(a.get('y'))))\n return out\n\ndef weighted_pair(rows,A,B):\n use=[(r,a,b)for r,a,b in zip(rows,A,B)if r['w']>0 and r['y']is not None and a is not None and b is not None and r['role']not in ['excluded','unused']]\n mass=sum((r['w']for r,a,b in use),F(0));records=[];groups={}\n for r,a,b in use:\n  la=(a-r['y'])**2;lb=(b-r['y'])**2;d=la-lb\n  records.append(dict(id=r['id'],group=r['group'],weight=r['w'],lossA=la,lossB=lb,difference=d))\n  g=groups.setdefault(r['group'],dict(group=r['group'],rows=0,mass=F(0),sum=F(0)));g['rows']+=1;g['mass']+=r['w'];g['sum']+=r['w']*d\n total=sum((g['sum']for g in groups.values()),F(0));mean=total/mass if mass else None;G=len(groups)\n for g in groups.values():g['leaveOut']=(total-g['sum'])/(mass-g['mass'])if mass>g['mass']else None\n leaves=[g['leaveOut']for g in groups.values()if g['leaveOut']is not None]\n proxy=F(G-1,G)*sum((v-sum(leaves,F(0))/G)**2 for v in leaves) if G>1 and len(leaves)==G else None\n return dict(rows=len(use),mass=mass,groupCount=G,meanDifference=mean,minimumLeaveOut=min(leaves)if leaves else None,maximumLeaveOut=max(leaves)if leaves else None,varianceProxy=proxy,groups=list(groups.values()),records=records)\n\ndef run_selection(rows,candidates,criterion,required,binary=False):\n results=[]\n for c,pred in candidates:\n  val=[dict(r,role='excluded')if r['role']!='validation'else r for r in rows]\n  test=[dict(r,role='excluded')if r['role']!='test'else r for r in rows]\n  v=risk(val,pred,binary);t=risk(test,pred,binary);cohort={g:risk([dict(r,role='excluded')if r['role']!='validation'or r['cohort']!=g else r for r in rows],pred,binary)for g in required}\n  values=[cohort[g]['MSE']for g in required]\n  score=v['MSE']if criterion=='mean'else max(values)if values and None not in values else None\n  results.append(dict(id=c,criterion=score,validation=v,test=t,cohorts=cohort))\n eligible=[(i,r['criterion'])for i,r in enumerate(results)if r['criterion']is not None]\n chosen=min(eligible,key=lambda t:(t[1],t[0]))[0]if eligible else None\n return dict(criterion=criterion,selected=results[chosen]['id']if chosen is not None else None,selectedIndex=chosen,candidates=results)\n\ndef fixed_operation(api,a):\n if api=='realdata':\n  kind=a['kind'];rows=read_sources(Path(__file__).parent/'data',a.get('seed',20261104))[kind];binary=kind=='company'\n  defs=[('constant','constant',F(0)),('ridge:1/100','ridge',F(1,100)),('ridge:1/10','ridge',F(1,10)),('ridge:1','ridge',F(1)),('one-split-stump','stump',F(0))]\n  fits=[fit(rows,method,lam,5,binary)for _,method,lam in defs]\n  selection=run_selection(rows,[(d[0],f['pred'])for d,f in zip(defs,fits)],a.get('criterion','mean'),list(dict.fromkeys(r['cohort']for r in rows)),binary)\n  chosen=selection['selectedIndex'];best=fits[chosen];base=fits[0]\n  test=[dict(r,role='excluded')if r['role']!='test'else r for r in rows]\n  paired=weighted_pair(test,best['pred'],base['pred'])\n  records=[dict(id=r['id'],sourceRow=r.get('sourceRow'),originalID=r.get('originalID'),group=r['group'],cohort=r['cohort'],plannedRole=r['plannedRole'],role=r['role'],eligible=r['eligible'],y=r['y'],baselinePrediction=base['pred'][i],selectedPrediction=best['pred'][i],selectedRawPrediction=best['raw'][i],queryInvariant=best['invariant'][i])for i,r in enumerate(rows)]\n  return dict(kind=kind,nativeRows=len(rows),eligibleRows=sum(r['eligible']for r in rows),selection=selection,models=[dict(id=d[0],train=f['train'],mass=f.get('mass'),meanX=f.get('meanX'),scales=f.get('scales'),model=f.get('model'))for d,f in zip(defs,fits)],paired=paired,records=records)\n rows=fixed_rows(a.get('rows',[]));binary=a.get('task')=='binary'\n if api=='split':\n  assignment,state,order=split(rows,a.get('seed',0));records=[dict(id=r['id'],group=r['group'],rank=assignment[r['group']][0],role=assignment[r['group']][1])for r in rows]\n  return dict(state=state,groupOrder=order,records=records,groupCount=len(order))\n if api=='fit':return fit(rows,a.get('method','constant'),Q(a.get('lambda','0')),a.get('minLeafRows',1),binary)\n if api=='evaluate':\n  pred=[Q(r.get('prediction'))for r in a['rows']];threshold=Q(a.get('threshold','1/2'));rr=risk(rows,pred,binary,threshold)\n  records=[]\n  for r,p in zip(rows,pred):\n   valid=r['w']>0 and r['y']is not None and p is not None and r['role']not in ['excluded','unused']\n   records.append(dict(id=r['id'],weight=r['w'],y=r['y'],prediction=p,eligible=valid,loss=(p-r['y'])**2 if valid else None,correct=dict(defined=valid and binary,value=bool(int(p>=threshold)==int(r['y']))if valid and binary else None)))\n  return dict(metrics=rr,records=records)\n if api=='select':return run_selection(rows,[(c['id'],list(map(Q,c['predictions'])))for c in a['candidates']],a.get('criterion','mean'),a.get('requiredCohorts',list(dict.fromkeys(r['cohort']for r in rows))),binary)\n if api=='paired':return weighted_pair(rows,[Q(r.get('predictionA'))for r in a['rows']],[Q(r.get('predictionB'))for r in a['rows']])\n raise ValueError('unknown-api')\n\ndef report_values(api,z):\n summary=[];series=[]\n def add(k,v,u='dimensionless'):summary.append((k,v,u))\n if api=='split':\n  add('groups',z['groupCount'],'groups');add('rows',len(z['records']),'rows');add('finalState',z['state'],'unsigned 32-bit state')\n  series=[('planned role code',[(i,F({'test':0,'validation':1,'train':2}[r['role']]))for i,r in enumerate(z['records'])])]\n elif api=='fit':\n  add('defined',z['defined']);add('trainingRows',len(z['train']),'rows');add('trainingMass',z.get('mass'),'analysis weight mass')\n  model=z.get('model',{});add('modelRank',model.get('rank'),'parameters');add('threshold',model.get('threshold'),'constructed feature units');add('minimumObjective',model.get('minimumObjective'),'constructed squared outcome units')\n  series=[('prediction',list(enumerate(z['pred'])))];\n  if model.get('theta')is not None:\n   for i,v in enumerate(model['theta']):add('theta'+str(i),v,'constructed outcome units per standardized coordinate')\n elif api=='evaluate':\n  for k in ['rows','mass','MSE','MAE','R2','Brier','accuracy','positiveRecall','negativeRecall','precision','F1','balancedAccuracy','AUROC']: \n   if k in z['metrics']:add(k,z['metrics'][k],'rows'if k=='rows'else'analysis weight mass'if k=='mass'else FIXED['unit']if k in ['MSE','Brier']else('probability-score units'if FIXED['input'].get('task')=='binary'else'constructed outcome units')if k=='MAE'else'dimensionless')\n  series=[('squared loss',[(i,r['loss'])for i,r in enumerate(z['records'])])]\n elif api=='select':\n  add('selectedIndex',z['selectedIndex'],'zero-based candidate index')\n  for i,c in enumerate(z['candidates']):add('criterion'+str(i),c['criterion'],FIXED['unit']);add('testMSE'+str(i),c['test']['MSE'],FIXED['unit'])\n  series=[('validation criterion',[(i,c['criterion'])for i,c in enumerate(z['candidates'])]),('test MSE',[(i,c['test']['MSE'])for i,c in enumerate(z['candidates'])])]\n elif api=='paired':\n  for k in ['rows','mass','groupCount','meanDifference','minimumLeaveOut','maximumLeaveOut','varianceProxy']:add(k,z[k],'rows'if k=='rows'else'groups'if k=='groupCount'else'analysis weight mass'if k=='mass'else FIXED['unit']+' squared'if k=='varianceProxy'else FIXED['unit'])\n  series=[('loss A minus loss B',[(i,r['difference'])for i,r in enumerate(z['records'])])]\n elif api=='realdata':\n  add('nativeRows',z['nativeRows'],'native records');add('eligibleRows',z['eligibleRows'],'complete records');add('selectedIndex',z['selection']['selectedIndex'],'zero-based candidate index')\n  for i,c in enumerate(z['selection']['candidates']):add('validationMSE'+str(i),c['validation']['MSE'],FIXED['unit']);add('testMSE'+str(i),c['test']['MSE'],FIXED['unit'])\n  for k in ['meanDifference','minimumLeaveOut','maximumLeaveOut','varianceProxy']:add(k,z['paired'][k],FIXED['unit']+' squared'if k=='varianceProxy'else FIXED['unit'])\n  best=z['selection']['candidates'][z['selection']['selectedIndex']]['test']\n  for k in ['accuracy','positiveRecall','negativeRecall','precision','balancedAccuracy','AUROC']:\n   if k in best:add(k,best[k])\n  series=[('validation MSE',[(i,c['validation']['MSE'])for i,c in enumerate(z['selection']['candidates'])]),('test MSE',[(i,c['test']['MSE'])for i,c in enumerate(z['selection']['candidates'])])]\n return summary,series\n\n\ndef fixed_svg(points,title):\n good=[p for p in points if p['y'] is not None];xx=[float(p['x'])for p in good];yy=[float(p['y'])for p in good];xmin=min(xx)if xx else 0;xmax=max(xx)if xx else 1;ymin=min([0]+yy);ymax=max([0]+yy)\n if xmin==xmax:xmin-=.5;xmax+=.5\n if ymin==ymax:ymin-=.5;ymax+=.5\n pad=(ymax-ymin)*.08;ymin-=pad;ymax+=pad;X=lambda x:82+(float(x)-xmin)/(xmax-xmin)*608;Y=lambda y:354-(float(y)-ymin)/(ymax-ymin)*290;e=html.escape\n out=['<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"720\" height=\"480\" viewBox=\"0 0 720 480\" role=\"img\" aria-label=\"'+e(title)+'\"><rect width=\"720\" height=\"480\" fill=\"white\"/><g font-family=\"Arial,sans-serif\" font-size=\"13\" fill=\"#18232f\"><text x=\"360\" y=\"25\" text-anchor=\"middle\">'+e(title)+'</text>']\n for j in range(5):\n  y=ymin+(ymax-ymin)*j/4;x=xmin+(xmax-xmin)*j/4;out.append('<line x1=\"82\" y1=\"'+str(Y(y))+'\" x2=\"690\" y2=\"'+str(Y(y))+'\" stroke=\"#e2e8f0\"/><text x=\"73\" y=\"'+str(Y(y)+4)+'\" text-anchor=\"end\">'+format(y,'.3g')+'</text><text x=\"'+str(X(x))+'\" y=\"380\" text-anchor=\"middle\">'+format(x,'.3g')+'</text>')\n series=list(dict.fromkeys(p['series']for p in good))\n for j,s in enumerate(series):\n  pp=[p for p in good if p['series']==s];color=['#0f766e','#c76622','#4f46e5','#b23857'][j%4]\n  for p in pp:out.append('<circle cx=\"'+format(X(p['x']),'.6f')+'\" cy=\"'+format(Y(p['y']),'.6f')+'\" r=\"2.6\" fill=\"'+color+'\"><title>'+e(s+': '+str(p['y']))+'</title></circle>')\n  out.append('<text x=\"'+str(82+(j%2)*310)+'\" y=\"'+str(432+(j//2)*23)+'\" fill=\"'+color+'\">'+e(s)+'</text>')\n out.append('<text x=\"360\" y=\"405\" text-anchor=\"middle\">Declared record / candidate index; units in summary</text></g></svg>');return''.join(out)\n\nFIXED={'api': 'evaluate', 'variant': 'no-predicted-positive-missing-label', 'title': 'No positive predictions and a missing label', 'input': {'task': 'binary', 'rows': [{'id': 'n', 'y': '0', 'prediction': '0'}, {'id': 'p', 'y': '1', 'prediction': '1/4'}, {'id': 'unknown', 'y': None, 'prediction': '0'}]}, 'unit': 'Squared probability-score units; one-component Brier loss', 'titleI18n': {'ko': '양성 예측 없음과 결측 정답', 'en': 'No positive predictions and a missing label'}}\n\nOUT=Path(sys.argv[1]);OUT.mkdir(parents=True,exist_ok=False)\nresult=fixed_operation(FIXED['api'],FIXED['input']);summary,series=report_values(FIXED['api'],result)\ndef encode(v):\n if isinstance(v,F):return str(v)\n if isinstance(v,dict):return{k:encode(x)for k,x in v.items()}\n if isinstance(v,(list,tuple)):return[encode(x)for x in v]\n return v\n(OUT/'full.json').write_text(json.dumps(dict(arithmetic='Exact rational author implementation; factual rows, declared group split and finite five-candidate comparison',result=encode(result)),ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\nsummaryRows=[dict(metric=m,value=''if v is None else str(int(v))if isinstance(v,bool)else str(v),unit=u,defined=int(v is not None))for m,v,u in summary]\npoints=[dict(series=name,index=i,x=str(x),y=''if y is None else str(y),defined=int(y is not None))for name,pp in series for i,(x,y)in enumerate(pp)]\nfor name,rows in [('summary',summaryRows),('plot-points',points)]:\n with(OUT/(name+'.csv')).open('w',encoding='utf8',newline='')as f:writer=csv.DictWriter(f,fieldnames=list(rows[0]));writer.writeheader();writer.writerows(rows)\n(OUT/'plot.svg').write_text(fixed_svg([dict(p,x=number(p['x']),y=None if not p['defined']else number(p['y']))for p in points],FIXED['title']),encoding='utf8');print(FIXED['api']+'/'+FIXED['variant'])\n",
        "returnCode": 0,
        "stdout": "evaluate/no-predicted-positive-missing-label\r\n",
        "stderr": "",
        "diagnosticScope": "Public projection omits private absolute-path/traceback frames; actual exit and warnings/reason retained. Raw complete streams and commands in private execution proof.",
        "resultFolder": "ml22-code/runs/python-evaluate-no-predicted-positive-missing-label",
        "kind": null,
        "inputFiles": [
          {
            "file": "ml22-code/evaluate-no-predicted-positive-missing-label-input.json",
            "sha256": "5c1815929f0ff6096976f78ffffd8736d3269ff032a3c9aff389852708eed58f",
            "scope": "Complete fixed literal input; program embeds the same values"
          }
        ],
        "files": [
          {
            "file": "ml22-code/runs/python-evaluate-no-predicted-positive-missing-label/full.json",
            "sha256": "c009f588df12f9dd233cc9c4c8bed8c29d0558c3c559081e2a48bba1279e46b8",
            "bytes": 1634
          },
          {
            "file": "ml22-code/runs/python-evaluate-no-predicted-positive-missing-label/plot-points.csv",
            "sha256": "e6d539881233b60257644c94a86161896901e432254616ca9a5eaca64fbd7a47",
            "bytes": 94
          },
          {
            "file": "ml22-code/runs/python-evaluate-no-predicted-positive-missing-label/plot.svg",
            "sha256": "c7f13783271be2058819e5b0291a6aeea5321bd21463c92c267ccf6a2e7777a1",
            "bytes": 1577
          },
          {
            "file": "ml22-code/runs/python-evaluate-no-predicted-positive-missing-label/summary.csv",
            "sha256": "69bf2b87eef74ffce7125dbeccccc8c8760f9caa5d1e41076cfedd65a9a79a3c",
            "bytes": 486
          }
        ],
        "summaryRows": [
          {
            "metric": "rows",
            "value": "2.0",
            "unit": "rows",
            "defined": "true",
            "rawValue": "2",
            "arithmetic": "Exact Fraction",
            "exactFraction": "2",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "mass",
            "value": "2.0",
            "unit": "analysis weight mass",
            "defined": "true",
            "rawValue": "2",
            "arithmetic": "Exact Fraction",
            "exactFraction": "2",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "MSE",
            "value": "0.28125",
            "unit": "Squared probability-score units; one-component Brier loss",
            "defined": "true",
            "rawValue": "9/32",
            "arithmetic": "Exact Fraction",
            "exactFraction": "9/32",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "MAE",
            "value": "0.375",
            "unit": "probability-score units",
            "defined": "true",
            "rawValue": "3/8",
            "arithmetic": "Exact Fraction",
            "exactFraction": "3/8",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "R2",
            "value": "-0.125",
            "unit": "dimensionless",
            "defined": "true",
            "rawValue": "-1/8",
            "arithmetic": "Exact Fraction",
            "exactFraction": "-1/8",
            "mathematicallyPositive": false,
            "mathematicallyNegative": true,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "Brier",
            "value": "0.28125",
            "unit": "Squared probability-score units; one-component Brier loss",
            "defined": "true",
            "rawValue": "9/32",
            "arithmetic": "Exact Fraction",
            "exactFraction": "9/32",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "accuracy",
            "value": "0.5",
            "unit": "dimensionless",
            "defined": "true",
            "rawValue": "1/2",
            "arithmetic": "Exact Fraction",
            "exactFraction": "1/2",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "positiveRecall",
            "value": "0.0",
            "unit": "dimensionless",
            "defined": "true",
            "rawValue": "0",
            "arithmetic": "Exact Fraction",
            "exactFraction": "0",
            "mathematicallyPositive": false,
            "mathematicallyNegative": false,
            "exactZero": true,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "negativeRecall",
            "value": "1.0",
            "unit": "dimensionless",
            "defined": "true",
            "rawValue": "1",
            "arithmetic": "Exact Fraction",
            "exactFraction": "1",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "precision",
            "value": "",
            "unit": "dimensionless",
            "defined": "false",
            "rawValue": "",
            "arithmetic": "Exact Fraction",
            "exactFraction": null
          },
          {
            "metric": "F1",
            "value": "0.0",
            "unit": "dimensionless",
            "defined": "true",
            "rawValue": "0",
            "arithmetic": "Exact Fraction",
            "exactFraction": "0",
            "mathematicallyPositive": false,
            "mathematicallyNegative": false,
            "exactZero": true,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "balancedAccuracy",
            "value": "0.5",
            "unit": "dimensionless",
            "defined": "true",
            "rawValue": "1/2",
            "arithmetic": "Exact Fraction",
            "exactFraction": "1/2",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "AUROC",
            "value": "1.0",
            "unit": "dimensionless",
            "defined": "true",
            "rawValue": "1",
            "arithmetic": "Exact Fraction",
            "exactFraction": "1",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          }
        ],
        "plotRows": [
          {
            "series": "squared loss",
            "index": "0",
            "x": "0",
            "y": "0",
            "defined": true,
            "xExact": "0",
            "yExact": "0"
          },
          {
            "series": "squared loss",
            "index": "1",
            "x": "1",
            "y": "9/16",
            "defined": true,
            "xExact": "1",
            "yExact": "9/16"
          },
          {
            "series": "squared loss",
            "index": "2",
            "x": "2",
            "y": "",
            "defined": false,
            "xExact": "2",
            "yExact": null
          }
        ],
        "plotFile": "ml22-code/runs/python-evaluate-no-predicted-positive-missing-label/plot.svg",
        "fullResultFile": "ml22-code/runs/python-evaluate-no-predicted-positive-missing-label/full.json",
        "arithmeticScope": "Python exact rational versus base-R approximate floating algebra; copied author kernels, not independent oracle.",
        "plotScope": "Original scatter vectors plot every defined declared comparison point, with missing points omitted. Source profiles show candidate risks; all source records remain in the full result and source CSV files.",
        "reproductionScope": "Standalone literal program plus four native CSV files for factual source profiles. No answer/engine/checker imports."
      },
      "reject-negative-weight": {
        "api": "evaluate",
        "variant": "reject-negative-weight",
        "language": "python",
        "title": "Genuine rejection of a negative weight",
        "titleI18n": {
          "ko": "음의 비중의 실제 거절",
          "en": "Genuine rejection of a negative weight"
        },
        "input": {
          "rows": [
            {
              "id": "bad",
              "y": "0",
              "prediction": "0",
              "weight": "-1"
            }
          ]
        },
        "expectedFailure": true,
        "codeFile": "ml22-code/evaluate-reject-negative-weight.py",
        "codeSHA256": "0efdcf3c3727b521815c30a2a735164be26db0fc380dd8f114db2f1de2435f59",
        "code": "# ML22 standalone fixed literal. Attribution and arithmetic scope in README.\nimport csv,hashlib,html,json,math,sys,time\nfrom pathlib import Path\nfrom fractions import Fraction as F\nfrom collections import Counter\nsys.set_int_max_str_digits(200000)\nnumber=lambda v:F(str(v))\ndef Q(x):return None if x is None or x in ('','.') else F(str(x))\n\ndef canonical(v):return None if Q(v) is None else str(Q(v))\n\ndef fingerprint(tag,values):return tag+':'+hashlib.sha256(json.dumps([canonical(x)for x in values],separators=(',',':')).encode()).hexdigest()\n\ndef split(rows,seed=20261104,pattern=('test','validation','train','train')):\n order=sorted(set(r['group'] for r in rows));state=seed\n for j in range(len(order)-1,0,-1):state=(1664525*state+1013904223)&0xffffffff;k=state%(j+1);order[k],order[j]=order[j],order[k]\n roles={g:(i,pattern[i%len(pattern)]) for i,g in enumerate(order)}\n return roles,state,order\n\ndef solve(A,b):\n n=len(b);M=[list(row)+[rhs]for row,rhs in zip(A,b)];piv=[];rank=0\n for j in range(n):\n  candidates=[i for i in range(rank,n)if M[i][j]]\n  if not candidates:continue\n  k=max(candidates,key=lambda i:abs(M[i][j]));M[rank],M[k]=M[k],M[rank];v=M[rank][j];M[rank]=[x/v for x in M[rank]]\n  for i in range(n):\n   if i!=rank:\n    v=M[i][j];M[i]=[a-v*b for a,b in zip(M[i],M[rank])]\n  piv.append(j);rank+=1\n x=[F(0)]*n\n for i,j in enumerate(piv):x[j]=M[i][-1]\n null=[]\n for j in range(n):\n  if j not in piv:\n   v=[F(0)]*n;v[j]=F(1)\n   for i,k in enumerate(piv):v[k]=-M[i][j]\n   null.append(v)\n return x,rank,null\n\ndef dot(a,b):return sum((x*y for x,y in zip(a,b)),F(0))\n\ndef fit(rows,method,lam=F(0),minleaf=1,binary=False):\n use=[r for r in rows if r['role']=='train'and r['w']>0 and r['y']is not None and None not in r['x']];p=len(rows[0]['x'])if rows else 0\n if not use:return dict(defined=False,pred=[None]*len(rows),raw=[None]*len(rows),train=[],invariant=[None]*len(rows))\n mass=sum(r['w']for r in use);mu=[sum(r['w']*r['x'][j]for r in use)/mass for j in range(p)];scale=[max(r['x'][j]for r in use)-min(r['x'][j]for r in use)or F(1)for j in range(p)];mean=sum(r['w']*r['y']for r in use)/mass;model={};z=lambda r:[F(1)]+[(x-m)/s for x,m,s in zip(r['x'],mu,scale)]\n if method=='constant':model=dict(mean=mean,parameterCount=1,rank=1,unique=True)\n elif method=='ridge':\n  vectors=[z(r)for r in use];n=p+1;A=[[sum(r['w']*xx[j]*xx[k]for r,xx in zip(use,vectors))/mass+(lam if j==k and j>0 else F(0))for k in range(n)]for j in range(n)];b=[sum(r['w']*r['y']*xx[j]for r,xx in zip(use,vectors))/mass for j in range(n)];theta,rank,null=solve(A,b);objective=sum(r['w']*(dot(xx,theta)-r['y'])**2 for r,xx in zip(use,vectors))/(2*mass)+lam*sum(x*x for x in theta[1:])/2;model=dict(lambdaValue=lam,theta=theta,rank=rank,unique=rank==n,nullspace=null,minimumObjective=objective,parameterCount=n)\n else:\n  best=None;total=sum(r['w']*r['y']for r in use);total2=sum(r['w']*r['y']**2 for r in use);base=total2-total**2/mass\n  for j in range(p):\n   ordered=sorted(enumerate(use),key=lambda v:(v[1]['x'][j],v[0]));leftW=F(0);leftS=F(0)\n   for i,(_idx,r)in enumerate(ordered[:-1]):\n    leftW+=r['w'];leftS+=r['w']*r['y'];rightW=mass-leftW\n    if i+1<minleaf or len(use)-i-1<minleaf or r['x'][j]==ordered[i+1][1]['x'][j]:continue\n    SSE=total2-leftS**2/leftW-(total-leftS)**2/rightW\n    if best is None or SSE<best['weightedSSE']:best=dict(feature=j,threshold=(r['x'][j]+ordered[i+1][1]['x'][j])/2,leftMean=leftS/leftW,rightMean=(total-leftS)/rightW,leftRows=i+1,rightRows=len(use)-i-1,leftWeight=leftW,rightWeight=rightW,weightedSSE=SSE)\n  model=dict(split=False,mean=mean,weightedSSE=base,trainingMSE=base/mass)if best is None or best['weightedSSE']>=base else dict(split=True,**best,trainingMSE=best['weightedSSE']/mass,improvement=(base-best['weightedSSE'])/mass)\n raw=[];invariant=[]\n for r in rows:\n  if None in r['x']:raw.append(None);invariant.append(None);continue\n  if method=='constant':v=mean;iv=True\n  elif method=='ridge':zz=z(r);v=dot(zz,model['theta']);iv=all(dot(zz,nn)==0 for nn in model['nullspace'])\n  else:v=(model['leftMean']if r['x'][model['feature']]<=model['threshold']else model['rightMean'])if model['split']else mean;iv=True\n  raw.append(v);invariant.append(iv)\n pred=[None if x is None else min(F(1),max(F(0),x))if binary else x for x in raw]\n return dict(defined=True,train=[r['id']for r in use],mass=mass,meanX=mu,scales=scale,model=model,pred=pred,raw=raw,invariant=invariant)\n\ndef risk(rows,pred,binary=False,threshold=F(1,2)):\n use=[(r,p)for r,p in zip(rows,pred)if r['w']>0 and r['y']is not None and p is not None and r['role']not in['excluded','unused']];mass=sum((r['w']for r,p in use),F(0));d=dict(rows=len(use),mass=mass)\n if not mass:\n  d.update({k:None for k in ['MSE','MAE','R2']+(['Brier','accuracy','balancedAccuracy','AUROC']if binary else[])});return d\n mean=sum(r['w']*r['y']for r,p in use)/mass;sse=sum(r['w']*(p-r['y'])**2 for r,p in use);sst=sum(r['w']*(r['y']-mean)**2 for r,p in use);d.update(meanY=mean,SSE=sse,SST=sst,MSE=sse/mass,MAE=sum(r['w']*abs(p-r['y'])for r,p in use)/mass,R2=1-sse/sst if sst else None)\n if binary:\n  weights=Counter();num=Counter()\n  for r,p in use:k=('T'if int(p>=threshold)==int(r['y'])else'F')+('P'if p>=threshold else'N');weights[k]+=r['w'];num[k]+=1\n  TP,FP,TN,FN=[weights[k]for k in ['TP','FP','TN','FN']];positive=TP+FN;negative=TN+FP;rate=lambda a,b:a/b if b else None;TPR=rate(TP,positive);TNR=rate(TN,negative)\n  # Pair enumeration is independent of the subject's score-tie-block formula.\n  negatives=[(r,p)for r,p in use if not r['y']];positives=[(r,p)for r,p in use if r['y']];wins=sum((a['w']*b['w']*(F(1)if pa>pb else F(1,2)if pa==pb else F(0))for a,pa in positives for b,pb in negatives),F(0))\n  d.update(Brier=d['MSE'],threshold=threshold,confusionMass={k:weights[k]for k in ['TP','FP','TN','FN']},confusionRows={k:num[k]for k in ['TP','FP','TN','FN']},positiveMass=positive,negativeMass=negative,accuracy=(TP+TN)/mass,positiveRecall=TPR,negativeRecall=TNR,precision=rate(TP,TP+FP),F1=rate(2*TP,2*TP+FP+FN),balancedAccuracy=(TPR+TNR)/2 if TPR is not None and TNR is not None else None,AUROC=rate(wins,positive*negative))\n return d\n\nNATIVE_SHA256={'actual1599-red-wine-original12-fields.csv': '77e9ac73115930d6c43983333a5a57940deefc493affeb17aca478c09c5f6e00', 'actual4898-white-wine-original12-fields.csv': '50d810bbb42b9cc3e87fa4c27a4c0f168e72da09dd812863425ca3873fec28ef', 'actual3613-NLS-original52-fields.csv': '6e1e1895558795435b65f8634252a7589865273a0e69adbd715fcfa04a3c11a1', 'actual3150-churn-original14-fields.csv': '1c0753e434226e769d1015c922121a7d8967df66014e057c4f7543e490f11764'}\n\ndef read_sources(directory,seed):\n def read(name):\n  p=directory/name\n  if hashlib.sha256(p.read_bytes()).hexdigest()!=NATIVE_SHA256[name]:raise ValueError('Native file hash differs: '+name)\n  with p.open(encoding='utf8',newline='')as f:return list(csv.DictReader(f))\n sources={};wine=[]\n for typ,n in [('red',1599),('white',4898)]:\n  table=read(f'actual{n}-{typ}-wine-original12-fields.csv');assert len(table)==n;features=[k for k in table[0]if k not in ['sourceRow','wineType','quality']];assert len(features)==11\n  for r in table:\n   i=int(r['sourceRow']);red='1'if typ=='red'else'0';nativeX=[r[k]for k in features];wine.append(dict(id=f'wine-{typ}-row:{i}',sourceRow=f'{typ}:{i}',originalID=None,group=fingerprint('wine-predictors',[red]+nativeX),cohort=typ,x=list(map(Q,nativeX+[red])),y=Q(r['quality'])))\n sources['country']=wine\n table=read('actual3613-NLS-original52-fields.csv');assert len(table)==3613;sources['person']=[dict(id='nls-row:'+r['sourceRow'],sourceRow=int(r['sourceRow']),originalID=r['id'],group='nls-id:'+r['id'],cohort='schooling-over12'if Q(r['ed76'])>12 else'schooling-at-most12',x=[Q(r['ed76']),Q(r['age76'])],y=Q(r['lwage76']))for r in table]\n table=read('actual3150-churn-original14-fields.csv');assert len(table)==3150;predictors=[k for k in table[0]if k not in ['sourceRow','Churn']];assert len(predictors)==13;sources['company']=[dict(id='customer-row:'+r['sourceRow'],sourceRow=int(r['sourceRow']),originalID=None,group=fingerprint('customer-predictors',[r[k]for k in predictors]),cohort='pay-as-you-go'if r['Tariff Plan']=='1'else'contractual'if r['Tariff Plan']=='2'else'other-native-tariff',x=[Q(r[k])for k in ['Call  Failure','Subscription  Length','Seconds of Use','Age']],y=Q(r['Churn']))for r in table]\n for kind,rows in sources.items():\n  assignments,state,order=split(rows,seed)\n  for r in rows:\n   rank,planned=assignments[r['group']];r.update(w=F(1),splitRank=rank,plannedRole=planned,eligible=r['y']is not None and None not in r['x']);r['role']=planned if r['eligible']else'excluded'\n return sources\n# New ML22 fixed-profile kernels. The public Fraction fitting/source readers are\n# copied by value above this file by the standalone builder; never imported.\ndef fixed_rows(data, prediction_key=None):\n out=[]\n for i,a in enumerate(data):\n  w=Q(a.get('weight','1'))\n  if w is None or w<0:raise ValueError('negative-weight' if w is not None and w<0 else 'missing-weight')\n  out.append(dict(id=a.get('id',str(i)),group=a.get('group',a.get('id',str(i))),cohort=a.get('cohort','all'),role=a.get('role','train'),w=w,x=[Q(v)for v in a.get('x',[])],y=Q(a.get('y'))))\n return out\n\ndef weighted_pair(rows,A,B):\n use=[(r,a,b)for r,a,b in zip(rows,A,B)if r['w']>0 and r['y']is not None and a is not None and b is not None and r['role']not in ['excluded','unused']]\n mass=sum((r['w']for r,a,b in use),F(0));records=[];groups={}\n for r,a,b in use:\n  la=(a-r['y'])**2;lb=(b-r['y'])**2;d=la-lb\n  records.append(dict(id=r['id'],group=r['group'],weight=r['w'],lossA=la,lossB=lb,difference=d))\n  g=groups.setdefault(r['group'],dict(group=r['group'],rows=0,mass=F(0),sum=F(0)));g['rows']+=1;g['mass']+=r['w'];g['sum']+=r['w']*d\n total=sum((g['sum']for g in groups.values()),F(0));mean=total/mass if mass else None;G=len(groups)\n for g in groups.values():g['leaveOut']=(total-g['sum'])/(mass-g['mass'])if mass>g['mass']else None\n leaves=[g['leaveOut']for g in groups.values()if g['leaveOut']is not None]\n proxy=F(G-1,G)*sum((v-sum(leaves,F(0))/G)**2 for v in leaves) if G>1 and len(leaves)==G else None\n return dict(rows=len(use),mass=mass,groupCount=G,meanDifference=mean,minimumLeaveOut=min(leaves)if leaves else None,maximumLeaveOut=max(leaves)if leaves else None,varianceProxy=proxy,groups=list(groups.values()),records=records)\n\ndef run_selection(rows,candidates,criterion,required,binary=False):\n results=[]\n for c,pred in candidates:\n  val=[dict(r,role='excluded')if r['role']!='validation'else r for r in rows]\n  test=[dict(r,role='excluded')if r['role']!='test'else r for r in rows]\n  v=risk(val,pred,binary);t=risk(test,pred,binary);cohort={g:risk([dict(r,role='excluded')if r['role']!='validation'or r['cohort']!=g else r for r in rows],pred,binary)for g in required}\n  values=[cohort[g]['MSE']for g in required]\n  score=v['MSE']if criterion=='mean'else max(values)if values and None not in values else None\n  results.append(dict(id=c,criterion=score,validation=v,test=t,cohorts=cohort))\n eligible=[(i,r['criterion'])for i,r in enumerate(results)if r['criterion']is not None]\n chosen=min(eligible,key=lambda t:(t[1],t[0]))[0]if eligible else None\n return dict(criterion=criterion,selected=results[chosen]['id']if chosen is not None else None,selectedIndex=chosen,candidates=results)\n\ndef fixed_operation(api,a):\n if api=='realdata':\n  kind=a['kind'];rows=read_sources(Path(__file__).parent/'data',a.get('seed',20261104))[kind];binary=kind=='company'\n  defs=[('constant','constant',F(0)),('ridge:1/100','ridge',F(1,100)),('ridge:1/10','ridge',F(1,10)),('ridge:1','ridge',F(1)),('one-split-stump','stump',F(0))]\n  fits=[fit(rows,method,lam,5,binary)for _,method,lam in defs]\n  selection=run_selection(rows,[(d[0],f['pred'])for d,f in zip(defs,fits)],a.get('criterion','mean'),list(dict.fromkeys(r['cohort']for r in rows)),binary)\n  chosen=selection['selectedIndex'];best=fits[chosen];base=fits[0]\n  test=[dict(r,role='excluded')if r['role']!='test'else r for r in rows]\n  paired=weighted_pair(test,best['pred'],base['pred'])\n  records=[dict(id=r['id'],sourceRow=r.get('sourceRow'),originalID=r.get('originalID'),group=r['group'],cohort=r['cohort'],plannedRole=r['plannedRole'],role=r['role'],eligible=r['eligible'],y=r['y'],baselinePrediction=base['pred'][i],selectedPrediction=best['pred'][i],selectedRawPrediction=best['raw'][i],queryInvariant=best['invariant'][i])for i,r in enumerate(rows)]\n  return dict(kind=kind,nativeRows=len(rows),eligibleRows=sum(r['eligible']for r in rows),selection=selection,models=[dict(id=d[0],train=f['train'],mass=f.get('mass'),meanX=f.get('meanX'),scales=f.get('scales'),model=f.get('model'))for d,f in zip(defs,fits)],paired=paired,records=records)\n rows=fixed_rows(a.get('rows',[]));binary=a.get('task')=='binary'\n if api=='split':\n  assignment,state,order=split(rows,a.get('seed',0));records=[dict(id=r['id'],group=r['group'],rank=assignment[r['group']][0],role=assignment[r['group']][1])for r in rows]\n  return dict(state=state,groupOrder=order,records=records,groupCount=len(order))\n if api=='fit':return fit(rows,a.get('method','constant'),Q(a.get('lambda','0')),a.get('minLeafRows',1),binary)\n if api=='evaluate':\n  pred=[Q(r.get('prediction'))for r in a['rows']];threshold=Q(a.get('threshold','1/2'));rr=risk(rows,pred,binary,threshold)\n  records=[]\n  for r,p in zip(rows,pred):\n   valid=r['w']>0 and r['y']is not None and p is not None and r['role']not in ['excluded','unused']\n   records.append(dict(id=r['id'],weight=r['w'],y=r['y'],prediction=p,eligible=valid,loss=(p-r['y'])**2 if valid else None,correct=dict(defined=valid and binary,value=bool(int(p>=threshold)==int(r['y']))if valid and binary else None)))\n  return dict(metrics=rr,records=records)\n if api=='select':return run_selection(rows,[(c['id'],list(map(Q,c['predictions'])))for c in a['candidates']],a.get('criterion','mean'),a.get('requiredCohorts',list(dict.fromkeys(r['cohort']for r in rows))),binary)\n if api=='paired':return weighted_pair(rows,[Q(r.get('predictionA'))for r in a['rows']],[Q(r.get('predictionB'))for r in a['rows']])\n raise ValueError('unknown-api')\n\ndef report_values(api,z):\n summary=[];series=[]\n def add(k,v,u='dimensionless'):summary.append((k,v,u))\n if api=='split':\n  add('groups',z['groupCount'],'groups');add('rows',len(z['records']),'rows');add('finalState',z['state'],'unsigned 32-bit state')\n  series=[('planned role code',[(i,F({'test':0,'validation':1,'train':2}[r['role']]))for i,r in enumerate(z['records'])])]\n elif api=='fit':\n  add('defined',z['defined']);add('trainingRows',len(z['train']),'rows');add('trainingMass',z.get('mass'),'analysis weight mass')\n  model=z.get('model',{});add('modelRank',model.get('rank'),'parameters');add('threshold',model.get('threshold'),'constructed feature units');add('minimumObjective',model.get('minimumObjective'),'constructed squared outcome units')\n  series=[('prediction',list(enumerate(z['pred'])))];\n  if model.get('theta')is not None:\n   for i,v in enumerate(model['theta']):add('theta'+str(i),v,'constructed outcome units per standardized coordinate')\n elif api=='evaluate':\n  for k in ['rows','mass','MSE','MAE','R2','Brier','accuracy','positiveRecall','negativeRecall','precision','F1','balancedAccuracy','AUROC']: \n   if k in z['metrics']:add(k,z['metrics'][k],'rows'if k=='rows'else'analysis weight mass'if k=='mass'else FIXED['unit']if k in ['MSE','Brier']else'constructed outcome units'if k=='MAE'else'dimensionless')\n  series=[('squared loss',[(i,r['loss'])for i,r in enumerate(z['records'])])]\n elif api=='select':\n  add('selectedIndex',z['selectedIndex'],'zero-based candidate index')\n  for i,c in enumerate(z['candidates']):add('criterion'+str(i),c['criterion'],FIXED['unit']);add('testMSE'+str(i),c['test']['MSE'],FIXED['unit'])\n  series=[('validation criterion',[(i,c['criterion'])for i,c in enumerate(z['candidates'])]),('test MSE',[(i,c['test']['MSE'])for i,c in enumerate(z['candidates'])])]\n elif api=='paired':\n  for k in ['rows','mass','groupCount','meanDifference','minimumLeaveOut','maximumLeaveOut','varianceProxy']:add(k,z[k],'rows'if k=='rows'else'groups'if k=='groupCount'else'analysis weight mass'if k=='mass'else FIXED['unit']+' squared'if k=='varianceProxy'else FIXED['unit'])\n  series=[('loss A minus loss B',[(i,r['difference'])for i,r in enumerate(z['records'])])]\n elif api=='realdata':\n  add('nativeRows',z['nativeRows'],'native records');add('eligibleRows',z['eligibleRows'],'complete records');add('selectedIndex',z['selection']['selectedIndex'],'zero-based candidate index')\n  for i,c in enumerate(z['selection']['candidates']):add('validationMSE'+str(i),c['validation']['MSE'],FIXED['unit']);add('testMSE'+str(i),c['test']['MSE'],FIXED['unit'])\n  for k in ['meanDifference','minimumLeaveOut','maximumLeaveOut','varianceProxy']:add(k,z['paired'][k],FIXED['unit']+' squared'if k=='varianceProxy'else FIXED['unit'])\n  best=z['selection']['candidates'][z['selection']['selectedIndex']]['test']\n  for k in ['accuracy','positiveRecall','negativeRecall','precision','balancedAccuracy','AUROC']:\n   if k in best:add(k,best[k])\n  series=[('validation MSE',[(i,c['validation']['MSE'])for i,c in enumerate(z['selection']['candidates'])]),('test MSE',[(i,c['test']['MSE'])for i,c in enumerate(z['selection']['candidates'])])]\n return summary,series\n\n\ndef fixed_svg(points,title):\n good=[p for p in points if p['y'] is not None];xx=[float(p['x'])for p in good];yy=[float(p['y'])for p in good];xmin=min(xx)if xx else 0;xmax=max(xx)if xx else 1;ymin=min([0]+yy);ymax=max([0]+yy)\n if xmin==xmax:xmin-=.5;xmax+=.5\n if ymin==ymax:ymin-=.5;ymax+=.5\n pad=(ymax-ymin)*.08;ymin-=pad;ymax+=pad;X=lambda x:82+(float(x)-xmin)/(xmax-xmin)*608;Y=lambda y:354-(float(y)-ymin)/(ymax-ymin)*290;e=html.escape\n out=['<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"720\" height=\"480\" viewBox=\"0 0 720 480\" role=\"img\" aria-label=\"'+e(title)+'\"><rect width=\"720\" height=\"480\" fill=\"white\"/><g font-family=\"Arial,sans-serif\" font-size=\"13\" fill=\"#18232f\"><text x=\"360\" y=\"25\" text-anchor=\"middle\">'+e(title)+'</text>']\n for j in range(5):\n  y=ymin+(ymax-ymin)*j/4;x=xmin+(xmax-xmin)*j/4;out.append('<line x1=\"82\" y1=\"'+str(Y(y))+'\" x2=\"690\" y2=\"'+str(Y(y))+'\" stroke=\"#e2e8f0\"/><text x=\"73\" y=\"'+str(Y(y)+4)+'\" text-anchor=\"end\">'+format(y,'.3g')+'</text><text x=\"'+str(X(x))+'\" y=\"380\" text-anchor=\"middle\">'+format(x,'.3g')+'</text>')\n series=list(dict.fromkeys(p['series']for p in good))\n for j,s in enumerate(series):\n  pp=[p for p in good if p['series']==s];color=['#0f766e','#c76622','#4f46e5','#b23857'][j%4]\n  for p in pp:out.append('<circle cx=\"'+format(X(p['x']),'.6f')+'\" cy=\"'+format(Y(p['y']),'.6f')+'\" r=\"2.6\" fill=\"'+color+'\"><title>'+e(s+': '+str(p['y']))+'</title></circle>')\n  out.append('<text x=\"'+str(82+(j%2)*310)+'\" y=\"'+str(432+(j//2)*23)+'\" fill=\"'+color+'\">'+e(s)+'</text>')\n out.append('<text x=\"360\" y=\"405\" text-anchor=\"middle\">Declared record / candidate index; units in summary</text></g></svg>');return''.join(out)\n\nFIXED={'api': 'evaluate', 'variant': 'reject-negative-weight', 'title': 'Genuine rejection of a negative weight', 'input': {'rows': [{'id': 'bad', 'y': '0', 'prediction': '0', 'weight': '-1'}]}, 'expectedFailure': True, 'error': 'negative-weight', 'unit': 'Invalid input; no plotted zero', 'titleI18n': {'ko': '음의 비중의 실제 거절', 'en': 'Genuine rejection of a negative weight'}}\n\nOUT=Path(sys.argv[1]);OUT.mkdir(parents=True,exist_ok=False)\nresult=fixed_operation(FIXED['api'],FIXED['input']);summary,series=report_values(FIXED['api'],result)\ndef encode(v):\n if isinstance(v,F):return str(v)\n if isinstance(v,dict):return{k:encode(x)for k,x in v.items()}\n if isinstance(v,(list,tuple)):return[encode(x)for x in v]\n return v\n(OUT/'full.json').write_text(json.dumps(dict(arithmetic='Exact rational author implementation; factual rows, declared group split and finite five-candidate comparison',result=encode(result)),ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\nsummaryRows=[dict(metric=m,value=''if v is None else str(int(v))if isinstance(v,bool)else str(v),unit=u,defined=int(v is not None))for m,v,u in summary]\npoints=[dict(series=name,index=i,x=str(x),y=''if y is None else str(y),defined=int(y is not None))for name,pp in series for i,(x,y)in enumerate(pp)]\nfor name,rows in [('summary',summaryRows),('plot-points',points)]:\n with(OUT/(name+'.csv')).open('w',encoding='utf8',newline='')as f:writer=csv.DictWriter(f,fieldnames=list(rows[0]));writer.writeheader();writer.writerows(rows)\n(OUT/'plot.svg').write_text(fixed_svg([dict(p,x=number(p['x']),y=None if not p['defined']else number(p['y']))for p in points],FIXED['title']),encoding='utf8');print(FIXED['api']+'/'+FIXED['variant'])\n",
        "returnCode": 1,
        "stdout": "",
        "stderr": "    result=fixed_operation(FIXED['api'],FIXED['input']);summary,series=report_values(FIXED['api'],result)\n    rows=fixed_rows(a.get('rows',[]));binary=a.get('task')=='binary'\n    if w is None or w<0:raise ValueError('negative-weight' if w is not None and w<0 else 'missing-weight')\nValueError: negative-weight",
        "diagnosticScope": "Public projection omits private absolute-path/traceback frames; actual exit and warnings/reason retained. Raw complete streams and commands in private execution proof.",
        "resultFolder": "ml22-code/runs/python-evaluate-reject-negative-weight",
        "kind": null,
        "inputFiles": [
          {
            "file": "ml22-code/evaluate-reject-negative-weight-input.json",
            "sha256": "8769116a70fa17195d8a056b88ca746b7d8363583ead1c34436957a1dde28a48",
            "scope": "Complete fixed literal input; program embeds the same values"
          }
        ],
        "files": [],
        "summaryRows": [],
        "plotRows": [],
        "plotFile": null,
        "fullResultFile": null,
        "arithmeticScope": "Python exact rational versus base-R approximate floating algebra; copied author kernels, not independent oracle.",
        "plotScope": "Original scatter vectors plot every defined declared comparison point, with missing points omitted. Source profiles show candidate risks; all source records remain in the full result and source CSV files.",
        "reproductionScope": "Standalone literal program plus four native CSV files for factual source profiles. No answer/engine/checker imports."
      }
    },
    "r": {
      "weighted-regression-loss": {
        "api": "evaluate",
        "variant": "weighted-regression-loss",
        "language": "r",
        "title": "Weight mass differs from row count",
        "titleI18n": {
          "ko": "행 수와 다른 비중 질량",
          "en": "Weight mass differs from row count"
        },
        "input": {
          "rows": [
            {
              "id": "a",
              "y": "1",
              "prediction": "2",
              "weight": "1"
            },
            {
              "id": "b",
              "y": "3",
              "prediction": "1",
              "weight": "3"
            }
          ]
        },
        "expectedFailure": false,
        "codeFile": "ml22-code/evaluate-weighted-regression-loss.R",
        "codeSHA256": "cc8c7f92c8d9967ab0d02f852fcd8ddd1a18d19f3946eb0758a104d025af62ed",
        "code": "# ML22 standalone; source/public functions copied by value, no source() dependency.\noptions(stringsAsFactors=FALSE,digits=17,warn=1)\nargs0<-commandArgs(trailingOnly=FALSE);script0<-sub('^--file=','',args0[grepl('^--file=',args0)][1]);source_dir<-file.path(dirname(normalizePath(script0)), 'data');seed<-20261104;leaf_min<-5\nnative_hash <- c(\"actual1599-red-wine-original12-fields.csv\"=\"77e9ac73115930d6c43983333a5a57940deefc493affeb17aca478c09c5f6e00\",\"actual4898-white-wine-original12-fields.csv\"=\"50d810bbb42b9cc3e87fa4c27a4c0f168e72da09dd812863425ca3873fec28ef\",\"actual3613-NLS-original52-fields.csv\"=\"6e1e1895558795435b65f8634252a7589865273a0e69adbd715fcfa04a3c11a1\",\"actual3150-churn-original14-fields.csv\"=\"1c0753e434226e769d1015c922121a7d8967df66014e057c4f7543e490f11764\")\nsha256<-getExportedValue('tools','sha256sum')\nread_native<-function(name){f<-file.path(source_dir,name);if(unname(sha256(f))!=native_hash[[name]])stop(paste('Native hash differs',name));read.csv(f,check.names=FALSE,colClasses='character',na.strings=NULL)}\ngcd_small<-function(a,b){while(b!=0){r<-a%%b;a<-b;b<-r};a}\ncanonical<-function(token){\n if(is.na(token)||token%in%c('','.'))return('null')\n if(!grepl('^[+-]?[0-9]+([.][0-9]*)?$',token))stop('Unsupported native fingerprint token')\n neg<-substr(token,1,1)=='-';s<-sub('^[+-]','',token);parts<-strsplit(s,'.',fixed=TRUE)[[1]];dec<-if(length(parts)==2)nchar(parts[2])else 0;n<-as.numeric(gsub('.','',s,fixed=TRUE));d<-10^dec\n # Every native fingerprint numerator/denominator must remain exactly integral\n # in binary64; reject rather than silently rounding a changed future source.\n if(!is.finite(n)||n>2^53||d>2^53)stop('Native canonical integer range exceeded')\n g<-gcd_small(n,d);n<-n/g;d<-d/g;if(neg)n<--n\n out<-sprintf('%.0f',n);if(d!=1)out<-paste0(out,'/',sprintf('%.0f',d));out\n}\nfp_cache<-new.env(hash=TRUE,parent=emptyenv());hash_file<-tempfile('ml22-hash-')\nfingerprint<-function(tag,values){a<-vapply(values,canonical,'');payload<-paste0('[',paste0('\"',a,'\"',collapse=','),']');key<-paste0(tag,':',payload);if(exists(key,fp_cache,inherits=FALSE))return(get(key,fp_cache,inherits=FALSE));con<-file(hash_file,'wb');writeBin(charToRaw(payload),con);close(con);value<-paste0(tag,':',unname(sha256(hash_file)));assign(key,value,fp_cache);value}\nassign_roles<-function(group){order<-sort(unique(group),method='radix');state<-seed;if(length(order)>1)for(j in seq.int(length(order),2)){state<-(1664525*state+1013904223)%%2^32;k<-state%%j+1;order[c(j,k)]<-order[c(k,j)]};rank<-match(group,order)-1;list(rank=rank,planned=c('test','validation','train','train')[rank%%4+1],state=state)}\n\nfit_model<-function(r,x,method,lambda){\n tr<-which(r$role=='train'&r$eligible);if(!length(tr))stop('No complete positive training rows');y<-r$y[tr];xx<-x[tr,,drop=FALSE];mu<-colMeans(xx);scale<-apply(xx,2,function(v)diff(range(v)));scale[scale==0]<-1;z<-cbind(1,sweep(sweep(x,2,mu,'-'),2,scale,'/'));meanY<-mean(y);model<-list();n<-length(tr)\n if(method=='constant'){model<-list(mean=meanY,parameterCount=1,rank=1,unique=TRUE);raw<-rep(meanY,nrow(r))}\n else if(method=='ridge'){zt<-z[tr,,drop=FALSE];pen<-diag(c(0,rep(lambda,ncol(x))));theta<-drop(solve(crossprod(zt)/n+pen,crossprod(zt,y)/n));raw<-drop(z%*%theta);objective<-mean((y-raw[tr])^2)/2+lambda*sum(theta[-1]^2)/2;model<-list(lambdaValue=lambda,theta=theta,rank=length(theta),unique=TRUE,minimumObjective=objective,parameterCount=length(theta))}\n else{base<-sum((y-meanY)^2);best<-NULL;total<-sum(y);total2<-sum(y*y)\n  for(j in seq_len(ncol(x))){ord<-order(xx[,j],seq_len(n));sx<-xx[ord,j];sy<-y[ord];left<-cumsum(sy)\n   if(n<2*leaf_min)next\n   for(i in seq.int(leaf_min,n-leaf_min)){if(sx[i]==sx[i+1])next;loss<-total2-left[i]^2/i-(total-left[i])^2/(n-i)\n    # Explicit approximate-tie tolerance; exact source JavaScript/Python\n    # contracts are authoritative for general arbitrarily close ties.\n    if(is.null(best)||loss<best$weightedSSE-1e-12*max(1,abs(loss),abs(best$weightedSSE)))best<-list(feature=j-1,threshold=(sx[i]+sx[i+1])/2,leftMean=left[i]/i,rightMean=(total-left[i])/(n-i),leftRows=i,rightRows=n-i,leftWeight=i,rightWeight=n-i,weightedSSE=loss)\n   }\n  }\n  if(is.null(best)||best$weightedSSE>=base-1e-12*max(1,abs(base))){model<-list(split=FALSE,mean=meanY,weightedSSE=base,trainingMSE=base/n);raw<-rep(meanY,nrow(r))}else{model<-c(list(split=TRUE),best,list(trainingMSE=best$weightedSSE/n,improvement=(base-best$weightedSSE)/n));raw<-ifelse(x[,model$feature+1]<=model$threshold,model$leftMean,model$rightMean)}\n }\n pred<-if(r$dataset[1]=='company')pmax(0,pmin(1,raw))else raw;list(meanX=mu,scales=scale,model=model,raw=raw,pred=pred)\n}\n\n# New standalone fixed-profile adapters; native and fit helpers copied by value.\nnum<-function(x){if(is.null(x)||length(x)==0||is.na(x)||x%in%c('','.'))return(NA_real_);if(is.character(x)&&grepl('/',x,fixed=TRUE)){v<-strsplit(x,'/',fixed=TRUE)[[1]];return(as.numeric(v[1])/as.numeric(v[2]))};as.numeric(x)}\nfixedRows<-function(aa){\n rr<-lapply(seq_along(aa),function(i){a<-aa[[i]];w<-num(if(is.null(a$weight))'1'else a$weight);if(is.na(w)||w<0)stop(if(!is.na(w)&&w<0)'negative-weight'else'missing-weight');list(id=if(is.null(a$id))as.character(i-1)else a$id,group=if(is.null(a$group))if(is.null(a$id))as.character(i-1)else a$id else a$group,cohort=if(is.null(a$cohort))'all'else a$cohort,role=if(is.null(a$role))'train'else a$role,w=w,y=num(a$y),x=vapply(a$x,num,0.0))})\n p<-if(length(rr))length(rr[[1]]$x)else 0;xx<-matrix(NA_real_,length(rr),p)\n if(p)for(i in seq_along(rr))xx[i,]<-rr[[i]]$x\n r<-data.frame(id=vapply(rr,`[[`,'','id'),group=vapply(rr,`[[`,'','group'),cohort=vapply(rr,`[[`,'','cohort'),role=vapply(rr,`[[`,'','role'),w=vapply(rr,`[[`,0.0,'w'),y=vapply(rr,`[[`,0.0,'y'));r$eligible<-!is.na(r$y)&rowSums(is.na(xx))==0&r$w>0;list(r=r,x=xx)\n}\nweightedRisk<-function(r,p,binary=FALSE,threshold=.5){\n ii<-which(r$w>0&!is.na(r$y)&!is.na(p)&!r$role%in%c('excluded','unused'));y<-r$y[ii];p<-p[ii];w<-r$w[ii];W<-sum(w);d<-list(rows=length(ii),mass=W,MSE=NA_real_,MAE=NA_real_,R2=NA_real_)\n if(W==0){if(binary)d<-c(d,setNames(rep(list(NA_real_),10),c('Brier','accuracy','positiveRecall','negativeRecall','precision','F1','balancedAccuracy','AUROC','positiveMass','negativeMass')));return(d)}\n mu<-sum(w*y)/W;sse<-sum(w*(p-y)^2);sst<-sum(w*(y-mu)^2);d<-c(d,list(meanY=mu,SSE=sse,SST=sst));d$MSE<-sse/W;d$MAE<-sum(w*abs(p-y))/W;d$R2<-if(sst>0)1-sse/sst else NA_real_\n if(binary){pos<-y==1;yes<-p>=threshold;TP<-sum(w[pos&yes]);FP<-sum(w[!pos&yes]);TN<-sum(w[!pos&!yes]);FN<-sum(w[pos&!yes]);rate<-function(a,b)if(b>0)a/b else NA_real_;tpr<-rate(TP,TP+FN);tnr<-rate(TN,TN+FP);auc<-NA_real_;P<-sum(w[pos]);N<-sum(w[!pos]);if(P>0&&N>0){wins<-sum(vapply(which(pos),function(i)sum(w[i]*w[!pos]*ifelse(p[i]>p[!pos],1,ifelse(p[i]==p[!pos],.5,0))),0.0));auc<-wins/(P*N)};d<-c(d,list(Brier=d$MSE,threshold=threshold,confusionMass=list(TP=TP,FP=FP,TN=TN,FN=FN),confusionRows=list(TP=sum(pos&yes),FP=sum(!pos&yes),TN=sum(!pos&!yes),FN=sum(pos&!yes)),positiveMass=P,negativeMass=N,accuracy=(TP+TN)/W,positiveRecall=tpr,negativeRecall=tnr,precision=rate(TP,TP+FP),F1=rate(2*TP,2*TP+FP+FN),balancedAccuracy=if(is.finite(tpr)&&is.finite(tnr))(tpr+tnr)/2 else NA_real_,AUROC=auc))};d\n}\nweightedPair<-function(r,A,B){\n ii<-which(r$w>0&!is.na(r$y)&!is.na(A)&!is.na(B)&!r$role%in%c('excluded','unused'));rr<-r[ii,,drop=FALSE];la<-(A[ii]-rr$y)^2;lb<-(B[ii]-rr$y)^2;d<-la-lb;W<-sum(rr$w);S<-sum(rr$w*d);mu<-if(W>0)S/W else NA_real_;ids<-unique(rr$group);groups<-lapply(ids,function(g){jj<-which(rr$group==g);wg<-sum(rr$w[jj]);sg<-sum(rr$w[jj]*d[jj]);list(group=g,rows=length(jj),mass=wg,sum=sg,leaveOut=if(W>wg)(S-sg)/(W-wg)else NA_real_)});leaves<-vapply(groups,`[[`,0.0,'leaveOut');G<-length(groups);proxy<-if(G>1&&all(is.finite(leaves)))(G-1)/G*sum((leaves-mean(leaves))^2) else NA_real_\n list(rows=length(ii),mass=W,groupCount=G,meanDifference=mu,minimumLeaveOut=if(any(is.finite(leaves)))min(leaves,na.rm=TRUE)else NA_real_,maximumLeaveOut=if(any(is.finite(leaves)))max(leaves,na.rm=TRUE)else NA_real_,varianceProxy=proxy,groups=groups,records=lapply(seq_along(ii),function(j)list(id=rr$id[j],group=rr$group[j],weight=rr$w[j],lossA=la[j],lossB=lb[j],difference=d[j])))\n}\nrunSelection<-function(r,candidates,criterion,required,binary=FALSE){\n out<-lapply(candidates,function(c){v<-r;t<-r;v$role[v$role!='validation']<-'excluded';t$role[t$role!='test']<-'excluded';val<-weightedRisk(v,c$pred,binary);test<-weightedRisk(t,c$pred,binary);co<-setNames(lapply(required,function(g){z<-v;z$role[z$cohort!=g]<-'excluded';weightedRisk(z,c$pred,binary)}),required);vv<-vapply(co,`[[`,0.0,'MSE');score<-if(criterion=='mean')val$MSE else if(length(vv)&&all(is.finite(vv)))max(vv)else NA_real_;list(id=c$id,criterion=score,validation=val,test=test,cohorts=co)})\n scores<-vapply(out,`[[`,0.0,'criterion');eligible<-which(is.finite(scores));k<-if(length(eligible))eligible[which.min(scores[eligible])]else NA_integer_;list(criterion=criterion,selected=if(!is.na(k))out[[k]]$id else NULL,selectedIndex=if(!is.na(k))k-1 else NA_real_,candidates=out)\n}\nfixedOperation<-function(api,a){\n if(api=='realdata'){\n  kind<-a$kind;r<-rows[[kind]];x<-X[[kind]];asgn<-assign_roles(r$group);r$dataset<-kind;r$splitRank<-asgn$rank;r$plannedRole<-asgn$planned;r$eligible<-!is.na(r$y)&rowSums(is.na(x))==0;r$role<-ifelse(r$eligible,r$plannedRole,'excluded');r$w<-1;binary<-kind=='company';leaf_min<<-5\n  defs<-data.frame(id=c('constant','ridge:1/100','ridge:1/10','ridge:1','one-split-stump'),method=c('constant','ridge','ridge','ridge','stump'),lambda=c(0,.01,.1,1,0));fits<-lapply(seq_len(5),function(i)fit_model(r,x,defs$method[i],defs$lambda[i]));candidates<-lapply(seq_len(5),function(i)list(id=defs$id[i],pred=fits[[i]]$pred));selection<-runSelection(r,candidates,a$criterion,unique(r$cohort),binary);k<-selection$selectedIndex+1;best<-fits[[k]];base<-fits[[1]];test<-r;test$role[test$role!='test']<-'excluded';paired<-weightedPair(test,best$pred,base$pred)\n  records<-lapply(seq_len(nrow(r)),function(i)list(id=r$id[i],sourceRow=r$sourceRow[i],originalID=r$originalID[i],group=r$group[i],cohort=r$cohort[i],plannedRole=r$plannedRole[i],role=r$role[i],eligible=r$eligible[i],y=r$y[i],baselinePrediction=base$pred[i],selectedPrediction=best$pred[i],selectedRawPrediction=best$raw[i],queryInvariant=TRUE))\n  return(list(kind=kind,nativeRows=nrow(r),eligibleRows=sum(r$eligible),selection=selection,models=lapply(seq_len(5),function(i)list(id=defs$id[i],train=as.list(r$id[r$role=='train']),mass=sum(r$role=='train'),meanX=fits[[i]]$meanX,scales=fits[[i]]$scales,model=fits[[i]]$model)),paired=paired,records=records))\n }\n f<-fixedRows(a$rows);r<-f$r;x<-f$x;binary<-identical(a$task,'binary')\n if(api=='split'){seed<<-a$seed;asgn<-assign_roles(r$group);return(list(state=asgn$state,groupCount=length(unique(r$group)),records=lapply(seq_len(nrow(r)),function(i)list(id=r$id[i],group=r$group[i],rank=asgn$rank[i],role=asgn$planned[i]))))}\n if(api=='fit'){\n  r$dataset<-if(binary)'company'else'fixed';leaf_min<<-if(is.null(a$minLeafRows))1 else a$minLeafRows;fit<-fit_model(r,x,a$method,if(is.null(a$lambda))0 else num(a$lambda));bad<-rowSums(is.na(x))>0;fit$raw[bad]<-NA_real_;fit$pred[bad]<-NA_real_;fit$defined<-TRUE;fit$train<-as.list(r$id[r$role=='train'&r$eligible]);fit$mass<-sum(r$w[r$role=='train'&r$eligible]);fit$invariant<-ifelse(bad,NA,TRUE);return(fit)\n }\n if(api=='evaluate'){p<-vapply(a$rows,function(v)num(v$prediction),0.0);threshold<-if(is.null(a$threshold)).5 else num(a$threshold);m<-weightedRisk(r,p,binary,threshold);records<-lapply(seq_len(nrow(r)),function(i){valid<-r$w[i]>0&&!is.na(r$y[i])&&!is.na(p[i])&&!r$role[i]%in%c('excluded','unused');list(id=r$id[i],weight=r$w[i],y=r$y[i],prediction=p[i],eligible=valid,loss=if(valid)(p[i]-r$y[i])^2 else NA_real_,correct=list(defined=valid&&binary,value=if(valid&&binary)(p[i]>=threshold)==r$y[i] else NULL))});return(list(metrics=m,records=records))}\n if(api=='select'){cs<-lapply(a$candidates,function(c)list(id=c$id,pred=vapply(c$predictions,num,0.0)));return(runSelection(r,cs,a$criterion,unlist(a$requiredCohorts),binary))}\n if(api=='paired')return(weightedPair(r,vapply(a$rows,function(v)num(v$predictionA),0.0),vapply(a$rows,function(v)num(v$predictionB),0.0)))\n stop('unknown-api')\n}\nreportValues<-function(api,z){\n ss<-list();pp<-list();add<-function(k,v,u='dimensionless')ss[[length(ss)+1]]<<-list(metric=k,value=if(is.null(v)||length(v)==0||is.na(v))NULL else unname(v),unit=u);series<-function(name,values){for(i in seq_along(values))pp[[length(pp)+1]]<<-list(series=name,index=i-1,x=i-1,y=if(is.null(values[[i]])||is.na(values[[i]]))NULL else unname(values[[i]]))}\n if(api=='split'){add('groups',z$groupCount,'groups');add('rows',length(z$records),'rows');add('finalState',z$state,'unsigned 32-bit state');series('planned role code',lapply(z$records,function(r)switch(r$role,test=0,validation=1,train=2)))}\n if(api=='fit'){add('defined',z$defined);add('trainingRows',length(z$train),'rows');add('trainingMass',z$mass,'analysis weight mass');add('modelRank',z$model$rank,'parameters');add('threshold',z$model$threshold,'constructed feature units');add('minimumObjective',z$model$minimumObjective,'constructed squared outcome units');series('prediction',as.list(z$pred));if(!is.null(z$model$theta))for(i in seq_along(z$model$theta))add(paste0('theta',i-1),z$model$theta[i],'constructed outcome units per standardized coordinate')}\n if(api=='evaluate'){for(k in c('rows','mass','MSE','MAE','R2','Brier','accuracy','positiveRecall','negativeRecall','precision','F1','balancedAccuracy','AUROC'))if(k%in%names(z$metrics))add(k,z$metrics[[k]],if(k=='rows')'rows'else if(k=='mass')'analysis weight mass'else if(k%in%c('MSE','Brier'))FIXED$unit else if(k=='MAE')if(identical(FIXED$input$task,'binary'))'probability-score units'else'constructed outcome units'else'dimensionless');series('squared loss',lapply(z$records,`[[`,'loss'))}\n if(api=='select'){add('selectedIndex',z$selectedIndex,'zero-based candidate index');for(i in seq_along(z$candidates)){c<-z$candidates[[i]];add(paste0('criterion',i-1),c$criterion,FIXED$unit);add(paste0('testMSE',i-1),c$test$MSE,FIXED$unit)};series('validation criterion',lapply(z$candidates,`[[`,'criterion'));series('test MSE',lapply(z$candidates,function(c)c$test$MSE))}\n if(api=='paired'){for(k in c('rows','mass','groupCount','meanDifference','minimumLeaveOut','maximumLeaveOut','varianceProxy'))add(k,z[[k]],if(k=='rows')'rows'else if(k=='groupCount')'groups'else if(k=='mass')'analysis weight mass'else if(k=='varianceProxy')paste(FIXED$unit,'squared')else FIXED$unit);series('loss A minus loss B',lapply(z$records,`[[`,'difference'))}\n if(api=='realdata'){add('nativeRows',z$nativeRows,'native records');add('eligibleRows',z$eligibleRows,'complete records');add('selectedIndex',z$selection$selectedIndex,'zero-based candidate index');for(i in seq_along(z$selection$candidates)){c<-z$selection$candidates[[i]];add(paste0('validationMSE',i-1),c$validation$MSE,FIXED$unit);add(paste0('testMSE',i-1),c$test$MSE,FIXED$unit)};for(k in c('meanDifference','minimumLeaveOut','maximumLeaveOut','varianceProxy'))add(k,z$paired[[k]],if(k=='varianceProxy')paste(FIXED$unit,'squared')else FIXED$unit);best<-z$selection$candidates[[z$selection$selectedIndex+1]]$test;for(k in c('accuracy','positiveRecall','negativeRecall','precision','balancedAccuracy','AUROC'))if(k%in%names(best))add(k,best[[k]]);series('validation MSE',lapply(z$selection$candidates,function(c)c$validation$MSE));series('test MSE',lapply(z$selection$candidates,function(c)c$test$MSE))}\n list(summary=ss,points=pp)\n}\n\nescapeXML<-function(s){s<-gsub('&','&amp;',s,fixed=TRUE);s<-gsub('<','&lt;',s,fixed=TRUE);s<-gsub('>','&gt;',s,fixed=TRUE);gsub('\"','&quot;',s,fixed=TRUE)}\nsvgPlot<-function(pp,title){\n xx<-vapply(pp,function(p)as.numeric(p$x),numeric(1));yy<-vapply(pp,function(p)as.numeric(p$y),numeric(1));xmin<-if(length(xx))min(xx)else 0;xmax<-if(length(xx))max(xx)else 1;ymin<-min(c(0,yy));ymax<-max(c(0,yy));if(xmin==xmax){xmin<-xmin-.5;xmax<-xmax+.5};if(ymin==ymax){ymin<-ymin-.5;ymax<-ymax+.5};pad<-(ymax-ymin)*.08;ymin<-ymin-pad;ymax<-ymax+pad;X<-function(x)82+(as.numeric(x)-xmin)/(xmax-xmin)*608;Y<-function(y)354-(as.numeric(y)-ymin)/(ymax-ymin)*290\n out<-paste0('<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"720\" height=\"480\" viewBox=\"0 0 720 480\" role=\"img\" aria-label=\"',escapeXML(title),'\"><rect width=\"720\" height=\"480\" fill=\"white\"/><g font-family=\"Arial,sans-serif\" font-size=\"13\" fill=\"#18232f\"><text x=\"360\" y=\"25\" text-anchor=\"middle\">',escapeXML(title),'</text>')\n for(j in 0:4){y<-ymin+(ymax-ymin)*j/4;x<-xmin+(xmax-xmin)*j/4;out<-paste0(out,'<line x1=\"82\" y1=\"',Y(y),'\" x2=\"690\" y2=\"',Y(y),'\" stroke=\"#e2e8f0\"/><text x=\"73\" y=\"',Y(y)+4,'\" text-anchor=\"end\">',sprintf('%.3g',y),'</text><text x=\"',X(x),'\" y=\"380\" text-anchor=\"middle\">',sprintf('%.3g',x),'</text>')}\n ss<-unique(vapply(pp,`[[`,character(1),'series'));cols<-c('#0f766e','#c76622','#4f46e5','#b23857')\n for(j in seq_along(ss)){rr<-Filter(function(p)p$series==ss[j],pp);xy<-vapply(rr,function(p)sprintf('%.6f,%.6f',X(p$x),Y(p$y)),character(1));col<-cols[(j-1)%%4+1];for(p in rr)out<-paste0(out,'<circle cx=\"',sprintf('%.6f',X(p$x)),'\" cy=\"',sprintf('%.6f',Y(p$y)),'\" r=\"2.6\" fill=\"',col,'\"><title>',escapeXML(ss[j]),': ',escapeXML(p$y),'</title></circle>');out<-paste0(out,'<text x=\"',82+((j-1)%%2)*310,'\" y=\"',432+floor((j-1)/2)*23,'\" fill=\"',col,'\">',escapeXML(ss[j]),'</text>')}\n paste0(out,'<text x=\"360\" y=\"405\" text-anchor=\"middle\">Declared record / candidate index; fixed example</text></g></svg>')\n}\ntoJSON<-function(x){\n if(is.null(x))return('null');if(is.list(x)){v<-vapply(x,toJSON,character(1));if(!is.null(names(x)))paste0('{',paste(paste0(vapply(names(x),toJSON,character(1)),':',v),collapse=','),'}')else paste0('[',paste(v,collapse=','),']')}\n else if(length(x)!=1){if(!is.numeric(x)&&!is.null(names(x)))toJSON(as.list(x))else paste0('[',paste(vapply(as.list(x),toJSON,character(1)),collapse=','),']')}\n else if(is.na(x))'null'else if(is.logical(x))if(x)'true'else'false'else if(is.numeric(x))if(is.finite(x))sprintf('%.17g',x)else'null'else paste0('\"',gsub('\\n','\\\\n',gsub('\"','\\\\\"',gsub('\\\\','\\\\\\\\',x,fixed=TRUE),fixed=TRUE),fixed=TRUE),'\"')\n}\n\nFIXED<-list(`api`=\"evaluate\",`variant`=\"weighted-regression-loss\",`title`=\"Weight mass differs from row count\",`input`=list(`rows`=list(list(`id`=\"a\",`y`=\"1\",`prediction`=\"2\",`weight`=\"1\"),list(`id`=\"b\",`y`=\"3\",`prediction`=\"1\",`weight`=\"3\"))),`unit`=\"Constructed squared outcome units\",`titleI18n`=list(`ko`=\"행 수와 다른 비중 질량\",`en`=\"Weight mass differs from row count\"))\n\nargs<-commandArgs(trailingOnly=TRUE);out<-if(length(args))args[1]else stop('NEW output directory required');if(dir.exists(out))stop('Preserve previous output directory');dir.create(out,recursive=TRUE)\nz<-fixedOperation(FIXED$api,FIXED$input);rr<-reportValues(FIXED$api,z)\nwriteLines(toJSON(list(arithmetic='BaseR binary64 author counterpart; native group hashing exact within declared integer range, stump approximate tie tolerance1e-12; not an independent exact oracle',result=z)),file.path(out,'full.json'),useBytes=TRUE)\nsums<-do.call(rbind,lapply(rr$summary,function(row)data.frame(metric=row$metric,value=if(is.null(row$value))''else if(is.logical(row$value))as.character(as.integer(row$value))else format(row$value,digits=17,scientific=NA,trim=TRUE),unit=row$unit,defined=as.integer(!is.null(row$value)),stringsAsFactors=FALSE)))\npoints<-do.call(rbind,lapply(rr$points,function(p)data.frame(series=p$series,index=p$index,x=p$x,y=if(is.null(p$y))NA_real_ else p$y,defined=as.integer(!is.null(p$y)),stringsAsFactors=FALSE)))\nwrite.csv(sums,file.path(out,'summary.csv'),row.names=FALSE,na='');write.csv(points,file.path(out,'plot-points.csv'),row.names=FALSE,na='');writeLines(svgPlot(Filter(function(p)!is.null(p$y),rr$points),FIXED$title),file.path(out,'plot.svg'),useBytes=TRUE);cat(FIXED$api,'/',FIXED$variant,'\\n',sep='')\n",
        "returnCode": 0,
        "stdout": "evaluate/weighted-regression-loss\r\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 ",
        "diagnosticScope": "Public projection omits private absolute-path/traceback frames; actual exit and warnings/reason retained. Raw complete streams and commands in private execution proof.",
        "resultFolder": "ml22-code/runs/r-evaluate-weighted-regression-loss",
        "kind": null,
        "inputFiles": [
          {
            "file": "ml22-code/evaluate-weighted-regression-loss-input.json",
            "sha256": "a75d3f805a5bb31a01cf33e0b219ac32650bc0180cf9beb471347bab828cf170",
            "scope": "Complete fixed literal input; program embeds the same values"
          }
        ],
        "files": [
          {
            "file": "ml22-code/runs/r-evaluate-weighted-regression-loss/full.json",
            "sha256": "948da042bd12719b2b11436bbe6b27651db9b4ca835c1493b4c2b6163b4befd6",
            "bytes": 527
          },
          {
            "file": "ml22-code/runs/r-evaluate-weighted-regression-loss/plot-points.csv",
            "sha256": "79695b9906449fd63731b15f0a0838746521350ecfe1edfe54180d31b3cc2149",
            "bytes": 84
          },
          {
            "file": "ml22-code/runs/r-evaluate-weighted-regression-loss/plot.svg",
            "sha256": "a1087f852a4196eee2a3fe755047e2526d39bdfea300eb55a89396a4abac9545",
            "bytes": 1519
          },
          {
            "file": "ml22-code/runs/r-evaluate-weighted-regression-loss/summary.csv",
            "sha256": "af6941a8dd5a90d0d6d46d3e3a082d02e97b86c4432765b07af40266aeeb418f",
            "bytes": 234
          }
        ],
        "summaryRows": [
          {
            "metric": "rows",
            "value": "2.0",
            "unit": "rows",
            "defined": "true",
            "rawValue": "2",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "mass",
            "value": "4.0",
            "unit": "analysis weight mass",
            "defined": "true",
            "rawValue": "4",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "MSE",
            "value": "3.25",
            "unit": "Constructed squared outcome units",
            "defined": "true",
            "rawValue": "3.25",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "MAE",
            "value": "1.75",
            "unit": "constructed outcome units",
            "defined": "true",
            "rawValue": "1.75",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "R2",
            "value": "-3.333333333333333",
            "unit": "dimensionless",
            "defined": "true",
            "rawValue": "-3.333333333333333",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": false,
            "mathematicallyNegative": true,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          }
        ],
        "plotRows": [
          {
            "series": "squared loss",
            "index": "0",
            "x": "0",
            "y": "1",
            "defined": true,
            "xExact": null,
            "yExact": null
          },
          {
            "series": "squared loss",
            "index": "1",
            "x": "1",
            "y": "4",
            "defined": true,
            "xExact": null,
            "yExact": null
          }
        ],
        "plotFile": "ml22-code/runs/r-evaluate-weighted-regression-loss/plot.svg",
        "fullResultFile": "ml22-code/runs/r-evaluate-weighted-regression-loss/full.json",
        "arithmeticScope": "Python exact rational versus base-R approximate floating algebra; copied author kernels, not independent oracle.",
        "plotScope": "Original scatter vectors plot every defined declared comparison point, with missing points omitted. Source profiles show candidate risks; all source records remain in the full result and source CSV files.",
        "reproductionScope": "Standalone literal program plus four native CSV files for factual source profiles. No answer/engine/checker imports."
      },
      "weighted-AUC-tie": {
        "api": "evaluate",
        "variant": "weighted-AUC-tie",
        "language": "r",
        "title": "Weighted AUC with a positive-negative score tie",
        "titleI18n": {
          "ko": "양성·음성 점수 동률의 가중 AUC",
          "en": "Weighted AUC with a positive-negative score tie"
        },
        "input": {
          "task": "binary",
          "rows": [
            {
              "id": "p",
              "y": "1",
              "prediction": "4/5",
              "weight": "2"
            },
            {
              "id": "n1",
              "y": "0",
              "prediction": "3/10"
            },
            {
              "id": "n2",
              "y": "0",
              "prediction": "4/5"
            }
          ]
        },
        "expectedFailure": false,
        "codeFile": "ml22-code/evaluate-weighted-AUC-tie.R",
        "codeSHA256": "14439bfb7d07192d7af5b18b4e5b819c67a0c05cd3d992bbf7dd4e29df372744",
        "code": "# ML22 standalone; source/public functions copied by value, no source() dependency.\noptions(stringsAsFactors=FALSE,digits=17,warn=1)\nargs0<-commandArgs(trailingOnly=FALSE);script0<-sub('^--file=','',args0[grepl('^--file=',args0)][1]);source_dir<-file.path(dirname(normalizePath(script0)), 'data');seed<-20261104;leaf_min<-5\nnative_hash <- c(\"actual1599-red-wine-original12-fields.csv\"=\"77e9ac73115930d6c43983333a5a57940deefc493affeb17aca478c09c5f6e00\",\"actual4898-white-wine-original12-fields.csv\"=\"50d810bbb42b9cc3e87fa4c27a4c0f168e72da09dd812863425ca3873fec28ef\",\"actual3613-NLS-original52-fields.csv\"=\"6e1e1895558795435b65f8634252a7589865273a0e69adbd715fcfa04a3c11a1\",\"actual3150-churn-original14-fields.csv\"=\"1c0753e434226e769d1015c922121a7d8967df66014e057c4f7543e490f11764\")\nsha256<-getExportedValue('tools','sha256sum')\nread_native<-function(name){f<-file.path(source_dir,name);if(unname(sha256(f))!=native_hash[[name]])stop(paste('Native hash differs',name));read.csv(f,check.names=FALSE,colClasses='character',na.strings=NULL)}\ngcd_small<-function(a,b){while(b!=0){r<-a%%b;a<-b;b<-r};a}\ncanonical<-function(token){\n if(is.na(token)||token%in%c('','.'))return('null')\n if(!grepl('^[+-]?[0-9]+([.][0-9]*)?$',token))stop('Unsupported native fingerprint token')\n neg<-substr(token,1,1)=='-';s<-sub('^[+-]','',token);parts<-strsplit(s,'.',fixed=TRUE)[[1]];dec<-if(length(parts)==2)nchar(parts[2])else 0;n<-as.numeric(gsub('.','',s,fixed=TRUE));d<-10^dec\n # Every native fingerprint numerator/denominator must remain exactly integral\n # in binary64; reject rather than silently rounding a changed future source.\n if(!is.finite(n)||n>2^53||d>2^53)stop('Native canonical integer range exceeded')\n g<-gcd_small(n,d);n<-n/g;d<-d/g;if(neg)n<--n\n out<-sprintf('%.0f',n);if(d!=1)out<-paste0(out,'/',sprintf('%.0f',d));out\n}\nfp_cache<-new.env(hash=TRUE,parent=emptyenv());hash_file<-tempfile('ml22-hash-')\nfingerprint<-function(tag,values){a<-vapply(values,canonical,'');payload<-paste0('[',paste0('\"',a,'\"',collapse=','),']');key<-paste0(tag,':',payload);if(exists(key,fp_cache,inherits=FALSE))return(get(key,fp_cache,inherits=FALSE));con<-file(hash_file,'wb');writeBin(charToRaw(payload),con);close(con);value<-paste0(tag,':',unname(sha256(hash_file)));assign(key,value,fp_cache);value}\nassign_roles<-function(group){order<-sort(unique(group),method='radix');state<-seed;if(length(order)>1)for(j in seq.int(length(order),2)){state<-(1664525*state+1013904223)%%2^32;k<-state%%j+1;order[c(j,k)]<-order[c(k,j)]};rank<-match(group,order)-1;list(rank=rank,planned=c('test','validation','train','train')[rank%%4+1],state=state)}\n\nfit_model<-function(r,x,method,lambda){\n tr<-which(r$role=='train'&r$eligible);if(!length(tr))stop('No complete positive training rows');y<-r$y[tr];xx<-x[tr,,drop=FALSE];mu<-colMeans(xx);scale<-apply(xx,2,function(v)diff(range(v)));scale[scale==0]<-1;z<-cbind(1,sweep(sweep(x,2,mu,'-'),2,scale,'/'));meanY<-mean(y);model<-list();n<-length(tr)\n if(method=='constant'){model<-list(mean=meanY,parameterCount=1,rank=1,unique=TRUE);raw<-rep(meanY,nrow(r))}\n else if(method=='ridge'){zt<-z[tr,,drop=FALSE];pen<-diag(c(0,rep(lambda,ncol(x))));theta<-drop(solve(crossprod(zt)/n+pen,crossprod(zt,y)/n));raw<-drop(z%*%theta);objective<-mean((y-raw[tr])^2)/2+lambda*sum(theta[-1]^2)/2;model<-list(lambdaValue=lambda,theta=theta,rank=length(theta),unique=TRUE,minimumObjective=objective,parameterCount=length(theta))}\n else{base<-sum((y-meanY)^2);best<-NULL;total<-sum(y);total2<-sum(y*y)\n  for(j in seq_len(ncol(x))){ord<-order(xx[,j],seq_len(n));sx<-xx[ord,j];sy<-y[ord];left<-cumsum(sy)\n   if(n<2*leaf_min)next\n   for(i in seq.int(leaf_min,n-leaf_min)){if(sx[i]==sx[i+1])next;loss<-total2-left[i]^2/i-(total-left[i])^2/(n-i)\n    # Explicit approximate-tie tolerance; exact source JavaScript/Python\n    # contracts are authoritative for general arbitrarily close ties.\n    if(is.null(best)||loss<best$weightedSSE-1e-12*max(1,abs(loss),abs(best$weightedSSE)))best<-list(feature=j-1,threshold=(sx[i]+sx[i+1])/2,leftMean=left[i]/i,rightMean=(total-left[i])/(n-i),leftRows=i,rightRows=n-i,leftWeight=i,rightWeight=n-i,weightedSSE=loss)\n   }\n  }\n  if(is.null(best)||best$weightedSSE>=base-1e-12*max(1,abs(base))){model<-list(split=FALSE,mean=meanY,weightedSSE=base,trainingMSE=base/n);raw<-rep(meanY,nrow(r))}else{model<-c(list(split=TRUE),best,list(trainingMSE=best$weightedSSE/n,improvement=(base-best$weightedSSE)/n));raw<-ifelse(x[,model$feature+1]<=model$threshold,model$leftMean,model$rightMean)}\n }\n pred<-if(r$dataset[1]=='company')pmax(0,pmin(1,raw))else raw;list(meanX=mu,scales=scale,model=model,raw=raw,pred=pred)\n}\n\n# New standalone fixed-profile adapters; native and fit helpers copied by value.\nnum<-function(x){if(is.null(x)||length(x)==0||is.na(x)||x%in%c('','.'))return(NA_real_);if(is.character(x)&&grepl('/',x,fixed=TRUE)){v<-strsplit(x,'/',fixed=TRUE)[[1]];return(as.numeric(v[1])/as.numeric(v[2]))};as.numeric(x)}\nfixedRows<-function(aa){\n rr<-lapply(seq_along(aa),function(i){a<-aa[[i]];w<-num(if(is.null(a$weight))'1'else a$weight);if(is.na(w)||w<0)stop(if(!is.na(w)&&w<0)'negative-weight'else'missing-weight');list(id=if(is.null(a$id))as.character(i-1)else a$id,group=if(is.null(a$group))if(is.null(a$id))as.character(i-1)else a$id else a$group,cohort=if(is.null(a$cohort))'all'else a$cohort,role=if(is.null(a$role))'train'else a$role,w=w,y=num(a$y),x=vapply(a$x,num,0.0))})\n p<-if(length(rr))length(rr[[1]]$x)else 0;xx<-matrix(NA_real_,length(rr),p)\n if(p)for(i in seq_along(rr))xx[i,]<-rr[[i]]$x\n r<-data.frame(id=vapply(rr,`[[`,'','id'),group=vapply(rr,`[[`,'','group'),cohort=vapply(rr,`[[`,'','cohort'),role=vapply(rr,`[[`,'','role'),w=vapply(rr,`[[`,0.0,'w'),y=vapply(rr,`[[`,0.0,'y'));r$eligible<-!is.na(r$y)&rowSums(is.na(xx))==0&r$w>0;list(r=r,x=xx)\n}\nweightedRisk<-function(r,p,binary=FALSE,threshold=.5){\n ii<-which(r$w>0&!is.na(r$y)&!is.na(p)&!r$role%in%c('excluded','unused'));y<-r$y[ii];p<-p[ii];w<-r$w[ii];W<-sum(w);d<-list(rows=length(ii),mass=W,MSE=NA_real_,MAE=NA_real_,R2=NA_real_)\n if(W==0){if(binary)d<-c(d,setNames(rep(list(NA_real_),10),c('Brier','accuracy','positiveRecall','negativeRecall','precision','F1','balancedAccuracy','AUROC','positiveMass','negativeMass')));return(d)}\n mu<-sum(w*y)/W;sse<-sum(w*(p-y)^2);sst<-sum(w*(y-mu)^2);d<-c(d,list(meanY=mu,SSE=sse,SST=sst));d$MSE<-sse/W;d$MAE<-sum(w*abs(p-y))/W;d$R2<-if(sst>0)1-sse/sst else NA_real_\n if(binary){pos<-y==1;yes<-p>=threshold;TP<-sum(w[pos&yes]);FP<-sum(w[!pos&yes]);TN<-sum(w[!pos&!yes]);FN<-sum(w[pos&!yes]);rate<-function(a,b)if(b>0)a/b else NA_real_;tpr<-rate(TP,TP+FN);tnr<-rate(TN,TN+FP);auc<-NA_real_;P<-sum(w[pos]);N<-sum(w[!pos]);if(P>0&&N>0){wins<-sum(vapply(which(pos),function(i)sum(w[i]*w[!pos]*ifelse(p[i]>p[!pos],1,ifelse(p[i]==p[!pos],.5,0))),0.0));auc<-wins/(P*N)};d<-c(d,list(Brier=d$MSE,threshold=threshold,confusionMass=list(TP=TP,FP=FP,TN=TN,FN=FN),confusionRows=list(TP=sum(pos&yes),FP=sum(!pos&yes),TN=sum(!pos&!yes),FN=sum(pos&!yes)),positiveMass=P,negativeMass=N,accuracy=(TP+TN)/W,positiveRecall=tpr,negativeRecall=tnr,precision=rate(TP,TP+FP),F1=rate(2*TP,2*TP+FP+FN),balancedAccuracy=if(is.finite(tpr)&&is.finite(tnr))(tpr+tnr)/2 else NA_real_,AUROC=auc))};d\n}\nweightedPair<-function(r,A,B){\n ii<-which(r$w>0&!is.na(r$y)&!is.na(A)&!is.na(B)&!r$role%in%c('excluded','unused'));rr<-r[ii,,drop=FALSE];la<-(A[ii]-rr$y)^2;lb<-(B[ii]-rr$y)^2;d<-la-lb;W<-sum(rr$w);S<-sum(rr$w*d);mu<-if(W>0)S/W else NA_real_;ids<-unique(rr$group);groups<-lapply(ids,function(g){jj<-which(rr$group==g);wg<-sum(rr$w[jj]);sg<-sum(rr$w[jj]*d[jj]);list(group=g,rows=length(jj),mass=wg,sum=sg,leaveOut=if(W>wg)(S-sg)/(W-wg)else NA_real_)});leaves<-vapply(groups,`[[`,0.0,'leaveOut');G<-length(groups);proxy<-if(G>1&&all(is.finite(leaves)))(G-1)/G*sum((leaves-mean(leaves))^2) else NA_real_\n list(rows=length(ii),mass=W,groupCount=G,meanDifference=mu,minimumLeaveOut=if(any(is.finite(leaves)))min(leaves,na.rm=TRUE)else NA_real_,maximumLeaveOut=if(any(is.finite(leaves)))max(leaves,na.rm=TRUE)else NA_real_,varianceProxy=proxy,groups=groups,records=lapply(seq_along(ii),function(j)list(id=rr$id[j],group=rr$group[j],weight=rr$w[j],lossA=la[j],lossB=lb[j],difference=d[j])))\n}\nrunSelection<-function(r,candidates,criterion,required,binary=FALSE){\n out<-lapply(candidates,function(c){v<-r;t<-r;v$role[v$role!='validation']<-'excluded';t$role[t$role!='test']<-'excluded';val<-weightedRisk(v,c$pred,binary);test<-weightedRisk(t,c$pred,binary);co<-setNames(lapply(required,function(g){z<-v;z$role[z$cohort!=g]<-'excluded';weightedRisk(z,c$pred,binary)}),required);vv<-vapply(co,`[[`,0.0,'MSE');score<-if(criterion=='mean')val$MSE else if(length(vv)&&all(is.finite(vv)))max(vv)else NA_real_;list(id=c$id,criterion=score,validation=val,test=test,cohorts=co)})\n scores<-vapply(out,`[[`,0.0,'criterion');eligible<-which(is.finite(scores));k<-if(length(eligible))eligible[which.min(scores[eligible])]else NA_integer_;list(criterion=criterion,selected=if(!is.na(k))out[[k]]$id else NULL,selectedIndex=if(!is.na(k))k-1 else NA_real_,candidates=out)\n}\nfixedOperation<-function(api,a){\n if(api=='realdata'){\n  kind<-a$kind;r<-rows[[kind]];x<-X[[kind]];asgn<-assign_roles(r$group);r$dataset<-kind;r$splitRank<-asgn$rank;r$plannedRole<-asgn$planned;r$eligible<-!is.na(r$y)&rowSums(is.na(x))==0;r$role<-ifelse(r$eligible,r$plannedRole,'excluded');r$w<-1;binary<-kind=='company';leaf_min<<-5\n  defs<-data.frame(id=c('constant','ridge:1/100','ridge:1/10','ridge:1','one-split-stump'),method=c('constant','ridge','ridge','ridge','stump'),lambda=c(0,.01,.1,1,0));fits<-lapply(seq_len(5),function(i)fit_model(r,x,defs$method[i],defs$lambda[i]));candidates<-lapply(seq_len(5),function(i)list(id=defs$id[i],pred=fits[[i]]$pred));selection<-runSelection(r,candidates,a$criterion,unique(r$cohort),binary);k<-selection$selectedIndex+1;best<-fits[[k]];base<-fits[[1]];test<-r;test$role[test$role!='test']<-'excluded';paired<-weightedPair(test,best$pred,base$pred)\n  records<-lapply(seq_len(nrow(r)),function(i)list(id=r$id[i],sourceRow=r$sourceRow[i],originalID=r$originalID[i],group=r$group[i],cohort=r$cohort[i],plannedRole=r$plannedRole[i],role=r$role[i],eligible=r$eligible[i],y=r$y[i],baselinePrediction=base$pred[i],selectedPrediction=best$pred[i],selectedRawPrediction=best$raw[i],queryInvariant=TRUE))\n  return(list(kind=kind,nativeRows=nrow(r),eligibleRows=sum(r$eligible),selection=selection,models=lapply(seq_len(5),function(i)list(id=defs$id[i],train=as.list(r$id[r$role=='train']),mass=sum(r$role=='train'),meanX=fits[[i]]$meanX,scales=fits[[i]]$scales,model=fits[[i]]$model)),paired=paired,records=records))\n }\n f<-fixedRows(a$rows);r<-f$r;x<-f$x;binary<-identical(a$task,'binary')\n if(api=='split'){seed<<-a$seed;asgn<-assign_roles(r$group);return(list(state=asgn$state,groupCount=length(unique(r$group)),records=lapply(seq_len(nrow(r)),function(i)list(id=r$id[i],group=r$group[i],rank=asgn$rank[i],role=asgn$planned[i]))))}\n if(api=='fit'){\n  r$dataset<-if(binary)'company'else'fixed';leaf_min<<-if(is.null(a$minLeafRows))1 else a$minLeafRows;fit<-fit_model(r,x,a$method,if(is.null(a$lambda))0 else num(a$lambda));bad<-rowSums(is.na(x))>0;fit$raw[bad]<-NA_real_;fit$pred[bad]<-NA_real_;fit$defined<-TRUE;fit$train<-as.list(r$id[r$role=='train'&r$eligible]);fit$mass<-sum(r$w[r$role=='train'&r$eligible]);fit$invariant<-ifelse(bad,NA,TRUE);return(fit)\n }\n if(api=='evaluate'){p<-vapply(a$rows,function(v)num(v$prediction),0.0);threshold<-if(is.null(a$threshold)).5 else num(a$threshold);m<-weightedRisk(r,p,binary,threshold);records<-lapply(seq_len(nrow(r)),function(i){valid<-r$w[i]>0&&!is.na(r$y[i])&&!is.na(p[i])&&!r$role[i]%in%c('excluded','unused');list(id=r$id[i],weight=r$w[i],y=r$y[i],prediction=p[i],eligible=valid,loss=if(valid)(p[i]-r$y[i])^2 else NA_real_,correct=list(defined=valid&&binary,value=if(valid&&binary)(p[i]>=threshold)==r$y[i] else NULL))});return(list(metrics=m,records=records))}\n if(api=='select'){cs<-lapply(a$candidates,function(c)list(id=c$id,pred=vapply(c$predictions,num,0.0)));return(runSelection(r,cs,a$criterion,unlist(a$requiredCohorts),binary))}\n if(api=='paired')return(weightedPair(r,vapply(a$rows,function(v)num(v$predictionA),0.0),vapply(a$rows,function(v)num(v$predictionB),0.0)))\n stop('unknown-api')\n}\nreportValues<-function(api,z){\n ss<-list();pp<-list();add<-function(k,v,u='dimensionless')ss[[length(ss)+1]]<<-list(metric=k,value=if(is.null(v)||length(v)==0||is.na(v))NULL else unname(v),unit=u);series<-function(name,values){for(i in seq_along(values))pp[[length(pp)+1]]<<-list(series=name,index=i-1,x=i-1,y=if(is.null(values[[i]])||is.na(values[[i]]))NULL else unname(values[[i]]))}\n if(api=='split'){add('groups',z$groupCount,'groups');add('rows',length(z$records),'rows');add('finalState',z$state,'unsigned 32-bit state');series('planned role code',lapply(z$records,function(r)switch(r$role,test=0,validation=1,train=2)))}\n if(api=='fit'){add('defined',z$defined);add('trainingRows',length(z$train),'rows');add('trainingMass',z$mass,'analysis weight mass');add('modelRank',z$model$rank,'parameters');add('threshold',z$model$threshold,'constructed feature units');add('minimumObjective',z$model$minimumObjective,'constructed squared outcome units');series('prediction',as.list(z$pred));if(!is.null(z$model$theta))for(i in seq_along(z$model$theta))add(paste0('theta',i-1),z$model$theta[i],'constructed outcome units per standardized coordinate')}\n if(api=='evaluate'){for(k in c('rows','mass','MSE','MAE','R2','Brier','accuracy','positiveRecall','negativeRecall','precision','F1','balancedAccuracy','AUROC'))if(k%in%names(z$metrics))add(k,z$metrics[[k]],if(k=='rows')'rows'else if(k=='mass')'analysis weight mass'else if(k%in%c('MSE','Brier'))FIXED$unit else if(k=='MAE')if(identical(FIXED$input$task,'binary'))'probability-score units'else'constructed outcome units'else'dimensionless');series('squared loss',lapply(z$records,`[[`,'loss'))}\n if(api=='select'){add('selectedIndex',z$selectedIndex,'zero-based candidate index');for(i in seq_along(z$candidates)){c<-z$candidates[[i]];add(paste0('criterion',i-1),c$criterion,FIXED$unit);add(paste0('testMSE',i-1),c$test$MSE,FIXED$unit)};series('validation criterion',lapply(z$candidates,`[[`,'criterion'));series('test MSE',lapply(z$candidates,function(c)c$test$MSE))}\n if(api=='paired'){for(k in c('rows','mass','groupCount','meanDifference','minimumLeaveOut','maximumLeaveOut','varianceProxy'))add(k,z[[k]],if(k=='rows')'rows'else if(k=='groupCount')'groups'else if(k=='mass')'analysis weight mass'else if(k=='varianceProxy')paste(FIXED$unit,'squared')else FIXED$unit);series('loss A minus loss B',lapply(z$records,`[[`,'difference'))}\n if(api=='realdata'){add('nativeRows',z$nativeRows,'native records');add('eligibleRows',z$eligibleRows,'complete records');add('selectedIndex',z$selection$selectedIndex,'zero-based candidate index');for(i in seq_along(z$selection$candidates)){c<-z$selection$candidates[[i]];add(paste0('validationMSE',i-1),c$validation$MSE,FIXED$unit);add(paste0('testMSE',i-1),c$test$MSE,FIXED$unit)};for(k in c('meanDifference','minimumLeaveOut','maximumLeaveOut','varianceProxy'))add(k,z$paired[[k]],if(k=='varianceProxy')paste(FIXED$unit,'squared')else FIXED$unit);best<-z$selection$candidates[[z$selection$selectedIndex+1]]$test;for(k in c('accuracy','positiveRecall','negativeRecall','precision','balancedAccuracy','AUROC'))if(k%in%names(best))add(k,best[[k]]);series('validation MSE',lapply(z$selection$candidates,function(c)c$validation$MSE));series('test MSE',lapply(z$selection$candidates,function(c)c$test$MSE))}\n list(summary=ss,points=pp)\n}\n\nescapeXML<-function(s){s<-gsub('&','&amp;',s,fixed=TRUE);s<-gsub('<','&lt;',s,fixed=TRUE);s<-gsub('>','&gt;',s,fixed=TRUE);gsub('\"','&quot;',s,fixed=TRUE)}\nsvgPlot<-function(pp,title){\n xx<-vapply(pp,function(p)as.numeric(p$x),numeric(1));yy<-vapply(pp,function(p)as.numeric(p$y),numeric(1));xmin<-if(length(xx))min(xx)else 0;xmax<-if(length(xx))max(xx)else 1;ymin<-min(c(0,yy));ymax<-max(c(0,yy));if(xmin==xmax){xmin<-xmin-.5;xmax<-xmax+.5};if(ymin==ymax){ymin<-ymin-.5;ymax<-ymax+.5};pad<-(ymax-ymin)*.08;ymin<-ymin-pad;ymax<-ymax+pad;X<-function(x)82+(as.numeric(x)-xmin)/(xmax-xmin)*608;Y<-function(y)354-(as.numeric(y)-ymin)/(ymax-ymin)*290\n out<-paste0('<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"720\" height=\"480\" viewBox=\"0 0 720 480\" role=\"img\" aria-label=\"',escapeXML(title),'\"><rect width=\"720\" height=\"480\" fill=\"white\"/><g font-family=\"Arial,sans-serif\" font-size=\"13\" fill=\"#18232f\"><text x=\"360\" y=\"25\" text-anchor=\"middle\">',escapeXML(title),'</text>')\n for(j in 0:4){y<-ymin+(ymax-ymin)*j/4;x<-xmin+(xmax-xmin)*j/4;out<-paste0(out,'<line x1=\"82\" y1=\"',Y(y),'\" x2=\"690\" y2=\"',Y(y),'\" stroke=\"#e2e8f0\"/><text x=\"73\" y=\"',Y(y)+4,'\" text-anchor=\"end\">',sprintf('%.3g',y),'</text><text x=\"',X(x),'\" y=\"380\" text-anchor=\"middle\">',sprintf('%.3g',x),'</text>')}\n ss<-unique(vapply(pp,`[[`,character(1),'series'));cols<-c('#0f766e','#c76622','#4f46e5','#b23857')\n for(j in seq_along(ss)){rr<-Filter(function(p)p$series==ss[j],pp);xy<-vapply(rr,function(p)sprintf('%.6f,%.6f',X(p$x),Y(p$y)),character(1));col<-cols[(j-1)%%4+1];for(p in rr)out<-paste0(out,'<circle cx=\"',sprintf('%.6f',X(p$x)),'\" cy=\"',sprintf('%.6f',Y(p$y)),'\" r=\"2.6\" fill=\"',col,'\"><title>',escapeXML(ss[j]),': ',escapeXML(p$y),'</title></circle>');out<-paste0(out,'<text x=\"',82+((j-1)%%2)*310,'\" y=\"',432+floor((j-1)/2)*23,'\" fill=\"',col,'\">',escapeXML(ss[j]),'</text>')}\n paste0(out,'<text x=\"360\" y=\"405\" text-anchor=\"middle\">Declared record / candidate index; fixed example</text></g></svg>')\n}\ntoJSON<-function(x){\n if(is.null(x))return('null');if(is.list(x)){v<-vapply(x,toJSON,character(1));if(!is.null(names(x)))paste0('{',paste(paste0(vapply(names(x),toJSON,character(1)),':',v),collapse=','),'}')else paste0('[',paste(v,collapse=','),']')}\n else if(length(x)!=1){if(!is.numeric(x)&&!is.null(names(x)))toJSON(as.list(x))else paste0('[',paste(vapply(as.list(x),toJSON,character(1)),collapse=','),']')}\n else if(is.na(x))'null'else if(is.logical(x))if(x)'true'else'false'else if(is.numeric(x))if(is.finite(x))sprintf('%.17g',x)else'null'else paste0('\"',gsub('\\n','\\\\n',gsub('\"','\\\\\"',gsub('\\\\','\\\\\\\\',x,fixed=TRUE),fixed=TRUE),fixed=TRUE),'\"')\n}\n\nFIXED<-list(`api`=\"evaluate\",`variant`=\"weighted-AUC-tie\",`title`=\"Weighted AUC with a positive-negative score tie\",`input`=list(`task`=\"binary\",`rows`=list(list(`id`=\"p\",`y`=\"1\",`prediction`=\"4/5\",`weight`=\"2\"),list(`id`=\"n1\",`y`=\"0\",`prediction`=\"3/10\"),list(`id`=\"n2\",`y`=\"0\",`prediction`=\"4/5\"))),`unit`=\"Squared probability-score units; one-component Brier loss\",`titleI18n`=list(`ko`=\"양성·음성 점수 동률의 가중 AUC\",`en`=\"Weighted AUC with a positive-negative score tie\"))\n\nargs<-commandArgs(trailingOnly=TRUE);out<-if(length(args))args[1]else stop('NEW output directory required');if(dir.exists(out))stop('Preserve previous output directory');dir.create(out,recursive=TRUE)\nz<-fixedOperation(FIXED$api,FIXED$input);rr<-reportValues(FIXED$api,z)\nwriteLines(toJSON(list(arithmetic='BaseR binary64 author counterpart; native group hashing exact within declared integer range, stump approximate tie tolerance1e-12; not an independent exact oracle',result=z)),file.path(out,'full.json'),useBytes=TRUE)\nsums<-do.call(rbind,lapply(rr$summary,function(row)data.frame(metric=row$metric,value=if(is.null(row$value))''else if(is.logical(row$value))as.character(as.integer(row$value))else format(row$value,digits=17,scientific=NA,trim=TRUE),unit=row$unit,defined=as.integer(!is.null(row$value)),stringsAsFactors=FALSE)))\npoints<-do.call(rbind,lapply(rr$points,function(p)data.frame(series=p$series,index=p$index,x=p$x,y=if(is.null(p$y))NA_real_ else p$y,defined=as.integer(!is.null(p$y)),stringsAsFactors=FALSE)))\nwrite.csv(sums,file.path(out,'summary.csv'),row.names=FALSE,na='');write.csv(points,file.path(out,'plot-points.csv'),row.names=FALSE,na='');writeLines(svgPlot(Filter(function(p)!is.null(p$y),rr$points),FIXED$title),file.path(out,'plot.svg'),useBytes=TRUE);cat(FIXED$api,'/',FIXED$variant,'\\n',sep='')\n",
        "returnCode": 0,
        "stdout": "evaluate/weighted-AUC-tie\r\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 ",
        "diagnosticScope": "Public projection omits private absolute-path/traceback frames; actual exit and warnings/reason retained. Raw complete streams and commands in private execution proof.",
        "resultFolder": "ml22-code/runs/r-evaluate-weighted-AUC-tie",
        "kind": null,
        "inputFiles": [
          {
            "file": "ml22-code/evaluate-weighted-AUC-tie-input.json",
            "sha256": "1268c9008fa9802867bb14729863f3bccbedd233243e96e6f2ade25c1c552dac",
            "scope": "Complete fixed literal input; program embeds the same values"
          }
        ],
        "files": [
          {
            "file": "ml22-code/runs/r-evaluate-weighted-AUC-tie/full.json",
            "sha256": "67b5c3024f5ecf9cd500e59b2ab36ebb752b9896deab3ec7a17ecce886e6bdc1",
            "bytes": 1099
          },
          {
            "file": "ml22-code/runs/r-evaluate-weighted-AUC-tie/plot-points.csv",
            "sha256": "1f20bdef5fcbbd378a15465628360d3853651ee5c73bba28e3fd788e991fb1ad",
            "bytes": 117
          },
          {
            "file": "ml22-code/runs/r-evaluate-weighted-AUC-tie/plot.svg",
            "sha256": "1d611845f83f94a10bfc78fd48d88276991612b4f5b458c06f11af3b48e6bbbe",
            "bytes": 1660
          },
          {
            "file": "ml22-code/runs/r-evaluate-weighted-AUC-tie/summary.csv",
            "sha256": "714748fc7e0e53153083cc1f7cfbefffe0b8b43da601567cbef8352bc63d82c0",
            "bytes": 663
          }
        ],
        "summaryRows": [
          {
            "metric": "rows",
            "value": "3.0",
            "unit": "rows",
            "defined": "true",
            "rawValue": "3",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "mass",
            "value": "4.0",
            "unit": "analysis weight mass",
            "defined": "true",
            "rawValue": "4",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "MSE",
            "value": "0.2025",
            "unit": "Squared probability-score units; one-component Brier loss",
            "defined": "true",
            "rawValue": "0.20250000000000001",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "MAE",
            "value": "0.375",
            "unit": "probability-score units",
            "defined": "true",
            "rawValue": "0.375",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "R2",
            "value": "0.18999999999999995",
            "unit": "dimensionless",
            "defined": "true",
            "rawValue": "0.18999999999999995",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "Brier",
            "value": "0.2025",
            "unit": "Squared probability-score units; one-component Brier loss",
            "defined": "true",
            "rawValue": "0.20250000000000001",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "accuracy",
            "value": "0.75",
            "unit": "dimensionless",
            "defined": "true",
            "rawValue": "0.75",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "positiveRecall",
            "value": "1.0",
            "unit": "dimensionless",
            "defined": "true",
            "rawValue": "1",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "negativeRecall",
            "value": "0.5",
            "unit": "dimensionless",
            "defined": "true",
            "rawValue": "0.5",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "precision",
            "value": "0.6666666666666666",
            "unit": "dimensionless",
            "defined": "true",
            "rawValue": "0.66666666666666663",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "F1",
            "value": "0.8",
            "unit": "dimensionless",
            "defined": "true",
            "rawValue": "0.80000000000000004",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "balancedAccuracy",
            "value": "0.75",
            "unit": "dimensionless",
            "defined": "true",
            "rawValue": "0.75",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "AUROC",
            "value": "0.75",
            "unit": "dimensionless",
            "defined": "true",
            "rawValue": "0.75",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          }
        ],
        "plotRows": [
          {
            "series": "squared loss",
            "index": "0",
            "x": "0",
            "y": "0.04",
            "defined": true,
            "xExact": null,
            "yExact": null
          },
          {
            "series": "squared loss",
            "index": "1",
            "x": "1",
            "y": "0.09",
            "defined": true,
            "xExact": null,
            "yExact": null
          },
          {
            "series": "squared loss",
            "index": "2",
            "x": "2",
            "y": "0.64",
            "defined": true,
            "xExact": null,
            "yExact": null
          }
        ],
        "plotFile": "ml22-code/runs/r-evaluate-weighted-AUC-tie/plot.svg",
        "fullResultFile": "ml22-code/runs/r-evaluate-weighted-AUC-tie/full.json",
        "arithmeticScope": "Python exact rational versus base-R approximate floating algebra; copied author kernels, not independent oracle.",
        "plotScope": "Original scatter vectors plot every defined declared comparison point, with missing points omitted. Source profiles show candidate risks; all source records remain in the full result and source CSV files.",
        "reproductionScope": "Standalone literal program plus four native CSV files for factual source profiles. No answer/engine/checker imports."
      },
      "no-predicted-positive-missing-label": {
        "api": "evaluate",
        "variant": "no-predicted-positive-missing-label",
        "language": "r",
        "title": "No positive predictions and a missing label",
        "titleI18n": {
          "ko": "양성 예측 없음과 결측 정답",
          "en": "No positive predictions and a missing label"
        },
        "input": {
          "task": "binary",
          "rows": [
            {
              "id": "n",
              "y": "0",
              "prediction": "0"
            },
            {
              "id": "p",
              "y": "1",
              "prediction": "1/4"
            },
            {
              "id": "unknown",
              "y": null,
              "prediction": "0"
            }
          ]
        },
        "expectedFailure": false,
        "codeFile": "ml22-code/evaluate-no-predicted-positive-missing-label.R",
        "codeSHA256": "c59f692e07a519358e00ded65be5b6fb1285a243325e960a71e38755200ef83e",
        "code": "# ML22 standalone; source/public functions copied by value, no source() dependency.\noptions(stringsAsFactors=FALSE,digits=17,warn=1)\nargs0<-commandArgs(trailingOnly=FALSE);script0<-sub('^--file=','',args0[grepl('^--file=',args0)][1]);source_dir<-file.path(dirname(normalizePath(script0)), 'data');seed<-20261104;leaf_min<-5\nnative_hash <- c(\"actual1599-red-wine-original12-fields.csv\"=\"77e9ac73115930d6c43983333a5a57940deefc493affeb17aca478c09c5f6e00\",\"actual4898-white-wine-original12-fields.csv\"=\"50d810bbb42b9cc3e87fa4c27a4c0f168e72da09dd812863425ca3873fec28ef\",\"actual3613-NLS-original52-fields.csv\"=\"6e1e1895558795435b65f8634252a7589865273a0e69adbd715fcfa04a3c11a1\",\"actual3150-churn-original14-fields.csv\"=\"1c0753e434226e769d1015c922121a7d8967df66014e057c4f7543e490f11764\")\nsha256<-getExportedValue('tools','sha256sum')\nread_native<-function(name){f<-file.path(source_dir,name);if(unname(sha256(f))!=native_hash[[name]])stop(paste('Native hash differs',name));read.csv(f,check.names=FALSE,colClasses='character',na.strings=NULL)}\ngcd_small<-function(a,b){while(b!=0){r<-a%%b;a<-b;b<-r};a}\ncanonical<-function(token){\n if(is.na(token)||token%in%c('','.'))return('null')\n if(!grepl('^[+-]?[0-9]+([.][0-9]*)?$',token))stop('Unsupported native fingerprint token')\n neg<-substr(token,1,1)=='-';s<-sub('^[+-]','',token);parts<-strsplit(s,'.',fixed=TRUE)[[1]];dec<-if(length(parts)==2)nchar(parts[2])else 0;n<-as.numeric(gsub('.','',s,fixed=TRUE));d<-10^dec\n # Every native fingerprint numerator/denominator must remain exactly integral\n # in binary64; reject rather than silently rounding a changed future source.\n if(!is.finite(n)||n>2^53||d>2^53)stop('Native canonical integer range exceeded')\n g<-gcd_small(n,d);n<-n/g;d<-d/g;if(neg)n<--n\n out<-sprintf('%.0f',n);if(d!=1)out<-paste0(out,'/',sprintf('%.0f',d));out\n}\nfp_cache<-new.env(hash=TRUE,parent=emptyenv());hash_file<-tempfile('ml22-hash-')\nfingerprint<-function(tag,values){a<-vapply(values,canonical,'');payload<-paste0('[',paste0('\"',a,'\"',collapse=','),']');key<-paste0(tag,':',payload);if(exists(key,fp_cache,inherits=FALSE))return(get(key,fp_cache,inherits=FALSE));con<-file(hash_file,'wb');writeBin(charToRaw(payload),con);close(con);value<-paste0(tag,':',unname(sha256(hash_file)));assign(key,value,fp_cache);value}\nassign_roles<-function(group){order<-sort(unique(group),method='radix');state<-seed;if(length(order)>1)for(j in seq.int(length(order),2)){state<-(1664525*state+1013904223)%%2^32;k<-state%%j+1;order[c(j,k)]<-order[c(k,j)]};rank<-match(group,order)-1;list(rank=rank,planned=c('test','validation','train','train')[rank%%4+1],state=state)}\n\nfit_model<-function(r,x,method,lambda){\n tr<-which(r$role=='train'&r$eligible);if(!length(tr))stop('No complete positive training rows');y<-r$y[tr];xx<-x[tr,,drop=FALSE];mu<-colMeans(xx);scale<-apply(xx,2,function(v)diff(range(v)));scale[scale==0]<-1;z<-cbind(1,sweep(sweep(x,2,mu,'-'),2,scale,'/'));meanY<-mean(y);model<-list();n<-length(tr)\n if(method=='constant'){model<-list(mean=meanY,parameterCount=1,rank=1,unique=TRUE);raw<-rep(meanY,nrow(r))}\n else if(method=='ridge'){zt<-z[tr,,drop=FALSE];pen<-diag(c(0,rep(lambda,ncol(x))));theta<-drop(solve(crossprod(zt)/n+pen,crossprod(zt,y)/n));raw<-drop(z%*%theta);objective<-mean((y-raw[tr])^2)/2+lambda*sum(theta[-1]^2)/2;model<-list(lambdaValue=lambda,theta=theta,rank=length(theta),unique=TRUE,minimumObjective=objective,parameterCount=length(theta))}\n else{base<-sum((y-meanY)^2);best<-NULL;total<-sum(y);total2<-sum(y*y)\n  for(j in seq_len(ncol(x))){ord<-order(xx[,j],seq_len(n));sx<-xx[ord,j];sy<-y[ord];left<-cumsum(sy)\n   if(n<2*leaf_min)next\n   for(i in seq.int(leaf_min,n-leaf_min)){if(sx[i]==sx[i+1])next;loss<-total2-left[i]^2/i-(total-left[i])^2/(n-i)\n    # Explicit approximate-tie tolerance; exact source JavaScript/Python\n    # contracts are authoritative for general arbitrarily close ties.\n    if(is.null(best)||loss<best$weightedSSE-1e-12*max(1,abs(loss),abs(best$weightedSSE)))best<-list(feature=j-1,threshold=(sx[i]+sx[i+1])/2,leftMean=left[i]/i,rightMean=(total-left[i])/(n-i),leftRows=i,rightRows=n-i,leftWeight=i,rightWeight=n-i,weightedSSE=loss)\n   }\n  }\n  if(is.null(best)||best$weightedSSE>=base-1e-12*max(1,abs(base))){model<-list(split=FALSE,mean=meanY,weightedSSE=base,trainingMSE=base/n);raw<-rep(meanY,nrow(r))}else{model<-c(list(split=TRUE),best,list(trainingMSE=best$weightedSSE/n,improvement=(base-best$weightedSSE)/n));raw<-ifelse(x[,model$feature+1]<=model$threshold,model$leftMean,model$rightMean)}\n }\n pred<-if(r$dataset[1]=='company')pmax(0,pmin(1,raw))else raw;list(meanX=mu,scales=scale,model=model,raw=raw,pred=pred)\n}\n\n# New standalone fixed-profile adapters; native and fit helpers copied by value.\nnum<-function(x){if(is.null(x)||length(x)==0||is.na(x)||x%in%c('','.'))return(NA_real_);if(is.character(x)&&grepl('/',x,fixed=TRUE)){v<-strsplit(x,'/',fixed=TRUE)[[1]];return(as.numeric(v[1])/as.numeric(v[2]))};as.numeric(x)}\nfixedRows<-function(aa){\n rr<-lapply(seq_along(aa),function(i){a<-aa[[i]];w<-num(if(is.null(a$weight))'1'else a$weight);if(is.na(w)||w<0)stop(if(!is.na(w)&&w<0)'negative-weight'else'missing-weight');list(id=if(is.null(a$id))as.character(i-1)else a$id,group=if(is.null(a$group))if(is.null(a$id))as.character(i-1)else a$id else a$group,cohort=if(is.null(a$cohort))'all'else a$cohort,role=if(is.null(a$role))'train'else a$role,w=w,y=num(a$y),x=vapply(a$x,num,0.0))})\n p<-if(length(rr))length(rr[[1]]$x)else 0;xx<-matrix(NA_real_,length(rr),p)\n if(p)for(i in seq_along(rr))xx[i,]<-rr[[i]]$x\n r<-data.frame(id=vapply(rr,`[[`,'','id'),group=vapply(rr,`[[`,'','group'),cohort=vapply(rr,`[[`,'','cohort'),role=vapply(rr,`[[`,'','role'),w=vapply(rr,`[[`,0.0,'w'),y=vapply(rr,`[[`,0.0,'y'));r$eligible<-!is.na(r$y)&rowSums(is.na(xx))==0&r$w>0;list(r=r,x=xx)\n}\nweightedRisk<-function(r,p,binary=FALSE,threshold=.5){\n ii<-which(r$w>0&!is.na(r$y)&!is.na(p)&!r$role%in%c('excluded','unused'));y<-r$y[ii];p<-p[ii];w<-r$w[ii];W<-sum(w);d<-list(rows=length(ii),mass=W,MSE=NA_real_,MAE=NA_real_,R2=NA_real_)\n if(W==0){if(binary)d<-c(d,setNames(rep(list(NA_real_),10),c('Brier','accuracy','positiveRecall','negativeRecall','precision','F1','balancedAccuracy','AUROC','positiveMass','negativeMass')));return(d)}\n mu<-sum(w*y)/W;sse<-sum(w*(p-y)^2);sst<-sum(w*(y-mu)^2);d<-c(d,list(meanY=mu,SSE=sse,SST=sst));d$MSE<-sse/W;d$MAE<-sum(w*abs(p-y))/W;d$R2<-if(sst>0)1-sse/sst else NA_real_\n if(binary){pos<-y==1;yes<-p>=threshold;TP<-sum(w[pos&yes]);FP<-sum(w[!pos&yes]);TN<-sum(w[!pos&!yes]);FN<-sum(w[pos&!yes]);rate<-function(a,b)if(b>0)a/b else NA_real_;tpr<-rate(TP,TP+FN);tnr<-rate(TN,TN+FP);auc<-NA_real_;P<-sum(w[pos]);N<-sum(w[!pos]);if(P>0&&N>0){wins<-sum(vapply(which(pos),function(i)sum(w[i]*w[!pos]*ifelse(p[i]>p[!pos],1,ifelse(p[i]==p[!pos],.5,0))),0.0));auc<-wins/(P*N)};d<-c(d,list(Brier=d$MSE,threshold=threshold,confusionMass=list(TP=TP,FP=FP,TN=TN,FN=FN),confusionRows=list(TP=sum(pos&yes),FP=sum(!pos&yes),TN=sum(!pos&!yes),FN=sum(pos&!yes)),positiveMass=P,negativeMass=N,accuracy=(TP+TN)/W,positiveRecall=tpr,negativeRecall=tnr,precision=rate(TP,TP+FP),F1=rate(2*TP,2*TP+FP+FN),balancedAccuracy=if(is.finite(tpr)&&is.finite(tnr))(tpr+tnr)/2 else NA_real_,AUROC=auc))};d\n}\nweightedPair<-function(r,A,B){\n ii<-which(r$w>0&!is.na(r$y)&!is.na(A)&!is.na(B)&!r$role%in%c('excluded','unused'));rr<-r[ii,,drop=FALSE];la<-(A[ii]-rr$y)^2;lb<-(B[ii]-rr$y)^2;d<-la-lb;W<-sum(rr$w);S<-sum(rr$w*d);mu<-if(W>0)S/W else NA_real_;ids<-unique(rr$group);groups<-lapply(ids,function(g){jj<-which(rr$group==g);wg<-sum(rr$w[jj]);sg<-sum(rr$w[jj]*d[jj]);list(group=g,rows=length(jj),mass=wg,sum=sg,leaveOut=if(W>wg)(S-sg)/(W-wg)else NA_real_)});leaves<-vapply(groups,`[[`,0.0,'leaveOut');G<-length(groups);proxy<-if(G>1&&all(is.finite(leaves)))(G-1)/G*sum((leaves-mean(leaves))^2) else NA_real_\n list(rows=length(ii),mass=W,groupCount=G,meanDifference=mu,minimumLeaveOut=if(any(is.finite(leaves)))min(leaves,na.rm=TRUE)else NA_real_,maximumLeaveOut=if(any(is.finite(leaves)))max(leaves,na.rm=TRUE)else NA_real_,varianceProxy=proxy,groups=groups,records=lapply(seq_along(ii),function(j)list(id=rr$id[j],group=rr$group[j],weight=rr$w[j],lossA=la[j],lossB=lb[j],difference=d[j])))\n}\nrunSelection<-function(r,candidates,criterion,required,binary=FALSE){\n out<-lapply(candidates,function(c){v<-r;t<-r;v$role[v$role!='validation']<-'excluded';t$role[t$role!='test']<-'excluded';val<-weightedRisk(v,c$pred,binary);test<-weightedRisk(t,c$pred,binary);co<-setNames(lapply(required,function(g){z<-v;z$role[z$cohort!=g]<-'excluded';weightedRisk(z,c$pred,binary)}),required);vv<-vapply(co,`[[`,0.0,'MSE');score<-if(criterion=='mean')val$MSE else if(length(vv)&&all(is.finite(vv)))max(vv)else NA_real_;list(id=c$id,criterion=score,validation=val,test=test,cohorts=co)})\n scores<-vapply(out,`[[`,0.0,'criterion');eligible<-which(is.finite(scores));k<-if(length(eligible))eligible[which.min(scores[eligible])]else NA_integer_;list(criterion=criterion,selected=if(!is.na(k))out[[k]]$id else NULL,selectedIndex=if(!is.na(k))k-1 else NA_real_,candidates=out)\n}\nfixedOperation<-function(api,a){\n if(api=='realdata'){\n  kind<-a$kind;r<-rows[[kind]];x<-X[[kind]];asgn<-assign_roles(r$group);r$dataset<-kind;r$splitRank<-asgn$rank;r$plannedRole<-asgn$planned;r$eligible<-!is.na(r$y)&rowSums(is.na(x))==0;r$role<-ifelse(r$eligible,r$plannedRole,'excluded');r$w<-1;binary<-kind=='company';leaf_min<<-5\n  defs<-data.frame(id=c('constant','ridge:1/100','ridge:1/10','ridge:1','one-split-stump'),method=c('constant','ridge','ridge','ridge','stump'),lambda=c(0,.01,.1,1,0));fits<-lapply(seq_len(5),function(i)fit_model(r,x,defs$method[i],defs$lambda[i]));candidates<-lapply(seq_len(5),function(i)list(id=defs$id[i],pred=fits[[i]]$pred));selection<-runSelection(r,candidates,a$criterion,unique(r$cohort),binary);k<-selection$selectedIndex+1;best<-fits[[k]];base<-fits[[1]];test<-r;test$role[test$role!='test']<-'excluded';paired<-weightedPair(test,best$pred,base$pred)\n  records<-lapply(seq_len(nrow(r)),function(i)list(id=r$id[i],sourceRow=r$sourceRow[i],originalID=r$originalID[i],group=r$group[i],cohort=r$cohort[i],plannedRole=r$plannedRole[i],role=r$role[i],eligible=r$eligible[i],y=r$y[i],baselinePrediction=base$pred[i],selectedPrediction=best$pred[i],selectedRawPrediction=best$raw[i],queryInvariant=TRUE))\n  return(list(kind=kind,nativeRows=nrow(r),eligibleRows=sum(r$eligible),selection=selection,models=lapply(seq_len(5),function(i)list(id=defs$id[i],train=as.list(r$id[r$role=='train']),mass=sum(r$role=='train'),meanX=fits[[i]]$meanX,scales=fits[[i]]$scales,model=fits[[i]]$model)),paired=paired,records=records))\n }\n f<-fixedRows(a$rows);r<-f$r;x<-f$x;binary<-identical(a$task,'binary')\n if(api=='split'){seed<<-a$seed;asgn<-assign_roles(r$group);return(list(state=asgn$state,groupCount=length(unique(r$group)),records=lapply(seq_len(nrow(r)),function(i)list(id=r$id[i],group=r$group[i],rank=asgn$rank[i],role=asgn$planned[i]))))}\n if(api=='fit'){\n  r$dataset<-if(binary)'company'else'fixed';leaf_min<<-if(is.null(a$minLeafRows))1 else a$minLeafRows;fit<-fit_model(r,x,a$method,if(is.null(a$lambda))0 else num(a$lambda));bad<-rowSums(is.na(x))>0;fit$raw[bad]<-NA_real_;fit$pred[bad]<-NA_real_;fit$defined<-TRUE;fit$train<-as.list(r$id[r$role=='train'&r$eligible]);fit$mass<-sum(r$w[r$role=='train'&r$eligible]);fit$invariant<-ifelse(bad,NA,TRUE);return(fit)\n }\n if(api=='evaluate'){p<-vapply(a$rows,function(v)num(v$prediction),0.0);threshold<-if(is.null(a$threshold)).5 else num(a$threshold);m<-weightedRisk(r,p,binary,threshold);records<-lapply(seq_len(nrow(r)),function(i){valid<-r$w[i]>0&&!is.na(r$y[i])&&!is.na(p[i])&&!r$role[i]%in%c('excluded','unused');list(id=r$id[i],weight=r$w[i],y=r$y[i],prediction=p[i],eligible=valid,loss=if(valid)(p[i]-r$y[i])^2 else NA_real_,correct=list(defined=valid&&binary,value=if(valid&&binary)(p[i]>=threshold)==r$y[i] else NULL))});return(list(metrics=m,records=records))}\n if(api=='select'){cs<-lapply(a$candidates,function(c)list(id=c$id,pred=vapply(c$predictions,num,0.0)));return(runSelection(r,cs,a$criterion,unlist(a$requiredCohorts),binary))}\n if(api=='paired')return(weightedPair(r,vapply(a$rows,function(v)num(v$predictionA),0.0),vapply(a$rows,function(v)num(v$predictionB),0.0)))\n stop('unknown-api')\n}\nreportValues<-function(api,z){\n ss<-list();pp<-list();add<-function(k,v,u='dimensionless')ss[[length(ss)+1]]<<-list(metric=k,value=if(is.null(v)||length(v)==0||is.na(v))NULL else unname(v),unit=u);series<-function(name,values){for(i in seq_along(values))pp[[length(pp)+1]]<<-list(series=name,index=i-1,x=i-1,y=if(is.null(values[[i]])||is.na(values[[i]]))NULL else unname(values[[i]]))}\n if(api=='split'){add('groups',z$groupCount,'groups');add('rows',length(z$records),'rows');add('finalState',z$state,'unsigned 32-bit state');series('planned role code',lapply(z$records,function(r)switch(r$role,test=0,validation=1,train=2)))}\n if(api=='fit'){add('defined',z$defined);add('trainingRows',length(z$train),'rows');add('trainingMass',z$mass,'analysis weight mass');add('modelRank',z$model$rank,'parameters');add('threshold',z$model$threshold,'constructed feature units');add('minimumObjective',z$model$minimumObjective,'constructed squared outcome units');series('prediction',as.list(z$pred));if(!is.null(z$model$theta))for(i in seq_along(z$model$theta))add(paste0('theta',i-1),z$model$theta[i],'constructed outcome units per standardized coordinate')}\n if(api=='evaluate'){for(k in c('rows','mass','MSE','MAE','R2','Brier','accuracy','positiveRecall','negativeRecall','precision','F1','balancedAccuracy','AUROC'))if(k%in%names(z$metrics))add(k,z$metrics[[k]],if(k=='rows')'rows'else if(k=='mass')'analysis weight mass'else if(k%in%c('MSE','Brier'))FIXED$unit else if(k=='MAE')if(identical(FIXED$input$task,'binary'))'probability-score units'else'constructed outcome units'else'dimensionless');series('squared loss',lapply(z$records,`[[`,'loss'))}\n if(api=='select'){add('selectedIndex',z$selectedIndex,'zero-based candidate index');for(i in seq_along(z$candidates)){c<-z$candidates[[i]];add(paste0('criterion',i-1),c$criterion,FIXED$unit);add(paste0('testMSE',i-1),c$test$MSE,FIXED$unit)};series('validation criterion',lapply(z$candidates,`[[`,'criterion'));series('test MSE',lapply(z$candidates,function(c)c$test$MSE))}\n if(api=='paired'){for(k in c('rows','mass','groupCount','meanDifference','minimumLeaveOut','maximumLeaveOut','varianceProxy'))add(k,z[[k]],if(k=='rows')'rows'else if(k=='groupCount')'groups'else if(k=='mass')'analysis weight mass'else if(k=='varianceProxy')paste(FIXED$unit,'squared')else FIXED$unit);series('loss A minus loss B',lapply(z$records,`[[`,'difference'))}\n if(api=='realdata'){add('nativeRows',z$nativeRows,'native records');add('eligibleRows',z$eligibleRows,'complete records');add('selectedIndex',z$selection$selectedIndex,'zero-based candidate index');for(i in seq_along(z$selection$candidates)){c<-z$selection$candidates[[i]];add(paste0('validationMSE',i-1),c$validation$MSE,FIXED$unit);add(paste0('testMSE',i-1),c$test$MSE,FIXED$unit)};for(k in c('meanDifference','minimumLeaveOut','maximumLeaveOut','varianceProxy'))add(k,z$paired[[k]],if(k=='varianceProxy')paste(FIXED$unit,'squared')else FIXED$unit);best<-z$selection$candidates[[z$selection$selectedIndex+1]]$test;for(k in c('accuracy','positiveRecall','negativeRecall','precision','balancedAccuracy','AUROC'))if(k%in%names(best))add(k,best[[k]]);series('validation MSE',lapply(z$selection$candidates,function(c)c$validation$MSE));series('test MSE',lapply(z$selection$candidates,function(c)c$test$MSE))}\n list(summary=ss,points=pp)\n}\n\nescapeXML<-function(s){s<-gsub('&','&amp;',s,fixed=TRUE);s<-gsub('<','&lt;',s,fixed=TRUE);s<-gsub('>','&gt;',s,fixed=TRUE);gsub('\"','&quot;',s,fixed=TRUE)}\nsvgPlot<-function(pp,title){\n xx<-vapply(pp,function(p)as.numeric(p$x),numeric(1));yy<-vapply(pp,function(p)as.numeric(p$y),numeric(1));xmin<-if(length(xx))min(xx)else 0;xmax<-if(length(xx))max(xx)else 1;ymin<-min(c(0,yy));ymax<-max(c(0,yy));if(xmin==xmax){xmin<-xmin-.5;xmax<-xmax+.5};if(ymin==ymax){ymin<-ymin-.5;ymax<-ymax+.5};pad<-(ymax-ymin)*.08;ymin<-ymin-pad;ymax<-ymax+pad;X<-function(x)82+(as.numeric(x)-xmin)/(xmax-xmin)*608;Y<-function(y)354-(as.numeric(y)-ymin)/(ymax-ymin)*290\n out<-paste0('<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"720\" height=\"480\" viewBox=\"0 0 720 480\" role=\"img\" aria-label=\"',escapeXML(title),'\"><rect width=\"720\" height=\"480\" fill=\"white\"/><g font-family=\"Arial,sans-serif\" font-size=\"13\" fill=\"#18232f\"><text x=\"360\" y=\"25\" text-anchor=\"middle\">',escapeXML(title),'</text>')\n for(j in 0:4){y<-ymin+(ymax-ymin)*j/4;x<-xmin+(xmax-xmin)*j/4;out<-paste0(out,'<line x1=\"82\" y1=\"',Y(y),'\" x2=\"690\" y2=\"',Y(y),'\" stroke=\"#e2e8f0\"/><text x=\"73\" y=\"',Y(y)+4,'\" text-anchor=\"end\">',sprintf('%.3g',y),'</text><text x=\"',X(x),'\" y=\"380\" text-anchor=\"middle\">',sprintf('%.3g',x),'</text>')}\n ss<-unique(vapply(pp,`[[`,character(1),'series'));cols<-c('#0f766e','#c76622','#4f46e5','#b23857')\n for(j in seq_along(ss)){rr<-Filter(function(p)p$series==ss[j],pp);xy<-vapply(rr,function(p)sprintf('%.6f,%.6f',X(p$x),Y(p$y)),character(1));col<-cols[(j-1)%%4+1];for(p in rr)out<-paste0(out,'<circle cx=\"',sprintf('%.6f',X(p$x)),'\" cy=\"',sprintf('%.6f',Y(p$y)),'\" r=\"2.6\" fill=\"',col,'\"><title>',escapeXML(ss[j]),': ',escapeXML(p$y),'</title></circle>');out<-paste0(out,'<text x=\"',82+((j-1)%%2)*310,'\" y=\"',432+floor((j-1)/2)*23,'\" fill=\"',col,'\">',escapeXML(ss[j]),'</text>')}\n paste0(out,'<text x=\"360\" y=\"405\" text-anchor=\"middle\">Declared record / candidate index; fixed example</text></g></svg>')\n}\ntoJSON<-function(x){\n if(is.null(x))return('null');if(is.list(x)){v<-vapply(x,toJSON,character(1));if(!is.null(names(x)))paste0('{',paste(paste0(vapply(names(x),toJSON,character(1)),':',v),collapse=','),'}')else paste0('[',paste(v,collapse=','),']')}\n else if(length(x)!=1){if(!is.numeric(x)&&!is.null(names(x)))toJSON(as.list(x))else paste0('[',paste(vapply(as.list(x),toJSON,character(1)),collapse=','),']')}\n else if(is.na(x))'null'else if(is.logical(x))if(x)'true'else'false'else if(is.numeric(x))if(is.finite(x))sprintf('%.17g',x)else'null'else paste0('\"',gsub('\\n','\\\\n',gsub('\"','\\\\\"',gsub('\\\\','\\\\\\\\',x,fixed=TRUE),fixed=TRUE),fixed=TRUE),'\"')\n}\n\nFIXED<-list(`api`=\"evaluate\",`variant`=\"no-predicted-positive-missing-label\",`title`=\"No positive predictions and a missing label\",`input`=list(`task`=\"binary\",`rows`=list(list(`id`=\"n\",`y`=\"0\",`prediction`=\"0\"),list(`id`=\"p\",`y`=\"1\",`prediction`=\"1/4\"),list(`id`=\"unknown\",`y`=NULL,`prediction`=\"0\"))),`unit`=\"Squared probability-score units; one-component Brier loss\",`titleI18n`=list(`ko`=\"양성 예측 없음과 결측 정답\",`en`=\"No positive predictions and a missing label\"))\n\nargs<-commandArgs(trailingOnly=TRUE);out<-if(length(args))args[1]else stop('NEW output directory required');if(dir.exists(out))stop('Preserve previous output directory');dir.create(out,recursive=TRUE)\nz<-fixedOperation(FIXED$api,FIXED$input);rr<-reportValues(FIXED$api,z)\nwriteLines(toJSON(list(arithmetic='BaseR binary64 author counterpart; native group hashing exact within declared integer range, stump approximate tie tolerance1e-12; not an independent exact oracle',result=z)),file.path(out,'full.json'),useBytes=TRUE)\nsums<-do.call(rbind,lapply(rr$summary,function(row)data.frame(metric=row$metric,value=if(is.null(row$value))''else if(is.logical(row$value))as.character(as.integer(row$value))else format(row$value,digits=17,scientific=NA,trim=TRUE),unit=row$unit,defined=as.integer(!is.null(row$value)),stringsAsFactors=FALSE)))\npoints<-do.call(rbind,lapply(rr$points,function(p)data.frame(series=p$series,index=p$index,x=p$x,y=if(is.null(p$y))NA_real_ else p$y,defined=as.integer(!is.null(p$y)),stringsAsFactors=FALSE)))\nwrite.csv(sums,file.path(out,'summary.csv'),row.names=FALSE,na='');write.csv(points,file.path(out,'plot-points.csv'),row.names=FALSE,na='');writeLines(svgPlot(Filter(function(p)!is.null(p$y),rr$points),FIXED$title),file.path(out,'plot.svg'),useBytes=TRUE);cat(FIXED$api,'/',FIXED$variant,'\\n',sep='')\n",
        "returnCode": 0,
        "stdout": "evaluate/no-predicted-positive-missing-label\r\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 ",
        "diagnosticScope": "Public projection omits private absolute-path/traceback frames; actual exit and warnings/reason retained. Raw complete streams and commands in private execution proof.",
        "resultFolder": "ml22-code/runs/r-evaluate-no-predicted-positive-missing-label",
        "kind": null,
        "inputFiles": [
          {
            "file": "ml22-code/evaluate-no-predicted-positive-missing-label-input.json",
            "sha256": "5c1815929f0ff6096976f78ffffd8736d3269ff032a3c9aff389852708eed58f",
            "scope": "Complete fixed literal input; program embeds the same values"
          }
        ],
        "files": [
          {
            "file": "ml22-code/runs/r-evaluate-no-predicted-positive-missing-label/full.json",
            "sha256": "93449bb3621668a8d1266d1588891b268ec7ef349810237b52cc41d98ea20f4a",
            "bytes": 922
          },
          {
            "file": "ml22-code/runs/r-evaluate-no-predicted-positive-missing-label/plot-points.csv",
            "sha256": "34af7dc7cfdbab9e791a2b65c91b0edc75afdfc1c10c0bbbadf55b12b206c2a5",
            "bytes": 112
          },
          {
            "file": "ml22-code/runs/r-evaluate-no-predicted-positive-missing-label/plot.svg",
            "sha256": "43ef5a083964a93fb774f40429126ffd939286987b9bb62f5af404e2e8c1095e",
            "bytes": 1550
          },
          {
            "file": "ml22-code/runs/r-evaluate-no-predicted-positive-missing-label/summary.csv",
            "sha256": "4bb578b66ee89ad56f508921059f061641f36eb8f21af4e43dd1e5afa4d56857",
            "bytes": 582
          }
        ],
        "summaryRows": [
          {
            "metric": "rows",
            "value": "2.0",
            "unit": "rows",
            "defined": "true",
            "rawValue": "2",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "mass",
            "value": "2.0",
            "unit": "analysis weight mass",
            "defined": "true",
            "rawValue": "2",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "MSE",
            "value": "0.28125",
            "unit": "Squared probability-score units; one-component Brier loss",
            "defined": "true",
            "rawValue": "0.28125",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "MAE",
            "value": "0.375",
            "unit": "probability-score units",
            "defined": "true",
            "rawValue": "0.375",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "R2",
            "value": "-0.125",
            "unit": "dimensionless",
            "defined": "true",
            "rawValue": "-0.125",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": false,
            "mathematicallyNegative": true,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "Brier",
            "value": "0.28125",
            "unit": "Squared probability-score units; one-component Brier loss",
            "defined": "true",
            "rawValue": "0.28125",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "accuracy",
            "value": "0.5",
            "unit": "dimensionless",
            "defined": "true",
            "rawValue": "0.5",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "positiveRecall",
            "value": "0.0",
            "unit": "dimensionless",
            "defined": "true",
            "rawValue": "0",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": false,
            "mathematicallyNegative": false,
            "exactZero": true,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "negativeRecall",
            "value": "1.0",
            "unit": "dimensionless",
            "defined": "true",
            "rawValue": "1",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "precision",
            "value": "",
            "unit": "dimensionless",
            "defined": "false",
            "rawValue": "",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null
          },
          {
            "metric": "F1",
            "value": "0.0",
            "unit": "dimensionless",
            "defined": "true",
            "rawValue": "0",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": false,
            "mathematicallyNegative": false,
            "exactZero": true,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "balancedAccuracy",
            "value": "0.5",
            "unit": "dimensionless",
            "defined": "true",
            "rawValue": "0.5",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "AUROC",
            "value": "1.0",
            "unit": "dimensionless",
            "defined": "true",
            "rawValue": "1",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          }
        ],
        "plotRows": [
          {
            "series": "squared loss",
            "index": "0",
            "x": "0",
            "y": "0",
            "defined": true,
            "xExact": null,
            "yExact": null
          },
          {
            "series": "squared loss",
            "index": "1",
            "x": "1",
            "y": "0.5625",
            "defined": true,
            "xExact": null,
            "yExact": null
          },
          {
            "series": "squared loss",
            "index": "2",
            "x": "2",
            "y": "",
            "defined": false,
            "xExact": null,
            "yExact": null
          }
        ],
        "plotFile": "ml22-code/runs/r-evaluate-no-predicted-positive-missing-label/plot.svg",
        "fullResultFile": "ml22-code/runs/r-evaluate-no-predicted-positive-missing-label/full.json",
        "arithmeticScope": "Python exact rational versus base-R approximate floating algebra; copied author kernels, not independent oracle.",
        "plotScope": "Original scatter vectors plot every defined declared comparison point, with missing points omitted. Source profiles show candidate risks; all source records remain in the full result and source CSV files.",
        "reproductionScope": "Standalone literal program plus four native CSV files for factual source profiles. No answer/engine/checker imports."
      },
      "reject-negative-weight": {
        "api": "evaluate",
        "variant": "reject-negative-weight",
        "language": "r",
        "title": "Genuine rejection of a negative weight",
        "titleI18n": {
          "ko": "음의 비중의 실제 거절",
          "en": "Genuine rejection of a negative weight"
        },
        "input": {
          "rows": [
            {
              "id": "bad",
              "y": "0",
              "prediction": "0",
              "weight": "-1"
            }
          ]
        },
        "expectedFailure": true,
        "codeFile": "ml22-code/evaluate-reject-negative-weight.R",
        "codeSHA256": "ea5dec40c7a51d06bcaba18bba1f1d7cd48812c4b0d913b04d58f7459da9fdaa",
        "code": "# ML22 standalone; source/public functions copied by value, no source() dependency.\noptions(stringsAsFactors=FALSE,digits=17,warn=1)\nargs0<-commandArgs(trailingOnly=FALSE);script0<-sub('^--file=','',args0[grepl('^--file=',args0)][1]);source_dir<-file.path(dirname(normalizePath(script0)), 'data');seed<-20261104;leaf_min<-5\nnative_hash <- c(\"actual1599-red-wine-original12-fields.csv\"=\"77e9ac73115930d6c43983333a5a57940deefc493affeb17aca478c09c5f6e00\",\"actual4898-white-wine-original12-fields.csv\"=\"50d810bbb42b9cc3e87fa4c27a4c0f168e72da09dd812863425ca3873fec28ef\",\"actual3613-NLS-original52-fields.csv\"=\"6e1e1895558795435b65f8634252a7589865273a0e69adbd715fcfa04a3c11a1\",\"actual3150-churn-original14-fields.csv\"=\"1c0753e434226e769d1015c922121a7d8967df66014e057c4f7543e490f11764\")\nsha256<-getExportedValue('tools','sha256sum')\nread_native<-function(name){f<-file.path(source_dir,name);if(unname(sha256(f))!=native_hash[[name]])stop(paste('Native hash differs',name));read.csv(f,check.names=FALSE,colClasses='character',na.strings=NULL)}\ngcd_small<-function(a,b){while(b!=0){r<-a%%b;a<-b;b<-r};a}\ncanonical<-function(token){\n if(is.na(token)||token%in%c('','.'))return('null')\n if(!grepl('^[+-]?[0-9]+([.][0-9]*)?$',token))stop('Unsupported native fingerprint token')\n neg<-substr(token,1,1)=='-';s<-sub('^[+-]','',token);parts<-strsplit(s,'.',fixed=TRUE)[[1]];dec<-if(length(parts)==2)nchar(parts[2])else 0;n<-as.numeric(gsub('.','',s,fixed=TRUE));d<-10^dec\n # Every native fingerprint numerator/denominator must remain exactly integral\n # in binary64; reject rather than silently rounding a changed future source.\n if(!is.finite(n)||n>2^53||d>2^53)stop('Native canonical integer range exceeded')\n g<-gcd_small(n,d);n<-n/g;d<-d/g;if(neg)n<--n\n out<-sprintf('%.0f',n);if(d!=1)out<-paste0(out,'/',sprintf('%.0f',d));out\n}\nfp_cache<-new.env(hash=TRUE,parent=emptyenv());hash_file<-tempfile('ml22-hash-')\nfingerprint<-function(tag,values){a<-vapply(values,canonical,'');payload<-paste0('[',paste0('\"',a,'\"',collapse=','),']');key<-paste0(tag,':',payload);if(exists(key,fp_cache,inherits=FALSE))return(get(key,fp_cache,inherits=FALSE));con<-file(hash_file,'wb');writeBin(charToRaw(payload),con);close(con);value<-paste0(tag,':',unname(sha256(hash_file)));assign(key,value,fp_cache);value}\nassign_roles<-function(group){order<-sort(unique(group),method='radix');state<-seed;if(length(order)>1)for(j in seq.int(length(order),2)){state<-(1664525*state+1013904223)%%2^32;k<-state%%j+1;order[c(j,k)]<-order[c(k,j)]};rank<-match(group,order)-1;list(rank=rank,planned=c('test','validation','train','train')[rank%%4+1],state=state)}\n\nfit_model<-function(r,x,method,lambda){\n tr<-which(r$role=='train'&r$eligible);if(!length(tr))stop('No complete positive training rows');y<-r$y[tr];xx<-x[tr,,drop=FALSE];mu<-colMeans(xx);scale<-apply(xx,2,function(v)diff(range(v)));scale[scale==0]<-1;z<-cbind(1,sweep(sweep(x,2,mu,'-'),2,scale,'/'));meanY<-mean(y);model<-list();n<-length(tr)\n if(method=='constant'){model<-list(mean=meanY,parameterCount=1,rank=1,unique=TRUE);raw<-rep(meanY,nrow(r))}\n else if(method=='ridge'){zt<-z[tr,,drop=FALSE];pen<-diag(c(0,rep(lambda,ncol(x))));theta<-drop(solve(crossprod(zt)/n+pen,crossprod(zt,y)/n));raw<-drop(z%*%theta);objective<-mean((y-raw[tr])^2)/2+lambda*sum(theta[-1]^2)/2;model<-list(lambdaValue=lambda,theta=theta,rank=length(theta),unique=TRUE,minimumObjective=objective,parameterCount=length(theta))}\n else{base<-sum((y-meanY)^2);best<-NULL;total<-sum(y);total2<-sum(y*y)\n  for(j in seq_len(ncol(x))){ord<-order(xx[,j],seq_len(n));sx<-xx[ord,j];sy<-y[ord];left<-cumsum(sy)\n   if(n<2*leaf_min)next\n   for(i in seq.int(leaf_min,n-leaf_min)){if(sx[i]==sx[i+1])next;loss<-total2-left[i]^2/i-(total-left[i])^2/(n-i)\n    # Explicit approximate-tie tolerance; exact source JavaScript/Python\n    # contracts are authoritative for general arbitrarily close ties.\n    if(is.null(best)||loss<best$weightedSSE-1e-12*max(1,abs(loss),abs(best$weightedSSE)))best<-list(feature=j-1,threshold=(sx[i]+sx[i+1])/2,leftMean=left[i]/i,rightMean=(total-left[i])/(n-i),leftRows=i,rightRows=n-i,leftWeight=i,rightWeight=n-i,weightedSSE=loss)\n   }\n  }\n  if(is.null(best)||best$weightedSSE>=base-1e-12*max(1,abs(base))){model<-list(split=FALSE,mean=meanY,weightedSSE=base,trainingMSE=base/n);raw<-rep(meanY,nrow(r))}else{model<-c(list(split=TRUE),best,list(trainingMSE=best$weightedSSE/n,improvement=(base-best$weightedSSE)/n));raw<-ifelse(x[,model$feature+1]<=model$threshold,model$leftMean,model$rightMean)}\n }\n pred<-if(r$dataset[1]=='company')pmax(0,pmin(1,raw))else raw;list(meanX=mu,scales=scale,model=model,raw=raw,pred=pred)\n}\n\n# New standalone fixed-profile adapters; native and fit helpers copied by value.\nnum<-function(x){if(is.null(x)||length(x)==0||is.na(x)||x%in%c('','.'))return(NA_real_);if(is.character(x)&&grepl('/',x,fixed=TRUE)){v<-strsplit(x,'/',fixed=TRUE)[[1]];return(as.numeric(v[1])/as.numeric(v[2]))};as.numeric(x)}\nfixedRows<-function(aa){\n rr<-lapply(seq_along(aa),function(i){a<-aa[[i]];w<-num(if(is.null(a$weight))'1'else a$weight);if(is.na(w)||w<0)stop(if(!is.na(w)&&w<0)'negative-weight'else'missing-weight');list(id=if(is.null(a$id))as.character(i-1)else a$id,group=if(is.null(a$group))if(is.null(a$id))as.character(i-1)else a$id else a$group,cohort=if(is.null(a$cohort))'all'else a$cohort,role=if(is.null(a$role))'train'else a$role,w=w,y=num(a$y),x=vapply(a$x,num,0.0))})\n p<-if(length(rr))length(rr[[1]]$x)else 0;xx<-matrix(NA_real_,length(rr),p)\n if(p)for(i in seq_along(rr))xx[i,]<-rr[[i]]$x\n r<-data.frame(id=vapply(rr,`[[`,'','id'),group=vapply(rr,`[[`,'','group'),cohort=vapply(rr,`[[`,'','cohort'),role=vapply(rr,`[[`,'','role'),w=vapply(rr,`[[`,0.0,'w'),y=vapply(rr,`[[`,0.0,'y'));r$eligible<-!is.na(r$y)&rowSums(is.na(xx))==0&r$w>0;list(r=r,x=xx)\n}\nweightedRisk<-function(r,p,binary=FALSE,threshold=.5){\n ii<-which(r$w>0&!is.na(r$y)&!is.na(p)&!r$role%in%c('excluded','unused'));y<-r$y[ii];p<-p[ii];w<-r$w[ii];W<-sum(w);d<-list(rows=length(ii),mass=W,MSE=NA_real_,MAE=NA_real_,R2=NA_real_)\n if(W==0){if(binary)d<-c(d,setNames(rep(list(NA_real_),10),c('Brier','accuracy','positiveRecall','negativeRecall','precision','F1','balancedAccuracy','AUROC','positiveMass','negativeMass')));return(d)}\n mu<-sum(w*y)/W;sse<-sum(w*(p-y)^2);sst<-sum(w*(y-mu)^2);d<-c(d,list(meanY=mu,SSE=sse,SST=sst));d$MSE<-sse/W;d$MAE<-sum(w*abs(p-y))/W;d$R2<-if(sst>0)1-sse/sst else NA_real_\n if(binary){pos<-y==1;yes<-p>=threshold;TP<-sum(w[pos&yes]);FP<-sum(w[!pos&yes]);TN<-sum(w[!pos&!yes]);FN<-sum(w[pos&!yes]);rate<-function(a,b)if(b>0)a/b else NA_real_;tpr<-rate(TP,TP+FN);tnr<-rate(TN,TN+FP);auc<-NA_real_;P<-sum(w[pos]);N<-sum(w[!pos]);if(P>0&&N>0){wins<-sum(vapply(which(pos),function(i)sum(w[i]*w[!pos]*ifelse(p[i]>p[!pos],1,ifelse(p[i]==p[!pos],.5,0))),0.0));auc<-wins/(P*N)};d<-c(d,list(Brier=d$MSE,threshold=threshold,confusionMass=list(TP=TP,FP=FP,TN=TN,FN=FN),confusionRows=list(TP=sum(pos&yes),FP=sum(!pos&yes),TN=sum(!pos&!yes),FN=sum(pos&!yes)),positiveMass=P,negativeMass=N,accuracy=(TP+TN)/W,positiveRecall=tpr,negativeRecall=tnr,precision=rate(TP,TP+FP),F1=rate(2*TP,2*TP+FP+FN),balancedAccuracy=if(is.finite(tpr)&&is.finite(tnr))(tpr+tnr)/2 else NA_real_,AUROC=auc))};d\n}\nweightedPair<-function(r,A,B){\n ii<-which(r$w>0&!is.na(r$y)&!is.na(A)&!is.na(B)&!r$role%in%c('excluded','unused'));rr<-r[ii,,drop=FALSE];la<-(A[ii]-rr$y)^2;lb<-(B[ii]-rr$y)^2;d<-la-lb;W<-sum(rr$w);S<-sum(rr$w*d);mu<-if(W>0)S/W else NA_real_;ids<-unique(rr$group);groups<-lapply(ids,function(g){jj<-which(rr$group==g);wg<-sum(rr$w[jj]);sg<-sum(rr$w[jj]*d[jj]);list(group=g,rows=length(jj),mass=wg,sum=sg,leaveOut=if(W>wg)(S-sg)/(W-wg)else NA_real_)});leaves<-vapply(groups,`[[`,0.0,'leaveOut');G<-length(groups);proxy<-if(G>1&&all(is.finite(leaves)))(G-1)/G*sum((leaves-mean(leaves))^2) else NA_real_\n list(rows=length(ii),mass=W,groupCount=G,meanDifference=mu,minimumLeaveOut=if(any(is.finite(leaves)))min(leaves,na.rm=TRUE)else NA_real_,maximumLeaveOut=if(any(is.finite(leaves)))max(leaves,na.rm=TRUE)else NA_real_,varianceProxy=proxy,groups=groups,records=lapply(seq_along(ii),function(j)list(id=rr$id[j],group=rr$group[j],weight=rr$w[j],lossA=la[j],lossB=lb[j],difference=d[j])))\n}\nrunSelection<-function(r,candidates,criterion,required,binary=FALSE){\n out<-lapply(candidates,function(c){v<-r;t<-r;v$role[v$role!='validation']<-'excluded';t$role[t$role!='test']<-'excluded';val<-weightedRisk(v,c$pred,binary);test<-weightedRisk(t,c$pred,binary);co<-setNames(lapply(required,function(g){z<-v;z$role[z$cohort!=g]<-'excluded';weightedRisk(z,c$pred,binary)}),required);vv<-vapply(co,`[[`,0.0,'MSE');score<-if(criterion=='mean')val$MSE else if(length(vv)&&all(is.finite(vv)))max(vv)else NA_real_;list(id=c$id,criterion=score,validation=val,test=test,cohorts=co)})\n scores<-vapply(out,`[[`,0.0,'criterion');eligible<-which(is.finite(scores));k<-if(length(eligible))eligible[which.min(scores[eligible])]else NA_integer_;list(criterion=criterion,selected=if(!is.na(k))out[[k]]$id else NULL,selectedIndex=if(!is.na(k))k-1 else NA_real_,candidates=out)\n}\nfixedOperation<-function(api,a){\n if(api=='realdata'){\n  kind<-a$kind;r<-rows[[kind]];x<-X[[kind]];asgn<-assign_roles(r$group);r$dataset<-kind;r$splitRank<-asgn$rank;r$plannedRole<-asgn$planned;r$eligible<-!is.na(r$y)&rowSums(is.na(x))==0;r$role<-ifelse(r$eligible,r$plannedRole,'excluded');r$w<-1;binary<-kind=='company';leaf_min<<-5\n  defs<-data.frame(id=c('constant','ridge:1/100','ridge:1/10','ridge:1','one-split-stump'),method=c('constant','ridge','ridge','ridge','stump'),lambda=c(0,.01,.1,1,0));fits<-lapply(seq_len(5),function(i)fit_model(r,x,defs$method[i],defs$lambda[i]));candidates<-lapply(seq_len(5),function(i)list(id=defs$id[i],pred=fits[[i]]$pred));selection<-runSelection(r,candidates,a$criterion,unique(r$cohort),binary);k<-selection$selectedIndex+1;best<-fits[[k]];base<-fits[[1]];test<-r;test$role[test$role!='test']<-'excluded';paired<-weightedPair(test,best$pred,base$pred)\n  records<-lapply(seq_len(nrow(r)),function(i)list(id=r$id[i],sourceRow=r$sourceRow[i],originalID=r$originalID[i],group=r$group[i],cohort=r$cohort[i],plannedRole=r$plannedRole[i],role=r$role[i],eligible=r$eligible[i],y=r$y[i],baselinePrediction=base$pred[i],selectedPrediction=best$pred[i],selectedRawPrediction=best$raw[i],queryInvariant=TRUE))\n  return(list(kind=kind,nativeRows=nrow(r),eligibleRows=sum(r$eligible),selection=selection,models=lapply(seq_len(5),function(i)list(id=defs$id[i],train=as.list(r$id[r$role=='train']),mass=sum(r$role=='train'),meanX=fits[[i]]$meanX,scales=fits[[i]]$scales,model=fits[[i]]$model)),paired=paired,records=records))\n }\n f<-fixedRows(a$rows);r<-f$r;x<-f$x;binary<-identical(a$task,'binary')\n if(api=='split'){seed<<-a$seed;asgn<-assign_roles(r$group);return(list(state=asgn$state,groupCount=length(unique(r$group)),records=lapply(seq_len(nrow(r)),function(i)list(id=r$id[i],group=r$group[i],rank=asgn$rank[i],role=asgn$planned[i]))))}\n if(api=='fit'){\n  r$dataset<-if(binary)'company'else'fixed';leaf_min<<-if(is.null(a$minLeafRows))1 else a$minLeafRows;fit<-fit_model(r,x,a$method,if(is.null(a$lambda))0 else num(a$lambda));bad<-rowSums(is.na(x))>0;fit$raw[bad]<-NA_real_;fit$pred[bad]<-NA_real_;fit$defined<-TRUE;fit$train<-as.list(r$id[r$role=='train'&r$eligible]);fit$mass<-sum(r$w[r$role=='train'&r$eligible]);fit$invariant<-ifelse(bad,NA,TRUE);return(fit)\n }\n if(api=='evaluate'){p<-vapply(a$rows,function(v)num(v$prediction),0.0);threshold<-if(is.null(a$threshold)).5 else num(a$threshold);m<-weightedRisk(r,p,binary,threshold);records<-lapply(seq_len(nrow(r)),function(i){valid<-r$w[i]>0&&!is.na(r$y[i])&&!is.na(p[i])&&!r$role[i]%in%c('excluded','unused');list(id=r$id[i],weight=r$w[i],y=r$y[i],prediction=p[i],eligible=valid,loss=if(valid)(p[i]-r$y[i])^2 else NA_real_,correct=list(defined=valid&&binary,value=if(valid&&binary)(p[i]>=threshold)==r$y[i] else NULL))});return(list(metrics=m,records=records))}\n if(api=='select'){cs<-lapply(a$candidates,function(c)list(id=c$id,pred=vapply(c$predictions,num,0.0)));return(runSelection(r,cs,a$criterion,unlist(a$requiredCohorts),binary))}\n if(api=='paired')return(weightedPair(r,vapply(a$rows,function(v)num(v$predictionA),0.0),vapply(a$rows,function(v)num(v$predictionB),0.0)))\n stop('unknown-api')\n}\nreportValues<-function(api,z){\n ss<-list();pp<-list();add<-function(k,v,u='dimensionless')ss[[length(ss)+1]]<<-list(metric=k,value=if(is.null(v)||length(v)==0||is.na(v))NULL else unname(v),unit=u);series<-function(name,values){for(i in seq_along(values))pp[[length(pp)+1]]<<-list(series=name,index=i-1,x=i-1,y=if(is.null(values[[i]])||is.na(values[[i]]))NULL else unname(values[[i]]))}\n if(api=='split'){add('groups',z$groupCount,'groups');add('rows',length(z$records),'rows');add('finalState',z$state,'unsigned 32-bit state');series('planned role code',lapply(z$records,function(r)switch(r$role,test=0,validation=1,train=2)))}\n if(api=='fit'){add('defined',z$defined);add('trainingRows',length(z$train),'rows');add('trainingMass',z$mass,'analysis weight mass');add('modelRank',z$model$rank,'parameters');add('threshold',z$model$threshold,'constructed feature units');add('minimumObjective',z$model$minimumObjective,'constructed squared outcome units');series('prediction',as.list(z$pred));if(!is.null(z$model$theta))for(i in seq_along(z$model$theta))add(paste0('theta',i-1),z$model$theta[i],'constructed outcome units per standardized coordinate')}\n if(api=='evaluate'){for(k in c('rows','mass','MSE','MAE','R2','Brier','accuracy','positiveRecall','negativeRecall','precision','F1','balancedAccuracy','AUROC'))if(k%in%names(z$metrics))add(k,z$metrics[[k]],if(k=='rows')'rows'else if(k=='mass')'analysis weight mass'else if(k%in%c('MSE','Brier'))FIXED$unit else if(k=='MAE')'constructed outcome units'else'dimensionless');series('squared loss',lapply(z$records,`[[`,'loss'))}\n if(api=='select'){add('selectedIndex',z$selectedIndex,'zero-based candidate index');for(i in seq_along(z$candidates)){c<-z$candidates[[i]];add(paste0('criterion',i-1),c$criterion,FIXED$unit);add(paste0('testMSE',i-1),c$test$MSE,FIXED$unit)};series('validation criterion',lapply(z$candidates,`[[`,'criterion'));series('test MSE',lapply(z$candidates,function(c)c$test$MSE))}\n if(api=='paired'){for(k in c('rows','mass','groupCount','meanDifference','minimumLeaveOut','maximumLeaveOut','varianceProxy'))add(k,z[[k]],if(k=='rows')'rows'else if(k=='groupCount')'groups'else if(k=='mass')'analysis weight mass'else if(k=='varianceProxy')paste(FIXED$unit,'squared')else FIXED$unit);series('loss A minus loss B',lapply(z$records,`[[`,'difference'))}\n if(api=='realdata'){add('nativeRows',z$nativeRows,'native records');add('eligibleRows',z$eligibleRows,'complete records');add('selectedIndex',z$selection$selectedIndex,'zero-based candidate index');for(i in seq_along(z$selection$candidates)){c<-z$selection$candidates[[i]];add(paste0('validationMSE',i-1),c$validation$MSE,FIXED$unit);add(paste0('testMSE',i-1),c$test$MSE,FIXED$unit)};for(k in c('meanDifference','minimumLeaveOut','maximumLeaveOut','varianceProxy'))add(k,z$paired[[k]],if(k=='varianceProxy')paste(FIXED$unit,'squared')else FIXED$unit);best<-z$selection$candidates[[z$selection$selectedIndex+1]]$test;for(k in c('accuracy','positiveRecall','negativeRecall','precision','balancedAccuracy','AUROC'))if(k%in%names(best))add(k,best[[k]]);series('validation MSE',lapply(z$selection$candidates,function(c)c$validation$MSE));series('test MSE',lapply(z$selection$candidates,function(c)c$test$MSE))}\n list(summary=ss,points=pp)\n}\n\nescapeXML<-function(s){s<-gsub('&','&amp;',s,fixed=TRUE);s<-gsub('<','&lt;',s,fixed=TRUE);s<-gsub('>','&gt;',s,fixed=TRUE);gsub('\"','&quot;',s,fixed=TRUE)}\nsvgPlot<-function(pp,title){\n xx<-vapply(pp,function(p)as.numeric(p$x),numeric(1));yy<-vapply(pp,function(p)as.numeric(p$y),numeric(1));xmin<-if(length(xx))min(xx)else 0;xmax<-if(length(xx))max(xx)else 1;ymin<-min(c(0,yy));ymax<-max(c(0,yy));if(xmin==xmax){xmin<-xmin-.5;xmax<-xmax+.5};if(ymin==ymax){ymin<-ymin-.5;ymax<-ymax+.5};pad<-(ymax-ymin)*.08;ymin<-ymin-pad;ymax<-ymax+pad;X<-function(x)82+(as.numeric(x)-xmin)/(xmax-xmin)*608;Y<-function(y)354-(as.numeric(y)-ymin)/(ymax-ymin)*290\n out<-paste0('<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"720\" height=\"480\" viewBox=\"0 0 720 480\" role=\"img\" aria-label=\"',escapeXML(title),'\"><rect width=\"720\" height=\"480\" fill=\"white\"/><g font-family=\"Arial,sans-serif\" font-size=\"13\" fill=\"#18232f\"><text x=\"360\" y=\"25\" text-anchor=\"middle\">',escapeXML(title),'</text>')\n for(j in 0:4){y<-ymin+(ymax-ymin)*j/4;x<-xmin+(xmax-xmin)*j/4;out<-paste0(out,'<line x1=\"82\" y1=\"',Y(y),'\" x2=\"690\" y2=\"',Y(y),'\" stroke=\"#e2e8f0\"/><text x=\"73\" y=\"',Y(y)+4,'\" text-anchor=\"end\">',sprintf('%.3g',y),'</text><text x=\"',X(x),'\" y=\"380\" text-anchor=\"middle\">',sprintf('%.3g',x),'</text>')}\n ss<-unique(vapply(pp,`[[`,character(1),'series'));cols<-c('#0f766e','#c76622','#4f46e5','#b23857')\n for(j in seq_along(ss)){rr<-Filter(function(p)p$series==ss[j],pp);xy<-vapply(rr,function(p)sprintf('%.6f,%.6f',X(p$x),Y(p$y)),character(1));col<-cols[(j-1)%%4+1];for(p in rr)out<-paste0(out,'<circle cx=\"',sprintf('%.6f',X(p$x)),'\" cy=\"',sprintf('%.6f',Y(p$y)),'\" r=\"2.6\" fill=\"',col,'\"><title>',escapeXML(ss[j]),': ',escapeXML(p$y),'</title></circle>');out<-paste0(out,'<text x=\"',82+((j-1)%%2)*310,'\" y=\"',432+floor((j-1)/2)*23,'\" fill=\"',col,'\">',escapeXML(ss[j]),'</text>')}\n paste0(out,'<text x=\"360\" y=\"405\" text-anchor=\"middle\">Declared record / candidate index; fixed example</text></g></svg>')\n}\ntoJSON<-function(x){\n if(is.null(x))return('null');if(is.list(x)){v<-vapply(x,toJSON,character(1));if(!is.null(names(x)))paste0('{',paste(paste0(vapply(names(x),toJSON,character(1)),':',v),collapse=','),'}')else paste0('[',paste(v,collapse=','),']')}\n else if(length(x)!=1){if(!is.numeric(x)&&!is.null(names(x)))toJSON(as.list(x))else paste0('[',paste(vapply(as.list(x),toJSON,character(1)),collapse=','),']')}\n else if(is.na(x))'null'else if(is.logical(x))if(x)'true'else'false'else if(is.numeric(x))if(is.finite(x))sprintf('%.17g',x)else'null'else paste0('\"',gsub('\\n','\\\\n',gsub('\"','\\\\\"',gsub('\\\\','\\\\\\\\',x,fixed=TRUE),fixed=TRUE),fixed=TRUE),'\"')\n}\n\nFIXED<-list(`api`=\"evaluate\",`variant`=\"reject-negative-weight\",`title`=\"Genuine rejection of a negative weight\",`input`=list(`rows`=list(list(`id`=\"bad\",`y`=\"0\",`prediction`=\"0\",`weight`=\"-1\"))),`expectedFailure`=TRUE,`error`=\"negative-weight\",`unit`=\"Invalid input; no plotted zero\",`titleI18n`=list(`ko`=\"음의 비중의 실제 거절\",`en`=\"Genuine rejection of a negative weight\"))\n\nargs<-commandArgs(trailingOnly=TRUE);out<-if(length(args))args[1]else stop('NEW output directory required');if(dir.exists(out))stop('Preserve previous output directory');dir.create(out,recursive=TRUE)\nz<-fixedOperation(FIXED$api,FIXED$input);rr<-reportValues(FIXED$api,z)\nwriteLines(toJSON(list(arithmetic='BaseR binary64 author counterpart; native group hashing exact within declared integer range, stump approximate tie tolerance1e-12; not an independent exact oracle',result=z)),file.path(out,'full.json'),useBytes=TRUE)\nsums<-do.call(rbind,lapply(rr$summary,function(row)data.frame(metric=row$metric,value=if(is.null(row$value))''else if(is.logical(row$value))as.character(as.integer(row$value))else format(row$value,digits=17,scientific=NA,trim=TRUE),unit=row$unit,defined=as.integer(!is.null(row$value)),stringsAsFactors=FALSE)))\npoints<-do.call(rbind,lapply(rr$points,function(p)data.frame(series=p$series,index=p$index,x=p$x,y=if(is.null(p$y))NA_real_ else p$y,defined=as.integer(!is.null(p$y)),stringsAsFactors=FALSE)))\nwrite.csv(sums,file.path(out,'summary.csv'),row.names=FALSE,na='');write.csv(points,file.path(out,'plot-points.csv'),row.names=FALSE,na='');writeLines(svgPlot(Filter(function(p)!is.null(p$y),rr$points),FIXED$title),file.path(out,'plot.svg'),useBytes=TRUE);cat(FIXED$api,'/',FIXED$variant,'\\n',sep='')\n",
        "returnCode": 1,
        "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 FUN(X[[i]], ...) : negative-weight\nCalls: fixedOperation -> fixedRows -> lapply -> FUN\nExecution halted",
        "diagnosticScope": "Public projection omits private absolute-path/traceback frames; actual exit and warnings/reason retained. Raw complete streams and commands in private execution proof.",
        "resultFolder": "ml22-code/runs/r-evaluate-reject-negative-weight",
        "kind": null,
        "inputFiles": [
          {
            "file": "ml22-code/evaluate-reject-negative-weight-input.json",
            "sha256": "8769116a70fa17195d8a056b88ca746b7d8363583ead1c34436957a1dde28a48",
            "scope": "Complete fixed literal input; program embeds the same values"
          }
        ],
        "files": [],
        "summaryRows": [],
        "plotRows": [],
        "plotFile": null,
        "fullResultFile": null,
        "arithmeticScope": "Python exact rational versus base-R approximate floating algebra; copied author kernels, not independent oracle.",
        "plotScope": "Original scatter vectors plot every defined declared comparison point, with missing points omitted. Source profiles show candidate risks; all source records remain in the full result and source CSV files.",
        "reproductionScope": "Standalone literal program plus four native CSV files for factual source profiles. No answer/engine/checker imports."
      }
    }
  },
  "select": {
    "python": {
      "mean-validation": {
        "api": "select",
        "variant": "mean-validation",
        "language": "python",
        "title": "Selection by mean validation risk",
        "titleI18n": {
          "ko": "평균 검증 위험의 선택",
          "en": "Selection by mean validation risk"
        },
        "input": {
          "rows": [
            {
              "id": "G",
              "y": "0",
              "weight": "9",
              "cohort": "G",
              "role": "validation"
            },
            {
              "id": "H",
              "y": "0",
              "weight": "1",
              "cohort": "H",
              "role": "validation"
            },
            {
              "id": "held",
              "y": "0",
              "cohort": "G",
              "role": "test"
            }
          ],
          "candidates": [
            {
              "id": "A",
              "predictions": [
                "1",
                "3",
                "0"
              ]
            },
            {
              "id": "B",
              "predictions": [
                "2",
                "2",
                "5"
              ]
            }
          ],
          "criterion": "mean",
          "requiredCohorts": [
            "G",
            "H"
          ]
        },
        "expectedFailure": false,
        "codeFile": "ml22-code/select-mean-validation.py",
        "codeSHA256": "349ca94cb32f7da2e608de853e43d8a0b1e0d4e43bc421094300b63bc904f38e",
        "code": "# ML22 standalone fixed literal. Attribution and arithmetic scope in README.\nimport csv,hashlib,html,json,math,sys,time\nfrom pathlib import Path\nfrom fractions import Fraction as F\nfrom collections import Counter\nsys.set_int_max_str_digits(200000)\nnumber=lambda v:F(str(v))\ndef Q(x):return None if x is None or x in ('','.') else F(str(x))\n\ndef canonical(v):return None if Q(v) is None else str(Q(v))\n\ndef fingerprint(tag,values):return tag+':'+hashlib.sha256(json.dumps([canonical(x)for x in values],separators=(',',':')).encode()).hexdigest()\n\ndef split(rows,seed=20261104,pattern=('test','validation','train','train')):\n order=sorted(set(r['group'] for r in rows));state=seed\n for j in range(len(order)-1,0,-1):state=(1664525*state+1013904223)&0xffffffff;k=state%(j+1);order[k],order[j]=order[j],order[k]\n roles={g:(i,pattern[i%len(pattern)]) for i,g in enumerate(order)}\n return roles,state,order\n\ndef solve(A,b):\n n=len(b);M=[list(row)+[rhs]for row,rhs in zip(A,b)];piv=[];rank=0\n for j in range(n):\n  candidates=[i for i in range(rank,n)if M[i][j]]\n  if not candidates:continue\n  k=max(candidates,key=lambda i:abs(M[i][j]));M[rank],M[k]=M[k],M[rank];v=M[rank][j];M[rank]=[x/v for x in M[rank]]\n  for i in range(n):\n   if i!=rank:\n    v=M[i][j];M[i]=[a-v*b for a,b in zip(M[i],M[rank])]\n  piv.append(j);rank+=1\n x=[F(0)]*n\n for i,j in enumerate(piv):x[j]=M[i][-1]\n null=[]\n for j in range(n):\n  if j not in piv:\n   v=[F(0)]*n;v[j]=F(1)\n   for i,k in enumerate(piv):v[k]=-M[i][j]\n   null.append(v)\n return x,rank,null\n\ndef dot(a,b):return sum((x*y for x,y in zip(a,b)),F(0))\n\ndef fit(rows,method,lam=F(0),minleaf=1,binary=False):\n use=[r for r in rows if r['role']=='train'and r['w']>0 and r['y']is not None and None not in r['x']];p=len(rows[0]['x'])if rows else 0\n if not use:return dict(defined=False,pred=[None]*len(rows),raw=[None]*len(rows),train=[],invariant=[None]*len(rows))\n mass=sum(r['w']for r in use);mu=[sum(r['w']*r['x'][j]for r in use)/mass for j in range(p)];scale=[max(r['x'][j]for r in use)-min(r['x'][j]for r in use)or F(1)for j in range(p)];mean=sum(r['w']*r['y']for r in use)/mass;model={};z=lambda r:[F(1)]+[(x-m)/s for x,m,s in zip(r['x'],mu,scale)]\n if method=='constant':model=dict(mean=mean,parameterCount=1,rank=1,unique=True)\n elif method=='ridge':\n  vectors=[z(r)for r in use];n=p+1;A=[[sum(r['w']*xx[j]*xx[k]for r,xx in zip(use,vectors))/mass+(lam if j==k and j>0 else F(0))for k in range(n)]for j in range(n)];b=[sum(r['w']*r['y']*xx[j]for r,xx in zip(use,vectors))/mass for j in range(n)];theta,rank,null=solve(A,b);objective=sum(r['w']*(dot(xx,theta)-r['y'])**2 for r,xx in zip(use,vectors))/(2*mass)+lam*sum(x*x for x in theta[1:])/2;model=dict(lambdaValue=lam,theta=theta,rank=rank,unique=rank==n,nullspace=null,minimumObjective=objective,parameterCount=n)\n else:\n  best=None;total=sum(r['w']*r['y']for r in use);total2=sum(r['w']*r['y']**2 for r in use);base=total2-total**2/mass\n  for j in range(p):\n   ordered=sorted(enumerate(use),key=lambda v:(v[1]['x'][j],v[0]));leftW=F(0);leftS=F(0)\n   for i,(_idx,r)in enumerate(ordered[:-1]):\n    leftW+=r['w'];leftS+=r['w']*r['y'];rightW=mass-leftW\n    if i+1<minleaf or len(use)-i-1<minleaf or r['x'][j]==ordered[i+1][1]['x'][j]:continue\n    SSE=total2-leftS**2/leftW-(total-leftS)**2/rightW\n    if best is None or SSE<best['weightedSSE']:best=dict(feature=j,threshold=(r['x'][j]+ordered[i+1][1]['x'][j])/2,leftMean=leftS/leftW,rightMean=(total-leftS)/rightW,leftRows=i+1,rightRows=len(use)-i-1,leftWeight=leftW,rightWeight=rightW,weightedSSE=SSE)\n  model=dict(split=False,mean=mean,weightedSSE=base,trainingMSE=base/mass)if best is None or best['weightedSSE']>=base else dict(split=True,**best,trainingMSE=best['weightedSSE']/mass,improvement=(base-best['weightedSSE'])/mass)\n raw=[];invariant=[]\n for r in rows:\n  if None in r['x']:raw.append(None);invariant.append(None);continue\n  if method=='constant':v=mean;iv=True\n  elif method=='ridge':zz=z(r);v=dot(zz,model['theta']);iv=all(dot(zz,nn)==0 for nn in model['nullspace'])\n  else:v=(model['leftMean']if r['x'][model['feature']]<=model['threshold']else model['rightMean'])if model['split']else mean;iv=True\n  raw.append(v);invariant.append(iv)\n pred=[None if x is None else min(F(1),max(F(0),x))if binary else x for x in raw]\n return dict(defined=True,train=[r['id']for r in use],mass=mass,meanX=mu,scales=scale,model=model,pred=pred,raw=raw,invariant=invariant)\n\ndef risk(rows,pred,binary=False,threshold=F(1,2)):\n use=[(r,p)for r,p in zip(rows,pred)if r['w']>0 and r['y']is not None and p is not None and r['role']not in['excluded','unused']];mass=sum((r['w']for r,p in use),F(0));d=dict(rows=len(use),mass=mass)\n if not mass:\n  d.update({k:None for k in ['MSE','MAE','R2']+(['Brier','accuracy','balancedAccuracy','AUROC']if binary else[])});return d\n mean=sum(r['w']*r['y']for r,p in use)/mass;sse=sum(r['w']*(p-r['y'])**2 for r,p in use);sst=sum(r['w']*(r['y']-mean)**2 for r,p in use);d.update(meanY=mean,SSE=sse,SST=sst,MSE=sse/mass,MAE=sum(r['w']*abs(p-r['y'])for r,p in use)/mass,R2=1-sse/sst if sst else None)\n if binary:\n  weights=Counter();num=Counter()\n  for r,p in use:k=('T'if int(p>=threshold)==int(r['y'])else'F')+('P'if p>=threshold else'N');weights[k]+=r['w'];num[k]+=1\n  TP,FP,TN,FN=[weights[k]for k in ['TP','FP','TN','FN']];positive=TP+FN;negative=TN+FP;rate=lambda a,b:a/b if b else None;TPR=rate(TP,positive);TNR=rate(TN,negative)\n  # Pair enumeration is independent of the subject's score-tie-block formula.\n  negatives=[(r,p)for r,p in use if not r['y']];positives=[(r,p)for r,p in use if r['y']];wins=sum((a['w']*b['w']*(F(1)if pa>pb else F(1,2)if pa==pb else F(0))for a,pa in positives for b,pb in negatives),F(0))\n  d.update(Brier=d['MSE'],threshold=threshold,confusionMass={k:weights[k]for k in ['TP','FP','TN','FN']},confusionRows={k:num[k]for k in ['TP','FP','TN','FN']},positiveMass=positive,negativeMass=negative,accuracy=(TP+TN)/mass,positiveRecall=TPR,negativeRecall=TNR,precision=rate(TP,TP+FP),F1=rate(2*TP,2*TP+FP+FN),balancedAccuracy=(TPR+TNR)/2 if TPR is not None and TNR is not None else None,AUROC=rate(wins,positive*negative))\n return d\n\nNATIVE_SHA256={'actual1599-red-wine-original12-fields.csv': '77e9ac73115930d6c43983333a5a57940deefc493affeb17aca478c09c5f6e00', 'actual4898-white-wine-original12-fields.csv': '50d810bbb42b9cc3e87fa4c27a4c0f168e72da09dd812863425ca3873fec28ef', 'actual3613-NLS-original52-fields.csv': '6e1e1895558795435b65f8634252a7589865273a0e69adbd715fcfa04a3c11a1', 'actual3150-churn-original14-fields.csv': '1c0753e434226e769d1015c922121a7d8967df66014e057c4f7543e490f11764'}\n\ndef read_sources(directory,seed):\n def read(name):\n  p=directory/name\n  if hashlib.sha256(p.read_bytes()).hexdigest()!=NATIVE_SHA256[name]:raise ValueError('Native file hash differs: '+name)\n  with p.open(encoding='utf8',newline='')as f:return list(csv.DictReader(f))\n sources={};wine=[]\n for typ,n in [('red',1599),('white',4898)]:\n  table=read(f'actual{n}-{typ}-wine-original12-fields.csv');assert len(table)==n;features=[k for k in table[0]if k not in ['sourceRow','wineType','quality']];assert len(features)==11\n  for r in table:\n   i=int(r['sourceRow']);red='1'if typ=='red'else'0';nativeX=[r[k]for k in features];wine.append(dict(id=f'wine-{typ}-row:{i}',sourceRow=f'{typ}:{i}',originalID=None,group=fingerprint('wine-predictors',[red]+nativeX),cohort=typ,x=list(map(Q,nativeX+[red])),y=Q(r['quality'])))\n sources['country']=wine\n table=read('actual3613-NLS-original52-fields.csv');assert len(table)==3613;sources['person']=[dict(id='nls-row:'+r['sourceRow'],sourceRow=int(r['sourceRow']),originalID=r['id'],group='nls-id:'+r['id'],cohort='schooling-over12'if Q(r['ed76'])>12 else'schooling-at-most12',x=[Q(r['ed76']),Q(r['age76'])],y=Q(r['lwage76']))for r in table]\n table=read('actual3150-churn-original14-fields.csv');assert len(table)==3150;predictors=[k for k in table[0]if k not in ['sourceRow','Churn']];assert len(predictors)==13;sources['company']=[dict(id='customer-row:'+r['sourceRow'],sourceRow=int(r['sourceRow']),originalID=None,group=fingerprint('customer-predictors',[r[k]for k in predictors]),cohort='pay-as-you-go'if r['Tariff Plan']=='1'else'contractual'if r['Tariff Plan']=='2'else'other-native-tariff',x=[Q(r[k])for k in ['Call  Failure','Subscription  Length','Seconds of Use','Age']],y=Q(r['Churn']))for r in table]\n for kind,rows in sources.items():\n  assignments,state,order=split(rows,seed)\n  for r in rows:\n   rank,planned=assignments[r['group']];r.update(w=F(1),splitRank=rank,plannedRole=planned,eligible=r['y']is not None and None not in r['x']);r['role']=planned if r['eligible']else'excluded'\n return sources\n# New ML22 fixed-profile kernels. The public Fraction fitting/source readers are\n# copied by value above this file by the standalone builder; never imported.\ndef fixed_rows(data, prediction_key=None):\n out=[]\n for i,a in enumerate(data):\n  w=Q(a.get('weight','1'))\n  if w is None or w<0:raise ValueError('negative-weight' if w is not None and w<0 else 'missing-weight')\n  out.append(dict(id=a.get('id',str(i)),group=a.get('group',a.get('id',str(i))),cohort=a.get('cohort','all'),role=a.get('role','train'),w=w,x=[Q(v)for v in a.get('x',[])],y=Q(a.get('y'))))\n return out\n\ndef weighted_pair(rows,A,B):\n use=[(r,a,b)for r,a,b in zip(rows,A,B)if r['w']>0 and r['y']is not None and a is not None and b is not None and r['role']not in ['excluded','unused']]\n mass=sum((r['w']for r,a,b in use),F(0));records=[];groups={}\n for r,a,b in use:\n  la=(a-r['y'])**2;lb=(b-r['y'])**2;d=la-lb\n  records.append(dict(id=r['id'],group=r['group'],weight=r['w'],lossA=la,lossB=lb,difference=d))\n  g=groups.setdefault(r['group'],dict(group=r['group'],rows=0,mass=F(0),sum=F(0)));g['rows']+=1;g['mass']+=r['w'];g['sum']+=r['w']*d\n total=sum((g['sum']for g in groups.values()),F(0));mean=total/mass if mass else None;G=len(groups)\n for g in groups.values():g['leaveOut']=(total-g['sum'])/(mass-g['mass'])if mass>g['mass']else None\n leaves=[g['leaveOut']for g in groups.values()if g['leaveOut']is not None]\n proxy=F(G-1,G)*sum((v-sum(leaves,F(0))/G)**2 for v in leaves) if G>1 and len(leaves)==G else None\n return dict(rows=len(use),mass=mass,groupCount=G,meanDifference=mean,minimumLeaveOut=min(leaves)if leaves else None,maximumLeaveOut=max(leaves)if leaves else None,varianceProxy=proxy,groups=list(groups.values()),records=records)\n\ndef run_selection(rows,candidates,criterion,required,binary=False):\n results=[]\n for c,pred in candidates:\n  val=[dict(r,role='excluded')if r['role']!='validation'else r for r in rows]\n  test=[dict(r,role='excluded')if r['role']!='test'else r for r in rows]\n  v=risk(val,pred,binary);t=risk(test,pred,binary);cohort={g:risk([dict(r,role='excluded')if r['role']!='validation'or r['cohort']!=g else r for r in rows],pred,binary)for g in required}\n  values=[cohort[g]['MSE']for g in required]\n  score=v['MSE']if criterion=='mean'else max(values)if values and None not in values else None\n  results.append(dict(id=c,criterion=score,validation=v,test=t,cohorts=cohort))\n eligible=[(i,r['criterion'])for i,r in enumerate(results)if r['criterion']is not None]\n chosen=min(eligible,key=lambda t:(t[1],t[0]))[0]if eligible else None\n return dict(criterion=criterion,selected=results[chosen]['id']if chosen is not None else None,selectedIndex=chosen,candidates=results)\n\ndef fixed_operation(api,a):\n if api=='realdata':\n  kind=a['kind'];rows=read_sources(Path(__file__).parent/'data',a.get('seed',20261104))[kind];binary=kind=='company'\n  defs=[('constant','constant',F(0)),('ridge:1/100','ridge',F(1,100)),('ridge:1/10','ridge',F(1,10)),('ridge:1','ridge',F(1)),('one-split-stump','stump',F(0))]\n  fits=[fit(rows,method,lam,5,binary)for _,method,lam in defs]\n  selection=run_selection(rows,[(d[0],f['pred'])for d,f in zip(defs,fits)],a.get('criterion','mean'),list(dict.fromkeys(r['cohort']for r in rows)),binary)\n  chosen=selection['selectedIndex'];best=fits[chosen];base=fits[0]\n  test=[dict(r,role='excluded')if r['role']!='test'else r for r in rows]\n  paired=weighted_pair(test,best['pred'],base['pred'])\n  records=[dict(id=r['id'],sourceRow=r.get('sourceRow'),originalID=r.get('originalID'),group=r['group'],cohort=r['cohort'],plannedRole=r['plannedRole'],role=r['role'],eligible=r['eligible'],y=r['y'],baselinePrediction=base['pred'][i],selectedPrediction=best['pred'][i],selectedRawPrediction=best['raw'][i],queryInvariant=best['invariant'][i])for i,r in enumerate(rows)]\n  return dict(kind=kind,nativeRows=len(rows),eligibleRows=sum(r['eligible']for r in rows),selection=selection,models=[dict(id=d[0],train=f['train'],mass=f.get('mass'),meanX=f.get('meanX'),scales=f.get('scales'),model=f.get('model'))for d,f in zip(defs,fits)],paired=paired,records=records)\n rows=fixed_rows(a.get('rows',[]));binary=a.get('task')=='binary'\n if api=='split':\n  assignment,state,order=split(rows,a.get('seed',0));records=[dict(id=r['id'],group=r['group'],rank=assignment[r['group']][0],role=assignment[r['group']][1])for r in rows]\n  return dict(state=state,groupOrder=order,records=records,groupCount=len(order))\n if api=='fit':return fit(rows,a.get('method','constant'),Q(a.get('lambda','0')),a.get('minLeafRows',1),binary)\n if api=='evaluate':\n  pred=[Q(r.get('prediction'))for r in a['rows']];threshold=Q(a.get('threshold','1/2'));rr=risk(rows,pred,binary,threshold)\n  records=[]\n  for r,p in zip(rows,pred):\n   valid=r['w']>0 and r['y']is not None and p is not None and r['role']not in ['excluded','unused']\n   records.append(dict(id=r['id'],weight=r['w'],y=r['y'],prediction=p,eligible=valid,loss=(p-r['y'])**2 if valid else None,correct=dict(defined=valid and binary,value=bool(int(p>=threshold)==int(r['y']))if valid and binary else None)))\n  return dict(metrics=rr,records=records)\n if api=='select':return run_selection(rows,[(c['id'],list(map(Q,c['predictions'])))for c in a['candidates']],a.get('criterion','mean'),a.get('requiredCohorts',list(dict.fromkeys(r['cohort']for r in rows))),binary)\n if api=='paired':return weighted_pair(rows,[Q(r.get('predictionA'))for r in a['rows']],[Q(r.get('predictionB'))for r in a['rows']])\n raise ValueError('unknown-api')\n\ndef report_values(api,z):\n summary=[];series=[]\n def add(k,v,u='dimensionless'):summary.append((k,v,u))\n if api=='split':\n  add('groups',z['groupCount'],'groups');add('rows',len(z['records']),'rows');add('finalState',z['state'],'unsigned 32-bit state')\n  series=[('planned role code',[(i,F({'test':0,'validation':1,'train':2}[r['role']]))for i,r in enumerate(z['records'])])]\n elif api=='fit':\n  add('defined',z['defined']);add('trainingRows',len(z['train']),'rows');add('trainingMass',z.get('mass'),'analysis weight mass')\n  model=z.get('model',{});add('modelRank',model.get('rank'),'parameters');add('threshold',model.get('threshold'),'constructed feature units');add('minimumObjective',model.get('minimumObjective'),'constructed squared outcome units')\n  series=[('prediction',list(enumerate(z['pred'])))];\n  if model.get('theta')is not None:\n   for i,v in enumerate(model['theta']):add('theta'+str(i),v,'constructed outcome units per standardized coordinate')\n elif api=='evaluate':\n  for k in ['rows','mass','MSE','MAE','R2','Brier','accuracy','positiveRecall','negativeRecall','precision','F1','balancedAccuracy','AUROC']: \n   if k in z['metrics']:add(k,z['metrics'][k],'rows'if k=='rows'else'analysis weight mass'if k=='mass'else FIXED['unit']if k in ['MSE','Brier']else'constructed outcome units'if k=='MAE'else'dimensionless')\n  series=[('squared loss',[(i,r['loss'])for i,r in enumerate(z['records'])])]\n elif api=='select':\n  add('selectedIndex',z['selectedIndex'],'zero-based candidate index')\n  for i,c in enumerate(z['candidates']):add('criterion'+str(i),c['criterion'],FIXED['unit']);add('testMSE'+str(i),c['test']['MSE'],FIXED['unit'])\n  series=[('validation criterion',[(i,c['criterion'])for i,c in enumerate(z['candidates'])]),('test MSE',[(i,c['test']['MSE'])for i,c in enumerate(z['candidates'])])]\n elif api=='paired':\n  for k in ['rows','mass','groupCount','meanDifference','minimumLeaveOut','maximumLeaveOut','varianceProxy']:add(k,z[k],'rows'if k=='rows'else'groups'if k=='groupCount'else'analysis weight mass'if k=='mass'else FIXED['unit']+' squared'if k=='varianceProxy'else FIXED['unit'])\n  series=[('loss A minus loss B',[(i,r['difference'])for i,r in enumerate(z['records'])])]\n elif api=='realdata':\n  add('nativeRows',z['nativeRows'],'native records');add('eligibleRows',z['eligibleRows'],'complete records');add('selectedIndex',z['selection']['selectedIndex'],'zero-based candidate index')\n  for i,c in enumerate(z['selection']['candidates']):add('validationMSE'+str(i),c['validation']['MSE'],FIXED['unit']);add('testMSE'+str(i),c['test']['MSE'],FIXED['unit'])\n  for k in ['meanDifference','minimumLeaveOut','maximumLeaveOut','varianceProxy']:add(k,z['paired'][k],FIXED['unit']+' squared'if k=='varianceProxy'else FIXED['unit'])\n  best=z['selection']['candidates'][z['selection']['selectedIndex']]['test']\n  for k in ['accuracy','positiveRecall','negativeRecall','precision','balancedAccuracy','AUROC']:\n   if k in best:add(k,best[k])\n  series=[('validation MSE',[(i,c['validation']['MSE'])for i,c in enumerate(z['selection']['candidates'])]),('test MSE',[(i,c['test']['MSE'])for i,c in enumerate(z['selection']['candidates'])])]\n return summary,series\n\n\ndef fixed_svg(points,title):\n good=[p for p in points if p['y'] is not None];xx=[float(p['x'])for p in good];yy=[float(p['y'])for p in good];xmin=min(xx)if xx else 0;xmax=max(xx)if xx else 1;ymin=min([0]+yy);ymax=max([0]+yy)\n if xmin==xmax:xmin-=.5;xmax+=.5\n if ymin==ymax:ymin-=.5;ymax+=.5\n pad=(ymax-ymin)*.08;ymin-=pad;ymax+=pad;X=lambda x:82+(float(x)-xmin)/(xmax-xmin)*608;Y=lambda y:354-(float(y)-ymin)/(ymax-ymin)*290;e=html.escape\n out=['<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"720\" height=\"480\" viewBox=\"0 0 720 480\" role=\"img\" aria-label=\"'+e(title)+'\"><rect width=\"720\" height=\"480\" fill=\"white\"/><g font-family=\"Arial,sans-serif\" font-size=\"13\" fill=\"#18232f\"><text x=\"360\" y=\"25\" text-anchor=\"middle\">'+e(title)+'</text>']\n for j in range(5):\n  y=ymin+(ymax-ymin)*j/4;x=xmin+(xmax-xmin)*j/4;out.append('<line x1=\"82\" y1=\"'+str(Y(y))+'\" x2=\"690\" y2=\"'+str(Y(y))+'\" stroke=\"#e2e8f0\"/><text x=\"73\" y=\"'+str(Y(y)+4)+'\" text-anchor=\"end\">'+format(y,'.3g')+'</text><text x=\"'+str(X(x))+'\" y=\"380\" text-anchor=\"middle\">'+format(x,'.3g')+'</text>')\n series=list(dict.fromkeys(p['series']for p in good))\n for j,s in enumerate(series):\n  pp=[p for p in good if p['series']==s];color=['#0f766e','#c76622','#4f46e5','#b23857'][j%4]\n  for p in pp:out.append('<circle cx=\"'+format(X(p['x']),'.6f')+'\" cy=\"'+format(Y(p['y']),'.6f')+'\" r=\"2.6\" fill=\"'+color+'\"><title>'+e(s+': '+str(p['y']))+'</title></circle>')\n  out.append('<text x=\"'+str(82+(j%2)*310)+'\" y=\"'+str(432+(j//2)*23)+'\" fill=\"'+color+'\">'+e(s)+'</text>')\n out.append('<text x=\"360\" y=\"405\" text-anchor=\"middle\">Declared record / candidate index; units in summary</text></g></svg>');return''.join(out)\n\nFIXED={'api': 'select', 'variant': 'mean-validation', 'title': 'Selection by mean validation risk', 'input': {'rows': [{'id': 'G', 'y': '0', 'weight': '9', 'cohort': 'G', 'role': 'validation'}, {'id': 'H', 'y': '0', 'weight': '1', 'cohort': 'H', 'role': 'validation'}, {'id': 'held', 'y': '0', 'cohort': 'G', 'role': 'test'}], 'candidates': [{'id': 'A', 'predictions': ['1', '3', '0']}, {'id': 'B', 'predictions': ['2', '2', '5']}], 'criterion': 'mean', 'requiredCohorts': ['G', 'H']}, 'unit': 'Constructed squared outcome units', 'titleI18n': {'ko': '평균 검증 위험의 선택', 'en': 'Selection by mean validation risk'}}\n\nOUT=Path(sys.argv[1]);OUT.mkdir(parents=True,exist_ok=False)\nresult=fixed_operation(FIXED['api'],FIXED['input']);summary,series=report_values(FIXED['api'],result)\ndef encode(v):\n if isinstance(v,F):return str(v)\n if isinstance(v,dict):return{k:encode(x)for k,x in v.items()}\n if isinstance(v,(list,tuple)):return[encode(x)for x in v]\n return v\n(OUT/'full.json').write_text(json.dumps(dict(arithmetic='Exact rational author implementation; factual rows, declared group split and finite five-candidate comparison',result=encode(result)),ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\nsummaryRows=[dict(metric=m,value=''if v is None else str(int(v))if isinstance(v,bool)else str(v),unit=u,defined=int(v is not None))for m,v,u in summary]\npoints=[dict(series=name,index=i,x=str(x),y=''if y is None else str(y),defined=int(y is not None))for name,pp in series for i,(x,y)in enumerate(pp)]\nfor name,rows in [('summary',summaryRows),('plot-points',points)]:\n with(OUT/(name+'.csv')).open('w',encoding='utf8',newline='')as f:writer=csv.DictWriter(f,fieldnames=list(rows[0]));writer.writeheader();writer.writerows(rows)\n(OUT/'plot.svg').write_text(fixed_svg([dict(p,x=number(p['x']),y=None if not p['defined']else number(p['y']))for p in points],FIXED['title']),encoding='utf8');print(FIXED['api']+'/'+FIXED['variant'])\n",
        "returnCode": 0,
        "stdout": "select/mean-validation\r\n",
        "stderr": "",
        "diagnosticScope": "Public projection omits private absolute-path/traceback frames; actual exit and warnings/reason retained. Raw complete streams and commands in private execution proof.",
        "resultFolder": "ml22-code/runs/python-select-mean-validation",
        "kind": null,
        "inputFiles": [
          {
            "file": "ml22-code/select-mean-validation-input.json",
            "sha256": "b8f14eadb523c13369aa74bd5d4704d77ebd93299d131bade9aa0c30d1f74d9c",
            "scope": "Complete fixed literal input; program embeds the same values"
          }
        ],
        "files": [
          {
            "file": "ml22-code/runs/python-select-mean-validation/full.json",
            "sha256": "220723a6119362ff04827fdf388637be4e2fab8e38776e3fa4fa43b0538dbb2e",
            "bytes": 2273
          },
          {
            "file": "ml22-code/runs/python-select-mean-validation/plot-points.csv",
            "sha256": "058c8098fb2e9f4bc7b4a58f571442045f997d1cc200eab9c5d23d1abf12d39e",
            "bytes": 125
          },
          {
            "file": "ml22-code/runs/python-select-mean-validation/plot.svg",
            "sha256": "c97eec27007bfc90ec0f34fac1a4c218da50d28ca4e61bc222cc551062fa3733",
            "bytes": 1818
          },
          {
            "file": "ml22-code/runs/python-select-mean-validation/summary.csv",
            "sha256": "dced92cf21e13ea4957c5be820cf7a2cf4812c0ce900c514b2c1bacbc53282bd",
            "bytes": 272
          }
        ],
        "summaryRows": [
          {
            "metric": "selectedIndex",
            "value": "0.0",
            "unit": "zero-based candidate index",
            "defined": "true",
            "rawValue": "0",
            "arithmetic": "Exact Fraction",
            "exactFraction": "0",
            "mathematicallyPositive": false,
            "mathematicallyNegative": false,
            "exactZero": true,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "criterion0",
            "value": "1.8",
            "unit": "Constructed squared outcome units",
            "defined": "true",
            "rawValue": "9/5",
            "arithmetic": "Exact Fraction",
            "exactFraction": "9/5",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "testMSE0",
            "value": "0.0",
            "unit": "Constructed squared outcome units",
            "defined": "true",
            "rawValue": "0",
            "arithmetic": "Exact Fraction",
            "exactFraction": "0",
            "mathematicallyPositive": false,
            "mathematicallyNegative": false,
            "exactZero": true,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "criterion1",
            "value": "4.0",
            "unit": "Constructed squared outcome units",
            "defined": "true",
            "rawValue": "4",
            "arithmetic": "Exact Fraction",
            "exactFraction": "4",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "testMSE1",
            "value": "25.0",
            "unit": "Constructed squared outcome units",
            "defined": "true",
            "rawValue": "25",
            "arithmetic": "Exact Fraction",
            "exactFraction": "25",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          }
        ],
        "plotRows": [
          {
            "series": "validation criterion",
            "index": "0",
            "x": "0",
            "y": "9/5",
            "defined": true,
            "xExact": "0",
            "yExact": "9/5"
          },
          {
            "series": "validation criterion",
            "index": "1",
            "x": "1",
            "y": "4",
            "defined": true,
            "xExact": "1",
            "yExact": "4"
          },
          {
            "series": "test MSE",
            "index": "0",
            "x": "0",
            "y": "0",
            "defined": true,
            "xExact": "0",
            "yExact": "0"
          },
          {
            "series": "test MSE",
            "index": "1",
            "x": "1",
            "y": "25",
            "defined": true,
            "xExact": "1",
            "yExact": "25"
          }
        ],
        "plotFile": "ml22-code/runs/python-select-mean-validation/plot.svg",
        "fullResultFile": "ml22-code/runs/python-select-mean-validation/full.json",
        "arithmeticScope": "Python exact rational versus base-R approximate floating algebra; copied author kernels, not independent oracle.",
        "plotScope": "Original scatter vectors plot every defined declared comparison point, with missing points omitted. Source profiles show candidate risks; all source records remain in the full result and source CSV files.",
        "reproductionScope": "Standalone literal program plus four native CSV files for factual source profiles. No answer/engine/checker imports."
      },
      "worst-cohort-validation": {
        "api": "select",
        "variant": "worst-cohort-validation",
        "language": "python",
        "title": "Selection by worst-cohort validation risk",
        "titleI18n": {
          "ko": "최악 코호트 검증 위험의 선택",
          "en": "Selection by worst-cohort validation risk"
        },
        "input": {
          "rows": [
            {
              "id": "G",
              "y": "0",
              "weight": "9",
              "cohort": "G",
              "role": "validation"
            },
            {
              "id": "H",
              "y": "0",
              "weight": "1",
              "cohort": "H",
              "role": "validation"
            },
            {
              "id": "held",
              "y": "0",
              "cohort": "G",
              "role": "test"
            }
          ],
          "candidates": [
            {
              "id": "A",
              "predictions": [
                "1",
                "3",
                "0"
              ]
            },
            {
              "id": "B",
              "predictions": [
                "2",
                "2",
                "5"
              ]
            }
          ],
          "criterion": "worst-cohort",
          "requiredCohorts": [
            "G",
            "H"
          ]
        },
        "expectedFailure": false,
        "codeFile": "ml22-code/select-worst-cohort-validation.py",
        "codeSHA256": "be7c8225815b453e04242d0d39972323162f3b5b1d11745b86a9d9c36546f9dd",
        "code": "# ML22 standalone fixed literal. Attribution and arithmetic scope in README.\nimport csv,hashlib,html,json,math,sys,time\nfrom pathlib import Path\nfrom fractions import Fraction as F\nfrom collections import Counter\nsys.set_int_max_str_digits(200000)\nnumber=lambda v:F(str(v))\ndef Q(x):return None if x is None or x in ('','.') else F(str(x))\n\ndef canonical(v):return None if Q(v) is None else str(Q(v))\n\ndef fingerprint(tag,values):return tag+':'+hashlib.sha256(json.dumps([canonical(x)for x in values],separators=(',',':')).encode()).hexdigest()\n\ndef split(rows,seed=20261104,pattern=('test','validation','train','train')):\n order=sorted(set(r['group'] for r in rows));state=seed\n for j in range(len(order)-1,0,-1):state=(1664525*state+1013904223)&0xffffffff;k=state%(j+1);order[k],order[j]=order[j],order[k]\n roles={g:(i,pattern[i%len(pattern)]) for i,g in enumerate(order)}\n return roles,state,order\n\ndef solve(A,b):\n n=len(b);M=[list(row)+[rhs]for row,rhs in zip(A,b)];piv=[];rank=0\n for j in range(n):\n  candidates=[i for i in range(rank,n)if M[i][j]]\n  if not candidates:continue\n  k=max(candidates,key=lambda i:abs(M[i][j]));M[rank],M[k]=M[k],M[rank];v=M[rank][j];M[rank]=[x/v for x in M[rank]]\n  for i in range(n):\n   if i!=rank:\n    v=M[i][j];M[i]=[a-v*b for a,b in zip(M[i],M[rank])]\n  piv.append(j);rank+=1\n x=[F(0)]*n\n for i,j in enumerate(piv):x[j]=M[i][-1]\n null=[]\n for j in range(n):\n  if j not in piv:\n   v=[F(0)]*n;v[j]=F(1)\n   for i,k in enumerate(piv):v[k]=-M[i][j]\n   null.append(v)\n return x,rank,null\n\ndef dot(a,b):return sum((x*y for x,y in zip(a,b)),F(0))\n\ndef fit(rows,method,lam=F(0),minleaf=1,binary=False):\n use=[r for r in rows if r['role']=='train'and r['w']>0 and r['y']is not None and None not in r['x']];p=len(rows[0]['x'])if rows else 0\n if not use:return dict(defined=False,pred=[None]*len(rows),raw=[None]*len(rows),train=[],invariant=[None]*len(rows))\n mass=sum(r['w']for r in use);mu=[sum(r['w']*r['x'][j]for r in use)/mass for j in range(p)];scale=[max(r['x'][j]for r in use)-min(r['x'][j]for r in use)or F(1)for j in range(p)];mean=sum(r['w']*r['y']for r in use)/mass;model={};z=lambda r:[F(1)]+[(x-m)/s for x,m,s in zip(r['x'],mu,scale)]\n if method=='constant':model=dict(mean=mean,parameterCount=1,rank=1,unique=True)\n elif method=='ridge':\n  vectors=[z(r)for r in use];n=p+1;A=[[sum(r['w']*xx[j]*xx[k]for r,xx in zip(use,vectors))/mass+(lam if j==k and j>0 else F(0))for k in range(n)]for j in range(n)];b=[sum(r['w']*r['y']*xx[j]for r,xx in zip(use,vectors))/mass for j in range(n)];theta,rank,null=solve(A,b);objective=sum(r['w']*(dot(xx,theta)-r['y'])**2 for r,xx in zip(use,vectors))/(2*mass)+lam*sum(x*x for x in theta[1:])/2;model=dict(lambdaValue=lam,theta=theta,rank=rank,unique=rank==n,nullspace=null,minimumObjective=objective,parameterCount=n)\n else:\n  best=None;total=sum(r['w']*r['y']for r in use);total2=sum(r['w']*r['y']**2 for r in use);base=total2-total**2/mass\n  for j in range(p):\n   ordered=sorted(enumerate(use),key=lambda v:(v[1]['x'][j],v[0]));leftW=F(0);leftS=F(0)\n   for i,(_idx,r)in enumerate(ordered[:-1]):\n    leftW+=r['w'];leftS+=r['w']*r['y'];rightW=mass-leftW\n    if i+1<minleaf or len(use)-i-1<minleaf or r['x'][j]==ordered[i+1][1]['x'][j]:continue\n    SSE=total2-leftS**2/leftW-(total-leftS)**2/rightW\n    if best is None or SSE<best['weightedSSE']:best=dict(feature=j,threshold=(r['x'][j]+ordered[i+1][1]['x'][j])/2,leftMean=leftS/leftW,rightMean=(total-leftS)/rightW,leftRows=i+1,rightRows=len(use)-i-1,leftWeight=leftW,rightWeight=rightW,weightedSSE=SSE)\n  model=dict(split=False,mean=mean,weightedSSE=base,trainingMSE=base/mass)if best is None or best['weightedSSE']>=base else dict(split=True,**best,trainingMSE=best['weightedSSE']/mass,improvement=(base-best['weightedSSE'])/mass)\n raw=[];invariant=[]\n for r in rows:\n  if None in r['x']:raw.append(None);invariant.append(None);continue\n  if method=='constant':v=mean;iv=True\n  elif method=='ridge':zz=z(r);v=dot(zz,model['theta']);iv=all(dot(zz,nn)==0 for nn in model['nullspace'])\n  else:v=(model['leftMean']if r['x'][model['feature']]<=model['threshold']else model['rightMean'])if model['split']else mean;iv=True\n  raw.append(v);invariant.append(iv)\n pred=[None if x is None else min(F(1),max(F(0),x))if binary else x for x in raw]\n return dict(defined=True,train=[r['id']for r in use],mass=mass,meanX=mu,scales=scale,model=model,pred=pred,raw=raw,invariant=invariant)\n\ndef risk(rows,pred,binary=False,threshold=F(1,2)):\n use=[(r,p)for r,p in zip(rows,pred)if r['w']>0 and r['y']is not None and p is not None and r['role']not in['excluded','unused']];mass=sum((r['w']for r,p in use),F(0));d=dict(rows=len(use),mass=mass)\n if not mass:\n  d.update({k:None for k in ['MSE','MAE','R2']+(['Brier','accuracy','balancedAccuracy','AUROC']if binary else[])});return d\n mean=sum(r['w']*r['y']for r,p in use)/mass;sse=sum(r['w']*(p-r['y'])**2 for r,p in use);sst=sum(r['w']*(r['y']-mean)**2 for r,p in use);d.update(meanY=mean,SSE=sse,SST=sst,MSE=sse/mass,MAE=sum(r['w']*abs(p-r['y'])for r,p in use)/mass,R2=1-sse/sst if sst else None)\n if binary:\n  weights=Counter();num=Counter()\n  for r,p in use:k=('T'if int(p>=threshold)==int(r['y'])else'F')+('P'if p>=threshold else'N');weights[k]+=r['w'];num[k]+=1\n  TP,FP,TN,FN=[weights[k]for k in ['TP','FP','TN','FN']];positive=TP+FN;negative=TN+FP;rate=lambda a,b:a/b if b else None;TPR=rate(TP,positive);TNR=rate(TN,negative)\n  # Pair enumeration is independent of the subject's score-tie-block formula.\n  negatives=[(r,p)for r,p in use if not r['y']];positives=[(r,p)for r,p in use if r['y']];wins=sum((a['w']*b['w']*(F(1)if pa>pb else F(1,2)if pa==pb else F(0))for a,pa in positives for b,pb in negatives),F(0))\n  d.update(Brier=d['MSE'],threshold=threshold,confusionMass={k:weights[k]for k in ['TP','FP','TN','FN']},confusionRows={k:num[k]for k in ['TP','FP','TN','FN']},positiveMass=positive,negativeMass=negative,accuracy=(TP+TN)/mass,positiveRecall=TPR,negativeRecall=TNR,precision=rate(TP,TP+FP),F1=rate(2*TP,2*TP+FP+FN),balancedAccuracy=(TPR+TNR)/2 if TPR is not None and TNR is not None else None,AUROC=rate(wins,positive*negative))\n return d\n\nNATIVE_SHA256={'actual1599-red-wine-original12-fields.csv': '77e9ac73115930d6c43983333a5a57940deefc493affeb17aca478c09c5f6e00', 'actual4898-white-wine-original12-fields.csv': '50d810bbb42b9cc3e87fa4c27a4c0f168e72da09dd812863425ca3873fec28ef', 'actual3613-NLS-original52-fields.csv': '6e1e1895558795435b65f8634252a7589865273a0e69adbd715fcfa04a3c11a1', 'actual3150-churn-original14-fields.csv': '1c0753e434226e769d1015c922121a7d8967df66014e057c4f7543e490f11764'}\n\ndef read_sources(directory,seed):\n def read(name):\n  p=directory/name\n  if hashlib.sha256(p.read_bytes()).hexdigest()!=NATIVE_SHA256[name]:raise ValueError('Native file hash differs: '+name)\n  with p.open(encoding='utf8',newline='')as f:return list(csv.DictReader(f))\n sources={};wine=[]\n for typ,n in [('red',1599),('white',4898)]:\n  table=read(f'actual{n}-{typ}-wine-original12-fields.csv');assert len(table)==n;features=[k for k in table[0]if k not in ['sourceRow','wineType','quality']];assert len(features)==11\n  for r in table:\n   i=int(r['sourceRow']);red='1'if typ=='red'else'0';nativeX=[r[k]for k in features];wine.append(dict(id=f'wine-{typ}-row:{i}',sourceRow=f'{typ}:{i}',originalID=None,group=fingerprint('wine-predictors',[red]+nativeX),cohort=typ,x=list(map(Q,nativeX+[red])),y=Q(r['quality'])))\n sources['country']=wine\n table=read('actual3613-NLS-original52-fields.csv');assert len(table)==3613;sources['person']=[dict(id='nls-row:'+r['sourceRow'],sourceRow=int(r['sourceRow']),originalID=r['id'],group='nls-id:'+r['id'],cohort='schooling-over12'if Q(r['ed76'])>12 else'schooling-at-most12',x=[Q(r['ed76']),Q(r['age76'])],y=Q(r['lwage76']))for r in table]\n table=read('actual3150-churn-original14-fields.csv');assert len(table)==3150;predictors=[k for k in table[0]if k not in ['sourceRow','Churn']];assert len(predictors)==13;sources['company']=[dict(id='customer-row:'+r['sourceRow'],sourceRow=int(r['sourceRow']),originalID=None,group=fingerprint('customer-predictors',[r[k]for k in predictors]),cohort='pay-as-you-go'if r['Tariff Plan']=='1'else'contractual'if r['Tariff Plan']=='2'else'other-native-tariff',x=[Q(r[k])for k in ['Call  Failure','Subscription  Length','Seconds of Use','Age']],y=Q(r['Churn']))for r in table]\n for kind,rows in sources.items():\n  assignments,state,order=split(rows,seed)\n  for r in rows:\n   rank,planned=assignments[r['group']];r.update(w=F(1),splitRank=rank,plannedRole=planned,eligible=r['y']is not None and None not in r['x']);r['role']=planned if r['eligible']else'excluded'\n return sources\n# New ML22 fixed-profile kernels. The public Fraction fitting/source readers are\n# copied by value above this file by the standalone builder; never imported.\ndef fixed_rows(data, prediction_key=None):\n out=[]\n for i,a in enumerate(data):\n  w=Q(a.get('weight','1'))\n  if w is None or w<0:raise ValueError('negative-weight' if w is not None and w<0 else 'missing-weight')\n  out.append(dict(id=a.get('id',str(i)),group=a.get('group',a.get('id',str(i))),cohort=a.get('cohort','all'),role=a.get('role','train'),w=w,x=[Q(v)for v in a.get('x',[])],y=Q(a.get('y'))))\n return out\n\ndef weighted_pair(rows,A,B):\n use=[(r,a,b)for r,a,b in zip(rows,A,B)if r['w']>0 and r['y']is not None and a is not None and b is not None and r['role']not in ['excluded','unused']]\n mass=sum((r['w']for r,a,b in use),F(0));records=[];groups={}\n for r,a,b in use:\n  la=(a-r['y'])**2;lb=(b-r['y'])**2;d=la-lb\n  records.append(dict(id=r['id'],group=r['group'],weight=r['w'],lossA=la,lossB=lb,difference=d))\n  g=groups.setdefault(r['group'],dict(group=r['group'],rows=0,mass=F(0),sum=F(0)));g['rows']+=1;g['mass']+=r['w'];g['sum']+=r['w']*d\n total=sum((g['sum']for g in groups.values()),F(0));mean=total/mass if mass else None;G=len(groups)\n for g in groups.values():g['leaveOut']=(total-g['sum'])/(mass-g['mass'])if mass>g['mass']else None\n leaves=[g['leaveOut']for g in groups.values()if g['leaveOut']is not None]\n proxy=F(G-1,G)*sum((v-sum(leaves,F(0))/G)**2 for v in leaves) if G>1 and len(leaves)==G else None\n return dict(rows=len(use),mass=mass,groupCount=G,meanDifference=mean,minimumLeaveOut=min(leaves)if leaves else None,maximumLeaveOut=max(leaves)if leaves else None,varianceProxy=proxy,groups=list(groups.values()),records=records)\n\ndef run_selection(rows,candidates,criterion,required,binary=False):\n results=[]\n for c,pred in candidates:\n  val=[dict(r,role='excluded')if r['role']!='validation'else r for r in rows]\n  test=[dict(r,role='excluded')if r['role']!='test'else r for r in rows]\n  v=risk(val,pred,binary);t=risk(test,pred,binary);cohort={g:risk([dict(r,role='excluded')if r['role']!='validation'or r['cohort']!=g else r for r in rows],pred,binary)for g in required}\n  values=[cohort[g]['MSE']for g in required]\n  score=v['MSE']if criterion=='mean'else max(values)if values and None not in values else None\n  results.append(dict(id=c,criterion=score,validation=v,test=t,cohorts=cohort))\n eligible=[(i,r['criterion'])for i,r in enumerate(results)if r['criterion']is not None]\n chosen=min(eligible,key=lambda t:(t[1],t[0]))[0]if eligible else None\n return dict(criterion=criterion,selected=results[chosen]['id']if chosen is not None else None,selectedIndex=chosen,candidates=results)\n\ndef fixed_operation(api,a):\n if api=='realdata':\n  kind=a['kind'];rows=read_sources(Path(__file__).parent/'data',a.get('seed',20261104))[kind];binary=kind=='company'\n  defs=[('constant','constant',F(0)),('ridge:1/100','ridge',F(1,100)),('ridge:1/10','ridge',F(1,10)),('ridge:1','ridge',F(1)),('one-split-stump','stump',F(0))]\n  fits=[fit(rows,method,lam,5,binary)for _,method,lam in defs]\n  selection=run_selection(rows,[(d[0],f['pred'])for d,f in zip(defs,fits)],a.get('criterion','mean'),list(dict.fromkeys(r['cohort']for r in rows)),binary)\n  chosen=selection['selectedIndex'];best=fits[chosen];base=fits[0]\n  test=[dict(r,role='excluded')if r['role']!='test'else r for r in rows]\n  paired=weighted_pair(test,best['pred'],base['pred'])\n  records=[dict(id=r['id'],sourceRow=r.get('sourceRow'),originalID=r.get('originalID'),group=r['group'],cohort=r['cohort'],plannedRole=r['plannedRole'],role=r['role'],eligible=r['eligible'],y=r['y'],baselinePrediction=base['pred'][i],selectedPrediction=best['pred'][i],selectedRawPrediction=best['raw'][i],queryInvariant=best['invariant'][i])for i,r in enumerate(rows)]\n  return dict(kind=kind,nativeRows=len(rows),eligibleRows=sum(r['eligible']for r in rows),selection=selection,models=[dict(id=d[0],train=f['train'],mass=f.get('mass'),meanX=f.get('meanX'),scales=f.get('scales'),model=f.get('model'))for d,f in zip(defs,fits)],paired=paired,records=records)\n rows=fixed_rows(a.get('rows',[]));binary=a.get('task')=='binary'\n if api=='split':\n  assignment,state,order=split(rows,a.get('seed',0));records=[dict(id=r['id'],group=r['group'],rank=assignment[r['group']][0],role=assignment[r['group']][1])for r in rows]\n  return dict(state=state,groupOrder=order,records=records,groupCount=len(order))\n if api=='fit':return fit(rows,a.get('method','constant'),Q(a.get('lambda','0')),a.get('minLeafRows',1),binary)\n if api=='evaluate':\n  pred=[Q(r.get('prediction'))for r in a['rows']];threshold=Q(a.get('threshold','1/2'));rr=risk(rows,pred,binary,threshold)\n  records=[]\n  for r,p in zip(rows,pred):\n   valid=r['w']>0 and r['y']is not None and p is not None and r['role']not in ['excluded','unused']\n   records.append(dict(id=r['id'],weight=r['w'],y=r['y'],prediction=p,eligible=valid,loss=(p-r['y'])**2 if valid else None,correct=dict(defined=valid and binary,value=bool(int(p>=threshold)==int(r['y']))if valid and binary else None)))\n  return dict(metrics=rr,records=records)\n if api=='select':return run_selection(rows,[(c['id'],list(map(Q,c['predictions'])))for c in a['candidates']],a.get('criterion','mean'),a.get('requiredCohorts',list(dict.fromkeys(r['cohort']for r in rows))),binary)\n if api=='paired':return weighted_pair(rows,[Q(r.get('predictionA'))for r in a['rows']],[Q(r.get('predictionB'))for r in a['rows']])\n raise ValueError('unknown-api')\n\ndef report_values(api,z):\n summary=[];series=[]\n def add(k,v,u='dimensionless'):summary.append((k,v,u))\n if api=='split':\n  add('groups',z['groupCount'],'groups');add('rows',len(z['records']),'rows');add('finalState',z['state'],'unsigned 32-bit state')\n  series=[('planned role code',[(i,F({'test':0,'validation':1,'train':2}[r['role']]))for i,r in enumerate(z['records'])])]\n elif api=='fit':\n  add('defined',z['defined']);add('trainingRows',len(z['train']),'rows');add('trainingMass',z.get('mass'),'analysis weight mass')\n  model=z.get('model',{});add('modelRank',model.get('rank'),'parameters');add('threshold',model.get('threshold'),'constructed feature units');add('minimumObjective',model.get('minimumObjective'),'constructed squared outcome units')\n  series=[('prediction',list(enumerate(z['pred'])))];\n  if model.get('theta')is not None:\n   for i,v in enumerate(model['theta']):add('theta'+str(i),v,'constructed outcome units per standardized coordinate')\n elif api=='evaluate':\n  for k in ['rows','mass','MSE','MAE','R2','Brier','accuracy','positiveRecall','negativeRecall','precision','F1','balancedAccuracy','AUROC']: \n   if k in z['metrics']:add(k,z['metrics'][k],'rows'if k=='rows'else'analysis weight mass'if k=='mass'else FIXED['unit']if k in ['MSE','Brier']else'constructed outcome units'if k=='MAE'else'dimensionless')\n  series=[('squared loss',[(i,r['loss'])for i,r in enumerate(z['records'])])]\n elif api=='select':\n  add('selectedIndex',z['selectedIndex'],'zero-based candidate index')\n  for i,c in enumerate(z['candidates']):add('criterion'+str(i),c['criterion'],FIXED['unit']);add('testMSE'+str(i),c['test']['MSE'],FIXED['unit'])\n  series=[('validation criterion',[(i,c['criterion'])for i,c in enumerate(z['candidates'])]),('test MSE',[(i,c['test']['MSE'])for i,c in enumerate(z['candidates'])])]\n elif api=='paired':\n  for k in ['rows','mass','groupCount','meanDifference','minimumLeaveOut','maximumLeaveOut','varianceProxy']:add(k,z[k],'rows'if k=='rows'else'groups'if k=='groupCount'else'analysis weight mass'if k=='mass'else FIXED['unit']+' squared'if k=='varianceProxy'else FIXED['unit'])\n  series=[('loss A minus loss B',[(i,r['difference'])for i,r in enumerate(z['records'])])]\n elif api=='realdata':\n  add('nativeRows',z['nativeRows'],'native records');add('eligibleRows',z['eligibleRows'],'complete records');add('selectedIndex',z['selection']['selectedIndex'],'zero-based candidate index')\n  for i,c in enumerate(z['selection']['candidates']):add('validationMSE'+str(i),c['validation']['MSE'],FIXED['unit']);add('testMSE'+str(i),c['test']['MSE'],FIXED['unit'])\n  for k in ['meanDifference','minimumLeaveOut','maximumLeaveOut','varianceProxy']:add(k,z['paired'][k],FIXED['unit']+' squared'if k=='varianceProxy'else FIXED['unit'])\n  best=z['selection']['candidates'][z['selection']['selectedIndex']]['test']\n  for k in ['accuracy','positiveRecall','negativeRecall','precision','balancedAccuracy','AUROC']:\n   if k in best:add(k,best[k])\n  series=[('validation MSE',[(i,c['validation']['MSE'])for i,c in enumerate(z['selection']['candidates'])]),('test MSE',[(i,c['test']['MSE'])for i,c in enumerate(z['selection']['candidates'])])]\n return summary,series\n\n\ndef fixed_svg(points,title):\n good=[p for p in points if p['y'] is not None];xx=[float(p['x'])for p in good];yy=[float(p['y'])for p in good];xmin=min(xx)if xx else 0;xmax=max(xx)if xx else 1;ymin=min([0]+yy);ymax=max([0]+yy)\n if xmin==xmax:xmin-=.5;xmax+=.5\n if ymin==ymax:ymin-=.5;ymax+=.5\n pad=(ymax-ymin)*.08;ymin-=pad;ymax+=pad;X=lambda x:82+(float(x)-xmin)/(xmax-xmin)*608;Y=lambda y:354-(float(y)-ymin)/(ymax-ymin)*290;e=html.escape\n out=['<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"720\" height=\"480\" viewBox=\"0 0 720 480\" role=\"img\" aria-label=\"'+e(title)+'\"><rect width=\"720\" height=\"480\" fill=\"white\"/><g font-family=\"Arial,sans-serif\" font-size=\"13\" fill=\"#18232f\"><text x=\"360\" y=\"25\" text-anchor=\"middle\">'+e(title)+'</text>']\n for j in range(5):\n  y=ymin+(ymax-ymin)*j/4;x=xmin+(xmax-xmin)*j/4;out.append('<line x1=\"82\" y1=\"'+str(Y(y))+'\" x2=\"690\" y2=\"'+str(Y(y))+'\" stroke=\"#e2e8f0\"/><text x=\"73\" y=\"'+str(Y(y)+4)+'\" text-anchor=\"end\">'+format(y,'.3g')+'</text><text x=\"'+str(X(x))+'\" y=\"380\" text-anchor=\"middle\">'+format(x,'.3g')+'</text>')\n series=list(dict.fromkeys(p['series']for p in good))\n for j,s in enumerate(series):\n  pp=[p for p in good if p['series']==s];color=['#0f766e','#c76622','#4f46e5','#b23857'][j%4]\n  for p in pp:out.append('<circle cx=\"'+format(X(p['x']),'.6f')+'\" cy=\"'+format(Y(p['y']),'.6f')+'\" r=\"2.6\" fill=\"'+color+'\"><title>'+e(s+': '+str(p['y']))+'</title></circle>')\n  out.append('<text x=\"'+str(82+(j%2)*310)+'\" y=\"'+str(432+(j//2)*23)+'\" fill=\"'+color+'\">'+e(s)+'</text>')\n out.append('<text x=\"360\" y=\"405\" text-anchor=\"middle\">Declared record / candidate index; units in summary</text></g></svg>');return''.join(out)\n\nFIXED={'api': 'select', 'variant': 'worst-cohort-validation', 'title': 'Selection by worst-cohort validation risk', 'input': {'rows': [{'id': 'G', 'y': '0', 'weight': '9', 'cohort': 'G', 'role': 'validation'}, {'id': 'H', 'y': '0', 'weight': '1', 'cohort': 'H', 'role': 'validation'}, {'id': 'held', 'y': '0', 'cohort': 'G', 'role': 'test'}], 'candidates': [{'id': 'A', 'predictions': ['1', '3', '0']}, {'id': 'B', 'predictions': ['2', '2', '5']}], 'criterion': 'worst-cohort', 'requiredCohorts': ['G', 'H']}, 'unit': 'Constructed squared outcome units', 'titleI18n': {'ko': '최악 코호트 검증 위험의 선택', 'en': 'Selection by worst-cohort validation risk'}}\n\nOUT=Path(sys.argv[1]);OUT.mkdir(parents=True,exist_ok=False)\nresult=fixed_operation(FIXED['api'],FIXED['input']);summary,series=report_values(FIXED['api'],result)\ndef encode(v):\n if isinstance(v,F):return str(v)\n if isinstance(v,dict):return{k:encode(x)for k,x in v.items()}\n if isinstance(v,(list,tuple)):return[encode(x)for x in v]\n return v\n(OUT/'full.json').write_text(json.dumps(dict(arithmetic='Exact rational author implementation; factual rows, declared group split and finite five-candidate comparison',result=encode(result)),ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\nsummaryRows=[dict(metric=m,value=''if v is None else str(int(v))if isinstance(v,bool)else str(v),unit=u,defined=int(v is not None))for m,v,u in summary]\npoints=[dict(series=name,index=i,x=str(x),y=''if y is None else str(y),defined=int(y is not None))for name,pp in series for i,(x,y)in enumerate(pp)]\nfor name,rows in [('summary',summaryRows),('plot-points',points)]:\n with(OUT/(name+'.csv')).open('w',encoding='utf8',newline='')as f:writer=csv.DictWriter(f,fieldnames=list(rows[0]));writer.writeheader();writer.writerows(rows)\n(OUT/'plot.svg').write_text(fixed_svg([dict(p,x=number(p['x']),y=None if not p['defined']else number(p['y']))for p in points],FIXED['title']),encoding='utf8');print(FIXED['api']+'/'+FIXED['variant'])\n",
        "returnCode": 0,
        "stdout": "select/worst-cohort-validation\r\n",
        "stderr": "",
        "diagnosticScope": "Public projection omits private absolute-path/traceback frames; actual exit and warnings/reason retained. Raw complete streams and commands in private execution proof.",
        "resultFolder": "ml22-code/runs/python-select-worst-cohort-validation",
        "kind": null,
        "inputFiles": [
          {
            "file": "ml22-code/select-worst-cohort-validation-input.json",
            "sha256": "c630f7f131ae668678f208ef40659e05fee44c0a1e18f95d29b17da00d172b2b",
            "scope": "Complete fixed literal input; program embeds the same values"
          }
        ],
        "files": [
          {
            "file": "ml22-code/runs/python-select-worst-cohort-validation/full.json",
            "sha256": "a03558fd6c828d5120afde18b877795e32eb2e5b02b7a918d1345b52a5ab366d",
            "bytes": 2279
          },
          {
            "file": "ml22-code/runs/python-select-worst-cohort-validation/plot-points.csv",
            "sha256": "1044c7dc7b5c18833211bdbba8ae15e9b542b5c333150c24a2c75b223e279761",
            "bytes": 123
          },
          {
            "file": "ml22-code/runs/python-select-worst-cohort-validation/plot.svg",
            "sha256": "fea313860224f64639ad36897ef1999aded0500570e89b6664a4bfc15f7236b4",
            "bytes": 1832
          },
          {
            "file": "ml22-code/runs/python-select-worst-cohort-validation/summary.csv",
            "sha256": "8a309fdb5df3a18ee5dac29b1179a3a7f37804d9ee955f1bfce4405934662870",
            "bytes": 270
          }
        ],
        "summaryRows": [
          {
            "metric": "selectedIndex",
            "value": "1.0",
            "unit": "zero-based candidate index",
            "defined": "true",
            "rawValue": "1",
            "arithmetic": "Exact Fraction",
            "exactFraction": "1",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "criterion0",
            "value": "9.0",
            "unit": "Constructed squared outcome units",
            "defined": "true",
            "rawValue": "9",
            "arithmetic": "Exact Fraction",
            "exactFraction": "9",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "testMSE0",
            "value": "0.0",
            "unit": "Constructed squared outcome units",
            "defined": "true",
            "rawValue": "0",
            "arithmetic": "Exact Fraction",
            "exactFraction": "0",
            "mathematicallyPositive": false,
            "mathematicallyNegative": false,
            "exactZero": true,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "criterion1",
            "value": "4.0",
            "unit": "Constructed squared outcome units",
            "defined": "true",
            "rawValue": "4",
            "arithmetic": "Exact Fraction",
            "exactFraction": "4",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "testMSE1",
            "value": "25.0",
            "unit": "Constructed squared outcome units",
            "defined": "true",
            "rawValue": "25",
            "arithmetic": "Exact Fraction",
            "exactFraction": "25",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          }
        ],
        "plotRows": [
          {
            "series": "validation criterion",
            "index": "0",
            "x": "0",
            "y": "9",
            "defined": true,
            "xExact": "0",
            "yExact": "9"
          },
          {
            "series": "validation criterion",
            "index": "1",
            "x": "1",
            "y": "4",
            "defined": true,
            "xExact": "1",
            "yExact": "4"
          },
          {
            "series": "test MSE",
            "index": "0",
            "x": "0",
            "y": "0",
            "defined": true,
            "xExact": "0",
            "yExact": "0"
          },
          {
            "series": "test MSE",
            "index": "1",
            "x": "1",
            "y": "25",
            "defined": true,
            "xExact": "1",
            "yExact": "25"
          }
        ],
        "plotFile": "ml22-code/runs/python-select-worst-cohort-validation/plot.svg",
        "fullResultFile": "ml22-code/runs/python-select-worst-cohort-validation/full.json",
        "arithmeticScope": "Python exact rational versus base-R approximate floating algebra; copied author kernels, not independent oracle.",
        "plotScope": "Original scatter vectors plot every defined declared comparison point, with missing points omitted. Source profiles show candidate risks; all source records remain in the full result and source CSV files.",
        "reproductionScope": "Standalone literal program plus four native CSV files for factual source profiles. No answer/engine/checker imports."
      }
    },
    "r": {
      "mean-validation": {
        "api": "select",
        "variant": "mean-validation",
        "language": "r",
        "title": "Selection by mean validation risk",
        "titleI18n": {
          "ko": "평균 검증 위험의 선택",
          "en": "Selection by mean validation risk"
        },
        "input": {
          "rows": [
            {
              "id": "G",
              "y": "0",
              "weight": "9",
              "cohort": "G",
              "role": "validation"
            },
            {
              "id": "H",
              "y": "0",
              "weight": "1",
              "cohort": "H",
              "role": "validation"
            },
            {
              "id": "held",
              "y": "0",
              "cohort": "G",
              "role": "test"
            }
          ],
          "candidates": [
            {
              "id": "A",
              "predictions": [
                "1",
                "3",
                "0"
              ]
            },
            {
              "id": "B",
              "predictions": [
                "2",
                "2",
                "5"
              ]
            }
          ],
          "criterion": "mean",
          "requiredCohorts": [
            "G",
            "H"
          ]
        },
        "expectedFailure": false,
        "codeFile": "ml22-code/select-mean-validation.R",
        "codeSHA256": "69e7b1046f5ade99e3b064303edddf81456717de30141f2353936ef15b91877e",
        "code": "# ML22 standalone; source/public functions copied by value, no source() dependency.\noptions(stringsAsFactors=FALSE,digits=17,warn=1)\nargs0<-commandArgs(trailingOnly=FALSE);script0<-sub('^--file=','',args0[grepl('^--file=',args0)][1]);source_dir<-file.path(dirname(normalizePath(script0)), 'data');seed<-20261104;leaf_min<-5\nnative_hash <- c(\"actual1599-red-wine-original12-fields.csv\"=\"77e9ac73115930d6c43983333a5a57940deefc493affeb17aca478c09c5f6e00\",\"actual4898-white-wine-original12-fields.csv\"=\"50d810bbb42b9cc3e87fa4c27a4c0f168e72da09dd812863425ca3873fec28ef\",\"actual3613-NLS-original52-fields.csv\"=\"6e1e1895558795435b65f8634252a7589865273a0e69adbd715fcfa04a3c11a1\",\"actual3150-churn-original14-fields.csv\"=\"1c0753e434226e769d1015c922121a7d8967df66014e057c4f7543e490f11764\")\nsha256<-getExportedValue('tools','sha256sum')\nread_native<-function(name){f<-file.path(source_dir,name);if(unname(sha256(f))!=native_hash[[name]])stop(paste('Native hash differs',name));read.csv(f,check.names=FALSE,colClasses='character',na.strings=NULL)}\ngcd_small<-function(a,b){while(b!=0){r<-a%%b;a<-b;b<-r};a}\ncanonical<-function(token){\n if(is.na(token)||token%in%c('','.'))return('null')\n if(!grepl('^[+-]?[0-9]+([.][0-9]*)?$',token))stop('Unsupported native fingerprint token')\n neg<-substr(token,1,1)=='-';s<-sub('^[+-]','',token);parts<-strsplit(s,'.',fixed=TRUE)[[1]];dec<-if(length(parts)==2)nchar(parts[2])else 0;n<-as.numeric(gsub('.','',s,fixed=TRUE));d<-10^dec\n # Every native fingerprint numerator/denominator must remain exactly integral\n # in binary64; reject rather than silently rounding a changed future source.\n if(!is.finite(n)||n>2^53||d>2^53)stop('Native canonical integer range exceeded')\n g<-gcd_small(n,d);n<-n/g;d<-d/g;if(neg)n<--n\n out<-sprintf('%.0f',n);if(d!=1)out<-paste0(out,'/',sprintf('%.0f',d));out\n}\nfp_cache<-new.env(hash=TRUE,parent=emptyenv());hash_file<-tempfile('ml22-hash-')\nfingerprint<-function(tag,values){a<-vapply(values,canonical,'');payload<-paste0('[',paste0('\"',a,'\"',collapse=','),']');key<-paste0(tag,':',payload);if(exists(key,fp_cache,inherits=FALSE))return(get(key,fp_cache,inherits=FALSE));con<-file(hash_file,'wb');writeBin(charToRaw(payload),con);close(con);value<-paste0(tag,':',unname(sha256(hash_file)));assign(key,value,fp_cache);value}\nassign_roles<-function(group){order<-sort(unique(group),method='radix');state<-seed;if(length(order)>1)for(j in seq.int(length(order),2)){state<-(1664525*state+1013904223)%%2^32;k<-state%%j+1;order[c(j,k)]<-order[c(k,j)]};rank<-match(group,order)-1;list(rank=rank,planned=c('test','validation','train','train')[rank%%4+1],state=state)}\n\nfit_model<-function(r,x,method,lambda){\n tr<-which(r$role=='train'&r$eligible);if(!length(tr))stop('No complete positive training rows');y<-r$y[tr];xx<-x[tr,,drop=FALSE];mu<-colMeans(xx);scale<-apply(xx,2,function(v)diff(range(v)));scale[scale==0]<-1;z<-cbind(1,sweep(sweep(x,2,mu,'-'),2,scale,'/'));meanY<-mean(y);model<-list();n<-length(tr)\n if(method=='constant'){model<-list(mean=meanY,parameterCount=1,rank=1,unique=TRUE);raw<-rep(meanY,nrow(r))}\n else if(method=='ridge'){zt<-z[tr,,drop=FALSE];pen<-diag(c(0,rep(lambda,ncol(x))));theta<-drop(solve(crossprod(zt)/n+pen,crossprod(zt,y)/n));raw<-drop(z%*%theta);objective<-mean((y-raw[tr])^2)/2+lambda*sum(theta[-1]^2)/2;model<-list(lambdaValue=lambda,theta=theta,rank=length(theta),unique=TRUE,minimumObjective=objective,parameterCount=length(theta))}\n else{base<-sum((y-meanY)^2);best<-NULL;total<-sum(y);total2<-sum(y*y)\n  for(j in seq_len(ncol(x))){ord<-order(xx[,j],seq_len(n));sx<-xx[ord,j];sy<-y[ord];left<-cumsum(sy)\n   if(n<2*leaf_min)next\n   for(i in seq.int(leaf_min,n-leaf_min)){if(sx[i]==sx[i+1])next;loss<-total2-left[i]^2/i-(total-left[i])^2/(n-i)\n    # Explicit approximate-tie tolerance; exact source JavaScript/Python\n    # contracts are authoritative for general arbitrarily close ties.\n    if(is.null(best)||loss<best$weightedSSE-1e-12*max(1,abs(loss),abs(best$weightedSSE)))best<-list(feature=j-1,threshold=(sx[i]+sx[i+1])/2,leftMean=left[i]/i,rightMean=(total-left[i])/(n-i),leftRows=i,rightRows=n-i,leftWeight=i,rightWeight=n-i,weightedSSE=loss)\n   }\n  }\n  if(is.null(best)||best$weightedSSE>=base-1e-12*max(1,abs(base))){model<-list(split=FALSE,mean=meanY,weightedSSE=base,trainingMSE=base/n);raw<-rep(meanY,nrow(r))}else{model<-c(list(split=TRUE),best,list(trainingMSE=best$weightedSSE/n,improvement=(base-best$weightedSSE)/n));raw<-ifelse(x[,model$feature+1]<=model$threshold,model$leftMean,model$rightMean)}\n }\n pred<-if(r$dataset[1]=='company')pmax(0,pmin(1,raw))else raw;list(meanX=mu,scales=scale,model=model,raw=raw,pred=pred)\n}\n\n# New standalone fixed-profile adapters; native and fit helpers copied by value.\nnum<-function(x){if(is.null(x)||length(x)==0||is.na(x)||x%in%c('','.'))return(NA_real_);if(is.character(x)&&grepl('/',x,fixed=TRUE)){v<-strsplit(x,'/',fixed=TRUE)[[1]];return(as.numeric(v[1])/as.numeric(v[2]))};as.numeric(x)}\nfixedRows<-function(aa){\n rr<-lapply(seq_along(aa),function(i){a<-aa[[i]];w<-num(if(is.null(a$weight))'1'else a$weight);if(is.na(w)||w<0)stop(if(!is.na(w)&&w<0)'negative-weight'else'missing-weight');list(id=if(is.null(a$id))as.character(i-1)else a$id,group=if(is.null(a$group))if(is.null(a$id))as.character(i-1)else a$id else a$group,cohort=if(is.null(a$cohort))'all'else a$cohort,role=if(is.null(a$role))'train'else a$role,w=w,y=num(a$y),x=vapply(a$x,num,0.0))})\n p<-if(length(rr))length(rr[[1]]$x)else 0;xx<-matrix(NA_real_,length(rr),p)\n if(p)for(i in seq_along(rr))xx[i,]<-rr[[i]]$x\n r<-data.frame(id=vapply(rr,`[[`,'','id'),group=vapply(rr,`[[`,'','group'),cohort=vapply(rr,`[[`,'','cohort'),role=vapply(rr,`[[`,'','role'),w=vapply(rr,`[[`,0.0,'w'),y=vapply(rr,`[[`,0.0,'y'));r$eligible<-!is.na(r$y)&rowSums(is.na(xx))==0&r$w>0;list(r=r,x=xx)\n}\nweightedRisk<-function(r,p,binary=FALSE,threshold=.5){\n ii<-which(r$w>0&!is.na(r$y)&!is.na(p)&!r$role%in%c('excluded','unused'));y<-r$y[ii];p<-p[ii];w<-r$w[ii];W<-sum(w);d<-list(rows=length(ii),mass=W,MSE=NA_real_,MAE=NA_real_,R2=NA_real_)\n if(W==0){if(binary)d<-c(d,setNames(rep(list(NA_real_),10),c('Brier','accuracy','positiveRecall','negativeRecall','precision','F1','balancedAccuracy','AUROC','positiveMass','negativeMass')));return(d)}\n mu<-sum(w*y)/W;sse<-sum(w*(p-y)^2);sst<-sum(w*(y-mu)^2);d<-c(d,list(meanY=mu,SSE=sse,SST=sst));d$MSE<-sse/W;d$MAE<-sum(w*abs(p-y))/W;d$R2<-if(sst>0)1-sse/sst else NA_real_\n if(binary){pos<-y==1;yes<-p>=threshold;TP<-sum(w[pos&yes]);FP<-sum(w[!pos&yes]);TN<-sum(w[!pos&!yes]);FN<-sum(w[pos&!yes]);rate<-function(a,b)if(b>0)a/b else NA_real_;tpr<-rate(TP,TP+FN);tnr<-rate(TN,TN+FP);auc<-NA_real_;P<-sum(w[pos]);N<-sum(w[!pos]);if(P>0&&N>0){wins<-sum(vapply(which(pos),function(i)sum(w[i]*w[!pos]*ifelse(p[i]>p[!pos],1,ifelse(p[i]==p[!pos],.5,0))),0.0));auc<-wins/(P*N)};d<-c(d,list(Brier=d$MSE,threshold=threshold,confusionMass=list(TP=TP,FP=FP,TN=TN,FN=FN),confusionRows=list(TP=sum(pos&yes),FP=sum(!pos&yes),TN=sum(!pos&!yes),FN=sum(pos&!yes)),positiveMass=P,negativeMass=N,accuracy=(TP+TN)/W,positiveRecall=tpr,negativeRecall=tnr,precision=rate(TP,TP+FP),F1=rate(2*TP,2*TP+FP+FN),balancedAccuracy=if(is.finite(tpr)&&is.finite(tnr))(tpr+tnr)/2 else NA_real_,AUROC=auc))};d\n}\nweightedPair<-function(r,A,B){\n ii<-which(r$w>0&!is.na(r$y)&!is.na(A)&!is.na(B)&!r$role%in%c('excluded','unused'));rr<-r[ii,,drop=FALSE];la<-(A[ii]-rr$y)^2;lb<-(B[ii]-rr$y)^2;d<-la-lb;W<-sum(rr$w);S<-sum(rr$w*d);mu<-if(W>0)S/W else NA_real_;ids<-unique(rr$group);groups<-lapply(ids,function(g){jj<-which(rr$group==g);wg<-sum(rr$w[jj]);sg<-sum(rr$w[jj]*d[jj]);list(group=g,rows=length(jj),mass=wg,sum=sg,leaveOut=if(W>wg)(S-sg)/(W-wg)else NA_real_)});leaves<-vapply(groups,`[[`,0.0,'leaveOut');G<-length(groups);proxy<-if(G>1&&all(is.finite(leaves)))(G-1)/G*sum((leaves-mean(leaves))^2) else NA_real_\n list(rows=length(ii),mass=W,groupCount=G,meanDifference=mu,minimumLeaveOut=if(any(is.finite(leaves)))min(leaves,na.rm=TRUE)else NA_real_,maximumLeaveOut=if(any(is.finite(leaves)))max(leaves,na.rm=TRUE)else NA_real_,varianceProxy=proxy,groups=groups,records=lapply(seq_along(ii),function(j)list(id=rr$id[j],group=rr$group[j],weight=rr$w[j],lossA=la[j],lossB=lb[j],difference=d[j])))\n}\nrunSelection<-function(r,candidates,criterion,required,binary=FALSE){\n out<-lapply(candidates,function(c){v<-r;t<-r;v$role[v$role!='validation']<-'excluded';t$role[t$role!='test']<-'excluded';val<-weightedRisk(v,c$pred,binary);test<-weightedRisk(t,c$pred,binary);co<-setNames(lapply(required,function(g){z<-v;z$role[z$cohort!=g]<-'excluded';weightedRisk(z,c$pred,binary)}),required);vv<-vapply(co,`[[`,0.0,'MSE');score<-if(criterion=='mean')val$MSE else if(length(vv)&&all(is.finite(vv)))max(vv)else NA_real_;list(id=c$id,criterion=score,validation=val,test=test,cohorts=co)})\n scores<-vapply(out,`[[`,0.0,'criterion');eligible<-which(is.finite(scores));k<-if(length(eligible))eligible[which.min(scores[eligible])]else NA_integer_;list(criterion=criterion,selected=if(!is.na(k))out[[k]]$id else NULL,selectedIndex=if(!is.na(k))k-1 else NA_real_,candidates=out)\n}\nfixedOperation<-function(api,a){\n if(api=='realdata'){\n  kind<-a$kind;r<-rows[[kind]];x<-X[[kind]];asgn<-assign_roles(r$group);r$dataset<-kind;r$splitRank<-asgn$rank;r$plannedRole<-asgn$planned;r$eligible<-!is.na(r$y)&rowSums(is.na(x))==0;r$role<-ifelse(r$eligible,r$plannedRole,'excluded');r$w<-1;binary<-kind=='company';leaf_min<<-5\n  defs<-data.frame(id=c('constant','ridge:1/100','ridge:1/10','ridge:1','one-split-stump'),method=c('constant','ridge','ridge','ridge','stump'),lambda=c(0,.01,.1,1,0));fits<-lapply(seq_len(5),function(i)fit_model(r,x,defs$method[i],defs$lambda[i]));candidates<-lapply(seq_len(5),function(i)list(id=defs$id[i],pred=fits[[i]]$pred));selection<-runSelection(r,candidates,a$criterion,unique(r$cohort),binary);k<-selection$selectedIndex+1;best<-fits[[k]];base<-fits[[1]];test<-r;test$role[test$role!='test']<-'excluded';paired<-weightedPair(test,best$pred,base$pred)\n  records<-lapply(seq_len(nrow(r)),function(i)list(id=r$id[i],sourceRow=r$sourceRow[i],originalID=r$originalID[i],group=r$group[i],cohort=r$cohort[i],plannedRole=r$plannedRole[i],role=r$role[i],eligible=r$eligible[i],y=r$y[i],baselinePrediction=base$pred[i],selectedPrediction=best$pred[i],selectedRawPrediction=best$raw[i],queryInvariant=TRUE))\n  return(list(kind=kind,nativeRows=nrow(r),eligibleRows=sum(r$eligible),selection=selection,models=lapply(seq_len(5),function(i)list(id=defs$id[i],train=as.list(r$id[r$role=='train']),mass=sum(r$role=='train'),meanX=fits[[i]]$meanX,scales=fits[[i]]$scales,model=fits[[i]]$model)),paired=paired,records=records))\n }\n f<-fixedRows(a$rows);r<-f$r;x<-f$x;binary<-identical(a$task,'binary')\n if(api=='split'){seed<<-a$seed;asgn<-assign_roles(r$group);return(list(state=asgn$state,groupCount=length(unique(r$group)),records=lapply(seq_len(nrow(r)),function(i)list(id=r$id[i],group=r$group[i],rank=asgn$rank[i],role=asgn$planned[i]))))}\n if(api=='fit'){\n  r$dataset<-if(binary)'company'else'fixed';leaf_min<<-if(is.null(a$minLeafRows))1 else a$minLeafRows;fit<-fit_model(r,x,a$method,if(is.null(a$lambda))0 else num(a$lambda));bad<-rowSums(is.na(x))>0;fit$raw[bad]<-NA_real_;fit$pred[bad]<-NA_real_;fit$defined<-TRUE;fit$train<-as.list(r$id[r$role=='train'&r$eligible]);fit$mass<-sum(r$w[r$role=='train'&r$eligible]);fit$invariant<-ifelse(bad,NA,TRUE);return(fit)\n }\n if(api=='evaluate'){p<-vapply(a$rows,function(v)num(v$prediction),0.0);threshold<-if(is.null(a$threshold)).5 else num(a$threshold);m<-weightedRisk(r,p,binary,threshold);records<-lapply(seq_len(nrow(r)),function(i){valid<-r$w[i]>0&&!is.na(r$y[i])&&!is.na(p[i])&&!r$role[i]%in%c('excluded','unused');list(id=r$id[i],weight=r$w[i],y=r$y[i],prediction=p[i],eligible=valid,loss=if(valid)(p[i]-r$y[i])^2 else NA_real_,correct=list(defined=valid&&binary,value=if(valid&&binary)(p[i]>=threshold)==r$y[i] else NULL))});return(list(metrics=m,records=records))}\n if(api=='select'){cs<-lapply(a$candidates,function(c)list(id=c$id,pred=vapply(c$predictions,num,0.0)));return(runSelection(r,cs,a$criterion,unlist(a$requiredCohorts),binary))}\n if(api=='paired')return(weightedPair(r,vapply(a$rows,function(v)num(v$predictionA),0.0),vapply(a$rows,function(v)num(v$predictionB),0.0)))\n stop('unknown-api')\n}\nreportValues<-function(api,z){\n ss<-list();pp<-list();add<-function(k,v,u='dimensionless')ss[[length(ss)+1]]<<-list(metric=k,value=if(is.null(v)||length(v)==0||is.na(v))NULL else unname(v),unit=u);series<-function(name,values){for(i in seq_along(values))pp[[length(pp)+1]]<<-list(series=name,index=i-1,x=i-1,y=if(is.null(values[[i]])||is.na(values[[i]]))NULL else unname(values[[i]]))}\n if(api=='split'){add('groups',z$groupCount,'groups');add('rows',length(z$records),'rows');add('finalState',z$state,'unsigned 32-bit state');series('planned role code',lapply(z$records,function(r)switch(r$role,test=0,validation=1,train=2)))}\n if(api=='fit'){add('defined',z$defined);add('trainingRows',length(z$train),'rows');add('trainingMass',z$mass,'analysis weight mass');add('modelRank',z$model$rank,'parameters');add('threshold',z$model$threshold,'constructed feature units');add('minimumObjective',z$model$minimumObjective,'constructed squared outcome units');series('prediction',as.list(z$pred));if(!is.null(z$model$theta))for(i in seq_along(z$model$theta))add(paste0('theta',i-1),z$model$theta[i],'constructed outcome units per standardized coordinate')}\n if(api=='evaluate'){for(k in c('rows','mass','MSE','MAE','R2','Brier','accuracy','positiveRecall','negativeRecall','precision','F1','balancedAccuracy','AUROC'))if(k%in%names(z$metrics))add(k,z$metrics[[k]],if(k=='rows')'rows'else if(k=='mass')'analysis weight mass'else if(k%in%c('MSE','Brier'))FIXED$unit else if(k=='MAE')'constructed outcome units'else'dimensionless');series('squared loss',lapply(z$records,`[[`,'loss'))}\n if(api=='select'){add('selectedIndex',z$selectedIndex,'zero-based candidate index');for(i in seq_along(z$candidates)){c<-z$candidates[[i]];add(paste0('criterion',i-1),c$criterion,FIXED$unit);add(paste0('testMSE',i-1),c$test$MSE,FIXED$unit)};series('validation criterion',lapply(z$candidates,`[[`,'criterion'));series('test MSE',lapply(z$candidates,function(c)c$test$MSE))}\n if(api=='paired'){for(k in c('rows','mass','groupCount','meanDifference','minimumLeaveOut','maximumLeaveOut','varianceProxy'))add(k,z[[k]],if(k=='rows')'rows'else if(k=='groupCount')'groups'else if(k=='mass')'analysis weight mass'else if(k=='varianceProxy')paste(FIXED$unit,'squared')else FIXED$unit);series('loss A minus loss B',lapply(z$records,`[[`,'difference'))}\n if(api=='realdata'){add('nativeRows',z$nativeRows,'native records');add('eligibleRows',z$eligibleRows,'complete records');add('selectedIndex',z$selection$selectedIndex,'zero-based candidate index');for(i in seq_along(z$selection$candidates)){c<-z$selection$candidates[[i]];add(paste0('validationMSE',i-1),c$validation$MSE,FIXED$unit);add(paste0('testMSE',i-1),c$test$MSE,FIXED$unit)};for(k in c('meanDifference','minimumLeaveOut','maximumLeaveOut','varianceProxy'))add(k,z$paired[[k]],if(k=='varianceProxy')paste(FIXED$unit,'squared')else FIXED$unit);best<-z$selection$candidates[[z$selection$selectedIndex+1]]$test;for(k in c('accuracy','positiveRecall','negativeRecall','precision','balancedAccuracy','AUROC'))if(k%in%names(best))add(k,best[[k]]);series('validation MSE',lapply(z$selection$candidates,function(c)c$validation$MSE));series('test MSE',lapply(z$selection$candidates,function(c)c$test$MSE))}\n list(summary=ss,points=pp)\n}\n\nescapeXML<-function(s){s<-gsub('&','&amp;',s,fixed=TRUE);s<-gsub('<','&lt;',s,fixed=TRUE);s<-gsub('>','&gt;',s,fixed=TRUE);gsub('\"','&quot;',s,fixed=TRUE)}\nsvgPlot<-function(pp,title){\n xx<-vapply(pp,function(p)as.numeric(p$x),numeric(1));yy<-vapply(pp,function(p)as.numeric(p$y),numeric(1));xmin<-if(length(xx))min(xx)else 0;xmax<-if(length(xx))max(xx)else 1;ymin<-min(c(0,yy));ymax<-max(c(0,yy));if(xmin==xmax){xmin<-xmin-.5;xmax<-xmax+.5};if(ymin==ymax){ymin<-ymin-.5;ymax<-ymax+.5};pad<-(ymax-ymin)*.08;ymin<-ymin-pad;ymax<-ymax+pad;X<-function(x)82+(as.numeric(x)-xmin)/(xmax-xmin)*608;Y<-function(y)354-(as.numeric(y)-ymin)/(ymax-ymin)*290\n out<-paste0('<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"720\" height=\"480\" viewBox=\"0 0 720 480\" role=\"img\" aria-label=\"',escapeXML(title),'\"><rect width=\"720\" height=\"480\" fill=\"white\"/><g font-family=\"Arial,sans-serif\" font-size=\"13\" fill=\"#18232f\"><text x=\"360\" y=\"25\" text-anchor=\"middle\">',escapeXML(title),'</text>')\n for(j in 0:4){y<-ymin+(ymax-ymin)*j/4;x<-xmin+(xmax-xmin)*j/4;out<-paste0(out,'<line x1=\"82\" y1=\"',Y(y),'\" x2=\"690\" y2=\"',Y(y),'\" stroke=\"#e2e8f0\"/><text x=\"73\" y=\"',Y(y)+4,'\" text-anchor=\"end\">',sprintf('%.3g',y),'</text><text x=\"',X(x),'\" y=\"380\" text-anchor=\"middle\">',sprintf('%.3g',x),'</text>')}\n ss<-unique(vapply(pp,`[[`,character(1),'series'));cols<-c('#0f766e','#c76622','#4f46e5','#b23857')\n for(j in seq_along(ss)){rr<-Filter(function(p)p$series==ss[j],pp);xy<-vapply(rr,function(p)sprintf('%.6f,%.6f',X(p$x),Y(p$y)),character(1));col<-cols[(j-1)%%4+1];for(p in rr)out<-paste0(out,'<circle cx=\"',sprintf('%.6f',X(p$x)),'\" cy=\"',sprintf('%.6f',Y(p$y)),'\" r=\"2.6\" fill=\"',col,'\"><title>',escapeXML(ss[j]),': ',escapeXML(p$y),'</title></circle>');out<-paste0(out,'<text x=\"',82+((j-1)%%2)*310,'\" y=\"',432+floor((j-1)/2)*23,'\" fill=\"',col,'\">',escapeXML(ss[j]),'</text>')}\n paste0(out,'<text x=\"360\" y=\"405\" text-anchor=\"middle\">Declared record / candidate index; fixed example</text></g></svg>')\n}\ntoJSON<-function(x){\n if(is.null(x))return('null');if(is.list(x)){v<-vapply(x,toJSON,character(1));if(!is.null(names(x)))paste0('{',paste(paste0(vapply(names(x),toJSON,character(1)),':',v),collapse=','),'}')else paste0('[',paste(v,collapse=','),']')}\n else if(length(x)!=1){if(!is.numeric(x)&&!is.null(names(x)))toJSON(as.list(x))else paste0('[',paste(vapply(as.list(x),toJSON,character(1)),collapse=','),']')}\n else if(is.na(x))'null'else if(is.logical(x))if(x)'true'else'false'else if(is.numeric(x))if(is.finite(x))sprintf('%.17g',x)else'null'else paste0('\"',gsub('\\n','\\\\n',gsub('\"','\\\\\"',gsub('\\\\','\\\\\\\\',x,fixed=TRUE),fixed=TRUE),fixed=TRUE),'\"')\n}\n\nFIXED<-list(`api`=\"select\",`variant`=\"mean-validation\",`title`=\"Selection by mean validation risk\",`input`=list(`rows`=list(list(`id`=\"G\",`y`=\"0\",`weight`=\"9\",`cohort`=\"G\",`role`=\"validation\"),list(`id`=\"H\",`y`=\"0\",`weight`=\"1\",`cohort`=\"H\",`role`=\"validation\"),list(`id`=\"held\",`y`=\"0\",`cohort`=\"G\",`role`=\"test\")),`candidates`=list(list(`id`=\"A\",`predictions`=list(\"1\",\"3\",\"0\")),list(`id`=\"B\",`predictions`=list(\"2\",\"2\",\"5\"))),`criterion`=\"mean\",`requiredCohorts`=list(\"G\",\"H\")),`unit`=\"Constructed squared outcome units\",`titleI18n`=list(`ko`=\"평균 검증 위험의 선택\",`en`=\"Selection by mean validation risk\"))\n\nargs<-commandArgs(trailingOnly=TRUE);out<-if(length(args))args[1]else stop('NEW output directory required');if(dir.exists(out))stop('Preserve previous output directory');dir.create(out,recursive=TRUE)\nz<-fixedOperation(FIXED$api,FIXED$input);rr<-reportValues(FIXED$api,z)\nwriteLines(toJSON(list(arithmetic='BaseR binary64 author counterpart; native group hashing exact within declared integer range, stump approximate tie tolerance1e-12; not an independent exact oracle',result=z)),file.path(out,'full.json'),useBytes=TRUE)\nsums<-do.call(rbind,lapply(rr$summary,function(row)data.frame(metric=row$metric,value=if(is.null(row$value))''else if(is.logical(row$value))as.character(as.integer(row$value))else format(row$value,digits=17,scientific=NA,trim=TRUE),unit=row$unit,defined=as.integer(!is.null(row$value)),stringsAsFactors=FALSE)))\npoints<-do.call(rbind,lapply(rr$points,function(p)data.frame(series=p$series,index=p$index,x=p$x,y=if(is.null(p$y))NA_real_ else p$y,defined=as.integer(!is.null(p$y)),stringsAsFactors=FALSE)))\nwrite.csv(sums,file.path(out,'summary.csv'),row.names=FALSE,na='');write.csv(points,file.path(out,'plot-points.csv'),row.names=FALSE,na='');writeLines(svgPlot(Filter(function(p)!is.null(p$y),rr$points),FIXED$title),file.path(out,'plot.svg'),useBytes=TRUE);cat(FIXED$api,'/',FIXED$variant,'\\n',sep='')\n",
        "returnCode": 0,
        "stdout": "select/mean-validation\r\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 ",
        "diagnosticScope": "Public projection omits private absolute-path/traceback frames; actual exit and warnings/reason retained. Raw complete streams and commands in private execution proof.",
        "resultFolder": "ml22-code/runs/r-select-mean-validation",
        "kind": null,
        "inputFiles": [
          {
            "file": "ml22-code/select-mean-validation-input.json",
            "sha256": "b8f14eadb523c13369aa74bd5d4704d77ebd93299d131bade9aa0c30d1f74d9c",
            "scope": "Complete fixed literal input; program embeds the same values"
          }
        ],
        "files": [
          {
            "file": "ml22-code/runs/r-select-mean-validation/full.json",
            "sha256": "1b633f13bf33dc7628422457979902779eac6a06d711426defdc4062d3b5a0d2",
            "bytes": 978
          },
          {
            "file": "ml22-code/runs/r-select-mean-validation/plot-points.csv",
            "sha256": "f7bc742350796b1e46bc68457b9d0af8913632949b675e20d1f9e9cd9b0be362",
            "bytes": 143
          },
          {
            "file": "ml22-code/runs/r-select-mean-validation/plot.svg",
            "sha256": "7c5d528acf15372ccb14ee4b295b390ab21575664df58303e69fe18a7b82d5fe",
            "bytes": 1789
          },
          {
            "file": "ml22-code/runs/r-select-mean-validation/summary.csv",
            "sha256": "e1091f8e30abf38367dfd9843bb202bb6395243424d1ef220e5be3b514dddb8c",
            "bytes": 310
          }
        ],
        "summaryRows": [
          {
            "metric": "selectedIndex",
            "value": "0.0",
            "unit": "zero-based candidate index",
            "defined": "true",
            "rawValue": "0",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": false,
            "mathematicallyNegative": false,
            "exactZero": true,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "criterion0",
            "value": "1.8",
            "unit": "Constructed squared outcome units",
            "defined": "true",
            "rawValue": "1.8",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "testMSE0",
            "value": "0.0",
            "unit": "Constructed squared outcome units",
            "defined": "true",
            "rawValue": "0",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": false,
            "mathematicallyNegative": false,
            "exactZero": true,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "criterion1",
            "value": "4.0",
            "unit": "Constructed squared outcome units",
            "defined": "true",
            "rawValue": "4",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "testMSE1",
            "value": "25.0",
            "unit": "Constructed squared outcome units",
            "defined": "true",
            "rawValue": "25",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          }
        ],
        "plotRows": [
          {
            "series": "validation criterion",
            "index": "0",
            "x": "0",
            "y": "1.8",
            "defined": true,
            "xExact": null,
            "yExact": null
          },
          {
            "series": "validation criterion",
            "index": "1",
            "x": "1",
            "y": "4",
            "defined": true,
            "xExact": null,
            "yExact": null
          },
          {
            "series": "test MSE",
            "index": "0",
            "x": "0",
            "y": "0",
            "defined": true,
            "xExact": null,
            "yExact": null
          },
          {
            "series": "test MSE",
            "index": "1",
            "x": "1",
            "y": "25",
            "defined": true,
            "xExact": null,
            "yExact": null
          }
        ],
        "plotFile": "ml22-code/runs/r-select-mean-validation/plot.svg",
        "fullResultFile": "ml22-code/runs/r-select-mean-validation/full.json",
        "arithmeticScope": "Python exact rational versus base-R approximate floating algebra; copied author kernels, not independent oracle.",
        "plotScope": "Original scatter vectors plot every defined declared comparison point, with missing points omitted. Source profiles show candidate risks; all source records remain in the full result and source CSV files.",
        "reproductionScope": "Standalone literal program plus four native CSV files for factual source profiles. No answer/engine/checker imports."
      },
      "worst-cohort-validation": {
        "api": "select",
        "variant": "worst-cohort-validation",
        "language": "r",
        "title": "Selection by worst-cohort validation risk",
        "titleI18n": {
          "ko": "최악 코호트 검증 위험의 선택",
          "en": "Selection by worst-cohort validation risk"
        },
        "input": {
          "rows": [
            {
              "id": "G",
              "y": "0",
              "weight": "9",
              "cohort": "G",
              "role": "validation"
            },
            {
              "id": "H",
              "y": "0",
              "weight": "1",
              "cohort": "H",
              "role": "validation"
            },
            {
              "id": "held",
              "y": "0",
              "cohort": "G",
              "role": "test"
            }
          ],
          "candidates": [
            {
              "id": "A",
              "predictions": [
                "1",
                "3",
                "0"
              ]
            },
            {
              "id": "B",
              "predictions": [
                "2",
                "2",
                "5"
              ]
            }
          ],
          "criterion": "worst-cohort",
          "requiredCohorts": [
            "G",
            "H"
          ]
        },
        "expectedFailure": false,
        "codeFile": "ml22-code/select-worst-cohort-validation.R",
        "codeSHA256": "2a730e91305edd2991a6006a65bc0e7bca6e1b4f5955ba47cf942d5c731e6696",
        "code": "# ML22 standalone; source/public functions copied by value, no source() dependency.\noptions(stringsAsFactors=FALSE,digits=17,warn=1)\nargs0<-commandArgs(trailingOnly=FALSE);script0<-sub('^--file=','',args0[grepl('^--file=',args0)][1]);source_dir<-file.path(dirname(normalizePath(script0)), 'data');seed<-20261104;leaf_min<-5\nnative_hash <- c(\"actual1599-red-wine-original12-fields.csv\"=\"77e9ac73115930d6c43983333a5a57940deefc493affeb17aca478c09c5f6e00\",\"actual4898-white-wine-original12-fields.csv\"=\"50d810bbb42b9cc3e87fa4c27a4c0f168e72da09dd812863425ca3873fec28ef\",\"actual3613-NLS-original52-fields.csv\"=\"6e1e1895558795435b65f8634252a7589865273a0e69adbd715fcfa04a3c11a1\",\"actual3150-churn-original14-fields.csv\"=\"1c0753e434226e769d1015c922121a7d8967df66014e057c4f7543e490f11764\")\nsha256<-getExportedValue('tools','sha256sum')\nread_native<-function(name){f<-file.path(source_dir,name);if(unname(sha256(f))!=native_hash[[name]])stop(paste('Native hash differs',name));read.csv(f,check.names=FALSE,colClasses='character',na.strings=NULL)}\ngcd_small<-function(a,b){while(b!=0){r<-a%%b;a<-b;b<-r};a}\ncanonical<-function(token){\n if(is.na(token)||token%in%c('','.'))return('null')\n if(!grepl('^[+-]?[0-9]+([.][0-9]*)?$',token))stop('Unsupported native fingerprint token')\n neg<-substr(token,1,1)=='-';s<-sub('^[+-]','',token);parts<-strsplit(s,'.',fixed=TRUE)[[1]];dec<-if(length(parts)==2)nchar(parts[2])else 0;n<-as.numeric(gsub('.','',s,fixed=TRUE));d<-10^dec\n # Every native fingerprint numerator/denominator must remain exactly integral\n # in binary64; reject rather than silently rounding a changed future source.\n if(!is.finite(n)||n>2^53||d>2^53)stop('Native canonical integer range exceeded')\n g<-gcd_small(n,d);n<-n/g;d<-d/g;if(neg)n<--n\n out<-sprintf('%.0f',n);if(d!=1)out<-paste0(out,'/',sprintf('%.0f',d));out\n}\nfp_cache<-new.env(hash=TRUE,parent=emptyenv());hash_file<-tempfile('ml22-hash-')\nfingerprint<-function(tag,values){a<-vapply(values,canonical,'');payload<-paste0('[',paste0('\"',a,'\"',collapse=','),']');key<-paste0(tag,':',payload);if(exists(key,fp_cache,inherits=FALSE))return(get(key,fp_cache,inherits=FALSE));con<-file(hash_file,'wb');writeBin(charToRaw(payload),con);close(con);value<-paste0(tag,':',unname(sha256(hash_file)));assign(key,value,fp_cache);value}\nassign_roles<-function(group){order<-sort(unique(group),method='radix');state<-seed;if(length(order)>1)for(j in seq.int(length(order),2)){state<-(1664525*state+1013904223)%%2^32;k<-state%%j+1;order[c(j,k)]<-order[c(k,j)]};rank<-match(group,order)-1;list(rank=rank,planned=c('test','validation','train','train')[rank%%4+1],state=state)}\n\nfit_model<-function(r,x,method,lambda){\n tr<-which(r$role=='train'&r$eligible);if(!length(tr))stop('No complete positive training rows');y<-r$y[tr];xx<-x[tr,,drop=FALSE];mu<-colMeans(xx);scale<-apply(xx,2,function(v)diff(range(v)));scale[scale==0]<-1;z<-cbind(1,sweep(sweep(x,2,mu,'-'),2,scale,'/'));meanY<-mean(y);model<-list();n<-length(tr)\n if(method=='constant'){model<-list(mean=meanY,parameterCount=1,rank=1,unique=TRUE);raw<-rep(meanY,nrow(r))}\n else if(method=='ridge'){zt<-z[tr,,drop=FALSE];pen<-diag(c(0,rep(lambda,ncol(x))));theta<-drop(solve(crossprod(zt)/n+pen,crossprod(zt,y)/n));raw<-drop(z%*%theta);objective<-mean((y-raw[tr])^2)/2+lambda*sum(theta[-1]^2)/2;model<-list(lambdaValue=lambda,theta=theta,rank=length(theta),unique=TRUE,minimumObjective=objective,parameterCount=length(theta))}\n else{base<-sum((y-meanY)^2);best<-NULL;total<-sum(y);total2<-sum(y*y)\n  for(j in seq_len(ncol(x))){ord<-order(xx[,j],seq_len(n));sx<-xx[ord,j];sy<-y[ord];left<-cumsum(sy)\n   if(n<2*leaf_min)next\n   for(i in seq.int(leaf_min,n-leaf_min)){if(sx[i]==sx[i+1])next;loss<-total2-left[i]^2/i-(total-left[i])^2/(n-i)\n    # Explicit approximate-tie tolerance; exact source JavaScript/Python\n    # contracts are authoritative for general arbitrarily close ties.\n    if(is.null(best)||loss<best$weightedSSE-1e-12*max(1,abs(loss),abs(best$weightedSSE)))best<-list(feature=j-1,threshold=(sx[i]+sx[i+1])/2,leftMean=left[i]/i,rightMean=(total-left[i])/(n-i),leftRows=i,rightRows=n-i,leftWeight=i,rightWeight=n-i,weightedSSE=loss)\n   }\n  }\n  if(is.null(best)||best$weightedSSE>=base-1e-12*max(1,abs(base))){model<-list(split=FALSE,mean=meanY,weightedSSE=base,trainingMSE=base/n);raw<-rep(meanY,nrow(r))}else{model<-c(list(split=TRUE),best,list(trainingMSE=best$weightedSSE/n,improvement=(base-best$weightedSSE)/n));raw<-ifelse(x[,model$feature+1]<=model$threshold,model$leftMean,model$rightMean)}\n }\n pred<-if(r$dataset[1]=='company')pmax(0,pmin(1,raw))else raw;list(meanX=mu,scales=scale,model=model,raw=raw,pred=pred)\n}\n\n# New standalone fixed-profile adapters; native and fit helpers copied by value.\nnum<-function(x){if(is.null(x)||length(x)==0||is.na(x)||x%in%c('','.'))return(NA_real_);if(is.character(x)&&grepl('/',x,fixed=TRUE)){v<-strsplit(x,'/',fixed=TRUE)[[1]];return(as.numeric(v[1])/as.numeric(v[2]))};as.numeric(x)}\nfixedRows<-function(aa){\n rr<-lapply(seq_along(aa),function(i){a<-aa[[i]];w<-num(if(is.null(a$weight))'1'else a$weight);if(is.na(w)||w<0)stop(if(!is.na(w)&&w<0)'negative-weight'else'missing-weight');list(id=if(is.null(a$id))as.character(i-1)else a$id,group=if(is.null(a$group))if(is.null(a$id))as.character(i-1)else a$id else a$group,cohort=if(is.null(a$cohort))'all'else a$cohort,role=if(is.null(a$role))'train'else a$role,w=w,y=num(a$y),x=vapply(a$x,num,0.0))})\n p<-if(length(rr))length(rr[[1]]$x)else 0;xx<-matrix(NA_real_,length(rr),p)\n if(p)for(i in seq_along(rr))xx[i,]<-rr[[i]]$x\n r<-data.frame(id=vapply(rr,`[[`,'','id'),group=vapply(rr,`[[`,'','group'),cohort=vapply(rr,`[[`,'','cohort'),role=vapply(rr,`[[`,'','role'),w=vapply(rr,`[[`,0.0,'w'),y=vapply(rr,`[[`,0.0,'y'));r$eligible<-!is.na(r$y)&rowSums(is.na(xx))==0&r$w>0;list(r=r,x=xx)\n}\nweightedRisk<-function(r,p,binary=FALSE,threshold=.5){\n ii<-which(r$w>0&!is.na(r$y)&!is.na(p)&!r$role%in%c('excluded','unused'));y<-r$y[ii];p<-p[ii];w<-r$w[ii];W<-sum(w);d<-list(rows=length(ii),mass=W,MSE=NA_real_,MAE=NA_real_,R2=NA_real_)\n if(W==0){if(binary)d<-c(d,setNames(rep(list(NA_real_),10),c('Brier','accuracy','positiveRecall','negativeRecall','precision','F1','balancedAccuracy','AUROC','positiveMass','negativeMass')));return(d)}\n mu<-sum(w*y)/W;sse<-sum(w*(p-y)^2);sst<-sum(w*(y-mu)^2);d<-c(d,list(meanY=mu,SSE=sse,SST=sst));d$MSE<-sse/W;d$MAE<-sum(w*abs(p-y))/W;d$R2<-if(sst>0)1-sse/sst else NA_real_\n if(binary){pos<-y==1;yes<-p>=threshold;TP<-sum(w[pos&yes]);FP<-sum(w[!pos&yes]);TN<-sum(w[!pos&!yes]);FN<-sum(w[pos&!yes]);rate<-function(a,b)if(b>0)a/b else NA_real_;tpr<-rate(TP,TP+FN);tnr<-rate(TN,TN+FP);auc<-NA_real_;P<-sum(w[pos]);N<-sum(w[!pos]);if(P>0&&N>0){wins<-sum(vapply(which(pos),function(i)sum(w[i]*w[!pos]*ifelse(p[i]>p[!pos],1,ifelse(p[i]==p[!pos],.5,0))),0.0));auc<-wins/(P*N)};d<-c(d,list(Brier=d$MSE,threshold=threshold,confusionMass=list(TP=TP,FP=FP,TN=TN,FN=FN),confusionRows=list(TP=sum(pos&yes),FP=sum(!pos&yes),TN=sum(!pos&!yes),FN=sum(pos&!yes)),positiveMass=P,negativeMass=N,accuracy=(TP+TN)/W,positiveRecall=tpr,negativeRecall=tnr,precision=rate(TP,TP+FP),F1=rate(2*TP,2*TP+FP+FN),balancedAccuracy=if(is.finite(tpr)&&is.finite(tnr))(tpr+tnr)/2 else NA_real_,AUROC=auc))};d\n}\nweightedPair<-function(r,A,B){\n ii<-which(r$w>0&!is.na(r$y)&!is.na(A)&!is.na(B)&!r$role%in%c('excluded','unused'));rr<-r[ii,,drop=FALSE];la<-(A[ii]-rr$y)^2;lb<-(B[ii]-rr$y)^2;d<-la-lb;W<-sum(rr$w);S<-sum(rr$w*d);mu<-if(W>0)S/W else NA_real_;ids<-unique(rr$group);groups<-lapply(ids,function(g){jj<-which(rr$group==g);wg<-sum(rr$w[jj]);sg<-sum(rr$w[jj]*d[jj]);list(group=g,rows=length(jj),mass=wg,sum=sg,leaveOut=if(W>wg)(S-sg)/(W-wg)else NA_real_)});leaves<-vapply(groups,`[[`,0.0,'leaveOut');G<-length(groups);proxy<-if(G>1&&all(is.finite(leaves)))(G-1)/G*sum((leaves-mean(leaves))^2) else NA_real_\n list(rows=length(ii),mass=W,groupCount=G,meanDifference=mu,minimumLeaveOut=if(any(is.finite(leaves)))min(leaves,na.rm=TRUE)else NA_real_,maximumLeaveOut=if(any(is.finite(leaves)))max(leaves,na.rm=TRUE)else NA_real_,varianceProxy=proxy,groups=groups,records=lapply(seq_along(ii),function(j)list(id=rr$id[j],group=rr$group[j],weight=rr$w[j],lossA=la[j],lossB=lb[j],difference=d[j])))\n}\nrunSelection<-function(r,candidates,criterion,required,binary=FALSE){\n out<-lapply(candidates,function(c){v<-r;t<-r;v$role[v$role!='validation']<-'excluded';t$role[t$role!='test']<-'excluded';val<-weightedRisk(v,c$pred,binary);test<-weightedRisk(t,c$pred,binary);co<-setNames(lapply(required,function(g){z<-v;z$role[z$cohort!=g]<-'excluded';weightedRisk(z,c$pred,binary)}),required);vv<-vapply(co,`[[`,0.0,'MSE');score<-if(criterion=='mean')val$MSE else if(length(vv)&&all(is.finite(vv)))max(vv)else NA_real_;list(id=c$id,criterion=score,validation=val,test=test,cohorts=co)})\n scores<-vapply(out,`[[`,0.0,'criterion');eligible<-which(is.finite(scores));k<-if(length(eligible))eligible[which.min(scores[eligible])]else NA_integer_;list(criterion=criterion,selected=if(!is.na(k))out[[k]]$id else NULL,selectedIndex=if(!is.na(k))k-1 else NA_real_,candidates=out)\n}\nfixedOperation<-function(api,a){\n if(api=='realdata'){\n  kind<-a$kind;r<-rows[[kind]];x<-X[[kind]];asgn<-assign_roles(r$group);r$dataset<-kind;r$splitRank<-asgn$rank;r$plannedRole<-asgn$planned;r$eligible<-!is.na(r$y)&rowSums(is.na(x))==0;r$role<-ifelse(r$eligible,r$plannedRole,'excluded');r$w<-1;binary<-kind=='company';leaf_min<<-5\n  defs<-data.frame(id=c('constant','ridge:1/100','ridge:1/10','ridge:1','one-split-stump'),method=c('constant','ridge','ridge','ridge','stump'),lambda=c(0,.01,.1,1,0));fits<-lapply(seq_len(5),function(i)fit_model(r,x,defs$method[i],defs$lambda[i]));candidates<-lapply(seq_len(5),function(i)list(id=defs$id[i],pred=fits[[i]]$pred));selection<-runSelection(r,candidates,a$criterion,unique(r$cohort),binary);k<-selection$selectedIndex+1;best<-fits[[k]];base<-fits[[1]];test<-r;test$role[test$role!='test']<-'excluded';paired<-weightedPair(test,best$pred,base$pred)\n  records<-lapply(seq_len(nrow(r)),function(i)list(id=r$id[i],sourceRow=r$sourceRow[i],originalID=r$originalID[i],group=r$group[i],cohort=r$cohort[i],plannedRole=r$plannedRole[i],role=r$role[i],eligible=r$eligible[i],y=r$y[i],baselinePrediction=base$pred[i],selectedPrediction=best$pred[i],selectedRawPrediction=best$raw[i],queryInvariant=TRUE))\n  return(list(kind=kind,nativeRows=nrow(r),eligibleRows=sum(r$eligible),selection=selection,models=lapply(seq_len(5),function(i)list(id=defs$id[i],train=as.list(r$id[r$role=='train']),mass=sum(r$role=='train'),meanX=fits[[i]]$meanX,scales=fits[[i]]$scales,model=fits[[i]]$model)),paired=paired,records=records))\n }\n f<-fixedRows(a$rows);r<-f$r;x<-f$x;binary<-identical(a$task,'binary')\n if(api=='split'){seed<<-a$seed;asgn<-assign_roles(r$group);return(list(state=asgn$state,groupCount=length(unique(r$group)),records=lapply(seq_len(nrow(r)),function(i)list(id=r$id[i],group=r$group[i],rank=asgn$rank[i],role=asgn$planned[i]))))}\n if(api=='fit'){\n  r$dataset<-if(binary)'company'else'fixed';leaf_min<<-if(is.null(a$minLeafRows))1 else a$minLeafRows;fit<-fit_model(r,x,a$method,if(is.null(a$lambda))0 else num(a$lambda));bad<-rowSums(is.na(x))>0;fit$raw[bad]<-NA_real_;fit$pred[bad]<-NA_real_;fit$defined<-TRUE;fit$train<-as.list(r$id[r$role=='train'&r$eligible]);fit$mass<-sum(r$w[r$role=='train'&r$eligible]);fit$invariant<-ifelse(bad,NA,TRUE);return(fit)\n }\n if(api=='evaluate'){p<-vapply(a$rows,function(v)num(v$prediction),0.0);threshold<-if(is.null(a$threshold)).5 else num(a$threshold);m<-weightedRisk(r,p,binary,threshold);records<-lapply(seq_len(nrow(r)),function(i){valid<-r$w[i]>0&&!is.na(r$y[i])&&!is.na(p[i])&&!r$role[i]%in%c('excluded','unused');list(id=r$id[i],weight=r$w[i],y=r$y[i],prediction=p[i],eligible=valid,loss=if(valid)(p[i]-r$y[i])^2 else NA_real_,correct=list(defined=valid&&binary,value=if(valid&&binary)(p[i]>=threshold)==r$y[i] else NULL))});return(list(metrics=m,records=records))}\n if(api=='select'){cs<-lapply(a$candidates,function(c)list(id=c$id,pred=vapply(c$predictions,num,0.0)));return(runSelection(r,cs,a$criterion,unlist(a$requiredCohorts),binary))}\n if(api=='paired')return(weightedPair(r,vapply(a$rows,function(v)num(v$predictionA),0.0),vapply(a$rows,function(v)num(v$predictionB),0.0)))\n stop('unknown-api')\n}\nreportValues<-function(api,z){\n ss<-list();pp<-list();add<-function(k,v,u='dimensionless')ss[[length(ss)+1]]<<-list(metric=k,value=if(is.null(v)||length(v)==0||is.na(v))NULL else unname(v),unit=u);series<-function(name,values){for(i in seq_along(values))pp[[length(pp)+1]]<<-list(series=name,index=i-1,x=i-1,y=if(is.null(values[[i]])||is.na(values[[i]]))NULL else unname(values[[i]]))}\n if(api=='split'){add('groups',z$groupCount,'groups');add('rows',length(z$records),'rows');add('finalState',z$state,'unsigned 32-bit state');series('planned role code',lapply(z$records,function(r)switch(r$role,test=0,validation=1,train=2)))}\n if(api=='fit'){add('defined',z$defined);add('trainingRows',length(z$train),'rows');add('trainingMass',z$mass,'analysis weight mass');add('modelRank',z$model$rank,'parameters');add('threshold',z$model$threshold,'constructed feature units');add('minimumObjective',z$model$minimumObjective,'constructed squared outcome units');series('prediction',as.list(z$pred));if(!is.null(z$model$theta))for(i in seq_along(z$model$theta))add(paste0('theta',i-1),z$model$theta[i],'constructed outcome units per standardized coordinate')}\n if(api=='evaluate'){for(k in c('rows','mass','MSE','MAE','R2','Brier','accuracy','positiveRecall','negativeRecall','precision','F1','balancedAccuracy','AUROC'))if(k%in%names(z$metrics))add(k,z$metrics[[k]],if(k=='rows')'rows'else if(k=='mass')'analysis weight mass'else if(k%in%c('MSE','Brier'))FIXED$unit else if(k=='MAE')'constructed outcome units'else'dimensionless');series('squared loss',lapply(z$records,`[[`,'loss'))}\n if(api=='select'){add('selectedIndex',z$selectedIndex,'zero-based candidate index');for(i in seq_along(z$candidates)){c<-z$candidates[[i]];add(paste0('criterion',i-1),c$criterion,FIXED$unit);add(paste0('testMSE',i-1),c$test$MSE,FIXED$unit)};series('validation criterion',lapply(z$candidates,`[[`,'criterion'));series('test MSE',lapply(z$candidates,function(c)c$test$MSE))}\n if(api=='paired'){for(k in c('rows','mass','groupCount','meanDifference','minimumLeaveOut','maximumLeaveOut','varianceProxy'))add(k,z[[k]],if(k=='rows')'rows'else if(k=='groupCount')'groups'else if(k=='mass')'analysis weight mass'else if(k=='varianceProxy')paste(FIXED$unit,'squared')else FIXED$unit);series('loss A minus loss B',lapply(z$records,`[[`,'difference'))}\n if(api=='realdata'){add('nativeRows',z$nativeRows,'native records');add('eligibleRows',z$eligibleRows,'complete records');add('selectedIndex',z$selection$selectedIndex,'zero-based candidate index');for(i in seq_along(z$selection$candidates)){c<-z$selection$candidates[[i]];add(paste0('validationMSE',i-1),c$validation$MSE,FIXED$unit);add(paste0('testMSE',i-1),c$test$MSE,FIXED$unit)};for(k in c('meanDifference','minimumLeaveOut','maximumLeaveOut','varianceProxy'))add(k,z$paired[[k]],if(k=='varianceProxy')paste(FIXED$unit,'squared')else FIXED$unit);best<-z$selection$candidates[[z$selection$selectedIndex+1]]$test;for(k in c('accuracy','positiveRecall','negativeRecall','precision','balancedAccuracy','AUROC'))if(k%in%names(best))add(k,best[[k]]);series('validation MSE',lapply(z$selection$candidates,function(c)c$validation$MSE));series('test MSE',lapply(z$selection$candidates,function(c)c$test$MSE))}\n list(summary=ss,points=pp)\n}\n\nescapeXML<-function(s){s<-gsub('&','&amp;',s,fixed=TRUE);s<-gsub('<','&lt;',s,fixed=TRUE);s<-gsub('>','&gt;',s,fixed=TRUE);gsub('\"','&quot;',s,fixed=TRUE)}\nsvgPlot<-function(pp,title){\n xx<-vapply(pp,function(p)as.numeric(p$x),numeric(1));yy<-vapply(pp,function(p)as.numeric(p$y),numeric(1));xmin<-if(length(xx))min(xx)else 0;xmax<-if(length(xx))max(xx)else 1;ymin<-min(c(0,yy));ymax<-max(c(0,yy));if(xmin==xmax){xmin<-xmin-.5;xmax<-xmax+.5};if(ymin==ymax){ymin<-ymin-.5;ymax<-ymax+.5};pad<-(ymax-ymin)*.08;ymin<-ymin-pad;ymax<-ymax+pad;X<-function(x)82+(as.numeric(x)-xmin)/(xmax-xmin)*608;Y<-function(y)354-(as.numeric(y)-ymin)/(ymax-ymin)*290\n out<-paste0('<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"720\" height=\"480\" viewBox=\"0 0 720 480\" role=\"img\" aria-label=\"',escapeXML(title),'\"><rect width=\"720\" height=\"480\" fill=\"white\"/><g font-family=\"Arial,sans-serif\" font-size=\"13\" fill=\"#18232f\"><text x=\"360\" y=\"25\" text-anchor=\"middle\">',escapeXML(title),'</text>')\n for(j in 0:4){y<-ymin+(ymax-ymin)*j/4;x<-xmin+(xmax-xmin)*j/4;out<-paste0(out,'<line x1=\"82\" y1=\"',Y(y),'\" x2=\"690\" y2=\"',Y(y),'\" stroke=\"#e2e8f0\"/><text x=\"73\" y=\"',Y(y)+4,'\" text-anchor=\"end\">',sprintf('%.3g',y),'</text><text x=\"',X(x),'\" y=\"380\" text-anchor=\"middle\">',sprintf('%.3g',x),'</text>')}\n ss<-unique(vapply(pp,`[[`,character(1),'series'));cols<-c('#0f766e','#c76622','#4f46e5','#b23857')\n for(j in seq_along(ss)){rr<-Filter(function(p)p$series==ss[j],pp);xy<-vapply(rr,function(p)sprintf('%.6f,%.6f',X(p$x),Y(p$y)),character(1));col<-cols[(j-1)%%4+1];for(p in rr)out<-paste0(out,'<circle cx=\"',sprintf('%.6f',X(p$x)),'\" cy=\"',sprintf('%.6f',Y(p$y)),'\" r=\"2.6\" fill=\"',col,'\"><title>',escapeXML(ss[j]),': ',escapeXML(p$y),'</title></circle>');out<-paste0(out,'<text x=\"',82+((j-1)%%2)*310,'\" y=\"',432+floor((j-1)/2)*23,'\" fill=\"',col,'\">',escapeXML(ss[j]),'</text>')}\n paste0(out,'<text x=\"360\" y=\"405\" text-anchor=\"middle\">Declared record / candidate index; fixed example</text></g></svg>')\n}\ntoJSON<-function(x){\n if(is.null(x))return('null');if(is.list(x)){v<-vapply(x,toJSON,character(1));if(!is.null(names(x)))paste0('{',paste(paste0(vapply(names(x),toJSON,character(1)),':',v),collapse=','),'}')else paste0('[',paste(v,collapse=','),']')}\n else if(length(x)!=1){if(!is.numeric(x)&&!is.null(names(x)))toJSON(as.list(x))else paste0('[',paste(vapply(as.list(x),toJSON,character(1)),collapse=','),']')}\n else if(is.na(x))'null'else if(is.logical(x))if(x)'true'else'false'else if(is.numeric(x))if(is.finite(x))sprintf('%.17g',x)else'null'else paste0('\"',gsub('\\n','\\\\n',gsub('\"','\\\\\"',gsub('\\\\','\\\\\\\\',x,fixed=TRUE),fixed=TRUE),fixed=TRUE),'\"')\n}\n\nFIXED<-list(`api`=\"select\",`variant`=\"worst-cohort-validation\",`title`=\"Selection by worst-cohort validation risk\",`input`=list(`rows`=list(list(`id`=\"G\",`y`=\"0\",`weight`=\"9\",`cohort`=\"G\",`role`=\"validation\"),list(`id`=\"H\",`y`=\"0\",`weight`=\"1\",`cohort`=\"H\",`role`=\"validation\"),list(`id`=\"held\",`y`=\"0\",`cohort`=\"G\",`role`=\"test\")),`candidates`=list(list(`id`=\"A\",`predictions`=list(\"1\",\"3\",\"0\")),list(`id`=\"B\",`predictions`=list(\"2\",\"2\",\"5\"))),`criterion`=\"worst-cohort\",`requiredCohorts`=list(\"G\",\"H\")),`unit`=\"Constructed squared outcome units\",`titleI18n`=list(`ko`=\"최악 코호트 검증 위험의 선택\",`en`=\"Selection by worst-cohort validation risk\"))\n\nargs<-commandArgs(trailingOnly=TRUE);out<-if(length(args))args[1]else stop('NEW output directory required');if(dir.exists(out))stop('Preserve previous output directory');dir.create(out,recursive=TRUE)\nz<-fixedOperation(FIXED$api,FIXED$input);rr<-reportValues(FIXED$api,z)\nwriteLines(toJSON(list(arithmetic='BaseR binary64 author counterpart; native group hashing exact within declared integer range, stump approximate tie tolerance1e-12; not an independent exact oracle',result=z)),file.path(out,'full.json'),useBytes=TRUE)\nsums<-do.call(rbind,lapply(rr$summary,function(row)data.frame(metric=row$metric,value=if(is.null(row$value))''else if(is.logical(row$value))as.character(as.integer(row$value))else format(row$value,digits=17,scientific=NA,trim=TRUE),unit=row$unit,defined=as.integer(!is.null(row$value)),stringsAsFactors=FALSE)))\npoints<-do.call(rbind,lapply(rr$points,function(p)data.frame(series=p$series,index=p$index,x=p$x,y=if(is.null(p$y))NA_real_ else p$y,defined=as.integer(!is.null(p$y)),stringsAsFactors=FALSE)))\nwrite.csv(sums,file.path(out,'summary.csv'),row.names=FALSE,na='');write.csv(points,file.path(out,'plot-points.csv'),row.names=FALSE,na='');writeLines(svgPlot(Filter(function(p)!is.null(p$y),rr$points),FIXED$title),file.path(out,'plot.svg'),useBytes=TRUE);cat(FIXED$api,'/',FIXED$variant,'\\n',sep='')\n",
        "returnCode": 0,
        "stdout": "select/worst-cohort-validation\r\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 ",
        "diagnosticScope": "Public projection omits private absolute-path/traceback frames; actual exit and warnings/reason retained. Raw complete streams and commands in private execution proof.",
        "resultFolder": "ml22-code/runs/r-select-worst-cohort-validation",
        "kind": null,
        "inputFiles": [
          {
            "file": "ml22-code/select-worst-cohort-validation-input.json",
            "sha256": "c630f7f131ae668678f208ef40659e05fee44c0a1e18f95d29b17da00d172b2b",
            "scope": "Complete fixed literal input; program embeds the same values"
          }
        ],
        "files": [
          {
            "file": "ml22-code/runs/r-select-worst-cohort-validation/full.json",
            "sha256": "cbbe673c1c713035e33e4a8d8bc18029b44e31cb983024cee35e3a355a1de319",
            "bytes": 984
          },
          {
            "file": "ml22-code/runs/r-select-worst-cohort-validation/plot-points.csv",
            "sha256": "151090b755be1851c8b05468fbbc9210c75db052b181d057507de0f1edb52f7f",
            "bytes": 141
          },
          {
            "file": "ml22-code/runs/r-select-worst-cohort-validation/plot.svg",
            "sha256": "775c8fcdb6d08a7c57b89db5ddab05a58cddd7fa264ea51a8a10f71e075e116f",
            "bytes": 1803
          },
          {
            "file": "ml22-code/runs/r-select-worst-cohort-validation/summary.csv",
            "sha256": "e9cdc7a31638d7f69a8741420352d4e46e8d06accc029cbfff18d72b590973c3",
            "bytes": 308
          }
        ],
        "summaryRows": [
          {
            "metric": "selectedIndex",
            "value": "1.0",
            "unit": "zero-based candidate index",
            "defined": "true",
            "rawValue": "1",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "criterion0",
            "value": "9.0",
            "unit": "Constructed squared outcome units",
            "defined": "true",
            "rawValue": "9",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "testMSE0",
            "value": "0.0",
            "unit": "Constructed squared outcome units",
            "defined": "true",
            "rawValue": "0",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": false,
            "mathematicallyNegative": false,
            "exactZero": true,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "criterion1",
            "value": "4.0",
            "unit": "Constructed squared outcome units",
            "defined": "true",
            "rawValue": "4",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "testMSE1",
            "value": "25.0",
            "unit": "Constructed squared outcome units",
            "defined": "true",
            "rawValue": "25",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          }
        ],
        "plotRows": [
          {
            "series": "validation criterion",
            "index": "0",
            "x": "0",
            "y": "9",
            "defined": true,
            "xExact": null,
            "yExact": null
          },
          {
            "series": "validation criterion",
            "index": "1",
            "x": "1",
            "y": "4",
            "defined": true,
            "xExact": null,
            "yExact": null
          },
          {
            "series": "test MSE",
            "index": "0",
            "x": "0",
            "y": "0",
            "defined": true,
            "xExact": null,
            "yExact": null
          },
          {
            "series": "test MSE",
            "index": "1",
            "x": "1",
            "y": "25",
            "defined": true,
            "xExact": null,
            "yExact": null
          }
        ],
        "plotFile": "ml22-code/runs/r-select-worst-cohort-validation/plot.svg",
        "fullResultFile": "ml22-code/runs/r-select-worst-cohort-validation/full.json",
        "arithmeticScope": "Python exact rational versus base-R approximate floating algebra; copied author kernels, not independent oracle.",
        "plotScope": "Original scatter vectors plot every defined declared comparison point, with missing points omitted. Source profiles show candidate risks; all source records remain in the full result and source CSV files.",
        "reproductionScope": "Standalone literal program plus four native CSV files for factual source profiles. No answer/engine/checker imports."
      }
    }
  },
  "paired": {
    "python": {
      "unequal-group-masses": {
        "api": "paired",
        "variant": "unequal-group-masses",
        "language": "python",
        "title": "Loss differences with unequal group masses",
        "titleI18n": {
          "ko": "다른 묶음 질량의 손실 차이",
          "en": "Loss differences with unequal group masses"
        },
        "input": {
          "rows": [
            {
              "id": "G",
              "group": "G",
              "y": "0",
              "predictionA": "1",
              "predictionB": "0",
              "weight": "1"
            },
            {
              "id": "H",
              "group": "H",
              "y": "0",
              "predictionA": "2",
              "predictionB": "1",
              "weight": "3"
            }
          ]
        },
        "expectedFailure": false,
        "codeFile": "ml22-code/paired-unequal-group-masses.py",
        "codeSHA256": "2e6f8a0c2e5952c3ea6218b2b268521493c310c1110625b58d35f9e76b02b466",
        "code": "# ML22 standalone fixed literal. Attribution and arithmetic scope in README.\nimport csv,hashlib,html,json,math,sys,time\nfrom pathlib import Path\nfrom fractions import Fraction as F\nfrom collections import Counter\nsys.set_int_max_str_digits(200000)\nnumber=lambda v:F(str(v))\ndef Q(x):return None if x is None or x in ('','.') else F(str(x))\n\ndef canonical(v):return None if Q(v) is None else str(Q(v))\n\ndef fingerprint(tag,values):return tag+':'+hashlib.sha256(json.dumps([canonical(x)for x in values],separators=(',',':')).encode()).hexdigest()\n\ndef split(rows,seed=20261104,pattern=('test','validation','train','train')):\n order=sorted(set(r['group'] for r in rows));state=seed\n for j in range(len(order)-1,0,-1):state=(1664525*state+1013904223)&0xffffffff;k=state%(j+1);order[k],order[j]=order[j],order[k]\n roles={g:(i,pattern[i%len(pattern)]) for i,g in enumerate(order)}\n return roles,state,order\n\ndef solve(A,b):\n n=len(b);M=[list(row)+[rhs]for row,rhs in zip(A,b)];piv=[];rank=0\n for j in range(n):\n  candidates=[i for i in range(rank,n)if M[i][j]]\n  if not candidates:continue\n  k=max(candidates,key=lambda i:abs(M[i][j]));M[rank],M[k]=M[k],M[rank];v=M[rank][j];M[rank]=[x/v for x in M[rank]]\n  for i in range(n):\n   if i!=rank:\n    v=M[i][j];M[i]=[a-v*b for a,b in zip(M[i],M[rank])]\n  piv.append(j);rank+=1\n x=[F(0)]*n\n for i,j in enumerate(piv):x[j]=M[i][-1]\n null=[]\n for j in range(n):\n  if j not in piv:\n   v=[F(0)]*n;v[j]=F(1)\n   for i,k in enumerate(piv):v[k]=-M[i][j]\n   null.append(v)\n return x,rank,null\n\ndef dot(a,b):return sum((x*y for x,y in zip(a,b)),F(0))\n\ndef fit(rows,method,lam=F(0),minleaf=1,binary=False):\n use=[r for r in rows if r['role']=='train'and r['w']>0 and r['y']is not None and None not in r['x']];p=len(rows[0]['x'])if rows else 0\n if not use:return dict(defined=False,pred=[None]*len(rows),raw=[None]*len(rows),train=[],invariant=[None]*len(rows))\n mass=sum(r['w']for r in use);mu=[sum(r['w']*r['x'][j]for r in use)/mass for j in range(p)];scale=[max(r['x'][j]for r in use)-min(r['x'][j]for r in use)or F(1)for j in range(p)];mean=sum(r['w']*r['y']for r in use)/mass;model={};z=lambda r:[F(1)]+[(x-m)/s for x,m,s in zip(r['x'],mu,scale)]\n if method=='constant':model=dict(mean=mean,parameterCount=1,rank=1,unique=True)\n elif method=='ridge':\n  vectors=[z(r)for r in use];n=p+1;A=[[sum(r['w']*xx[j]*xx[k]for r,xx in zip(use,vectors))/mass+(lam if j==k and j>0 else F(0))for k in range(n)]for j in range(n)];b=[sum(r['w']*r['y']*xx[j]for r,xx in zip(use,vectors))/mass for j in range(n)];theta,rank,null=solve(A,b);objective=sum(r['w']*(dot(xx,theta)-r['y'])**2 for r,xx in zip(use,vectors))/(2*mass)+lam*sum(x*x for x in theta[1:])/2;model=dict(lambdaValue=lam,theta=theta,rank=rank,unique=rank==n,nullspace=null,minimumObjective=objective,parameterCount=n)\n else:\n  best=None;total=sum(r['w']*r['y']for r in use);total2=sum(r['w']*r['y']**2 for r in use);base=total2-total**2/mass\n  for j in range(p):\n   ordered=sorted(enumerate(use),key=lambda v:(v[1]['x'][j],v[0]));leftW=F(0);leftS=F(0)\n   for i,(_idx,r)in enumerate(ordered[:-1]):\n    leftW+=r['w'];leftS+=r['w']*r['y'];rightW=mass-leftW\n    if i+1<minleaf or len(use)-i-1<minleaf or r['x'][j]==ordered[i+1][1]['x'][j]:continue\n    SSE=total2-leftS**2/leftW-(total-leftS)**2/rightW\n    if best is None or SSE<best['weightedSSE']:best=dict(feature=j,threshold=(r['x'][j]+ordered[i+1][1]['x'][j])/2,leftMean=leftS/leftW,rightMean=(total-leftS)/rightW,leftRows=i+1,rightRows=len(use)-i-1,leftWeight=leftW,rightWeight=rightW,weightedSSE=SSE)\n  model=dict(split=False,mean=mean,weightedSSE=base,trainingMSE=base/mass)if best is None or best['weightedSSE']>=base else dict(split=True,**best,trainingMSE=best['weightedSSE']/mass,improvement=(base-best['weightedSSE'])/mass)\n raw=[];invariant=[]\n for r in rows:\n  if None in r['x']:raw.append(None);invariant.append(None);continue\n  if method=='constant':v=mean;iv=True\n  elif method=='ridge':zz=z(r);v=dot(zz,model['theta']);iv=all(dot(zz,nn)==0 for nn in model['nullspace'])\n  else:v=(model['leftMean']if r['x'][model['feature']]<=model['threshold']else model['rightMean'])if model['split']else mean;iv=True\n  raw.append(v);invariant.append(iv)\n pred=[None if x is None else min(F(1),max(F(0),x))if binary else x for x in raw]\n return dict(defined=True,train=[r['id']for r in use],mass=mass,meanX=mu,scales=scale,model=model,pred=pred,raw=raw,invariant=invariant)\n\ndef risk(rows,pred,binary=False,threshold=F(1,2)):\n use=[(r,p)for r,p in zip(rows,pred)if r['w']>0 and r['y']is not None and p is not None and r['role']not in['excluded','unused']];mass=sum((r['w']for r,p in use),F(0));d=dict(rows=len(use),mass=mass)\n if not mass:\n  d.update({k:None for k in ['MSE','MAE','R2']+(['Brier','accuracy','balancedAccuracy','AUROC']if binary else[])});return d\n mean=sum(r['w']*r['y']for r,p in use)/mass;sse=sum(r['w']*(p-r['y'])**2 for r,p in use);sst=sum(r['w']*(r['y']-mean)**2 for r,p in use);d.update(meanY=mean,SSE=sse,SST=sst,MSE=sse/mass,MAE=sum(r['w']*abs(p-r['y'])for r,p in use)/mass,R2=1-sse/sst if sst else None)\n if binary:\n  weights=Counter();num=Counter()\n  for r,p in use:k=('T'if int(p>=threshold)==int(r['y'])else'F')+('P'if p>=threshold else'N');weights[k]+=r['w'];num[k]+=1\n  TP,FP,TN,FN=[weights[k]for k in ['TP','FP','TN','FN']];positive=TP+FN;negative=TN+FP;rate=lambda a,b:a/b if b else None;TPR=rate(TP,positive);TNR=rate(TN,negative)\n  # Pair enumeration is independent of the subject's score-tie-block formula.\n  negatives=[(r,p)for r,p in use if not r['y']];positives=[(r,p)for r,p in use if r['y']];wins=sum((a['w']*b['w']*(F(1)if pa>pb else F(1,2)if pa==pb else F(0))for a,pa in positives for b,pb in negatives),F(0))\n  d.update(Brier=d['MSE'],threshold=threshold,confusionMass={k:weights[k]for k in ['TP','FP','TN','FN']},confusionRows={k:num[k]for k in ['TP','FP','TN','FN']},positiveMass=positive,negativeMass=negative,accuracy=(TP+TN)/mass,positiveRecall=TPR,negativeRecall=TNR,precision=rate(TP,TP+FP),F1=rate(2*TP,2*TP+FP+FN),balancedAccuracy=(TPR+TNR)/2 if TPR is not None and TNR is not None else None,AUROC=rate(wins,positive*negative))\n return d\n\nNATIVE_SHA256={'actual1599-red-wine-original12-fields.csv': '77e9ac73115930d6c43983333a5a57940deefc493affeb17aca478c09c5f6e00', 'actual4898-white-wine-original12-fields.csv': '50d810bbb42b9cc3e87fa4c27a4c0f168e72da09dd812863425ca3873fec28ef', 'actual3613-NLS-original52-fields.csv': '6e1e1895558795435b65f8634252a7589865273a0e69adbd715fcfa04a3c11a1', 'actual3150-churn-original14-fields.csv': '1c0753e434226e769d1015c922121a7d8967df66014e057c4f7543e490f11764'}\n\ndef read_sources(directory,seed):\n def read(name):\n  p=directory/name\n  if hashlib.sha256(p.read_bytes()).hexdigest()!=NATIVE_SHA256[name]:raise ValueError('Native file hash differs: '+name)\n  with p.open(encoding='utf8',newline='')as f:return list(csv.DictReader(f))\n sources={};wine=[]\n for typ,n in [('red',1599),('white',4898)]:\n  table=read(f'actual{n}-{typ}-wine-original12-fields.csv');assert len(table)==n;features=[k for k in table[0]if k not in ['sourceRow','wineType','quality']];assert len(features)==11\n  for r in table:\n   i=int(r['sourceRow']);red='1'if typ=='red'else'0';nativeX=[r[k]for k in features];wine.append(dict(id=f'wine-{typ}-row:{i}',sourceRow=f'{typ}:{i}',originalID=None,group=fingerprint('wine-predictors',[red]+nativeX),cohort=typ,x=list(map(Q,nativeX+[red])),y=Q(r['quality'])))\n sources['country']=wine\n table=read('actual3613-NLS-original52-fields.csv');assert len(table)==3613;sources['person']=[dict(id='nls-row:'+r['sourceRow'],sourceRow=int(r['sourceRow']),originalID=r['id'],group='nls-id:'+r['id'],cohort='schooling-over12'if Q(r['ed76'])>12 else'schooling-at-most12',x=[Q(r['ed76']),Q(r['age76'])],y=Q(r['lwage76']))for r in table]\n table=read('actual3150-churn-original14-fields.csv');assert len(table)==3150;predictors=[k for k in table[0]if k not in ['sourceRow','Churn']];assert len(predictors)==13;sources['company']=[dict(id='customer-row:'+r['sourceRow'],sourceRow=int(r['sourceRow']),originalID=None,group=fingerprint('customer-predictors',[r[k]for k in predictors]),cohort='pay-as-you-go'if r['Tariff Plan']=='1'else'contractual'if r['Tariff Plan']=='2'else'other-native-tariff',x=[Q(r[k])for k in ['Call  Failure','Subscription  Length','Seconds of Use','Age']],y=Q(r['Churn']))for r in table]\n for kind,rows in sources.items():\n  assignments,state,order=split(rows,seed)\n  for r in rows:\n   rank,planned=assignments[r['group']];r.update(w=F(1),splitRank=rank,plannedRole=planned,eligible=r['y']is not None and None not in r['x']);r['role']=planned if r['eligible']else'excluded'\n return sources\n# New ML22 fixed-profile kernels. The public Fraction fitting/source readers are\n# copied by value above this file by the standalone builder; never imported.\ndef fixed_rows(data, prediction_key=None):\n out=[]\n for i,a in enumerate(data):\n  w=Q(a.get('weight','1'))\n  if w is None or w<0:raise ValueError('negative-weight' if w is not None and w<0 else 'missing-weight')\n  out.append(dict(id=a.get('id',str(i)),group=a.get('group',a.get('id',str(i))),cohort=a.get('cohort','all'),role=a.get('role','train'),w=w,x=[Q(v)for v in a.get('x',[])],y=Q(a.get('y'))))\n return out\n\ndef weighted_pair(rows,A,B):\n use=[(r,a,b)for r,a,b in zip(rows,A,B)if r['w']>0 and r['y']is not None and a is not None and b is not None and r['role']not in ['excluded','unused']]\n mass=sum((r['w']for r,a,b in use),F(0));records=[];groups={}\n for r,a,b in use:\n  la=(a-r['y'])**2;lb=(b-r['y'])**2;d=la-lb\n  records.append(dict(id=r['id'],group=r['group'],weight=r['w'],lossA=la,lossB=lb,difference=d))\n  g=groups.setdefault(r['group'],dict(group=r['group'],rows=0,mass=F(0),sum=F(0)));g['rows']+=1;g['mass']+=r['w'];g['sum']+=r['w']*d\n total=sum((g['sum']for g in groups.values()),F(0));mean=total/mass if mass else None;G=len(groups)\n for g in groups.values():g['leaveOut']=(total-g['sum'])/(mass-g['mass'])if mass>g['mass']else None\n leaves=[g['leaveOut']for g in groups.values()if g['leaveOut']is not None]\n proxy=F(G-1,G)*sum((v-sum(leaves,F(0))/G)**2 for v in leaves) if G>1 and len(leaves)==G else None\n return dict(rows=len(use),mass=mass,groupCount=G,meanDifference=mean,minimumLeaveOut=min(leaves)if leaves else None,maximumLeaveOut=max(leaves)if leaves else None,varianceProxy=proxy,groups=list(groups.values()),records=records)\n\ndef run_selection(rows,candidates,criterion,required,binary=False):\n results=[]\n for c,pred in candidates:\n  val=[dict(r,role='excluded')if r['role']!='validation'else r for r in rows]\n  test=[dict(r,role='excluded')if r['role']!='test'else r for r in rows]\n  v=risk(val,pred,binary);t=risk(test,pred,binary);cohort={g:risk([dict(r,role='excluded')if r['role']!='validation'or r['cohort']!=g else r for r in rows],pred,binary)for g in required}\n  values=[cohort[g]['MSE']for g in required]\n  score=v['MSE']if criterion=='mean'else max(values)if values and None not in values else None\n  results.append(dict(id=c,criterion=score,validation=v,test=t,cohorts=cohort))\n eligible=[(i,r['criterion'])for i,r in enumerate(results)if r['criterion']is not None]\n chosen=min(eligible,key=lambda t:(t[1],t[0]))[0]if eligible else None\n return dict(criterion=criterion,selected=results[chosen]['id']if chosen is not None else None,selectedIndex=chosen,candidates=results)\n\ndef fixed_operation(api,a):\n if api=='realdata':\n  kind=a['kind'];rows=read_sources(Path(__file__).parent/'data',a.get('seed',20261104))[kind];binary=kind=='company'\n  defs=[('constant','constant',F(0)),('ridge:1/100','ridge',F(1,100)),('ridge:1/10','ridge',F(1,10)),('ridge:1','ridge',F(1)),('one-split-stump','stump',F(0))]\n  fits=[fit(rows,method,lam,5,binary)for _,method,lam in defs]\n  selection=run_selection(rows,[(d[0],f['pred'])for d,f in zip(defs,fits)],a.get('criterion','mean'),list(dict.fromkeys(r['cohort']for r in rows)),binary)\n  chosen=selection['selectedIndex'];best=fits[chosen];base=fits[0]\n  test=[dict(r,role='excluded')if r['role']!='test'else r for r in rows]\n  paired=weighted_pair(test,best['pred'],base['pred'])\n  records=[dict(id=r['id'],sourceRow=r.get('sourceRow'),originalID=r.get('originalID'),group=r['group'],cohort=r['cohort'],plannedRole=r['plannedRole'],role=r['role'],eligible=r['eligible'],y=r['y'],baselinePrediction=base['pred'][i],selectedPrediction=best['pred'][i],selectedRawPrediction=best['raw'][i],queryInvariant=best['invariant'][i])for i,r in enumerate(rows)]\n  return dict(kind=kind,nativeRows=len(rows),eligibleRows=sum(r['eligible']for r in rows),selection=selection,models=[dict(id=d[0],train=f['train'],mass=f.get('mass'),meanX=f.get('meanX'),scales=f.get('scales'),model=f.get('model'))for d,f in zip(defs,fits)],paired=paired,records=records)\n rows=fixed_rows(a.get('rows',[]));binary=a.get('task')=='binary'\n if api=='split':\n  assignment,state,order=split(rows,a.get('seed',0));records=[dict(id=r['id'],group=r['group'],rank=assignment[r['group']][0],role=assignment[r['group']][1])for r in rows]\n  return dict(state=state,groupOrder=order,records=records,groupCount=len(order))\n if api=='fit':return fit(rows,a.get('method','constant'),Q(a.get('lambda','0')),a.get('minLeafRows',1),binary)\n if api=='evaluate':\n  pred=[Q(r.get('prediction'))for r in a['rows']];threshold=Q(a.get('threshold','1/2'));rr=risk(rows,pred,binary,threshold)\n  records=[]\n  for r,p in zip(rows,pred):\n   valid=r['w']>0 and r['y']is not None and p is not None and r['role']not in ['excluded','unused']\n   records.append(dict(id=r['id'],weight=r['w'],y=r['y'],prediction=p,eligible=valid,loss=(p-r['y'])**2 if valid else None,correct=dict(defined=valid and binary,value=bool(int(p>=threshold)==int(r['y']))if valid and binary else None)))\n  return dict(metrics=rr,records=records)\n if api=='select':return run_selection(rows,[(c['id'],list(map(Q,c['predictions'])))for c in a['candidates']],a.get('criterion','mean'),a.get('requiredCohorts',list(dict.fromkeys(r['cohort']for r in rows))),binary)\n if api=='paired':return weighted_pair(rows,[Q(r.get('predictionA'))for r in a['rows']],[Q(r.get('predictionB'))for r in a['rows']])\n raise ValueError('unknown-api')\n\ndef report_values(api,z):\n summary=[];series=[]\n def add(k,v,u='dimensionless'):summary.append((k,v,u))\n if api=='split':\n  add('groups',z['groupCount'],'groups');add('rows',len(z['records']),'rows');add('finalState',z['state'],'unsigned 32-bit state')\n  series=[('planned role code',[(i,F({'test':0,'validation':1,'train':2}[r['role']]))for i,r in enumerate(z['records'])])]\n elif api=='fit':\n  add('defined',z['defined']);add('trainingRows',len(z['train']),'rows');add('trainingMass',z.get('mass'),'analysis weight mass')\n  model=z.get('model',{});add('modelRank',model.get('rank'),'parameters');add('threshold',model.get('threshold'),'constructed feature units');add('minimumObjective',model.get('minimumObjective'),'constructed squared outcome units')\n  series=[('prediction',list(enumerate(z['pred'])))];\n  if model.get('theta')is not None:\n   for i,v in enumerate(model['theta']):add('theta'+str(i),v,'constructed outcome units per standardized coordinate')\n elif api=='evaluate':\n  for k in ['rows','mass','MSE','MAE','R2','Brier','accuracy','positiveRecall','negativeRecall','precision','F1','balancedAccuracy','AUROC']: \n   if k in z['metrics']:add(k,z['metrics'][k],'rows'if k=='rows'else'analysis weight mass'if k=='mass'else FIXED['unit']if k in ['MSE','Brier']else'constructed outcome units'if k=='MAE'else'dimensionless')\n  series=[('squared loss',[(i,r['loss'])for i,r in enumerate(z['records'])])]\n elif api=='select':\n  add('selectedIndex',z['selectedIndex'],'zero-based candidate index')\n  for i,c in enumerate(z['candidates']):add('criterion'+str(i),c['criterion'],FIXED['unit']);add('testMSE'+str(i),c['test']['MSE'],FIXED['unit'])\n  series=[('validation criterion',[(i,c['criterion'])for i,c in enumerate(z['candidates'])]),('test MSE',[(i,c['test']['MSE'])for i,c in enumerate(z['candidates'])])]\n elif api=='paired':\n  for k in ['rows','mass','groupCount','meanDifference','minimumLeaveOut','maximumLeaveOut','varianceProxy']:add(k,z[k],'rows'if k=='rows'else'groups'if k=='groupCount'else'analysis weight mass'if k=='mass'else FIXED['unit']+' squared'if k=='varianceProxy'else FIXED['unit'])\n  series=[('loss A minus loss B',[(i,r['difference'])for i,r in enumerate(z['records'])])]\n elif api=='realdata':\n  add('nativeRows',z['nativeRows'],'native records');add('eligibleRows',z['eligibleRows'],'complete records');add('selectedIndex',z['selection']['selectedIndex'],'zero-based candidate index')\n  for i,c in enumerate(z['selection']['candidates']):add('validationMSE'+str(i),c['validation']['MSE'],FIXED['unit']);add('testMSE'+str(i),c['test']['MSE'],FIXED['unit'])\n  for k in ['meanDifference','minimumLeaveOut','maximumLeaveOut','varianceProxy']:add(k,z['paired'][k],FIXED['unit']+' squared'if k=='varianceProxy'else FIXED['unit'])\n  best=z['selection']['candidates'][z['selection']['selectedIndex']]['test']\n  for k in ['accuracy','positiveRecall','negativeRecall','precision','balancedAccuracy','AUROC']:\n   if k in best:add(k,best[k])\n  series=[('validation MSE',[(i,c['validation']['MSE'])for i,c in enumerate(z['selection']['candidates'])]),('test MSE',[(i,c['test']['MSE'])for i,c in enumerate(z['selection']['candidates'])])]\n return summary,series\n\n\ndef fixed_svg(points,title):\n good=[p for p in points if p['y'] is not None];xx=[float(p['x'])for p in good];yy=[float(p['y'])for p in good];xmin=min(xx)if xx else 0;xmax=max(xx)if xx else 1;ymin=min([0]+yy);ymax=max([0]+yy)\n if xmin==xmax:xmin-=.5;xmax+=.5\n if ymin==ymax:ymin-=.5;ymax+=.5\n pad=(ymax-ymin)*.08;ymin-=pad;ymax+=pad;X=lambda x:82+(float(x)-xmin)/(xmax-xmin)*608;Y=lambda y:354-(float(y)-ymin)/(ymax-ymin)*290;e=html.escape\n out=['<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"720\" height=\"480\" viewBox=\"0 0 720 480\" role=\"img\" aria-label=\"'+e(title)+'\"><rect width=\"720\" height=\"480\" fill=\"white\"/><g font-family=\"Arial,sans-serif\" font-size=\"13\" fill=\"#18232f\"><text x=\"360\" y=\"25\" text-anchor=\"middle\">'+e(title)+'</text>']\n for j in range(5):\n  y=ymin+(ymax-ymin)*j/4;x=xmin+(xmax-xmin)*j/4;out.append('<line x1=\"82\" y1=\"'+str(Y(y))+'\" x2=\"690\" y2=\"'+str(Y(y))+'\" stroke=\"#e2e8f0\"/><text x=\"73\" y=\"'+str(Y(y)+4)+'\" text-anchor=\"end\">'+format(y,'.3g')+'</text><text x=\"'+str(X(x))+'\" y=\"380\" text-anchor=\"middle\">'+format(x,'.3g')+'</text>')\n series=list(dict.fromkeys(p['series']for p in good))\n for j,s in enumerate(series):\n  pp=[p for p in good if p['series']==s];color=['#0f766e','#c76622','#4f46e5','#b23857'][j%4]\n  for p in pp:out.append('<circle cx=\"'+format(X(p['x']),'.6f')+'\" cy=\"'+format(Y(p['y']),'.6f')+'\" r=\"2.6\" fill=\"'+color+'\"><title>'+e(s+': '+str(p['y']))+'</title></circle>')\n  out.append('<text x=\"'+str(82+(j%2)*310)+'\" y=\"'+str(432+(j//2)*23)+'\" fill=\"'+color+'\">'+e(s)+'</text>')\n out.append('<text x=\"360\" y=\"405\" text-anchor=\"middle\">Declared record / candidate index; units in summary</text></g></svg>');return''.join(out)\n\nFIXED={'api': 'paired', 'variant': 'unequal-group-masses', 'title': 'Loss differences with unequal group masses', 'input': {'rows': [{'id': 'G', 'group': 'G', 'y': '0', 'predictionA': '1', 'predictionB': '0', 'weight': '1'}, {'id': 'H', 'group': 'H', 'y': '0', 'predictionA': '2', 'predictionB': '1', 'weight': '3'}]}, 'unit': 'Constructed squared outcome units', 'titleI18n': {'ko': '다른 묶음 질량의 손실 차이', 'en': 'Loss differences with unequal group masses'}}\n\nOUT=Path(sys.argv[1]);OUT.mkdir(parents=True,exist_ok=False)\nresult=fixed_operation(FIXED['api'],FIXED['input']);summary,series=report_values(FIXED['api'],result)\ndef encode(v):\n if isinstance(v,F):return str(v)\n if isinstance(v,dict):return{k:encode(x)for k,x in v.items()}\n if isinstance(v,(list,tuple)):return[encode(x)for x in v]\n return v\n(OUT/'full.json').write_text(json.dumps(dict(arithmetic='Exact rational author implementation; factual rows, declared group split and finite five-candidate comparison',result=encode(result)),ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\nsummaryRows=[dict(metric=m,value=''if v is None else str(int(v))if isinstance(v,bool)else str(v),unit=u,defined=int(v is not None))for m,v,u in summary]\npoints=[dict(series=name,index=i,x=str(x),y=''if y is None else str(y),defined=int(y is not None))for name,pp in series for i,(x,y)in enumerate(pp)]\nfor name,rows in [('summary',summaryRows),('plot-points',points)]:\n with(OUT/(name+'.csv')).open('w',encoding='utf8',newline='')as f:writer=csv.DictWriter(f,fieldnames=list(rows[0]));writer.writeheader();writer.writerows(rows)\n(OUT/'plot.svg').write_text(fixed_svg([dict(p,x=number(p['x']),y=None if not p['defined']else number(p['y']))for p in points],FIXED['title']),encoding='utf8');print(FIXED['api']+'/'+FIXED['variant'])\n",
        "returnCode": 0,
        "stdout": "paired/unequal-group-masses\r\n",
        "stderr": "",
        "diagnosticScope": "Public projection omits private absolute-path/traceback frames; actual exit and warnings/reason retained. Raw complete streams and commands in private execution proof.",
        "resultFolder": "ml22-code/runs/python-paired-unequal-group-masses",
        "kind": null,
        "inputFiles": [
          {
            "file": "ml22-code/paired-unequal-group-masses-input.json",
            "sha256": "56a4feb23576b62964361703a4fee17246dfe639fe5189e7765125b70bcfa310",
            "scope": "Complete fixed literal input; program embeds the same values"
          }
        ],
        "files": [
          {
            "file": "ml22-code/runs/python-paired-unequal-group-masses/full.json",
            "sha256": "99e98c5e44a0514973cc7bb438b387d6bb4eef426c10ec6a790b3623682a1422",
            "bytes": 953
          },
          {
            "file": "ml22-code/runs/python-paired-unequal-group-masses/plot-points.csv",
            "sha256": "551070d27aa77f8bca9b5979c74662cd4b1a7af66b1897ffd199fed60878a34a",
            "bytes": 84
          },
          {
            "file": "ml22-code/runs/python-paired-unequal-group-masses/plot.svg",
            "sha256": "5fa458633ebef14a17ee22d910269220121919ac48839fb336d9f2e43abd550f",
            "bytes": 1587
          },
          {
            "file": "ml22-code/runs/python-paired-unequal-group-masses/summary.csv",
            "sha256": "f9c87c83ebb3762e3d6a19f1e225f4eb25db7e614e84e658f6e3a94857cbd982",
            "bytes": 323
          }
        ],
        "summaryRows": [
          {
            "metric": "rows",
            "value": "2.0",
            "unit": "rows",
            "defined": "true",
            "rawValue": "2",
            "arithmetic": "Exact Fraction",
            "exactFraction": "2",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "mass",
            "value": "4.0",
            "unit": "analysis weight mass",
            "defined": "true",
            "rawValue": "4",
            "arithmetic": "Exact Fraction",
            "exactFraction": "4",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "groupCount",
            "value": "2.0",
            "unit": "groups",
            "defined": "true",
            "rawValue": "2",
            "arithmetic": "Exact Fraction",
            "exactFraction": "2",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "meanDifference",
            "value": "2.5",
            "unit": "Constructed squared outcome units",
            "defined": "true",
            "rawValue": "5/2",
            "arithmetic": "Exact Fraction",
            "exactFraction": "5/2",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "minimumLeaveOut",
            "value": "1.0",
            "unit": "Constructed squared outcome units",
            "defined": "true",
            "rawValue": "1",
            "arithmetic": "Exact Fraction",
            "exactFraction": "1",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "maximumLeaveOut",
            "value": "3.0",
            "unit": "Constructed squared outcome units",
            "defined": "true",
            "rawValue": "3",
            "arithmetic": "Exact Fraction",
            "exactFraction": "3",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "varianceProxy",
            "value": "1.0",
            "unit": "Constructed squared outcome units squared",
            "defined": "true",
            "rawValue": "1",
            "arithmetic": "Exact Fraction",
            "exactFraction": "1",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          }
        ],
        "plotRows": [
          {
            "series": "loss A minus loss B",
            "index": "0",
            "x": "0",
            "y": "1",
            "defined": true,
            "xExact": "0",
            "yExact": "1"
          },
          {
            "series": "loss A minus loss B",
            "index": "1",
            "x": "1",
            "y": "3",
            "defined": true,
            "xExact": "1",
            "yExact": "3"
          }
        ],
        "plotFile": "ml22-code/runs/python-paired-unequal-group-masses/plot.svg",
        "fullResultFile": "ml22-code/runs/python-paired-unequal-group-masses/full.json",
        "arithmeticScope": "Python exact rational versus base-R approximate floating algebra; copied author kernels, not independent oracle.",
        "plotScope": "Original scatter vectors plot every defined declared comparison point, with missing points omitted. Source profiles show candidate risks; all source records remain in the full result and source CSV files.",
        "reproductionScope": "Standalone literal program plus four native CSV files for factual source profiles. No answer/engine/checker imports."
      },
      "single-group-undefined-deletion": {
        "api": "paired",
        "variant": "single-group-undefined-deletion",
        "language": "python",
        "title": "Undefined deletion diagnostic with one group",
        "titleI18n": {
          "ko": "묶음 하나의 삭제 진단 미정의",
          "en": "Undefined deletion diagnostic with one group"
        },
        "input": {
          "rows": [
            {
              "id": "G",
              "group": "same",
              "y": "0",
              "predictionA": "1",
              "predictionB": "0",
              "weight": "1"
            },
            {
              "id": "H",
              "group": "same",
              "y": "0",
              "predictionA": "2",
              "predictionB": "1",
              "weight": "3"
            }
          ]
        },
        "expectedFailure": false,
        "codeFile": "ml22-code/paired-single-group-undefined-deletion.py",
        "codeSHA256": "1d25e76f925ea04889aad97bdbda9e9424ccfbb44e40ed7398a24f91be1df8c7",
        "code": "# ML22 standalone fixed literal. Attribution and arithmetic scope in README.\nimport csv,hashlib,html,json,math,sys,time\nfrom pathlib import Path\nfrom fractions import Fraction as F\nfrom collections import Counter\nsys.set_int_max_str_digits(200000)\nnumber=lambda v:F(str(v))\ndef Q(x):return None if x is None or x in ('','.') else F(str(x))\n\ndef canonical(v):return None if Q(v) is None else str(Q(v))\n\ndef fingerprint(tag,values):return tag+':'+hashlib.sha256(json.dumps([canonical(x)for x in values],separators=(',',':')).encode()).hexdigest()\n\ndef split(rows,seed=20261104,pattern=('test','validation','train','train')):\n order=sorted(set(r['group'] for r in rows));state=seed\n for j in range(len(order)-1,0,-1):state=(1664525*state+1013904223)&0xffffffff;k=state%(j+1);order[k],order[j]=order[j],order[k]\n roles={g:(i,pattern[i%len(pattern)]) for i,g in enumerate(order)}\n return roles,state,order\n\ndef solve(A,b):\n n=len(b);M=[list(row)+[rhs]for row,rhs in zip(A,b)];piv=[];rank=0\n for j in range(n):\n  candidates=[i for i in range(rank,n)if M[i][j]]\n  if not candidates:continue\n  k=max(candidates,key=lambda i:abs(M[i][j]));M[rank],M[k]=M[k],M[rank];v=M[rank][j];M[rank]=[x/v for x in M[rank]]\n  for i in range(n):\n   if i!=rank:\n    v=M[i][j];M[i]=[a-v*b for a,b in zip(M[i],M[rank])]\n  piv.append(j);rank+=1\n x=[F(0)]*n\n for i,j in enumerate(piv):x[j]=M[i][-1]\n null=[]\n for j in range(n):\n  if j not in piv:\n   v=[F(0)]*n;v[j]=F(1)\n   for i,k in enumerate(piv):v[k]=-M[i][j]\n   null.append(v)\n return x,rank,null\n\ndef dot(a,b):return sum((x*y for x,y in zip(a,b)),F(0))\n\ndef fit(rows,method,lam=F(0),minleaf=1,binary=False):\n use=[r for r in rows if r['role']=='train'and r['w']>0 and r['y']is not None and None not in r['x']];p=len(rows[0]['x'])if rows else 0\n if not use:return dict(defined=False,pred=[None]*len(rows),raw=[None]*len(rows),train=[],invariant=[None]*len(rows))\n mass=sum(r['w']for r in use);mu=[sum(r['w']*r['x'][j]for r in use)/mass for j in range(p)];scale=[max(r['x'][j]for r in use)-min(r['x'][j]for r in use)or F(1)for j in range(p)];mean=sum(r['w']*r['y']for r in use)/mass;model={};z=lambda r:[F(1)]+[(x-m)/s for x,m,s in zip(r['x'],mu,scale)]\n if method=='constant':model=dict(mean=mean,parameterCount=1,rank=1,unique=True)\n elif method=='ridge':\n  vectors=[z(r)for r in use];n=p+1;A=[[sum(r['w']*xx[j]*xx[k]for r,xx in zip(use,vectors))/mass+(lam if j==k and j>0 else F(0))for k in range(n)]for j in range(n)];b=[sum(r['w']*r['y']*xx[j]for r,xx in zip(use,vectors))/mass for j in range(n)];theta,rank,null=solve(A,b);objective=sum(r['w']*(dot(xx,theta)-r['y'])**2 for r,xx in zip(use,vectors))/(2*mass)+lam*sum(x*x for x in theta[1:])/2;model=dict(lambdaValue=lam,theta=theta,rank=rank,unique=rank==n,nullspace=null,minimumObjective=objective,parameterCount=n)\n else:\n  best=None;total=sum(r['w']*r['y']for r in use);total2=sum(r['w']*r['y']**2 for r in use);base=total2-total**2/mass\n  for j in range(p):\n   ordered=sorted(enumerate(use),key=lambda v:(v[1]['x'][j],v[0]));leftW=F(0);leftS=F(0)\n   for i,(_idx,r)in enumerate(ordered[:-1]):\n    leftW+=r['w'];leftS+=r['w']*r['y'];rightW=mass-leftW\n    if i+1<minleaf or len(use)-i-1<minleaf or r['x'][j]==ordered[i+1][1]['x'][j]:continue\n    SSE=total2-leftS**2/leftW-(total-leftS)**2/rightW\n    if best is None or SSE<best['weightedSSE']:best=dict(feature=j,threshold=(r['x'][j]+ordered[i+1][1]['x'][j])/2,leftMean=leftS/leftW,rightMean=(total-leftS)/rightW,leftRows=i+1,rightRows=len(use)-i-1,leftWeight=leftW,rightWeight=rightW,weightedSSE=SSE)\n  model=dict(split=False,mean=mean,weightedSSE=base,trainingMSE=base/mass)if best is None or best['weightedSSE']>=base else dict(split=True,**best,trainingMSE=best['weightedSSE']/mass,improvement=(base-best['weightedSSE'])/mass)\n raw=[];invariant=[]\n for r in rows:\n  if None in r['x']:raw.append(None);invariant.append(None);continue\n  if method=='constant':v=mean;iv=True\n  elif method=='ridge':zz=z(r);v=dot(zz,model['theta']);iv=all(dot(zz,nn)==0 for nn in model['nullspace'])\n  else:v=(model['leftMean']if r['x'][model['feature']]<=model['threshold']else model['rightMean'])if model['split']else mean;iv=True\n  raw.append(v);invariant.append(iv)\n pred=[None if x is None else min(F(1),max(F(0),x))if binary else x for x in raw]\n return dict(defined=True,train=[r['id']for r in use],mass=mass,meanX=mu,scales=scale,model=model,pred=pred,raw=raw,invariant=invariant)\n\ndef risk(rows,pred,binary=False,threshold=F(1,2)):\n use=[(r,p)for r,p in zip(rows,pred)if r['w']>0 and r['y']is not None and p is not None and r['role']not in['excluded','unused']];mass=sum((r['w']for r,p in use),F(0));d=dict(rows=len(use),mass=mass)\n if not mass:\n  d.update({k:None for k in ['MSE','MAE','R2']+(['Brier','accuracy','balancedAccuracy','AUROC']if binary else[])});return d\n mean=sum(r['w']*r['y']for r,p in use)/mass;sse=sum(r['w']*(p-r['y'])**2 for r,p in use);sst=sum(r['w']*(r['y']-mean)**2 for r,p in use);d.update(meanY=mean,SSE=sse,SST=sst,MSE=sse/mass,MAE=sum(r['w']*abs(p-r['y'])for r,p in use)/mass,R2=1-sse/sst if sst else None)\n if binary:\n  weights=Counter();num=Counter()\n  for r,p in use:k=('T'if int(p>=threshold)==int(r['y'])else'F')+('P'if p>=threshold else'N');weights[k]+=r['w'];num[k]+=1\n  TP,FP,TN,FN=[weights[k]for k in ['TP','FP','TN','FN']];positive=TP+FN;negative=TN+FP;rate=lambda a,b:a/b if b else None;TPR=rate(TP,positive);TNR=rate(TN,negative)\n  # Pair enumeration is independent of the subject's score-tie-block formula.\n  negatives=[(r,p)for r,p in use if not r['y']];positives=[(r,p)for r,p in use if r['y']];wins=sum((a['w']*b['w']*(F(1)if pa>pb else F(1,2)if pa==pb else F(0))for a,pa in positives for b,pb in negatives),F(0))\n  d.update(Brier=d['MSE'],threshold=threshold,confusionMass={k:weights[k]for k in ['TP','FP','TN','FN']},confusionRows={k:num[k]for k in ['TP','FP','TN','FN']},positiveMass=positive,negativeMass=negative,accuracy=(TP+TN)/mass,positiveRecall=TPR,negativeRecall=TNR,precision=rate(TP,TP+FP),F1=rate(2*TP,2*TP+FP+FN),balancedAccuracy=(TPR+TNR)/2 if TPR is not None and TNR is not None else None,AUROC=rate(wins,positive*negative))\n return d\n\nNATIVE_SHA256={'actual1599-red-wine-original12-fields.csv': '77e9ac73115930d6c43983333a5a57940deefc493affeb17aca478c09c5f6e00', 'actual4898-white-wine-original12-fields.csv': '50d810bbb42b9cc3e87fa4c27a4c0f168e72da09dd812863425ca3873fec28ef', 'actual3613-NLS-original52-fields.csv': '6e1e1895558795435b65f8634252a7589865273a0e69adbd715fcfa04a3c11a1', 'actual3150-churn-original14-fields.csv': '1c0753e434226e769d1015c922121a7d8967df66014e057c4f7543e490f11764'}\n\ndef read_sources(directory,seed):\n def read(name):\n  p=directory/name\n  if hashlib.sha256(p.read_bytes()).hexdigest()!=NATIVE_SHA256[name]:raise ValueError('Native file hash differs: '+name)\n  with p.open(encoding='utf8',newline='')as f:return list(csv.DictReader(f))\n sources={};wine=[]\n for typ,n in [('red',1599),('white',4898)]:\n  table=read(f'actual{n}-{typ}-wine-original12-fields.csv');assert len(table)==n;features=[k for k in table[0]if k not in ['sourceRow','wineType','quality']];assert len(features)==11\n  for r in table:\n   i=int(r['sourceRow']);red='1'if typ=='red'else'0';nativeX=[r[k]for k in features];wine.append(dict(id=f'wine-{typ}-row:{i}',sourceRow=f'{typ}:{i}',originalID=None,group=fingerprint('wine-predictors',[red]+nativeX),cohort=typ,x=list(map(Q,nativeX+[red])),y=Q(r['quality'])))\n sources['country']=wine\n table=read('actual3613-NLS-original52-fields.csv');assert len(table)==3613;sources['person']=[dict(id='nls-row:'+r['sourceRow'],sourceRow=int(r['sourceRow']),originalID=r['id'],group='nls-id:'+r['id'],cohort='schooling-over12'if Q(r['ed76'])>12 else'schooling-at-most12',x=[Q(r['ed76']),Q(r['age76'])],y=Q(r['lwage76']))for r in table]\n table=read('actual3150-churn-original14-fields.csv');assert len(table)==3150;predictors=[k for k in table[0]if k not in ['sourceRow','Churn']];assert len(predictors)==13;sources['company']=[dict(id='customer-row:'+r['sourceRow'],sourceRow=int(r['sourceRow']),originalID=None,group=fingerprint('customer-predictors',[r[k]for k in predictors]),cohort='pay-as-you-go'if r['Tariff Plan']=='1'else'contractual'if r['Tariff Plan']=='2'else'other-native-tariff',x=[Q(r[k])for k in ['Call  Failure','Subscription  Length','Seconds of Use','Age']],y=Q(r['Churn']))for r in table]\n for kind,rows in sources.items():\n  assignments,state,order=split(rows,seed)\n  for r in rows:\n   rank,planned=assignments[r['group']];r.update(w=F(1),splitRank=rank,plannedRole=planned,eligible=r['y']is not None and None not in r['x']);r['role']=planned if r['eligible']else'excluded'\n return sources\n# New ML22 fixed-profile kernels. The public Fraction fitting/source readers are\n# copied by value above this file by the standalone builder; never imported.\ndef fixed_rows(data, prediction_key=None):\n out=[]\n for i,a in enumerate(data):\n  w=Q(a.get('weight','1'))\n  if w is None or w<0:raise ValueError('negative-weight' if w is not None and w<0 else 'missing-weight')\n  out.append(dict(id=a.get('id',str(i)),group=a.get('group',a.get('id',str(i))),cohort=a.get('cohort','all'),role=a.get('role','train'),w=w,x=[Q(v)for v in a.get('x',[])],y=Q(a.get('y'))))\n return out\n\ndef weighted_pair(rows,A,B):\n use=[(r,a,b)for r,a,b in zip(rows,A,B)if r['w']>0 and r['y']is not None and a is not None and b is not None and r['role']not in ['excluded','unused']]\n mass=sum((r['w']for r,a,b in use),F(0));records=[];groups={}\n for r,a,b in use:\n  la=(a-r['y'])**2;lb=(b-r['y'])**2;d=la-lb\n  records.append(dict(id=r['id'],group=r['group'],weight=r['w'],lossA=la,lossB=lb,difference=d))\n  g=groups.setdefault(r['group'],dict(group=r['group'],rows=0,mass=F(0),sum=F(0)));g['rows']+=1;g['mass']+=r['w'];g['sum']+=r['w']*d\n total=sum((g['sum']for g in groups.values()),F(0));mean=total/mass if mass else None;G=len(groups)\n for g in groups.values():g['leaveOut']=(total-g['sum'])/(mass-g['mass'])if mass>g['mass']else None\n leaves=[g['leaveOut']for g in groups.values()if g['leaveOut']is not None]\n proxy=F(G-1,G)*sum((v-sum(leaves,F(0))/G)**2 for v in leaves) if G>1 and len(leaves)==G else None\n return dict(rows=len(use),mass=mass,groupCount=G,meanDifference=mean,minimumLeaveOut=min(leaves)if leaves else None,maximumLeaveOut=max(leaves)if leaves else None,varianceProxy=proxy,groups=list(groups.values()),records=records)\n\ndef run_selection(rows,candidates,criterion,required,binary=False):\n results=[]\n for c,pred in candidates:\n  val=[dict(r,role='excluded')if r['role']!='validation'else r for r in rows]\n  test=[dict(r,role='excluded')if r['role']!='test'else r for r in rows]\n  v=risk(val,pred,binary);t=risk(test,pred,binary);cohort={g:risk([dict(r,role='excluded')if r['role']!='validation'or r['cohort']!=g else r for r in rows],pred,binary)for g in required}\n  values=[cohort[g]['MSE']for g in required]\n  score=v['MSE']if criterion=='mean'else max(values)if values and None not in values else None\n  results.append(dict(id=c,criterion=score,validation=v,test=t,cohorts=cohort))\n eligible=[(i,r['criterion'])for i,r in enumerate(results)if r['criterion']is not None]\n chosen=min(eligible,key=lambda t:(t[1],t[0]))[0]if eligible else None\n return dict(criterion=criterion,selected=results[chosen]['id']if chosen is not None else None,selectedIndex=chosen,candidates=results)\n\ndef fixed_operation(api,a):\n if api=='realdata':\n  kind=a['kind'];rows=read_sources(Path(__file__).parent/'data',a.get('seed',20261104))[kind];binary=kind=='company'\n  defs=[('constant','constant',F(0)),('ridge:1/100','ridge',F(1,100)),('ridge:1/10','ridge',F(1,10)),('ridge:1','ridge',F(1)),('one-split-stump','stump',F(0))]\n  fits=[fit(rows,method,lam,5,binary)for _,method,lam in defs]\n  selection=run_selection(rows,[(d[0],f['pred'])for d,f in zip(defs,fits)],a.get('criterion','mean'),list(dict.fromkeys(r['cohort']for r in rows)),binary)\n  chosen=selection['selectedIndex'];best=fits[chosen];base=fits[0]\n  test=[dict(r,role='excluded')if r['role']!='test'else r for r in rows]\n  paired=weighted_pair(test,best['pred'],base['pred'])\n  records=[dict(id=r['id'],sourceRow=r.get('sourceRow'),originalID=r.get('originalID'),group=r['group'],cohort=r['cohort'],plannedRole=r['plannedRole'],role=r['role'],eligible=r['eligible'],y=r['y'],baselinePrediction=base['pred'][i],selectedPrediction=best['pred'][i],selectedRawPrediction=best['raw'][i],queryInvariant=best['invariant'][i])for i,r in enumerate(rows)]\n  return dict(kind=kind,nativeRows=len(rows),eligibleRows=sum(r['eligible']for r in rows),selection=selection,models=[dict(id=d[0],train=f['train'],mass=f.get('mass'),meanX=f.get('meanX'),scales=f.get('scales'),model=f.get('model'))for d,f in zip(defs,fits)],paired=paired,records=records)\n rows=fixed_rows(a.get('rows',[]));binary=a.get('task')=='binary'\n if api=='split':\n  assignment,state,order=split(rows,a.get('seed',0));records=[dict(id=r['id'],group=r['group'],rank=assignment[r['group']][0],role=assignment[r['group']][1])for r in rows]\n  return dict(state=state,groupOrder=order,records=records,groupCount=len(order))\n if api=='fit':return fit(rows,a.get('method','constant'),Q(a.get('lambda','0')),a.get('minLeafRows',1),binary)\n if api=='evaluate':\n  pred=[Q(r.get('prediction'))for r in a['rows']];threshold=Q(a.get('threshold','1/2'));rr=risk(rows,pred,binary,threshold)\n  records=[]\n  for r,p in zip(rows,pred):\n   valid=r['w']>0 and r['y']is not None and p is not None and r['role']not in ['excluded','unused']\n   records.append(dict(id=r['id'],weight=r['w'],y=r['y'],prediction=p,eligible=valid,loss=(p-r['y'])**2 if valid else None,correct=dict(defined=valid and binary,value=bool(int(p>=threshold)==int(r['y']))if valid and binary else None)))\n  return dict(metrics=rr,records=records)\n if api=='select':return run_selection(rows,[(c['id'],list(map(Q,c['predictions'])))for c in a['candidates']],a.get('criterion','mean'),a.get('requiredCohorts',list(dict.fromkeys(r['cohort']for r in rows))),binary)\n if api=='paired':return weighted_pair(rows,[Q(r.get('predictionA'))for r in a['rows']],[Q(r.get('predictionB'))for r in a['rows']])\n raise ValueError('unknown-api')\n\ndef report_values(api,z):\n summary=[];series=[]\n def add(k,v,u='dimensionless'):summary.append((k,v,u))\n if api=='split':\n  add('groups',z['groupCount'],'groups');add('rows',len(z['records']),'rows');add('finalState',z['state'],'unsigned 32-bit state')\n  series=[('planned role code',[(i,F({'test':0,'validation':1,'train':2}[r['role']]))for i,r in enumerate(z['records'])])]\n elif api=='fit':\n  add('defined',z['defined']);add('trainingRows',len(z['train']),'rows');add('trainingMass',z.get('mass'),'analysis weight mass')\n  model=z.get('model',{});add('modelRank',model.get('rank'),'parameters');add('threshold',model.get('threshold'),'constructed feature units');add('minimumObjective',model.get('minimumObjective'),'constructed squared outcome units')\n  series=[('prediction',list(enumerate(z['pred'])))];\n  if model.get('theta')is not None:\n   for i,v in enumerate(model['theta']):add('theta'+str(i),v,'constructed outcome units per standardized coordinate')\n elif api=='evaluate':\n  for k in ['rows','mass','MSE','MAE','R2','Brier','accuracy','positiveRecall','negativeRecall','precision','F1','balancedAccuracy','AUROC']: \n   if k in z['metrics']:add(k,z['metrics'][k],'rows'if k=='rows'else'analysis weight mass'if k=='mass'else FIXED['unit']if k in ['MSE','Brier']else'constructed outcome units'if k=='MAE'else'dimensionless')\n  series=[('squared loss',[(i,r['loss'])for i,r in enumerate(z['records'])])]\n elif api=='select':\n  add('selectedIndex',z['selectedIndex'],'zero-based candidate index')\n  for i,c in enumerate(z['candidates']):add('criterion'+str(i),c['criterion'],FIXED['unit']);add('testMSE'+str(i),c['test']['MSE'],FIXED['unit'])\n  series=[('validation criterion',[(i,c['criterion'])for i,c in enumerate(z['candidates'])]),('test MSE',[(i,c['test']['MSE'])for i,c in enumerate(z['candidates'])])]\n elif api=='paired':\n  for k in ['rows','mass','groupCount','meanDifference','minimumLeaveOut','maximumLeaveOut','varianceProxy']:add(k,z[k],'rows'if k=='rows'else'groups'if k=='groupCount'else'analysis weight mass'if k=='mass'else FIXED['unit']+' squared'if k=='varianceProxy'else FIXED['unit'])\n  series=[('loss A minus loss B',[(i,r['difference'])for i,r in enumerate(z['records'])])]\n elif api=='realdata':\n  add('nativeRows',z['nativeRows'],'native records');add('eligibleRows',z['eligibleRows'],'complete records');add('selectedIndex',z['selection']['selectedIndex'],'zero-based candidate index')\n  for i,c in enumerate(z['selection']['candidates']):add('validationMSE'+str(i),c['validation']['MSE'],FIXED['unit']);add('testMSE'+str(i),c['test']['MSE'],FIXED['unit'])\n  for k in ['meanDifference','minimumLeaveOut','maximumLeaveOut','varianceProxy']:add(k,z['paired'][k],FIXED['unit']+' squared'if k=='varianceProxy'else FIXED['unit'])\n  best=z['selection']['candidates'][z['selection']['selectedIndex']]['test']\n  for k in ['accuracy','positiveRecall','negativeRecall','precision','balancedAccuracy','AUROC']:\n   if k in best:add(k,best[k])\n  series=[('validation MSE',[(i,c['validation']['MSE'])for i,c in enumerate(z['selection']['candidates'])]),('test MSE',[(i,c['test']['MSE'])for i,c in enumerate(z['selection']['candidates'])])]\n return summary,series\n\n\ndef fixed_svg(points,title):\n good=[p for p in points if p['y'] is not None];xx=[float(p['x'])for p in good];yy=[float(p['y'])for p in good];xmin=min(xx)if xx else 0;xmax=max(xx)if xx else 1;ymin=min([0]+yy);ymax=max([0]+yy)\n if xmin==xmax:xmin-=.5;xmax+=.5\n if ymin==ymax:ymin-=.5;ymax+=.5\n pad=(ymax-ymin)*.08;ymin-=pad;ymax+=pad;X=lambda x:82+(float(x)-xmin)/(xmax-xmin)*608;Y=lambda y:354-(float(y)-ymin)/(ymax-ymin)*290;e=html.escape\n out=['<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"720\" height=\"480\" viewBox=\"0 0 720 480\" role=\"img\" aria-label=\"'+e(title)+'\"><rect width=\"720\" height=\"480\" fill=\"white\"/><g font-family=\"Arial,sans-serif\" font-size=\"13\" fill=\"#18232f\"><text x=\"360\" y=\"25\" text-anchor=\"middle\">'+e(title)+'</text>']\n for j in range(5):\n  y=ymin+(ymax-ymin)*j/4;x=xmin+(xmax-xmin)*j/4;out.append('<line x1=\"82\" y1=\"'+str(Y(y))+'\" x2=\"690\" y2=\"'+str(Y(y))+'\" stroke=\"#e2e8f0\"/><text x=\"73\" y=\"'+str(Y(y)+4)+'\" text-anchor=\"end\">'+format(y,'.3g')+'</text><text x=\"'+str(X(x))+'\" y=\"380\" text-anchor=\"middle\">'+format(x,'.3g')+'</text>')\n series=list(dict.fromkeys(p['series']for p in good))\n for j,s in enumerate(series):\n  pp=[p for p in good if p['series']==s];color=['#0f766e','#c76622','#4f46e5','#b23857'][j%4]\n  for p in pp:out.append('<circle cx=\"'+format(X(p['x']),'.6f')+'\" cy=\"'+format(Y(p['y']),'.6f')+'\" r=\"2.6\" fill=\"'+color+'\"><title>'+e(s+': '+str(p['y']))+'</title></circle>')\n  out.append('<text x=\"'+str(82+(j%2)*310)+'\" y=\"'+str(432+(j//2)*23)+'\" fill=\"'+color+'\">'+e(s)+'</text>')\n out.append('<text x=\"360\" y=\"405\" text-anchor=\"middle\">Declared record / candidate index; units in summary</text></g></svg>');return''.join(out)\n\nFIXED={'api': 'paired', 'variant': 'single-group-undefined-deletion', 'title': 'Undefined deletion diagnostic with one group', 'input': {'rows': [{'id': 'G', 'group': 'same', 'y': '0', 'predictionA': '1', 'predictionB': '0', 'weight': '1'}, {'id': 'H', 'group': 'same', 'y': '0', 'predictionA': '2', 'predictionB': '1', 'weight': '3'}]}, 'unit': 'Constructed squared outcome units', 'titleI18n': {'ko': '묶음 하나의 삭제 진단 미정의', 'en': 'Undefined deletion diagnostic with one group'}}\n\nOUT=Path(sys.argv[1]);OUT.mkdir(parents=True,exist_ok=False)\nresult=fixed_operation(FIXED['api'],FIXED['input']);summary,series=report_values(FIXED['api'],result)\ndef encode(v):\n if isinstance(v,F):return str(v)\n if isinstance(v,dict):return{k:encode(x)for k,x in v.items()}\n if isinstance(v,(list,tuple)):return[encode(x)for x in v]\n return v\n(OUT/'full.json').write_text(json.dumps(dict(arithmetic='Exact rational author implementation; factual rows, declared group split and finite five-candidate comparison',result=encode(result)),ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\nsummaryRows=[dict(metric=m,value=''if v is None else str(int(v))if isinstance(v,bool)else str(v),unit=u,defined=int(v is not None))for m,v,u in summary]\npoints=[dict(series=name,index=i,x=str(x),y=''if y is None else str(y),defined=int(y is not None))for name,pp in series for i,(x,y)in enumerate(pp)]\nfor name,rows in [('summary',summaryRows),('plot-points',points)]:\n with(OUT/(name+'.csv')).open('w',encoding='utf8',newline='')as f:writer=csv.DictWriter(f,fieldnames=list(rows[0]));writer.writeheader();writer.writerows(rows)\n(OUT/'plot.svg').write_text(fixed_svg([dict(p,x=number(p['x']),y=None if not p['defined']else number(p['y']))for p in points],FIXED['title']),encoding='utf8');print(FIXED['api']+'/'+FIXED['variant'])\n",
        "returnCode": 0,
        "stdout": "paired/single-group-undefined-deletion\r\n",
        "stderr": "",
        "diagnosticScope": "Public projection omits private absolute-path/traceback frames; actual exit and warnings/reason retained. Raw complete streams and commands in private execution proof.",
        "resultFolder": "ml22-code/runs/python-paired-single-group-undefined-deletion",
        "kind": null,
        "inputFiles": [
          {
            "file": "ml22-code/paired-single-group-undefined-deletion-input.json",
            "sha256": "91f51dab5b248e61e645912e6701426308cefbc23b45149608f460110464188e",
            "scope": "Complete fixed literal input; program embeds the same values"
          }
        ],
        "files": [
          {
            "file": "ml22-code/runs/python-paired-single-group-undefined-deletion/full.json",
            "sha256": "2e3716c29b6c086c3f627b9079c76a9164455f5b79625734f84ab1c673707e03",
            "bytes": 837
          },
          {
            "file": "ml22-code/runs/python-paired-single-group-undefined-deletion/plot-points.csv",
            "sha256": "551070d27aa77f8bca9b5979c74662cd4b1a7af66b1897ffd199fed60878a34a",
            "bytes": 84
          },
          {
            "file": "ml22-code/runs/python-paired-single-group-undefined-deletion/plot.svg",
            "sha256": "055ffa6913194a07a4c57fddde269bb5656ec89b53d3f4852e712269f1fbede0",
            "bytes": 1591
          },
          {
            "file": "ml22-code/runs/python-paired-single-group-undefined-deletion/summary.csv",
            "sha256": "3cb9f57db4bfdf90a8df410b70c83d65a1737af71c986866f890577294259061",
            "bytes": 320
          }
        ],
        "summaryRows": [
          {
            "metric": "rows",
            "value": "2.0",
            "unit": "rows",
            "defined": "true",
            "rawValue": "2",
            "arithmetic": "Exact Fraction",
            "exactFraction": "2",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "mass",
            "value": "4.0",
            "unit": "analysis weight mass",
            "defined": "true",
            "rawValue": "4",
            "arithmetic": "Exact Fraction",
            "exactFraction": "4",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "groupCount",
            "value": "1.0",
            "unit": "groups",
            "defined": "true",
            "rawValue": "1",
            "arithmetic": "Exact Fraction",
            "exactFraction": "1",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "meanDifference",
            "value": "2.5",
            "unit": "Constructed squared outcome units",
            "defined": "true",
            "rawValue": "5/2",
            "arithmetic": "Exact Fraction",
            "exactFraction": "5/2",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "minimumLeaveOut",
            "value": "",
            "unit": "Constructed squared outcome units",
            "defined": "false",
            "rawValue": "",
            "arithmetic": "Exact Fraction",
            "exactFraction": null
          },
          {
            "metric": "maximumLeaveOut",
            "value": "",
            "unit": "Constructed squared outcome units",
            "defined": "false",
            "rawValue": "",
            "arithmetic": "Exact Fraction",
            "exactFraction": null
          },
          {
            "metric": "varianceProxy",
            "value": "",
            "unit": "Constructed squared outcome units squared",
            "defined": "false",
            "rawValue": "",
            "arithmetic": "Exact Fraction",
            "exactFraction": null
          }
        ],
        "plotRows": [
          {
            "series": "loss A minus loss B",
            "index": "0",
            "x": "0",
            "y": "1",
            "defined": true,
            "xExact": "0",
            "yExact": "1"
          },
          {
            "series": "loss A minus loss B",
            "index": "1",
            "x": "1",
            "y": "3",
            "defined": true,
            "xExact": "1",
            "yExact": "3"
          }
        ],
        "plotFile": "ml22-code/runs/python-paired-single-group-undefined-deletion/plot.svg",
        "fullResultFile": "ml22-code/runs/python-paired-single-group-undefined-deletion/full.json",
        "arithmeticScope": "Python exact rational versus base-R approximate floating algebra; copied author kernels, not independent oracle.",
        "plotScope": "Original scatter vectors plot every defined declared comparison point, with missing points omitted. Source profiles show candidate risks; all source records remain in the full result and source CSV files.",
        "reproductionScope": "Standalone literal program plus four native CSV files for factual source profiles. No answer/engine/checker imports."
      }
    },
    "r": {
      "unequal-group-masses": {
        "api": "paired",
        "variant": "unequal-group-masses",
        "language": "r",
        "title": "Loss differences with unequal group masses",
        "titleI18n": {
          "ko": "다른 묶음 질량의 손실 차이",
          "en": "Loss differences with unequal group masses"
        },
        "input": {
          "rows": [
            {
              "id": "G",
              "group": "G",
              "y": "0",
              "predictionA": "1",
              "predictionB": "0",
              "weight": "1"
            },
            {
              "id": "H",
              "group": "H",
              "y": "0",
              "predictionA": "2",
              "predictionB": "1",
              "weight": "3"
            }
          ]
        },
        "expectedFailure": false,
        "codeFile": "ml22-code/paired-unequal-group-masses.R",
        "codeSHA256": "079c18b054cecbf56c00784536dcdd4f9a6220bfe4aa906effa3b872d5044b70",
        "code": "# ML22 standalone; source/public functions copied by value, no source() dependency.\noptions(stringsAsFactors=FALSE,digits=17,warn=1)\nargs0<-commandArgs(trailingOnly=FALSE);script0<-sub('^--file=','',args0[grepl('^--file=',args0)][1]);source_dir<-file.path(dirname(normalizePath(script0)), 'data');seed<-20261104;leaf_min<-5\nnative_hash <- c(\"actual1599-red-wine-original12-fields.csv\"=\"77e9ac73115930d6c43983333a5a57940deefc493affeb17aca478c09c5f6e00\",\"actual4898-white-wine-original12-fields.csv\"=\"50d810bbb42b9cc3e87fa4c27a4c0f168e72da09dd812863425ca3873fec28ef\",\"actual3613-NLS-original52-fields.csv\"=\"6e1e1895558795435b65f8634252a7589865273a0e69adbd715fcfa04a3c11a1\",\"actual3150-churn-original14-fields.csv\"=\"1c0753e434226e769d1015c922121a7d8967df66014e057c4f7543e490f11764\")\nsha256<-getExportedValue('tools','sha256sum')\nread_native<-function(name){f<-file.path(source_dir,name);if(unname(sha256(f))!=native_hash[[name]])stop(paste('Native hash differs',name));read.csv(f,check.names=FALSE,colClasses='character',na.strings=NULL)}\ngcd_small<-function(a,b){while(b!=0){r<-a%%b;a<-b;b<-r};a}\ncanonical<-function(token){\n if(is.na(token)||token%in%c('','.'))return('null')\n if(!grepl('^[+-]?[0-9]+([.][0-9]*)?$',token))stop('Unsupported native fingerprint token')\n neg<-substr(token,1,1)=='-';s<-sub('^[+-]','',token);parts<-strsplit(s,'.',fixed=TRUE)[[1]];dec<-if(length(parts)==2)nchar(parts[2])else 0;n<-as.numeric(gsub('.','',s,fixed=TRUE));d<-10^dec\n # Every native fingerprint numerator/denominator must remain exactly integral\n # in binary64; reject rather than silently rounding a changed future source.\n if(!is.finite(n)||n>2^53||d>2^53)stop('Native canonical integer range exceeded')\n g<-gcd_small(n,d);n<-n/g;d<-d/g;if(neg)n<--n\n out<-sprintf('%.0f',n);if(d!=1)out<-paste0(out,'/',sprintf('%.0f',d));out\n}\nfp_cache<-new.env(hash=TRUE,parent=emptyenv());hash_file<-tempfile('ml22-hash-')\nfingerprint<-function(tag,values){a<-vapply(values,canonical,'');payload<-paste0('[',paste0('\"',a,'\"',collapse=','),']');key<-paste0(tag,':',payload);if(exists(key,fp_cache,inherits=FALSE))return(get(key,fp_cache,inherits=FALSE));con<-file(hash_file,'wb');writeBin(charToRaw(payload),con);close(con);value<-paste0(tag,':',unname(sha256(hash_file)));assign(key,value,fp_cache);value}\nassign_roles<-function(group){order<-sort(unique(group),method='radix');state<-seed;if(length(order)>1)for(j in seq.int(length(order),2)){state<-(1664525*state+1013904223)%%2^32;k<-state%%j+1;order[c(j,k)]<-order[c(k,j)]};rank<-match(group,order)-1;list(rank=rank,planned=c('test','validation','train','train')[rank%%4+1],state=state)}\n\nfit_model<-function(r,x,method,lambda){\n tr<-which(r$role=='train'&r$eligible);if(!length(tr))stop('No complete positive training rows');y<-r$y[tr];xx<-x[tr,,drop=FALSE];mu<-colMeans(xx);scale<-apply(xx,2,function(v)diff(range(v)));scale[scale==0]<-1;z<-cbind(1,sweep(sweep(x,2,mu,'-'),2,scale,'/'));meanY<-mean(y);model<-list();n<-length(tr)\n if(method=='constant'){model<-list(mean=meanY,parameterCount=1,rank=1,unique=TRUE);raw<-rep(meanY,nrow(r))}\n else if(method=='ridge'){zt<-z[tr,,drop=FALSE];pen<-diag(c(0,rep(lambda,ncol(x))));theta<-drop(solve(crossprod(zt)/n+pen,crossprod(zt,y)/n));raw<-drop(z%*%theta);objective<-mean((y-raw[tr])^2)/2+lambda*sum(theta[-1]^2)/2;model<-list(lambdaValue=lambda,theta=theta,rank=length(theta),unique=TRUE,minimumObjective=objective,parameterCount=length(theta))}\n else{base<-sum((y-meanY)^2);best<-NULL;total<-sum(y);total2<-sum(y*y)\n  for(j in seq_len(ncol(x))){ord<-order(xx[,j],seq_len(n));sx<-xx[ord,j];sy<-y[ord];left<-cumsum(sy)\n   if(n<2*leaf_min)next\n   for(i in seq.int(leaf_min,n-leaf_min)){if(sx[i]==sx[i+1])next;loss<-total2-left[i]^2/i-(total-left[i])^2/(n-i)\n    # Explicit approximate-tie tolerance; exact source JavaScript/Python\n    # contracts are authoritative for general arbitrarily close ties.\n    if(is.null(best)||loss<best$weightedSSE-1e-12*max(1,abs(loss),abs(best$weightedSSE)))best<-list(feature=j-1,threshold=(sx[i]+sx[i+1])/2,leftMean=left[i]/i,rightMean=(total-left[i])/(n-i),leftRows=i,rightRows=n-i,leftWeight=i,rightWeight=n-i,weightedSSE=loss)\n   }\n  }\n  if(is.null(best)||best$weightedSSE>=base-1e-12*max(1,abs(base))){model<-list(split=FALSE,mean=meanY,weightedSSE=base,trainingMSE=base/n);raw<-rep(meanY,nrow(r))}else{model<-c(list(split=TRUE),best,list(trainingMSE=best$weightedSSE/n,improvement=(base-best$weightedSSE)/n));raw<-ifelse(x[,model$feature+1]<=model$threshold,model$leftMean,model$rightMean)}\n }\n pred<-if(r$dataset[1]=='company')pmax(0,pmin(1,raw))else raw;list(meanX=mu,scales=scale,model=model,raw=raw,pred=pred)\n}\n\n# New standalone fixed-profile adapters; native and fit helpers copied by value.\nnum<-function(x){if(is.null(x)||length(x)==0||is.na(x)||x%in%c('','.'))return(NA_real_);if(is.character(x)&&grepl('/',x,fixed=TRUE)){v<-strsplit(x,'/',fixed=TRUE)[[1]];return(as.numeric(v[1])/as.numeric(v[2]))};as.numeric(x)}\nfixedRows<-function(aa){\n rr<-lapply(seq_along(aa),function(i){a<-aa[[i]];w<-num(if(is.null(a$weight))'1'else a$weight);if(is.na(w)||w<0)stop(if(!is.na(w)&&w<0)'negative-weight'else'missing-weight');list(id=if(is.null(a$id))as.character(i-1)else a$id,group=if(is.null(a$group))if(is.null(a$id))as.character(i-1)else a$id else a$group,cohort=if(is.null(a$cohort))'all'else a$cohort,role=if(is.null(a$role))'train'else a$role,w=w,y=num(a$y),x=vapply(a$x,num,0.0))})\n p<-if(length(rr))length(rr[[1]]$x)else 0;xx<-matrix(NA_real_,length(rr),p)\n if(p)for(i in seq_along(rr))xx[i,]<-rr[[i]]$x\n r<-data.frame(id=vapply(rr,`[[`,'','id'),group=vapply(rr,`[[`,'','group'),cohort=vapply(rr,`[[`,'','cohort'),role=vapply(rr,`[[`,'','role'),w=vapply(rr,`[[`,0.0,'w'),y=vapply(rr,`[[`,0.0,'y'));r$eligible<-!is.na(r$y)&rowSums(is.na(xx))==0&r$w>0;list(r=r,x=xx)\n}\nweightedRisk<-function(r,p,binary=FALSE,threshold=.5){\n ii<-which(r$w>0&!is.na(r$y)&!is.na(p)&!r$role%in%c('excluded','unused'));y<-r$y[ii];p<-p[ii];w<-r$w[ii];W<-sum(w);d<-list(rows=length(ii),mass=W,MSE=NA_real_,MAE=NA_real_,R2=NA_real_)\n if(W==0){if(binary)d<-c(d,setNames(rep(list(NA_real_),10),c('Brier','accuracy','positiveRecall','negativeRecall','precision','F1','balancedAccuracy','AUROC','positiveMass','negativeMass')));return(d)}\n mu<-sum(w*y)/W;sse<-sum(w*(p-y)^2);sst<-sum(w*(y-mu)^2);d<-c(d,list(meanY=mu,SSE=sse,SST=sst));d$MSE<-sse/W;d$MAE<-sum(w*abs(p-y))/W;d$R2<-if(sst>0)1-sse/sst else NA_real_\n if(binary){pos<-y==1;yes<-p>=threshold;TP<-sum(w[pos&yes]);FP<-sum(w[!pos&yes]);TN<-sum(w[!pos&!yes]);FN<-sum(w[pos&!yes]);rate<-function(a,b)if(b>0)a/b else NA_real_;tpr<-rate(TP,TP+FN);tnr<-rate(TN,TN+FP);auc<-NA_real_;P<-sum(w[pos]);N<-sum(w[!pos]);if(P>0&&N>0){wins<-sum(vapply(which(pos),function(i)sum(w[i]*w[!pos]*ifelse(p[i]>p[!pos],1,ifelse(p[i]==p[!pos],.5,0))),0.0));auc<-wins/(P*N)};d<-c(d,list(Brier=d$MSE,threshold=threshold,confusionMass=list(TP=TP,FP=FP,TN=TN,FN=FN),confusionRows=list(TP=sum(pos&yes),FP=sum(!pos&yes),TN=sum(!pos&!yes),FN=sum(pos&!yes)),positiveMass=P,negativeMass=N,accuracy=(TP+TN)/W,positiveRecall=tpr,negativeRecall=tnr,precision=rate(TP,TP+FP),F1=rate(2*TP,2*TP+FP+FN),balancedAccuracy=if(is.finite(tpr)&&is.finite(tnr))(tpr+tnr)/2 else NA_real_,AUROC=auc))};d\n}\nweightedPair<-function(r,A,B){\n ii<-which(r$w>0&!is.na(r$y)&!is.na(A)&!is.na(B)&!r$role%in%c('excluded','unused'));rr<-r[ii,,drop=FALSE];la<-(A[ii]-rr$y)^2;lb<-(B[ii]-rr$y)^2;d<-la-lb;W<-sum(rr$w);S<-sum(rr$w*d);mu<-if(W>0)S/W else NA_real_;ids<-unique(rr$group);groups<-lapply(ids,function(g){jj<-which(rr$group==g);wg<-sum(rr$w[jj]);sg<-sum(rr$w[jj]*d[jj]);list(group=g,rows=length(jj),mass=wg,sum=sg,leaveOut=if(W>wg)(S-sg)/(W-wg)else NA_real_)});leaves<-vapply(groups,`[[`,0.0,'leaveOut');G<-length(groups);proxy<-if(G>1&&all(is.finite(leaves)))(G-1)/G*sum((leaves-mean(leaves))^2) else NA_real_\n list(rows=length(ii),mass=W,groupCount=G,meanDifference=mu,minimumLeaveOut=if(any(is.finite(leaves)))min(leaves,na.rm=TRUE)else NA_real_,maximumLeaveOut=if(any(is.finite(leaves)))max(leaves,na.rm=TRUE)else NA_real_,varianceProxy=proxy,groups=groups,records=lapply(seq_along(ii),function(j)list(id=rr$id[j],group=rr$group[j],weight=rr$w[j],lossA=la[j],lossB=lb[j],difference=d[j])))\n}\nrunSelection<-function(r,candidates,criterion,required,binary=FALSE){\n out<-lapply(candidates,function(c){v<-r;t<-r;v$role[v$role!='validation']<-'excluded';t$role[t$role!='test']<-'excluded';val<-weightedRisk(v,c$pred,binary);test<-weightedRisk(t,c$pred,binary);co<-setNames(lapply(required,function(g){z<-v;z$role[z$cohort!=g]<-'excluded';weightedRisk(z,c$pred,binary)}),required);vv<-vapply(co,`[[`,0.0,'MSE');score<-if(criterion=='mean')val$MSE else if(length(vv)&&all(is.finite(vv)))max(vv)else NA_real_;list(id=c$id,criterion=score,validation=val,test=test,cohorts=co)})\n scores<-vapply(out,`[[`,0.0,'criterion');eligible<-which(is.finite(scores));k<-if(length(eligible))eligible[which.min(scores[eligible])]else NA_integer_;list(criterion=criterion,selected=if(!is.na(k))out[[k]]$id else NULL,selectedIndex=if(!is.na(k))k-1 else NA_real_,candidates=out)\n}\nfixedOperation<-function(api,a){\n if(api=='realdata'){\n  kind<-a$kind;r<-rows[[kind]];x<-X[[kind]];asgn<-assign_roles(r$group);r$dataset<-kind;r$splitRank<-asgn$rank;r$plannedRole<-asgn$planned;r$eligible<-!is.na(r$y)&rowSums(is.na(x))==0;r$role<-ifelse(r$eligible,r$plannedRole,'excluded');r$w<-1;binary<-kind=='company';leaf_min<<-5\n  defs<-data.frame(id=c('constant','ridge:1/100','ridge:1/10','ridge:1','one-split-stump'),method=c('constant','ridge','ridge','ridge','stump'),lambda=c(0,.01,.1,1,0));fits<-lapply(seq_len(5),function(i)fit_model(r,x,defs$method[i],defs$lambda[i]));candidates<-lapply(seq_len(5),function(i)list(id=defs$id[i],pred=fits[[i]]$pred));selection<-runSelection(r,candidates,a$criterion,unique(r$cohort),binary);k<-selection$selectedIndex+1;best<-fits[[k]];base<-fits[[1]];test<-r;test$role[test$role!='test']<-'excluded';paired<-weightedPair(test,best$pred,base$pred)\n  records<-lapply(seq_len(nrow(r)),function(i)list(id=r$id[i],sourceRow=r$sourceRow[i],originalID=r$originalID[i],group=r$group[i],cohort=r$cohort[i],plannedRole=r$plannedRole[i],role=r$role[i],eligible=r$eligible[i],y=r$y[i],baselinePrediction=base$pred[i],selectedPrediction=best$pred[i],selectedRawPrediction=best$raw[i],queryInvariant=TRUE))\n  return(list(kind=kind,nativeRows=nrow(r),eligibleRows=sum(r$eligible),selection=selection,models=lapply(seq_len(5),function(i)list(id=defs$id[i],train=as.list(r$id[r$role=='train']),mass=sum(r$role=='train'),meanX=fits[[i]]$meanX,scales=fits[[i]]$scales,model=fits[[i]]$model)),paired=paired,records=records))\n }\n f<-fixedRows(a$rows);r<-f$r;x<-f$x;binary<-identical(a$task,'binary')\n if(api=='split'){seed<<-a$seed;asgn<-assign_roles(r$group);return(list(state=asgn$state,groupCount=length(unique(r$group)),records=lapply(seq_len(nrow(r)),function(i)list(id=r$id[i],group=r$group[i],rank=asgn$rank[i],role=asgn$planned[i]))))}\n if(api=='fit'){\n  r$dataset<-if(binary)'company'else'fixed';leaf_min<<-if(is.null(a$minLeafRows))1 else a$minLeafRows;fit<-fit_model(r,x,a$method,if(is.null(a$lambda))0 else num(a$lambda));bad<-rowSums(is.na(x))>0;fit$raw[bad]<-NA_real_;fit$pred[bad]<-NA_real_;fit$defined<-TRUE;fit$train<-as.list(r$id[r$role=='train'&r$eligible]);fit$mass<-sum(r$w[r$role=='train'&r$eligible]);fit$invariant<-ifelse(bad,NA,TRUE);return(fit)\n }\n if(api=='evaluate'){p<-vapply(a$rows,function(v)num(v$prediction),0.0);threshold<-if(is.null(a$threshold)).5 else num(a$threshold);m<-weightedRisk(r,p,binary,threshold);records<-lapply(seq_len(nrow(r)),function(i){valid<-r$w[i]>0&&!is.na(r$y[i])&&!is.na(p[i])&&!r$role[i]%in%c('excluded','unused');list(id=r$id[i],weight=r$w[i],y=r$y[i],prediction=p[i],eligible=valid,loss=if(valid)(p[i]-r$y[i])^2 else NA_real_,correct=list(defined=valid&&binary,value=if(valid&&binary)(p[i]>=threshold)==r$y[i] else NULL))});return(list(metrics=m,records=records))}\n if(api=='select'){cs<-lapply(a$candidates,function(c)list(id=c$id,pred=vapply(c$predictions,num,0.0)));return(runSelection(r,cs,a$criterion,unlist(a$requiredCohorts),binary))}\n if(api=='paired')return(weightedPair(r,vapply(a$rows,function(v)num(v$predictionA),0.0),vapply(a$rows,function(v)num(v$predictionB),0.0)))\n stop('unknown-api')\n}\nreportValues<-function(api,z){\n ss<-list();pp<-list();add<-function(k,v,u='dimensionless')ss[[length(ss)+1]]<<-list(metric=k,value=if(is.null(v)||length(v)==0||is.na(v))NULL else unname(v),unit=u);series<-function(name,values){for(i in seq_along(values))pp[[length(pp)+1]]<<-list(series=name,index=i-1,x=i-1,y=if(is.null(values[[i]])||is.na(values[[i]]))NULL else unname(values[[i]]))}\n if(api=='split'){add('groups',z$groupCount,'groups');add('rows',length(z$records),'rows');add('finalState',z$state,'unsigned 32-bit state');series('planned role code',lapply(z$records,function(r)switch(r$role,test=0,validation=1,train=2)))}\n if(api=='fit'){add('defined',z$defined);add('trainingRows',length(z$train),'rows');add('trainingMass',z$mass,'analysis weight mass');add('modelRank',z$model$rank,'parameters');add('threshold',z$model$threshold,'constructed feature units');add('minimumObjective',z$model$minimumObjective,'constructed squared outcome units');series('prediction',as.list(z$pred));if(!is.null(z$model$theta))for(i in seq_along(z$model$theta))add(paste0('theta',i-1),z$model$theta[i],'constructed outcome units per standardized coordinate')}\n if(api=='evaluate'){for(k in c('rows','mass','MSE','MAE','R2','Brier','accuracy','positiveRecall','negativeRecall','precision','F1','balancedAccuracy','AUROC'))if(k%in%names(z$metrics))add(k,z$metrics[[k]],if(k=='rows')'rows'else if(k=='mass')'analysis weight mass'else if(k%in%c('MSE','Brier'))FIXED$unit else if(k=='MAE')'constructed outcome units'else'dimensionless');series('squared loss',lapply(z$records,`[[`,'loss'))}\n if(api=='select'){add('selectedIndex',z$selectedIndex,'zero-based candidate index');for(i in seq_along(z$candidates)){c<-z$candidates[[i]];add(paste0('criterion',i-1),c$criterion,FIXED$unit);add(paste0('testMSE',i-1),c$test$MSE,FIXED$unit)};series('validation criterion',lapply(z$candidates,`[[`,'criterion'));series('test MSE',lapply(z$candidates,function(c)c$test$MSE))}\n if(api=='paired'){for(k in c('rows','mass','groupCount','meanDifference','minimumLeaveOut','maximumLeaveOut','varianceProxy'))add(k,z[[k]],if(k=='rows')'rows'else if(k=='groupCount')'groups'else if(k=='mass')'analysis weight mass'else if(k=='varianceProxy')paste(FIXED$unit,'squared')else FIXED$unit);series('loss A minus loss B',lapply(z$records,`[[`,'difference'))}\n if(api=='realdata'){add('nativeRows',z$nativeRows,'native records');add('eligibleRows',z$eligibleRows,'complete records');add('selectedIndex',z$selection$selectedIndex,'zero-based candidate index');for(i in seq_along(z$selection$candidates)){c<-z$selection$candidates[[i]];add(paste0('validationMSE',i-1),c$validation$MSE,FIXED$unit);add(paste0('testMSE',i-1),c$test$MSE,FIXED$unit)};for(k in c('meanDifference','minimumLeaveOut','maximumLeaveOut','varianceProxy'))add(k,z$paired[[k]],if(k=='varianceProxy')paste(FIXED$unit,'squared')else FIXED$unit);best<-z$selection$candidates[[z$selection$selectedIndex+1]]$test;for(k in c('accuracy','positiveRecall','negativeRecall','precision','balancedAccuracy','AUROC'))if(k%in%names(best))add(k,best[[k]]);series('validation MSE',lapply(z$selection$candidates,function(c)c$validation$MSE));series('test MSE',lapply(z$selection$candidates,function(c)c$test$MSE))}\n list(summary=ss,points=pp)\n}\n\nescapeXML<-function(s){s<-gsub('&','&amp;',s,fixed=TRUE);s<-gsub('<','&lt;',s,fixed=TRUE);s<-gsub('>','&gt;',s,fixed=TRUE);gsub('\"','&quot;',s,fixed=TRUE)}\nsvgPlot<-function(pp,title){\n xx<-vapply(pp,function(p)as.numeric(p$x),numeric(1));yy<-vapply(pp,function(p)as.numeric(p$y),numeric(1));xmin<-if(length(xx))min(xx)else 0;xmax<-if(length(xx))max(xx)else 1;ymin<-min(c(0,yy));ymax<-max(c(0,yy));if(xmin==xmax){xmin<-xmin-.5;xmax<-xmax+.5};if(ymin==ymax){ymin<-ymin-.5;ymax<-ymax+.5};pad<-(ymax-ymin)*.08;ymin<-ymin-pad;ymax<-ymax+pad;X<-function(x)82+(as.numeric(x)-xmin)/(xmax-xmin)*608;Y<-function(y)354-(as.numeric(y)-ymin)/(ymax-ymin)*290\n out<-paste0('<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"720\" height=\"480\" viewBox=\"0 0 720 480\" role=\"img\" aria-label=\"',escapeXML(title),'\"><rect width=\"720\" height=\"480\" fill=\"white\"/><g font-family=\"Arial,sans-serif\" font-size=\"13\" fill=\"#18232f\"><text x=\"360\" y=\"25\" text-anchor=\"middle\">',escapeXML(title),'</text>')\n for(j in 0:4){y<-ymin+(ymax-ymin)*j/4;x<-xmin+(xmax-xmin)*j/4;out<-paste0(out,'<line x1=\"82\" y1=\"',Y(y),'\" x2=\"690\" y2=\"',Y(y),'\" stroke=\"#e2e8f0\"/><text x=\"73\" y=\"',Y(y)+4,'\" text-anchor=\"end\">',sprintf('%.3g',y),'</text><text x=\"',X(x),'\" y=\"380\" text-anchor=\"middle\">',sprintf('%.3g',x),'</text>')}\n ss<-unique(vapply(pp,`[[`,character(1),'series'));cols<-c('#0f766e','#c76622','#4f46e5','#b23857')\n for(j in seq_along(ss)){rr<-Filter(function(p)p$series==ss[j],pp);xy<-vapply(rr,function(p)sprintf('%.6f,%.6f',X(p$x),Y(p$y)),character(1));col<-cols[(j-1)%%4+1];for(p in rr)out<-paste0(out,'<circle cx=\"',sprintf('%.6f',X(p$x)),'\" cy=\"',sprintf('%.6f',Y(p$y)),'\" r=\"2.6\" fill=\"',col,'\"><title>',escapeXML(ss[j]),': ',escapeXML(p$y),'</title></circle>');out<-paste0(out,'<text x=\"',82+((j-1)%%2)*310,'\" y=\"',432+floor((j-1)/2)*23,'\" fill=\"',col,'\">',escapeXML(ss[j]),'</text>')}\n paste0(out,'<text x=\"360\" y=\"405\" text-anchor=\"middle\">Declared record / candidate index; fixed example</text></g></svg>')\n}\ntoJSON<-function(x){\n if(is.null(x))return('null');if(is.list(x)){v<-vapply(x,toJSON,character(1));if(!is.null(names(x)))paste0('{',paste(paste0(vapply(names(x),toJSON,character(1)),':',v),collapse=','),'}')else paste0('[',paste(v,collapse=','),']')}\n else if(length(x)!=1){if(!is.numeric(x)&&!is.null(names(x)))toJSON(as.list(x))else paste0('[',paste(vapply(as.list(x),toJSON,character(1)),collapse=','),']')}\n else if(is.na(x))'null'else if(is.logical(x))if(x)'true'else'false'else if(is.numeric(x))if(is.finite(x))sprintf('%.17g',x)else'null'else paste0('\"',gsub('\\n','\\\\n',gsub('\"','\\\\\"',gsub('\\\\','\\\\\\\\',x,fixed=TRUE),fixed=TRUE),fixed=TRUE),'\"')\n}\n\nFIXED<-list(`api`=\"paired\",`variant`=\"unequal-group-masses\",`title`=\"Loss differences with unequal group masses\",`input`=list(`rows`=list(list(`id`=\"G\",`group`=\"G\",`y`=\"0\",`predictionA`=\"1\",`predictionB`=\"0\",`weight`=\"1\"),list(`id`=\"H\",`group`=\"H\",`y`=\"0\",`predictionA`=\"2\",`predictionB`=\"1\",`weight`=\"3\"))),`unit`=\"Constructed squared outcome units\",`titleI18n`=list(`ko`=\"다른 묶음 질량의 손실 차이\",`en`=\"Loss differences with unequal group masses\"))\n\nargs<-commandArgs(trailingOnly=TRUE);out<-if(length(args))args[1]else stop('NEW output directory required');if(dir.exists(out))stop('Preserve previous output directory');dir.create(out,recursive=TRUE)\nz<-fixedOperation(FIXED$api,FIXED$input);rr<-reportValues(FIXED$api,z)\nwriteLines(toJSON(list(arithmetic='BaseR binary64 author counterpart; native group hashing exact within declared integer range, stump approximate tie tolerance1e-12; not an independent exact oracle',result=z)),file.path(out,'full.json'),useBytes=TRUE)\nsums<-do.call(rbind,lapply(rr$summary,function(row)data.frame(metric=row$metric,value=if(is.null(row$value))''else if(is.logical(row$value))as.character(as.integer(row$value))else format(row$value,digits=17,scientific=NA,trim=TRUE),unit=row$unit,defined=as.integer(!is.null(row$value)),stringsAsFactors=FALSE)))\npoints<-do.call(rbind,lapply(rr$points,function(p)data.frame(series=p$series,index=p$index,x=p$x,y=if(is.null(p$y))NA_real_ else p$y,defined=as.integer(!is.null(p$y)),stringsAsFactors=FALSE)))\nwrite.csv(sums,file.path(out,'summary.csv'),row.names=FALSE,na='');write.csv(points,file.path(out,'plot-points.csv'),row.names=FALSE,na='');writeLines(svgPlot(Filter(function(p)!is.null(p$y),rr$points),FIXED$title),file.path(out,'plot.svg'),useBytes=TRUE);cat(FIXED$api,'/',FIXED$variant,'\\n',sep='')\n",
        "returnCode": 0,
        "stdout": "paired/unequal-group-masses\r\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 ",
        "diagnosticScope": "Public projection omits private absolute-path/traceback frames; actual exit and warnings/reason retained. Raw complete streams and commands in private execution proof.",
        "resultFolder": "ml22-code/runs/r-paired-unequal-group-masses",
        "kind": null,
        "inputFiles": [
          {
            "file": "ml22-code/paired-unequal-group-masses-input.json",
            "sha256": "56a4feb23576b62964361703a4fee17246dfe639fe5189e7765125b70bcfa310",
            "scope": "Complete fixed literal input; program embeds the same values"
          }
        ],
        "files": [
          {
            "file": "ml22-code/runs/r-paired-unequal-group-masses/full.json",
            "sha256": "2da37b44147bd4cbaf2c0a75384684fcbc2a17af8e29b0419f809fcad3de75e8",
            "bytes": 571
          },
          {
            "file": "ml22-code/runs/r-paired-unequal-group-masses/plot-points.csv",
            "sha256": "00729eb7cd159705494478c48a5f0b480b734f92db84ed16995cab50cf073c80",
            "bytes": 98
          },
          {
            "file": "ml22-code/runs/r-paired-unequal-group-masses/plot.svg",
            "sha256": "f034337b30e6a8d504d88ebaf7553a644c6f48ca9c951e2e05c36fc6c0d27cde",
            "bytes": 1558
          },
          {
            "file": "ml22-code/runs/r-paired-unequal-group-masses/summary.csv",
            "sha256": "ec5fdceb22e727caad182809c605a452015ae499256bf8a12fc324e392a1f79a",
            "bytes": 373
          }
        ],
        "summaryRows": [
          {
            "metric": "rows",
            "value": "2.0",
            "unit": "rows",
            "defined": "true",
            "rawValue": "2",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "mass",
            "value": "4.0",
            "unit": "analysis weight mass",
            "defined": "true",
            "rawValue": "4",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "groupCount",
            "value": "2.0",
            "unit": "groups",
            "defined": "true",
            "rawValue": "2",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "meanDifference",
            "value": "2.5",
            "unit": "Constructed squared outcome units",
            "defined": "true",
            "rawValue": "2.5",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "minimumLeaveOut",
            "value": "1.0",
            "unit": "Constructed squared outcome units",
            "defined": "true",
            "rawValue": "1",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "maximumLeaveOut",
            "value": "3.0",
            "unit": "Constructed squared outcome units",
            "defined": "true",
            "rawValue": "3",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "varianceProxy",
            "value": "1.0",
            "unit": "Constructed squared outcome units squared",
            "defined": "true",
            "rawValue": "1",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          }
        ],
        "plotRows": [
          {
            "series": "loss A minus loss B",
            "index": "0",
            "x": "0",
            "y": "1",
            "defined": true,
            "xExact": null,
            "yExact": null
          },
          {
            "series": "loss A minus loss B",
            "index": "1",
            "x": "1",
            "y": "3",
            "defined": true,
            "xExact": null,
            "yExact": null
          }
        ],
        "plotFile": "ml22-code/runs/r-paired-unequal-group-masses/plot.svg",
        "fullResultFile": "ml22-code/runs/r-paired-unequal-group-masses/full.json",
        "arithmeticScope": "Python exact rational versus base-R approximate floating algebra; copied author kernels, not independent oracle.",
        "plotScope": "Original scatter vectors plot every defined declared comparison point, with missing points omitted. Source profiles show candidate risks; all source records remain in the full result and source CSV files.",
        "reproductionScope": "Standalone literal program plus four native CSV files for factual source profiles. No answer/engine/checker imports."
      },
      "single-group-undefined-deletion": {
        "api": "paired",
        "variant": "single-group-undefined-deletion",
        "language": "r",
        "title": "Undefined deletion diagnostic with one group",
        "titleI18n": {
          "ko": "묶음 하나의 삭제 진단 미정의",
          "en": "Undefined deletion diagnostic with one group"
        },
        "input": {
          "rows": [
            {
              "id": "G",
              "group": "same",
              "y": "0",
              "predictionA": "1",
              "predictionB": "0",
              "weight": "1"
            },
            {
              "id": "H",
              "group": "same",
              "y": "0",
              "predictionA": "2",
              "predictionB": "1",
              "weight": "3"
            }
          ]
        },
        "expectedFailure": false,
        "codeFile": "ml22-code/paired-single-group-undefined-deletion.R",
        "codeSHA256": "8e4025d48b8e5df79c130cef5dca1ff0bc29c1a917956c02acf69c532943f92f",
        "code": "# ML22 standalone; source/public functions copied by value, no source() dependency.\noptions(stringsAsFactors=FALSE,digits=17,warn=1)\nargs0<-commandArgs(trailingOnly=FALSE);script0<-sub('^--file=','',args0[grepl('^--file=',args0)][1]);source_dir<-file.path(dirname(normalizePath(script0)), 'data');seed<-20261104;leaf_min<-5\nnative_hash <- c(\"actual1599-red-wine-original12-fields.csv\"=\"77e9ac73115930d6c43983333a5a57940deefc493affeb17aca478c09c5f6e00\",\"actual4898-white-wine-original12-fields.csv\"=\"50d810bbb42b9cc3e87fa4c27a4c0f168e72da09dd812863425ca3873fec28ef\",\"actual3613-NLS-original52-fields.csv\"=\"6e1e1895558795435b65f8634252a7589865273a0e69adbd715fcfa04a3c11a1\",\"actual3150-churn-original14-fields.csv\"=\"1c0753e434226e769d1015c922121a7d8967df66014e057c4f7543e490f11764\")\nsha256<-getExportedValue('tools','sha256sum')\nread_native<-function(name){f<-file.path(source_dir,name);if(unname(sha256(f))!=native_hash[[name]])stop(paste('Native hash differs',name));read.csv(f,check.names=FALSE,colClasses='character',na.strings=NULL)}\ngcd_small<-function(a,b){while(b!=0){r<-a%%b;a<-b;b<-r};a}\ncanonical<-function(token){\n if(is.na(token)||token%in%c('','.'))return('null')\n if(!grepl('^[+-]?[0-9]+([.][0-9]*)?$',token))stop('Unsupported native fingerprint token')\n neg<-substr(token,1,1)=='-';s<-sub('^[+-]','',token);parts<-strsplit(s,'.',fixed=TRUE)[[1]];dec<-if(length(parts)==2)nchar(parts[2])else 0;n<-as.numeric(gsub('.','',s,fixed=TRUE));d<-10^dec\n # Every native fingerprint numerator/denominator must remain exactly integral\n # in binary64; reject rather than silently rounding a changed future source.\n if(!is.finite(n)||n>2^53||d>2^53)stop('Native canonical integer range exceeded')\n g<-gcd_small(n,d);n<-n/g;d<-d/g;if(neg)n<--n\n out<-sprintf('%.0f',n);if(d!=1)out<-paste0(out,'/',sprintf('%.0f',d));out\n}\nfp_cache<-new.env(hash=TRUE,parent=emptyenv());hash_file<-tempfile('ml22-hash-')\nfingerprint<-function(tag,values){a<-vapply(values,canonical,'');payload<-paste0('[',paste0('\"',a,'\"',collapse=','),']');key<-paste0(tag,':',payload);if(exists(key,fp_cache,inherits=FALSE))return(get(key,fp_cache,inherits=FALSE));con<-file(hash_file,'wb');writeBin(charToRaw(payload),con);close(con);value<-paste0(tag,':',unname(sha256(hash_file)));assign(key,value,fp_cache);value}\nassign_roles<-function(group){order<-sort(unique(group),method='radix');state<-seed;if(length(order)>1)for(j in seq.int(length(order),2)){state<-(1664525*state+1013904223)%%2^32;k<-state%%j+1;order[c(j,k)]<-order[c(k,j)]};rank<-match(group,order)-1;list(rank=rank,planned=c('test','validation','train','train')[rank%%4+1],state=state)}\n\nfit_model<-function(r,x,method,lambda){\n tr<-which(r$role=='train'&r$eligible);if(!length(tr))stop('No complete positive training rows');y<-r$y[tr];xx<-x[tr,,drop=FALSE];mu<-colMeans(xx);scale<-apply(xx,2,function(v)diff(range(v)));scale[scale==0]<-1;z<-cbind(1,sweep(sweep(x,2,mu,'-'),2,scale,'/'));meanY<-mean(y);model<-list();n<-length(tr)\n if(method=='constant'){model<-list(mean=meanY,parameterCount=1,rank=1,unique=TRUE);raw<-rep(meanY,nrow(r))}\n else if(method=='ridge'){zt<-z[tr,,drop=FALSE];pen<-diag(c(0,rep(lambda,ncol(x))));theta<-drop(solve(crossprod(zt)/n+pen,crossprod(zt,y)/n));raw<-drop(z%*%theta);objective<-mean((y-raw[tr])^2)/2+lambda*sum(theta[-1]^2)/2;model<-list(lambdaValue=lambda,theta=theta,rank=length(theta),unique=TRUE,minimumObjective=objective,parameterCount=length(theta))}\n else{base<-sum((y-meanY)^2);best<-NULL;total<-sum(y);total2<-sum(y*y)\n  for(j in seq_len(ncol(x))){ord<-order(xx[,j],seq_len(n));sx<-xx[ord,j];sy<-y[ord];left<-cumsum(sy)\n   if(n<2*leaf_min)next\n   for(i in seq.int(leaf_min,n-leaf_min)){if(sx[i]==sx[i+1])next;loss<-total2-left[i]^2/i-(total-left[i])^2/(n-i)\n    # Explicit approximate-tie tolerance; exact source JavaScript/Python\n    # contracts are authoritative for general arbitrarily close ties.\n    if(is.null(best)||loss<best$weightedSSE-1e-12*max(1,abs(loss),abs(best$weightedSSE)))best<-list(feature=j-1,threshold=(sx[i]+sx[i+1])/2,leftMean=left[i]/i,rightMean=(total-left[i])/(n-i),leftRows=i,rightRows=n-i,leftWeight=i,rightWeight=n-i,weightedSSE=loss)\n   }\n  }\n  if(is.null(best)||best$weightedSSE>=base-1e-12*max(1,abs(base))){model<-list(split=FALSE,mean=meanY,weightedSSE=base,trainingMSE=base/n);raw<-rep(meanY,nrow(r))}else{model<-c(list(split=TRUE),best,list(trainingMSE=best$weightedSSE/n,improvement=(base-best$weightedSSE)/n));raw<-ifelse(x[,model$feature+1]<=model$threshold,model$leftMean,model$rightMean)}\n }\n pred<-if(r$dataset[1]=='company')pmax(0,pmin(1,raw))else raw;list(meanX=mu,scales=scale,model=model,raw=raw,pred=pred)\n}\n\n# New standalone fixed-profile adapters; native and fit helpers copied by value.\nnum<-function(x){if(is.null(x)||length(x)==0||is.na(x)||x%in%c('','.'))return(NA_real_);if(is.character(x)&&grepl('/',x,fixed=TRUE)){v<-strsplit(x,'/',fixed=TRUE)[[1]];return(as.numeric(v[1])/as.numeric(v[2]))};as.numeric(x)}\nfixedRows<-function(aa){\n rr<-lapply(seq_along(aa),function(i){a<-aa[[i]];w<-num(if(is.null(a$weight))'1'else a$weight);if(is.na(w)||w<0)stop(if(!is.na(w)&&w<0)'negative-weight'else'missing-weight');list(id=if(is.null(a$id))as.character(i-1)else a$id,group=if(is.null(a$group))if(is.null(a$id))as.character(i-1)else a$id else a$group,cohort=if(is.null(a$cohort))'all'else a$cohort,role=if(is.null(a$role))'train'else a$role,w=w,y=num(a$y),x=vapply(a$x,num,0.0))})\n p<-if(length(rr))length(rr[[1]]$x)else 0;xx<-matrix(NA_real_,length(rr),p)\n if(p)for(i in seq_along(rr))xx[i,]<-rr[[i]]$x\n r<-data.frame(id=vapply(rr,`[[`,'','id'),group=vapply(rr,`[[`,'','group'),cohort=vapply(rr,`[[`,'','cohort'),role=vapply(rr,`[[`,'','role'),w=vapply(rr,`[[`,0.0,'w'),y=vapply(rr,`[[`,0.0,'y'));r$eligible<-!is.na(r$y)&rowSums(is.na(xx))==0&r$w>0;list(r=r,x=xx)\n}\nweightedRisk<-function(r,p,binary=FALSE,threshold=.5){\n ii<-which(r$w>0&!is.na(r$y)&!is.na(p)&!r$role%in%c('excluded','unused'));y<-r$y[ii];p<-p[ii];w<-r$w[ii];W<-sum(w);d<-list(rows=length(ii),mass=W,MSE=NA_real_,MAE=NA_real_,R2=NA_real_)\n if(W==0){if(binary)d<-c(d,setNames(rep(list(NA_real_),10),c('Brier','accuracy','positiveRecall','negativeRecall','precision','F1','balancedAccuracy','AUROC','positiveMass','negativeMass')));return(d)}\n mu<-sum(w*y)/W;sse<-sum(w*(p-y)^2);sst<-sum(w*(y-mu)^2);d<-c(d,list(meanY=mu,SSE=sse,SST=sst));d$MSE<-sse/W;d$MAE<-sum(w*abs(p-y))/W;d$R2<-if(sst>0)1-sse/sst else NA_real_\n if(binary){pos<-y==1;yes<-p>=threshold;TP<-sum(w[pos&yes]);FP<-sum(w[!pos&yes]);TN<-sum(w[!pos&!yes]);FN<-sum(w[pos&!yes]);rate<-function(a,b)if(b>0)a/b else NA_real_;tpr<-rate(TP,TP+FN);tnr<-rate(TN,TN+FP);auc<-NA_real_;P<-sum(w[pos]);N<-sum(w[!pos]);if(P>0&&N>0){wins<-sum(vapply(which(pos),function(i)sum(w[i]*w[!pos]*ifelse(p[i]>p[!pos],1,ifelse(p[i]==p[!pos],.5,0))),0.0));auc<-wins/(P*N)};d<-c(d,list(Brier=d$MSE,threshold=threshold,confusionMass=list(TP=TP,FP=FP,TN=TN,FN=FN),confusionRows=list(TP=sum(pos&yes),FP=sum(!pos&yes),TN=sum(!pos&!yes),FN=sum(pos&!yes)),positiveMass=P,negativeMass=N,accuracy=(TP+TN)/W,positiveRecall=tpr,negativeRecall=tnr,precision=rate(TP,TP+FP),F1=rate(2*TP,2*TP+FP+FN),balancedAccuracy=if(is.finite(tpr)&&is.finite(tnr))(tpr+tnr)/2 else NA_real_,AUROC=auc))};d\n}\nweightedPair<-function(r,A,B){\n ii<-which(r$w>0&!is.na(r$y)&!is.na(A)&!is.na(B)&!r$role%in%c('excluded','unused'));rr<-r[ii,,drop=FALSE];la<-(A[ii]-rr$y)^2;lb<-(B[ii]-rr$y)^2;d<-la-lb;W<-sum(rr$w);S<-sum(rr$w*d);mu<-if(W>0)S/W else NA_real_;ids<-unique(rr$group);groups<-lapply(ids,function(g){jj<-which(rr$group==g);wg<-sum(rr$w[jj]);sg<-sum(rr$w[jj]*d[jj]);list(group=g,rows=length(jj),mass=wg,sum=sg,leaveOut=if(W>wg)(S-sg)/(W-wg)else NA_real_)});leaves<-vapply(groups,`[[`,0.0,'leaveOut');G<-length(groups);proxy<-if(G>1&&all(is.finite(leaves)))(G-1)/G*sum((leaves-mean(leaves))^2) else NA_real_\n list(rows=length(ii),mass=W,groupCount=G,meanDifference=mu,minimumLeaveOut=if(any(is.finite(leaves)))min(leaves,na.rm=TRUE)else NA_real_,maximumLeaveOut=if(any(is.finite(leaves)))max(leaves,na.rm=TRUE)else NA_real_,varianceProxy=proxy,groups=groups,records=lapply(seq_along(ii),function(j)list(id=rr$id[j],group=rr$group[j],weight=rr$w[j],lossA=la[j],lossB=lb[j],difference=d[j])))\n}\nrunSelection<-function(r,candidates,criterion,required,binary=FALSE){\n out<-lapply(candidates,function(c){v<-r;t<-r;v$role[v$role!='validation']<-'excluded';t$role[t$role!='test']<-'excluded';val<-weightedRisk(v,c$pred,binary);test<-weightedRisk(t,c$pred,binary);co<-setNames(lapply(required,function(g){z<-v;z$role[z$cohort!=g]<-'excluded';weightedRisk(z,c$pred,binary)}),required);vv<-vapply(co,`[[`,0.0,'MSE');score<-if(criterion=='mean')val$MSE else if(length(vv)&&all(is.finite(vv)))max(vv)else NA_real_;list(id=c$id,criterion=score,validation=val,test=test,cohorts=co)})\n scores<-vapply(out,`[[`,0.0,'criterion');eligible<-which(is.finite(scores));k<-if(length(eligible))eligible[which.min(scores[eligible])]else NA_integer_;list(criterion=criterion,selected=if(!is.na(k))out[[k]]$id else NULL,selectedIndex=if(!is.na(k))k-1 else NA_real_,candidates=out)\n}\nfixedOperation<-function(api,a){\n if(api=='realdata'){\n  kind<-a$kind;r<-rows[[kind]];x<-X[[kind]];asgn<-assign_roles(r$group);r$dataset<-kind;r$splitRank<-asgn$rank;r$plannedRole<-asgn$planned;r$eligible<-!is.na(r$y)&rowSums(is.na(x))==0;r$role<-ifelse(r$eligible,r$plannedRole,'excluded');r$w<-1;binary<-kind=='company';leaf_min<<-5\n  defs<-data.frame(id=c('constant','ridge:1/100','ridge:1/10','ridge:1','one-split-stump'),method=c('constant','ridge','ridge','ridge','stump'),lambda=c(0,.01,.1,1,0));fits<-lapply(seq_len(5),function(i)fit_model(r,x,defs$method[i],defs$lambda[i]));candidates<-lapply(seq_len(5),function(i)list(id=defs$id[i],pred=fits[[i]]$pred));selection<-runSelection(r,candidates,a$criterion,unique(r$cohort),binary);k<-selection$selectedIndex+1;best<-fits[[k]];base<-fits[[1]];test<-r;test$role[test$role!='test']<-'excluded';paired<-weightedPair(test,best$pred,base$pred)\n  records<-lapply(seq_len(nrow(r)),function(i)list(id=r$id[i],sourceRow=r$sourceRow[i],originalID=r$originalID[i],group=r$group[i],cohort=r$cohort[i],plannedRole=r$plannedRole[i],role=r$role[i],eligible=r$eligible[i],y=r$y[i],baselinePrediction=base$pred[i],selectedPrediction=best$pred[i],selectedRawPrediction=best$raw[i],queryInvariant=TRUE))\n  return(list(kind=kind,nativeRows=nrow(r),eligibleRows=sum(r$eligible),selection=selection,models=lapply(seq_len(5),function(i)list(id=defs$id[i],train=as.list(r$id[r$role=='train']),mass=sum(r$role=='train'),meanX=fits[[i]]$meanX,scales=fits[[i]]$scales,model=fits[[i]]$model)),paired=paired,records=records))\n }\n f<-fixedRows(a$rows);r<-f$r;x<-f$x;binary<-identical(a$task,'binary')\n if(api=='split'){seed<<-a$seed;asgn<-assign_roles(r$group);return(list(state=asgn$state,groupCount=length(unique(r$group)),records=lapply(seq_len(nrow(r)),function(i)list(id=r$id[i],group=r$group[i],rank=asgn$rank[i],role=asgn$planned[i]))))}\n if(api=='fit'){\n  r$dataset<-if(binary)'company'else'fixed';leaf_min<<-if(is.null(a$minLeafRows))1 else a$minLeafRows;fit<-fit_model(r,x,a$method,if(is.null(a$lambda))0 else num(a$lambda));bad<-rowSums(is.na(x))>0;fit$raw[bad]<-NA_real_;fit$pred[bad]<-NA_real_;fit$defined<-TRUE;fit$train<-as.list(r$id[r$role=='train'&r$eligible]);fit$mass<-sum(r$w[r$role=='train'&r$eligible]);fit$invariant<-ifelse(bad,NA,TRUE);return(fit)\n }\n if(api=='evaluate'){p<-vapply(a$rows,function(v)num(v$prediction),0.0);threshold<-if(is.null(a$threshold)).5 else num(a$threshold);m<-weightedRisk(r,p,binary,threshold);records<-lapply(seq_len(nrow(r)),function(i){valid<-r$w[i]>0&&!is.na(r$y[i])&&!is.na(p[i])&&!r$role[i]%in%c('excluded','unused');list(id=r$id[i],weight=r$w[i],y=r$y[i],prediction=p[i],eligible=valid,loss=if(valid)(p[i]-r$y[i])^2 else NA_real_,correct=list(defined=valid&&binary,value=if(valid&&binary)(p[i]>=threshold)==r$y[i] else NULL))});return(list(metrics=m,records=records))}\n if(api=='select'){cs<-lapply(a$candidates,function(c)list(id=c$id,pred=vapply(c$predictions,num,0.0)));return(runSelection(r,cs,a$criterion,unlist(a$requiredCohorts),binary))}\n if(api=='paired')return(weightedPair(r,vapply(a$rows,function(v)num(v$predictionA),0.0),vapply(a$rows,function(v)num(v$predictionB),0.0)))\n stop('unknown-api')\n}\nreportValues<-function(api,z){\n ss<-list();pp<-list();add<-function(k,v,u='dimensionless')ss[[length(ss)+1]]<<-list(metric=k,value=if(is.null(v)||length(v)==0||is.na(v))NULL else unname(v),unit=u);series<-function(name,values){for(i in seq_along(values))pp[[length(pp)+1]]<<-list(series=name,index=i-1,x=i-1,y=if(is.null(values[[i]])||is.na(values[[i]]))NULL else unname(values[[i]]))}\n if(api=='split'){add('groups',z$groupCount,'groups');add('rows',length(z$records),'rows');add('finalState',z$state,'unsigned 32-bit state');series('planned role code',lapply(z$records,function(r)switch(r$role,test=0,validation=1,train=2)))}\n if(api=='fit'){add('defined',z$defined);add('trainingRows',length(z$train),'rows');add('trainingMass',z$mass,'analysis weight mass');add('modelRank',z$model$rank,'parameters');add('threshold',z$model$threshold,'constructed feature units');add('minimumObjective',z$model$minimumObjective,'constructed squared outcome units');series('prediction',as.list(z$pred));if(!is.null(z$model$theta))for(i in seq_along(z$model$theta))add(paste0('theta',i-1),z$model$theta[i],'constructed outcome units per standardized coordinate')}\n if(api=='evaluate'){for(k in c('rows','mass','MSE','MAE','R2','Brier','accuracy','positiveRecall','negativeRecall','precision','F1','balancedAccuracy','AUROC'))if(k%in%names(z$metrics))add(k,z$metrics[[k]],if(k=='rows')'rows'else if(k=='mass')'analysis weight mass'else if(k%in%c('MSE','Brier'))FIXED$unit else if(k=='MAE')'constructed outcome units'else'dimensionless');series('squared loss',lapply(z$records,`[[`,'loss'))}\n if(api=='select'){add('selectedIndex',z$selectedIndex,'zero-based candidate index');for(i in seq_along(z$candidates)){c<-z$candidates[[i]];add(paste0('criterion',i-1),c$criterion,FIXED$unit);add(paste0('testMSE',i-1),c$test$MSE,FIXED$unit)};series('validation criterion',lapply(z$candidates,`[[`,'criterion'));series('test MSE',lapply(z$candidates,function(c)c$test$MSE))}\n if(api=='paired'){for(k in c('rows','mass','groupCount','meanDifference','minimumLeaveOut','maximumLeaveOut','varianceProxy'))add(k,z[[k]],if(k=='rows')'rows'else if(k=='groupCount')'groups'else if(k=='mass')'analysis weight mass'else if(k=='varianceProxy')paste(FIXED$unit,'squared')else FIXED$unit);series('loss A minus loss B',lapply(z$records,`[[`,'difference'))}\n if(api=='realdata'){add('nativeRows',z$nativeRows,'native records');add('eligibleRows',z$eligibleRows,'complete records');add('selectedIndex',z$selection$selectedIndex,'zero-based candidate index');for(i in seq_along(z$selection$candidates)){c<-z$selection$candidates[[i]];add(paste0('validationMSE',i-1),c$validation$MSE,FIXED$unit);add(paste0('testMSE',i-1),c$test$MSE,FIXED$unit)};for(k in c('meanDifference','minimumLeaveOut','maximumLeaveOut','varianceProxy'))add(k,z$paired[[k]],if(k=='varianceProxy')paste(FIXED$unit,'squared')else FIXED$unit);best<-z$selection$candidates[[z$selection$selectedIndex+1]]$test;for(k in c('accuracy','positiveRecall','negativeRecall','precision','balancedAccuracy','AUROC'))if(k%in%names(best))add(k,best[[k]]);series('validation MSE',lapply(z$selection$candidates,function(c)c$validation$MSE));series('test MSE',lapply(z$selection$candidates,function(c)c$test$MSE))}\n list(summary=ss,points=pp)\n}\n\nescapeXML<-function(s){s<-gsub('&','&amp;',s,fixed=TRUE);s<-gsub('<','&lt;',s,fixed=TRUE);s<-gsub('>','&gt;',s,fixed=TRUE);gsub('\"','&quot;',s,fixed=TRUE)}\nsvgPlot<-function(pp,title){\n xx<-vapply(pp,function(p)as.numeric(p$x),numeric(1));yy<-vapply(pp,function(p)as.numeric(p$y),numeric(1));xmin<-if(length(xx))min(xx)else 0;xmax<-if(length(xx))max(xx)else 1;ymin<-min(c(0,yy));ymax<-max(c(0,yy));if(xmin==xmax){xmin<-xmin-.5;xmax<-xmax+.5};if(ymin==ymax){ymin<-ymin-.5;ymax<-ymax+.5};pad<-(ymax-ymin)*.08;ymin<-ymin-pad;ymax<-ymax+pad;X<-function(x)82+(as.numeric(x)-xmin)/(xmax-xmin)*608;Y<-function(y)354-(as.numeric(y)-ymin)/(ymax-ymin)*290\n out<-paste0('<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"720\" height=\"480\" viewBox=\"0 0 720 480\" role=\"img\" aria-label=\"',escapeXML(title),'\"><rect width=\"720\" height=\"480\" fill=\"white\"/><g font-family=\"Arial,sans-serif\" font-size=\"13\" fill=\"#18232f\"><text x=\"360\" y=\"25\" text-anchor=\"middle\">',escapeXML(title),'</text>')\n for(j in 0:4){y<-ymin+(ymax-ymin)*j/4;x<-xmin+(xmax-xmin)*j/4;out<-paste0(out,'<line x1=\"82\" y1=\"',Y(y),'\" x2=\"690\" y2=\"',Y(y),'\" stroke=\"#e2e8f0\"/><text x=\"73\" y=\"',Y(y)+4,'\" text-anchor=\"end\">',sprintf('%.3g',y),'</text><text x=\"',X(x),'\" y=\"380\" text-anchor=\"middle\">',sprintf('%.3g',x),'</text>')}\n ss<-unique(vapply(pp,`[[`,character(1),'series'));cols<-c('#0f766e','#c76622','#4f46e5','#b23857')\n for(j in seq_along(ss)){rr<-Filter(function(p)p$series==ss[j],pp);xy<-vapply(rr,function(p)sprintf('%.6f,%.6f',X(p$x),Y(p$y)),character(1));col<-cols[(j-1)%%4+1];for(p in rr)out<-paste0(out,'<circle cx=\"',sprintf('%.6f',X(p$x)),'\" cy=\"',sprintf('%.6f',Y(p$y)),'\" r=\"2.6\" fill=\"',col,'\"><title>',escapeXML(ss[j]),': ',escapeXML(p$y),'</title></circle>');out<-paste0(out,'<text x=\"',82+((j-1)%%2)*310,'\" y=\"',432+floor((j-1)/2)*23,'\" fill=\"',col,'\">',escapeXML(ss[j]),'</text>')}\n paste0(out,'<text x=\"360\" y=\"405\" text-anchor=\"middle\">Declared record / candidate index; fixed example</text></g></svg>')\n}\ntoJSON<-function(x){\n if(is.null(x))return('null');if(is.list(x)){v<-vapply(x,toJSON,character(1));if(!is.null(names(x)))paste0('{',paste(paste0(vapply(names(x),toJSON,character(1)),':',v),collapse=','),'}')else paste0('[',paste(v,collapse=','),']')}\n else if(length(x)!=1){if(!is.numeric(x)&&!is.null(names(x)))toJSON(as.list(x))else paste0('[',paste(vapply(as.list(x),toJSON,character(1)),collapse=','),']')}\n else if(is.na(x))'null'else if(is.logical(x))if(x)'true'else'false'else if(is.numeric(x))if(is.finite(x))sprintf('%.17g',x)else'null'else paste0('\"',gsub('\\n','\\\\n',gsub('\"','\\\\\"',gsub('\\\\','\\\\\\\\',x,fixed=TRUE),fixed=TRUE),fixed=TRUE),'\"')\n}\n\nFIXED<-list(`api`=\"paired\",`variant`=\"single-group-undefined-deletion\",`title`=\"Undefined deletion diagnostic with one group\",`input`=list(`rows`=list(list(`id`=\"G\",`group`=\"same\",`y`=\"0\",`predictionA`=\"1\",`predictionB`=\"0\",`weight`=\"1\"),list(`id`=\"H\",`group`=\"same\",`y`=\"0\",`predictionA`=\"2\",`predictionB`=\"1\",`weight`=\"3\"))),`unit`=\"Constructed squared outcome units\",`titleI18n`=list(`ko`=\"묶음 하나의 삭제 진단 미정의\",`en`=\"Undefined deletion diagnostic with one group\"))\n\nargs<-commandArgs(trailingOnly=TRUE);out<-if(length(args))args[1]else stop('NEW output directory required');if(dir.exists(out))stop('Preserve previous output directory');dir.create(out,recursive=TRUE)\nz<-fixedOperation(FIXED$api,FIXED$input);rr<-reportValues(FIXED$api,z)\nwriteLines(toJSON(list(arithmetic='BaseR binary64 author counterpart; native group hashing exact within declared integer range, stump approximate tie tolerance1e-12; not an independent exact oracle',result=z)),file.path(out,'full.json'),useBytes=TRUE)\nsums<-do.call(rbind,lapply(rr$summary,function(row)data.frame(metric=row$metric,value=if(is.null(row$value))''else if(is.logical(row$value))as.character(as.integer(row$value))else format(row$value,digits=17,scientific=NA,trim=TRUE),unit=row$unit,defined=as.integer(!is.null(row$value)),stringsAsFactors=FALSE)))\npoints<-do.call(rbind,lapply(rr$points,function(p)data.frame(series=p$series,index=p$index,x=p$x,y=if(is.null(p$y))NA_real_ else p$y,defined=as.integer(!is.null(p$y)),stringsAsFactors=FALSE)))\nwrite.csv(sums,file.path(out,'summary.csv'),row.names=FALSE,na='');write.csv(points,file.path(out,'plot-points.csv'),row.names=FALSE,na='');writeLines(svgPlot(Filter(function(p)!is.null(p$y),rr$points),FIXED$title),file.path(out,'plot.svg'),useBytes=TRUE);cat(FIXED$api,'/',FIXED$variant,'\\n',sep='')\n",
        "returnCode": 0,
        "stdout": "paired/single-group-undefined-deletion\r\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 ",
        "diagnosticScope": "Public projection omits private absolute-path/traceback frames; actual exit and warnings/reason retained. Raw complete streams and commands in private execution proof.",
        "resultFolder": "ml22-code/runs/r-paired-single-group-undefined-deletion",
        "kind": null,
        "inputFiles": [
          {
            "file": "ml22-code/paired-single-group-undefined-deletion-input.json",
            "sha256": "91f51dab5b248e61e645912e6701426308cefbc23b45149608f460110464188e",
            "scope": "Complete fixed literal input; program embeds the same values"
          }
        ],
        "files": [
          {
            "file": "ml22-code/runs/r-paired-single-group-undefined-deletion/full.json",
            "sha256": "12b2820aa9aa60f2d69672875915ae50c591420c94136103ab142b0eb2f57e25",
            "bytes": 540
          },
          {
            "file": "ml22-code/runs/r-paired-single-group-undefined-deletion/plot-points.csv",
            "sha256": "00729eb7cd159705494478c48a5f0b480b734f92db84ed16995cab50cf073c80",
            "bytes": 98
          },
          {
            "file": "ml22-code/runs/r-paired-single-group-undefined-deletion/plot.svg",
            "sha256": "bab013f9bc04f031fc2711423f02ad791592fe33500917792a3bef85f87bc545",
            "bytes": 1562
          },
          {
            "file": "ml22-code/runs/r-paired-single-group-undefined-deletion/summary.csv",
            "sha256": "bd3e91844e6dcabf9be891b9523569e7b360a85edc98890dc60163071c088e03",
            "bytes": 370
          }
        ],
        "summaryRows": [
          {
            "metric": "rows",
            "value": "2.0",
            "unit": "rows",
            "defined": "true",
            "rawValue": "2",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "mass",
            "value": "4.0",
            "unit": "analysis weight mass",
            "defined": "true",
            "rawValue": "4",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "groupCount",
            "value": "1.0",
            "unit": "groups",
            "defined": "true",
            "rawValue": "1",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "meanDifference",
            "value": "2.5",
            "unit": "Constructed squared outcome units",
            "defined": "true",
            "rawValue": "2.5",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "minimumLeaveOut",
            "value": "",
            "unit": "Constructed squared outcome units",
            "defined": "false",
            "rawValue": "",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null
          },
          {
            "metric": "maximumLeaveOut",
            "value": "",
            "unit": "Constructed squared outcome units",
            "defined": "false",
            "rawValue": "",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null
          },
          {
            "metric": "varianceProxy",
            "value": "",
            "unit": "Constructed squared outcome units squared",
            "defined": "false",
            "rawValue": "",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null
          }
        ],
        "plotRows": [
          {
            "series": "loss A minus loss B",
            "index": "0",
            "x": "0",
            "y": "1",
            "defined": true,
            "xExact": null,
            "yExact": null
          },
          {
            "series": "loss A minus loss B",
            "index": "1",
            "x": "1",
            "y": "3",
            "defined": true,
            "xExact": null,
            "yExact": null
          }
        ],
        "plotFile": "ml22-code/runs/r-paired-single-group-undefined-deletion/plot.svg",
        "fullResultFile": "ml22-code/runs/r-paired-single-group-undefined-deletion/full.json",
        "arithmeticScope": "Python exact rational versus base-R approximate floating algebra; copied author kernels, not independent oracle.",
        "plotScope": "Original scatter vectors plot every defined declared comparison point, with missing points omitted. Source profiles show candidate risks; all source records remain in the full result and source CSV files.",
        "reproductionScope": "Standalone literal program plus four native CSV files for factual source profiles. No answer/engine/checker imports."
      }
    }
  },
  "realdata": {
    "python": {
      "country": {
        "api": "realdata",
        "variant": "country",
        "language": "python",
        "title": "All 6,497 factual wine records",
        "titleI18n": {
          "ko": "실제 와인 전체 6,497행",
          "en": "All 6,497 factual wine records"
        },
        "input": {
          "kind": "country",
          "seed": 20261104,
          "criterion": "mean"
        },
        "expectedFailure": false,
        "codeFile": "ml22-code/realdata-country.py",
        "codeSHA256": "97f72857baf97f575c9dc892e8458a4a9206da7650efa807723b272f6c3dc13c",
        "code": "# ML22 standalone fixed literal. Attribution and arithmetic scope in README.\nimport csv,hashlib,html,json,math,sys,time\nfrom pathlib import Path\nfrom fractions import Fraction as F\nfrom collections import Counter\nsys.set_int_max_str_digits(200000)\nnumber=lambda v:F(str(v))\ndef Q(x):return None if x is None or x in ('','.') else F(str(x))\n\ndef canonical(v):return None if Q(v) is None else str(Q(v))\n\ndef fingerprint(tag,values):return tag+':'+hashlib.sha256(json.dumps([canonical(x)for x in values],separators=(',',':')).encode()).hexdigest()\n\ndef split(rows,seed=20261104,pattern=('test','validation','train','train')):\n order=sorted(set(r['group'] for r in rows));state=seed\n for j in range(len(order)-1,0,-1):state=(1664525*state+1013904223)&0xffffffff;k=state%(j+1);order[k],order[j]=order[j],order[k]\n roles={g:(i,pattern[i%len(pattern)]) for i,g in enumerate(order)}\n return roles,state,order\n\ndef solve(A,b):\n n=len(b);M=[list(row)+[rhs]for row,rhs in zip(A,b)];piv=[];rank=0\n for j in range(n):\n  candidates=[i for i in range(rank,n)if M[i][j]]\n  if not candidates:continue\n  k=max(candidates,key=lambda i:abs(M[i][j]));M[rank],M[k]=M[k],M[rank];v=M[rank][j];M[rank]=[x/v for x in M[rank]]\n  for i in range(n):\n   if i!=rank:\n    v=M[i][j];M[i]=[a-v*b for a,b in zip(M[i],M[rank])]\n  piv.append(j);rank+=1\n x=[F(0)]*n\n for i,j in enumerate(piv):x[j]=M[i][-1]\n null=[]\n for j in range(n):\n  if j not in piv:\n   v=[F(0)]*n;v[j]=F(1)\n   for i,k in enumerate(piv):v[k]=-M[i][j]\n   null.append(v)\n return x,rank,null\n\ndef dot(a,b):return sum((x*y for x,y in zip(a,b)),F(0))\n\ndef fit(rows,method,lam=F(0),minleaf=1,binary=False):\n use=[r for r in rows if r['role']=='train'and r['w']>0 and r['y']is not None and None not in r['x']];p=len(rows[0]['x'])if rows else 0\n if not use:return dict(defined=False,pred=[None]*len(rows),raw=[None]*len(rows),train=[],invariant=[None]*len(rows))\n mass=sum(r['w']for r in use);mu=[sum(r['w']*r['x'][j]for r in use)/mass for j in range(p)];scale=[max(r['x'][j]for r in use)-min(r['x'][j]for r in use)or F(1)for j in range(p)];mean=sum(r['w']*r['y']for r in use)/mass;model={};z=lambda r:[F(1)]+[(x-m)/s for x,m,s in zip(r['x'],mu,scale)]\n if method=='constant':model=dict(mean=mean,parameterCount=1,rank=1,unique=True)\n elif method=='ridge':\n  vectors=[z(r)for r in use];n=p+1;A=[[sum(r['w']*xx[j]*xx[k]for r,xx in zip(use,vectors))/mass+(lam if j==k and j>0 else F(0))for k in range(n)]for j in range(n)];b=[sum(r['w']*r['y']*xx[j]for r,xx in zip(use,vectors))/mass for j in range(n)];theta,rank,null=solve(A,b);objective=sum(r['w']*(dot(xx,theta)-r['y'])**2 for r,xx in zip(use,vectors))/(2*mass)+lam*sum(x*x for x in theta[1:])/2;model=dict(lambdaValue=lam,theta=theta,rank=rank,unique=rank==n,nullspace=null,minimumObjective=objective,parameterCount=n)\n else:\n  best=None;total=sum(r['w']*r['y']for r in use);total2=sum(r['w']*r['y']**2 for r in use);base=total2-total**2/mass\n  for j in range(p):\n   ordered=sorted(enumerate(use),key=lambda v:(v[1]['x'][j],v[0]));leftW=F(0);leftS=F(0)\n   for i,(_idx,r)in enumerate(ordered[:-1]):\n    leftW+=r['w'];leftS+=r['w']*r['y'];rightW=mass-leftW\n    if i+1<minleaf or len(use)-i-1<minleaf or r['x'][j]==ordered[i+1][1]['x'][j]:continue\n    SSE=total2-leftS**2/leftW-(total-leftS)**2/rightW\n    if best is None or SSE<best['weightedSSE']:best=dict(feature=j,threshold=(r['x'][j]+ordered[i+1][1]['x'][j])/2,leftMean=leftS/leftW,rightMean=(total-leftS)/rightW,leftRows=i+1,rightRows=len(use)-i-1,leftWeight=leftW,rightWeight=rightW,weightedSSE=SSE)\n  model=dict(split=False,mean=mean,weightedSSE=base,trainingMSE=base/mass)if best is None or best['weightedSSE']>=base else dict(split=True,**best,trainingMSE=best['weightedSSE']/mass,improvement=(base-best['weightedSSE'])/mass)\n raw=[];invariant=[]\n for r in rows:\n  if None in r['x']:raw.append(None);invariant.append(None);continue\n  if method=='constant':v=mean;iv=True\n  elif method=='ridge':zz=z(r);v=dot(zz,model['theta']);iv=all(dot(zz,nn)==0 for nn in model['nullspace'])\n  else:v=(model['leftMean']if r['x'][model['feature']]<=model['threshold']else model['rightMean'])if model['split']else mean;iv=True\n  raw.append(v);invariant.append(iv)\n pred=[None if x is None else min(F(1),max(F(0),x))if binary else x for x in raw]\n return dict(defined=True,train=[r['id']for r in use],mass=mass,meanX=mu,scales=scale,model=model,pred=pred,raw=raw,invariant=invariant)\n\ndef risk(rows,pred,binary=False,threshold=F(1,2)):\n use=[(r,p)for r,p in zip(rows,pred)if r['w']>0 and r['y']is not None and p is not None and r['role']not in['excluded','unused']];mass=sum((r['w']for r,p in use),F(0));d=dict(rows=len(use),mass=mass)\n if not mass:\n  d.update({k:None for k in ['MSE','MAE','R2']+(['Brier','accuracy','balancedAccuracy','AUROC']if binary else[])});return d\n mean=sum(r['w']*r['y']for r,p in use)/mass;sse=sum(r['w']*(p-r['y'])**2 for r,p in use);sst=sum(r['w']*(r['y']-mean)**2 for r,p in use);d.update(meanY=mean,SSE=sse,SST=sst,MSE=sse/mass,MAE=sum(r['w']*abs(p-r['y'])for r,p in use)/mass,R2=1-sse/sst if sst else None)\n if binary:\n  weights=Counter();num=Counter()\n  for r,p in use:k=('T'if int(p>=threshold)==int(r['y'])else'F')+('P'if p>=threshold else'N');weights[k]+=r['w'];num[k]+=1\n  TP,FP,TN,FN=[weights[k]for k in ['TP','FP','TN','FN']];positive=TP+FN;negative=TN+FP;rate=lambda a,b:a/b if b else None;TPR=rate(TP,positive);TNR=rate(TN,negative)\n  # Pair enumeration is independent of the subject's score-tie-block formula.\n  negatives=[(r,p)for r,p in use if not r['y']];positives=[(r,p)for r,p in use if r['y']];wins=sum((a['w']*b['w']*(F(1)if pa>pb else F(1,2)if pa==pb else F(0))for a,pa in positives for b,pb in negatives),F(0))\n  d.update(Brier=d['MSE'],threshold=threshold,confusionMass={k:weights[k]for k in ['TP','FP','TN','FN']},confusionRows={k:num[k]for k in ['TP','FP','TN','FN']},positiveMass=positive,negativeMass=negative,accuracy=(TP+TN)/mass,positiveRecall=TPR,negativeRecall=TNR,precision=rate(TP,TP+FP),F1=rate(2*TP,2*TP+FP+FN),balancedAccuracy=(TPR+TNR)/2 if TPR is not None and TNR is not None else None,AUROC=rate(wins,positive*negative))\n return d\n\nNATIVE_SHA256={'actual1599-red-wine-original12-fields.csv': '77e9ac73115930d6c43983333a5a57940deefc493affeb17aca478c09c5f6e00', 'actual4898-white-wine-original12-fields.csv': '50d810bbb42b9cc3e87fa4c27a4c0f168e72da09dd812863425ca3873fec28ef', 'actual3613-NLS-original52-fields.csv': '6e1e1895558795435b65f8634252a7589865273a0e69adbd715fcfa04a3c11a1', 'actual3150-churn-original14-fields.csv': '1c0753e434226e769d1015c922121a7d8967df66014e057c4f7543e490f11764'}\n\ndef read_sources(directory,seed):\n def read(name):\n  p=directory/name\n  if hashlib.sha256(p.read_bytes()).hexdigest()!=NATIVE_SHA256[name]:raise ValueError('Native file hash differs: '+name)\n  with p.open(encoding='utf8',newline='')as f:return list(csv.DictReader(f))\n sources={};wine=[]\n for typ,n in [('red',1599),('white',4898)]:\n  table=read(f'actual{n}-{typ}-wine-original12-fields.csv');assert len(table)==n;features=[k for k in table[0]if k not in ['sourceRow','wineType','quality']];assert len(features)==11\n  for r in table:\n   i=int(r['sourceRow']);red='1'if typ=='red'else'0';nativeX=[r[k]for k in features];wine.append(dict(id=f'wine-{typ}-row:{i}',sourceRow=f'{typ}:{i}',originalID=None,group=fingerprint('wine-predictors',[red]+nativeX),cohort=typ,x=list(map(Q,nativeX+[red])),y=Q(r['quality'])))\n sources['country']=wine\n table=read('actual3613-NLS-original52-fields.csv');assert len(table)==3613;sources['person']=[dict(id='nls-row:'+r['sourceRow'],sourceRow=int(r['sourceRow']),originalID=r['id'],group='nls-id:'+r['id'],cohort='schooling-over12'if Q(r['ed76'])>12 else'schooling-at-most12',x=[Q(r['ed76']),Q(r['age76'])],y=Q(r['lwage76']))for r in table]\n table=read('actual3150-churn-original14-fields.csv');assert len(table)==3150;predictors=[k for k in table[0]if k not in ['sourceRow','Churn']];assert len(predictors)==13;sources['company']=[dict(id='customer-row:'+r['sourceRow'],sourceRow=int(r['sourceRow']),originalID=None,group=fingerprint('customer-predictors',[r[k]for k in predictors]),cohort='pay-as-you-go'if r['Tariff Plan']=='1'else'contractual'if r['Tariff Plan']=='2'else'other-native-tariff',x=[Q(r[k])for k in ['Call  Failure','Subscription  Length','Seconds of Use','Age']],y=Q(r['Churn']))for r in table]\n for kind,rows in sources.items():\n  assignments,state,order=split(rows,seed)\n  for r in rows:\n   rank,planned=assignments[r['group']];r.update(w=F(1),splitRank=rank,plannedRole=planned,eligible=r['y']is not None and None not in r['x']);r['role']=planned if r['eligible']else'excluded'\n return sources\n# New ML22 fixed-profile kernels. The public Fraction fitting/source readers are\n# copied by value above this file by the standalone builder; never imported.\ndef fixed_rows(data, prediction_key=None):\n out=[]\n for i,a in enumerate(data):\n  w=Q(a.get('weight','1'))\n  if w is None or w<0:raise ValueError('negative-weight' if w is not None and w<0 else 'missing-weight')\n  out.append(dict(id=a.get('id',str(i)),group=a.get('group',a.get('id',str(i))),cohort=a.get('cohort','all'),role=a.get('role','train'),w=w,x=[Q(v)for v in a.get('x',[])],y=Q(a.get('y'))))\n return out\n\ndef weighted_pair(rows,A,B):\n use=[(r,a,b)for r,a,b in zip(rows,A,B)if r['w']>0 and r['y']is not None and a is not None and b is not None and r['role']not in ['excluded','unused']]\n mass=sum((r['w']for r,a,b in use),F(0));records=[];groups={}\n for r,a,b in use:\n  la=(a-r['y'])**2;lb=(b-r['y'])**2;d=la-lb\n  records.append(dict(id=r['id'],group=r['group'],weight=r['w'],lossA=la,lossB=lb,difference=d))\n  g=groups.setdefault(r['group'],dict(group=r['group'],rows=0,mass=F(0),sum=F(0)));g['rows']+=1;g['mass']+=r['w'];g['sum']+=r['w']*d\n total=sum((g['sum']for g in groups.values()),F(0));mean=total/mass if mass else None;G=len(groups)\n for g in groups.values():g['leaveOut']=(total-g['sum'])/(mass-g['mass'])if mass>g['mass']else None\n leaves=[g['leaveOut']for g in groups.values()if g['leaveOut']is not None]\n proxy=F(G-1,G)*sum((v-sum(leaves,F(0))/G)**2 for v in leaves) if G>1 and len(leaves)==G else None\n return dict(rows=len(use),mass=mass,groupCount=G,meanDifference=mean,minimumLeaveOut=min(leaves)if leaves else None,maximumLeaveOut=max(leaves)if leaves else None,varianceProxy=proxy,groups=list(groups.values()),records=records)\n\ndef run_selection(rows,candidates,criterion,required,binary=False):\n results=[]\n for c,pred in candidates:\n  val=[dict(r,role='excluded')if r['role']!='validation'else r for r in rows]\n  test=[dict(r,role='excluded')if r['role']!='test'else r for r in rows]\n  v=risk(val,pred,binary);t=risk(test,pred,binary);cohort={g:risk([dict(r,role='excluded')if r['role']!='validation'or r['cohort']!=g else r for r in rows],pred,binary)for g in required}\n  values=[cohort[g]['MSE']for g in required]\n  score=v['MSE']if criterion=='mean'else max(values)if values and None not in values else None\n  results.append(dict(id=c,criterion=score,validation=v,test=t,cohorts=cohort))\n eligible=[(i,r['criterion'])for i,r in enumerate(results)if r['criterion']is not None]\n chosen=min(eligible,key=lambda t:(t[1],t[0]))[0]if eligible else None\n return dict(criterion=criterion,selected=results[chosen]['id']if chosen is not None else None,selectedIndex=chosen,candidates=results)\n\ndef fixed_operation(api,a):\n if api=='realdata':\n  kind=a['kind'];rows=read_sources(Path(__file__).parent/'data',a.get('seed',20261104))[kind];binary=kind=='company'\n  defs=[('constant','constant',F(0)),('ridge:1/100','ridge',F(1,100)),('ridge:1/10','ridge',F(1,10)),('ridge:1','ridge',F(1)),('one-split-stump','stump',F(0))]\n  fits=[fit(rows,method,lam,5,binary)for _,method,lam in defs]\n  selection=run_selection(rows,[(d[0],f['pred'])for d,f in zip(defs,fits)],a.get('criterion','mean'),list(dict.fromkeys(r['cohort']for r in rows)),binary)\n  chosen=selection['selectedIndex'];best=fits[chosen];base=fits[0]\n  test=[dict(r,role='excluded')if r['role']!='test'else r for r in rows]\n  paired=weighted_pair(test,best['pred'],base['pred'])\n  records=[dict(id=r['id'],sourceRow=r.get('sourceRow'),originalID=r.get('originalID'),group=r['group'],cohort=r['cohort'],plannedRole=r['plannedRole'],role=r['role'],eligible=r['eligible'],y=r['y'],baselinePrediction=base['pred'][i],selectedPrediction=best['pred'][i],selectedRawPrediction=best['raw'][i],queryInvariant=best['invariant'][i])for i,r in enumerate(rows)]\n  return dict(kind=kind,nativeRows=len(rows),eligibleRows=sum(r['eligible']for r in rows),selection=selection,models=[dict(id=d[0],train=f['train'],mass=f.get('mass'),meanX=f.get('meanX'),scales=f.get('scales'),model=f.get('model'))for d,f in zip(defs,fits)],paired=paired,records=records)\n rows=fixed_rows(a.get('rows',[]));binary=a.get('task')=='binary'\n if api=='split':\n  assignment,state,order=split(rows,a.get('seed',0));records=[dict(id=r['id'],group=r['group'],rank=assignment[r['group']][0],role=assignment[r['group']][1])for r in rows]\n  return dict(state=state,groupOrder=order,records=records,groupCount=len(order))\n if api=='fit':return fit(rows,a.get('method','constant'),Q(a.get('lambda','0')),a.get('minLeafRows',1),binary)\n if api=='evaluate':\n  pred=[Q(r.get('prediction'))for r in a['rows']];threshold=Q(a.get('threshold','1/2'));rr=risk(rows,pred,binary,threshold)\n  records=[]\n  for r,p in zip(rows,pred):\n   valid=r['w']>0 and r['y']is not None and p is not None and r['role']not in ['excluded','unused']\n   records.append(dict(id=r['id'],weight=r['w'],y=r['y'],prediction=p,eligible=valid,loss=(p-r['y'])**2 if valid else None,correct=dict(defined=valid and binary,value=bool(int(p>=threshold)==int(r['y']))if valid and binary else None)))\n  return dict(metrics=rr,records=records)\n if api=='select':return run_selection(rows,[(c['id'],list(map(Q,c['predictions'])))for c in a['candidates']],a.get('criterion','mean'),a.get('requiredCohorts',list(dict.fromkeys(r['cohort']for r in rows))),binary)\n if api=='paired':return weighted_pair(rows,[Q(r.get('predictionA'))for r in a['rows']],[Q(r.get('predictionB'))for r in a['rows']])\n raise ValueError('unknown-api')\n\ndef report_values(api,z):\n summary=[];series=[]\n def add(k,v,u='dimensionless'):summary.append((k,v,u))\n if api=='split':\n  add('groups',z['groupCount'],'groups');add('rows',len(z['records']),'rows');add('finalState',z['state'],'unsigned 32-bit state')\n  series=[('planned role code',[(i,F({'test':0,'validation':1,'train':2}[r['role']]))for i,r in enumerate(z['records'])])]\n elif api=='fit':\n  add('defined',z['defined']);add('trainingRows',len(z['train']),'rows');add('trainingMass',z.get('mass'),'analysis weight mass')\n  model=z.get('model',{});add('modelRank',model.get('rank'),'parameters');add('threshold',model.get('threshold'),'constructed feature units');add('minimumObjective',model.get('minimumObjective'),'constructed squared outcome units')\n  series=[('prediction',list(enumerate(z['pred'])))];\n  if model.get('theta')is not None:\n   for i,v in enumerate(model['theta']):add('theta'+str(i),v,'constructed outcome units per standardized coordinate')\n elif api=='evaluate':\n  for k in ['rows','mass','MSE','MAE','R2','Brier','accuracy','positiveRecall','negativeRecall','precision','F1','balancedAccuracy','AUROC']: \n   if k in z['metrics']:add(k,z['metrics'][k],'rows'if k=='rows'else'analysis weight mass'if k=='mass'else FIXED['unit']if k in ['MSE','Brier']else'constructed outcome units'if k=='MAE'else'dimensionless')\n  series=[('squared loss',[(i,r['loss'])for i,r in enumerate(z['records'])])]\n elif api=='select':\n  add('selectedIndex',z['selectedIndex'],'zero-based candidate index')\n  for i,c in enumerate(z['candidates']):add('criterion'+str(i),c['criterion'],FIXED['unit']);add('testMSE'+str(i),c['test']['MSE'],FIXED['unit'])\n  series=[('validation criterion',[(i,c['criterion'])for i,c in enumerate(z['candidates'])]),('test MSE',[(i,c['test']['MSE'])for i,c in enumerate(z['candidates'])])]\n elif api=='paired':\n  for k in ['rows','mass','groupCount','meanDifference','minimumLeaveOut','maximumLeaveOut','varianceProxy']:add(k,z[k],'rows'if k=='rows'else'groups'if k=='groupCount'else'analysis weight mass'if k=='mass'else FIXED['unit']+' squared'if k=='varianceProxy'else FIXED['unit'])\n  series=[('loss A minus loss B',[(i,r['difference'])for i,r in enumerate(z['records'])])]\n elif api=='realdata':\n  add('nativeRows',z['nativeRows'],'native records');add('eligibleRows',z['eligibleRows'],'complete records');add('selectedIndex',z['selection']['selectedIndex'],'zero-based candidate index')\n  for i,c in enumerate(z['selection']['candidates']):add('validationMSE'+str(i),c['validation']['MSE'],FIXED['unit']);add('testMSE'+str(i),c['test']['MSE'],FIXED['unit'])\n  for k in ['meanDifference','minimumLeaveOut','maximumLeaveOut','varianceProxy']:add(k,z['paired'][k],FIXED['unit']+' squared'if k=='varianceProxy'else FIXED['unit'])\n  best=z['selection']['candidates'][z['selection']['selectedIndex']]['test']\n  for k in ['accuracy','positiveRecall','negativeRecall','precision','balancedAccuracy','AUROC']:\n   if k in best:add(k,best[k])\n  series=[('validation MSE',[(i,c['validation']['MSE'])for i,c in enumerate(z['selection']['candidates'])]),('test MSE',[(i,c['test']['MSE'])for i,c in enumerate(z['selection']['candidates'])])]\n return summary,series\n\n\ndef fixed_svg(points,title):\n good=[p for p in points if p['y'] is not None];xx=[float(p['x'])for p in good];yy=[float(p['y'])for p in good];xmin=min(xx)if xx else 0;xmax=max(xx)if xx else 1;ymin=min([0]+yy);ymax=max([0]+yy)\n if xmin==xmax:xmin-=.5;xmax+=.5\n if ymin==ymax:ymin-=.5;ymax+=.5\n pad=(ymax-ymin)*.08;ymin-=pad;ymax+=pad;X=lambda x:82+(float(x)-xmin)/(xmax-xmin)*608;Y=lambda y:354-(float(y)-ymin)/(ymax-ymin)*290;e=html.escape\n out=['<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"720\" height=\"480\" viewBox=\"0 0 720 480\" role=\"img\" aria-label=\"'+e(title)+'\"><rect width=\"720\" height=\"480\" fill=\"white\"/><g font-family=\"Arial,sans-serif\" font-size=\"13\" fill=\"#18232f\"><text x=\"360\" y=\"25\" text-anchor=\"middle\">'+e(title)+'</text>']\n for j in range(5):\n  y=ymin+(ymax-ymin)*j/4;x=xmin+(xmax-xmin)*j/4;out.append('<line x1=\"82\" y1=\"'+str(Y(y))+'\" x2=\"690\" y2=\"'+str(Y(y))+'\" stroke=\"#e2e8f0\"/><text x=\"73\" y=\"'+str(Y(y)+4)+'\" text-anchor=\"end\">'+format(y,'.3g')+'</text><text x=\"'+str(X(x))+'\" y=\"380\" text-anchor=\"middle\">'+format(x,'.3g')+'</text>')\n series=list(dict.fromkeys(p['series']for p in good))\n for j,s in enumerate(series):\n  pp=[p for p in good if p['series']==s];color=['#0f766e','#c76622','#4f46e5','#b23857'][j%4]\n  for p in pp:out.append('<circle cx=\"'+format(X(p['x']),'.6f')+'\" cy=\"'+format(Y(p['y']),'.6f')+'\" r=\"2.6\" fill=\"'+color+'\"><title>'+e(s+': '+str(p['y']))+'</title></circle>')\n  out.append('<text x=\"'+str(82+(j%2)*310)+'\" y=\"'+str(432+(j//2)*23)+'\" fill=\"'+color+'\">'+e(s)+'</text>')\n out.append('<text x=\"360\" y=\"405\" text-anchor=\"middle\">Declared record / candidate index; units in summary</text></g></svg>');return''.join(out)\n\nFIXED={'api': 'realdata', 'variant': 'country', 'title': 'All 6,497 factual wine records', 'input': {'kind': 'country', 'seed': 20261104, 'criterion': 'mean'}, 'unit': 'Squared native quality-score units', 'titleI18n': {'ko': '실제 와인 전체 6,497행', 'en': 'All 6,497 factual wine records'}}\n\nOUT=Path(sys.argv[1]);OUT.mkdir(parents=True,exist_ok=False)\nresult=fixed_operation(FIXED['api'],FIXED['input']);summary,series=report_values(FIXED['api'],result)\ndef encode(v):\n if isinstance(v,F):return str(v)\n if isinstance(v,dict):return{k:encode(x)for k,x in v.items()}\n if isinstance(v,(list,tuple)):return[encode(x)for x in v]\n return v\n(OUT/'full.json').write_text(json.dumps(dict(arithmetic='Exact rational author implementation; factual rows, declared group split and finite five-candidate comparison',result=encode(result)),ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\nsummaryRows=[dict(metric=m,value=''if v is None else str(int(v))if isinstance(v,bool)else str(v),unit=u,defined=int(v is not None))for m,v,u in summary]\npoints=[dict(series=name,index=i,x=str(x),y=''if y is None else str(y),defined=int(y is not None))for name,pp in series for i,(x,y)in enumerate(pp)]\nfor name,rows in [('summary',summaryRows),('plot-points',points)]:\n with(OUT/(name+'.csv')).open('w',encoding='utf8',newline='')as f:writer=csv.DictWriter(f,fieldnames=list(rows[0]));writer.writeheader();writer.writerows(rows)\n(OUT/'plot.svg').write_text(fixed_svg([dict(p,x=number(p['x']),y=None if not p['defined']else number(p['y']))for p in points],FIXED['title']),encoding='utf8');print(FIXED['api']+'/'+FIXED['variant'])\n",
        "returnCode": 0,
        "stdout": "realdata/country\r\n",
        "stderr": "",
        "diagnosticScope": "Public projection omits private absolute-path/traceback frames; actual exit and warnings/reason retained. Raw complete streams and commands in private execution proof.",
        "resultFolder": "ml22-code/runs/python-realdata-country",
        "kind": "country",
        "inputFiles": [
          {
            "file": "ml22-code/realdata-country-input.json",
            "sha256": "d2f3e8a3424de26a843b6f0be54c0bc6e46fb0091ada2ac12cdf01de88c96282",
            "scope": "Complete fixed literal input; program embeds the same values"
          },
          {
            "file": "ml22-code/data/actual1599-red-wine-original12-fields.csv",
            "sha256": "77e9ac73115930d6c43983333a5a57940deefc493affeb17aca478c09c5f6e00",
            "scope": "All native rows and original fields; required sibling data file"
          },
          {
            "file": "ml22-code/data/actual3150-churn-original14-fields.csv",
            "sha256": "1c0753e434226e769d1015c922121a7d8967df66014e057c4f7543e490f11764",
            "scope": "All native rows and original fields; required sibling data file"
          },
          {
            "file": "ml22-code/data/actual3613-NLS-original52-fields.csv",
            "sha256": "6e1e1895558795435b65f8634252a7589865273a0e69adbd715fcfa04a3c11a1",
            "scope": "All native rows and original fields; required sibling data file"
          },
          {
            "file": "ml22-code/data/actual4898-white-wine-original12-fields.csv",
            "sha256": "50d810bbb42b9cc3e87fa4c27a4c0f168e72da09dd812863425ca3873fec28ef",
            "scope": "All native rows and original fields; required sibling data file"
          }
        ],
        "files": [
          {
            "file": "ml22-code/runs/python-realdata-country/full.json",
            "sha256": "9e057413737be1c40fd325de75c27f998a379cc7f40e5b710ef8ff12bcd1bcc3",
            "bytes": 10536417
          },
          {
            "file": "ml22-code/runs/python-realdata-country/plot-points.csv",
            "sha256": "d887aa0ba29f13114057b06087a04efb8585f74e02ea7028c4784792c8eaa46e",
            "bytes": 3270
          },
          {
            "file": "ml22-code/runs/python-realdata-country/plot.svg",
            "sha256": "53281b1e2bffcd27a5bd96e1214a17634bef12d0138c70b11f0f63b779cd72c7",
            "bytes": 5433
          },
          {
            "file": "ml22-code/runs/python-realdata-country/summary.csv",
            "sha256": "9cfd826a6d5e69f35ce2e41eff8ba9c32a8a2aa55f0c012e5171a593acefb2cc",
            "bytes": 6405
          }
        ],
        "summaryRows": [
          {
            "metric": "nativeRows",
            "value": "6497.0",
            "unit": "native records",
            "defined": "true",
            "rawValue": "6497",
            "arithmetic": "Exact Fraction",
            "exactFraction": "6497",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "eligibleRows",
            "value": "6497.0",
            "unit": "complete records",
            "defined": "true",
            "rawValue": "6497",
            "arithmetic": "Exact Fraction",
            "exactFraction": "6497",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "selectedIndex",
            "value": "1.0",
            "unit": "zero-based candidate index",
            "defined": "true",
            "rawValue": "1",
            "arithmetic": "Exact Fraction",
            "exactFraction": "1",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "validationMSE0",
            "value": "0.7117725202339443",
            "unit": "Squared native quality-score units",
            "defined": "true",
            "rawValue": "3069287792/4312175175",
            "arithmetic": "Exact Fraction",
            "exactFraction": "3069287792/4312175175",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "testMSE0",
            "value": "0.7705622486123525",
            "unit": "Squared native quality-score units",
            "defined": "true",
            "rawValue": "488033327/633347050",
            "arithmetic": "Exact Fraction",
            "exactFraction": "488033327/633347050",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "validationMSE1",
            "value": "0.5164888710603163",
            "unit": "Squared native quality-score units",
            "defined": "true",
            "rawValue": "241727349146981490999199463207730489140576336499510588994749613796266534125765558495324433326985549538348674437138695586299283745998821957755442236658513615129380298427615195876593861091292328264877379190878481702208842147246387493161517/468020440887200131311421009493268523189618070097318059286279579777604137775526683095864160179036508554941901798177715757597655500683544291642387414599019870943488736690578685578248037095481433047749707192380423351568597699939007249530332",
            "arithmetic": "Exact Fraction",
            "exactFraction": "241727349146981490999199463207730489140576336499510588994749613796266534125765558495324433326985549538348674437138695586299283745998821957755442236658513615129380298427615195876593861091292328264877379190878481702208842147246387493161517/468020440887200131311421009493268523189618070097318059286279579777604137775526683095864160179036508554941901798177715757597655500683544291642387414599019870943488736690578685578248037095481433047749707192380423351568597699939007249530332",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "testMSE1",
            "value": "0.566539309764345",
            "unit": "Squared native quality-score units",
            "defined": "true",
            "rawValue": "525743601649685268902626545340665932788311400045999158335779555826191673512721523901891013444286782119333837738454960321023656836944090981334398321467687225391010201834306925328316386022772636915613272400945179028161509605905701928385237/927991390162089695253849520051763386275237795008687159321935186438640145417321949037745398684232094358324606268131244757693631422731253669177903301182823183910062433683776410962275591980475470441115512786857497898564762515603879239240732",
            "arithmetic": "Exact Fraction",
            "exactFraction": "525743601649685268902626545340665932788311400045999158335779555826191673512721523901891013444286782119333837738454960321023656836944090981334398321467687225391010201834306925328316386022772636915613272400945179028161509605905701928385237/927991390162089695253849520051763386275237795008687159321935186438640145417321949037745398684232094358324606268131244757693631422731253669177903301182823183910062433683776410962275591980475470441115512786857497898564762515603879239240732",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "validationMSE2",
            "value": "0.6256699535370438",
            "unit": "Squared native quality-score units",
            "defined": "true",
            "rawValue": "1696286555183788526891530788557218527842295005351996687337842423632818676851547779183348111970767193059719197038925584484384759199135250914110124431063670917068852498621313650698755016958019123915107337945119829096766268369945125601277101/2711152334540477919929459645130036954006211493791611164219031818016807831566929652219046715359775592894733344023415766837562385354022916479220241681147153654613809000362584118272309835936961332796985069286953124414404872932342251411022264",
            "arithmetic": "Exact Fraction",
            "exactFraction": "1696286555183788526891530788557218527842295005351996687337842423632818676851547779183348111970767193059719197038925584484384759199135250914110124431063670917068852498621313650698755016958019123915107337945119829096766268369945125601277101/2711152334540477919929459645130036954006211493791611164219031818016807831566929652219046715359775592894733344023415766837562385354022916479220241681147153654613809000362584118272309835936961332796985069286953124414404872932342251411022264",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "testMSE2",
            "value": "0.6833769814535918",
            "unit": "Squared native quality-score units",
            "defined": "true",
            "rawValue": "1836806452827737340176457405701606545998470496095661160561609202541629456185620408400388414876595068851150577469473438506120105613767044480651387577245314533224770433961043011868090635673700933231787405215610579437280009156423220257805707/2687837756725019264598370925823021894205175277014533426934592969458923734735273009018145822230146073054115244013386392921268851327636970023010731003299450859058161994216959930523039358232343729197993797192347876415755199577887219764981532",
            "arithmetic": "Exact Fraction",
            "exactFraction": "1836806452827737340176457405701606545998470496095661160561609202541629456185620408400388414876595068851150577469473438506120105613767044480651387577245314533224770433961043011868090635673700933231787405215610579437280009156423220257805707/2687837756725019264598370925823021894205175277014533426934592969458923734735273009018145822230146073054115244013386392921268851327636970023010731003299450859058161994216959930523039358232343729197993797192347876415755199577887219764981532",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "validationMSE3",
            "value": "0.6974566904311391",
            "unit": "Squared native quality-score units",
            "defined": "true",
            "rawValue": "1183129037404576653108218353657815476332811942350183648621625645927297781402303080323413533740907481422086317440204898210746167557523270598435150258153441299820254823125773715029305614379894514876893713848346593820288308742407997767830911158350825005279266315/1696347678123518841341845327824053581489590242115745986249403678748606406789431773989436466668155720169547613439120508891619298513825660872299241943681348156196579614893136378063651913900338455893379858564004541258239703126796536805708941940946480877873249372",
            "arithmetic": "Exact Fraction",
            "exactFraction": "1183129037404576653108218353657815476332811942350183648621625645927297781402303080323413533740907481422086317440204898210746167557523270598435150258153441299820254823125773715029305614379894514876893713848346593820288308742407997767830911158350825005279266315/1696347678123518841341845327824053581489590242115745986249403678748606406789431773989436466668155720169547613439120508891619298513825660872299241943681348156196579614893136378063651913900338455893379858564004541258239703126796536805708941940946480877873249372",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "testMSE3",
            "value": "0.7561259162319759",
            "unit": "Squared native quality-score units",
            "defined": "true",
            "rawValue": "1271622261660796498522753509865943345321628172534931532399504343354135796117720934576356898266494820698752800011355355088885157052849182833789001030934746793281696342184796944483992563757499805275141706949893824106230701487470150342973500775100044824161683845/1681759921677739195286080073162175970837959859198288711183376865786394803782643048660288978625554872453101872291609644564541491278448781724748757062101778823158034089949337907982023457638296233299702144792569612770760983321037844228755670941454312123395223886",
            "arithmetic": "Exact Fraction",
            "exactFraction": "1271622261660796498522753509865943345321628172534931532399504343354135796117720934576356898266494820698752800011355355088885157052849182833789001030934746793281696342184796944483992563757499805275141706949893824106230701487470150342973500775100044824161683845/1681759921677739195286080073162175970837959859198288711183376865786394803782643048660288978625554872453101872291609644564541491278448781724748757062101778823158034089949337907982023457638296233299702144792569612770760983321037844228755670941454312123395223886",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "validationMSE4",
            "value": "0.5969600181536415",
            "unit": "Squared native quality-score units",
            "defined": "true",
            "rawValue": "360374160424693/603682239120983",
            "arithmetic": "Exact Fraction",
            "exactFraction": "360374160424693/603682239120983",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "testMSE4",
            "value": "0.6431173472689219",
            "unit": "Squared native quality-score units",
            "defined": "true",
            "rawValue": "513199812964779/797987824685722",
            "arithmetic": "Exact Fraction",
            "exactFraction": "513199812964779/797987824685722",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "meanDifference",
            "value": "-0.20402293884800743",
            "unit": "Squared native quality-score units",
            "defined": "true",
            "rawValue": "-222885811165346477247615299414522832813596912850799548385900003686219372434821783613844187197691149889587832056081830435987259762186628470427701231475882637866690019399158713410370193477586766672942372268951784805063402496297419525484725417053/1092454664283566041495213001242937152407866813229101741132765149855228145188906831455959826966045127280978684614000804609875885251624800100697957213734949022678523248493383685395064883769215235690042209540508317963637902552431776737415170728700",
            "arithmetic": "Exact Fraction",
            "exactFraction": "-222885811165346477247615299414522832813596912850799548385900003686219372434821783613844187197691149889587832056081830435987259762186628470427701231475882637866690019399158713410370193477586766672942372268951784805063402496297419525484725417053/1092454664283566041495213001242937152407866813229101741132765149855228145188906831455959826966045127280978684614000804609875885251624800100697957213734949022678523248493383685395064883769215235690042209540508317963637902552431776737415170728700",
            "mathematicallyPositive": false,
            "mathematicallyNegative": true,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "minimumLeaveOut",
            "value": "-0.2064720619132734",
            "unit": "Squared native quality-score units",
            "defined": "true",
            "rawValue": "-11571549686703831772947034263341069069937138301692702698292236453444850930998345122625077092894530266348183166707532516391467161302321189931692542594069005405206150990075030843466072585334795584521541021706257127126644837277635664177080604611/56044142628673648225404979245920195922782758448184401589710628505584194808947636706662623093425363406979575641907847968833781473875175618548817135871904448003582233565831579399449425263996915436886923760814181367651312472950031669056986453740",
            "arithmetic": "Exact Fraction",
            "exactFraction": "-11571549686703831772947034263341069069937138301692702698292236453444850930998345122625077092894530266348183166707532516391467161302321189931692542594069005405206150990075030843466072585334795584521541021706257127126644837277635664177080604611/56044142628673648225404979245920195922782758448184401589710628505584194808947636706662623093425363406979575641907847968833781473875175618548817135871904448003582233565831579399449425263996915436886923760814181367651312472950031669056986453740",
            "mathematicallyPositive": false,
            "mathematicallyNegative": true,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "maximumLeaveOut",
            "value": "-0.20153295080969408",
            "unit": "Squared native quality-score units",
            "defined": "true",
            "rawValue": "-31919921459614684492964622453653793602357845113228772164409283282008412103143203664591834853455348879890216172207221957610374407553735595051108921470966553889536269874203100919614271685202325971457194581960287847933108580151422600567864059003/158385620472338571071796680477600553694820839092695047970921341428824898373112886344916108742289070497985757248870005129312860687038539791551004949203208222618819355729524028737574462702599978408593480193605295169449361336597915586465396499700",
            "arithmetic": "Exact Fraction",
            "exactFraction": "-31919921459614684492964622453653793602357845113228772164409283282008412103143203664591834853455348879890216172207221957610374407553735595051108921470966553889536269874203100919614271685202325971457194581960287847933108580151422600567864059003/158385620472338571071796680477600553694820839092695047970921341428824898373112886344916108742289070497985757248870005129312860687038539791551004949203208222618819355729524028737574462702599978408593480193605295169449361336597915586465396499700",
            "mathematicallyPositive": false,
            "mathematicallyNegative": true,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "varianceProxy",
            "value": "0.00021807524742993207",
            "unit": "Squared native quality-score units squared",
            "defined": "true",
            "rawValue": "828600091182957357739030920660476714609887932282824788555376605768158409709787059365621779493099714962538257444532802257656690107232051847998132993070868644810847305235990104855655737517697104155112677781579708208670918573910660050116907801127618883731609518603353347508644028315728326226208503712488765877402820616406448099716212223413096321890451709702253646405974294681733219113899899402096473978009639795327463857999150723661116400009879690900042606983553700590660775471445144188313273028582763201072323/3799606332897491719874528971834505435428306492491904387846769074786812437618683039978981669033355250556177126926057155892710201235203079150269618633354163509406608851807876214411104439111867368434287823252165264189060442927169107301558179078397384975296405807991479688324418778786317669698134132686728094953903062667167029064047896984812127140317452133197606221584684885415884731950247625999663357765262699691948819543045589338926329346939576373805302181055329917232959664373052062554831670306514472960840750000",
            "arithmetic": "Exact Fraction",
            "exactFraction": "828600091182957357739030920660476714609887932282824788555376605768158409709787059365621779493099714962538257444532802257656690107232051847998132993070868644810847305235990104855655737517697104155112677781579708208670918573910660050116907801127618883731609518603353347508644028315728326226208503712488765877402820616406448099716212223413096321890451709702253646405974294681733219113899899402096473978009639795327463857999150723661116400009879690900042606983553700590660775471445144188313273028582763201072323/3799606332897491719874528971834505435428306492491904387846769074786812437618683039978981669033355250556177126926057155892710201235203079150269618633354163509406608851807876214411104439111867368434287823252165264189060442927169107301558179078397384975296405807991479688324418778786317669698134132686728094953903062667167029064047896984812127140317452133197606221584684885415884731950247625999663357765262699691948819543045589338926329346939576373805302181055329917232959664373052062554831670306514472960840750000",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          }
        ],
        "plotRows": [
          {
            "series": "validation MSE",
            "index": "0",
            "x": "0",
            "y": "3069287792/4312175175",
            "defined": true,
            "xExact": "0",
            "yExact": "3069287792/4312175175"
          },
          {
            "series": "validation MSE",
            "index": "1",
            "x": "1",
            "y": "241727349146981490999199463207730489140576336499510588994749613796266534125765558495324433326985549538348674437138695586299283745998821957755442236658513615129380298427615195876593861091292328264877379190878481702208842147246387493161517/468020440887200131311421009493268523189618070097318059286279579777604137775526683095864160179036508554941901798177715757597655500683544291642387414599019870943488736690578685578248037095481433047749707192380423351568597699939007249530332",
            "defined": true,
            "xExact": "1",
            "yExact": "241727349146981490999199463207730489140576336499510588994749613796266534125765558495324433326985549538348674437138695586299283745998821957755442236658513615129380298427615195876593861091292328264877379190878481702208842147246387493161517/468020440887200131311421009493268523189618070097318059286279579777604137775526683095864160179036508554941901798177715757597655500683544291642387414599019870943488736690578685578248037095481433047749707192380423351568597699939007249530332"
          },
          {
            "series": "validation MSE",
            "index": "2",
            "x": "2",
            "y": "1696286555183788526891530788557218527842295005351996687337842423632818676851547779183348111970767193059719197038925584484384759199135250914110124431063670917068852498621313650698755016958019123915107337945119829096766268369945125601277101/2711152334540477919929459645130036954006211493791611164219031818016807831566929652219046715359775592894733344023415766837562385354022916479220241681147153654613809000362584118272309835936961332796985069286953124414404872932342251411022264",
            "defined": true,
            "xExact": "2",
            "yExact": "1696286555183788526891530788557218527842295005351996687337842423632818676851547779183348111970767193059719197038925584484384759199135250914110124431063670917068852498621313650698755016958019123915107337945119829096766268369945125601277101/2711152334540477919929459645130036954006211493791611164219031818016807831566929652219046715359775592894733344023415766837562385354022916479220241681147153654613809000362584118272309835936961332796985069286953124414404872932342251411022264"
          },
          {
            "series": "validation MSE",
            "index": "3",
            "x": "3",
            "y": "1183129037404576653108218353657815476332811942350183648621625645927297781402303080323413533740907481422086317440204898210746167557523270598435150258153441299820254823125773715029305614379894514876893713848346593820288308742407997767830911158350825005279266315/1696347678123518841341845327824053581489590242115745986249403678748606406789431773989436466668155720169547613439120508891619298513825660872299241943681348156196579614893136378063651913900338455893379858564004541258239703126796536805708941940946480877873249372",
            "defined": true,
            "xExact": "3",
            "yExact": "1183129037404576653108218353657815476332811942350183648621625645927297781402303080323413533740907481422086317440204898210746167557523270598435150258153441299820254823125773715029305614379894514876893713848346593820288308742407997767830911158350825005279266315/1696347678123518841341845327824053581489590242115745986249403678748606406789431773989436466668155720169547613439120508891619298513825660872299241943681348156196579614893136378063651913900338455893379858564004541258239703126796536805708941940946480877873249372"
          },
          {
            "series": "validation MSE",
            "index": "4",
            "x": "4",
            "y": "360374160424693/603682239120983",
            "defined": true,
            "xExact": "4",
            "yExact": "360374160424693/603682239120983"
          },
          {
            "series": "test MSE",
            "index": "0",
            "x": "0",
            "y": "488033327/633347050",
            "defined": true,
            "xExact": "0",
            "yExact": "488033327/633347050"
          },
          {
            "series": "test MSE",
            "index": "1",
            "x": "1",
            "y": "525743601649685268902626545340665932788311400045999158335779555826191673512721523901891013444286782119333837738454960321023656836944090981334398321467687225391010201834306925328316386022772636915613272400945179028161509605905701928385237/927991390162089695253849520051763386275237795008687159321935186438640145417321949037745398684232094358324606268131244757693631422731253669177903301182823183910062433683776410962275591980475470441115512786857497898564762515603879239240732",
            "defined": true,
            "xExact": "1",
            "yExact": "525743601649685268902626545340665932788311400045999158335779555826191673512721523901891013444286782119333837738454960321023656836944090981334398321467687225391010201834306925328316386022772636915613272400945179028161509605905701928385237/927991390162089695253849520051763386275237795008687159321935186438640145417321949037745398684232094358324606268131244757693631422731253669177903301182823183910062433683776410962275591980475470441115512786857497898564762515603879239240732"
          },
          {
            "series": "test MSE",
            "index": "2",
            "x": "2",
            "y": "1836806452827737340176457405701606545998470496095661160561609202541629456185620408400388414876595068851150577469473438506120105613767044480651387577245314533224770433961043011868090635673700933231787405215610579437280009156423220257805707/2687837756725019264598370925823021894205175277014533426934592969458923734735273009018145822230146073054115244013386392921268851327636970023010731003299450859058161994216959930523039358232343729197993797192347876415755199577887219764981532",
            "defined": true,
            "xExact": "2",
            "yExact": "1836806452827737340176457405701606545998470496095661160561609202541629456185620408400388414876595068851150577469473438506120105613767044480651387577245314533224770433961043011868090635673700933231787405215610579437280009156423220257805707/2687837756725019264598370925823021894205175277014533426934592969458923734735273009018145822230146073054115244013386392921268851327636970023010731003299450859058161994216959930523039358232343729197993797192347876415755199577887219764981532"
          },
          {
            "series": "test MSE",
            "index": "3",
            "x": "3",
            "y": "1271622261660796498522753509865943345321628172534931532399504343354135796117720934576356898266494820698752800011355355088885157052849182833789001030934746793281696342184796944483992563757499805275141706949893824106230701487470150342973500775100044824161683845/1681759921677739195286080073162175970837959859198288711183376865786394803782643048660288978625554872453101872291609644564541491278448781724748757062101778823158034089949337907982023457638296233299702144792569612770760983321037844228755670941454312123395223886",
            "defined": true,
            "xExact": "3",
            "yExact": "1271622261660796498522753509865943345321628172534931532399504343354135796117720934576356898266494820698752800011355355088885157052849182833789001030934746793281696342184796944483992563757499805275141706949893824106230701487470150342973500775100044824161683845/1681759921677739195286080073162175970837959859198288711183376865786394803782643048660288978625554872453101872291609644564541491278448781724748757062101778823158034089949337907982023457638296233299702144792569612770760983321037844228755670941454312123395223886"
          },
          {
            "series": "test MSE",
            "index": "4",
            "x": "4",
            "y": "513199812964779/797987824685722",
            "defined": true,
            "xExact": "4",
            "yExact": "513199812964779/797987824685722"
          }
        ],
        "plotFile": "ml22-code/runs/python-realdata-country/plot.svg",
        "fullResultFile": "ml22-code/runs/python-realdata-country/full.json",
        "arithmeticScope": "Python exact rational versus base-R approximate floating algebra; copied author kernels, not independent oracle.",
        "plotScope": "Original scatter vectors plot every defined declared comparison point, with missing points omitted. Source profiles show candidate risks; all source records remain in the full result and source CSV files.",
        "reproductionScope": "Standalone literal program plus four native CSV files for factual source profiles. No answer/engine/checker imports."
      },
      "person": {
        "api": "realdata",
        "variant": "person",
        "language": "python",
        "title": "All 3,613 factual NLS records",
        "titleI18n": {
          "ko": "실제 NLS 전체 3,613행",
          "en": "All 3,613 factual NLS records"
        },
        "input": {
          "kind": "person",
          "seed": 20261104,
          "criterion": "mean"
        },
        "expectedFailure": false,
        "codeFile": "ml22-code/realdata-person.py",
        "codeSHA256": "34094830739c876f5c963233f165c1fded7d4841f51a58d0fd1bbb65d2701104",
        "code": "# ML22 standalone fixed literal. Attribution and arithmetic scope in README.\nimport csv,hashlib,html,json,math,sys,time\nfrom pathlib import Path\nfrom fractions import Fraction as F\nfrom collections import Counter\nsys.set_int_max_str_digits(200000)\nnumber=lambda v:F(str(v))\ndef Q(x):return None if x is None or x in ('','.') else F(str(x))\n\ndef canonical(v):return None if Q(v) is None else str(Q(v))\n\ndef fingerprint(tag,values):return tag+':'+hashlib.sha256(json.dumps([canonical(x)for x in values],separators=(',',':')).encode()).hexdigest()\n\ndef split(rows,seed=20261104,pattern=('test','validation','train','train')):\n order=sorted(set(r['group'] for r in rows));state=seed\n for j in range(len(order)-1,0,-1):state=(1664525*state+1013904223)&0xffffffff;k=state%(j+1);order[k],order[j]=order[j],order[k]\n roles={g:(i,pattern[i%len(pattern)]) for i,g in enumerate(order)}\n return roles,state,order\n\ndef solve(A,b):\n n=len(b);M=[list(row)+[rhs]for row,rhs in zip(A,b)];piv=[];rank=0\n for j in range(n):\n  candidates=[i for i in range(rank,n)if M[i][j]]\n  if not candidates:continue\n  k=max(candidates,key=lambda i:abs(M[i][j]));M[rank],M[k]=M[k],M[rank];v=M[rank][j];M[rank]=[x/v for x in M[rank]]\n  for i in range(n):\n   if i!=rank:\n    v=M[i][j];M[i]=[a-v*b for a,b in zip(M[i],M[rank])]\n  piv.append(j);rank+=1\n x=[F(0)]*n\n for i,j in enumerate(piv):x[j]=M[i][-1]\n null=[]\n for j in range(n):\n  if j not in piv:\n   v=[F(0)]*n;v[j]=F(1)\n   for i,k in enumerate(piv):v[k]=-M[i][j]\n   null.append(v)\n return x,rank,null\n\ndef dot(a,b):return sum((x*y for x,y in zip(a,b)),F(0))\n\ndef fit(rows,method,lam=F(0),minleaf=1,binary=False):\n use=[r for r in rows if r['role']=='train'and r['w']>0 and r['y']is not None and None not in r['x']];p=len(rows[0]['x'])if rows else 0\n if not use:return dict(defined=False,pred=[None]*len(rows),raw=[None]*len(rows),train=[],invariant=[None]*len(rows))\n mass=sum(r['w']for r in use);mu=[sum(r['w']*r['x'][j]for r in use)/mass for j in range(p)];scale=[max(r['x'][j]for r in use)-min(r['x'][j]for r in use)or F(1)for j in range(p)];mean=sum(r['w']*r['y']for r in use)/mass;model={};z=lambda r:[F(1)]+[(x-m)/s for x,m,s in zip(r['x'],mu,scale)]\n if method=='constant':model=dict(mean=mean,parameterCount=1,rank=1,unique=True)\n elif method=='ridge':\n  vectors=[z(r)for r in use];n=p+1;A=[[sum(r['w']*xx[j]*xx[k]for r,xx in zip(use,vectors))/mass+(lam if j==k and j>0 else F(0))for k in range(n)]for j in range(n)];b=[sum(r['w']*r['y']*xx[j]for r,xx in zip(use,vectors))/mass for j in range(n)];theta,rank,null=solve(A,b);objective=sum(r['w']*(dot(xx,theta)-r['y'])**2 for r,xx in zip(use,vectors))/(2*mass)+lam*sum(x*x for x in theta[1:])/2;model=dict(lambdaValue=lam,theta=theta,rank=rank,unique=rank==n,nullspace=null,minimumObjective=objective,parameterCount=n)\n else:\n  best=None;total=sum(r['w']*r['y']for r in use);total2=sum(r['w']*r['y']**2 for r in use);base=total2-total**2/mass\n  for j in range(p):\n   ordered=sorted(enumerate(use),key=lambda v:(v[1]['x'][j],v[0]));leftW=F(0);leftS=F(0)\n   for i,(_idx,r)in enumerate(ordered[:-1]):\n    leftW+=r['w'];leftS+=r['w']*r['y'];rightW=mass-leftW\n    if i+1<minleaf or len(use)-i-1<minleaf or r['x'][j]==ordered[i+1][1]['x'][j]:continue\n    SSE=total2-leftS**2/leftW-(total-leftS)**2/rightW\n    if best is None or SSE<best['weightedSSE']:best=dict(feature=j,threshold=(r['x'][j]+ordered[i+1][1]['x'][j])/2,leftMean=leftS/leftW,rightMean=(total-leftS)/rightW,leftRows=i+1,rightRows=len(use)-i-1,leftWeight=leftW,rightWeight=rightW,weightedSSE=SSE)\n  model=dict(split=False,mean=mean,weightedSSE=base,trainingMSE=base/mass)if best is None or best['weightedSSE']>=base else dict(split=True,**best,trainingMSE=best['weightedSSE']/mass,improvement=(base-best['weightedSSE'])/mass)\n raw=[];invariant=[]\n for r in rows:\n  if None in r['x']:raw.append(None);invariant.append(None);continue\n  if method=='constant':v=mean;iv=True\n  elif method=='ridge':zz=z(r);v=dot(zz,model['theta']);iv=all(dot(zz,nn)==0 for nn in model['nullspace'])\n  else:v=(model['leftMean']if r['x'][model['feature']]<=model['threshold']else model['rightMean'])if model['split']else mean;iv=True\n  raw.append(v);invariant.append(iv)\n pred=[None if x is None else min(F(1),max(F(0),x))if binary else x for x in raw]\n return dict(defined=True,train=[r['id']for r in use],mass=mass,meanX=mu,scales=scale,model=model,pred=pred,raw=raw,invariant=invariant)\n\ndef risk(rows,pred,binary=False,threshold=F(1,2)):\n use=[(r,p)for r,p in zip(rows,pred)if r['w']>0 and r['y']is not None and p is not None and r['role']not in['excluded','unused']];mass=sum((r['w']for r,p in use),F(0));d=dict(rows=len(use),mass=mass)\n if not mass:\n  d.update({k:None for k in ['MSE','MAE','R2']+(['Brier','accuracy','balancedAccuracy','AUROC']if binary else[])});return d\n mean=sum(r['w']*r['y']for r,p in use)/mass;sse=sum(r['w']*(p-r['y'])**2 for r,p in use);sst=sum(r['w']*(r['y']-mean)**2 for r,p in use);d.update(meanY=mean,SSE=sse,SST=sst,MSE=sse/mass,MAE=sum(r['w']*abs(p-r['y'])for r,p in use)/mass,R2=1-sse/sst if sst else None)\n if binary:\n  weights=Counter();num=Counter()\n  for r,p in use:k=('T'if int(p>=threshold)==int(r['y'])else'F')+('P'if p>=threshold else'N');weights[k]+=r['w'];num[k]+=1\n  TP,FP,TN,FN=[weights[k]for k in ['TP','FP','TN','FN']];positive=TP+FN;negative=TN+FP;rate=lambda a,b:a/b if b else None;TPR=rate(TP,positive);TNR=rate(TN,negative)\n  # Pair enumeration is independent of the subject's score-tie-block formula.\n  negatives=[(r,p)for r,p in use if not r['y']];positives=[(r,p)for r,p in use if r['y']];wins=sum((a['w']*b['w']*(F(1)if pa>pb else F(1,2)if pa==pb else F(0))for a,pa in positives for b,pb in negatives),F(0))\n  d.update(Brier=d['MSE'],threshold=threshold,confusionMass={k:weights[k]for k in ['TP','FP','TN','FN']},confusionRows={k:num[k]for k in ['TP','FP','TN','FN']},positiveMass=positive,negativeMass=negative,accuracy=(TP+TN)/mass,positiveRecall=TPR,negativeRecall=TNR,precision=rate(TP,TP+FP),F1=rate(2*TP,2*TP+FP+FN),balancedAccuracy=(TPR+TNR)/2 if TPR is not None and TNR is not None else None,AUROC=rate(wins,positive*negative))\n return d\n\nNATIVE_SHA256={'actual1599-red-wine-original12-fields.csv': '77e9ac73115930d6c43983333a5a57940deefc493affeb17aca478c09c5f6e00', 'actual4898-white-wine-original12-fields.csv': '50d810bbb42b9cc3e87fa4c27a4c0f168e72da09dd812863425ca3873fec28ef', 'actual3613-NLS-original52-fields.csv': '6e1e1895558795435b65f8634252a7589865273a0e69adbd715fcfa04a3c11a1', 'actual3150-churn-original14-fields.csv': '1c0753e434226e769d1015c922121a7d8967df66014e057c4f7543e490f11764'}\n\ndef read_sources(directory,seed):\n def read(name):\n  p=directory/name\n  if hashlib.sha256(p.read_bytes()).hexdigest()!=NATIVE_SHA256[name]:raise ValueError('Native file hash differs: '+name)\n  with p.open(encoding='utf8',newline='')as f:return list(csv.DictReader(f))\n sources={};wine=[]\n for typ,n in [('red',1599),('white',4898)]:\n  table=read(f'actual{n}-{typ}-wine-original12-fields.csv');assert len(table)==n;features=[k for k in table[0]if k not in ['sourceRow','wineType','quality']];assert len(features)==11\n  for r in table:\n   i=int(r['sourceRow']);red='1'if typ=='red'else'0';nativeX=[r[k]for k in features];wine.append(dict(id=f'wine-{typ}-row:{i}',sourceRow=f'{typ}:{i}',originalID=None,group=fingerprint('wine-predictors',[red]+nativeX),cohort=typ,x=list(map(Q,nativeX+[red])),y=Q(r['quality'])))\n sources['country']=wine\n table=read('actual3613-NLS-original52-fields.csv');assert len(table)==3613;sources['person']=[dict(id='nls-row:'+r['sourceRow'],sourceRow=int(r['sourceRow']),originalID=r['id'],group='nls-id:'+r['id'],cohort='schooling-over12'if Q(r['ed76'])>12 else'schooling-at-most12',x=[Q(r['ed76']),Q(r['age76'])],y=Q(r['lwage76']))for r in table]\n table=read('actual3150-churn-original14-fields.csv');assert len(table)==3150;predictors=[k for k in table[0]if k not in ['sourceRow','Churn']];assert len(predictors)==13;sources['company']=[dict(id='customer-row:'+r['sourceRow'],sourceRow=int(r['sourceRow']),originalID=None,group=fingerprint('customer-predictors',[r[k]for k in predictors]),cohort='pay-as-you-go'if r['Tariff Plan']=='1'else'contractual'if r['Tariff Plan']=='2'else'other-native-tariff',x=[Q(r[k])for k in ['Call  Failure','Subscription  Length','Seconds of Use','Age']],y=Q(r['Churn']))for r in table]\n for kind,rows in sources.items():\n  assignments,state,order=split(rows,seed)\n  for r in rows:\n   rank,planned=assignments[r['group']];r.update(w=F(1),splitRank=rank,plannedRole=planned,eligible=r['y']is not None and None not in r['x']);r['role']=planned if r['eligible']else'excluded'\n return sources\n# New ML22 fixed-profile kernels. The public Fraction fitting/source readers are\n# copied by value above this file by the standalone builder; never imported.\ndef fixed_rows(data, prediction_key=None):\n out=[]\n for i,a in enumerate(data):\n  w=Q(a.get('weight','1'))\n  if w is None or w<0:raise ValueError('negative-weight' if w is not None and w<0 else 'missing-weight')\n  out.append(dict(id=a.get('id',str(i)),group=a.get('group',a.get('id',str(i))),cohort=a.get('cohort','all'),role=a.get('role','train'),w=w,x=[Q(v)for v in a.get('x',[])],y=Q(a.get('y'))))\n return out\n\ndef weighted_pair(rows,A,B):\n use=[(r,a,b)for r,a,b in zip(rows,A,B)if r['w']>0 and r['y']is not None and a is not None and b is not None and r['role']not in ['excluded','unused']]\n mass=sum((r['w']for r,a,b in use),F(0));records=[];groups={}\n for r,a,b in use:\n  la=(a-r['y'])**2;lb=(b-r['y'])**2;d=la-lb\n  records.append(dict(id=r['id'],group=r['group'],weight=r['w'],lossA=la,lossB=lb,difference=d))\n  g=groups.setdefault(r['group'],dict(group=r['group'],rows=0,mass=F(0),sum=F(0)));g['rows']+=1;g['mass']+=r['w'];g['sum']+=r['w']*d\n total=sum((g['sum']for g in groups.values()),F(0));mean=total/mass if mass else None;G=len(groups)\n for g in groups.values():g['leaveOut']=(total-g['sum'])/(mass-g['mass'])if mass>g['mass']else None\n leaves=[g['leaveOut']for g in groups.values()if g['leaveOut']is not None]\n proxy=F(G-1,G)*sum((v-sum(leaves,F(0))/G)**2 for v in leaves) if G>1 and len(leaves)==G else None\n return dict(rows=len(use),mass=mass,groupCount=G,meanDifference=mean,minimumLeaveOut=min(leaves)if leaves else None,maximumLeaveOut=max(leaves)if leaves else None,varianceProxy=proxy,groups=list(groups.values()),records=records)\n\ndef run_selection(rows,candidates,criterion,required,binary=False):\n results=[]\n for c,pred in candidates:\n  val=[dict(r,role='excluded')if r['role']!='validation'else r for r in rows]\n  test=[dict(r,role='excluded')if r['role']!='test'else r for r in rows]\n  v=risk(val,pred,binary);t=risk(test,pred,binary);cohort={g:risk([dict(r,role='excluded')if r['role']!='validation'or r['cohort']!=g else r for r in rows],pred,binary)for g in required}\n  values=[cohort[g]['MSE']for g in required]\n  score=v['MSE']if criterion=='mean'else max(values)if values and None not in values else None\n  results.append(dict(id=c,criterion=score,validation=v,test=t,cohorts=cohort))\n eligible=[(i,r['criterion'])for i,r in enumerate(results)if r['criterion']is not None]\n chosen=min(eligible,key=lambda t:(t[1],t[0]))[0]if eligible else None\n return dict(criterion=criterion,selected=results[chosen]['id']if chosen is not None else None,selectedIndex=chosen,candidates=results)\n\ndef fixed_operation(api,a):\n if api=='realdata':\n  kind=a['kind'];rows=read_sources(Path(__file__).parent/'data',a.get('seed',20261104))[kind];binary=kind=='company'\n  defs=[('constant','constant',F(0)),('ridge:1/100','ridge',F(1,100)),('ridge:1/10','ridge',F(1,10)),('ridge:1','ridge',F(1)),('one-split-stump','stump',F(0))]\n  fits=[fit(rows,method,lam,5,binary)for _,method,lam in defs]\n  selection=run_selection(rows,[(d[0],f['pred'])for d,f in zip(defs,fits)],a.get('criterion','mean'),list(dict.fromkeys(r['cohort']for r in rows)),binary)\n  chosen=selection['selectedIndex'];best=fits[chosen];base=fits[0]\n  test=[dict(r,role='excluded')if r['role']!='test'else r for r in rows]\n  paired=weighted_pair(test,best['pred'],base['pred'])\n  records=[dict(id=r['id'],sourceRow=r.get('sourceRow'),originalID=r.get('originalID'),group=r['group'],cohort=r['cohort'],plannedRole=r['plannedRole'],role=r['role'],eligible=r['eligible'],y=r['y'],baselinePrediction=base['pred'][i],selectedPrediction=best['pred'][i],selectedRawPrediction=best['raw'][i],queryInvariant=best['invariant'][i])for i,r in enumerate(rows)]\n  return dict(kind=kind,nativeRows=len(rows),eligibleRows=sum(r['eligible']for r in rows),selection=selection,models=[dict(id=d[0],train=f['train'],mass=f.get('mass'),meanX=f.get('meanX'),scales=f.get('scales'),model=f.get('model'))for d,f in zip(defs,fits)],paired=paired,records=records)\n rows=fixed_rows(a.get('rows',[]));binary=a.get('task')=='binary'\n if api=='split':\n  assignment,state,order=split(rows,a.get('seed',0));records=[dict(id=r['id'],group=r['group'],rank=assignment[r['group']][0],role=assignment[r['group']][1])for r in rows]\n  return dict(state=state,groupOrder=order,records=records,groupCount=len(order))\n if api=='fit':return fit(rows,a.get('method','constant'),Q(a.get('lambda','0')),a.get('minLeafRows',1),binary)\n if api=='evaluate':\n  pred=[Q(r.get('prediction'))for r in a['rows']];threshold=Q(a.get('threshold','1/2'));rr=risk(rows,pred,binary,threshold)\n  records=[]\n  for r,p in zip(rows,pred):\n   valid=r['w']>0 and r['y']is not None and p is not None and r['role']not in ['excluded','unused']\n   records.append(dict(id=r['id'],weight=r['w'],y=r['y'],prediction=p,eligible=valid,loss=(p-r['y'])**2 if valid else None,correct=dict(defined=valid and binary,value=bool(int(p>=threshold)==int(r['y']))if valid and binary else None)))\n  return dict(metrics=rr,records=records)\n if api=='select':return run_selection(rows,[(c['id'],list(map(Q,c['predictions'])))for c in a['candidates']],a.get('criterion','mean'),a.get('requiredCohorts',list(dict.fromkeys(r['cohort']for r in rows))),binary)\n if api=='paired':return weighted_pair(rows,[Q(r.get('predictionA'))for r in a['rows']],[Q(r.get('predictionB'))for r in a['rows']])\n raise ValueError('unknown-api')\n\ndef report_values(api,z):\n summary=[];series=[]\n def add(k,v,u='dimensionless'):summary.append((k,v,u))\n if api=='split':\n  add('groups',z['groupCount'],'groups');add('rows',len(z['records']),'rows');add('finalState',z['state'],'unsigned 32-bit state')\n  series=[('planned role code',[(i,F({'test':0,'validation':1,'train':2}[r['role']]))for i,r in enumerate(z['records'])])]\n elif api=='fit':\n  add('defined',z['defined']);add('trainingRows',len(z['train']),'rows');add('trainingMass',z.get('mass'),'analysis weight mass')\n  model=z.get('model',{});add('modelRank',model.get('rank'),'parameters');add('threshold',model.get('threshold'),'constructed feature units');add('minimumObjective',model.get('minimumObjective'),'constructed squared outcome units')\n  series=[('prediction',list(enumerate(z['pred'])))];\n  if model.get('theta')is not None:\n   for i,v in enumerate(model['theta']):add('theta'+str(i),v,'constructed outcome units per standardized coordinate')\n elif api=='evaluate':\n  for k in ['rows','mass','MSE','MAE','R2','Brier','accuracy','positiveRecall','negativeRecall','precision','F1','balancedAccuracy','AUROC']: \n   if k in z['metrics']:add(k,z['metrics'][k],'rows'if k=='rows'else'analysis weight mass'if k=='mass'else FIXED['unit']if k in ['MSE','Brier']else'constructed outcome units'if k=='MAE'else'dimensionless')\n  series=[('squared loss',[(i,r['loss'])for i,r in enumerate(z['records'])])]\n elif api=='select':\n  add('selectedIndex',z['selectedIndex'],'zero-based candidate index')\n  for i,c in enumerate(z['candidates']):add('criterion'+str(i),c['criterion'],FIXED['unit']);add('testMSE'+str(i),c['test']['MSE'],FIXED['unit'])\n  series=[('validation criterion',[(i,c['criterion'])for i,c in enumerate(z['candidates'])]),('test MSE',[(i,c['test']['MSE'])for i,c in enumerate(z['candidates'])])]\n elif api=='paired':\n  for k in ['rows','mass','groupCount','meanDifference','minimumLeaveOut','maximumLeaveOut','varianceProxy']:add(k,z[k],'rows'if k=='rows'else'groups'if k=='groupCount'else'analysis weight mass'if k=='mass'else FIXED['unit']+' squared'if k=='varianceProxy'else FIXED['unit'])\n  series=[('loss A minus loss B',[(i,r['difference'])for i,r in enumerate(z['records'])])]\n elif api=='realdata':\n  add('nativeRows',z['nativeRows'],'native records');add('eligibleRows',z['eligibleRows'],'complete records');add('selectedIndex',z['selection']['selectedIndex'],'zero-based candidate index')\n  for i,c in enumerate(z['selection']['candidates']):add('validationMSE'+str(i),c['validation']['MSE'],FIXED['unit']);add('testMSE'+str(i),c['test']['MSE'],FIXED['unit'])\n  for k in ['meanDifference','minimumLeaveOut','maximumLeaveOut','varianceProxy']:add(k,z['paired'][k],FIXED['unit']+' squared'if k=='varianceProxy'else FIXED['unit'])\n  best=z['selection']['candidates'][z['selection']['selectedIndex']]['test']\n  for k in ['accuracy','positiveRecall','negativeRecall','precision','balancedAccuracy','AUROC']:\n   if k in best:add(k,best[k])\n  series=[('validation MSE',[(i,c['validation']['MSE'])for i,c in enumerate(z['selection']['candidates'])]),('test MSE',[(i,c['test']['MSE'])for i,c in enumerate(z['selection']['candidates'])])]\n return summary,series\n\n\ndef fixed_svg(points,title):\n good=[p for p in points if p['y'] is not None];xx=[float(p['x'])for p in good];yy=[float(p['y'])for p in good];xmin=min(xx)if xx else 0;xmax=max(xx)if xx else 1;ymin=min([0]+yy);ymax=max([0]+yy)\n if xmin==xmax:xmin-=.5;xmax+=.5\n if ymin==ymax:ymin-=.5;ymax+=.5\n pad=(ymax-ymin)*.08;ymin-=pad;ymax+=pad;X=lambda x:82+(float(x)-xmin)/(xmax-xmin)*608;Y=lambda y:354-(float(y)-ymin)/(ymax-ymin)*290;e=html.escape\n out=['<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"720\" height=\"480\" viewBox=\"0 0 720 480\" role=\"img\" aria-label=\"'+e(title)+'\"><rect width=\"720\" height=\"480\" fill=\"white\"/><g font-family=\"Arial,sans-serif\" font-size=\"13\" fill=\"#18232f\"><text x=\"360\" y=\"25\" text-anchor=\"middle\">'+e(title)+'</text>']\n for j in range(5):\n  y=ymin+(ymax-ymin)*j/4;x=xmin+(xmax-xmin)*j/4;out.append('<line x1=\"82\" y1=\"'+str(Y(y))+'\" x2=\"690\" y2=\"'+str(Y(y))+'\" stroke=\"#e2e8f0\"/><text x=\"73\" y=\"'+str(Y(y)+4)+'\" text-anchor=\"end\">'+format(y,'.3g')+'</text><text x=\"'+str(X(x))+'\" y=\"380\" text-anchor=\"middle\">'+format(x,'.3g')+'</text>')\n series=list(dict.fromkeys(p['series']for p in good))\n for j,s in enumerate(series):\n  pp=[p for p in good if p['series']==s];color=['#0f766e','#c76622','#4f46e5','#b23857'][j%4]\n  for p in pp:out.append('<circle cx=\"'+format(X(p['x']),'.6f')+'\" cy=\"'+format(Y(p['y']),'.6f')+'\" r=\"2.6\" fill=\"'+color+'\"><title>'+e(s+': '+str(p['y']))+'</title></circle>')\n  out.append('<text x=\"'+str(82+(j%2)*310)+'\" y=\"'+str(432+(j//2)*23)+'\" fill=\"'+color+'\">'+e(s)+'</text>')\n out.append('<text x=\"360\" y=\"405\" text-anchor=\"middle\">Declared record / candidate index; units in summary</text></g></svg>');return''.join(out)\n\nFIXED={'api': 'realdata', 'variant': 'person', 'title': 'All 3,613 factual NLS records', 'input': {'kind': 'person', 'seed': 20261104, 'criterion': 'mean'}, 'unit': 'Squared native log-hourly-wage units', 'titleI18n': {'ko': '실제 NLS 전체 3,613행', 'en': 'All 3,613 factual NLS records'}}\n\nOUT=Path(sys.argv[1]);OUT.mkdir(parents=True,exist_ok=False)\nresult=fixed_operation(FIXED['api'],FIXED['input']);summary,series=report_values(FIXED['api'],result)\ndef encode(v):\n if isinstance(v,F):return str(v)\n if isinstance(v,dict):return{k:encode(x)for k,x in v.items()}\n if isinstance(v,(list,tuple)):return[encode(x)for x in v]\n return v\n(OUT/'full.json').write_text(json.dumps(dict(arithmetic='Exact rational author implementation; factual rows, declared group split and finite five-candidate comparison',result=encode(result)),ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\nsummaryRows=[dict(metric=m,value=''if v is None else str(int(v))if isinstance(v,bool)else str(v),unit=u,defined=int(v is not None))for m,v,u in summary]\npoints=[dict(series=name,index=i,x=str(x),y=''if y is None else str(y),defined=int(y is not None))for name,pp in series for i,(x,y)in enumerate(pp)]\nfor name,rows in [('summary',summaryRows),('plot-points',points)]:\n with(OUT/(name+'.csv')).open('w',encoding='utf8',newline='')as f:writer=csv.DictWriter(f,fieldnames=list(rows[0]));writer.writeheader();writer.writerows(rows)\n(OUT/'plot.svg').write_text(fixed_svg([dict(p,x=number(p['x']),y=None if not p['defined']else number(p['y']))for p in points],FIXED['title']),encoding='utf8');print(FIXED['api']+'/'+FIXED['variant'])\n",
        "returnCode": 0,
        "stdout": "realdata/person\r\n",
        "stderr": "",
        "diagnosticScope": "Public projection omits private absolute-path/traceback frames; actual exit and warnings/reason retained. Raw complete streams and commands in private execution proof.",
        "resultFolder": "ml22-code/runs/python-realdata-person",
        "kind": "person",
        "inputFiles": [
          {
            "file": "ml22-code/realdata-person-input.json",
            "sha256": "1b2f34acaccaa946deeb19382972db0a58f0dec48f76499901c61fd766e8348e",
            "scope": "Complete fixed literal input; program embeds the same values"
          },
          {
            "file": "ml22-code/data/actual1599-red-wine-original12-fields.csv",
            "sha256": "77e9ac73115930d6c43983333a5a57940deefc493affeb17aca478c09c5f6e00",
            "scope": "All native rows and original fields; required sibling data file"
          },
          {
            "file": "ml22-code/data/actual3150-churn-original14-fields.csv",
            "sha256": "1c0753e434226e769d1015c922121a7d8967df66014e057c4f7543e490f11764",
            "scope": "All native rows and original fields; required sibling data file"
          },
          {
            "file": "ml22-code/data/actual3613-NLS-original52-fields.csv",
            "sha256": "6e1e1895558795435b65f8634252a7589865273a0e69adbd715fcfa04a3c11a1",
            "scope": "All native rows and original fields; required sibling data file"
          },
          {
            "file": "ml22-code/data/actual4898-white-wine-original12-fields.csv",
            "sha256": "50d810bbb42b9cc3e87fa4c27a4c0f168e72da09dd812863425ca3873fec28ef",
            "scope": "All native rows and original fields; required sibling data file"
          }
        ],
        "files": [
          {
            "file": "ml22-code/runs/python-realdata-person/full.json",
            "sha256": "89bcfde7edee69a815fbd1331a23e97bfa0d9bce195e3b5f6d64cc2b8a6ef190",
            "bytes": 2739639
          },
          {
            "file": "ml22-code/runs/python-realdata-person/plot-points.csv",
            "sha256": "82de2bb0028589647bf3b7c82e086a6762208cd55999b8425bc1a78367a0b90d",
            "bytes": 948
          },
          {
            "file": "ml22-code/runs/python-realdata-person/plot.svg",
            "sha256": "4ee222ff19608b25f401cba15a5c81035a2ae9f88f0b8dbd4a7ac4abdec2c017",
            "bytes": 3108
          },
          {
            "file": "ml22-code/runs/python-realdata-person/summary.csv",
            "sha256": "c3cd996107fc4c7362733b801e034f2de2a12889a6c8759851eac574ba02d034",
            "bytes": 2056
          }
        ],
        "summaryRows": [
          {
            "metric": "nativeRows",
            "value": "3613.0",
            "unit": "native records",
            "defined": "true",
            "rawValue": "3613",
            "arithmetic": "Exact Fraction",
            "exactFraction": "3613",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "eligibleRows",
            "value": "3010.0",
            "unit": "complete records",
            "defined": "true",
            "rawValue": "3010",
            "arithmetic": "Exact Fraction",
            "exactFraction": "3010",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "selectedIndex",
            "value": "1.0",
            "unit": "zero-based candidate index",
            "defined": "true",
            "rawValue": "1",
            "arithmetic": "Exact Fraction",
            "exactFraction": "1",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "validationMSE0",
            "value": "0.19270891465306084",
            "unit": "Squared native log-hourly-wage units",
            "defined": "true",
            "rawValue": "26535986714300132031541/137699840000000000000000",
            "arithmetic": "Exact Fraction",
            "exactFraction": "26535986714300132031541/137699840000000000000000",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "testMSE0",
            "value": "0.18945394707517765",
            "unit": "Squared native log-hourly-wage units",
            "defined": "true",
            "rawValue": "652194454990510789482733/3442496000000000000000000",
            "arithmetic": "Exact Fraction",
            "exactFraction": "652194454990510789482733/3442496000000000000000000",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "validationMSE1",
            "value": "0.1583230793809525",
            "unit": "Squared native log-hourly-wage units",
            "defined": "true",
            "rawValue": "123449889884265196094677049725988859407/779734012040175040817519680000000000000",
            "arithmetic": "Exact Fraction",
            "exactFraction": "123449889884265196094677049725988859407/779734012040175040817519680000000000000",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "testMSE1",
            "value": "0.16116601462121782",
            "unit": "Squared native log-hourly-wage units",
            "defined": "true",
            "rawValue": "2454426234084525081299034014019236440957/15229179922659668765967181250000000000000",
            "arithmetic": "Exact Fraction",
            "exactFraction": "2454426234084525081299034014019236440957/15229179922659668765967181250000000000000",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "validationMSE2",
            "value": "0.173487189674229",
            "unit": "Squared native log-hourly-wage units",
            "defined": "true",
            "rawValue": "52926425126334262034447890785816347301331/305073966704507214797252360000000000000000",
            "arithmetic": "Exact Fraction",
            "exactFraction": "52926425126334262034447890785816347301331/305073966704507214797252360000000000000000",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "testMSE2",
            "value": "0.1718741737309936",
            "unit": "Squared native log-hourly-wage units",
            "defined": "true",
            "rawValue": "8192864992839660639764749554038112081427/47667807297579252312070681250000000000000",
            "arithmetic": "Exact Fraction",
            "exactFraction": "8192864992839660639764749554038112081427/47667807297579252312070681250000000000000",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "validationMSE3",
            "value": "0.18889820168037785",
            "unit": "Squared native log-hourly-wage units",
            "defined": "true",
            "rawValue": "2894471278293040410909439104766320233388184603/15322916007377264082490572495560000000000000000",
            "arithmetic": "Exact Fraction",
            "exactFraction": "2894471278293040410909439104766320233388184603/15322916007377264082490572495560000000000000000",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "testMSE3",
            "value": "0.1858654236294305",
            "unit": "Squared native log-hourly-wage units",
            "defined": "true",
            "rawValue": "445000042960837059973910635159281676044961447/2394205626152697512889151952431250000000000000",
            "arithmetic": "Exact Fraction",
            "exactFraction": "445000042960837059973910635159281676044961447/2394205626152697512889151952431250000000000000",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "validationMSE4",
            "value": "0.17660562905005237",
            "unit": "Squared native log-hourly-wage units",
            "defined": "true",
            "rawValue": "130010340889295671804408697/736161930900000000000000000",
            "arithmetic": "Exact Fraction",
            "exactFraction": "130010340889295671804408697/736161930900000000000000000",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "testMSE4",
            "value": "0.18093471313758677",
            "unit": "Squared native log-hourly-wage units",
            "defined": "true",
            "rawValue": "266394495580406962239907321/1472323861800000000000000000",
            "arithmetic": "Exact Fraction",
            "exactFraction": "266394495580406962239907321/1472323861800000000000000000",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "meanDifference",
            "value": "-0.028287932453959837",
            "unit": "Squared native log-hourly-wage units",
            "defined": "true",
            "rawValue": "-232179611206816603705893356728143564379167/8207726442528158324394944000000000000000000",
            "arithmetic": "Exact Fraction",
            "exactFraction": "-232179611206816603705893356728143564379167/8207726442528158324394944000000000000000000",
            "mathematicallyPositive": false,
            "mathematicallyNegative": true,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "minimumLeaveOut",
            "value": "-0.02894267928146423",
            "unit": "Squared native log-hourly-wage units",
            "defined": "true",
            "rawValue": "-49423902119051413998808422146035577038381/1707647783344784617827136000000000000000000",
            "arithmetic": "Exact Fraction",
            "exactFraction": "-49423902119051413998808422146035577038381/1707647783344784617827136000000000000000000",
            "mathematicallyPositive": false,
            "mathematicallyNegative": true,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "maximumLeaveOut",
            "value": "-0.027187152761044806",
            "unit": "Squared native log-hourly-wage units",
            "defined": "true",
            "rawValue": "-46426081147854201558741813785594173553521/1707647783344784617827136000000000000000000",
            "arithmetic": "Exact Fraction",
            "exactFraction": "-46426081147854201558741813785594173553521/1707647783344784617827136000000000000000000",
            "mathematicallyPositive": false,
            "mathematicallyNegative": true,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "varianceProxy",
            "value": "2.6627624406065672e-05",
            "unit": "Squared native log-hourly-wage units squared",
            "defined": "true",
            "rawValue": "217220044097736676210965748590763022952477030465985267913526134641927411892414799/8157695211002554926031143788745434757226150295536000000000000000000000000000000000000",
            "arithmetic": "Exact Fraction",
            "exactFraction": "217220044097736676210965748590763022952477030465985267913526134641927411892414799/8157695211002554926031143788745434757226150295536000000000000000000000000000000000000",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          }
        ],
        "plotRows": [
          {
            "series": "validation MSE",
            "index": "0",
            "x": "0",
            "y": "26535986714300132031541/137699840000000000000000",
            "defined": true,
            "xExact": "0",
            "yExact": "26535986714300132031541/137699840000000000000000"
          },
          {
            "series": "validation MSE",
            "index": "1",
            "x": "1",
            "y": "123449889884265196094677049725988859407/779734012040175040817519680000000000000",
            "defined": true,
            "xExact": "1",
            "yExact": "123449889884265196094677049725988859407/779734012040175040817519680000000000000"
          },
          {
            "series": "validation MSE",
            "index": "2",
            "x": "2",
            "y": "52926425126334262034447890785816347301331/305073966704507214797252360000000000000000",
            "defined": true,
            "xExact": "2",
            "yExact": "52926425126334262034447890785816347301331/305073966704507214797252360000000000000000"
          },
          {
            "series": "validation MSE",
            "index": "3",
            "x": "3",
            "y": "2894471278293040410909439104766320233388184603/15322916007377264082490572495560000000000000000",
            "defined": true,
            "xExact": "3",
            "yExact": "2894471278293040410909439104766320233388184603/15322916007377264082490572495560000000000000000"
          },
          {
            "series": "validation MSE",
            "index": "4",
            "x": "4",
            "y": "130010340889295671804408697/736161930900000000000000000",
            "defined": true,
            "xExact": "4",
            "yExact": "130010340889295671804408697/736161930900000000000000000"
          },
          {
            "series": "test MSE",
            "index": "0",
            "x": "0",
            "y": "652194454990510789482733/3442496000000000000000000",
            "defined": true,
            "xExact": "0",
            "yExact": "652194454990510789482733/3442496000000000000000000"
          },
          {
            "series": "test MSE",
            "index": "1",
            "x": "1",
            "y": "2454426234084525081299034014019236440957/15229179922659668765967181250000000000000",
            "defined": true,
            "xExact": "1",
            "yExact": "2454426234084525081299034014019236440957/15229179922659668765967181250000000000000"
          },
          {
            "series": "test MSE",
            "index": "2",
            "x": "2",
            "y": "8192864992839660639764749554038112081427/47667807297579252312070681250000000000000",
            "defined": true,
            "xExact": "2",
            "yExact": "8192864992839660639764749554038112081427/47667807297579252312070681250000000000000"
          },
          {
            "series": "test MSE",
            "index": "3",
            "x": "3",
            "y": "445000042960837059973910635159281676044961447/2394205626152697512889151952431250000000000000",
            "defined": true,
            "xExact": "3",
            "yExact": "445000042960837059973910635159281676044961447/2394205626152697512889151952431250000000000000"
          },
          {
            "series": "test MSE",
            "index": "4",
            "x": "4",
            "y": "266394495580406962239907321/1472323861800000000000000000",
            "defined": true,
            "xExact": "4",
            "yExact": "266394495580406962239907321/1472323861800000000000000000"
          }
        ],
        "plotFile": "ml22-code/runs/python-realdata-person/plot.svg",
        "fullResultFile": "ml22-code/runs/python-realdata-person/full.json",
        "arithmeticScope": "Python exact rational versus base-R approximate floating algebra; copied author kernels, not independent oracle.",
        "plotScope": "Original scatter vectors plot every defined declared comparison point, with missing points omitted. Source profiles show candidate risks; all source records remain in the full result and source CSV files.",
        "reproductionScope": "Standalone literal program plus four native CSV files for factual source profiles. No answer/engine/checker imports."
      },
      "company": {
        "api": "realdata",
        "variant": "company",
        "language": "python",
        "title": "All 3,150 factual churn records",
        "titleI18n": {
          "ko": "실제 이탈 전체 3,150행",
          "en": "All 3,150 factual churn records"
        },
        "input": {
          "kind": "company",
          "seed": 20261104,
          "criterion": "mean"
        },
        "expectedFailure": false,
        "codeFile": "ml22-code/realdata-company.py",
        "codeSHA256": "2faf177fade552157010a31580a4d1bf19b92bda1c6f0b59aaaf9dbde52506c4",
        "code": "# ML22 standalone fixed literal. Attribution and arithmetic scope in README.\nimport csv,hashlib,html,json,math,sys,time\nfrom pathlib import Path\nfrom fractions import Fraction as F\nfrom collections import Counter\nsys.set_int_max_str_digits(200000)\nnumber=lambda v:F(str(v))\ndef Q(x):return None if x is None or x in ('','.') else F(str(x))\n\ndef canonical(v):return None if Q(v) is None else str(Q(v))\n\ndef fingerprint(tag,values):return tag+':'+hashlib.sha256(json.dumps([canonical(x)for x in values],separators=(',',':')).encode()).hexdigest()\n\ndef split(rows,seed=20261104,pattern=('test','validation','train','train')):\n order=sorted(set(r['group'] for r in rows));state=seed\n for j in range(len(order)-1,0,-1):state=(1664525*state+1013904223)&0xffffffff;k=state%(j+1);order[k],order[j]=order[j],order[k]\n roles={g:(i,pattern[i%len(pattern)]) for i,g in enumerate(order)}\n return roles,state,order\n\ndef solve(A,b):\n n=len(b);M=[list(row)+[rhs]for row,rhs in zip(A,b)];piv=[];rank=0\n for j in range(n):\n  candidates=[i for i in range(rank,n)if M[i][j]]\n  if not candidates:continue\n  k=max(candidates,key=lambda i:abs(M[i][j]));M[rank],M[k]=M[k],M[rank];v=M[rank][j];M[rank]=[x/v for x in M[rank]]\n  for i in range(n):\n   if i!=rank:\n    v=M[i][j];M[i]=[a-v*b for a,b in zip(M[i],M[rank])]\n  piv.append(j);rank+=1\n x=[F(0)]*n\n for i,j in enumerate(piv):x[j]=M[i][-1]\n null=[]\n for j in range(n):\n  if j not in piv:\n   v=[F(0)]*n;v[j]=F(1)\n   for i,k in enumerate(piv):v[k]=-M[i][j]\n   null.append(v)\n return x,rank,null\n\ndef dot(a,b):return sum((x*y for x,y in zip(a,b)),F(0))\n\ndef fit(rows,method,lam=F(0),minleaf=1,binary=False):\n use=[r for r in rows if r['role']=='train'and r['w']>0 and r['y']is not None and None not in r['x']];p=len(rows[0]['x'])if rows else 0\n if not use:return dict(defined=False,pred=[None]*len(rows),raw=[None]*len(rows),train=[],invariant=[None]*len(rows))\n mass=sum(r['w']for r in use);mu=[sum(r['w']*r['x'][j]for r in use)/mass for j in range(p)];scale=[max(r['x'][j]for r in use)-min(r['x'][j]for r in use)or F(1)for j in range(p)];mean=sum(r['w']*r['y']for r in use)/mass;model={};z=lambda r:[F(1)]+[(x-m)/s for x,m,s in zip(r['x'],mu,scale)]\n if method=='constant':model=dict(mean=mean,parameterCount=1,rank=1,unique=True)\n elif method=='ridge':\n  vectors=[z(r)for r in use];n=p+1;A=[[sum(r['w']*xx[j]*xx[k]for r,xx in zip(use,vectors))/mass+(lam if j==k and j>0 else F(0))for k in range(n)]for j in range(n)];b=[sum(r['w']*r['y']*xx[j]for r,xx in zip(use,vectors))/mass for j in range(n)];theta,rank,null=solve(A,b);objective=sum(r['w']*(dot(xx,theta)-r['y'])**2 for r,xx in zip(use,vectors))/(2*mass)+lam*sum(x*x for x in theta[1:])/2;model=dict(lambdaValue=lam,theta=theta,rank=rank,unique=rank==n,nullspace=null,minimumObjective=objective,parameterCount=n)\n else:\n  best=None;total=sum(r['w']*r['y']for r in use);total2=sum(r['w']*r['y']**2 for r in use);base=total2-total**2/mass\n  for j in range(p):\n   ordered=sorted(enumerate(use),key=lambda v:(v[1]['x'][j],v[0]));leftW=F(0);leftS=F(0)\n   for i,(_idx,r)in enumerate(ordered[:-1]):\n    leftW+=r['w'];leftS+=r['w']*r['y'];rightW=mass-leftW\n    if i+1<minleaf or len(use)-i-1<minleaf or r['x'][j]==ordered[i+1][1]['x'][j]:continue\n    SSE=total2-leftS**2/leftW-(total-leftS)**2/rightW\n    if best is None or SSE<best['weightedSSE']:best=dict(feature=j,threshold=(r['x'][j]+ordered[i+1][1]['x'][j])/2,leftMean=leftS/leftW,rightMean=(total-leftS)/rightW,leftRows=i+1,rightRows=len(use)-i-1,leftWeight=leftW,rightWeight=rightW,weightedSSE=SSE)\n  model=dict(split=False,mean=mean,weightedSSE=base,trainingMSE=base/mass)if best is None or best['weightedSSE']>=base else dict(split=True,**best,trainingMSE=best['weightedSSE']/mass,improvement=(base-best['weightedSSE'])/mass)\n raw=[];invariant=[]\n for r in rows:\n  if None in r['x']:raw.append(None);invariant.append(None);continue\n  if method=='constant':v=mean;iv=True\n  elif method=='ridge':zz=z(r);v=dot(zz,model['theta']);iv=all(dot(zz,nn)==0 for nn in model['nullspace'])\n  else:v=(model['leftMean']if r['x'][model['feature']]<=model['threshold']else model['rightMean'])if model['split']else mean;iv=True\n  raw.append(v);invariant.append(iv)\n pred=[None if x is None else min(F(1),max(F(0),x))if binary else x for x in raw]\n return dict(defined=True,train=[r['id']for r in use],mass=mass,meanX=mu,scales=scale,model=model,pred=pred,raw=raw,invariant=invariant)\n\ndef risk(rows,pred,binary=False,threshold=F(1,2)):\n use=[(r,p)for r,p in zip(rows,pred)if r['w']>0 and r['y']is not None and p is not None and r['role']not in['excluded','unused']];mass=sum((r['w']for r,p in use),F(0));d=dict(rows=len(use),mass=mass)\n if not mass:\n  d.update({k:None for k in ['MSE','MAE','R2']+(['Brier','accuracy','balancedAccuracy','AUROC']if binary else[])});return d\n mean=sum(r['w']*r['y']for r,p in use)/mass;sse=sum(r['w']*(p-r['y'])**2 for r,p in use);sst=sum(r['w']*(r['y']-mean)**2 for r,p in use);d.update(meanY=mean,SSE=sse,SST=sst,MSE=sse/mass,MAE=sum(r['w']*abs(p-r['y'])for r,p in use)/mass,R2=1-sse/sst if sst else None)\n if binary:\n  weights=Counter();num=Counter()\n  for r,p in use:k=('T'if int(p>=threshold)==int(r['y'])else'F')+('P'if p>=threshold else'N');weights[k]+=r['w'];num[k]+=1\n  TP,FP,TN,FN=[weights[k]for k in ['TP','FP','TN','FN']];positive=TP+FN;negative=TN+FP;rate=lambda a,b:a/b if b else None;TPR=rate(TP,positive);TNR=rate(TN,negative)\n  # Pair enumeration is independent of the subject's score-tie-block formula.\n  negatives=[(r,p)for r,p in use if not r['y']];positives=[(r,p)for r,p in use if r['y']];wins=sum((a['w']*b['w']*(F(1)if pa>pb else F(1,2)if pa==pb else F(0))for a,pa in positives for b,pb in negatives),F(0))\n  d.update(Brier=d['MSE'],threshold=threshold,confusionMass={k:weights[k]for k in ['TP','FP','TN','FN']},confusionRows={k:num[k]for k in ['TP','FP','TN','FN']},positiveMass=positive,negativeMass=negative,accuracy=(TP+TN)/mass,positiveRecall=TPR,negativeRecall=TNR,precision=rate(TP,TP+FP),F1=rate(2*TP,2*TP+FP+FN),balancedAccuracy=(TPR+TNR)/2 if TPR is not None and TNR is not None else None,AUROC=rate(wins,positive*negative))\n return d\n\nNATIVE_SHA256={'actual1599-red-wine-original12-fields.csv': '77e9ac73115930d6c43983333a5a57940deefc493affeb17aca478c09c5f6e00', 'actual4898-white-wine-original12-fields.csv': '50d810bbb42b9cc3e87fa4c27a4c0f168e72da09dd812863425ca3873fec28ef', 'actual3613-NLS-original52-fields.csv': '6e1e1895558795435b65f8634252a7589865273a0e69adbd715fcfa04a3c11a1', 'actual3150-churn-original14-fields.csv': '1c0753e434226e769d1015c922121a7d8967df66014e057c4f7543e490f11764'}\n\ndef read_sources(directory,seed):\n def read(name):\n  p=directory/name\n  if hashlib.sha256(p.read_bytes()).hexdigest()!=NATIVE_SHA256[name]:raise ValueError('Native file hash differs: '+name)\n  with p.open(encoding='utf8',newline='')as f:return list(csv.DictReader(f))\n sources={};wine=[]\n for typ,n in [('red',1599),('white',4898)]:\n  table=read(f'actual{n}-{typ}-wine-original12-fields.csv');assert len(table)==n;features=[k for k in table[0]if k not in ['sourceRow','wineType','quality']];assert len(features)==11\n  for r in table:\n   i=int(r['sourceRow']);red='1'if typ=='red'else'0';nativeX=[r[k]for k in features];wine.append(dict(id=f'wine-{typ}-row:{i}',sourceRow=f'{typ}:{i}',originalID=None,group=fingerprint('wine-predictors',[red]+nativeX),cohort=typ,x=list(map(Q,nativeX+[red])),y=Q(r['quality'])))\n sources['country']=wine\n table=read('actual3613-NLS-original52-fields.csv');assert len(table)==3613;sources['person']=[dict(id='nls-row:'+r['sourceRow'],sourceRow=int(r['sourceRow']),originalID=r['id'],group='nls-id:'+r['id'],cohort='schooling-over12'if Q(r['ed76'])>12 else'schooling-at-most12',x=[Q(r['ed76']),Q(r['age76'])],y=Q(r['lwage76']))for r in table]\n table=read('actual3150-churn-original14-fields.csv');assert len(table)==3150;predictors=[k for k in table[0]if k not in ['sourceRow','Churn']];assert len(predictors)==13;sources['company']=[dict(id='customer-row:'+r['sourceRow'],sourceRow=int(r['sourceRow']),originalID=None,group=fingerprint('customer-predictors',[r[k]for k in predictors]),cohort='pay-as-you-go'if r['Tariff Plan']=='1'else'contractual'if r['Tariff Plan']=='2'else'other-native-tariff',x=[Q(r[k])for k in ['Call  Failure','Subscription  Length','Seconds of Use','Age']],y=Q(r['Churn']))for r in table]\n for kind,rows in sources.items():\n  assignments,state,order=split(rows,seed)\n  for r in rows:\n   rank,planned=assignments[r['group']];r.update(w=F(1),splitRank=rank,plannedRole=planned,eligible=r['y']is not None and None not in r['x']);r['role']=planned if r['eligible']else'excluded'\n return sources\n# New ML22 fixed-profile kernels. The public Fraction fitting/source readers are\n# copied by value above this file by the standalone builder; never imported.\ndef fixed_rows(data, prediction_key=None):\n out=[]\n for i,a in enumerate(data):\n  w=Q(a.get('weight','1'))\n  if w is None or w<0:raise ValueError('negative-weight' if w is not None and w<0 else 'missing-weight')\n  out.append(dict(id=a.get('id',str(i)),group=a.get('group',a.get('id',str(i))),cohort=a.get('cohort','all'),role=a.get('role','train'),w=w,x=[Q(v)for v in a.get('x',[])],y=Q(a.get('y'))))\n return out\n\ndef weighted_pair(rows,A,B):\n use=[(r,a,b)for r,a,b in zip(rows,A,B)if r['w']>0 and r['y']is not None and a is not None and b is not None and r['role']not in ['excluded','unused']]\n mass=sum((r['w']for r,a,b in use),F(0));records=[];groups={}\n for r,a,b in use:\n  la=(a-r['y'])**2;lb=(b-r['y'])**2;d=la-lb\n  records.append(dict(id=r['id'],group=r['group'],weight=r['w'],lossA=la,lossB=lb,difference=d))\n  g=groups.setdefault(r['group'],dict(group=r['group'],rows=0,mass=F(0),sum=F(0)));g['rows']+=1;g['mass']+=r['w'];g['sum']+=r['w']*d\n total=sum((g['sum']for g in groups.values()),F(0));mean=total/mass if mass else None;G=len(groups)\n for g in groups.values():g['leaveOut']=(total-g['sum'])/(mass-g['mass'])if mass>g['mass']else None\n leaves=[g['leaveOut']for g in groups.values()if g['leaveOut']is not None]\n proxy=F(G-1,G)*sum((v-sum(leaves,F(0))/G)**2 for v in leaves) if G>1 and len(leaves)==G else None\n return dict(rows=len(use),mass=mass,groupCount=G,meanDifference=mean,minimumLeaveOut=min(leaves)if leaves else None,maximumLeaveOut=max(leaves)if leaves else None,varianceProxy=proxy,groups=list(groups.values()),records=records)\n\ndef run_selection(rows,candidates,criterion,required,binary=False):\n results=[]\n for c,pred in candidates:\n  val=[dict(r,role='excluded')if r['role']!='validation'else r for r in rows]\n  test=[dict(r,role='excluded')if r['role']!='test'else r for r in rows]\n  v=risk(val,pred,binary);t=risk(test,pred,binary);cohort={g:risk([dict(r,role='excluded')if r['role']!='validation'or r['cohort']!=g else r for r in rows],pred,binary)for g in required}\n  values=[cohort[g]['MSE']for g in required]\n  score=v['MSE']if criterion=='mean'else max(values)if values and None not in values else None\n  results.append(dict(id=c,criterion=score,validation=v,test=t,cohorts=cohort))\n eligible=[(i,r['criterion'])for i,r in enumerate(results)if r['criterion']is not None]\n chosen=min(eligible,key=lambda t:(t[1],t[0]))[0]if eligible else None\n return dict(criterion=criterion,selected=results[chosen]['id']if chosen is not None else None,selectedIndex=chosen,candidates=results)\n\ndef fixed_operation(api,a):\n if api=='realdata':\n  kind=a['kind'];rows=read_sources(Path(__file__).parent/'data',a.get('seed',20261104))[kind];binary=kind=='company'\n  defs=[('constant','constant',F(0)),('ridge:1/100','ridge',F(1,100)),('ridge:1/10','ridge',F(1,10)),('ridge:1','ridge',F(1)),('one-split-stump','stump',F(0))]\n  fits=[fit(rows,method,lam,5,binary)for _,method,lam in defs]\n  selection=run_selection(rows,[(d[0],f['pred'])for d,f in zip(defs,fits)],a.get('criterion','mean'),list(dict.fromkeys(r['cohort']for r in rows)),binary)\n  chosen=selection['selectedIndex'];best=fits[chosen];base=fits[0]\n  test=[dict(r,role='excluded')if r['role']!='test'else r for r in rows]\n  paired=weighted_pair(test,best['pred'],base['pred'])\n  records=[dict(id=r['id'],sourceRow=r.get('sourceRow'),originalID=r.get('originalID'),group=r['group'],cohort=r['cohort'],plannedRole=r['plannedRole'],role=r['role'],eligible=r['eligible'],y=r['y'],baselinePrediction=base['pred'][i],selectedPrediction=best['pred'][i],selectedRawPrediction=best['raw'][i],queryInvariant=best['invariant'][i])for i,r in enumerate(rows)]\n  return dict(kind=kind,nativeRows=len(rows),eligibleRows=sum(r['eligible']for r in rows),selection=selection,models=[dict(id=d[0],train=f['train'],mass=f.get('mass'),meanX=f.get('meanX'),scales=f.get('scales'),model=f.get('model'))for d,f in zip(defs,fits)],paired=paired,records=records)\n rows=fixed_rows(a.get('rows',[]));binary=a.get('task')=='binary'\n if api=='split':\n  assignment,state,order=split(rows,a.get('seed',0));records=[dict(id=r['id'],group=r['group'],rank=assignment[r['group']][0],role=assignment[r['group']][1])for r in rows]\n  return dict(state=state,groupOrder=order,records=records,groupCount=len(order))\n if api=='fit':return fit(rows,a.get('method','constant'),Q(a.get('lambda','0')),a.get('minLeafRows',1),binary)\n if api=='evaluate':\n  pred=[Q(r.get('prediction'))for r in a['rows']];threshold=Q(a.get('threshold','1/2'));rr=risk(rows,pred,binary,threshold)\n  records=[]\n  for r,p in zip(rows,pred):\n   valid=r['w']>0 and r['y']is not None and p is not None and r['role']not in ['excluded','unused']\n   records.append(dict(id=r['id'],weight=r['w'],y=r['y'],prediction=p,eligible=valid,loss=(p-r['y'])**2 if valid else None,correct=dict(defined=valid and binary,value=bool(int(p>=threshold)==int(r['y']))if valid and binary else None)))\n  return dict(metrics=rr,records=records)\n if api=='select':return run_selection(rows,[(c['id'],list(map(Q,c['predictions'])))for c in a['candidates']],a.get('criterion','mean'),a.get('requiredCohorts',list(dict.fromkeys(r['cohort']for r in rows))),binary)\n if api=='paired':return weighted_pair(rows,[Q(r.get('predictionA'))for r in a['rows']],[Q(r.get('predictionB'))for r in a['rows']])\n raise ValueError('unknown-api')\n\ndef report_values(api,z):\n summary=[];series=[]\n def add(k,v,u='dimensionless'):summary.append((k,v,u))\n if api=='split':\n  add('groups',z['groupCount'],'groups');add('rows',len(z['records']),'rows');add('finalState',z['state'],'unsigned 32-bit state')\n  series=[('planned role code',[(i,F({'test':0,'validation':1,'train':2}[r['role']]))for i,r in enumerate(z['records'])])]\n elif api=='fit':\n  add('defined',z['defined']);add('trainingRows',len(z['train']),'rows');add('trainingMass',z.get('mass'),'analysis weight mass')\n  model=z.get('model',{});add('modelRank',model.get('rank'),'parameters');add('threshold',model.get('threshold'),'constructed feature units');add('minimumObjective',model.get('minimumObjective'),'constructed squared outcome units')\n  series=[('prediction',list(enumerate(z['pred'])))];\n  if model.get('theta')is not None:\n   for i,v in enumerate(model['theta']):add('theta'+str(i),v,'constructed outcome units per standardized coordinate')\n elif api=='evaluate':\n  for k in ['rows','mass','MSE','MAE','R2','Brier','accuracy','positiveRecall','negativeRecall','precision','F1','balancedAccuracy','AUROC']: \n   if k in z['metrics']:add(k,z['metrics'][k],'rows'if k=='rows'else'analysis weight mass'if k=='mass'else FIXED['unit']if k in ['MSE','Brier']else'constructed outcome units'if k=='MAE'else'dimensionless')\n  series=[('squared loss',[(i,r['loss'])for i,r in enumerate(z['records'])])]\n elif api=='select':\n  add('selectedIndex',z['selectedIndex'],'zero-based candidate index')\n  for i,c in enumerate(z['candidates']):add('criterion'+str(i),c['criterion'],FIXED['unit']);add('testMSE'+str(i),c['test']['MSE'],FIXED['unit'])\n  series=[('validation criterion',[(i,c['criterion'])for i,c in enumerate(z['candidates'])]),('test MSE',[(i,c['test']['MSE'])for i,c in enumerate(z['candidates'])])]\n elif api=='paired':\n  for k in ['rows','mass','groupCount','meanDifference','minimumLeaveOut','maximumLeaveOut','varianceProxy']:add(k,z[k],'rows'if k=='rows'else'groups'if k=='groupCount'else'analysis weight mass'if k=='mass'else FIXED['unit']+' squared'if k=='varianceProxy'else FIXED['unit'])\n  series=[('loss A minus loss B',[(i,r['difference'])for i,r in enumerate(z['records'])])]\n elif api=='realdata':\n  add('nativeRows',z['nativeRows'],'native records');add('eligibleRows',z['eligibleRows'],'complete records');add('selectedIndex',z['selection']['selectedIndex'],'zero-based candidate index')\n  for i,c in enumerate(z['selection']['candidates']):add('validationMSE'+str(i),c['validation']['MSE'],FIXED['unit']);add('testMSE'+str(i),c['test']['MSE'],FIXED['unit'])\n  for k in ['meanDifference','minimumLeaveOut','maximumLeaveOut','varianceProxy']:add(k,z['paired'][k],FIXED['unit']+' squared'if k=='varianceProxy'else FIXED['unit'])\n  best=z['selection']['candidates'][z['selection']['selectedIndex']]['test']\n  for k in ['accuracy','positiveRecall','negativeRecall','precision','balancedAccuracy','AUROC']:\n   if k in best:add(k,best[k])\n  series=[('validation MSE',[(i,c['validation']['MSE'])for i,c in enumerate(z['selection']['candidates'])]),('test MSE',[(i,c['test']['MSE'])for i,c in enumerate(z['selection']['candidates'])])]\n return summary,series\n\n\ndef fixed_svg(points,title):\n good=[p for p in points if p['y'] is not None];xx=[float(p['x'])for p in good];yy=[float(p['y'])for p in good];xmin=min(xx)if xx else 0;xmax=max(xx)if xx else 1;ymin=min([0]+yy);ymax=max([0]+yy)\n if xmin==xmax:xmin-=.5;xmax+=.5\n if ymin==ymax:ymin-=.5;ymax+=.5\n pad=(ymax-ymin)*.08;ymin-=pad;ymax+=pad;X=lambda x:82+(float(x)-xmin)/(xmax-xmin)*608;Y=lambda y:354-(float(y)-ymin)/(ymax-ymin)*290;e=html.escape\n out=['<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"720\" height=\"480\" viewBox=\"0 0 720 480\" role=\"img\" aria-label=\"'+e(title)+'\"><rect width=\"720\" height=\"480\" fill=\"white\"/><g font-family=\"Arial,sans-serif\" font-size=\"13\" fill=\"#18232f\"><text x=\"360\" y=\"25\" text-anchor=\"middle\">'+e(title)+'</text>']\n for j in range(5):\n  y=ymin+(ymax-ymin)*j/4;x=xmin+(xmax-xmin)*j/4;out.append('<line x1=\"82\" y1=\"'+str(Y(y))+'\" x2=\"690\" y2=\"'+str(Y(y))+'\" stroke=\"#e2e8f0\"/><text x=\"73\" y=\"'+str(Y(y)+4)+'\" text-anchor=\"end\">'+format(y,'.3g')+'</text><text x=\"'+str(X(x))+'\" y=\"380\" text-anchor=\"middle\">'+format(x,'.3g')+'</text>')\n series=list(dict.fromkeys(p['series']for p in good))\n for j,s in enumerate(series):\n  pp=[p for p in good if p['series']==s];color=['#0f766e','#c76622','#4f46e5','#b23857'][j%4]\n  for p in pp:out.append('<circle cx=\"'+format(X(p['x']),'.6f')+'\" cy=\"'+format(Y(p['y']),'.6f')+'\" r=\"2.6\" fill=\"'+color+'\"><title>'+e(s+': '+str(p['y']))+'</title></circle>')\n  out.append('<text x=\"'+str(82+(j%2)*310)+'\" y=\"'+str(432+(j//2)*23)+'\" fill=\"'+color+'\">'+e(s)+'</text>')\n out.append('<text x=\"360\" y=\"405\" text-anchor=\"middle\">Declared record / candidate index; units in summary</text></g></svg>');return''.join(out)\n\nFIXED={'api': 'realdata', 'variant': 'company', 'title': 'All 3,150 factual churn records', 'input': {'kind': 'company', 'seed': 20261104, 'criterion': 'mean'}, 'unit': 'One-component Brier loss', 'titleI18n': {'ko': '실제 이탈 전체 3,150행', 'en': 'All 3,150 factual churn records'}}\n\nOUT=Path(sys.argv[1]);OUT.mkdir(parents=True,exist_ok=False)\nresult=fixed_operation(FIXED['api'],FIXED['input']);summary,series=report_values(FIXED['api'],result)\ndef encode(v):\n if isinstance(v,F):return str(v)\n if isinstance(v,dict):return{k:encode(x)for k,x in v.items()}\n if isinstance(v,(list,tuple)):return[encode(x)for x in v]\n return v\n(OUT/'full.json').write_text(json.dumps(dict(arithmetic='Exact rational author implementation; factual rows, declared group split and finite five-candidate comparison',result=encode(result)),ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\nsummaryRows=[dict(metric=m,value=''if v is None else str(int(v))if isinstance(v,bool)else str(v),unit=u,defined=int(v is not None))for m,v,u in summary]\npoints=[dict(series=name,index=i,x=str(x),y=''if y is None else str(y),defined=int(y is not None))for name,pp in series for i,(x,y)in enumerate(pp)]\nfor name,rows in [('summary',summaryRows),('plot-points',points)]:\n with(OUT/(name+'.csv')).open('w',encoding='utf8',newline='')as f:writer=csv.DictWriter(f,fieldnames=list(rows[0]));writer.writeheader();writer.writerows(rows)\n(OUT/'plot.svg').write_text(fixed_svg([dict(p,x=number(p['x']),y=None if not p['defined']else number(p['y']))for p in points],FIXED['title']),encoding='utf8');print(FIXED['api']+'/'+FIXED['variant'])\n",
        "returnCode": 0,
        "stdout": "realdata/company\r\n",
        "stderr": "",
        "diagnosticScope": "Public projection omits private absolute-path/traceback frames; actual exit and warnings/reason retained. Raw complete streams and commands in private execution proof.",
        "resultFolder": "ml22-code/runs/python-realdata-company",
        "kind": "company",
        "inputFiles": [
          {
            "file": "ml22-code/realdata-company-input.json",
            "sha256": "af603911fbcca13a2aa49e482acf3bee8ce91e35ecbf6b645b174f814e1d5c31",
            "scope": "Complete fixed literal input; program embeds the same values"
          },
          {
            "file": "ml22-code/data/actual1599-red-wine-original12-fields.csv",
            "sha256": "77e9ac73115930d6c43983333a5a57940deefc493affeb17aca478c09c5f6e00",
            "scope": "All native rows and original fields; required sibling data file"
          },
          {
            "file": "ml22-code/data/actual3150-churn-original14-fields.csv",
            "sha256": "1c0753e434226e769d1015c922121a7d8967df66014e057c4f7543e490f11764",
            "scope": "All native rows and original fields; required sibling data file"
          },
          {
            "file": "ml22-code/data/actual3613-NLS-original52-fields.csv",
            "sha256": "6e1e1895558795435b65f8634252a7589865273a0e69adbd715fcfa04a3c11a1",
            "scope": "All native rows and original fields; required sibling data file"
          },
          {
            "file": "ml22-code/data/actual4898-white-wine-original12-fields.csv",
            "sha256": "50d810bbb42b9cc3e87fa4c27a4c0f168e72da09dd812863425ca3873fec28ef",
            "scope": "All native rows and original fields; required sibling data file"
          }
        ],
        "files": [
          {
            "file": "ml22-code/runs/python-realdata-company/full.json",
            "sha256": "7221f5bd029b02fce716e44149aa5b07e5817e7f7fa5fb616300a3495e221c4d",
            "bytes": 3008214
          },
          {
            "file": "ml22-code/runs/python-realdata-company/plot-points.csv",
            "sha256": "56d307271d2c2c0c79906d0b00ad1ecffede583fce305ce43d346c273293d02e",
            "bytes": 1106
          },
          {
            "file": "ml22-code/runs/python-realdata-company/plot.svg",
            "sha256": "792f340c7414778cf6ca3e9403437d7f3345c93dff178f85f16d0ee80324f90b",
            "bytes": 3272
          },
          {
            "file": "ml22-code/runs/python-realdata-company/summary.csv",
            "sha256": "cd1aea843cd4f16b63dd54e2c8fefa334119a76839b49ab2d474b9308fc00be0",
            "bytes": 2548
          }
        ],
        "summaryRows": [
          {
            "metric": "nativeRows",
            "value": "3150.0",
            "unit": "native records",
            "defined": "true",
            "rawValue": "3150",
            "arithmetic": "Exact Fraction",
            "exactFraction": "3150",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "eligibleRows",
            "value": "3150.0",
            "unit": "complete records",
            "defined": "true",
            "rawValue": "3150",
            "arithmetic": "Exact Fraction",
            "exactFraction": "3150",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "selectedIndex",
            "value": "1.0",
            "unit": "zero-based candidate index",
            "defined": "true",
            "rawValue": "1",
            "arithmetic": "Exact Fraction",
            "exactFraction": "1",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "validationMSE0",
            "value": "0.12499149938983464",
            "unit": "One-component Brier loss",
            "defined": "true",
            "rawValue": "83102353/664864038",
            "arithmetic": "Exact Fraction",
            "exactFraction": "83102353/664864038",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "testMSE0",
            "value": "0.14213568334634585",
            "unit": "One-component Brier loss",
            "defined": "true",
            "rawValue": "92697452/652175793",
            "arithmetic": "Exact Fraction",
            "exactFraction": "92697452/652175793",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "validationMSE1",
            "value": "0.11116870372046501",
            "unit": "One-component Brier loss",
            "defined": "true",
            "rawValue": "3920872183834245942009661795464032720167435839626426953869419146/35269568256308213808552546180253382178642517944375363893429661753",
            "arithmetic": "Exact Fraction",
            "exactFraction": "3920872183834245942009661795464032720167435839626426953869419146/35269568256308213808552546180253382178642517944375363893429661753",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "testMSE1",
            "value": "0.12441445028437267",
            "unit": "One-component Brier loss",
            "defined": "true",
            "rawValue": "8608605299378373725151029887311431161241906170464773320439311372/69192969785276419456473315788741368090924634440492126111537580691",
            "arithmetic": "Exact Fraction",
            "exactFraction": "8608605299378373725151029887311431161241906170464773320439311372/69192969785276419456473315788741368090924634440492126111537580691",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "validationMSE2",
            "value": "0.11787977575762064",
            "unit": "One-component Brier loss",
            "defined": "true",
            "rawValue": "1083438805857671538472533999320009790884259655625080048276764827/9191049091282563806248475435326655031166729988306136663454504425",
            "arithmetic": "Exact Fraction",
            "exactFraction": "1083438805857671538472533999320009790884259655625080048276764827/9191049091282563806248475435326655031166729988306136663454504425",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "testMSE2",
            "value": "0.13371629262494444",
            "unit": "One-component Brier loss",
            "defined": "true",
            "rawValue": "803692629831510063429181050962534374663506498859818838996933196/6010431594044831802050529737605471610712085513981366723938441825",
            "arithmetic": "Exact Fraction",
            "exactFraction": "803692629831510063429181050962534374663506498859818838996933196/6010431594044831802050529737605471610712085513981366723938441825",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "validationMSE3",
            "value": "0.12370219758680522",
            "unit": "One-component Brier loss",
            "defined": "true",
            "rawValue": "5936396521741433988851538550296894180464053722922996589474653129855/47989418438388712992631765897753854663366128706953329144984626946824",
            "arithmetic": "Exact Fraction",
            "exactFraction": "5936396521741433988851538550296894180464053722922996589474653129855/47989418438388712992631765897753854663366128706953329144984626946824",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "testMSE3",
            "value": "0.14065893189875783",
            "unit": "One-component Brier loss",
            "defined": "true",
            "rawValue": "1103553477974861314036221516757507339596283181348596444512547708861/7845598307039376106301758165218028402344208064686390324593542700594",
            "arithmetic": "Exact Fraction",
            "exactFraction": "1103553477974861314036221516757507339596283181348596444512547708861/7845598307039376106301758165218028402344208064686390324593542700594",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "validationMSE4",
            "value": "0.11125797920842811",
            "unit": "One-component Brier loss",
            "defined": "true",
            "rawValue": "1870307974801/16810551369958",
            "arithmetic": "Exact Fraction",
            "exactFraction": "1870307974801/16810551369958",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "testMSE4",
            "value": "0.13001090422832914",
            "unit": "One-component Brier loss",
            "defined": "true",
            "rawValue": "6431537758804/49469217962739",
            "arithmetic": "Exact Fraction",
            "exactFraction": "6431537758804/49469217962739",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "meanDifference",
            "value": "-0.017721233061973176",
            "unit": "One-component Brier loss",
            "defined": "true",
            "rawValue": "-115245425516935856470321994247537376203338653280099293526365546893224/6503239651208774835455557531036434962761733617158533456845082596405017",
            "arithmetic": "Exact Fraction",
            "exactFraction": "-115245425516935856470321994247537376203338653280099293526365546893224/6503239651208774835455557531036434962761733617158533456845082596405017",
            "mathematicallyPositive": false,
            "mathematicallyNegative": true,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "minimumLeaveOut",
            "value": "-0.018029096391805048",
            "unit": "One-component Brier loss",
            "defined": "true",
            "rawValue": "-29197829610745935176342678969175748654967600263914748699742676350371/1619483804192068441514224443526583025746112651743759304428347417003584",
            "arithmetic": "Exact Fraction",
            "exactFraction": "-29197829610745935176342678969175748654967600263914748699742676350371/1619483804192068441514224443526583025746112651743759304428347417003584",
            "mathematicallyPositive": false,
            "mathematicallyNegative": true,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "maximumLeaveOut",
            "value": "-0.01715639157175262",
            "unit": "One-component Brier loss",
            "defined": "true",
            "rawValue": "-333848112251731077689085543216612649242663833427165803950428374741830/19459110084745322367569353079249099168730634831108607892271861932433689",
            "arithmetic": "Exact Fraction",
            "exactFraction": "-333848112251731077689085543216612649242663833427165803950428374741830/19459110084745322367569353079249099168730634831108607892271861932433689",
            "mathematicallyPositive": false,
            "mathematicallyNegative": true,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "varianceProxy",
            "value": "5.0647335083384074e-06",
            "unit": "One-component Brier loss squared",
            "defined": "true",
            "rawValue": "4527851472844702713241718099183350181105256215817721071699496045403724552625344318816749538132064313520703579389804499051972719893970037277370506177/893995995127917308551718241706858831227418848100204880309374250291985232418600069482901818148988443004205577762371036621323000148097885470453957775155200",
            "arithmetic": "Exact Fraction",
            "exactFraction": "4527851472844702713241718099183350181105256215817721071699496045403724552625344318816749538132064313520703579389804499051972719893970037277370506177/893995995127917308551718241706858831227418848100204880309374250291985232418600069482901818148988443004205577762371036621323000148097885470453957775155200",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "accuracy",
            "value": "0.8287937743190662",
            "unit": "dimensionless",
            "defined": "true",
            "rawValue": "213/257",
            "arithmetic": "Exact Fraction",
            "exactFraction": "213/257",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "positiveRecall",
            "value": "0.0",
            "unit": "dimensionless",
            "defined": "true",
            "rawValue": "0",
            "arithmetic": "Exact Fraction",
            "exactFraction": "0",
            "mathematicallyPositive": false,
            "mathematicallyNegative": false,
            "exactZero": true,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "negativeRecall",
            "value": "1.0",
            "unit": "dimensionless",
            "defined": "true",
            "rawValue": "1",
            "arithmetic": "Exact Fraction",
            "exactFraction": "1",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "precision",
            "value": "",
            "unit": "dimensionless",
            "defined": "false",
            "rawValue": "",
            "arithmetic": "Exact Fraction",
            "exactFraction": null
          },
          {
            "metric": "balancedAccuracy",
            "value": "0.5",
            "unit": "dimensionless",
            "defined": "true",
            "rawValue": "1/2",
            "arithmetic": "Exact Fraction",
            "exactFraction": "1/2",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "AUROC",
            "value": "0.8154194527433964",
            "unit": "dimensionless",
            "defined": "true",
            "rawValue": "68779/84348",
            "arithmetic": "Exact Fraction",
            "exactFraction": "68779/84348",
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          }
        ],
        "plotRows": [
          {
            "series": "validation MSE",
            "index": "0",
            "x": "0",
            "y": "83102353/664864038",
            "defined": true,
            "xExact": "0",
            "yExact": "83102353/664864038"
          },
          {
            "series": "validation MSE",
            "index": "1",
            "x": "1",
            "y": "3920872183834245942009661795464032720167435839626426953869419146/35269568256308213808552546180253382178642517944375363893429661753",
            "defined": true,
            "xExact": "1",
            "yExact": "3920872183834245942009661795464032720167435839626426953869419146/35269568256308213808552546180253382178642517944375363893429661753"
          },
          {
            "series": "validation MSE",
            "index": "2",
            "x": "2",
            "y": "1083438805857671538472533999320009790884259655625080048276764827/9191049091282563806248475435326655031166729988306136663454504425",
            "defined": true,
            "xExact": "2",
            "yExact": "1083438805857671538472533999320009790884259655625080048276764827/9191049091282563806248475435326655031166729988306136663454504425"
          },
          {
            "series": "validation MSE",
            "index": "3",
            "x": "3",
            "y": "5936396521741433988851538550296894180464053722922996589474653129855/47989418438388712992631765897753854663366128706953329144984626946824",
            "defined": true,
            "xExact": "3",
            "yExact": "5936396521741433988851538550296894180464053722922996589474653129855/47989418438388712992631765897753854663366128706953329144984626946824"
          },
          {
            "series": "validation MSE",
            "index": "4",
            "x": "4",
            "y": "1870307974801/16810551369958",
            "defined": true,
            "xExact": "4",
            "yExact": "1870307974801/16810551369958"
          },
          {
            "series": "test MSE",
            "index": "0",
            "x": "0",
            "y": "92697452/652175793",
            "defined": true,
            "xExact": "0",
            "yExact": "92697452/652175793"
          },
          {
            "series": "test MSE",
            "index": "1",
            "x": "1",
            "y": "8608605299378373725151029887311431161241906170464773320439311372/69192969785276419456473315788741368090924634440492126111537580691",
            "defined": true,
            "xExact": "1",
            "yExact": "8608605299378373725151029887311431161241906170464773320439311372/69192969785276419456473315788741368090924634440492126111537580691"
          },
          {
            "series": "test MSE",
            "index": "2",
            "x": "2",
            "y": "803692629831510063429181050962534374663506498859818838996933196/6010431594044831802050529737605471610712085513981366723938441825",
            "defined": true,
            "xExact": "2",
            "yExact": "803692629831510063429181050962534374663506498859818838996933196/6010431594044831802050529737605471610712085513981366723938441825"
          },
          {
            "series": "test MSE",
            "index": "3",
            "x": "3",
            "y": "1103553477974861314036221516757507339596283181348596444512547708861/7845598307039376106301758165218028402344208064686390324593542700594",
            "defined": true,
            "xExact": "3",
            "yExact": "1103553477974861314036221516757507339596283181348596444512547708861/7845598307039376106301758165218028402344208064686390324593542700594"
          },
          {
            "series": "test MSE",
            "index": "4",
            "x": "4",
            "y": "6431537758804/49469217962739",
            "defined": true,
            "xExact": "4",
            "yExact": "6431537758804/49469217962739"
          }
        ],
        "plotFile": "ml22-code/runs/python-realdata-company/plot.svg",
        "fullResultFile": "ml22-code/runs/python-realdata-company/full.json",
        "arithmeticScope": "Python exact rational versus base-R approximate floating algebra; copied author kernels, not independent oracle.",
        "plotScope": "Original scatter vectors plot every defined declared comparison point, with missing points omitted. Source profiles show candidate risks; all source records remain in the full result and source CSV files.",
        "reproductionScope": "Standalone literal program plus four native CSV files for factual source profiles. No answer/engine/checker imports."
      }
    },
    "r": {
      "country": {
        "api": "realdata",
        "variant": "country",
        "language": "r",
        "title": "All 6,497 factual wine records",
        "titleI18n": {
          "ko": "실제 와인 전체 6,497행",
          "en": "All 6,497 factual wine records"
        },
        "input": {
          "kind": "country",
          "seed": 20261104,
          "criterion": "mean"
        },
        "expectedFailure": false,
        "codeFile": "ml22-code/realdata-country.R",
        "codeSHA256": "32c5bf83eff233969524756862a13edbd41e0bbb60ad0caf0127d56104848742",
        "code": "# ML22 standalone; source/public functions copied by value, no source() dependency.\noptions(stringsAsFactors=FALSE,digits=17,warn=1)\nargs0<-commandArgs(trailingOnly=FALSE);script0<-sub('^--file=','',args0[grepl('^--file=',args0)][1]);source_dir<-file.path(dirname(normalizePath(script0)), 'data');seed<-20261104;leaf_min<-5\nnative_hash <- c(\"actual1599-red-wine-original12-fields.csv\"=\"77e9ac73115930d6c43983333a5a57940deefc493affeb17aca478c09c5f6e00\",\"actual4898-white-wine-original12-fields.csv\"=\"50d810bbb42b9cc3e87fa4c27a4c0f168e72da09dd812863425ca3873fec28ef\",\"actual3613-NLS-original52-fields.csv\"=\"6e1e1895558795435b65f8634252a7589865273a0e69adbd715fcfa04a3c11a1\",\"actual3150-churn-original14-fields.csv\"=\"1c0753e434226e769d1015c922121a7d8967df66014e057c4f7543e490f11764\")\nsha256<-getExportedValue('tools','sha256sum')\nread_native<-function(name){f<-file.path(source_dir,name);if(unname(sha256(f))!=native_hash[[name]])stop(paste('Native hash differs',name));read.csv(f,check.names=FALSE,colClasses='character',na.strings=NULL)}\ngcd_small<-function(a,b){while(b!=0){r<-a%%b;a<-b;b<-r};a}\ncanonical<-function(token){\n if(is.na(token)||token%in%c('','.'))return('null')\n if(!grepl('^[+-]?[0-9]+([.][0-9]*)?$',token))stop('Unsupported native fingerprint token')\n neg<-substr(token,1,1)=='-';s<-sub('^[+-]','',token);parts<-strsplit(s,'.',fixed=TRUE)[[1]];dec<-if(length(parts)==2)nchar(parts[2])else 0;n<-as.numeric(gsub('.','',s,fixed=TRUE));d<-10^dec\n # Every native fingerprint numerator/denominator must remain exactly integral\n # in binary64; reject rather than silently rounding a changed future source.\n if(!is.finite(n)||n>2^53||d>2^53)stop('Native canonical integer range exceeded')\n g<-gcd_small(n,d);n<-n/g;d<-d/g;if(neg)n<--n\n out<-sprintf('%.0f',n);if(d!=1)out<-paste0(out,'/',sprintf('%.0f',d));out\n}\nfp_cache<-new.env(hash=TRUE,parent=emptyenv());hash_file<-tempfile('ml22-hash-')\nfingerprint<-function(tag,values){a<-vapply(values,canonical,'');payload<-paste0('[',paste0('\"',a,'\"',collapse=','),']');key<-paste0(tag,':',payload);if(exists(key,fp_cache,inherits=FALSE))return(get(key,fp_cache,inherits=FALSE));con<-file(hash_file,'wb');writeBin(charToRaw(payload),con);close(con);value<-paste0(tag,':',unname(sha256(hash_file)));assign(key,value,fp_cache);value}\nassign_roles<-function(group){order<-sort(unique(group),method='radix');state<-seed;if(length(order)>1)for(j in seq.int(length(order),2)){state<-(1664525*state+1013904223)%%2^32;k<-state%%j+1;order[c(j,k)]<-order[c(k,j)]};rank<-match(group,order)-1;list(rank=rank,planned=c('test','validation','train','train')[rank%%4+1],state=state)}\nrows<-list();X<-list()\nfor(typ in c('red','white')){n<-if(typ=='red')1599 else 4898;d<-read_native(paste0('actual',n,'-',typ,'-wine-original12-fields.csv'));stopifnot(nrow(d)==n);features<-setdiff(names(d),c('sourceRow','wineType','quality'));stopifnot(length(features)==11);red<-if(typ=='red')'1'else'0';group<-vapply(seq_len(n),function(i)fingerprint('wine-predictors',c(red,unlist(d[i,features],use.names=FALSE))),'');r<-data.frame(id=paste0('wine-',typ,'-row:',d$sourceRow),sourceRow=paste0(typ,':',d$sourceRow),originalID='',group=group,cohort=typ,y=as.numeric(d$quality));xx<-cbind(sapply(d[features],as.numeric),as.numeric(red));rows$country<-rbind(rows$country,r);X$country<-rbind(X$country,xx)}\nd<-read_native('actual3613-NLS-original52-fields.csv');stopifnot(nrow(d)==3613);rows$person<-data.frame(id=paste0('nls-row:',d$sourceRow),sourceRow=d$sourceRow,originalID=d$id,group=paste0('nls-id:',d$id),cohort=ifelse(as.numeric(d$ed76)>12,'schooling-over12','schooling-at-most12'),y=as.numeric(ifelse(d$lwage76=='.',NA,d$lwage76)));X$person<-cbind(as.numeric(d$ed76),as.numeric(d$age76))\nd<-read_native('actual3150-churn-original14-fields.csv');stopifnot(nrow(d)==3150,sum(d[['Charge  Amount']]=='10')==7);features<-setdiff(names(d),c('sourceRow','Churn'));group<-vapply(seq_len(nrow(d)),function(i)fingerprint('customer-predictors',unlist(d[i,features],use.names=FALSE)),'');rows$company<-data.frame(id=paste0('customer-row:',d$sourceRow),sourceRow=d$sourceRow,originalID='',group=group,cohort=ifelse(d[['Tariff Plan']]=='1','pay-as-you-go',ifelse(d[['Tariff Plan']]=='2','contractual','other-native-tariff')),y=as.numeric(d$Churn));X$company<-sapply(d[c('Call  Failure','Subscription  Length','Seconds of Use','Age')],as.numeric)\nif(file.exists(hash_file))unlink(hash_file)\n\nfit_model<-function(r,x,method,lambda){\n tr<-which(r$role=='train'&r$eligible);if(!length(tr))stop('No complete positive training rows');y<-r$y[tr];xx<-x[tr,,drop=FALSE];mu<-colMeans(xx);scale<-apply(xx,2,function(v)diff(range(v)));scale[scale==0]<-1;z<-cbind(1,sweep(sweep(x,2,mu,'-'),2,scale,'/'));meanY<-mean(y);model<-list();n<-length(tr)\n if(method=='constant'){model<-list(mean=meanY,parameterCount=1,rank=1,unique=TRUE);raw<-rep(meanY,nrow(r))}\n else if(method=='ridge'){zt<-z[tr,,drop=FALSE];pen<-diag(c(0,rep(lambda,ncol(x))));theta<-drop(solve(crossprod(zt)/n+pen,crossprod(zt,y)/n));raw<-drop(z%*%theta);objective<-mean((y-raw[tr])^2)/2+lambda*sum(theta[-1]^2)/2;model<-list(lambdaValue=lambda,theta=theta,rank=length(theta),unique=TRUE,minimumObjective=objective,parameterCount=length(theta))}\n else{base<-sum((y-meanY)^2);best<-NULL;total<-sum(y);total2<-sum(y*y)\n  for(j in seq_len(ncol(x))){ord<-order(xx[,j],seq_len(n));sx<-xx[ord,j];sy<-y[ord];left<-cumsum(sy)\n   if(n<2*leaf_min)next\n   for(i in seq.int(leaf_min,n-leaf_min)){if(sx[i]==sx[i+1])next;loss<-total2-left[i]^2/i-(total-left[i])^2/(n-i)\n    # Explicit approximate-tie tolerance; exact source JavaScript/Python\n    # contracts are authoritative for general arbitrarily close ties.\n    if(is.null(best)||loss<best$weightedSSE-1e-12*max(1,abs(loss),abs(best$weightedSSE)))best<-list(feature=j-1,threshold=(sx[i]+sx[i+1])/2,leftMean=left[i]/i,rightMean=(total-left[i])/(n-i),leftRows=i,rightRows=n-i,leftWeight=i,rightWeight=n-i,weightedSSE=loss)\n   }\n  }\n  if(is.null(best)||best$weightedSSE>=base-1e-12*max(1,abs(base))){model<-list(split=FALSE,mean=meanY,weightedSSE=base,trainingMSE=base/n);raw<-rep(meanY,nrow(r))}else{model<-c(list(split=TRUE),best,list(trainingMSE=best$weightedSSE/n,improvement=(base-best$weightedSSE)/n));raw<-ifelse(x[,model$feature+1]<=model$threshold,model$leftMean,model$rightMean)}\n }\n pred<-if(r$dataset[1]=='company')pmax(0,pmin(1,raw))else raw;list(meanX=mu,scales=scale,model=model,raw=raw,pred=pred)\n}\n\n# New standalone fixed-profile adapters; native and fit helpers copied by value.\nnum<-function(x){if(is.null(x)||length(x)==0||is.na(x)||x%in%c('','.'))return(NA_real_);if(is.character(x)&&grepl('/',x,fixed=TRUE)){v<-strsplit(x,'/',fixed=TRUE)[[1]];return(as.numeric(v[1])/as.numeric(v[2]))};as.numeric(x)}\nfixedRows<-function(aa){\n rr<-lapply(seq_along(aa),function(i){a<-aa[[i]];w<-num(if(is.null(a$weight))'1'else a$weight);if(is.na(w)||w<0)stop(if(!is.na(w)&&w<0)'negative-weight'else'missing-weight');list(id=if(is.null(a$id))as.character(i-1)else a$id,group=if(is.null(a$group))if(is.null(a$id))as.character(i-1)else a$id else a$group,cohort=if(is.null(a$cohort))'all'else a$cohort,role=if(is.null(a$role))'train'else a$role,w=w,y=num(a$y),x=vapply(a$x,num,0.0))})\n p<-if(length(rr))length(rr[[1]]$x)else 0;xx<-matrix(NA_real_,length(rr),p)\n if(p)for(i in seq_along(rr))xx[i,]<-rr[[i]]$x\n r<-data.frame(id=vapply(rr,`[[`,'','id'),group=vapply(rr,`[[`,'','group'),cohort=vapply(rr,`[[`,'','cohort'),role=vapply(rr,`[[`,'','role'),w=vapply(rr,`[[`,0.0,'w'),y=vapply(rr,`[[`,0.0,'y'));r$eligible<-!is.na(r$y)&rowSums(is.na(xx))==0&r$w>0;list(r=r,x=xx)\n}\nweightedRisk<-function(r,p,binary=FALSE,threshold=.5){\n ii<-which(r$w>0&!is.na(r$y)&!is.na(p)&!r$role%in%c('excluded','unused'));y<-r$y[ii];p<-p[ii];w<-r$w[ii];W<-sum(w);d<-list(rows=length(ii),mass=W,MSE=NA_real_,MAE=NA_real_,R2=NA_real_)\n if(W==0){if(binary)d<-c(d,setNames(rep(list(NA_real_),10),c('Brier','accuracy','positiveRecall','negativeRecall','precision','F1','balancedAccuracy','AUROC','positiveMass','negativeMass')));return(d)}\n mu<-sum(w*y)/W;sse<-sum(w*(p-y)^2);sst<-sum(w*(y-mu)^2);d<-c(d,list(meanY=mu,SSE=sse,SST=sst));d$MSE<-sse/W;d$MAE<-sum(w*abs(p-y))/W;d$R2<-if(sst>0)1-sse/sst else NA_real_\n if(binary){pos<-y==1;yes<-p>=threshold;TP<-sum(w[pos&yes]);FP<-sum(w[!pos&yes]);TN<-sum(w[!pos&!yes]);FN<-sum(w[pos&!yes]);rate<-function(a,b)if(b>0)a/b else NA_real_;tpr<-rate(TP,TP+FN);tnr<-rate(TN,TN+FP);auc<-NA_real_;P<-sum(w[pos]);N<-sum(w[!pos]);if(P>0&&N>0){wins<-sum(vapply(which(pos),function(i)sum(w[i]*w[!pos]*ifelse(p[i]>p[!pos],1,ifelse(p[i]==p[!pos],.5,0))),0.0));auc<-wins/(P*N)};d<-c(d,list(Brier=d$MSE,threshold=threshold,confusionMass=list(TP=TP,FP=FP,TN=TN,FN=FN),confusionRows=list(TP=sum(pos&yes),FP=sum(!pos&yes),TN=sum(!pos&!yes),FN=sum(pos&!yes)),positiveMass=P,negativeMass=N,accuracy=(TP+TN)/W,positiveRecall=tpr,negativeRecall=tnr,precision=rate(TP,TP+FP),F1=rate(2*TP,2*TP+FP+FN),balancedAccuracy=if(is.finite(tpr)&&is.finite(tnr))(tpr+tnr)/2 else NA_real_,AUROC=auc))};d\n}\nweightedPair<-function(r,A,B){\n ii<-which(r$w>0&!is.na(r$y)&!is.na(A)&!is.na(B)&!r$role%in%c('excluded','unused'));rr<-r[ii,,drop=FALSE];la<-(A[ii]-rr$y)^2;lb<-(B[ii]-rr$y)^2;d<-la-lb;W<-sum(rr$w);S<-sum(rr$w*d);mu<-if(W>0)S/W else NA_real_;ids<-unique(rr$group);groups<-lapply(ids,function(g){jj<-which(rr$group==g);wg<-sum(rr$w[jj]);sg<-sum(rr$w[jj]*d[jj]);list(group=g,rows=length(jj),mass=wg,sum=sg,leaveOut=if(W>wg)(S-sg)/(W-wg)else NA_real_)});leaves<-vapply(groups,`[[`,0.0,'leaveOut');G<-length(groups);proxy<-if(G>1&&all(is.finite(leaves)))(G-1)/G*sum((leaves-mean(leaves))^2) else NA_real_\n list(rows=length(ii),mass=W,groupCount=G,meanDifference=mu,minimumLeaveOut=if(any(is.finite(leaves)))min(leaves,na.rm=TRUE)else NA_real_,maximumLeaveOut=if(any(is.finite(leaves)))max(leaves,na.rm=TRUE)else NA_real_,varianceProxy=proxy,groups=groups,records=lapply(seq_along(ii),function(j)list(id=rr$id[j],group=rr$group[j],weight=rr$w[j],lossA=la[j],lossB=lb[j],difference=d[j])))\n}\nrunSelection<-function(r,candidates,criterion,required,binary=FALSE){\n out<-lapply(candidates,function(c){v<-r;t<-r;v$role[v$role!='validation']<-'excluded';t$role[t$role!='test']<-'excluded';val<-weightedRisk(v,c$pred,binary);test<-weightedRisk(t,c$pred,binary);co<-setNames(lapply(required,function(g){z<-v;z$role[z$cohort!=g]<-'excluded';weightedRisk(z,c$pred,binary)}),required);vv<-vapply(co,`[[`,0.0,'MSE');score<-if(criterion=='mean')val$MSE else if(length(vv)&&all(is.finite(vv)))max(vv)else NA_real_;list(id=c$id,criterion=score,validation=val,test=test,cohorts=co)})\n scores<-vapply(out,`[[`,0.0,'criterion');eligible<-which(is.finite(scores));k<-if(length(eligible))eligible[which.min(scores[eligible])]else NA_integer_;list(criterion=criterion,selected=if(!is.na(k))out[[k]]$id else NULL,selectedIndex=if(!is.na(k))k-1 else NA_real_,candidates=out)\n}\nfixedOperation<-function(api,a){\n if(api=='realdata'){\n  kind<-a$kind;r<-rows[[kind]];x<-X[[kind]];asgn<-assign_roles(r$group);r$dataset<-kind;r$splitRank<-asgn$rank;r$plannedRole<-asgn$planned;r$eligible<-!is.na(r$y)&rowSums(is.na(x))==0;r$role<-ifelse(r$eligible,r$plannedRole,'excluded');r$w<-1;binary<-kind=='company';leaf_min<<-5\n  defs<-data.frame(id=c('constant','ridge:1/100','ridge:1/10','ridge:1','one-split-stump'),method=c('constant','ridge','ridge','ridge','stump'),lambda=c(0,.01,.1,1,0));fits<-lapply(seq_len(5),function(i)fit_model(r,x,defs$method[i],defs$lambda[i]));candidates<-lapply(seq_len(5),function(i)list(id=defs$id[i],pred=fits[[i]]$pred));selection<-runSelection(r,candidates,a$criterion,unique(r$cohort),binary);k<-selection$selectedIndex+1;best<-fits[[k]];base<-fits[[1]];test<-r;test$role[test$role!='test']<-'excluded';paired<-weightedPair(test,best$pred,base$pred)\n  records<-lapply(seq_len(nrow(r)),function(i)list(id=r$id[i],sourceRow=r$sourceRow[i],originalID=r$originalID[i],group=r$group[i],cohort=r$cohort[i],plannedRole=r$plannedRole[i],role=r$role[i],eligible=r$eligible[i],y=r$y[i],baselinePrediction=base$pred[i],selectedPrediction=best$pred[i],selectedRawPrediction=best$raw[i],queryInvariant=TRUE))\n  return(list(kind=kind,nativeRows=nrow(r),eligibleRows=sum(r$eligible),selection=selection,models=lapply(seq_len(5),function(i)list(id=defs$id[i],train=as.list(r$id[r$role=='train']),mass=sum(r$role=='train'),meanX=fits[[i]]$meanX,scales=fits[[i]]$scales,model=fits[[i]]$model)),paired=paired,records=records))\n }\n f<-fixedRows(a$rows);r<-f$r;x<-f$x;binary<-identical(a$task,'binary')\n if(api=='split'){seed<<-a$seed;asgn<-assign_roles(r$group);return(list(state=asgn$state,groupCount=length(unique(r$group)),records=lapply(seq_len(nrow(r)),function(i)list(id=r$id[i],group=r$group[i],rank=asgn$rank[i],role=asgn$planned[i]))))}\n if(api=='fit'){\n  r$dataset<-if(binary)'company'else'fixed';leaf_min<<-if(is.null(a$minLeafRows))1 else a$minLeafRows;fit<-fit_model(r,x,a$method,if(is.null(a$lambda))0 else num(a$lambda));bad<-rowSums(is.na(x))>0;fit$raw[bad]<-NA_real_;fit$pred[bad]<-NA_real_;fit$defined<-TRUE;fit$train<-as.list(r$id[r$role=='train'&r$eligible]);fit$mass<-sum(r$w[r$role=='train'&r$eligible]);fit$invariant<-ifelse(bad,NA,TRUE);return(fit)\n }\n if(api=='evaluate'){p<-vapply(a$rows,function(v)num(v$prediction),0.0);threshold<-if(is.null(a$threshold)).5 else num(a$threshold);m<-weightedRisk(r,p,binary,threshold);records<-lapply(seq_len(nrow(r)),function(i){valid<-r$w[i]>0&&!is.na(r$y[i])&&!is.na(p[i])&&!r$role[i]%in%c('excluded','unused');list(id=r$id[i],weight=r$w[i],y=r$y[i],prediction=p[i],eligible=valid,loss=if(valid)(p[i]-r$y[i])^2 else NA_real_,correct=list(defined=valid&&binary,value=if(valid&&binary)(p[i]>=threshold)==r$y[i] else NULL))});return(list(metrics=m,records=records))}\n if(api=='select'){cs<-lapply(a$candidates,function(c)list(id=c$id,pred=vapply(c$predictions,num,0.0)));return(runSelection(r,cs,a$criterion,unlist(a$requiredCohorts),binary))}\n if(api=='paired')return(weightedPair(r,vapply(a$rows,function(v)num(v$predictionA),0.0),vapply(a$rows,function(v)num(v$predictionB),0.0)))\n stop('unknown-api')\n}\nreportValues<-function(api,z){\n ss<-list();pp<-list();add<-function(k,v,u='dimensionless')ss[[length(ss)+1]]<<-list(metric=k,value=if(is.null(v)||length(v)==0||is.na(v))NULL else unname(v),unit=u);series<-function(name,values){for(i in seq_along(values))pp[[length(pp)+1]]<<-list(series=name,index=i-1,x=i-1,y=if(is.null(values[[i]])||is.na(values[[i]]))NULL else unname(values[[i]]))}\n if(api=='split'){add('groups',z$groupCount,'groups');add('rows',length(z$records),'rows');add('finalState',z$state,'unsigned 32-bit state');series('planned role code',lapply(z$records,function(r)switch(r$role,test=0,validation=1,train=2)))}\n if(api=='fit'){add('defined',z$defined);add('trainingRows',length(z$train),'rows');add('trainingMass',z$mass,'analysis weight mass');add('modelRank',z$model$rank,'parameters');add('threshold',z$model$threshold,'constructed feature units');add('minimumObjective',z$model$minimumObjective,'constructed squared outcome units');series('prediction',as.list(z$pred));if(!is.null(z$model$theta))for(i in seq_along(z$model$theta))add(paste0('theta',i-1),z$model$theta[i],'constructed outcome units per standardized coordinate')}\n if(api=='evaluate'){for(k in c('rows','mass','MSE','MAE','R2','Brier','accuracy','positiveRecall','negativeRecall','precision','F1','balancedAccuracy','AUROC'))if(k%in%names(z$metrics))add(k,z$metrics[[k]],if(k=='rows')'rows'else if(k=='mass')'analysis weight mass'else if(k%in%c('MSE','Brier'))FIXED$unit else if(k=='MAE')'constructed outcome units'else'dimensionless');series('squared loss',lapply(z$records,`[[`,'loss'))}\n if(api=='select'){add('selectedIndex',z$selectedIndex,'zero-based candidate index');for(i in seq_along(z$candidates)){c<-z$candidates[[i]];add(paste0('criterion',i-1),c$criterion,FIXED$unit);add(paste0('testMSE',i-1),c$test$MSE,FIXED$unit)};series('validation criterion',lapply(z$candidates,`[[`,'criterion'));series('test MSE',lapply(z$candidates,function(c)c$test$MSE))}\n if(api=='paired'){for(k in c('rows','mass','groupCount','meanDifference','minimumLeaveOut','maximumLeaveOut','varianceProxy'))add(k,z[[k]],if(k=='rows')'rows'else if(k=='groupCount')'groups'else if(k=='mass')'analysis weight mass'else if(k=='varianceProxy')paste(FIXED$unit,'squared')else FIXED$unit);series('loss A minus loss B',lapply(z$records,`[[`,'difference'))}\n if(api=='realdata'){add('nativeRows',z$nativeRows,'native records');add('eligibleRows',z$eligibleRows,'complete records');add('selectedIndex',z$selection$selectedIndex,'zero-based candidate index');for(i in seq_along(z$selection$candidates)){c<-z$selection$candidates[[i]];add(paste0('validationMSE',i-1),c$validation$MSE,FIXED$unit);add(paste0('testMSE',i-1),c$test$MSE,FIXED$unit)};for(k in c('meanDifference','minimumLeaveOut','maximumLeaveOut','varianceProxy'))add(k,z$paired[[k]],if(k=='varianceProxy')paste(FIXED$unit,'squared')else FIXED$unit);best<-z$selection$candidates[[z$selection$selectedIndex+1]]$test;for(k in c('accuracy','positiveRecall','negativeRecall','precision','balancedAccuracy','AUROC'))if(k%in%names(best))add(k,best[[k]]);series('validation MSE',lapply(z$selection$candidates,function(c)c$validation$MSE));series('test MSE',lapply(z$selection$candidates,function(c)c$test$MSE))}\n list(summary=ss,points=pp)\n}\n\nescapeXML<-function(s){s<-gsub('&','&amp;',s,fixed=TRUE);s<-gsub('<','&lt;',s,fixed=TRUE);s<-gsub('>','&gt;',s,fixed=TRUE);gsub('\"','&quot;',s,fixed=TRUE)}\nsvgPlot<-function(pp,title){\n xx<-vapply(pp,function(p)as.numeric(p$x),numeric(1));yy<-vapply(pp,function(p)as.numeric(p$y),numeric(1));xmin<-if(length(xx))min(xx)else 0;xmax<-if(length(xx))max(xx)else 1;ymin<-min(c(0,yy));ymax<-max(c(0,yy));if(xmin==xmax){xmin<-xmin-.5;xmax<-xmax+.5};if(ymin==ymax){ymin<-ymin-.5;ymax<-ymax+.5};pad<-(ymax-ymin)*.08;ymin<-ymin-pad;ymax<-ymax+pad;X<-function(x)82+(as.numeric(x)-xmin)/(xmax-xmin)*608;Y<-function(y)354-(as.numeric(y)-ymin)/(ymax-ymin)*290\n out<-paste0('<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"720\" height=\"480\" viewBox=\"0 0 720 480\" role=\"img\" aria-label=\"',escapeXML(title),'\"><rect width=\"720\" height=\"480\" fill=\"white\"/><g font-family=\"Arial,sans-serif\" font-size=\"13\" fill=\"#18232f\"><text x=\"360\" y=\"25\" text-anchor=\"middle\">',escapeXML(title),'</text>')\n for(j in 0:4){y<-ymin+(ymax-ymin)*j/4;x<-xmin+(xmax-xmin)*j/4;out<-paste0(out,'<line x1=\"82\" y1=\"',Y(y),'\" x2=\"690\" y2=\"',Y(y),'\" stroke=\"#e2e8f0\"/><text x=\"73\" y=\"',Y(y)+4,'\" text-anchor=\"end\">',sprintf('%.3g',y),'</text><text x=\"',X(x),'\" y=\"380\" text-anchor=\"middle\">',sprintf('%.3g',x),'</text>')}\n ss<-unique(vapply(pp,`[[`,character(1),'series'));cols<-c('#0f766e','#c76622','#4f46e5','#b23857')\n for(j in seq_along(ss)){rr<-Filter(function(p)p$series==ss[j],pp);xy<-vapply(rr,function(p)sprintf('%.6f,%.6f',X(p$x),Y(p$y)),character(1));col<-cols[(j-1)%%4+1];for(p in rr)out<-paste0(out,'<circle cx=\"',sprintf('%.6f',X(p$x)),'\" cy=\"',sprintf('%.6f',Y(p$y)),'\" r=\"2.6\" fill=\"',col,'\"><title>',escapeXML(ss[j]),': ',escapeXML(p$y),'</title></circle>');out<-paste0(out,'<text x=\"',82+((j-1)%%2)*310,'\" y=\"',432+floor((j-1)/2)*23,'\" fill=\"',col,'\">',escapeXML(ss[j]),'</text>')}\n paste0(out,'<text x=\"360\" y=\"405\" text-anchor=\"middle\">Declared record / candidate index; fixed example</text></g></svg>')\n}\ntoJSON<-function(x){\n if(is.null(x))return('null');if(is.list(x)){v<-vapply(x,toJSON,character(1));if(!is.null(names(x)))paste0('{',paste(paste0(vapply(names(x),toJSON,character(1)),':',v),collapse=','),'}')else paste0('[',paste(v,collapse=','),']')}\n else if(length(x)!=1){if(!is.numeric(x)&&!is.null(names(x)))toJSON(as.list(x))else paste0('[',paste(vapply(as.list(x),toJSON,character(1)),collapse=','),']')}\n else if(is.na(x))'null'else if(is.logical(x))if(x)'true'else'false'else if(is.numeric(x))if(is.finite(x))sprintf('%.17g',x)else'null'else paste0('\"',gsub('\\n','\\\\n',gsub('\"','\\\\\"',gsub('\\\\','\\\\\\\\',x,fixed=TRUE),fixed=TRUE),fixed=TRUE),'\"')\n}\n\nFIXED<-list(`api`=\"realdata\",`variant`=\"country\",`title`=\"All 6,497 factual wine records\",`input`=list(`kind`=\"country\",`seed`=20261104,`criterion`=\"mean\"),`unit`=\"Squared native quality-score units\",`titleI18n`=list(`ko`=\"실제 와인 전체 6,497행\",`en`=\"All 6,497 factual wine records\"))\n\nargs<-commandArgs(trailingOnly=TRUE);out<-if(length(args))args[1]else stop('NEW output directory required');if(dir.exists(out))stop('Preserve previous output directory');dir.create(out,recursive=TRUE)\nz<-fixedOperation(FIXED$api,FIXED$input);rr<-reportValues(FIXED$api,z)\nwriteLines(toJSON(list(arithmetic='BaseR binary64 author counterpart; native group hashing exact within declared integer range, stump approximate tie tolerance1e-12; not an independent exact oracle',result=z)),file.path(out,'full.json'),useBytes=TRUE)\nsums<-do.call(rbind,lapply(rr$summary,function(row)data.frame(metric=row$metric,value=if(is.null(row$value))''else if(is.logical(row$value))as.character(as.integer(row$value))else format(row$value,digits=17,scientific=NA,trim=TRUE),unit=row$unit,defined=as.integer(!is.null(row$value)),stringsAsFactors=FALSE)))\npoints<-do.call(rbind,lapply(rr$points,function(p)data.frame(series=p$series,index=p$index,x=p$x,y=if(is.null(p$y))NA_real_ else p$y,defined=as.integer(!is.null(p$y)),stringsAsFactors=FALSE)))\nwrite.csv(sums,file.path(out,'summary.csv'),row.names=FALSE,na='');write.csv(points,file.path(out,'plot-points.csv'),row.names=FALSE,na='');writeLines(svgPlot(Filter(function(p)!is.null(p$y),rr$points),FIXED$title),file.path(out,'plot.svg'),useBytes=TRUE);cat(FIXED$api,'/',FIXED$variant,'\\n',sep='')\n",
        "returnCode": 0,
        "stdout": "realdata/country\r\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 ",
        "diagnosticScope": "Public projection omits private absolute-path/traceback frames; actual exit and warnings/reason retained. Raw complete streams and commands in private execution proof.",
        "resultFolder": "ml22-code/runs/r-realdata-country",
        "kind": "country",
        "inputFiles": [
          {
            "file": "ml22-code/realdata-country-input.json",
            "sha256": "d2f3e8a3424de26a843b6f0be54c0bc6e46fb0091ada2ac12cdf01de88c96282",
            "scope": "Complete fixed literal input; program embeds the same values"
          },
          {
            "file": "ml22-code/data/actual1599-red-wine-original12-fields.csv",
            "sha256": "77e9ac73115930d6c43983333a5a57940deefc493affeb17aca478c09c5f6e00",
            "scope": "All native rows and original fields; required sibling data file"
          },
          {
            "file": "ml22-code/data/actual3150-churn-original14-fields.csv",
            "sha256": "1c0753e434226e769d1015c922121a7d8967df66014e057c4f7543e490f11764",
            "scope": "All native rows and original fields; required sibling data file"
          },
          {
            "file": "ml22-code/data/actual3613-NLS-original52-fields.csv",
            "sha256": "6e1e1895558795435b65f8634252a7589865273a0e69adbd715fcfa04a3c11a1",
            "scope": "All native rows and original fields; required sibling data file"
          },
          {
            "file": "ml22-code/data/actual4898-white-wine-original12-fields.csv",
            "sha256": "50d810bbb42b9cc3e87fa4c27a4c0f168e72da09dd812863425ca3873fec28ef",
            "scope": "All native rows and original fields; required sibling data file"
          }
        ],
        "files": [
          {
            "file": "ml22-code/runs/r-realdata-country/full.json",
            "sha256": "d1fc111dffee9e4e62bff9ed4ef1a7ec014eb7fd86806d7f08d6e09bbdbc9a39",
            "bytes": 3414104
          },
          {
            "file": "ml22-code/runs/r-realdata-country/plot-points.csv",
            "sha256": "eabcda937b0df0f0b6be298b4174e9841219b7f78d8d76e8dd2d83c5711ecf1c",
            "bytes": 426
          },
          {
            "file": "ml22-code/runs/r-realdata-country/plot.svg",
            "sha256": "7d8cb65438ab260ffbd802c74a796927c53c68bca15b5017e31f1e3449049521",
            "bytes": 2530
          },
          {
            "file": "ml22-code/runs/r-realdata-country/summary.csv",
            "sha256": "0e0b7c456b31dc9af84542853595742cbc6bee262f59eb896a4330b0a8197fdb",
            "bytes": 1261
          }
        ],
        "summaryRows": [
          {
            "metric": "nativeRows",
            "value": "6497.0",
            "unit": "native records",
            "defined": "true",
            "rawValue": "6497",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "eligibleRows",
            "value": "6497.0",
            "unit": "complete records",
            "defined": "true",
            "rawValue": "6497",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "selectedIndex",
            "value": "1.0",
            "unit": "zero-based candidate index",
            "defined": "true",
            "rawValue": "1",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "validationMSE0",
            "value": "0.7117725202339443",
            "unit": "Squared native quality-score units",
            "defined": "true",
            "rawValue": "0.71177252023394433",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "testMSE0",
            "value": "0.7705622486123523",
            "unit": "Squared native quality-score units",
            "defined": "true",
            "rawValue": "0.77056224861235234",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "validationMSE1",
            "value": "0.5164888710603188",
            "unit": "Squared native quality-score units",
            "defined": "true",
            "rawValue": "0.51648887106031882",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "testMSE1",
            "value": "0.5665393097643553",
            "unit": "Squared native quality-score units",
            "defined": "true",
            "rawValue": "0.56653930976435529",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "validationMSE2",
            "value": "0.6256699535370389",
            "unit": "Squared native quality-score units",
            "defined": "true",
            "rawValue": "0.62566995353703891",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "testMSE2",
            "value": "0.683376981453588",
            "unit": "Squared native quality-score units",
            "defined": "true",
            "rawValue": "0.68337698145358805",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "validationMSE3",
            "value": "0.6974566904311359",
            "unit": "Squared native quality-score units",
            "defined": "true",
            "rawValue": "0.6974566904311359",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "testMSE3",
            "value": "0.7561259162319727",
            "unit": "Squared native quality-score units",
            "defined": "true",
            "rawValue": "0.75612591623197267",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "validationMSE4",
            "value": "0.5969600181536416",
            "unit": "Squared native quality-score units",
            "defined": "true",
            "rawValue": "0.59696001815364164",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "testMSE4",
            "value": "0.6431173472689219",
            "unit": "Squared native quality-score units",
            "defined": "true",
            "rawValue": "0.64311734726892189",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "meanDifference",
            "value": "-0.20402293884799708",
            "unit": "Squared native quality-score units",
            "defined": "true",
            "rawValue": "-0.20402293884799708",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": false,
            "mathematicallyNegative": true,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "minimumLeaveOut",
            "value": "-0.20647206191326314",
            "unit": "Squared native quality-score units",
            "defined": "true",
            "rawValue": "-0.20647206191326314",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": false,
            "mathematicallyNegative": true,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "maximumLeaveOut",
            "value": "-0.2015329508096836",
            "unit": "Squared native quality-score units",
            "defined": "true",
            "rawValue": "-0.20153295080968359",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": false,
            "mathematicallyNegative": true,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "varianceProxy",
            "value": "0.00021807524742994036",
            "unit": "Squared native quality-score units squared",
            "defined": "true",
            "rawValue": "0.00021807524742994036",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          }
        ],
        "plotRows": [
          {
            "series": "validation MSE",
            "index": "0",
            "x": "0",
            "y": "0.711772520233944",
            "defined": true,
            "xExact": null,
            "yExact": null
          },
          {
            "series": "validation MSE",
            "index": "1",
            "x": "1",
            "y": "0.516488871060319",
            "defined": true,
            "xExact": null,
            "yExact": null
          },
          {
            "series": "validation MSE",
            "index": "2",
            "x": "2",
            "y": "0.625669953537039",
            "defined": true,
            "xExact": null,
            "yExact": null
          },
          {
            "series": "validation MSE",
            "index": "3",
            "x": "3",
            "y": "0.697456690431136",
            "defined": true,
            "xExact": null,
            "yExact": null
          },
          {
            "series": "validation MSE",
            "index": "4",
            "x": "4",
            "y": "0.596960018153642",
            "defined": true,
            "xExact": null,
            "yExact": null
          },
          {
            "series": "test MSE",
            "index": "0",
            "x": "0",
            "y": "0.770562248612352",
            "defined": true,
            "xExact": null,
            "yExact": null
          },
          {
            "series": "test MSE",
            "index": "1",
            "x": "1",
            "y": "0.566539309764355",
            "defined": true,
            "xExact": null,
            "yExact": null
          },
          {
            "series": "test MSE",
            "index": "2",
            "x": "2",
            "y": "0.683376981453588",
            "defined": true,
            "xExact": null,
            "yExact": null
          },
          {
            "series": "test MSE",
            "index": "3",
            "x": "3",
            "y": "0.756125916231973",
            "defined": true,
            "xExact": null,
            "yExact": null
          },
          {
            "series": "test MSE",
            "index": "4",
            "x": "4",
            "y": "0.643117347268922",
            "defined": true,
            "xExact": null,
            "yExact": null
          }
        ],
        "plotFile": "ml22-code/runs/r-realdata-country/plot.svg",
        "fullResultFile": "ml22-code/runs/r-realdata-country/full.json",
        "arithmeticScope": "Python exact rational versus base-R approximate floating algebra; copied author kernels, not independent oracle.",
        "plotScope": "Original scatter vectors plot every defined declared comparison point, with missing points omitted. Source profiles show candidate risks; all source records remain in the full result and source CSV files.",
        "reproductionScope": "Standalone literal program plus four native CSV files for factual source profiles. No answer/engine/checker imports."
      },
      "person": {
        "api": "realdata",
        "variant": "person",
        "language": "r",
        "title": "All 3,613 factual NLS records",
        "titleI18n": {
          "ko": "실제 NLS 전체 3,613행",
          "en": "All 3,613 factual NLS records"
        },
        "input": {
          "kind": "person",
          "seed": 20261104,
          "criterion": "mean"
        },
        "expectedFailure": false,
        "codeFile": "ml22-code/realdata-person.R",
        "codeSHA256": "f366c73a6cb61e9a032d35063a8a0d664d64a2b1cd7cd8b33fce58d49e4d799b",
        "code": "# ML22 standalone; source/public functions copied by value, no source() dependency.\noptions(stringsAsFactors=FALSE,digits=17,warn=1)\nargs0<-commandArgs(trailingOnly=FALSE);script0<-sub('^--file=','',args0[grepl('^--file=',args0)][1]);source_dir<-file.path(dirname(normalizePath(script0)), 'data');seed<-20261104;leaf_min<-5\nnative_hash <- c(\"actual1599-red-wine-original12-fields.csv\"=\"77e9ac73115930d6c43983333a5a57940deefc493affeb17aca478c09c5f6e00\",\"actual4898-white-wine-original12-fields.csv\"=\"50d810bbb42b9cc3e87fa4c27a4c0f168e72da09dd812863425ca3873fec28ef\",\"actual3613-NLS-original52-fields.csv\"=\"6e1e1895558795435b65f8634252a7589865273a0e69adbd715fcfa04a3c11a1\",\"actual3150-churn-original14-fields.csv\"=\"1c0753e434226e769d1015c922121a7d8967df66014e057c4f7543e490f11764\")\nsha256<-getExportedValue('tools','sha256sum')\nread_native<-function(name){f<-file.path(source_dir,name);if(unname(sha256(f))!=native_hash[[name]])stop(paste('Native hash differs',name));read.csv(f,check.names=FALSE,colClasses='character',na.strings=NULL)}\ngcd_small<-function(a,b){while(b!=0){r<-a%%b;a<-b;b<-r};a}\ncanonical<-function(token){\n if(is.na(token)||token%in%c('','.'))return('null')\n if(!grepl('^[+-]?[0-9]+([.][0-9]*)?$',token))stop('Unsupported native fingerprint token')\n neg<-substr(token,1,1)=='-';s<-sub('^[+-]','',token);parts<-strsplit(s,'.',fixed=TRUE)[[1]];dec<-if(length(parts)==2)nchar(parts[2])else 0;n<-as.numeric(gsub('.','',s,fixed=TRUE));d<-10^dec\n # Every native fingerprint numerator/denominator must remain exactly integral\n # in binary64; reject rather than silently rounding a changed future source.\n if(!is.finite(n)||n>2^53||d>2^53)stop('Native canonical integer range exceeded')\n g<-gcd_small(n,d);n<-n/g;d<-d/g;if(neg)n<--n\n out<-sprintf('%.0f',n);if(d!=1)out<-paste0(out,'/',sprintf('%.0f',d));out\n}\nfp_cache<-new.env(hash=TRUE,parent=emptyenv());hash_file<-tempfile('ml22-hash-')\nfingerprint<-function(tag,values){a<-vapply(values,canonical,'');payload<-paste0('[',paste0('\"',a,'\"',collapse=','),']');key<-paste0(tag,':',payload);if(exists(key,fp_cache,inherits=FALSE))return(get(key,fp_cache,inherits=FALSE));con<-file(hash_file,'wb');writeBin(charToRaw(payload),con);close(con);value<-paste0(tag,':',unname(sha256(hash_file)));assign(key,value,fp_cache);value}\nassign_roles<-function(group){order<-sort(unique(group),method='radix');state<-seed;if(length(order)>1)for(j in seq.int(length(order),2)){state<-(1664525*state+1013904223)%%2^32;k<-state%%j+1;order[c(j,k)]<-order[c(k,j)]};rank<-match(group,order)-1;list(rank=rank,planned=c('test','validation','train','train')[rank%%4+1],state=state)}\nrows<-list();X<-list()\nfor(typ in c('red','white')){n<-if(typ=='red')1599 else 4898;d<-read_native(paste0('actual',n,'-',typ,'-wine-original12-fields.csv'));stopifnot(nrow(d)==n);features<-setdiff(names(d),c('sourceRow','wineType','quality'));stopifnot(length(features)==11);red<-if(typ=='red')'1'else'0';group<-vapply(seq_len(n),function(i)fingerprint('wine-predictors',c(red,unlist(d[i,features],use.names=FALSE))),'');r<-data.frame(id=paste0('wine-',typ,'-row:',d$sourceRow),sourceRow=paste0(typ,':',d$sourceRow),originalID='',group=group,cohort=typ,y=as.numeric(d$quality));xx<-cbind(sapply(d[features],as.numeric),as.numeric(red));rows$country<-rbind(rows$country,r);X$country<-rbind(X$country,xx)}\nd<-read_native('actual3613-NLS-original52-fields.csv');stopifnot(nrow(d)==3613);rows$person<-data.frame(id=paste0('nls-row:',d$sourceRow),sourceRow=d$sourceRow,originalID=d$id,group=paste0('nls-id:',d$id),cohort=ifelse(as.numeric(d$ed76)>12,'schooling-over12','schooling-at-most12'),y=as.numeric(ifelse(d$lwage76=='.',NA,d$lwage76)));X$person<-cbind(as.numeric(d$ed76),as.numeric(d$age76))\nd<-read_native('actual3150-churn-original14-fields.csv');stopifnot(nrow(d)==3150,sum(d[['Charge  Amount']]=='10')==7);features<-setdiff(names(d),c('sourceRow','Churn'));group<-vapply(seq_len(nrow(d)),function(i)fingerprint('customer-predictors',unlist(d[i,features],use.names=FALSE)),'');rows$company<-data.frame(id=paste0('customer-row:',d$sourceRow),sourceRow=d$sourceRow,originalID='',group=group,cohort=ifelse(d[['Tariff Plan']]=='1','pay-as-you-go',ifelse(d[['Tariff Plan']]=='2','contractual','other-native-tariff')),y=as.numeric(d$Churn));X$company<-sapply(d[c('Call  Failure','Subscription  Length','Seconds of Use','Age')],as.numeric)\nif(file.exists(hash_file))unlink(hash_file)\n\nfit_model<-function(r,x,method,lambda){\n tr<-which(r$role=='train'&r$eligible);if(!length(tr))stop('No complete positive training rows');y<-r$y[tr];xx<-x[tr,,drop=FALSE];mu<-colMeans(xx);scale<-apply(xx,2,function(v)diff(range(v)));scale[scale==0]<-1;z<-cbind(1,sweep(sweep(x,2,mu,'-'),2,scale,'/'));meanY<-mean(y);model<-list();n<-length(tr)\n if(method=='constant'){model<-list(mean=meanY,parameterCount=1,rank=1,unique=TRUE);raw<-rep(meanY,nrow(r))}\n else if(method=='ridge'){zt<-z[tr,,drop=FALSE];pen<-diag(c(0,rep(lambda,ncol(x))));theta<-drop(solve(crossprod(zt)/n+pen,crossprod(zt,y)/n));raw<-drop(z%*%theta);objective<-mean((y-raw[tr])^2)/2+lambda*sum(theta[-1]^2)/2;model<-list(lambdaValue=lambda,theta=theta,rank=length(theta),unique=TRUE,minimumObjective=objective,parameterCount=length(theta))}\n else{base<-sum((y-meanY)^2);best<-NULL;total<-sum(y);total2<-sum(y*y)\n  for(j in seq_len(ncol(x))){ord<-order(xx[,j],seq_len(n));sx<-xx[ord,j];sy<-y[ord];left<-cumsum(sy)\n   if(n<2*leaf_min)next\n   for(i in seq.int(leaf_min,n-leaf_min)){if(sx[i]==sx[i+1])next;loss<-total2-left[i]^2/i-(total-left[i])^2/(n-i)\n    # Explicit approximate-tie tolerance; exact source JavaScript/Python\n    # contracts are authoritative for general arbitrarily close ties.\n    if(is.null(best)||loss<best$weightedSSE-1e-12*max(1,abs(loss),abs(best$weightedSSE)))best<-list(feature=j-1,threshold=(sx[i]+sx[i+1])/2,leftMean=left[i]/i,rightMean=(total-left[i])/(n-i),leftRows=i,rightRows=n-i,leftWeight=i,rightWeight=n-i,weightedSSE=loss)\n   }\n  }\n  if(is.null(best)||best$weightedSSE>=base-1e-12*max(1,abs(base))){model<-list(split=FALSE,mean=meanY,weightedSSE=base,trainingMSE=base/n);raw<-rep(meanY,nrow(r))}else{model<-c(list(split=TRUE),best,list(trainingMSE=best$weightedSSE/n,improvement=(base-best$weightedSSE)/n));raw<-ifelse(x[,model$feature+1]<=model$threshold,model$leftMean,model$rightMean)}\n }\n pred<-if(r$dataset[1]=='company')pmax(0,pmin(1,raw))else raw;list(meanX=mu,scales=scale,model=model,raw=raw,pred=pred)\n}\n\n# New standalone fixed-profile adapters; native and fit helpers copied by value.\nnum<-function(x){if(is.null(x)||length(x)==0||is.na(x)||x%in%c('','.'))return(NA_real_);if(is.character(x)&&grepl('/',x,fixed=TRUE)){v<-strsplit(x,'/',fixed=TRUE)[[1]];return(as.numeric(v[1])/as.numeric(v[2]))};as.numeric(x)}\nfixedRows<-function(aa){\n rr<-lapply(seq_along(aa),function(i){a<-aa[[i]];w<-num(if(is.null(a$weight))'1'else a$weight);if(is.na(w)||w<0)stop(if(!is.na(w)&&w<0)'negative-weight'else'missing-weight');list(id=if(is.null(a$id))as.character(i-1)else a$id,group=if(is.null(a$group))if(is.null(a$id))as.character(i-1)else a$id else a$group,cohort=if(is.null(a$cohort))'all'else a$cohort,role=if(is.null(a$role))'train'else a$role,w=w,y=num(a$y),x=vapply(a$x,num,0.0))})\n p<-if(length(rr))length(rr[[1]]$x)else 0;xx<-matrix(NA_real_,length(rr),p)\n if(p)for(i in seq_along(rr))xx[i,]<-rr[[i]]$x\n r<-data.frame(id=vapply(rr,`[[`,'','id'),group=vapply(rr,`[[`,'','group'),cohort=vapply(rr,`[[`,'','cohort'),role=vapply(rr,`[[`,'','role'),w=vapply(rr,`[[`,0.0,'w'),y=vapply(rr,`[[`,0.0,'y'));r$eligible<-!is.na(r$y)&rowSums(is.na(xx))==0&r$w>0;list(r=r,x=xx)\n}\nweightedRisk<-function(r,p,binary=FALSE,threshold=.5){\n ii<-which(r$w>0&!is.na(r$y)&!is.na(p)&!r$role%in%c('excluded','unused'));y<-r$y[ii];p<-p[ii];w<-r$w[ii];W<-sum(w);d<-list(rows=length(ii),mass=W,MSE=NA_real_,MAE=NA_real_,R2=NA_real_)\n if(W==0){if(binary)d<-c(d,setNames(rep(list(NA_real_),10),c('Brier','accuracy','positiveRecall','negativeRecall','precision','F1','balancedAccuracy','AUROC','positiveMass','negativeMass')));return(d)}\n mu<-sum(w*y)/W;sse<-sum(w*(p-y)^2);sst<-sum(w*(y-mu)^2);d<-c(d,list(meanY=mu,SSE=sse,SST=sst));d$MSE<-sse/W;d$MAE<-sum(w*abs(p-y))/W;d$R2<-if(sst>0)1-sse/sst else NA_real_\n if(binary){pos<-y==1;yes<-p>=threshold;TP<-sum(w[pos&yes]);FP<-sum(w[!pos&yes]);TN<-sum(w[!pos&!yes]);FN<-sum(w[pos&!yes]);rate<-function(a,b)if(b>0)a/b else NA_real_;tpr<-rate(TP,TP+FN);tnr<-rate(TN,TN+FP);auc<-NA_real_;P<-sum(w[pos]);N<-sum(w[!pos]);if(P>0&&N>0){wins<-sum(vapply(which(pos),function(i)sum(w[i]*w[!pos]*ifelse(p[i]>p[!pos],1,ifelse(p[i]==p[!pos],.5,0))),0.0));auc<-wins/(P*N)};d<-c(d,list(Brier=d$MSE,threshold=threshold,confusionMass=list(TP=TP,FP=FP,TN=TN,FN=FN),confusionRows=list(TP=sum(pos&yes),FP=sum(!pos&yes),TN=sum(!pos&!yes),FN=sum(pos&!yes)),positiveMass=P,negativeMass=N,accuracy=(TP+TN)/W,positiveRecall=tpr,negativeRecall=tnr,precision=rate(TP,TP+FP),F1=rate(2*TP,2*TP+FP+FN),balancedAccuracy=if(is.finite(tpr)&&is.finite(tnr))(tpr+tnr)/2 else NA_real_,AUROC=auc))};d\n}\nweightedPair<-function(r,A,B){\n ii<-which(r$w>0&!is.na(r$y)&!is.na(A)&!is.na(B)&!r$role%in%c('excluded','unused'));rr<-r[ii,,drop=FALSE];la<-(A[ii]-rr$y)^2;lb<-(B[ii]-rr$y)^2;d<-la-lb;W<-sum(rr$w);S<-sum(rr$w*d);mu<-if(W>0)S/W else NA_real_;ids<-unique(rr$group);groups<-lapply(ids,function(g){jj<-which(rr$group==g);wg<-sum(rr$w[jj]);sg<-sum(rr$w[jj]*d[jj]);list(group=g,rows=length(jj),mass=wg,sum=sg,leaveOut=if(W>wg)(S-sg)/(W-wg)else NA_real_)});leaves<-vapply(groups,`[[`,0.0,'leaveOut');G<-length(groups);proxy<-if(G>1&&all(is.finite(leaves)))(G-1)/G*sum((leaves-mean(leaves))^2) else NA_real_\n list(rows=length(ii),mass=W,groupCount=G,meanDifference=mu,minimumLeaveOut=if(any(is.finite(leaves)))min(leaves,na.rm=TRUE)else NA_real_,maximumLeaveOut=if(any(is.finite(leaves)))max(leaves,na.rm=TRUE)else NA_real_,varianceProxy=proxy,groups=groups,records=lapply(seq_along(ii),function(j)list(id=rr$id[j],group=rr$group[j],weight=rr$w[j],lossA=la[j],lossB=lb[j],difference=d[j])))\n}\nrunSelection<-function(r,candidates,criterion,required,binary=FALSE){\n out<-lapply(candidates,function(c){v<-r;t<-r;v$role[v$role!='validation']<-'excluded';t$role[t$role!='test']<-'excluded';val<-weightedRisk(v,c$pred,binary);test<-weightedRisk(t,c$pred,binary);co<-setNames(lapply(required,function(g){z<-v;z$role[z$cohort!=g]<-'excluded';weightedRisk(z,c$pred,binary)}),required);vv<-vapply(co,`[[`,0.0,'MSE');score<-if(criterion=='mean')val$MSE else if(length(vv)&&all(is.finite(vv)))max(vv)else NA_real_;list(id=c$id,criterion=score,validation=val,test=test,cohorts=co)})\n scores<-vapply(out,`[[`,0.0,'criterion');eligible<-which(is.finite(scores));k<-if(length(eligible))eligible[which.min(scores[eligible])]else NA_integer_;list(criterion=criterion,selected=if(!is.na(k))out[[k]]$id else NULL,selectedIndex=if(!is.na(k))k-1 else NA_real_,candidates=out)\n}\nfixedOperation<-function(api,a){\n if(api=='realdata'){\n  kind<-a$kind;r<-rows[[kind]];x<-X[[kind]];asgn<-assign_roles(r$group);r$dataset<-kind;r$splitRank<-asgn$rank;r$plannedRole<-asgn$planned;r$eligible<-!is.na(r$y)&rowSums(is.na(x))==0;r$role<-ifelse(r$eligible,r$plannedRole,'excluded');r$w<-1;binary<-kind=='company';leaf_min<<-5\n  defs<-data.frame(id=c('constant','ridge:1/100','ridge:1/10','ridge:1','one-split-stump'),method=c('constant','ridge','ridge','ridge','stump'),lambda=c(0,.01,.1,1,0));fits<-lapply(seq_len(5),function(i)fit_model(r,x,defs$method[i],defs$lambda[i]));candidates<-lapply(seq_len(5),function(i)list(id=defs$id[i],pred=fits[[i]]$pred));selection<-runSelection(r,candidates,a$criterion,unique(r$cohort),binary);k<-selection$selectedIndex+1;best<-fits[[k]];base<-fits[[1]];test<-r;test$role[test$role!='test']<-'excluded';paired<-weightedPair(test,best$pred,base$pred)\n  records<-lapply(seq_len(nrow(r)),function(i)list(id=r$id[i],sourceRow=r$sourceRow[i],originalID=r$originalID[i],group=r$group[i],cohort=r$cohort[i],plannedRole=r$plannedRole[i],role=r$role[i],eligible=r$eligible[i],y=r$y[i],baselinePrediction=base$pred[i],selectedPrediction=best$pred[i],selectedRawPrediction=best$raw[i],queryInvariant=TRUE))\n  return(list(kind=kind,nativeRows=nrow(r),eligibleRows=sum(r$eligible),selection=selection,models=lapply(seq_len(5),function(i)list(id=defs$id[i],train=as.list(r$id[r$role=='train']),mass=sum(r$role=='train'),meanX=fits[[i]]$meanX,scales=fits[[i]]$scales,model=fits[[i]]$model)),paired=paired,records=records))\n }\n f<-fixedRows(a$rows);r<-f$r;x<-f$x;binary<-identical(a$task,'binary')\n if(api=='split'){seed<<-a$seed;asgn<-assign_roles(r$group);return(list(state=asgn$state,groupCount=length(unique(r$group)),records=lapply(seq_len(nrow(r)),function(i)list(id=r$id[i],group=r$group[i],rank=asgn$rank[i],role=asgn$planned[i]))))}\n if(api=='fit'){\n  r$dataset<-if(binary)'company'else'fixed';leaf_min<<-if(is.null(a$minLeafRows))1 else a$minLeafRows;fit<-fit_model(r,x,a$method,if(is.null(a$lambda))0 else num(a$lambda));bad<-rowSums(is.na(x))>0;fit$raw[bad]<-NA_real_;fit$pred[bad]<-NA_real_;fit$defined<-TRUE;fit$train<-as.list(r$id[r$role=='train'&r$eligible]);fit$mass<-sum(r$w[r$role=='train'&r$eligible]);fit$invariant<-ifelse(bad,NA,TRUE);return(fit)\n }\n if(api=='evaluate'){p<-vapply(a$rows,function(v)num(v$prediction),0.0);threshold<-if(is.null(a$threshold)).5 else num(a$threshold);m<-weightedRisk(r,p,binary,threshold);records<-lapply(seq_len(nrow(r)),function(i){valid<-r$w[i]>0&&!is.na(r$y[i])&&!is.na(p[i])&&!r$role[i]%in%c('excluded','unused');list(id=r$id[i],weight=r$w[i],y=r$y[i],prediction=p[i],eligible=valid,loss=if(valid)(p[i]-r$y[i])^2 else NA_real_,correct=list(defined=valid&&binary,value=if(valid&&binary)(p[i]>=threshold)==r$y[i] else NULL))});return(list(metrics=m,records=records))}\n if(api=='select'){cs<-lapply(a$candidates,function(c)list(id=c$id,pred=vapply(c$predictions,num,0.0)));return(runSelection(r,cs,a$criterion,unlist(a$requiredCohorts),binary))}\n if(api=='paired')return(weightedPair(r,vapply(a$rows,function(v)num(v$predictionA),0.0),vapply(a$rows,function(v)num(v$predictionB),0.0)))\n stop('unknown-api')\n}\nreportValues<-function(api,z){\n ss<-list();pp<-list();add<-function(k,v,u='dimensionless')ss[[length(ss)+1]]<<-list(metric=k,value=if(is.null(v)||length(v)==0||is.na(v))NULL else unname(v),unit=u);series<-function(name,values){for(i in seq_along(values))pp[[length(pp)+1]]<<-list(series=name,index=i-1,x=i-1,y=if(is.null(values[[i]])||is.na(values[[i]]))NULL else unname(values[[i]]))}\n if(api=='split'){add('groups',z$groupCount,'groups');add('rows',length(z$records),'rows');add('finalState',z$state,'unsigned 32-bit state');series('planned role code',lapply(z$records,function(r)switch(r$role,test=0,validation=1,train=2)))}\n if(api=='fit'){add('defined',z$defined);add('trainingRows',length(z$train),'rows');add('trainingMass',z$mass,'analysis weight mass');add('modelRank',z$model$rank,'parameters');add('threshold',z$model$threshold,'constructed feature units');add('minimumObjective',z$model$minimumObjective,'constructed squared outcome units');series('prediction',as.list(z$pred));if(!is.null(z$model$theta))for(i in seq_along(z$model$theta))add(paste0('theta',i-1),z$model$theta[i],'constructed outcome units per standardized coordinate')}\n if(api=='evaluate'){for(k in c('rows','mass','MSE','MAE','R2','Brier','accuracy','positiveRecall','negativeRecall','precision','F1','balancedAccuracy','AUROC'))if(k%in%names(z$metrics))add(k,z$metrics[[k]],if(k=='rows')'rows'else if(k=='mass')'analysis weight mass'else if(k%in%c('MSE','Brier'))FIXED$unit else if(k=='MAE')'constructed outcome units'else'dimensionless');series('squared loss',lapply(z$records,`[[`,'loss'))}\n if(api=='select'){add('selectedIndex',z$selectedIndex,'zero-based candidate index');for(i in seq_along(z$candidates)){c<-z$candidates[[i]];add(paste0('criterion',i-1),c$criterion,FIXED$unit);add(paste0('testMSE',i-1),c$test$MSE,FIXED$unit)};series('validation criterion',lapply(z$candidates,`[[`,'criterion'));series('test MSE',lapply(z$candidates,function(c)c$test$MSE))}\n if(api=='paired'){for(k in c('rows','mass','groupCount','meanDifference','minimumLeaveOut','maximumLeaveOut','varianceProxy'))add(k,z[[k]],if(k=='rows')'rows'else if(k=='groupCount')'groups'else if(k=='mass')'analysis weight mass'else if(k=='varianceProxy')paste(FIXED$unit,'squared')else FIXED$unit);series('loss A minus loss B',lapply(z$records,`[[`,'difference'))}\n if(api=='realdata'){add('nativeRows',z$nativeRows,'native records');add('eligibleRows',z$eligibleRows,'complete records');add('selectedIndex',z$selection$selectedIndex,'zero-based candidate index');for(i in seq_along(z$selection$candidates)){c<-z$selection$candidates[[i]];add(paste0('validationMSE',i-1),c$validation$MSE,FIXED$unit);add(paste0('testMSE',i-1),c$test$MSE,FIXED$unit)};for(k in c('meanDifference','minimumLeaveOut','maximumLeaveOut','varianceProxy'))add(k,z$paired[[k]],if(k=='varianceProxy')paste(FIXED$unit,'squared')else FIXED$unit);best<-z$selection$candidates[[z$selection$selectedIndex+1]]$test;for(k in c('accuracy','positiveRecall','negativeRecall','precision','balancedAccuracy','AUROC'))if(k%in%names(best))add(k,best[[k]]);series('validation MSE',lapply(z$selection$candidates,function(c)c$validation$MSE));series('test MSE',lapply(z$selection$candidates,function(c)c$test$MSE))}\n list(summary=ss,points=pp)\n}\n\nescapeXML<-function(s){s<-gsub('&','&amp;',s,fixed=TRUE);s<-gsub('<','&lt;',s,fixed=TRUE);s<-gsub('>','&gt;',s,fixed=TRUE);gsub('\"','&quot;',s,fixed=TRUE)}\nsvgPlot<-function(pp,title){\n xx<-vapply(pp,function(p)as.numeric(p$x),numeric(1));yy<-vapply(pp,function(p)as.numeric(p$y),numeric(1));xmin<-if(length(xx))min(xx)else 0;xmax<-if(length(xx))max(xx)else 1;ymin<-min(c(0,yy));ymax<-max(c(0,yy));if(xmin==xmax){xmin<-xmin-.5;xmax<-xmax+.5};if(ymin==ymax){ymin<-ymin-.5;ymax<-ymax+.5};pad<-(ymax-ymin)*.08;ymin<-ymin-pad;ymax<-ymax+pad;X<-function(x)82+(as.numeric(x)-xmin)/(xmax-xmin)*608;Y<-function(y)354-(as.numeric(y)-ymin)/(ymax-ymin)*290\n out<-paste0('<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"720\" height=\"480\" viewBox=\"0 0 720 480\" role=\"img\" aria-label=\"',escapeXML(title),'\"><rect width=\"720\" height=\"480\" fill=\"white\"/><g font-family=\"Arial,sans-serif\" font-size=\"13\" fill=\"#18232f\"><text x=\"360\" y=\"25\" text-anchor=\"middle\">',escapeXML(title),'</text>')\n for(j in 0:4){y<-ymin+(ymax-ymin)*j/4;x<-xmin+(xmax-xmin)*j/4;out<-paste0(out,'<line x1=\"82\" y1=\"',Y(y),'\" x2=\"690\" y2=\"',Y(y),'\" stroke=\"#e2e8f0\"/><text x=\"73\" y=\"',Y(y)+4,'\" text-anchor=\"end\">',sprintf('%.3g',y),'</text><text x=\"',X(x),'\" y=\"380\" text-anchor=\"middle\">',sprintf('%.3g',x),'</text>')}\n ss<-unique(vapply(pp,`[[`,character(1),'series'));cols<-c('#0f766e','#c76622','#4f46e5','#b23857')\n for(j in seq_along(ss)){rr<-Filter(function(p)p$series==ss[j],pp);xy<-vapply(rr,function(p)sprintf('%.6f,%.6f',X(p$x),Y(p$y)),character(1));col<-cols[(j-1)%%4+1];for(p in rr)out<-paste0(out,'<circle cx=\"',sprintf('%.6f',X(p$x)),'\" cy=\"',sprintf('%.6f',Y(p$y)),'\" r=\"2.6\" fill=\"',col,'\"><title>',escapeXML(ss[j]),': ',escapeXML(p$y),'</title></circle>');out<-paste0(out,'<text x=\"',82+((j-1)%%2)*310,'\" y=\"',432+floor((j-1)/2)*23,'\" fill=\"',col,'\">',escapeXML(ss[j]),'</text>')}\n paste0(out,'<text x=\"360\" y=\"405\" text-anchor=\"middle\">Declared record / candidate index; fixed example</text></g></svg>')\n}\ntoJSON<-function(x){\n if(is.null(x))return('null');if(is.list(x)){v<-vapply(x,toJSON,character(1));if(!is.null(names(x)))paste0('{',paste(paste0(vapply(names(x),toJSON,character(1)),':',v),collapse=','),'}')else paste0('[',paste(v,collapse=','),']')}\n else if(length(x)!=1){if(!is.numeric(x)&&!is.null(names(x)))toJSON(as.list(x))else paste0('[',paste(vapply(as.list(x),toJSON,character(1)),collapse=','),']')}\n else if(is.na(x))'null'else if(is.logical(x))if(x)'true'else'false'else if(is.numeric(x))if(is.finite(x))sprintf('%.17g',x)else'null'else paste0('\"',gsub('\\n','\\\\n',gsub('\"','\\\\\"',gsub('\\\\','\\\\\\\\',x,fixed=TRUE),fixed=TRUE),fixed=TRUE),'\"')\n}\n\nFIXED<-list(`api`=\"realdata\",`variant`=\"person\",`title`=\"All 3,613 factual NLS records\",`input`=list(`kind`=\"person\",`seed`=20261104,`criterion`=\"mean\"),`unit`=\"Squared native log-hourly-wage units\",`titleI18n`=list(`ko`=\"실제 NLS 전체 3,613행\",`en`=\"All 3,613 factual NLS records\"))\n\nargs<-commandArgs(trailingOnly=TRUE);out<-if(length(args))args[1]else stop('NEW output directory required');if(dir.exists(out))stop('Preserve previous output directory');dir.create(out,recursive=TRUE)\nz<-fixedOperation(FIXED$api,FIXED$input);rr<-reportValues(FIXED$api,z)\nwriteLines(toJSON(list(arithmetic='BaseR binary64 author counterpart; native group hashing exact within declared integer range, stump approximate tie tolerance1e-12; not an independent exact oracle',result=z)),file.path(out,'full.json'),useBytes=TRUE)\nsums<-do.call(rbind,lapply(rr$summary,function(row)data.frame(metric=row$metric,value=if(is.null(row$value))''else if(is.logical(row$value))as.character(as.integer(row$value))else format(row$value,digits=17,scientific=NA,trim=TRUE),unit=row$unit,defined=as.integer(!is.null(row$value)),stringsAsFactors=FALSE)))\npoints<-do.call(rbind,lapply(rr$points,function(p)data.frame(series=p$series,index=p$index,x=p$x,y=if(is.null(p$y))NA_real_ else p$y,defined=as.integer(!is.null(p$y)),stringsAsFactors=FALSE)))\nwrite.csv(sums,file.path(out,'summary.csv'),row.names=FALSE,na='');write.csv(points,file.path(out,'plot-points.csv'),row.names=FALSE,na='');writeLines(svgPlot(Filter(function(p)!is.null(p$y),rr$points),FIXED$title),file.path(out,'plot.svg'),useBytes=TRUE);cat(FIXED$api,'/',FIXED$variant,'\\n',sep='')\n",
        "returnCode": 0,
        "stdout": "realdata/person\r\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 ",
        "diagnosticScope": "Public projection omits private absolute-path/traceback frames; actual exit and warnings/reason retained. Raw complete streams and commands in private execution proof.",
        "resultFolder": "ml22-code/runs/r-realdata-person",
        "kind": "person",
        "inputFiles": [
          {
            "file": "ml22-code/realdata-person-input.json",
            "sha256": "1b2f34acaccaa946deeb19382972db0a58f0dec48f76499901c61fd766e8348e",
            "scope": "Complete fixed literal input; program embeds the same values"
          },
          {
            "file": "ml22-code/data/actual1599-red-wine-original12-fields.csv",
            "sha256": "77e9ac73115930d6c43983333a5a57940deefc493affeb17aca478c09c5f6e00",
            "scope": "All native rows and original fields; required sibling data file"
          },
          {
            "file": "ml22-code/data/actual3150-churn-original14-fields.csv",
            "sha256": "1c0753e434226e769d1015c922121a7d8967df66014e057c4f7543e490f11764",
            "scope": "All native rows and original fields; required sibling data file"
          },
          {
            "file": "ml22-code/data/actual3613-NLS-original52-fields.csv",
            "sha256": "6e1e1895558795435b65f8634252a7589865273a0e69adbd715fcfa04a3c11a1",
            "scope": "All native rows and original fields; required sibling data file"
          },
          {
            "file": "ml22-code/data/actual4898-white-wine-original12-fields.csv",
            "sha256": "50d810bbb42b9cc3e87fa4c27a4c0f168e72da09dd812863425ca3873fec28ef",
            "scope": "All native rows and original fields; required sibling data file"
          }
        ],
        "files": [
          {
            "file": "ml22-code/runs/r-realdata-person/full.json",
            "sha256": "5a5a1461647aa0fac6d9e2a8c99040ed1385f5fbb02bdf8dfcd9615a69be1ee5",
            "bytes": 1500594
          },
          {
            "file": "ml22-code/runs/r-realdata-person/plot-points.csv",
            "sha256": "dc277d14645a007bc9ae977b00f0ae9bda1055b00c6e4002c896ac6e020dc921",
            "bytes": 425
          },
          {
            "file": "ml22-code/runs/r-realdata-person/plot.svg",
            "sha256": "1ebe2627c44b626ff6f9975788dd6e081811c0a49050fd4015b32e9ea2733610",
            "bytes": 2526
          },
          {
            "file": "ml22-code/runs/r-realdata-person/summary.csv",
            "sha256": "2ce55dacb6ed56022861d0bf8eed6270ec43f4164fd4712d451f4e3f82d3f64c",
            "bytes": 1293
          }
        ],
        "summaryRows": [
          {
            "metric": "nativeRows",
            "value": "3613.0",
            "unit": "native records",
            "defined": "true",
            "rawValue": "3613",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "eligibleRows",
            "value": "3010.0",
            "unit": "complete records",
            "defined": "true",
            "rawValue": "3010",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "selectedIndex",
            "value": "1.0",
            "unit": "zero-based candidate index",
            "defined": "true",
            "rawValue": "1",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "validationMSE0",
            "value": "0.19270891465306084",
            "unit": "Squared native log-hourly-wage units",
            "defined": "true",
            "rawValue": "0.19270891465306084",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "testMSE0",
            "value": "0.18945394707517765",
            "unit": "Squared native log-hourly-wage units",
            "defined": "true",
            "rawValue": "0.18945394707517765",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "validationMSE1",
            "value": "0.15832307938095105",
            "unit": "Squared native log-hourly-wage units",
            "defined": "true",
            "rawValue": "0.15832307938095105",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "testMSE1",
            "value": "0.16116601462121713",
            "unit": "Squared native log-hourly-wage units",
            "defined": "true",
            "rawValue": "0.16116601462121713",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "validationMSE2",
            "value": "0.17348718967422805",
            "unit": "Squared native log-hourly-wage units",
            "defined": "true",
            "rawValue": "0.17348718967422805",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "testMSE2",
            "value": "0.1718741737309928",
            "unit": "Squared native log-hourly-wage units",
            "defined": "true",
            "rawValue": "0.17187417373099281",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "validationMSE3",
            "value": "0.18889820168037766",
            "unit": "Squared native log-hourly-wage units",
            "defined": "true",
            "rawValue": "0.18889820168037766",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "testMSE3",
            "value": "0.18586542362943034",
            "unit": "Squared native log-hourly-wage units",
            "defined": "true",
            "rawValue": "0.18586542362943034",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "validationMSE4",
            "value": "0.17660562905005242",
            "unit": "Squared native log-hourly-wage units",
            "defined": "true",
            "rawValue": "0.17660562905005242",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "testMSE4",
            "value": "0.18093471313758677",
            "unit": "Squared native log-hourly-wage units",
            "defined": "true",
            "rawValue": "0.18093471313758677",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "meanDifference",
            "value": "-0.028287932453960527",
            "unit": "Squared native log-hourly-wage units",
            "defined": "true",
            "rawValue": "-0.028287932453960527",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": false,
            "mathematicallyNegative": true,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "minimumLeaveOut",
            "value": "-0.028942679281464934",
            "unit": "Squared native log-hourly-wage units",
            "defined": "true",
            "rawValue": "-0.028942679281464934",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": false,
            "mathematicallyNegative": true,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "maximumLeaveOut",
            "value": "-0.027187152761045434",
            "unit": "Squared native log-hourly-wage units",
            "defined": "true",
            "rawValue": "-0.027187152761045434",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": false,
            "mathematicallyNegative": true,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "varianceProxy",
            "value": "2.6627624406067796e-05",
            "unit": "Squared native log-hourly-wage units squared",
            "defined": "true",
            "rawValue": "2.6627624406067796e-05",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          }
        ],
        "plotRows": [
          {
            "series": "validation MSE",
            "index": "0",
            "x": "0",
            "y": "0.192708914653061",
            "defined": true,
            "xExact": null,
            "yExact": null
          },
          {
            "series": "validation MSE",
            "index": "1",
            "x": "1",
            "y": "0.158323079380951",
            "defined": true,
            "xExact": null,
            "yExact": null
          },
          {
            "series": "validation MSE",
            "index": "2",
            "x": "2",
            "y": "0.173487189674228",
            "defined": true,
            "xExact": null,
            "yExact": null
          },
          {
            "series": "validation MSE",
            "index": "3",
            "x": "3",
            "y": "0.188898201680378",
            "defined": true,
            "xExact": null,
            "yExact": null
          },
          {
            "series": "validation MSE",
            "index": "4",
            "x": "4",
            "y": "0.176605629050052",
            "defined": true,
            "xExact": null,
            "yExact": null
          },
          {
            "series": "test MSE",
            "index": "0",
            "x": "0",
            "y": "0.189453947075178",
            "defined": true,
            "xExact": null,
            "yExact": null
          },
          {
            "series": "test MSE",
            "index": "1",
            "x": "1",
            "y": "0.161166014621217",
            "defined": true,
            "xExact": null,
            "yExact": null
          },
          {
            "series": "test MSE",
            "index": "2",
            "x": "2",
            "y": "0.171874173730993",
            "defined": true,
            "xExact": null,
            "yExact": null
          },
          {
            "series": "test MSE",
            "index": "3",
            "x": "3",
            "y": "0.18586542362943",
            "defined": true,
            "xExact": null,
            "yExact": null
          },
          {
            "series": "test MSE",
            "index": "4",
            "x": "4",
            "y": "0.180934713137587",
            "defined": true,
            "xExact": null,
            "yExact": null
          }
        ],
        "plotFile": "ml22-code/runs/r-realdata-person/plot.svg",
        "fullResultFile": "ml22-code/runs/r-realdata-person/full.json",
        "arithmeticScope": "Python exact rational versus base-R approximate floating algebra; copied author kernels, not independent oracle.",
        "plotScope": "Original scatter vectors plot every defined declared comparison point, with missing points omitted. Source profiles show candidate risks; all source records remain in the full result and source CSV files.",
        "reproductionScope": "Standalone literal program plus four native CSV files for factual source profiles. No answer/engine/checker imports."
      },
      "company": {
        "api": "realdata",
        "variant": "company",
        "language": "r",
        "title": "All 3,150 factual churn records",
        "titleI18n": {
          "ko": "실제 이탈 전체 3,150행",
          "en": "All 3,150 factual churn records"
        },
        "input": {
          "kind": "company",
          "seed": 20261104,
          "criterion": "mean"
        },
        "expectedFailure": false,
        "codeFile": "ml22-code/realdata-company.R",
        "codeSHA256": "4ba4a65088fe2885ba0e41a5bf2b820beaf9584ba89b39805fcd7f2763ad9dd9",
        "code": "# ML22 standalone; source/public functions copied by value, no source() dependency.\noptions(stringsAsFactors=FALSE,digits=17,warn=1)\nargs0<-commandArgs(trailingOnly=FALSE);script0<-sub('^--file=','',args0[grepl('^--file=',args0)][1]);source_dir<-file.path(dirname(normalizePath(script0)), 'data');seed<-20261104;leaf_min<-5\nnative_hash <- c(\"actual1599-red-wine-original12-fields.csv\"=\"77e9ac73115930d6c43983333a5a57940deefc493affeb17aca478c09c5f6e00\",\"actual4898-white-wine-original12-fields.csv\"=\"50d810bbb42b9cc3e87fa4c27a4c0f168e72da09dd812863425ca3873fec28ef\",\"actual3613-NLS-original52-fields.csv\"=\"6e1e1895558795435b65f8634252a7589865273a0e69adbd715fcfa04a3c11a1\",\"actual3150-churn-original14-fields.csv\"=\"1c0753e434226e769d1015c922121a7d8967df66014e057c4f7543e490f11764\")\nsha256<-getExportedValue('tools','sha256sum')\nread_native<-function(name){f<-file.path(source_dir,name);if(unname(sha256(f))!=native_hash[[name]])stop(paste('Native hash differs',name));read.csv(f,check.names=FALSE,colClasses='character',na.strings=NULL)}\ngcd_small<-function(a,b){while(b!=0){r<-a%%b;a<-b;b<-r};a}\ncanonical<-function(token){\n if(is.na(token)||token%in%c('','.'))return('null')\n if(!grepl('^[+-]?[0-9]+([.][0-9]*)?$',token))stop('Unsupported native fingerprint token')\n neg<-substr(token,1,1)=='-';s<-sub('^[+-]','',token);parts<-strsplit(s,'.',fixed=TRUE)[[1]];dec<-if(length(parts)==2)nchar(parts[2])else 0;n<-as.numeric(gsub('.','',s,fixed=TRUE));d<-10^dec\n # Every native fingerprint numerator/denominator must remain exactly integral\n # in binary64; reject rather than silently rounding a changed future source.\n if(!is.finite(n)||n>2^53||d>2^53)stop('Native canonical integer range exceeded')\n g<-gcd_small(n,d);n<-n/g;d<-d/g;if(neg)n<--n\n out<-sprintf('%.0f',n);if(d!=1)out<-paste0(out,'/',sprintf('%.0f',d));out\n}\nfp_cache<-new.env(hash=TRUE,parent=emptyenv());hash_file<-tempfile('ml22-hash-')\nfingerprint<-function(tag,values){a<-vapply(values,canonical,'');payload<-paste0('[',paste0('\"',a,'\"',collapse=','),']');key<-paste0(tag,':',payload);if(exists(key,fp_cache,inherits=FALSE))return(get(key,fp_cache,inherits=FALSE));con<-file(hash_file,'wb');writeBin(charToRaw(payload),con);close(con);value<-paste0(tag,':',unname(sha256(hash_file)));assign(key,value,fp_cache);value}\nassign_roles<-function(group){order<-sort(unique(group),method='radix');state<-seed;if(length(order)>1)for(j in seq.int(length(order),2)){state<-(1664525*state+1013904223)%%2^32;k<-state%%j+1;order[c(j,k)]<-order[c(k,j)]};rank<-match(group,order)-1;list(rank=rank,planned=c('test','validation','train','train')[rank%%4+1],state=state)}\nrows<-list();X<-list()\nfor(typ in c('red','white')){n<-if(typ=='red')1599 else 4898;d<-read_native(paste0('actual',n,'-',typ,'-wine-original12-fields.csv'));stopifnot(nrow(d)==n);features<-setdiff(names(d),c('sourceRow','wineType','quality'));stopifnot(length(features)==11);red<-if(typ=='red')'1'else'0';group<-vapply(seq_len(n),function(i)fingerprint('wine-predictors',c(red,unlist(d[i,features],use.names=FALSE))),'');r<-data.frame(id=paste0('wine-',typ,'-row:',d$sourceRow),sourceRow=paste0(typ,':',d$sourceRow),originalID='',group=group,cohort=typ,y=as.numeric(d$quality));xx<-cbind(sapply(d[features],as.numeric),as.numeric(red));rows$country<-rbind(rows$country,r);X$country<-rbind(X$country,xx)}\nd<-read_native('actual3613-NLS-original52-fields.csv');stopifnot(nrow(d)==3613);rows$person<-data.frame(id=paste0('nls-row:',d$sourceRow),sourceRow=d$sourceRow,originalID=d$id,group=paste0('nls-id:',d$id),cohort=ifelse(as.numeric(d$ed76)>12,'schooling-over12','schooling-at-most12'),y=as.numeric(ifelse(d$lwage76=='.',NA,d$lwage76)));X$person<-cbind(as.numeric(d$ed76),as.numeric(d$age76))\nd<-read_native('actual3150-churn-original14-fields.csv');stopifnot(nrow(d)==3150,sum(d[['Charge  Amount']]=='10')==7);features<-setdiff(names(d),c('sourceRow','Churn'));group<-vapply(seq_len(nrow(d)),function(i)fingerprint('customer-predictors',unlist(d[i,features],use.names=FALSE)),'');rows$company<-data.frame(id=paste0('customer-row:',d$sourceRow),sourceRow=d$sourceRow,originalID='',group=group,cohort=ifelse(d[['Tariff Plan']]=='1','pay-as-you-go',ifelse(d[['Tariff Plan']]=='2','contractual','other-native-tariff')),y=as.numeric(d$Churn));X$company<-sapply(d[c('Call  Failure','Subscription  Length','Seconds of Use','Age')],as.numeric)\nif(file.exists(hash_file))unlink(hash_file)\n\nfit_model<-function(r,x,method,lambda){\n tr<-which(r$role=='train'&r$eligible);if(!length(tr))stop('No complete positive training rows');y<-r$y[tr];xx<-x[tr,,drop=FALSE];mu<-colMeans(xx);scale<-apply(xx,2,function(v)diff(range(v)));scale[scale==0]<-1;z<-cbind(1,sweep(sweep(x,2,mu,'-'),2,scale,'/'));meanY<-mean(y);model<-list();n<-length(tr)\n if(method=='constant'){model<-list(mean=meanY,parameterCount=1,rank=1,unique=TRUE);raw<-rep(meanY,nrow(r))}\n else if(method=='ridge'){zt<-z[tr,,drop=FALSE];pen<-diag(c(0,rep(lambda,ncol(x))));theta<-drop(solve(crossprod(zt)/n+pen,crossprod(zt,y)/n));raw<-drop(z%*%theta);objective<-mean((y-raw[tr])^2)/2+lambda*sum(theta[-1]^2)/2;model<-list(lambdaValue=lambda,theta=theta,rank=length(theta),unique=TRUE,minimumObjective=objective,parameterCount=length(theta))}\n else{base<-sum((y-meanY)^2);best<-NULL;total<-sum(y);total2<-sum(y*y)\n  for(j in seq_len(ncol(x))){ord<-order(xx[,j],seq_len(n));sx<-xx[ord,j];sy<-y[ord];left<-cumsum(sy)\n   if(n<2*leaf_min)next\n   for(i in seq.int(leaf_min,n-leaf_min)){if(sx[i]==sx[i+1])next;loss<-total2-left[i]^2/i-(total-left[i])^2/(n-i)\n    # Explicit approximate-tie tolerance; exact source JavaScript/Python\n    # contracts are authoritative for general arbitrarily close ties.\n    if(is.null(best)||loss<best$weightedSSE-1e-12*max(1,abs(loss),abs(best$weightedSSE)))best<-list(feature=j-1,threshold=(sx[i]+sx[i+1])/2,leftMean=left[i]/i,rightMean=(total-left[i])/(n-i),leftRows=i,rightRows=n-i,leftWeight=i,rightWeight=n-i,weightedSSE=loss)\n   }\n  }\n  if(is.null(best)||best$weightedSSE>=base-1e-12*max(1,abs(base))){model<-list(split=FALSE,mean=meanY,weightedSSE=base,trainingMSE=base/n);raw<-rep(meanY,nrow(r))}else{model<-c(list(split=TRUE),best,list(trainingMSE=best$weightedSSE/n,improvement=(base-best$weightedSSE)/n));raw<-ifelse(x[,model$feature+1]<=model$threshold,model$leftMean,model$rightMean)}\n }\n pred<-if(r$dataset[1]=='company')pmax(0,pmin(1,raw))else raw;list(meanX=mu,scales=scale,model=model,raw=raw,pred=pred)\n}\n\n# New standalone fixed-profile adapters; native and fit helpers copied by value.\nnum<-function(x){if(is.null(x)||length(x)==0||is.na(x)||x%in%c('','.'))return(NA_real_);if(is.character(x)&&grepl('/',x,fixed=TRUE)){v<-strsplit(x,'/',fixed=TRUE)[[1]];return(as.numeric(v[1])/as.numeric(v[2]))};as.numeric(x)}\nfixedRows<-function(aa){\n rr<-lapply(seq_along(aa),function(i){a<-aa[[i]];w<-num(if(is.null(a$weight))'1'else a$weight);if(is.na(w)||w<0)stop(if(!is.na(w)&&w<0)'negative-weight'else'missing-weight');list(id=if(is.null(a$id))as.character(i-1)else a$id,group=if(is.null(a$group))if(is.null(a$id))as.character(i-1)else a$id else a$group,cohort=if(is.null(a$cohort))'all'else a$cohort,role=if(is.null(a$role))'train'else a$role,w=w,y=num(a$y),x=vapply(a$x,num,0.0))})\n p<-if(length(rr))length(rr[[1]]$x)else 0;xx<-matrix(NA_real_,length(rr),p)\n if(p)for(i in seq_along(rr))xx[i,]<-rr[[i]]$x\n r<-data.frame(id=vapply(rr,`[[`,'','id'),group=vapply(rr,`[[`,'','group'),cohort=vapply(rr,`[[`,'','cohort'),role=vapply(rr,`[[`,'','role'),w=vapply(rr,`[[`,0.0,'w'),y=vapply(rr,`[[`,0.0,'y'));r$eligible<-!is.na(r$y)&rowSums(is.na(xx))==0&r$w>0;list(r=r,x=xx)\n}\nweightedRisk<-function(r,p,binary=FALSE,threshold=.5){\n ii<-which(r$w>0&!is.na(r$y)&!is.na(p)&!r$role%in%c('excluded','unused'));y<-r$y[ii];p<-p[ii];w<-r$w[ii];W<-sum(w);d<-list(rows=length(ii),mass=W,MSE=NA_real_,MAE=NA_real_,R2=NA_real_)\n if(W==0){if(binary)d<-c(d,setNames(rep(list(NA_real_),10),c('Brier','accuracy','positiveRecall','negativeRecall','precision','F1','balancedAccuracy','AUROC','positiveMass','negativeMass')));return(d)}\n mu<-sum(w*y)/W;sse<-sum(w*(p-y)^2);sst<-sum(w*(y-mu)^2);d<-c(d,list(meanY=mu,SSE=sse,SST=sst));d$MSE<-sse/W;d$MAE<-sum(w*abs(p-y))/W;d$R2<-if(sst>0)1-sse/sst else NA_real_\n if(binary){pos<-y==1;yes<-p>=threshold;TP<-sum(w[pos&yes]);FP<-sum(w[!pos&yes]);TN<-sum(w[!pos&!yes]);FN<-sum(w[pos&!yes]);rate<-function(a,b)if(b>0)a/b else NA_real_;tpr<-rate(TP,TP+FN);tnr<-rate(TN,TN+FP);auc<-NA_real_;P<-sum(w[pos]);N<-sum(w[!pos]);if(P>0&&N>0){wins<-sum(vapply(which(pos),function(i)sum(w[i]*w[!pos]*ifelse(p[i]>p[!pos],1,ifelse(p[i]==p[!pos],.5,0))),0.0));auc<-wins/(P*N)};d<-c(d,list(Brier=d$MSE,threshold=threshold,confusionMass=list(TP=TP,FP=FP,TN=TN,FN=FN),confusionRows=list(TP=sum(pos&yes),FP=sum(!pos&yes),TN=sum(!pos&!yes),FN=sum(pos&!yes)),positiveMass=P,negativeMass=N,accuracy=(TP+TN)/W,positiveRecall=tpr,negativeRecall=tnr,precision=rate(TP,TP+FP),F1=rate(2*TP,2*TP+FP+FN),balancedAccuracy=if(is.finite(tpr)&&is.finite(tnr))(tpr+tnr)/2 else NA_real_,AUROC=auc))};d\n}\nweightedPair<-function(r,A,B){\n ii<-which(r$w>0&!is.na(r$y)&!is.na(A)&!is.na(B)&!r$role%in%c('excluded','unused'));rr<-r[ii,,drop=FALSE];la<-(A[ii]-rr$y)^2;lb<-(B[ii]-rr$y)^2;d<-la-lb;W<-sum(rr$w);S<-sum(rr$w*d);mu<-if(W>0)S/W else NA_real_;ids<-unique(rr$group);groups<-lapply(ids,function(g){jj<-which(rr$group==g);wg<-sum(rr$w[jj]);sg<-sum(rr$w[jj]*d[jj]);list(group=g,rows=length(jj),mass=wg,sum=sg,leaveOut=if(W>wg)(S-sg)/(W-wg)else NA_real_)});leaves<-vapply(groups,`[[`,0.0,'leaveOut');G<-length(groups);proxy<-if(G>1&&all(is.finite(leaves)))(G-1)/G*sum((leaves-mean(leaves))^2) else NA_real_\n list(rows=length(ii),mass=W,groupCount=G,meanDifference=mu,minimumLeaveOut=if(any(is.finite(leaves)))min(leaves,na.rm=TRUE)else NA_real_,maximumLeaveOut=if(any(is.finite(leaves)))max(leaves,na.rm=TRUE)else NA_real_,varianceProxy=proxy,groups=groups,records=lapply(seq_along(ii),function(j)list(id=rr$id[j],group=rr$group[j],weight=rr$w[j],lossA=la[j],lossB=lb[j],difference=d[j])))\n}\nrunSelection<-function(r,candidates,criterion,required,binary=FALSE){\n out<-lapply(candidates,function(c){v<-r;t<-r;v$role[v$role!='validation']<-'excluded';t$role[t$role!='test']<-'excluded';val<-weightedRisk(v,c$pred,binary);test<-weightedRisk(t,c$pred,binary);co<-setNames(lapply(required,function(g){z<-v;z$role[z$cohort!=g]<-'excluded';weightedRisk(z,c$pred,binary)}),required);vv<-vapply(co,`[[`,0.0,'MSE');score<-if(criterion=='mean')val$MSE else if(length(vv)&&all(is.finite(vv)))max(vv)else NA_real_;list(id=c$id,criterion=score,validation=val,test=test,cohorts=co)})\n scores<-vapply(out,`[[`,0.0,'criterion');eligible<-which(is.finite(scores));k<-if(length(eligible))eligible[which.min(scores[eligible])]else NA_integer_;list(criterion=criterion,selected=if(!is.na(k))out[[k]]$id else NULL,selectedIndex=if(!is.na(k))k-1 else NA_real_,candidates=out)\n}\nfixedOperation<-function(api,a){\n if(api=='realdata'){\n  kind<-a$kind;r<-rows[[kind]];x<-X[[kind]];asgn<-assign_roles(r$group);r$dataset<-kind;r$splitRank<-asgn$rank;r$plannedRole<-asgn$planned;r$eligible<-!is.na(r$y)&rowSums(is.na(x))==0;r$role<-ifelse(r$eligible,r$plannedRole,'excluded');r$w<-1;binary<-kind=='company';leaf_min<<-5\n  defs<-data.frame(id=c('constant','ridge:1/100','ridge:1/10','ridge:1','one-split-stump'),method=c('constant','ridge','ridge','ridge','stump'),lambda=c(0,.01,.1,1,0));fits<-lapply(seq_len(5),function(i)fit_model(r,x,defs$method[i],defs$lambda[i]));candidates<-lapply(seq_len(5),function(i)list(id=defs$id[i],pred=fits[[i]]$pred));selection<-runSelection(r,candidates,a$criterion,unique(r$cohort),binary);k<-selection$selectedIndex+1;best<-fits[[k]];base<-fits[[1]];test<-r;test$role[test$role!='test']<-'excluded';paired<-weightedPair(test,best$pred,base$pred)\n  records<-lapply(seq_len(nrow(r)),function(i)list(id=r$id[i],sourceRow=r$sourceRow[i],originalID=r$originalID[i],group=r$group[i],cohort=r$cohort[i],plannedRole=r$plannedRole[i],role=r$role[i],eligible=r$eligible[i],y=r$y[i],baselinePrediction=base$pred[i],selectedPrediction=best$pred[i],selectedRawPrediction=best$raw[i],queryInvariant=TRUE))\n  return(list(kind=kind,nativeRows=nrow(r),eligibleRows=sum(r$eligible),selection=selection,models=lapply(seq_len(5),function(i)list(id=defs$id[i],train=as.list(r$id[r$role=='train']),mass=sum(r$role=='train'),meanX=fits[[i]]$meanX,scales=fits[[i]]$scales,model=fits[[i]]$model)),paired=paired,records=records))\n }\n f<-fixedRows(a$rows);r<-f$r;x<-f$x;binary<-identical(a$task,'binary')\n if(api=='split'){seed<<-a$seed;asgn<-assign_roles(r$group);return(list(state=asgn$state,groupCount=length(unique(r$group)),records=lapply(seq_len(nrow(r)),function(i)list(id=r$id[i],group=r$group[i],rank=asgn$rank[i],role=asgn$planned[i]))))}\n if(api=='fit'){\n  r$dataset<-if(binary)'company'else'fixed';leaf_min<<-if(is.null(a$minLeafRows))1 else a$minLeafRows;fit<-fit_model(r,x,a$method,if(is.null(a$lambda))0 else num(a$lambda));bad<-rowSums(is.na(x))>0;fit$raw[bad]<-NA_real_;fit$pred[bad]<-NA_real_;fit$defined<-TRUE;fit$train<-as.list(r$id[r$role=='train'&r$eligible]);fit$mass<-sum(r$w[r$role=='train'&r$eligible]);fit$invariant<-ifelse(bad,NA,TRUE);return(fit)\n }\n if(api=='evaluate'){p<-vapply(a$rows,function(v)num(v$prediction),0.0);threshold<-if(is.null(a$threshold)).5 else num(a$threshold);m<-weightedRisk(r,p,binary,threshold);records<-lapply(seq_len(nrow(r)),function(i){valid<-r$w[i]>0&&!is.na(r$y[i])&&!is.na(p[i])&&!r$role[i]%in%c('excluded','unused');list(id=r$id[i],weight=r$w[i],y=r$y[i],prediction=p[i],eligible=valid,loss=if(valid)(p[i]-r$y[i])^2 else NA_real_,correct=list(defined=valid&&binary,value=if(valid&&binary)(p[i]>=threshold)==r$y[i] else NULL))});return(list(metrics=m,records=records))}\n if(api=='select'){cs<-lapply(a$candidates,function(c)list(id=c$id,pred=vapply(c$predictions,num,0.0)));return(runSelection(r,cs,a$criterion,unlist(a$requiredCohorts),binary))}\n if(api=='paired')return(weightedPair(r,vapply(a$rows,function(v)num(v$predictionA),0.0),vapply(a$rows,function(v)num(v$predictionB),0.0)))\n stop('unknown-api')\n}\nreportValues<-function(api,z){\n ss<-list();pp<-list();add<-function(k,v,u='dimensionless')ss[[length(ss)+1]]<<-list(metric=k,value=if(is.null(v)||length(v)==0||is.na(v))NULL else unname(v),unit=u);series<-function(name,values){for(i in seq_along(values))pp[[length(pp)+1]]<<-list(series=name,index=i-1,x=i-1,y=if(is.null(values[[i]])||is.na(values[[i]]))NULL else unname(values[[i]]))}\n if(api=='split'){add('groups',z$groupCount,'groups');add('rows',length(z$records),'rows');add('finalState',z$state,'unsigned 32-bit state');series('planned role code',lapply(z$records,function(r)switch(r$role,test=0,validation=1,train=2)))}\n if(api=='fit'){add('defined',z$defined);add('trainingRows',length(z$train),'rows');add('trainingMass',z$mass,'analysis weight mass');add('modelRank',z$model$rank,'parameters');add('threshold',z$model$threshold,'constructed feature units');add('minimumObjective',z$model$minimumObjective,'constructed squared outcome units');series('prediction',as.list(z$pred));if(!is.null(z$model$theta))for(i in seq_along(z$model$theta))add(paste0('theta',i-1),z$model$theta[i],'constructed outcome units per standardized coordinate')}\n if(api=='evaluate'){for(k in c('rows','mass','MSE','MAE','R2','Brier','accuracy','positiveRecall','negativeRecall','precision','F1','balancedAccuracy','AUROC'))if(k%in%names(z$metrics))add(k,z$metrics[[k]],if(k=='rows')'rows'else if(k=='mass')'analysis weight mass'else if(k%in%c('MSE','Brier'))FIXED$unit else if(k=='MAE')'constructed outcome units'else'dimensionless');series('squared loss',lapply(z$records,`[[`,'loss'))}\n if(api=='select'){add('selectedIndex',z$selectedIndex,'zero-based candidate index');for(i in seq_along(z$candidates)){c<-z$candidates[[i]];add(paste0('criterion',i-1),c$criterion,FIXED$unit);add(paste0('testMSE',i-1),c$test$MSE,FIXED$unit)};series('validation criterion',lapply(z$candidates,`[[`,'criterion'));series('test MSE',lapply(z$candidates,function(c)c$test$MSE))}\n if(api=='paired'){for(k in c('rows','mass','groupCount','meanDifference','minimumLeaveOut','maximumLeaveOut','varianceProxy'))add(k,z[[k]],if(k=='rows')'rows'else if(k=='groupCount')'groups'else if(k=='mass')'analysis weight mass'else if(k=='varianceProxy')paste(FIXED$unit,'squared')else FIXED$unit);series('loss A minus loss B',lapply(z$records,`[[`,'difference'))}\n if(api=='realdata'){add('nativeRows',z$nativeRows,'native records');add('eligibleRows',z$eligibleRows,'complete records');add('selectedIndex',z$selection$selectedIndex,'zero-based candidate index');for(i in seq_along(z$selection$candidates)){c<-z$selection$candidates[[i]];add(paste0('validationMSE',i-1),c$validation$MSE,FIXED$unit);add(paste0('testMSE',i-1),c$test$MSE,FIXED$unit)};for(k in c('meanDifference','minimumLeaveOut','maximumLeaveOut','varianceProxy'))add(k,z$paired[[k]],if(k=='varianceProxy')paste(FIXED$unit,'squared')else FIXED$unit);best<-z$selection$candidates[[z$selection$selectedIndex+1]]$test;for(k in c('accuracy','positiveRecall','negativeRecall','precision','balancedAccuracy','AUROC'))if(k%in%names(best))add(k,best[[k]]);series('validation MSE',lapply(z$selection$candidates,function(c)c$validation$MSE));series('test MSE',lapply(z$selection$candidates,function(c)c$test$MSE))}\n list(summary=ss,points=pp)\n}\n\nescapeXML<-function(s){s<-gsub('&','&amp;',s,fixed=TRUE);s<-gsub('<','&lt;',s,fixed=TRUE);s<-gsub('>','&gt;',s,fixed=TRUE);gsub('\"','&quot;',s,fixed=TRUE)}\nsvgPlot<-function(pp,title){\n xx<-vapply(pp,function(p)as.numeric(p$x),numeric(1));yy<-vapply(pp,function(p)as.numeric(p$y),numeric(1));xmin<-if(length(xx))min(xx)else 0;xmax<-if(length(xx))max(xx)else 1;ymin<-min(c(0,yy));ymax<-max(c(0,yy));if(xmin==xmax){xmin<-xmin-.5;xmax<-xmax+.5};if(ymin==ymax){ymin<-ymin-.5;ymax<-ymax+.5};pad<-(ymax-ymin)*.08;ymin<-ymin-pad;ymax<-ymax+pad;X<-function(x)82+(as.numeric(x)-xmin)/(xmax-xmin)*608;Y<-function(y)354-(as.numeric(y)-ymin)/(ymax-ymin)*290\n out<-paste0('<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"720\" height=\"480\" viewBox=\"0 0 720 480\" role=\"img\" aria-label=\"',escapeXML(title),'\"><rect width=\"720\" height=\"480\" fill=\"white\"/><g font-family=\"Arial,sans-serif\" font-size=\"13\" fill=\"#18232f\"><text x=\"360\" y=\"25\" text-anchor=\"middle\">',escapeXML(title),'</text>')\n for(j in 0:4){y<-ymin+(ymax-ymin)*j/4;x<-xmin+(xmax-xmin)*j/4;out<-paste0(out,'<line x1=\"82\" y1=\"',Y(y),'\" x2=\"690\" y2=\"',Y(y),'\" stroke=\"#e2e8f0\"/><text x=\"73\" y=\"',Y(y)+4,'\" text-anchor=\"end\">',sprintf('%.3g',y),'</text><text x=\"',X(x),'\" y=\"380\" text-anchor=\"middle\">',sprintf('%.3g',x),'</text>')}\n ss<-unique(vapply(pp,`[[`,character(1),'series'));cols<-c('#0f766e','#c76622','#4f46e5','#b23857')\n for(j in seq_along(ss)){rr<-Filter(function(p)p$series==ss[j],pp);xy<-vapply(rr,function(p)sprintf('%.6f,%.6f',X(p$x),Y(p$y)),character(1));col<-cols[(j-1)%%4+1];for(p in rr)out<-paste0(out,'<circle cx=\"',sprintf('%.6f',X(p$x)),'\" cy=\"',sprintf('%.6f',Y(p$y)),'\" r=\"2.6\" fill=\"',col,'\"><title>',escapeXML(ss[j]),': ',escapeXML(p$y),'</title></circle>');out<-paste0(out,'<text x=\"',82+((j-1)%%2)*310,'\" y=\"',432+floor((j-1)/2)*23,'\" fill=\"',col,'\">',escapeXML(ss[j]),'</text>')}\n paste0(out,'<text x=\"360\" y=\"405\" text-anchor=\"middle\">Declared record / candidate index; fixed example</text></g></svg>')\n}\ntoJSON<-function(x){\n if(is.null(x))return('null');if(is.list(x)){v<-vapply(x,toJSON,character(1));if(!is.null(names(x)))paste0('{',paste(paste0(vapply(names(x),toJSON,character(1)),':',v),collapse=','),'}')else paste0('[',paste(v,collapse=','),']')}\n else if(length(x)!=1){if(!is.numeric(x)&&!is.null(names(x)))toJSON(as.list(x))else paste0('[',paste(vapply(as.list(x),toJSON,character(1)),collapse=','),']')}\n else if(is.na(x))'null'else if(is.logical(x))if(x)'true'else'false'else if(is.numeric(x))if(is.finite(x))sprintf('%.17g',x)else'null'else paste0('\"',gsub('\\n','\\\\n',gsub('\"','\\\\\"',gsub('\\\\','\\\\\\\\',x,fixed=TRUE),fixed=TRUE),fixed=TRUE),'\"')\n}\n\nFIXED<-list(`api`=\"realdata\",`variant`=\"company\",`title`=\"All 3,150 factual churn records\",`input`=list(`kind`=\"company\",`seed`=20261104,`criterion`=\"mean\"),`unit`=\"One-component Brier loss\",`titleI18n`=list(`ko`=\"실제 이탈 전체 3,150행\",`en`=\"All 3,150 factual churn records\"))\n\nargs<-commandArgs(trailingOnly=TRUE);out<-if(length(args))args[1]else stop('NEW output directory required');if(dir.exists(out))stop('Preserve previous output directory');dir.create(out,recursive=TRUE)\nz<-fixedOperation(FIXED$api,FIXED$input);rr<-reportValues(FIXED$api,z)\nwriteLines(toJSON(list(arithmetic='BaseR binary64 author counterpart; native group hashing exact within declared integer range, stump approximate tie tolerance1e-12; not an independent exact oracle',result=z)),file.path(out,'full.json'),useBytes=TRUE)\nsums<-do.call(rbind,lapply(rr$summary,function(row)data.frame(metric=row$metric,value=if(is.null(row$value))''else if(is.logical(row$value))as.character(as.integer(row$value))else format(row$value,digits=17,scientific=NA,trim=TRUE),unit=row$unit,defined=as.integer(!is.null(row$value)),stringsAsFactors=FALSE)))\npoints<-do.call(rbind,lapply(rr$points,function(p)data.frame(series=p$series,index=p$index,x=p$x,y=if(is.null(p$y))NA_real_ else p$y,defined=as.integer(!is.null(p$y)),stringsAsFactors=FALSE)))\nwrite.csv(sums,file.path(out,'summary.csv'),row.names=FALSE,na='');write.csv(points,file.path(out,'plot-points.csv'),row.names=FALSE,na='');writeLines(svgPlot(Filter(function(p)!is.null(p$y),rr$points),FIXED$title),file.path(out,'plot.svg'),useBytes=TRUE);cat(FIXED$api,'/',FIXED$variant,'\\n',sep='')\n",
        "returnCode": 0,
        "stdout": "realdata/company\r\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 ",
        "diagnosticScope": "Public projection omits private absolute-path/traceback frames; actual exit and warnings/reason retained. Raw complete streams and commands in private execution proof.",
        "resultFolder": "ml22-code/runs/r-realdata-company",
        "kind": "company",
        "inputFiles": [
          {
            "file": "ml22-code/realdata-company-input.json",
            "sha256": "af603911fbcca13a2aa49e482acf3bee8ce91e35ecbf6b645b174f814e1d5c31",
            "scope": "Complete fixed literal input; program embeds the same values"
          },
          {
            "file": "ml22-code/data/actual1599-red-wine-original12-fields.csv",
            "sha256": "77e9ac73115930d6c43983333a5a57940deefc493affeb17aca478c09c5f6e00",
            "scope": "All native rows and original fields; required sibling data file"
          },
          {
            "file": "ml22-code/data/actual3150-churn-original14-fields.csv",
            "sha256": "1c0753e434226e769d1015c922121a7d8967df66014e057c4f7543e490f11764",
            "scope": "All native rows and original fields; required sibling data file"
          },
          {
            "file": "ml22-code/data/actual3613-NLS-original52-fields.csv",
            "sha256": "6e1e1895558795435b65f8634252a7589865273a0e69adbd715fcfa04a3c11a1",
            "scope": "All native rows and original fields; required sibling data file"
          },
          {
            "file": "ml22-code/data/actual4898-white-wine-original12-fields.csv",
            "sha256": "50d810bbb42b9cc3e87fa4c27a4c0f168e72da09dd812863425ca3873fec28ef",
            "scope": "All native rows and original fields; required sibling data file"
          }
        ],
        "files": [
          {
            "file": "ml22-code/runs/r-realdata-company/full.json",
            "sha256": "49518237bca06940009ad4baac8d24de1e1c4692e85e62f8edcb47f0a8354bcf",
            "bytes": 1690046
          },
          {
            "file": "ml22-code/runs/r-realdata-company/plot-points.csv",
            "sha256": "a42b7941e10db22686b04faf0fd2b0787ef82579decdb74413fc432f5852f90f",
            "bytes": 426
          },
          {
            "file": "ml22-code/runs/r-realdata-company/plot.svg",
            "sha256": "e1831a0dd1b28fd158df57a17056e5790cf1a452eac5539851a0a1e5dcb2498b",
            "bytes": 2533
          },
          {
            "file": "ml22-code/runs/r-realdata-company/summary.csv",
            "sha256": "51df5c23e3c4af01b05f7ea4f373a5b65571843154d40714dec9de64164e4b03",
            "bytes": 1383
          }
        ],
        "summaryRows": [
          {
            "metric": "nativeRows",
            "value": "3150.0",
            "unit": "native records",
            "defined": "true",
            "rawValue": "3150",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "eligibleRows",
            "value": "3150.0",
            "unit": "complete records",
            "defined": "true",
            "rawValue": "3150",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "selectedIndex",
            "value": "1.0",
            "unit": "zero-based candidate index",
            "defined": "true",
            "rawValue": "1",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "validationMSE0",
            "value": "0.12499149938983466",
            "unit": "One-component Brier loss",
            "defined": "true",
            "rawValue": "0.12499149938983466",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "testMSE0",
            "value": "0.14213568334634585",
            "unit": "One-component Brier loss",
            "defined": "true",
            "rawValue": "0.14213568334634585",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "validationMSE1",
            "value": "0.11116870372046503",
            "unit": "One-component Brier loss",
            "defined": "true",
            "rawValue": "0.11116870372046503",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "testMSE1",
            "value": "0.12441445028437267",
            "unit": "One-component Brier loss",
            "defined": "true",
            "rawValue": "0.12441445028437267",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "validationMSE2",
            "value": "0.11787977575762065",
            "unit": "One-component Brier loss",
            "defined": "true",
            "rawValue": "0.11787977575762065",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "testMSE2",
            "value": "0.13371629262494447",
            "unit": "One-component Brier loss",
            "defined": "true",
            "rawValue": "0.13371629262494447",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "validationMSE3",
            "value": "0.12370219758680523",
            "unit": "One-component Brier loss",
            "defined": "true",
            "rawValue": "0.12370219758680523",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "testMSE3",
            "value": "0.14065893189875783",
            "unit": "One-component Brier loss",
            "defined": "true",
            "rawValue": "0.14065893189875783",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "validationMSE4",
            "value": "0.11125797920842813",
            "unit": "One-component Brier loss",
            "defined": "true",
            "rawValue": "0.11125797920842813",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "testMSE4",
            "value": "0.13001090422832914",
            "unit": "One-component Brier loss",
            "defined": "true",
            "rawValue": "0.13001090422832914",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "meanDifference",
            "value": "-0.017721233061973173",
            "unit": "One-component Brier loss",
            "defined": "true",
            "rawValue": "-0.017721233061973173",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": false,
            "mathematicallyNegative": true,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "minimumLeaveOut",
            "value": "-0.018029096391805045",
            "unit": "One-component Brier loss",
            "defined": "true",
            "rawValue": "-0.018029096391805045",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": false,
            "mathematicallyNegative": true,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "maximumLeaveOut",
            "value": "-0.017156391571752614",
            "unit": "One-component Brier loss",
            "defined": "true",
            "rawValue": "-0.017156391571752614",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": false,
            "mathematicallyNegative": true,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "varianceProxy",
            "value": "5.064733508338412e-06",
            "unit": "One-component Brier loss squared",
            "defined": "true",
            "rawValue": "5.0647335083384117e-06",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "accuracy",
            "value": "0.8287937743190662",
            "unit": "dimensionless",
            "defined": "true",
            "rawValue": "0.8287937743190662",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "positiveRecall",
            "value": "0.0",
            "unit": "dimensionless",
            "defined": "true",
            "rawValue": "0",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": false,
            "mathematicallyNegative": false,
            "exactZero": true,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "negativeRecall",
            "value": "1.0",
            "unit": "dimensionless",
            "defined": "true",
            "rawValue": "1",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "precision",
            "value": "",
            "unit": "dimensionless",
            "defined": "false",
            "rawValue": "",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null
          },
          {
            "metric": "balancedAccuracy",
            "value": "0.5",
            "unit": "dimensionless",
            "defined": "true",
            "rawValue": "0.5",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          },
          {
            "metric": "AUROC",
            "value": "0.8154194527433964",
            "unit": "dimensionless",
            "defined": "true",
            "rawValue": "0.81541945274339644",
            "arithmetic": "BaseR binary64 approximate",
            "exactFraction": null,
            "mathematicallyPositive": true,
            "mathematicallyNegative": false,
            "exactZero": false,
            "displayUnderflow": false,
            "displayOverflow": false,
            "displayRoundedToOne": false
          }
        ],
        "plotRows": [
          {
            "series": "validation MSE",
            "index": "0",
            "x": "0",
            "y": "0.124991499389835",
            "defined": true,
            "xExact": null,
            "yExact": null
          },
          {
            "series": "validation MSE",
            "index": "1",
            "x": "1",
            "y": "0.111168703720465",
            "defined": true,
            "xExact": null,
            "yExact": null
          },
          {
            "series": "validation MSE",
            "index": "2",
            "x": "2",
            "y": "0.117879775757621",
            "defined": true,
            "xExact": null,
            "yExact": null
          },
          {
            "series": "validation MSE",
            "index": "3",
            "x": "3",
            "y": "0.123702197586805",
            "defined": true,
            "xExact": null,
            "yExact": null
          },
          {
            "series": "validation MSE",
            "index": "4",
            "x": "4",
            "y": "0.111257979208428",
            "defined": true,
            "xExact": null,
            "yExact": null
          },
          {
            "series": "test MSE",
            "index": "0",
            "x": "0",
            "y": "0.142135683346346",
            "defined": true,
            "xExact": null,
            "yExact": null
          },
          {
            "series": "test MSE",
            "index": "1",
            "x": "1",
            "y": "0.124414450284373",
            "defined": true,
            "xExact": null,
            "yExact": null
          },
          {
            "series": "test MSE",
            "index": "2",
            "x": "2",
            "y": "0.133716292624944",
            "defined": true,
            "xExact": null,
            "yExact": null
          },
          {
            "series": "test MSE",
            "index": "3",
            "x": "3",
            "y": "0.140658931898758",
            "defined": true,
            "xExact": null,
            "yExact": null
          },
          {
            "series": "test MSE",
            "index": "4",
            "x": "4",
            "y": "0.130010904228329",
            "defined": true,
            "xExact": null,
            "yExact": null
          }
        ],
        "plotFile": "ml22-code/runs/r-realdata-company/plot.svg",
        "fullResultFile": "ml22-code/runs/r-realdata-company/full.json",
        "arithmeticScope": "Python exact rational versus base-R approximate floating algebra; copied author kernels, not independent oracle.",
        "plotScope": "Original scatter vectors plot every defined declared comparison point, with missing points omitted. Source profiles show candidate risks; all source records remain in the full result and source CSV files.",
        "reproductionScope": "Standalone literal program plus four native CSV files for factual source profiles. No answer/engine/checker imports."
      }
    }
  }
}
