{
  "variance": {
    "python": {
      "correlated": {
        "api": "variance",
        "variant": "correlated",
        "language": "python",
        "codeFile": "ml09-code/variance-correlated.py",
        "codeSHA256": "d186559f4e8d6567c893e69b2129107f348262b969085d82a155eb2e48d540d9",
        "codeText": "\"\"\"ML09 exact Fraction reproduction from native source fields.\n\npython ml09-public-analysis.py --source-dir ml09-sources --output-dir results\n\nThis authored educational implementation uses direct-centered leaf losses and\nexhaustive midpoint partitions. It reads no JS engine, model contract, checker,\nstored target answers or derived-result CSV. Its five tree arithmetic helpers\nwere copied from the author's own separate Fraction reference, not an independent\npeer. Parser/work budgets and display rounding of the production JS are separate.\nNumerical predictions/proper scores do not certify causal effects, calibration,\nIID OOB validity, survey representativeness or production parameter optimality.\n\"\"\"\nfrom pathlib import Path\nfrom fractions import Fraction as Q\nimport csv,json,math,itertools,argparse\n\ndef normalized(rows,task='regression'):\n return [dict(id=r.get('id',i),x=[None if x is None else Q(x)for x in r.get('x',[])],y=None if r['y']is None else str(r['y'])if task=='classification'else Q(r['y']),w=Q(r.get('weight',1)))for i,r in enumerate(rows)]\n\ndef totals(rows,task,classes):\n W=sum((r['w']for r in rows),Q());mu=sum((r['w']*r['y']for r in rows),Q())/W if task=='regression'and W else None\n probs=[sum((r['w']for r in rows if r['y']==c),Q())/W for c in classes]if task=='classification'and W else[]\n risk=sum((r['w']*(r['y']-mu)**2 for r in rows),Q())if task=='regression'and W else W*sum((p*(1-p)for p in probs),Q())\n return dict(n=len(rows),w=W,mu=mu,p=probs,risk=risk,pred=mu if task=='regression'else classes[max(range(len(probs)),key=lambda i:probs[i])]if probs else None)\n\ndef fit(rows,a,task,classes,schedule=None):\n good=[r for r in rows if r['w']>0 and r['y']is not None];root=totals(good,task,classes)['w'];depth=a.get('maxDepth',2);minimum=a.get('minLeaf',1);minmass=Q(a.get('minLeafWeight',0));mingain=Q(a.get('minGain',0));route=a.get('missingRoute','best')\n def build(rr,d,path):\n  st=totals(rr,task,classes);n=dict(rows=rr,st=st,split=None,left=None,right=None,path=path)\n  if d==depth:return n\n  best=None\n  for j in range(len(rr[0]['x'])):\n   if schedule is not None and j not in schedule[path]:continue\n   values=sorted({r['x'][j]for r in rr if r['x'][j]is not None});missing=[r for r in rr if r['x'][j]is None];observed=[r for r in rr if r['x'][j]is not None]\n   candidates=[]\n   for lo,hi in zip(values,values[1:]):\n    q=(lo+hi)/2;left=[r for r in observed if r['x'][j]<=q];right=[r for r in observed if r['x'][j]>q];directions=[route]if route!='best'else['left','right']if missing else['left'if len(left)>=len(right)else'right']\n    for direction in directions:candidates.append(('threshold',q,direction,left+missing if direction=='left'else left,right+missing if direction=='right'else right))\n   if missing and observed:candidates.append(('missing-only',None,'left',missing,observed))\n   for kind,q,direction,left,right in candidates:\n    l=totals(left,task,classes);r=totals(right,task,classes)\n    if min(l['n'],r['n'])<minimum or min(l['w'],r['w'])<minmass or min(l['w'],r['w'])<=0:continue\n    gain=(st['risk']-l['risk']-r['risk'])/root\n    if best is None or gain>best['gain']:best=dict(feature=j,kind=kind,threshold=q,missingRoute=direction,left=left,right=right,gain=gain)\n  if best and best['gain']>0 and best['gain']>mingain:\n   j=best['feature'];go=lambda r:r['x'][j]is None if best['kind']=='missing-only'else best['missingRoute']=='left'if r['x'][j]is None else r['x'][j]<=best['threshold'];n['split']=best;n['left']=build([r for r in rr if go(r)],d+1,path+'L');n['right']=build([r for r in rr if not go(r)],d+1,path+'R')\n  return n\n return build(good,0,'')\n\ndef predict(tree,x):\n n=tree\n while n['split']:\n  s=n['split'];v=x[s['feature']];left=v is None if s['kind']=='missing-only'else s['missingRoute']=='left'if v is None else v<=s['threshold'];n=n['left'if left else'right']\n return dict(prediction=n['st']['pred'],probabilities=n['st']['p'])\n\ndef combine(preds,w,task,classes,mode='probabilities'):\n mass=sum(w,Q())\n if not preds or not mass:return dict(prediction=None,probabilities=[],vote=None,prob=None)\n if task=='regression':return dict(prediction=sum((p['prediction']*v for p,v in zip(preds,w)),Q())/mass,probabilities=[],vote=None,prob=None)\n votes=[sum((v for p,v in zip(preds,w)if p['prediction']==c),Q())/mass for c in classes];ps=[sum((p['probabilities'][j]*v for p,v in zip(preds,w)),Q())/mass for j in range(len(classes))];vote=classes[max(range(len(classes)),key=lambda j:votes[j])];prob=classes[max(range(len(classes)),key=lambda j:ps[j])];return dict(prediction=vote if mode=='votes'else prob,probabilities=ps,vote=vote,prob=prob,votes=votes)\ndef number(v):\n if v is None or isinstance(v,bool):raise ValueError('explicit null/bool is not a numeric parameter')\n return Q(v)\ndef variance(a):\n B=a['B'];v=number(a['marginalVariance']);rho=number(a.get('rho',0))\n if not isinstance(B,int)or isinstance(B,bool)or B<1 or v<0:raise ValueError('positive integer B/nonnegative variance')\n if B>1 and v and not -Q(1,B-1)<=rho<=1:raise ValueError('equicorrelation PSD bound')\n return dict(B=B,marginalVariance=v,correlationApplicable=B>1 and bool(v),varianceOfMean=v if B==1 else v*(1+(B-1)*rho)/B)\ndef aggregate(a):\n task=a.get('task','regression');classes=[str(c)for c in a.get('classes',[])];members=a['members'];w=[number(v)for v in a.get('memberWeights',[1]*len(members))]\n if not members or min(w)<0 or sum(w)<=0:raise ValueError('nonnegative member weights/positive total')\n order=[p.get('id',i)for i,p in enumerate(members[0]['predictions'])];keys=lambda x:(type(x).__name__,x);lookup=[{keys(p.get('id',i)):p for i,p in enumerate(m['predictions'])}for m in members]\n if any(set(m)!={keys(v)for v in order}for m in lookup):raise ValueError('same query ID set')\n out=[]\n for pid in order:\n  predictions=[dict(prediction=number(m[keys(pid)]['value']),probabilities=[])if task=='regression'else dict(prediction=str(m[keys(pid)]['label']),probabilities=[number(v)for v in m[keys(pid)]['probabilities']])for m in lookup]\n  if task=='classification'and any(min(p['probabilities'])<0 or sum(p['probabilities'])!=1 for p in predictions):raise ValueError('probability simplex')\n  out.append(dict(id=pid,**combine(predictions,w,task,classes,a.get('aggregation','probabilities'))))\n return dict(task=task,classes=classes,predictions=out)\ndef scored(preds,rows,task,classes):\n mass=loss=absolute=errors=voteerrors=Q();out=[]\n for p,r in zip(preds,rows):\n  ok=p['prediction']is not None and r['y']is not None and r['w']>0;v=None\n  if ok:\n   mass+=r['w']\n   if task=='regression':e=r['y']-p['prediction'];v=e*e;absolute+=r['w']*abs(e)\n   else:v=sum(((q-(1 if r['y']==c else 0))**2 for c,q in zip(classes,p['probabilities'])),Q());errors+=r['w']*(p['prediction']!=r['y']);voteerrors+=r['w']*(p['vote']!=r['y'])\n   loss+=r['w']*v\n  out.append(dict(p,actual=r['y'],weight=r['w'],scoreEligible=ok,loss=v))\n return dict(rows=out,eligibleRows=sum(r['scoreEligible']for r in out),weight=mass,totalLoss=loss,meanLoss=loss/mass if mass else None,MAE=absolute/mass if mass and task=='regression'else None,errorRate=errors/mass if mass and task=='classification'else None,labelVoteErrorRate=voteerrors/mass if mass and task=='classification'else None)\ndef ensemble(a,forest=False):\n task=a.get('task','regression');classes=[str(v)for v in(a.get('classes')or[])];rr=normalized(a['rows'],task);key=lambda x:(type(x).__name__,x);lookup={key(r['id']):r for r in rr};weights=[number(v)for v in a.get('memberWeights',[1]*len(a['bootstrapDraws']))]\n if not any(r['w']>0 and r['y']is not None for r in rr)or min(weights)<0 or sum(weights)<=0:raise ValueError('positive eligible training and member weight')\n members=[]\n for i,draw in enumerate(a['bootstrapDraws']):\n  data=[lookup[key(v)]for v in draw];schedule=a['nodeFeatures'][i]if forest else None;model=fit(data,a,task,classes,schedule);inbag={key(v)for v in draw};members.append(dict(tree=model,draw=draw,inbag=inbag,weight=weights[i]))\n predictions=[]\n for q in a.get('queries',[]):predictions.append(dict(id=q['id'],**combine([predict(m['tree'],[None if v is None else number(v)for v in q['x']])for m in members],weights,task,classes,a.get('aggregation','probabilities'))))\n oob=[]\n for r in rr:\n  applicable=[i for i,m in enumerate(members)if key(r['id'])not in m['inbag']];p=combine([predict(members[i]['tree'],r['x'])for i in applicable],[weights[i]for i in applicable],task,classes,a.get('aggregation','probabilities'));oob.append(dict(id=r['id'],applicable=applicable,positiveMembers=sum(weights[i]>0 for i in applicable),**p))\n return dict(task=task,classes=classes,members=members,predictions=predictions,outOfBag=scored(oob,rr,task,classes))\ndef boost(a):\n if a.get('task','regression')!='regression':raise ValueError('regression boosting only')\n rr=normalized(a['rows']);good=[r for r in rr if r['w']and r['y']is not None];W=sum((r['w']for r in good),Q())\n if not W:raise ValueError('positive eligible training')\n eta=number(a.get('learningRate','1/2'));stages=a.get('stages',3)\n if not 0<=eta<=1 or not isinstance(stages,int)or isinstance(stages,bool)or not 0<=stages<=8:raise ValueError('supported rate/stages')\n initial=number(a['initial'])if'initial'in a else sum((r['w']*r['y']for r in good),Q())/W;training=[[initial]for r in rr];queries=[[initial]for q in a.get('queries',[])];fits=[];losses=[]\n for stage in range(stages+1):\n  sse=sum((r['w']*(r['y']-p[-1])**2 for r,p in zip(rr,training)if r['w']and r['y']is not None),Q());losses.append(dict(stage=stage,rawWeightedSSE=sse,MSE=sse/W,meanHalfSquaredLoss=sse/(2*W)))\n  if stage==stages:break\n  residuals=[dict(r,y=None if r['y']is None else r['y']-p[-1])for r,p in zip(rr,training)];tree=fit(residuals,a,'regression',[]);h=[predict(tree,r['x'])['prediction']for r in rr];qh=[predict(tree,[None if v is None else number(v)for v in q['x']])['prediction']for q in a.get('queries',[])];norm=sum((r['w']*v*v for r,v in zip(rr,h)if r['y']is not None),Q());stageRows=[]\n  for i,(r,p)in enumerate(zip(rr,training)):\n   residual=None if r['y']is None else r['y']-p[-1];stageRows.append(dict(id=r['id'],before=p[-1],residual=residual,negativeCoordinateDerivative=None if residual is None else r['w']*residual/W,fit=h[i],addition=eta*h[i],after=p[-1]+eta*h[i]));p.append(p[-1]+eta*h[i])\n  for p,v in zip(queries,qh):p.append(p[-1]+eta*v)\n  fits.append(dict(stage=stage+1,tree=tree,rows=stageRows,queryFits=qh,norm=norm,predictedSSEDecrease=eta*(2-eta)*norm))\n return dict(task='regression',initial=initial,learningRate=eta,stages=stages,training=training,queries=queries,fits=fits,losses=losses,predictions=[dict(id=q['id'],prediction=p[-1],probabilities=[],vote=None,prob=None)for q,p in zip(a.get('queries',[]),queries)])\nclass Stream:\n def __init__(self,state):self.state=state\n def choose(self,n):\n  limit=(1<<32)-((1<<32)%n)\n  while True:\n   self.state=(1664525*self.state+1013904223)&0xffffffff\n   if self.state<limit:return self.state%n\ndef fixed_schedules(ids,p,seed):\n stream=Stream(seed);draws=[];schedules=[];paths=['']+[p for d in[1,2]for p in map(''.join,itertools.product('LR',repeat=d))]\n for member in range(4):\n  draws.append([ids[stream.choose(len(ids))]for _ in range(len(ids))]);schedule={}\n  for path in paths:\n   order=list(range(p))\n   for j in range(p-1,0,-1):k=stream.choose(j+1);order[j],order[k]=order[k],order[j]\n   schedule[path]=sorted(order[:max(1,int(math.sqrt(p)))])\n  schedules.append(schedule)\n return draws,schedules\ndef csvread(file):\n with Path(file).open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))\ndef read_sources(source):\n source=Path(source);raw=csvread(source/'actual320-country-four-indicators-original-2020-2024.csv');lookup={(r['countryISO3'],int(r['date']),r['indicatorID']):r for r in raw};country=[]\n for code in sorted({r['countryISO3']for r in raw}):\n  for year in range(2020,2025):\n   cols=['NY.GDP.PCAP.KD','NY.GDP.MKTP.KD.ZG','FP.CPI.TOTL.ZG','SP.DYN.LE00.IN'];v=[lookup[code,year,k]['originalValueToken']for k in cols];x=[None if not z else Q(z)for z in v[:3]];x[0]=None if x[0]is None else x[0]/10000;y=None if not v[3]else Q(v[3]);eligible=y is not None and None not in x;country.append(dict(id=code+':'+str(year),sourceRow=code+':'+str(year),originalID=code,year=year,x=x,y=y,weight='1',role='excluded'if not eligible else'outer-test'if year==2024 else'train'))\n person=[]\n for i,r in enumerate(csvread(source/'actual3613-NLS-original52-fields-and-selection.csv'),1):\n  v=lambda k:None if r[k]=='.'else Q(r[k]);x=[v('ed76'),v('age76')];y=None if v('wage76')is None else v('wage76')/100;eligible=y is not None and None not in x;person.append(dict(id='person:'+str(i),sourceRow=str(i),originalID=r['id'],x=x,y=y,weight='1',role='excluded'if not eligible else'outer-test'if i%5==0 else'train'))\n company=[]\n for i,r in enumerate(csvread(source/'actual3150-churn-original14-fields-and-selection.csv'),1):company.append(dict(id='customer:'+str(i),sourceRow=str(i),originalID='',x=[Q(r[k])for k in['Call  Failure','Subscription  Length','Charge  Amount']],y=r['Churn'],weight='1',role='outer-test'if i%5==0 else'train'))\n models={}\n for index,(kind,rr,task,leaf)in enumerate([('country',country,'regression',4),('person',person,'regression',50),('company',company,'classification',30)]):\n  ids=[r['id']for r in rr if r['role']=='train'];draws,schedules=fixed_schedules(ids,len(rr[0]['x']),20261102+7919*index);models[kind]=dict(records=rr,task=task,classes=['0','1']if task=='classification'else[],draws=draws,schedules=schedules,minLeaf=leaf)\n return models\n_OMITTED=object()\ndef realdata(models,kind,options=_OMITTED):\n options={}if options is _OMITTED else options\n if not isinstance(options,dict):raise ValueError('options object required, not explicit null')\n m=models[kind];train=[r for r in m['records']if r['role']=='train'];test=[r for r in m['records']if r['role']=='outer-test'];method=options.get('method','forest');depth=options.get('maxDepth',2);count=options.get('memberCount',3);a=dict(rows=train,queries=[dict(id=r['id'],x=r['x'])for r in test],task=m['task'],classes=m['classes'],maxDepth=depth,minLeaf=options.get('minLeaf',m['minLeaf']),minLeafWeight='0',minGain='0',missingRoute='best',learningRate=options.get('learningRate','1/2'),stages=options.get('stages',3))\n if method not in ['bagging','forest','boost']:raise ValueError('known source method')\n if not isinstance(depth,int)or isinstance(depth,bool)or not 0<=depth<=3:raise ValueError('source depth0..3')\n if method!='boost'and(not isinstance(count,int)or isinstance(count,bool)or not 1<=count<=4):raise ValueError('source member count1..4')\n if method=='boost':result=boost(a)\n else:\n  a.update(bootstrapDraws=m['draws'][:count],nodeFeatures=[{p:v for p,v in s.items()if len(p)<depth}for s in m['schedules'][:count]]);result=ensemble(a,method=='forest')\n outer=scored(result['predictions'],normalized(test,m['task']),m['task'],m['classes']);st=totals([r for r in normalized(train,m['task'])if r['w']and r['y']is not None],m['task'],m['classes']);constant=dict(prediction=st['pred'],probabilities=st['p'],vote=st['pred'],prob=st['pred']);baseline=scored([dict(id=r['id'],**constant)for r in test],normalized(test,m['task']),m['task'],m['classes']);return dict(kind=kind,method=method,settings=a,train=train,test=test,result=result,outer=outer,baseline=baseline)\ndef serial(x):\n if isinstance(x,Q):return str(x)\n if isinstance(x,dict):return{k:serial(v)for k,v in x.items()if k not in['inbag','tree']}\n if isinstance(x,(list,tuple)):return[serial(v)for v in x]\n return x\ndef writecsv(file,heads,rows):\n with Path(file).open('w',encoding='utf8',newline='')as f:\n  w=csv.writer(f);w.writerow(heads);w.writerows([[''if v is None else str(v)for v in r]for r in rows])\nAPI='variance'\nINPUT={'B': 4, 'marginalVariance': 4, 'rho': '1/2'}\n\ndef run_fixed(api,a,out,src):\n import matplotlib\n matplotlib.use('svg')\n import matplotlib.pyplot as plt\n from matplotlib.ticker import MaxNLocator\n plt.rcParams.update({'font.size':14,'svg.fonttype':'none','svg.hashsalt':'ml09-fixed-v1'})\n result=variance(a)if api=='variance'else aggregate(a)if api=='aggregate'else ensemble(a,api=='forest')if api in ['bagging','forest']else boost(a)if api=='boost'else realdata(read_sources(src),a['kind'])\n out=Path(out);out.mkdir(parents=True,exist_ok=True);summary={};points=[]\n def add(x,y,s):\n  if y is not None:points.append([x,y,s])\n if api=='variance':\n  summary={'B':result['B'],'varianceOfMean':result['varianceOfMean']};add(result['B'],result['varianceOfMean'],'Specified finite-B variance');xl='Number of members B';yl='Variance, stipulated units squared';title='Declared covariance model, not fitted trees'\n elif api=='aggregate':\n  p=result['predictions'][0];classification=a.get('task')=='classification';summary={'selectedPrediction':p['prediction']}\n  if classification:\n   summary.update(voteLabel=p['vote'],probabilityLabel=p['prob'],meanProbability1=p['probabilities'][1]);add(1,p['probabilities'][1],'Mean probability of class 1');add(2,p['votes'][1],'Label-vote share of class 1');xl='Aggregation (1=probability, 2=vote)';yl='Probability or vote share'\n  else:\n   for i,m in enumerate(a['members']):add(i+1,Q(m['predictions'][0]['value']),'Member prediction')\n   add(3,p['prediction'],'Weighted mean');xl='Member 1, member 2, aggregate 3';yl='Prediction, assumed units'\n  title='Votes and probabilities are distinct objects'\n elif api in ['bagging','forest']:\n  summary={'queryPrediction':result['predictions'][0]['prediction'],'OOB.scoreable':result['outOfBag']['eligibleRows'],'OOB.meanLoss':result['outOfBag']['meanLoss']}\n  for i,r in enumerate(a['rows']):add(i+1,Q(r['y']),'Observed training outcome')\n  for i,p in enumerate(result['outOfBag']['rows']):add(i+1,p['prediction'],'OOB prediction, when defined')\n  xl='Original training ID order';yl='Outcome, assumed units';title='Repeated draws and ID-level OOB membership'\n elif api=='boost':\n  summary={'initial':result['initial'],'finalMSE':result['losses'][-1]['MSE'],'stages':result['stages']}\n  for r in result['losses']:add(r['stage'],r['MSE'],'Training MSE')\n  xl='Boosting stage (0=initial)';yl='Weighted MSE, outcome units squared';title='Training descent does not certify held-out gain'\n else:\n  summary={'outer.scoreable':result['outer']['eligibleRows'],'outer.meanLoss':result['outer']['meanLoss'],'baseline.meanLoss':result['baseline']['meanLoss'],'OOB.scoreable':result['result']['outOfBag']['eligibleRows'],'OOB.meanLoss':result['result']['outOfBag']['meanLoss']}\n  for i,p in enumerate(result['outer']['rows']):\n   add(i+1,Q(p['actual']),'Observed outcome');add(i+1,p['probabilities'][1]if a['kind']=='company'else p['prediction'],'Forest probability of class 1'if a['kind']=='company'else'Forest prediction')\n  xl='Outer-test source order, not a time path';yl='Churn label / probability'if a['kind']=='company'else'Period life expectancy, years'if a['kind']=='country'else'Nominal 1976 USD per hour';title='Fixed forest; outer labels did not fit the trees'\n def display(v):return 'undefined'if v is None else format(float(v),'.9f')\n writecsv(out/'summary.csv',['metric','value'],[[k,display(v)]for k,v in summary.items()]);writecsv(out/'plot-points.csv',['x','y','series'],points);(out/'full.json').write_text(json.dumps(serial(result),indent=2)+'\\n',encoding='utf8')\n fig,ax=plt.subplots(figsize=(5.6,4.6));fig.subplots_adjust(left=.24,right=.96,bottom=.24,top=.76);colors=['#355c72','#a55336','#507956','#78568b']\n for i,s in enumerate(dict.fromkeys(p[2]for p in points)):\n  pp=[p for p in points if p[2]==s];ax.scatter([float(p[0])for p in pp],[float(p[1])for p in pp],s=12 if len(pp)>100 else 32,alpha=.5 if len(pp)>100 else 1,color=colors[i%4],label=s)\n ax.set_xlabel(xl,labelpad=10,fontsize=11);ax.set_ylabel(yl,labelpad=10,fontsize=11);ax.xaxis.set_major_locator(MaxNLocator(3));ax.yaxis.set_major_locator(MaxNLocator(4));ax.grid(alpha=.18);ax.legend(loc='lower left',bbox_to_anchor=(0,1.01),fontsize=9,frameon=False);fig.suptitle(title,fontsize=9,y=.99);fig.savefig(out/'plot.svg',metadata={'Date':None});plt.close(fig);print(', '.join(k+'='+display(v)for k,v in summary.items()))\nif __name__=='__main__':\n import sys\n try:run_fixed(API,INPUT,sys.argv[1]if len(sys.argv)>1 else'fixed-results',sys.argv[2]if len(sys.argv)>2 else'ml09-sources')\n except ValueError as error:print('Rejected declared input: '+str(error),file=sys.stderr);sys.exit(2)\n",
        "code": "\"\"\"ML09 exact Fraction reproduction from native source fields.\n\npython ml09-public-analysis.py --source-dir ml09-sources --output-dir results\n\nThis authored educational implementation uses direct-centered leaf losses and\nexhaustive midpoint partitions. It reads no JS engine, model contract, checker,\nstored target answers or derived-result CSV. Its five tree arithmetic helpers\nwere copied from the author's own separate Fraction reference, not an independent\npeer. Parser/work budgets and display rounding of the production JS are separate.\nNumerical predictions/proper scores do not certify causal effects, calibration,\nIID OOB validity, survey representativeness or production parameter optimality.\n\"\"\"\nfrom pathlib import Path\nfrom fractions import Fraction as Q\nimport csv,json,math,itertools,argparse\n\ndef normalized(rows,task='regression'):\n return [dict(id=r.get('id',i),x=[None if x is None else Q(x)for x in r.get('x',[])],y=None if r['y']is None else str(r['y'])if task=='classification'else Q(r['y']),w=Q(r.get('weight',1)))for i,r in enumerate(rows)]\n\ndef totals(rows,task,classes):\n W=sum((r['w']for r in rows),Q());mu=sum((r['w']*r['y']for r in rows),Q())/W if task=='regression'and W else None\n probs=[sum((r['w']for r in rows if r['y']==c),Q())/W for c in classes]if task=='classification'and W else[]\n risk=sum((r['w']*(r['y']-mu)**2 for r in rows),Q())if task=='regression'and W else W*sum((p*(1-p)for p in probs),Q())\n return dict(n=len(rows),w=W,mu=mu,p=probs,risk=risk,pred=mu if task=='regression'else classes[max(range(len(probs)),key=lambda i:probs[i])]if probs else None)\n\ndef fit(rows,a,task,classes,schedule=None):\n good=[r for r in rows if r['w']>0 and r['y']is not None];root=totals(good,task,classes)['w'];depth=a.get('maxDepth',2);minimum=a.get('minLeaf',1);minmass=Q(a.get('minLeafWeight',0));mingain=Q(a.get('minGain',0));route=a.get('missingRoute','best')\n def build(rr,d,path):\n  st=totals(rr,task,classes);n=dict(rows=rr,st=st,split=None,left=None,right=None,path=path)\n  if d==depth:return n\n  best=None\n  for j in range(len(rr[0]['x'])):\n   if schedule is not None and j not in schedule[path]:continue\n   values=sorted({r['x'][j]for r in rr if r['x'][j]is not None});missing=[r for r in rr if r['x'][j]is None];observed=[r for r in rr if r['x'][j]is not None]\n   candidates=[]\n   for lo,hi in zip(values,values[1:]):\n    q=(lo+hi)/2;left=[r for r in observed if r['x'][j]<=q];right=[r for r in observed if r['x'][j]>q];directions=[route]if route!='best'else['left','right']if missing else['left'if len(left)>=len(right)else'right']\n    for direction in directions:candidates.append(('threshold',q,direction,left+missing if direction=='left'else left,right+missing if direction=='right'else right))\n   if missing and observed:candidates.append(('missing-only',None,'left',missing,observed))\n   for kind,q,direction,left,right in candidates:\n    l=totals(left,task,classes);r=totals(right,task,classes)\n    if min(l['n'],r['n'])<minimum or min(l['w'],r['w'])<minmass or min(l['w'],r['w'])<=0:continue\n    gain=(st['risk']-l['risk']-r['risk'])/root\n    if best is None or gain>best['gain']:best=dict(feature=j,kind=kind,threshold=q,missingRoute=direction,left=left,right=right,gain=gain)\n  if best and best['gain']>0 and best['gain']>mingain:\n   j=best['feature'];go=lambda r:r['x'][j]is None if best['kind']=='missing-only'else best['missingRoute']=='left'if r['x'][j]is None else r['x'][j]<=best['threshold'];n['split']=best;n['left']=build([r for r in rr if go(r)],d+1,path+'L');n['right']=build([r for r in rr if not go(r)],d+1,path+'R')\n  return n\n return build(good,0,'')\n\ndef predict(tree,x):\n n=tree\n while n['split']:\n  s=n['split'];v=x[s['feature']];left=v is None if s['kind']=='missing-only'else s['missingRoute']=='left'if v is None else v<=s['threshold'];n=n['left'if left else'right']\n return dict(prediction=n['st']['pred'],probabilities=n['st']['p'])\n\ndef combine(preds,w,task,classes,mode='probabilities'):\n mass=sum(w,Q())\n if not preds or not mass:return dict(prediction=None,probabilities=[],vote=None,prob=None)\n if task=='regression':return dict(prediction=sum((p['prediction']*v for p,v in zip(preds,w)),Q())/mass,probabilities=[],vote=None,prob=None)\n votes=[sum((v for p,v in zip(preds,w)if p['prediction']==c),Q())/mass for c in classes];ps=[sum((p['probabilities'][j]*v for p,v in zip(preds,w)),Q())/mass for j in range(len(classes))];vote=classes[max(range(len(classes)),key=lambda j:votes[j])];prob=classes[max(range(len(classes)),key=lambda j:ps[j])];return dict(prediction=vote if mode=='votes'else prob,probabilities=ps,vote=vote,prob=prob,votes=votes)\ndef number(v):\n if v is None or isinstance(v,bool):raise ValueError('explicit null/bool is not a numeric parameter')\n return Q(v)\ndef variance(a):\n B=a['B'];v=number(a['marginalVariance']);rho=number(a.get('rho',0))\n if not isinstance(B,int)or isinstance(B,bool)or B<1 or v<0:raise ValueError('positive integer B/nonnegative variance')\n if B>1 and v and not -Q(1,B-1)<=rho<=1:raise ValueError('equicorrelation PSD bound')\n return dict(B=B,marginalVariance=v,correlationApplicable=B>1 and bool(v),varianceOfMean=v if B==1 else v*(1+(B-1)*rho)/B)\ndef aggregate(a):\n task=a.get('task','regression');classes=[str(c)for c in a.get('classes',[])];members=a['members'];w=[number(v)for v in a.get('memberWeights',[1]*len(members))]\n if not members or min(w)<0 or sum(w)<=0:raise ValueError('nonnegative member weights/positive total')\n order=[p.get('id',i)for i,p in enumerate(members[0]['predictions'])];keys=lambda x:(type(x).__name__,x);lookup=[{keys(p.get('id',i)):p for i,p in enumerate(m['predictions'])}for m in members]\n if any(set(m)!={keys(v)for v in order}for m in lookup):raise ValueError('same query ID set')\n out=[]\n for pid in order:\n  predictions=[dict(prediction=number(m[keys(pid)]['value']),probabilities=[])if task=='regression'else dict(prediction=str(m[keys(pid)]['label']),probabilities=[number(v)for v in m[keys(pid)]['probabilities']])for m in lookup]\n  if task=='classification'and any(min(p['probabilities'])<0 or sum(p['probabilities'])!=1 for p in predictions):raise ValueError('probability simplex')\n  out.append(dict(id=pid,**combine(predictions,w,task,classes,a.get('aggregation','probabilities'))))\n return dict(task=task,classes=classes,predictions=out)\ndef scored(preds,rows,task,classes):\n mass=loss=absolute=errors=voteerrors=Q();out=[]\n for p,r in zip(preds,rows):\n  ok=p['prediction']is not None and r['y']is not None and r['w']>0;v=None\n  if ok:\n   mass+=r['w']\n   if task=='regression':e=r['y']-p['prediction'];v=e*e;absolute+=r['w']*abs(e)\n   else:v=sum(((q-(1 if r['y']==c else 0))**2 for c,q in zip(classes,p['probabilities'])),Q());errors+=r['w']*(p['prediction']!=r['y']);voteerrors+=r['w']*(p['vote']!=r['y'])\n   loss+=r['w']*v\n  out.append(dict(p,actual=r['y'],weight=r['w'],scoreEligible=ok,loss=v))\n return dict(rows=out,eligibleRows=sum(r['scoreEligible']for r in out),weight=mass,totalLoss=loss,meanLoss=loss/mass if mass else None,MAE=absolute/mass if mass and task=='regression'else None,errorRate=errors/mass if mass and task=='classification'else None,labelVoteErrorRate=voteerrors/mass if mass and task=='classification'else None)\ndef ensemble(a,forest=False):\n task=a.get('task','regression');classes=[str(v)for v in(a.get('classes')or[])];rr=normalized(a['rows'],task);key=lambda x:(type(x).__name__,x);lookup={key(r['id']):r for r in rr};weights=[number(v)for v in a.get('memberWeights',[1]*len(a['bootstrapDraws']))]\n if not any(r['w']>0 and r['y']is not None for r in rr)or min(weights)<0 or sum(weights)<=0:raise ValueError('positive eligible training and member weight')\n members=[]\n for i,draw in enumerate(a['bootstrapDraws']):\n  data=[lookup[key(v)]for v in draw];schedule=a['nodeFeatures'][i]if forest else None;model=fit(data,a,task,classes,schedule);inbag={key(v)for v in draw};members.append(dict(tree=model,draw=draw,inbag=inbag,weight=weights[i]))\n predictions=[]\n for q in a.get('queries',[]):predictions.append(dict(id=q['id'],**combine([predict(m['tree'],[None if v is None else number(v)for v in q['x']])for m in members],weights,task,classes,a.get('aggregation','probabilities'))))\n oob=[]\n for r in rr:\n  applicable=[i for i,m in enumerate(members)if key(r['id'])not in m['inbag']];p=combine([predict(members[i]['tree'],r['x'])for i in applicable],[weights[i]for i in applicable],task,classes,a.get('aggregation','probabilities'));oob.append(dict(id=r['id'],applicable=applicable,positiveMembers=sum(weights[i]>0 for i in applicable),**p))\n return dict(task=task,classes=classes,members=members,predictions=predictions,outOfBag=scored(oob,rr,task,classes))\ndef boost(a):\n if a.get('task','regression')!='regression':raise ValueError('regression boosting only')\n rr=normalized(a['rows']);good=[r for r in rr if r['w']and r['y']is not None];W=sum((r['w']for r in good),Q())\n if not W:raise ValueError('positive eligible training')\n eta=number(a.get('learningRate','1/2'));stages=a.get('stages',3)\n if not 0<=eta<=1 or not isinstance(stages,int)or isinstance(stages,bool)or not 0<=stages<=8:raise ValueError('supported rate/stages')\n initial=number(a['initial'])if'initial'in a else sum((r['w']*r['y']for r in good),Q())/W;training=[[initial]for r in rr];queries=[[initial]for q in a.get('queries',[])];fits=[];losses=[]\n for stage in range(stages+1):\n  sse=sum((r['w']*(r['y']-p[-1])**2 for r,p in zip(rr,training)if r['w']and r['y']is not None),Q());losses.append(dict(stage=stage,rawWeightedSSE=sse,MSE=sse/W,meanHalfSquaredLoss=sse/(2*W)))\n  if stage==stages:break\n  residuals=[dict(r,y=None if r['y']is None else r['y']-p[-1])for r,p in zip(rr,training)];tree=fit(residuals,a,'regression',[]);h=[predict(tree,r['x'])['prediction']for r in rr];qh=[predict(tree,[None if v is None else number(v)for v in q['x']])['prediction']for q in a.get('queries',[])];norm=sum((r['w']*v*v for r,v in zip(rr,h)if r['y']is not None),Q());stageRows=[]\n  for i,(r,p)in enumerate(zip(rr,training)):\n   residual=None if r['y']is None else r['y']-p[-1];stageRows.append(dict(id=r['id'],before=p[-1],residual=residual,negativeCoordinateDerivative=None if residual is None else r['w']*residual/W,fit=h[i],addition=eta*h[i],after=p[-1]+eta*h[i]));p.append(p[-1]+eta*h[i])\n  for p,v in zip(queries,qh):p.append(p[-1]+eta*v)\n  fits.append(dict(stage=stage+1,tree=tree,rows=stageRows,queryFits=qh,norm=norm,predictedSSEDecrease=eta*(2-eta)*norm))\n return dict(task='regression',initial=initial,learningRate=eta,stages=stages,training=training,queries=queries,fits=fits,losses=losses,predictions=[dict(id=q['id'],prediction=p[-1],probabilities=[],vote=None,prob=None)for q,p in zip(a.get('queries',[]),queries)])\nclass Stream:\n def __init__(self,state):self.state=state\n def choose(self,n):\n  limit=(1<<32)-((1<<32)%n)\n  while True:\n   self.state=(1664525*self.state+1013904223)&0xffffffff\n   if self.state<limit:return self.state%n\ndef fixed_schedules(ids,p,seed):\n stream=Stream(seed);draws=[];schedules=[];paths=['']+[p for d in[1,2]for p in map(''.join,itertools.product('LR',repeat=d))]\n for member in range(4):\n  draws.append([ids[stream.choose(len(ids))]for _ in range(len(ids))]);schedule={}\n  for path in paths:\n   order=list(range(p))\n   for j in range(p-1,0,-1):k=stream.choose(j+1);order[j],order[k]=order[k],order[j]\n   schedule[path]=sorted(order[:max(1,int(math.sqrt(p)))])\n  schedules.append(schedule)\n return draws,schedules\ndef csvread(file):\n with Path(file).open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))\ndef read_sources(source):\n source=Path(source);raw=csvread(source/'actual320-country-four-indicators-original-2020-2024.csv');lookup={(r['countryISO3'],int(r['date']),r['indicatorID']):r for r in raw};country=[]\n for code in sorted({r['countryISO3']for r in raw}):\n  for year in range(2020,2025):\n   cols=['NY.GDP.PCAP.KD','NY.GDP.MKTP.KD.ZG','FP.CPI.TOTL.ZG','SP.DYN.LE00.IN'];v=[lookup[code,year,k]['originalValueToken']for k in cols];x=[None if not z else Q(z)for z in v[:3]];x[0]=None if x[0]is None else x[0]/10000;y=None if not v[3]else Q(v[3]);eligible=y is not None and None not in x;country.append(dict(id=code+':'+str(year),sourceRow=code+':'+str(year),originalID=code,year=year,x=x,y=y,weight='1',role='excluded'if not eligible else'outer-test'if year==2024 else'train'))\n person=[]\n for i,r in enumerate(csvread(source/'actual3613-NLS-original52-fields-and-selection.csv'),1):\n  v=lambda k:None if r[k]=='.'else Q(r[k]);x=[v('ed76'),v('age76')];y=None if v('wage76')is None else v('wage76')/100;eligible=y is not None and None not in x;person.append(dict(id='person:'+str(i),sourceRow=str(i),originalID=r['id'],x=x,y=y,weight='1',role='excluded'if not eligible else'outer-test'if i%5==0 else'train'))\n company=[]\n for i,r in enumerate(csvread(source/'actual3150-churn-original14-fields-and-selection.csv'),1):company.append(dict(id='customer:'+str(i),sourceRow=str(i),originalID='',x=[Q(r[k])for k in['Call  Failure','Subscription  Length','Charge  Amount']],y=r['Churn'],weight='1',role='outer-test'if i%5==0 else'train'))\n models={}\n for index,(kind,rr,task,leaf)in enumerate([('country',country,'regression',4),('person',person,'regression',50),('company',company,'classification',30)]):\n  ids=[r['id']for r in rr if r['role']=='train'];draws,schedules=fixed_schedules(ids,len(rr[0]['x']),20261102+7919*index);models[kind]=dict(records=rr,task=task,classes=['0','1']if task=='classification'else[],draws=draws,schedules=schedules,minLeaf=leaf)\n return models\n_OMITTED=object()\ndef realdata(models,kind,options=_OMITTED):\n options={}if options is _OMITTED else options\n if not isinstance(options,dict):raise ValueError('options object required, not explicit null')\n m=models[kind];train=[r for r in m['records']if r['role']=='train'];test=[r for r in m['records']if r['role']=='outer-test'];method=options.get('method','forest');depth=options.get('maxDepth',2);count=options.get('memberCount',3);a=dict(rows=train,queries=[dict(id=r['id'],x=r['x'])for r in test],task=m['task'],classes=m['classes'],maxDepth=depth,minLeaf=options.get('minLeaf',m['minLeaf']),minLeafWeight='0',minGain='0',missingRoute='best',learningRate=options.get('learningRate','1/2'),stages=options.get('stages',3))\n if method not in ['bagging','forest','boost']:raise ValueError('known source method')\n if not isinstance(depth,int)or isinstance(depth,bool)or not 0<=depth<=3:raise ValueError('source depth0..3')\n if method!='boost'and(not isinstance(count,int)or isinstance(count,bool)or not 1<=count<=4):raise ValueError('source member count1..4')\n if method=='boost':result=boost(a)\n else:\n  a.update(bootstrapDraws=m['draws'][:count],nodeFeatures=[{p:v for p,v in s.items()if len(p)<depth}for s in m['schedules'][:count]]);result=ensemble(a,method=='forest')\n outer=scored(result['predictions'],normalized(test,m['task']),m['task'],m['classes']);st=totals([r for r in normalized(train,m['task'])if r['w']and r['y']is not None],m['task'],m['classes']);constant=dict(prediction=st['pred'],probabilities=st['p'],vote=st['pred'],prob=st['pred']);baseline=scored([dict(id=r['id'],**constant)for r in test],normalized(test,m['task']),m['task'],m['classes']);return dict(kind=kind,method=method,settings=a,train=train,test=test,result=result,outer=outer,baseline=baseline)\ndef serial(x):\n if isinstance(x,Q):return str(x)\n if isinstance(x,dict):return{k:serial(v)for k,v in x.items()if k not in['inbag','tree']}\n if isinstance(x,(list,tuple)):return[serial(v)for v in x]\n return x\ndef writecsv(file,heads,rows):\n with Path(file).open('w',encoding='utf8',newline='')as f:\n  w=csv.writer(f);w.writerow(heads);w.writerows([[''if v is None else str(v)for v in r]for r in rows])\nAPI='variance'\nINPUT={'B': 4, 'marginalVariance': 4, 'rho': '1/2'}\n\ndef run_fixed(api,a,out,src):\n import matplotlib\n matplotlib.use('svg')\n import matplotlib.pyplot as plt\n from matplotlib.ticker import MaxNLocator\n plt.rcParams.update({'font.size':14,'svg.fonttype':'none','svg.hashsalt':'ml09-fixed-v1'})\n result=variance(a)if api=='variance'else aggregate(a)if api=='aggregate'else ensemble(a,api=='forest')if api in ['bagging','forest']else boost(a)if api=='boost'else realdata(read_sources(src),a['kind'])\n out=Path(out);out.mkdir(parents=True,exist_ok=True);summary={};points=[]\n def add(x,y,s):\n  if y is not None:points.append([x,y,s])\n if api=='variance':\n  summary={'B':result['B'],'varianceOfMean':result['varianceOfMean']};add(result['B'],result['varianceOfMean'],'Specified finite-B variance');xl='Number of members B';yl='Variance, stipulated units squared';title='Declared covariance model, not fitted trees'\n elif api=='aggregate':\n  p=result['predictions'][0];classification=a.get('task')=='classification';summary={'selectedPrediction':p['prediction']}\n  if classification:\n   summary.update(voteLabel=p['vote'],probabilityLabel=p['prob'],meanProbability1=p['probabilities'][1]);add(1,p['probabilities'][1],'Mean probability of class 1');add(2,p['votes'][1],'Label-vote share of class 1');xl='Aggregation (1=probability, 2=vote)';yl='Probability or vote share'\n  else:\n   for i,m in enumerate(a['members']):add(i+1,Q(m['predictions'][0]['value']),'Member prediction')\n   add(3,p['prediction'],'Weighted mean');xl='Member 1, member 2, aggregate 3';yl='Prediction, assumed units'\n  title='Votes and probabilities are distinct objects'\n elif api in ['bagging','forest']:\n  summary={'queryPrediction':result['predictions'][0]['prediction'],'OOB.scoreable':result['outOfBag']['eligibleRows'],'OOB.meanLoss':result['outOfBag']['meanLoss']}\n  for i,r in enumerate(a['rows']):add(i+1,Q(r['y']),'Observed training outcome')\n  for i,p in enumerate(result['outOfBag']['rows']):add(i+1,p['prediction'],'OOB prediction, when defined')\n  xl='Original training ID order';yl='Outcome, assumed units';title='Repeated draws and ID-level OOB membership'\n elif api=='boost':\n  summary={'initial':result['initial'],'finalMSE':result['losses'][-1]['MSE'],'stages':result['stages']}\n  for r in result['losses']:add(r['stage'],r['MSE'],'Training MSE')\n  xl='Boosting stage (0=initial)';yl='Weighted MSE, outcome units squared';title='Training descent does not certify held-out gain'\n else:\n  summary={'outer.scoreable':result['outer']['eligibleRows'],'outer.meanLoss':result['outer']['meanLoss'],'baseline.meanLoss':result['baseline']['meanLoss'],'OOB.scoreable':result['result']['outOfBag']['eligibleRows'],'OOB.meanLoss':result['result']['outOfBag']['meanLoss']}\n  for i,p in enumerate(result['outer']['rows']):\n   add(i+1,Q(p['actual']),'Observed outcome');add(i+1,p['probabilities'][1]if a['kind']=='company'else p['prediction'],'Forest probability of class 1'if a['kind']=='company'else'Forest prediction')\n  xl='Outer-test source order, not a time path';yl='Churn label / probability'if a['kind']=='company'else'Period life expectancy, years'if a['kind']=='country'else'Nominal 1976 USD per hour';title='Fixed forest; outer labels did not fit the trees'\n def display(v):return 'undefined'if v is None else format(float(v),'.9f')\n writecsv(out/'summary.csv',['metric','value'],[[k,display(v)]for k,v in summary.items()]);writecsv(out/'plot-points.csv',['x','y','series'],points);(out/'full.json').write_text(json.dumps(serial(result),indent=2)+'\\n',encoding='utf8')\n fig,ax=plt.subplots(figsize=(5.6,4.6));fig.subplots_adjust(left=.24,right=.96,bottom=.24,top=.76);colors=['#355c72','#a55336','#507956','#78568b']\n for i,s in enumerate(dict.fromkeys(p[2]for p in points)):\n  pp=[p for p in points if p[2]==s];ax.scatter([float(p[0])for p in pp],[float(p[1])for p in pp],s=12 if len(pp)>100 else 32,alpha=.5 if len(pp)>100 else 1,color=colors[i%4],label=s)\n ax.set_xlabel(xl,labelpad=10,fontsize=11);ax.set_ylabel(yl,labelpad=10,fontsize=11);ax.xaxis.set_major_locator(MaxNLocator(3));ax.yaxis.set_major_locator(MaxNLocator(4));ax.grid(alpha=.18);ax.legend(loc='lower left',bbox_to_anchor=(0,1.01),fontsize=9,frameon=False);fig.suptitle(title,fontsize=9,y=.99);fig.savefig(out/'plot.svg',metadata={'Date':None});plt.close(fig);print(', '.join(k+'='+display(v)for k,v in summary.items()))\nif __name__=='__main__':\n import sys\n try:run_fixed(API,INPUT,sys.argv[1]if len(sys.argv)>1 else'fixed-results',sys.argv[2]if len(sys.argv)>2 else'ml09-sources')\n except ValueError as error:print('Rejected declared input: '+str(error),file=sys.stderr);sys.exit(2)\n",
        "inputFiles": [],
        "input": {
          "B": 4,
          "marginalVariance": 4,
          "rho": "1/2"
        },
        "returnCode": 0,
        "expectedFailure": false,
        "stdout": "B=4.000000000, varianceOfMean=2.500000000\n",
        "stderr": "",
        "summary": {
          "B": "4.000000000",
          "varianceOfMean": "2.500000000"
        },
        "plotPoints": [
          {
            "x": "4",
            "y": "5/2",
            "series": "Specified finite-B variance"
          }
        ],
        "plotFile": "ml09-fixed-results/variance-correlated-python/plot.svg",
        "plotSHA256": "9ad8d4d181cfa0a7cc532c14dd4ed362b713e1df13c1e83de82bff4142884e73",
        "files": [
          {
            "file": "ml09-fixed-results/variance-correlated-python/full.json",
            "sha256": "10d8517edfe3f157daf74bccc9c45b0f01485730611aa5b9c6c4760454933e19"
          },
          {
            "file": "ml09-fixed-results/variance-correlated-python/plot-points.csv",
            "sha256": "79d86002ac323a9d3cd905351ada3079f25fc582a61aacaa4e45deb4a8683515"
          },
          {
            "file": "ml09-fixed-results/variance-correlated-python/plot.svg",
            "sha256": "9ad8d4d181cfa0a7cc532c14dd4ed362b713e1df13c1e83de82bff4142884e73"
          },
          {
            "file": "ml09-fixed-results/variance-correlated-python/summary.csv",
            "sha256": "7c83a234552d08a1894c507bfaaf7a1ec0f9ab6ae2cd815f2f10cc0b28f37297"
          }
        ],
        "scope": "Actually executed self-contained fixed example; current web controls execute separately. Python Fraction and finite-precision base R. Author gate, not independent peer."
      },
      "independent": {
        "api": "variance",
        "variant": "independent",
        "language": "python",
        "codeFile": "ml09-code/variance-independent.py",
        "codeSHA256": "aa480e78a5e4b69d01ed972887eb5f3fd8f8ee8dabddf46947580df64160c84e",
        "codeText": "\"\"\"ML09 exact Fraction reproduction from native source fields.\n\npython ml09-public-analysis.py --source-dir ml09-sources --output-dir results\n\nThis authored educational implementation uses direct-centered leaf losses and\nexhaustive midpoint partitions. It reads no JS engine, model contract, checker,\nstored target answers or derived-result CSV. Its five tree arithmetic helpers\nwere copied from the author's own separate Fraction reference, not an independent\npeer. Parser/work budgets and display rounding of the production JS are separate.\nNumerical predictions/proper scores do not certify causal effects, calibration,\nIID OOB validity, survey representativeness or production parameter optimality.\n\"\"\"\nfrom pathlib import Path\nfrom fractions import Fraction as Q\nimport csv,json,math,itertools,argparse\n\ndef normalized(rows,task='regression'):\n return [dict(id=r.get('id',i),x=[None if x is None else Q(x)for x in r.get('x',[])],y=None if r['y']is None else str(r['y'])if task=='classification'else Q(r['y']),w=Q(r.get('weight',1)))for i,r in enumerate(rows)]\n\ndef totals(rows,task,classes):\n W=sum((r['w']for r in rows),Q());mu=sum((r['w']*r['y']for r in rows),Q())/W if task=='regression'and W else None\n probs=[sum((r['w']for r in rows if r['y']==c),Q())/W for c in classes]if task=='classification'and W else[]\n risk=sum((r['w']*(r['y']-mu)**2 for r in rows),Q())if task=='regression'and W else W*sum((p*(1-p)for p in probs),Q())\n return dict(n=len(rows),w=W,mu=mu,p=probs,risk=risk,pred=mu if task=='regression'else classes[max(range(len(probs)),key=lambda i:probs[i])]if probs else None)\n\ndef fit(rows,a,task,classes,schedule=None):\n good=[r for r in rows if r['w']>0 and r['y']is not None];root=totals(good,task,classes)['w'];depth=a.get('maxDepth',2);minimum=a.get('minLeaf',1);minmass=Q(a.get('minLeafWeight',0));mingain=Q(a.get('minGain',0));route=a.get('missingRoute','best')\n def build(rr,d,path):\n  st=totals(rr,task,classes);n=dict(rows=rr,st=st,split=None,left=None,right=None,path=path)\n  if d==depth:return n\n  best=None\n  for j in range(len(rr[0]['x'])):\n   if schedule is not None and j not in schedule[path]:continue\n   values=sorted({r['x'][j]for r in rr if r['x'][j]is not None});missing=[r for r in rr if r['x'][j]is None];observed=[r for r in rr if r['x'][j]is not None]\n   candidates=[]\n   for lo,hi in zip(values,values[1:]):\n    q=(lo+hi)/2;left=[r for r in observed if r['x'][j]<=q];right=[r for r in observed if r['x'][j]>q];directions=[route]if route!='best'else['left','right']if missing else['left'if len(left)>=len(right)else'right']\n    for direction in directions:candidates.append(('threshold',q,direction,left+missing if direction=='left'else left,right+missing if direction=='right'else right))\n   if missing and observed:candidates.append(('missing-only',None,'left',missing,observed))\n   for kind,q,direction,left,right in candidates:\n    l=totals(left,task,classes);r=totals(right,task,classes)\n    if min(l['n'],r['n'])<minimum or min(l['w'],r['w'])<minmass or min(l['w'],r['w'])<=0:continue\n    gain=(st['risk']-l['risk']-r['risk'])/root\n    if best is None or gain>best['gain']:best=dict(feature=j,kind=kind,threshold=q,missingRoute=direction,left=left,right=right,gain=gain)\n  if best and best['gain']>0 and best['gain']>mingain:\n   j=best['feature'];go=lambda r:r['x'][j]is None if best['kind']=='missing-only'else best['missingRoute']=='left'if r['x'][j]is None else r['x'][j]<=best['threshold'];n['split']=best;n['left']=build([r for r in rr if go(r)],d+1,path+'L');n['right']=build([r for r in rr if not go(r)],d+1,path+'R')\n  return n\n return build(good,0,'')\n\ndef predict(tree,x):\n n=tree\n while n['split']:\n  s=n['split'];v=x[s['feature']];left=v is None if s['kind']=='missing-only'else s['missingRoute']=='left'if v is None else v<=s['threshold'];n=n['left'if left else'right']\n return dict(prediction=n['st']['pred'],probabilities=n['st']['p'])\n\ndef combine(preds,w,task,classes,mode='probabilities'):\n mass=sum(w,Q())\n if not preds or not mass:return dict(prediction=None,probabilities=[],vote=None,prob=None)\n if task=='regression':return dict(prediction=sum((p['prediction']*v for p,v in zip(preds,w)),Q())/mass,probabilities=[],vote=None,prob=None)\n votes=[sum((v for p,v in zip(preds,w)if p['prediction']==c),Q())/mass for c in classes];ps=[sum((p['probabilities'][j]*v for p,v in zip(preds,w)),Q())/mass for j in range(len(classes))];vote=classes[max(range(len(classes)),key=lambda j:votes[j])];prob=classes[max(range(len(classes)),key=lambda j:ps[j])];return dict(prediction=vote if mode=='votes'else prob,probabilities=ps,vote=vote,prob=prob,votes=votes)\ndef number(v):\n if v is None or isinstance(v,bool):raise ValueError('explicit null/bool is not a numeric parameter')\n return Q(v)\ndef variance(a):\n B=a['B'];v=number(a['marginalVariance']);rho=number(a.get('rho',0))\n if not isinstance(B,int)or isinstance(B,bool)or B<1 or v<0:raise ValueError('positive integer B/nonnegative variance')\n if B>1 and v and not -Q(1,B-1)<=rho<=1:raise ValueError('equicorrelation PSD bound')\n return dict(B=B,marginalVariance=v,correlationApplicable=B>1 and bool(v),varianceOfMean=v if B==1 else v*(1+(B-1)*rho)/B)\ndef aggregate(a):\n task=a.get('task','regression');classes=[str(c)for c in a.get('classes',[])];members=a['members'];w=[number(v)for v in a.get('memberWeights',[1]*len(members))]\n if not members or min(w)<0 or sum(w)<=0:raise ValueError('nonnegative member weights/positive total')\n order=[p.get('id',i)for i,p in enumerate(members[0]['predictions'])];keys=lambda x:(type(x).__name__,x);lookup=[{keys(p.get('id',i)):p for i,p in enumerate(m['predictions'])}for m in members]\n if any(set(m)!={keys(v)for v in order}for m in lookup):raise ValueError('same query ID set')\n out=[]\n for pid in order:\n  predictions=[dict(prediction=number(m[keys(pid)]['value']),probabilities=[])if task=='regression'else dict(prediction=str(m[keys(pid)]['label']),probabilities=[number(v)for v in m[keys(pid)]['probabilities']])for m in lookup]\n  if task=='classification'and any(min(p['probabilities'])<0 or sum(p['probabilities'])!=1 for p in predictions):raise ValueError('probability simplex')\n  out.append(dict(id=pid,**combine(predictions,w,task,classes,a.get('aggregation','probabilities'))))\n return dict(task=task,classes=classes,predictions=out)\ndef scored(preds,rows,task,classes):\n mass=loss=absolute=errors=voteerrors=Q();out=[]\n for p,r in zip(preds,rows):\n  ok=p['prediction']is not None and r['y']is not None and r['w']>0;v=None\n  if ok:\n   mass+=r['w']\n   if task=='regression':e=r['y']-p['prediction'];v=e*e;absolute+=r['w']*abs(e)\n   else:v=sum(((q-(1 if r['y']==c else 0))**2 for c,q in zip(classes,p['probabilities'])),Q());errors+=r['w']*(p['prediction']!=r['y']);voteerrors+=r['w']*(p['vote']!=r['y'])\n   loss+=r['w']*v\n  out.append(dict(p,actual=r['y'],weight=r['w'],scoreEligible=ok,loss=v))\n return dict(rows=out,eligibleRows=sum(r['scoreEligible']for r in out),weight=mass,totalLoss=loss,meanLoss=loss/mass if mass else None,MAE=absolute/mass if mass and task=='regression'else None,errorRate=errors/mass if mass and task=='classification'else None,labelVoteErrorRate=voteerrors/mass if mass and task=='classification'else None)\ndef ensemble(a,forest=False):\n task=a.get('task','regression');classes=[str(v)for v in(a.get('classes')or[])];rr=normalized(a['rows'],task);key=lambda x:(type(x).__name__,x);lookup={key(r['id']):r for r in rr};weights=[number(v)for v in a.get('memberWeights',[1]*len(a['bootstrapDraws']))]\n if not any(r['w']>0 and r['y']is not None for r in rr)or min(weights)<0 or sum(weights)<=0:raise ValueError('positive eligible training and member weight')\n members=[]\n for i,draw in enumerate(a['bootstrapDraws']):\n  data=[lookup[key(v)]for v in draw];schedule=a['nodeFeatures'][i]if forest else None;model=fit(data,a,task,classes,schedule);inbag={key(v)for v in draw};members.append(dict(tree=model,draw=draw,inbag=inbag,weight=weights[i]))\n predictions=[]\n for q in a.get('queries',[]):predictions.append(dict(id=q['id'],**combine([predict(m['tree'],[None if v is None else number(v)for v in q['x']])for m in members],weights,task,classes,a.get('aggregation','probabilities'))))\n oob=[]\n for r in rr:\n  applicable=[i for i,m in enumerate(members)if key(r['id'])not in m['inbag']];p=combine([predict(members[i]['tree'],r['x'])for i in applicable],[weights[i]for i in applicable],task,classes,a.get('aggregation','probabilities'));oob.append(dict(id=r['id'],applicable=applicable,positiveMembers=sum(weights[i]>0 for i in applicable),**p))\n return dict(task=task,classes=classes,members=members,predictions=predictions,outOfBag=scored(oob,rr,task,classes))\ndef boost(a):\n if a.get('task','regression')!='regression':raise ValueError('regression boosting only')\n rr=normalized(a['rows']);good=[r for r in rr if r['w']and r['y']is not None];W=sum((r['w']for r in good),Q())\n if not W:raise ValueError('positive eligible training')\n eta=number(a.get('learningRate','1/2'));stages=a.get('stages',3)\n if not 0<=eta<=1 or not isinstance(stages,int)or isinstance(stages,bool)or not 0<=stages<=8:raise ValueError('supported rate/stages')\n initial=number(a['initial'])if'initial'in a else sum((r['w']*r['y']for r in good),Q())/W;training=[[initial]for r in rr];queries=[[initial]for q in a.get('queries',[])];fits=[];losses=[]\n for stage in range(stages+1):\n  sse=sum((r['w']*(r['y']-p[-1])**2 for r,p in zip(rr,training)if r['w']and r['y']is not None),Q());losses.append(dict(stage=stage,rawWeightedSSE=sse,MSE=sse/W,meanHalfSquaredLoss=sse/(2*W)))\n  if stage==stages:break\n  residuals=[dict(r,y=None if r['y']is None else r['y']-p[-1])for r,p in zip(rr,training)];tree=fit(residuals,a,'regression',[]);h=[predict(tree,r['x'])['prediction']for r in rr];qh=[predict(tree,[None if v is None else number(v)for v in q['x']])['prediction']for q in a.get('queries',[])];norm=sum((r['w']*v*v for r,v in zip(rr,h)if r['y']is not None),Q());stageRows=[]\n  for i,(r,p)in enumerate(zip(rr,training)):\n   residual=None if r['y']is None else r['y']-p[-1];stageRows.append(dict(id=r['id'],before=p[-1],residual=residual,negativeCoordinateDerivative=None if residual is None else r['w']*residual/W,fit=h[i],addition=eta*h[i],after=p[-1]+eta*h[i]));p.append(p[-1]+eta*h[i])\n  for p,v in zip(queries,qh):p.append(p[-1]+eta*v)\n  fits.append(dict(stage=stage+1,tree=tree,rows=stageRows,queryFits=qh,norm=norm,predictedSSEDecrease=eta*(2-eta)*norm))\n return dict(task='regression',initial=initial,learningRate=eta,stages=stages,training=training,queries=queries,fits=fits,losses=losses,predictions=[dict(id=q['id'],prediction=p[-1],probabilities=[],vote=None,prob=None)for q,p in zip(a.get('queries',[]),queries)])\nclass Stream:\n def __init__(self,state):self.state=state\n def choose(self,n):\n  limit=(1<<32)-((1<<32)%n)\n  while True:\n   self.state=(1664525*self.state+1013904223)&0xffffffff\n   if self.state<limit:return self.state%n\ndef fixed_schedules(ids,p,seed):\n stream=Stream(seed);draws=[];schedules=[];paths=['']+[p for d in[1,2]for p in map(''.join,itertools.product('LR',repeat=d))]\n for member in range(4):\n  draws.append([ids[stream.choose(len(ids))]for _ in range(len(ids))]);schedule={}\n  for path in paths:\n   order=list(range(p))\n   for j in range(p-1,0,-1):k=stream.choose(j+1);order[j],order[k]=order[k],order[j]\n   schedule[path]=sorted(order[:max(1,int(math.sqrt(p)))])\n  schedules.append(schedule)\n return draws,schedules\ndef csvread(file):\n with Path(file).open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))\ndef read_sources(source):\n source=Path(source);raw=csvread(source/'actual320-country-four-indicators-original-2020-2024.csv');lookup={(r['countryISO3'],int(r['date']),r['indicatorID']):r for r in raw};country=[]\n for code in sorted({r['countryISO3']for r in raw}):\n  for year in range(2020,2025):\n   cols=['NY.GDP.PCAP.KD','NY.GDP.MKTP.KD.ZG','FP.CPI.TOTL.ZG','SP.DYN.LE00.IN'];v=[lookup[code,year,k]['originalValueToken']for k in cols];x=[None if not z else Q(z)for z in v[:3]];x[0]=None if x[0]is None else x[0]/10000;y=None if not v[3]else Q(v[3]);eligible=y is not None and None not in x;country.append(dict(id=code+':'+str(year),sourceRow=code+':'+str(year),originalID=code,year=year,x=x,y=y,weight='1',role='excluded'if not eligible else'outer-test'if year==2024 else'train'))\n person=[]\n for i,r in enumerate(csvread(source/'actual3613-NLS-original52-fields-and-selection.csv'),1):\n  v=lambda k:None if r[k]=='.'else Q(r[k]);x=[v('ed76'),v('age76')];y=None if v('wage76')is None else v('wage76')/100;eligible=y is not None and None not in x;person.append(dict(id='person:'+str(i),sourceRow=str(i),originalID=r['id'],x=x,y=y,weight='1',role='excluded'if not eligible else'outer-test'if i%5==0 else'train'))\n company=[]\n for i,r in enumerate(csvread(source/'actual3150-churn-original14-fields-and-selection.csv'),1):company.append(dict(id='customer:'+str(i),sourceRow=str(i),originalID='',x=[Q(r[k])for k in['Call  Failure','Subscription  Length','Charge  Amount']],y=r['Churn'],weight='1',role='outer-test'if i%5==0 else'train'))\n models={}\n for index,(kind,rr,task,leaf)in enumerate([('country',country,'regression',4),('person',person,'regression',50),('company',company,'classification',30)]):\n  ids=[r['id']for r in rr if r['role']=='train'];draws,schedules=fixed_schedules(ids,len(rr[0]['x']),20261102+7919*index);models[kind]=dict(records=rr,task=task,classes=['0','1']if task=='classification'else[],draws=draws,schedules=schedules,minLeaf=leaf)\n return models\n_OMITTED=object()\ndef realdata(models,kind,options=_OMITTED):\n options={}if options is _OMITTED else options\n if not isinstance(options,dict):raise ValueError('options object required, not explicit null')\n m=models[kind];train=[r for r in m['records']if r['role']=='train'];test=[r for r in m['records']if r['role']=='outer-test'];method=options.get('method','forest');depth=options.get('maxDepth',2);count=options.get('memberCount',3);a=dict(rows=train,queries=[dict(id=r['id'],x=r['x'])for r in test],task=m['task'],classes=m['classes'],maxDepth=depth,minLeaf=options.get('minLeaf',m['minLeaf']),minLeafWeight='0',minGain='0',missingRoute='best',learningRate=options.get('learningRate','1/2'),stages=options.get('stages',3))\n if method not in ['bagging','forest','boost']:raise ValueError('known source method')\n if not isinstance(depth,int)or isinstance(depth,bool)or not 0<=depth<=3:raise ValueError('source depth0..3')\n if method!='boost'and(not isinstance(count,int)or isinstance(count,bool)or not 1<=count<=4):raise ValueError('source member count1..4')\n if method=='boost':result=boost(a)\n else:\n  a.update(bootstrapDraws=m['draws'][:count],nodeFeatures=[{p:v for p,v in s.items()if len(p)<depth}for s in m['schedules'][:count]]);result=ensemble(a,method=='forest')\n outer=scored(result['predictions'],normalized(test,m['task']),m['task'],m['classes']);st=totals([r for r in normalized(train,m['task'])if r['w']and r['y']is not None],m['task'],m['classes']);constant=dict(prediction=st['pred'],probabilities=st['p'],vote=st['pred'],prob=st['pred']);baseline=scored([dict(id=r['id'],**constant)for r in test],normalized(test,m['task']),m['task'],m['classes']);return dict(kind=kind,method=method,settings=a,train=train,test=test,result=result,outer=outer,baseline=baseline)\ndef serial(x):\n if isinstance(x,Q):return str(x)\n if isinstance(x,dict):return{k:serial(v)for k,v in x.items()if k not in['inbag','tree']}\n if isinstance(x,(list,tuple)):return[serial(v)for v in x]\n return x\ndef writecsv(file,heads,rows):\n with Path(file).open('w',encoding='utf8',newline='')as f:\n  w=csv.writer(f);w.writerow(heads);w.writerows([[''if v is None else str(v)for v in r]for r in rows])\nAPI='variance'\nINPUT={'B': 10, 'marginalVariance': 4, 'rho': 0}\n\ndef run_fixed(api,a,out,src):\n import matplotlib\n matplotlib.use('svg')\n import matplotlib.pyplot as plt\n from matplotlib.ticker import MaxNLocator\n plt.rcParams.update({'font.size':14,'svg.fonttype':'none','svg.hashsalt':'ml09-fixed-v1'})\n result=variance(a)if api=='variance'else aggregate(a)if api=='aggregate'else ensemble(a,api=='forest')if api in ['bagging','forest']else boost(a)if api=='boost'else realdata(read_sources(src),a['kind'])\n out=Path(out);out.mkdir(parents=True,exist_ok=True);summary={};points=[]\n def add(x,y,s):\n  if y is not None:points.append([x,y,s])\n if api=='variance':\n  summary={'B':result['B'],'varianceOfMean':result['varianceOfMean']};add(result['B'],result['varianceOfMean'],'Specified finite-B variance');xl='Number of members B';yl='Variance, stipulated units squared';title='Declared covariance model, not fitted trees'\n elif api=='aggregate':\n  p=result['predictions'][0];classification=a.get('task')=='classification';summary={'selectedPrediction':p['prediction']}\n  if classification:\n   summary.update(voteLabel=p['vote'],probabilityLabel=p['prob'],meanProbability1=p['probabilities'][1]);add(1,p['probabilities'][1],'Mean probability of class 1');add(2,p['votes'][1],'Label-vote share of class 1');xl='Aggregation (1=probability, 2=vote)';yl='Probability or vote share'\n  else:\n   for i,m in enumerate(a['members']):add(i+1,Q(m['predictions'][0]['value']),'Member prediction')\n   add(3,p['prediction'],'Weighted mean');xl='Member 1, member 2, aggregate 3';yl='Prediction, assumed units'\n  title='Votes and probabilities are distinct objects'\n elif api in ['bagging','forest']:\n  summary={'queryPrediction':result['predictions'][0]['prediction'],'OOB.scoreable':result['outOfBag']['eligibleRows'],'OOB.meanLoss':result['outOfBag']['meanLoss']}\n  for i,r in enumerate(a['rows']):add(i+1,Q(r['y']),'Observed training outcome')\n  for i,p in enumerate(result['outOfBag']['rows']):add(i+1,p['prediction'],'OOB prediction, when defined')\n  xl='Original training ID order';yl='Outcome, assumed units';title='Repeated draws and ID-level OOB membership'\n elif api=='boost':\n  summary={'initial':result['initial'],'finalMSE':result['losses'][-1]['MSE'],'stages':result['stages']}\n  for r in result['losses']:add(r['stage'],r['MSE'],'Training MSE')\n  xl='Boosting stage (0=initial)';yl='Weighted MSE, outcome units squared';title='Training descent does not certify held-out gain'\n else:\n  summary={'outer.scoreable':result['outer']['eligibleRows'],'outer.meanLoss':result['outer']['meanLoss'],'baseline.meanLoss':result['baseline']['meanLoss'],'OOB.scoreable':result['result']['outOfBag']['eligibleRows'],'OOB.meanLoss':result['result']['outOfBag']['meanLoss']}\n  for i,p in enumerate(result['outer']['rows']):\n   add(i+1,Q(p['actual']),'Observed outcome');add(i+1,p['probabilities'][1]if a['kind']=='company'else p['prediction'],'Forest probability of class 1'if a['kind']=='company'else'Forest prediction')\n  xl='Outer-test source order, not a time path';yl='Churn label / probability'if a['kind']=='company'else'Period life expectancy, years'if a['kind']=='country'else'Nominal 1976 USD per hour';title='Fixed forest; outer labels did not fit the trees'\n def display(v):return 'undefined'if v is None else format(float(v),'.9f')\n writecsv(out/'summary.csv',['metric','value'],[[k,display(v)]for k,v in summary.items()]);writecsv(out/'plot-points.csv',['x','y','series'],points);(out/'full.json').write_text(json.dumps(serial(result),indent=2)+'\\n',encoding='utf8')\n fig,ax=plt.subplots(figsize=(5.6,4.6));fig.subplots_adjust(left=.24,right=.96,bottom=.24,top=.76);colors=['#355c72','#a55336','#507956','#78568b']\n for i,s in enumerate(dict.fromkeys(p[2]for p in points)):\n  pp=[p for p in points if p[2]==s];ax.scatter([float(p[0])for p in pp],[float(p[1])for p in pp],s=12 if len(pp)>100 else 32,alpha=.5 if len(pp)>100 else 1,color=colors[i%4],label=s)\n ax.set_xlabel(xl,labelpad=10,fontsize=11);ax.set_ylabel(yl,labelpad=10,fontsize=11);ax.xaxis.set_major_locator(MaxNLocator(3));ax.yaxis.set_major_locator(MaxNLocator(4));ax.grid(alpha=.18);ax.legend(loc='lower left',bbox_to_anchor=(0,1.01),fontsize=9,frameon=False);fig.suptitle(title,fontsize=9,y=.99);fig.savefig(out/'plot.svg',metadata={'Date':None});plt.close(fig);print(', '.join(k+'='+display(v)for k,v in summary.items()))\nif __name__=='__main__':\n import sys\n try:run_fixed(API,INPUT,sys.argv[1]if len(sys.argv)>1 else'fixed-results',sys.argv[2]if len(sys.argv)>2 else'ml09-sources')\n except ValueError as error:print('Rejected declared input: '+str(error),file=sys.stderr);sys.exit(2)\n",
        "code": "\"\"\"ML09 exact Fraction reproduction from native source fields.\n\npython ml09-public-analysis.py --source-dir ml09-sources --output-dir results\n\nThis authored educational implementation uses direct-centered leaf losses and\nexhaustive midpoint partitions. It reads no JS engine, model contract, checker,\nstored target answers or derived-result CSV. Its five tree arithmetic helpers\nwere copied from the author's own separate Fraction reference, not an independent\npeer. Parser/work budgets and display rounding of the production JS are separate.\nNumerical predictions/proper scores do not certify causal effects, calibration,\nIID OOB validity, survey representativeness or production parameter optimality.\n\"\"\"\nfrom pathlib import Path\nfrom fractions import Fraction as Q\nimport csv,json,math,itertools,argparse\n\ndef normalized(rows,task='regression'):\n return [dict(id=r.get('id',i),x=[None if x is None else Q(x)for x in r.get('x',[])],y=None if r['y']is None else str(r['y'])if task=='classification'else Q(r['y']),w=Q(r.get('weight',1)))for i,r in enumerate(rows)]\n\ndef totals(rows,task,classes):\n W=sum((r['w']for r in rows),Q());mu=sum((r['w']*r['y']for r in rows),Q())/W if task=='regression'and W else None\n probs=[sum((r['w']for r in rows if r['y']==c),Q())/W for c in classes]if task=='classification'and W else[]\n risk=sum((r['w']*(r['y']-mu)**2 for r in rows),Q())if task=='regression'and W else W*sum((p*(1-p)for p in probs),Q())\n return dict(n=len(rows),w=W,mu=mu,p=probs,risk=risk,pred=mu if task=='regression'else classes[max(range(len(probs)),key=lambda i:probs[i])]if probs else None)\n\ndef fit(rows,a,task,classes,schedule=None):\n good=[r for r in rows if r['w']>0 and r['y']is not None];root=totals(good,task,classes)['w'];depth=a.get('maxDepth',2);minimum=a.get('minLeaf',1);minmass=Q(a.get('minLeafWeight',0));mingain=Q(a.get('minGain',0));route=a.get('missingRoute','best')\n def build(rr,d,path):\n  st=totals(rr,task,classes);n=dict(rows=rr,st=st,split=None,left=None,right=None,path=path)\n  if d==depth:return n\n  best=None\n  for j in range(len(rr[0]['x'])):\n   if schedule is not None and j not in schedule[path]:continue\n   values=sorted({r['x'][j]for r in rr if r['x'][j]is not None});missing=[r for r in rr if r['x'][j]is None];observed=[r for r in rr if r['x'][j]is not None]\n   candidates=[]\n   for lo,hi in zip(values,values[1:]):\n    q=(lo+hi)/2;left=[r for r in observed if r['x'][j]<=q];right=[r for r in observed if r['x'][j]>q];directions=[route]if route!='best'else['left','right']if missing else['left'if len(left)>=len(right)else'right']\n    for direction in directions:candidates.append(('threshold',q,direction,left+missing if direction=='left'else left,right+missing if direction=='right'else right))\n   if missing and observed:candidates.append(('missing-only',None,'left',missing,observed))\n   for kind,q,direction,left,right in candidates:\n    l=totals(left,task,classes);r=totals(right,task,classes)\n    if min(l['n'],r['n'])<minimum or min(l['w'],r['w'])<minmass or min(l['w'],r['w'])<=0:continue\n    gain=(st['risk']-l['risk']-r['risk'])/root\n    if best is None or gain>best['gain']:best=dict(feature=j,kind=kind,threshold=q,missingRoute=direction,left=left,right=right,gain=gain)\n  if best and best['gain']>0 and best['gain']>mingain:\n   j=best['feature'];go=lambda r:r['x'][j]is None if best['kind']=='missing-only'else best['missingRoute']=='left'if r['x'][j]is None else r['x'][j]<=best['threshold'];n['split']=best;n['left']=build([r for r in rr if go(r)],d+1,path+'L');n['right']=build([r for r in rr if not go(r)],d+1,path+'R')\n  return n\n return build(good,0,'')\n\ndef predict(tree,x):\n n=tree\n while n['split']:\n  s=n['split'];v=x[s['feature']];left=v is None if s['kind']=='missing-only'else s['missingRoute']=='left'if v is None else v<=s['threshold'];n=n['left'if left else'right']\n return dict(prediction=n['st']['pred'],probabilities=n['st']['p'])\n\ndef combine(preds,w,task,classes,mode='probabilities'):\n mass=sum(w,Q())\n if not preds or not mass:return dict(prediction=None,probabilities=[],vote=None,prob=None)\n if task=='regression':return dict(prediction=sum((p['prediction']*v for p,v in zip(preds,w)),Q())/mass,probabilities=[],vote=None,prob=None)\n votes=[sum((v for p,v in zip(preds,w)if p['prediction']==c),Q())/mass for c in classes];ps=[sum((p['probabilities'][j]*v for p,v in zip(preds,w)),Q())/mass for j in range(len(classes))];vote=classes[max(range(len(classes)),key=lambda j:votes[j])];prob=classes[max(range(len(classes)),key=lambda j:ps[j])];return dict(prediction=vote if mode=='votes'else prob,probabilities=ps,vote=vote,prob=prob,votes=votes)\ndef number(v):\n if v is None or isinstance(v,bool):raise ValueError('explicit null/bool is not a numeric parameter')\n return Q(v)\ndef variance(a):\n B=a['B'];v=number(a['marginalVariance']);rho=number(a.get('rho',0))\n if not isinstance(B,int)or isinstance(B,bool)or B<1 or v<0:raise ValueError('positive integer B/nonnegative variance')\n if B>1 and v and not -Q(1,B-1)<=rho<=1:raise ValueError('equicorrelation PSD bound')\n return dict(B=B,marginalVariance=v,correlationApplicable=B>1 and bool(v),varianceOfMean=v if B==1 else v*(1+(B-1)*rho)/B)\ndef aggregate(a):\n task=a.get('task','regression');classes=[str(c)for c in a.get('classes',[])];members=a['members'];w=[number(v)for v in a.get('memberWeights',[1]*len(members))]\n if not members or min(w)<0 or sum(w)<=0:raise ValueError('nonnegative member weights/positive total')\n order=[p.get('id',i)for i,p in enumerate(members[0]['predictions'])];keys=lambda x:(type(x).__name__,x);lookup=[{keys(p.get('id',i)):p for i,p in enumerate(m['predictions'])}for m in members]\n if any(set(m)!={keys(v)for v in order}for m in lookup):raise ValueError('same query ID set')\n out=[]\n for pid in order:\n  predictions=[dict(prediction=number(m[keys(pid)]['value']),probabilities=[])if task=='regression'else dict(prediction=str(m[keys(pid)]['label']),probabilities=[number(v)for v in m[keys(pid)]['probabilities']])for m in lookup]\n  if task=='classification'and any(min(p['probabilities'])<0 or sum(p['probabilities'])!=1 for p in predictions):raise ValueError('probability simplex')\n  out.append(dict(id=pid,**combine(predictions,w,task,classes,a.get('aggregation','probabilities'))))\n return dict(task=task,classes=classes,predictions=out)\ndef scored(preds,rows,task,classes):\n mass=loss=absolute=errors=voteerrors=Q();out=[]\n for p,r in zip(preds,rows):\n  ok=p['prediction']is not None and r['y']is not None and r['w']>0;v=None\n  if ok:\n   mass+=r['w']\n   if task=='regression':e=r['y']-p['prediction'];v=e*e;absolute+=r['w']*abs(e)\n   else:v=sum(((q-(1 if r['y']==c else 0))**2 for c,q in zip(classes,p['probabilities'])),Q());errors+=r['w']*(p['prediction']!=r['y']);voteerrors+=r['w']*(p['vote']!=r['y'])\n   loss+=r['w']*v\n  out.append(dict(p,actual=r['y'],weight=r['w'],scoreEligible=ok,loss=v))\n return dict(rows=out,eligibleRows=sum(r['scoreEligible']for r in out),weight=mass,totalLoss=loss,meanLoss=loss/mass if mass else None,MAE=absolute/mass if mass and task=='regression'else None,errorRate=errors/mass if mass and task=='classification'else None,labelVoteErrorRate=voteerrors/mass if mass and task=='classification'else None)\ndef ensemble(a,forest=False):\n task=a.get('task','regression');classes=[str(v)for v in(a.get('classes')or[])];rr=normalized(a['rows'],task);key=lambda x:(type(x).__name__,x);lookup={key(r['id']):r for r in rr};weights=[number(v)for v in a.get('memberWeights',[1]*len(a['bootstrapDraws']))]\n if not any(r['w']>0 and r['y']is not None for r in rr)or min(weights)<0 or sum(weights)<=0:raise ValueError('positive eligible training and member weight')\n members=[]\n for i,draw in enumerate(a['bootstrapDraws']):\n  data=[lookup[key(v)]for v in draw];schedule=a['nodeFeatures'][i]if forest else None;model=fit(data,a,task,classes,schedule);inbag={key(v)for v in draw};members.append(dict(tree=model,draw=draw,inbag=inbag,weight=weights[i]))\n predictions=[]\n for q in a.get('queries',[]):predictions.append(dict(id=q['id'],**combine([predict(m['tree'],[None if v is None else number(v)for v in q['x']])for m in members],weights,task,classes,a.get('aggregation','probabilities'))))\n oob=[]\n for r in rr:\n  applicable=[i for i,m in enumerate(members)if key(r['id'])not in m['inbag']];p=combine([predict(members[i]['tree'],r['x'])for i in applicable],[weights[i]for i in applicable],task,classes,a.get('aggregation','probabilities'));oob.append(dict(id=r['id'],applicable=applicable,positiveMembers=sum(weights[i]>0 for i in applicable),**p))\n return dict(task=task,classes=classes,members=members,predictions=predictions,outOfBag=scored(oob,rr,task,classes))\ndef boost(a):\n if a.get('task','regression')!='regression':raise ValueError('regression boosting only')\n rr=normalized(a['rows']);good=[r for r in rr if r['w']and r['y']is not None];W=sum((r['w']for r in good),Q())\n if not W:raise ValueError('positive eligible training')\n eta=number(a.get('learningRate','1/2'));stages=a.get('stages',3)\n if not 0<=eta<=1 or not isinstance(stages,int)or isinstance(stages,bool)or not 0<=stages<=8:raise ValueError('supported rate/stages')\n initial=number(a['initial'])if'initial'in a else sum((r['w']*r['y']for r in good),Q())/W;training=[[initial]for r in rr];queries=[[initial]for q in a.get('queries',[])];fits=[];losses=[]\n for stage in range(stages+1):\n  sse=sum((r['w']*(r['y']-p[-1])**2 for r,p in zip(rr,training)if r['w']and r['y']is not None),Q());losses.append(dict(stage=stage,rawWeightedSSE=sse,MSE=sse/W,meanHalfSquaredLoss=sse/(2*W)))\n  if stage==stages:break\n  residuals=[dict(r,y=None if r['y']is None else r['y']-p[-1])for r,p in zip(rr,training)];tree=fit(residuals,a,'regression',[]);h=[predict(tree,r['x'])['prediction']for r in rr];qh=[predict(tree,[None if v is None else number(v)for v in q['x']])['prediction']for q in a.get('queries',[])];norm=sum((r['w']*v*v for r,v in zip(rr,h)if r['y']is not None),Q());stageRows=[]\n  for i,(r,p)in enumerate(zip(rr,training)):\n   residual=None if r['y']is None else r['y']-p[-1];stageRows.append(dict(id=r['id'],before=p[-1],residual=residual,negativeCoordinateDerivative=None if residual is None else r['w']*residual/W,fit=h[i],addition=eta*h[i],after=p[-1]+eta*h[i]));p.append(p[-1]+eta*h[i])\n  for p,v in zip(queries,qh):p.append(p[-1]+eta*v)\n  fits.append(dict(stage=stage+1,tree=tree,rows=stageRows,queryFits=qh,norm=norm,predictedSSEDecrease=eta*(2-eta)*norm))\n return dict(task='regression',initial=initial,learningRate=eta,stages=stages,training=training,queries=queries,fits=fits,losses=losses,predictions=[dict(id=q['id'],prediction=p[-1],probabilities=[],vote=None,prob=None)for q,p in zip(a.get('queries',[]),queries)])\nclass Stream:\n def __init__(self,state):self.state=state\n def choose(self,n):\n  limit=(1<<32)-((1<<32)%n)\n  while True:\n   self.state=(1664525*self.state+1013904223)&0xffffffff\n   if self.state<limit:return self.state%n\ndef fixed_schedules(ids,p,seed):\n stream=Stream(seed);draws=[];schedules=[];paths=['']+[p for d in[1,2]for p in map(''.join,itertools.product('LR',repeat=d))]\n for member in range(4):\n  draws.append([ids[stream.choose(len(ids))]for _ in range(len(ids))]);schedule={}\n  for path in paths:\n   order=list(range(p))\n   for j in range(p-1,0,-1):k=stream.choose(j+1);order[j],order[k]=order[k],order[j]\n   schedule[path]=sorted(order[:max(1,int(math.sqrt(p)))])\n  schedules.append(schedule)\n return draws,schedules\ndef csvread(file):\n with Path(file).open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))\ndef read_sources(source):\n source=Path(source);raw=csvread(source/'actual320-country-four-indicators-original-2020-2024.csv');lookup={(r['countryISO3'],int(r['date']),r['indicatorID']):r for r in raw};country=[]\n for code in sorted({r['countryISO3']for r in raw}):\n  for year in range(2020,2025):\n   cols=['NY.GDP.PCAP.KD','NY.GDP.MKTP.KD.ZG','FP.CPI.TOTL.ZG','SP.DYN.LE00.IN'];v=[lookup[code,year,k]['originalValueToken']for k in cols];x=[None if not z else Q(z)for z in v[:3]];x[0]=None if x[0]is None else x[0]/10000;y=None if not v[3]else Q(v[3]);eligible=y is not None and None not in x;country.append(dict(id=code+':'+str(year),sourceRow=code+':'+str(year),originalID=code,year=year,x=x,y=y,weight='1',role='excluded'if not eligible else'outer-test'if year==2024 else'train'))\n person=[]\n for i,r in enumerate(csvread(source/'actual3613-NLS-original52-fields-and-selection.csv'),1):\n  v=lambda k:None if r[k]=='.'else Q(r[k]);x=[v('ed76'),v('age76')];y=None if v('wage76')is None else v('wage76')/100;eligible=y is not None and None not in x;person.append(dict(id='person:'+str(i),sourceRow=str(i),originalID=r['id'],x=x,y=y,weight='1',role='excluded'if not eligible else'outer-test'if i%5==0 else'train'))\n company=[]\n for i,r in enumerate(csvread(source/'actual3150-churn-original14-fields-and-selection.csv'),1):company.append(dict(id='customer:'+str(i),sourceRow=str(i),originalID='',x=[Q(r[k])for k in['Call  Failure','Subscription  Length','Charge  Amount']],y=r['Churn'],weight='1',role='outer-test'if i%5==0 else'train'))\n models={}\n for index,(kind,rr,task,leaf)in enumerate([('country',country,'regression',4),('person',person,'regression',50),('company',company,'classification',30)]):\n  ids=[r['id']for r in rr if r['role']=='train'];draws,schedules=fixed_schedules(ids,len(rr[0]['x']),20261102+7919*index);models[kind]=dict(records=rr,task=task,classes=['0','1']if task=='classification'else[],draws=draws,schedules=schedules,minLeaf=leaf)\n return models\n_OMITTED=object()\ndef realdata(models,kind,options=_OMITTED):\n options={}if options is _OMITTED else options\n if not isinstance(options,dict):raise ValueError('options object required, not explicit null')\n m=models[kind];train=[r for r in m['records']if r['role']=='train'];test=[r for r in m['records']if r['role']=='outer-test'];method=options.get('method','forest');depth=options.get('maxDepth',2);count=options.get('memberCount',3);a=dict(rows=train,queries=[dict(id=r['id'],x=r['x'])for r in test],task=m['task'],classes=m['classes'],maxDepth=depth,minLeaf=options.get('minLeaf',m['minLeaf']),minLeafWeight='0',minGain='0',missingRoute='best',learningRate=options.get('learningRate','1/2'),stages=options.get('stages',3))\n if method not in ['bagging','forest','boost']:raise ValueError('known source method')\n if not isinstance(depth,int)or isinstance(depth,bool)or not 0<=depth<=3:raise ValueError('source depth0..3')\n if method!='boost'and(not isinstance(count,int)or isinstance(count,bool)or not 1<=count<=4):raise ValueError('source member count1..4')\n if method=='boost':result=boost(a)\n else:\n  a.update(bootstrapDraws=m['draws'][:count],nodeFeatures=[{p:v for p,v in s.items()if len(p)<depth}for s in m['schedules'][:count]]);result=ensemble(a,method=='forest')\n outer=scored(result['predictions'],normalized(test,m['task']),m['task'],m['classes']);st=totals([r for r in normalized(train,m['task'])if r['w']and r['y']is not None],m['task'],m['classes']);constant=dict(prediction=st['pred'],probabilities=st['p'],vote=st['pred'],prob=st['pred']);baseline=scored([dict(id=r['id'],**constant)for r in test],normalized(test,m['task']),m['task'],m['classes']);return dict(kind=kind,method=method,settings=a,train=train,test=test,result=result,outer=outer,baseline=baseline)\ndef serial(x):\n if isinstance(x,Q):return str(x)\n if isinstance(x,dict):return{k:serial(v)for k,v in x.items()if k not in['inbag','tree']}\n if isinstance(x,(list,tuple)):return[serial(v)for v in x]\n return x\ndef writecsv(file,heads,rows):\n with Path(file).open('w',encoding='utf8',newline='')as f:\n  w=csv.writer(f);w.writerow(heads);w.writerows([[''if v is None else str(v)for v in r]for r in rows])\nAPI='variance'\nINPUT={'B': 10, 'marginalVariance': 4, 'rho': 0}\n\ndef run_fixed(api,a,out,src):\n import matplotlib\n matplotlib.use('svg')\n import matplotlib.pyplot as plt\n from matplotlib.ticker import MaxNLocator\n plt.rcParams.update({'font.size':14,'svg.fonttype':'none','svg.hashsalt':'ml09-fixed-v1'})\n result=variance(a)if api=='variance'else aggregate(a)if api=='aggregate'else ensemble(a,api=='forest')if api in ['bagging','forest']else boost(a)if api=='boost'else realdata(read_sources(src),a['kind'])\n out=Path(out);out.mkdir(parents=True,exist_ok=True);summary={};points=[]\n def add(x,y,s):\n  if y is not None:points.append([x,y,s])\n if api=='variance':\n  summary={'B':result['B'],'varianceOfMean':result['varianceOfMean']};add(result['B'],result['varianceOfMean'],'Specified finite-B variance');xl='Number of members B';yl='Variance, stipulated units squared';title='Declared covariance model, not fitted trees'\n elif api=='aggregate':\n  p=result['predictions'][0];classification=a.get('task')=='classification';summary={'selectedPrediction':p['prediction']}\n  if classification:\n   summary.update(voteLabel=p['vote'],probabilityLabel=p['prob'],meanProbability1=p['probabilities'][1]);add(1,p['probabilities'][1],'Mean probability of class 1');add(2,p['votes'][1],'Label-vote share of class 1');xl='Aggregation (1=probability, 2=vote)';yl='Probability or vote share'\n  else:\n   for i,m in enumerate(a['members']):add(i+1,Q(m['predictions'][0]['value']),'Member prediction')\n   add(3,p['prediction'],'Weighted mean');xl='Member 1, member 2, aggregate 3';yl='Prediction, assumed units'\n  title='Votes and probabilities are distinct objects'\n elif api in ['bagging','forest']:\n  summary={'queryPrediction':result['predictions'][0]['prediction'],'OOB.scoreable':result['outOfBag']['eligibleRows'],'OOB.meanLoss':result['outOfBag']['meanLoss']}\n  for i,r in enumerate(a['rows']):add(i+1,Q(r['y']),'Observed training outcome')\n  for i,p in enumerate(result['outOfBag']['rows']):add(i+1,p['prediction'],'OOB prediction, when defined')\n  xl='Original training ID order';yl='Outcome, assumed units';title='Repeated draws and ID-level OOB membership'\n elif api=='boost':\n  summary={'initial':result['initial'],'finalMSE':result['losses'][-1]['MSE'],'stages':result['stages']}\n  for r in result['losses']:add(r['stage'],r['MSE'],'Training MSE')\n  xl='Boosting stage (0=initial)';yl='Weighted MSE, outcome units squared';title='Training descent does not certify held-out gain'\n else:\n  summary={'outer.scoreable':result['outer']['eligibleRows'],'outer.meanLoss':result['outer']['meanLoss'],'baseline.meanLoss':result['baseline']['meanLoss'],'OOB.scoreable':result['result']['outOfBag']['eligibleRows'],'OOB.meanLoss':result['result']['outOfBag']['meanLoss']}\n  for i,p in enumerate(result['outer']['rows']):\n   add(i+1,Q(p['actual']),'Observed outcome');add(i+1,p['probabilities'][1]if a['kind']=='company'else p['prediction'],'Forest probability of class 1'if a['kind']=='company'else'Forest prediction')\n  xl='Outer-test source order, not a time path';yl='Churn label / probability'if a['kind']=='company'else'Period life expectancy, years'if a['kind']=='country'else'Nominal 1976 USD per hour';title='Fixed forest; outer labels did not fit the trees'\n def display(v):return 'undefined'if v is None else format(float(v),'.9f')\n writecsv(out/'summary.csv',['metric','value'],[[k,display(v)]for k,v in summary.items()]);writecsv(out/'plot-points.csv',['x','y','series'],points);(out/'full.json').write_text(json.dumps(serial(result),indent=2)+'\\n',encoding='utf8')\n fig,ax=plt.subplots(figsize=(5.6,4.6));fig.subplots_adjust(left=.24,right=.96,bottom=.24,top=.76);colors=['#355c72','#a55336','#507956','#78568b']\n for i,s in enumerate(dict.fromkeys(p[2]for p in points)):\n  pp=[p for p in points if p[2]==s];ax.scatter([float(p[0])for p in pp],[float(p[1])for p in pp],s=12 if len(pp)>100 else 32,alpha=.5 if len(pp)>100 else 1,color=colors[i%4],label=s)\n ax.set_xlabel(xl,labelpad=10,fontsize=11);ax.set_ylabel(yl,labelpad=10,fontsize=11);ax.xaxis.set_major_locator(MaxNLocator(3));ax.yaxis.set_major_locator(MaxNLocator(4));ax.grid(alpha=.18);ax.legend(loc='lower left',bbox_to_anchor=(0,1.01),fontsize=9,frameon=False);fig.suptitle(title,fontsize=9,y=.99);fig.savefig(out/'plot.svg',metadata={'Date':None});plt.close(fig);print(', '.join(k+'='+display(v)for k,v in summary.items()))\nif __name__=='__main__':\n import sys\n try:run_fixed(API,INPUT,sys.argv[1]if len(sys.argv)>1 else'fixed-results',sys.argv[2]if len(sys.argv)>2 else'ml09-sources')\n except ValueError as error:print('Rejected declared input: '+str(error),file=sys.stderr);sys.exit(2)\n",
        "inputFiles": [],
        "input": {
          "B": 10,
          "marginalVariance": 4,
          "rho": 0
        },
        "returnCode": 0,
        "expectedFailure": false,
        "stdout": "B=10.000000000, varianceOfMean=0.400000000\n",
        "stderr": "",
        "summary": {
          "B": "10.000000000",
          "varianceOfMean": "0.400000000"
        },
        "plotPoints": [
          {
            "x": "10",
            "y": "2/5",
            "series": "Specified finite-B variance"
          }
        ],
        "plotFile": "ml09-fixed-results/variance-independent-python/plot.svg",
        "plotSHA256": "afb5658aac097df48488cd53f844023b92ec7ca6df9d2ff41b9839548049b3a0",
        "files": [
          {
            "file": "ml09-fixed-results/variance-independent-python/full.json",
            "sha256": "964556ed7bd3ced6006fbe754762b0049c58b9c9be2d9f572ccf12e9398025ce"
          },
          {
            "file": "ml09-fixed-results/variance-independent-python/plot-points.csv",
            "sha256": "80b3fbad1a059df774deea6ac54a3f7c5e113bfe1dcec47ddb21a2101227812c"
          },
          {
            "file": "ml09-fixed-results/variance-independent-python/plot.svg",
            "sha256": "afb5658aac097df48488cd53f844023b92ec7ca6df9d2ff41b9839548049b3a0"
          },
          {
            "file": "ml09-fixed-results/variance-independent-python/summary.csv",
            "sha256": "3d79efee6e1b0490a11e738e7bc5dc082eef9c52568baf9a947e81e8582a9ac5"
          }
        ],
        "scope": "Actually executed self-contained fixed example; current web controls execute separately. Python Fraction and finite-precision base R. Author gate, not independent peer."
      },
      "PSD-boundary": {
        "api": "variance",
        "variant": "PSD-boundary",
        "language": "python",
        "codeFile": "ml09-code/variance-PSD-boundary.py",
        "codeSHA256": "0c7018bc343c2c9a5cd24c1c1b825b1bc7702c6944cf39152e88ed06057222ac",
        "codeText": "\"\"\"ML09 exact Fraction reproduction from native source fields.\n\npython ml09-public-analysis.py --source-dir ml09-sources --output-dir results\n\nThis authored educational implementation uses direct-centered leaf losses and\nexhaustive midpoint partitions. It reads no JS engine, model contract, checker,\nstored target answers or derived-result CSV. Its five tree arithmetic helpers\nwere copied from the author's own separate Fraction reference, not an independent\npeer. Parser/work budgets and display rounding of the production JS are separate.\nNumerical predictions/proper scores do not certify causal effects, calibration,\nIID OOB validity, survey representativeness or production parameter optimality.\n\"\"\"\nfrom pathlib import Path\nfrom fractions import Fraction as Q\nimport csv,json,math,itertools,argparse\n\ndef normalized(rows,task='regression'):\n return [dict(id=r.get('id',i),x=[None if x is None else Q(x)for x in r.get('x',[])],y=None if r['y']is None else str(r['y'])if task=='classification'else Q(r['y']),w=Q(r.get('weight',1)))for i,r in enumerate(rows)]\n\ndef totals(rows,task,classes):\n W=sum((r['w']for r in rows),Q());mu=sum((r['w']*r['y']for r in rows),Q())/W if task=='regression'and W else None\n probs=[sum((r['w']for r in rows if r['y']==c),Q())/W for c in classes]if task=='classification'and W else[]\n risk=sum((r['w']*(r['y']-mu)**2 for r in rows),Q())if task=='regression'and W else W*sum((p*(1-p)for p in probs),Q())\n return dict(n=len(rows),w=W,mu=mu,p=probs,risk=risk,pred=mu if task=='regression'else classes[max(range(len(probs)),key=lambda i:probs[i])]if probs else None)\n\ndef fit(rows,a,task,classes,schedule=None):\n good=[r for r in rows if r['w']>0 and r['y']is not None];root=totals(good,task,classes)['w'];depth=a.get('maxDepth',2);minimum=a.get('minLeaf',1);minmass=Q(a.get('minLeafWeight',0));mingain=Q(a.get('minGain',0));route=a.get('missingRoute','best')\n def build(rr,d,path):\n  st=totals(rr,task,classes);n=dict(rows=rr,st=st,split=None,left=None,right=None,path=path)\n  if d==depth:return n\n  best=None\n  for j in range(len(rr[0]['x'])):\n   if schedule is not None and j not in schedule[path]:continue\n   values=sorted({r['x'][j]for r in rr if r['x'][j]is not None});missing=[r for r in rr if r['x'][j]is None];observed=[r for r in rr if r['x'][j]is not None]\n   candidates=[]\n   for lo,hi in zip(values,values[1:]):\n    q=(lo+hi)/2;left=[r for r in observed if r['x'][j]<=q];right=[r for r in observed if r['x'][j]>q];directions=[route]if route!='best'else['left','right']if missing else['left'if len(left)>=len(right)else'right']\n    for direction in directions:candidates.append(('threshold',q,direction,left+missing if direction=='left'else left,right+missing if direction=='right'else right))\n   if missing and observed:candidates.append(('missing-only',None,'left',missing,observed))\n   for kind,q,direction,left,right in candidates:\n    l=totals(left,task,classes);r=totals(right,task,classes)\n    if min(l['n'],r['n'])<minimum or min(l['w'],r['w'])<minmass or min(l['w'],r['w'])<=0:continue\n    gain=(st['risk']-l['risk']-r['risk'])/root\n    if best is None or gain>best['gain']:best=dict(feature=j,kind=kind,threshold=q,missingRoute=direction,left=left,right=right,gain=gain)\n  if best and best['gain']>0 and best['gain']>mingain:\n   j=best['feature'];go=lambda r:r['x'][j]is None if best['kind']=='missing-only'else best['missingRoute']=='left'if r['x'][j]is None else r['x'][j]<=best['threshold'];n['split']=best;n['left']=build([r for r in rr if go(r)],d+1,path+'L');n['right']=build([r for r in rr if not go(r)],d+1,path+'R')\n  return n\n return build(good,0,'')\n\ndef predict(tree,x):\n n=tree\n while n['split']:\n  s=n['split'];v=x[s['feature']];left=v is None if s['kind']=='missing-only'else s['missingRoute']=='left'if v is None else v<=s['threshold'];n=n['left'if left else'right']\n return dict(prediction=n['st']['pred'],probabilities=n['st']['p'])\n\ndef combine(preds,w,task,classes,mode='probabilities'):\n mass=sum(w,Q())\n if not preds or not mass:return dict(prediction=None,probabilities=[],vote=None,prob=None)\n if task=='regression':return dict(prediction=sum((p['prediction']*v for p,v in zip(preds,w)),Q())/mass,probabilities=[],vote=None,prob=None)\n votes=[sum((v for p,v in zip(preds,w)if p['prediction']==c),Q())/mass for c in classes];ps=[sum((p['probabilities'][j]*v for p,v in zip(preds,w)),Q())/mass for j in range(len(classes))];vote=classes[max(range(len(classes)),key=lambda j:votes[j])];prob=classes[max(range(len(classes)),key=lambda j:ps[j])];return dict(prediction=vote if mode=='votes'else prob,probabilities=ps,vote=vote,prob=prob,votes=votes)\ndef number(v):\n if v is None or isinstance(v,bool):raise ValueError('explicit null/bool is not a numeric parameter')\n return Q(v)\ndef variance(a):\n B=a['B'];v=number(a['marginalVariance']);rho=number(a.get('rho',0))\n if not isinstance(B,int)or isinstance(B,bool)or B<1 or v<0:raise ValueError('positive integer B/nonnegative variance')\n if B>1 and v and not -Q(1,B-1)<=rho<=1:raise ValueError('equicorrelation PSD bound')\n return dict(B=B,marginalVariance=v,correlationApplicable=B>1 and bool(v),varianceOfMean=v if B==1 else v*(1+(B-1)*rho)/B)\ndef aggregate(a):\n task=a.get('task','regression');classes=[str(c)for c in a.get('classes',[])];members=a['members'];w=[number(v)for v in a.get('memberWeights',[1]*len(members))]\n if not members or min(w)<0 or sum(w)<=0:raise ValueError('nonnegative member weights/positive total')\n order=[p.get('id',i)for i,p in enumerate(members[0]['predictions'])];keys=lambda x:(type(x).__name__,x);lookup=[{keys(p.get('id',i)):p for i,p in enumerate(m['predictions'])}for m in members]\n if any(set(m)!={keys(v)for v in order}for m in lookup):raise ValueError('same query ID set')\n out=[]\n for pid in order:\n  predictions=[dict(prediction=number(m[keys(pid)]['value']),probabilities=[])if task=='regression'else dict(prediction=str(m[keys(pid)]['label']),probabilities=[number(v)for v in m[keys(pid)]['probabilities']])for m in lookup]\n  if task=='classification'and any(min(p['probabilities'])<0 or sum(p['probabilities'])!=1 for p in predictions):raise ValueError('probability simplex')\n  out.append(dict(id=pid,**combine(predictions,w,task,classes,a.get('aggregation','probabilities'))))\n return dict(task=task,classes=classes,predictions=out)\ndef scored(preds,rows,task,classes):\n mass=loss=absolute=errors=voteerrors=Q();out=[]\n for p,r in zip(preds,rows):\n  ok=p['prediction']is not None and r['y']is not None and r['w']>0;v=None\n  if ok:\n   mass+=r['w']\n   if task=='regression':e=r['y']-p['prediction'];v=e*e;absolute+=r['w']*abs(e)\n   else:v=sum(((q-(1 if r['y']==c else 0))**2 for c,q in zip(classes,p['probabilities'])),Q());errors+=r['w']*(p['prediction']!=r['y']);voteerrors+=r['w']*(p['vote']!=r['y'])\n   loss+=r['w']*v\n  out.append(dict(p,actual=r['y'],weight=r['w'],scoreEligible=ok,loss=v))\n return dict(rows=out,eligibleRows=sum(r['scoreEligible']for r in out),weight=mass,totalLoss=loss,meanLoss=loss/mass if mass else None,MAE=absolute/mass if mass and task=='regression'else None,errorRate=errors/mass if mass and task=='classification'else None,labelVoteErrorRate=voteerrors/mass if mass and task=='classification'else None)\ndef ensemble(a,forest=False):\n task=a.get('task','regression');classes=[str(v)for v in(a.get('classes')or[])];rr=normalized(a['rows'],task);key=lambda x:(type(x).__name__,x);lookup={key(r['id']):r for r in rr};weights=[number(v)for v in a.get('memberWeights',[1]*len(a['bootstrapDraws']))]\n if not any(r['w']>0 and r['y']is not None for r in rr)or min(weights)<0 or sum(weights)<=0:raise ValueError('positive eligible training and member weight')\n members=[]\n for i,draw in enumerate(a['bootstrapDraws']):\n  data=[lookup[key(v)]for v in draw];schedule=a['nodeFeatures'][i]if forest else None;model=fit(data,a,task,classes,schedule);inbag={key(v)for v in draw};members.append(dict(tree=model,draw=draw,inbag=inbag,weight=weights[i]))\n predictions=[]\n for q in a.get('queries',[]):predictions.append(dict(id=q['id'],**combine([predict(m['tree'],[None if v is None else number(v)for v in q['x']])for m in members],weights,task,classes,a.get('aggregation','probabilities'))))\n oob=[]\n for r in rr:\n  applicable=[i for i,m in enumerate(members)if key(r['id'])not in m['inbag']];p=combine([predict(members[i]['tree'],r['x'])for i in applicable],[weights[i]for i in applicable],task,classes,a.get('aggregation','probabilities'));oob.append(dict(id=r['id'],applicable=applicable,positiveMembers=sum(weights[i]>0 for i in applicable),**p))\n return dict(task=task,classes=classes,members=members,predictions=predictions,outOfBag=scored(oob,rr,task,classes))\ndef boost(a):\n if a.get('task','regression')!='regression':raise ValueError('regression boosting only')\n rr=normalized(a['rows']);good=[r for r in rr if r['w']and r['y']is not None];W=sum((r['w']for r in good),Q())\n if not W:raise ValueError('positive eligible training')\n eta=number(a.get('learningRate','1/2'));stages=a.get('stages',3)\n if not 0<=eta<=1 or not isinstance(stages,int)or isinstance(stages,bool)or not 0<=stages<=8:raise ValueError('supported rate/stages')\n initial=number(a['initial'])if'initial'in a else sum((r['w']*r['y']for r in good),Q())/W;training=[[initial]for r in rr];queries=[[initial]for q in a.get('queries',[])];fits=[];losses=[]\n for stage in range(stages+1):\n  sse=sum((r['w']*(r['y']-p[-1])**2 for r,p in zip(rr,training)if r['w']and r['y']is not None),Q());losses.append(dict(stage=stage,rawWeightedSSE=sse,MSE=sse/W,meanHalfSquaredLoss=sse/(2*W)))\n  if stage==stages:break\n  residuals=[dict(r,y=None if r['y']is None else r['y']-p[-1])for r,p in zip(rr,training)];tree=fit(residuals,a,'regression',[]);h=[predict(tree,r['x'])['prediction']for r in rr];qh=[predict(tree,[None if v is None else number(v)for v in q['x']])['prediction']for q in a.get('queries',[])];norm=sum((r['w']*v*v for r,v in zip(rr,h)if r['y']is not None),Q());stageRows=[]\n  for i,(r,p)in enumerate(zip(rr,training)):\n   residual=None if r['y']is None else r['y']-p[-1];stageRows.append(dict(id=r['id'],before=p[-1],residual=residual,negativeCoordinateDerivative=None if residual is None else r['w']*residual/W,fit=h[i],addition=eta*h[i],after=p[-1]+eta*h[i]));p.append(p[-1]+eta*h[i])\n  for p,v in zip(queries,qh):p.append(p[-1]+eta*v)\n  fits.append(dict(stage=stage+1,tree=tree,rows=stageRows,queryFits=qh,norm=norm,predictedSSEDecrease=eta*(2-eta)*norm))\n return dict(task='regression',initial=initial,learningRate=eta,stages=stages,training=training,queries=queries,fits=fits,losses=losses,predictions=[dict(id=q['id'],prediction=p[-1],probabilities=[],vote=None,prob=None)for q,p in zip(a.get('queries',[]),queries)])\nclass Stream:\n def __init__(self,state):self.state=state\n def choose(self,n):\n  limit=(1<<32)-((1<<32)%n)\n  while True:\n   self.state=(1664525*self.state+1013904223)&0xffffffff\n   if self.state<limit:return self.state%n\ndef fixed_schedules(ids,p,seed):\n stream=Stream(seed);draws=[];schedules=[];paths=['']+[p for d in[1,2]for p in map(''.join,itertools.product('LR',repeat=d))]\n for member in range(4):\n  draws.append([ids[stream.choose(len(ids))]for _ in range(len(ids))]);schedule={}\n  for path in paths:\n   order=list(range(p))\n   for j in range(p-1,0,-1):k=stream.choose(j+1);order[j],order[k]=order[k],order[j]\n   schedule[path]=sorted(order[:max(1,int(math.sqrt(p)))])\n  schedules.append(schedule)\n return draws,schedules\ndef csvread(file):\n with Path(file).open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))\ndef read_sources(source):\n source=Path(source);raw=csvread(source/'actual320-country-four-indicators-original-2020-2024.csv');lookup={(r['countryISO3'],int(r['date']),r['indicatorID']):r for r in raw};country=[]\n for code in sorted({r['countryISO3']for r in raw}):\n  for year in range(2020,2025):\n   cols=['NY.GDP.PCAP.KD','NY.GDP.MKTP.KD.ZG','FP.CPI.TOTL.ZG','SP.DYN.LE00.IN'];v=[lookup[code,year,k]['originalValueToken']for k in cols];x=[None if not z else Q(z)for z in v[:3]];x[0]=None if x[0]is None else x[0]/10000;y=None if not v[3]else Q(v[3]);eligible=y is not None and None not in x;country.append(dict(id=code+':'+str(year),sourceRow=code+':'+str(year),originalID=code,year=year,x=x,y=y,weight='1',role='excluded'if not eligible else'outer-test'if year==2024 else'train'))\n person=[]\n for i,r in enumerate(csvread(source/'actual3613-NLS-original52-fields-and-selection.csv'),1):\n  v=lambda k:None if r[k]=='.'else Q(r[k]);x=[v('ed76'),v('age76')];y=None if v('wage76')is None else v('wage76')/100;eligible=y is not None and None not in x;person.append(dict(id='person:'+str(i),sourceRow=str(i),originalID=r['id'],x=x,y=y,weight='1',role='excluded'if not eligible else'outer-test'if i%5==0 else'train'))\n company=[]\n for i,r in enumerate(csvread(source/'actual3150-churn-original14-fields-and-selection.csv'),1):company.append(dict(id='customer:'+str(i),sourceRow=str(i),originalID='',x=[Q(r[k])for k in['Call  Failure','Subscription  Length','Charge  Amount']],y=r['Churn'],weight='1',role='outer-test'if i%5==0 else'train'))\n models={}\n for index,(kind,rr,task,leaf)in enumerate([('country',country,'regression',4),('person',person,'regression',50),('company',company,'classification',30)]):\n  ids=[r['id']for r in rr if r['role']=='train'];draws,schedules=fixed_schedules(ids,len(rr[0]['x']),20261102+7919*index);models[kind]=dict(records=rr,task=task,classes=['0','1']if task=='classification'else[],draws=draws,schedules=schedules,minLeaf=leaf)\n return models\n_OMITTED=object()\ndef realdata(models,kind,options=_OMITTED):\n options={}if options is _OMITTED else options\n if not isinstance(options,dict):raise ValueError('options object required, not explicit null')\n m=models[kind];train=[r for r in m['records']if r['role']=='train'];test=[r for r in m['records']if r['role']=='outer-test'];method=options.get('method','forest');depth=options.get('maxDepth',2);count=options.get('memberCount',3);a=dict(rows=train,queries=[dict(id=r['id'],x=r['x'])for r in test],task=m['task'],classes=m['classes'],maxDepth=depth,minLeaf=options.get('minLeaf',m['minLeaf']),minLeafWeight='0',minGain='0',missingRoute='best',learningRate=options.get('learningRate','1/2'),stages=options.get('stages',3))\n if method not in ['bagging','forest','boost']:raise ValueError('known source method')\n if not isinstance(depth,int)or isinstance(depth,bool)or not 0<=depth<=3:raise ValueError('source depth0..3')\n if method!='boost'and(not isinstance(count,int)or isinstance(count,bool)or not 1<=count<=4):raise ValueError('source member count1..4')\n if method=='boost':result=boost(a)\n else:\n  a.update(bootstrapDraws=m['draws'][:count],nodeFeatures=[{p:v for p,v in s.items()if len(p)<depth}for s in m['schedules'][:count]]);result=ensemble(a,method=='forest')\n outer=scored(result['predictions'],normalized(test,m['task']),m['task'],m['classes']);st=totals([r for r in normalized(train,m['task'])if r['w']and r['y']is not None],m['task'],m['classes']);constant=dict(prediction=st['pred'],probabilities=st['p'],vote=st['pred'],prob=st['pred']);baseline=scored([dict(id=r['id'],**constant)for r in test],normalized(test,m['task']),m['task'],m['classes']);return dict(kind=kind,method=method,settings=a,train=train,test=test,result=result,outer=outer,baseline=baseline)\ndef serial(x):\n if isinstance(x,Q):return str(x)\n if isinstance(x,dict):return{k:serial(v)for k,v in x.items()if k not in['inbag','tree']}\n if isinstance(x,(list,tuple)):return[serial(v)for v in x]\n return x\ndef writecsv(file,heads,rows):\n with Path(file).open('w',encoding='utf8',newline='')as f:\n  w=csv.writer(f);w.writerow(heads);w.writerows([[''if v is None else str(v)for v in r]for r in rows])\nAPI='variance'\nINPUT={'B': 4, 'marginalVariance': 4, 'rho': '-1/3'}\n\ndef run_fixed(api,a,out,src):\n import matplotlib\n matplotlib.use('svg')\n import matplotlib.pyplot as plt\n from matplotlib.ticker import MaxNLocator\n plt.rcParams.update({'font.size':14,'svg.fonttype':'none','svg.hashsalt':'ml09-fixed-v1'})\n result=variance(a)if api=='variance'else aggregate(a)if api=='aggregate'else ensemble(a,api=='forest')if api in ['bagging','forest']else boost(a)if api=='boost'else realdata(read_sources(src),a['kind'])\n out=Path(out);out.mkdir(parents=True,exist_ok=True);summary={};points=[]\n def add(x,y,s):\n  if y is not None:points.append([x,y,s])\n if api=='variance':\n  summary={'B':result['B'],'varianceOfMean':result['varianceOfMean']};add(result['B'],result['varianceOfMean'],'Specified finite-B variance');xl='Number of members B';yl='Variance, stipulated units squared';title='Declared covariance model, not fitted trees'\n elif api=='aggregate':\n  p=result['predictions'][0];classification=a.get('task')=='classification';summary={'selectedPrediction':p['prediction']}\n  if classification:\n   summary.update(voteLabel=p['vote'],probabilityLabel=p['prob'],meanProbability1=p['probabilities'][1]);add(1,p['probabilities'][1],'Mean probability of class 1');add(2,p['votes'][1],'Label-vote share of class 1');xl='Aggregation (1=probability, 2=vote)';yl='Probability or vote share'\n  else:\n   for i,m in enumerate(a['members']):add(i+1,Q(m['predictions'][0]['value']),'Member prediction')\n   add(3,p['prediction'],'Weighted mean');xl='Member 1, member 2, aggregate 3';yl='Prediction, assumed units'\n  title='Votes and probabilities are distinct objects'\n elif api in ['bagging','forest']:\n  summary={'queryPrediction':result['predictions'][0]['prediction'],'OOB.scoreable':result['outOfBag']['eligibleRows'],'OOB.meanLoss':result['outOfBag']['meanLoss']}\n  for i,r in enumerate(a['rows']):add(i+1,Q(r['y']),'Observed training outcome')\n  for i,p in enumerate(result['outOfBag']['rows']):add(i+1,p['prediction'],'OOB prediction, when defined')\n  xl='Original training ID order';yl='Outcome, assumed units';title='Repeated draws and ID-level OOB membership'\n elif api=='boost':\n  summary={'initial':result['initial'],'finalMSE':result['losses'][-1]['MSE'],'stages':result['stages']}\n  for r in result['losses']:add(r['stage'],r['MSE'],'Training MSE')\n  xl='Boosting stage (0=initial)';yl='Weighted MSE, outcome units squared';title='Training descent does not certify held-out gain'\n else:\n  summary={'outer.scoreable':result['outer']['eligibleRows'],'outer.meanLoss':result['outer']['meanLoss'],'baseline.meanLoss':result['baseline']['meanLoss'],'OOB.scoreable':result['result']['outOfBag']['eligibleRows'],'OOB.meanLoss':result['result']['outOfBag']['meanLoss']}\n  for i,p in enumerate(result['outer']['rows']):\n   add(i+1,Q(p['actual']),'Observed outcome');add(i+1,p['probabilities'][1]if a['kind']=='company'else p['prediction'],'Forest probability of class 1'if a['kind']=='company'else'Forest prediction')\n  xl='Outer-test source order, not a time path';yl='Churn label / probability'if a['kind']=='company'else'Period life expectancy, years'if a['kind']=='country'else'Nominal 1976 USD per hour';title='Fixed forest; outer labels did not fit the trees'\n def display(v):return 'undefined'if v is None else format(float(v),'.9f')\n writecsv(out/'summary.csv',['metric','value'],[[k,display(v)]for k,v in summary.items()]);writecsv(out/'plot-points.csv',['x','y','series'],points);(out/'full.json').write_text(json.dumps(serial(result),indent=2)+'\\n',encoding='utf8')\n fig,ax=plt.subplots(figsize=(5.6,4.6));fig.subplots_adjust(left=.24,right=.96,bottom=.24,top=.76);colors=['#355c72','#a55336','#507956','#78568b']\n for i,s in enumerate(dict.fromkeys(p[2]for p in points)):\n  pp=[p for p in points if p[2]==s];ax.scatter([float(p[0])for p in pp],[float(p[1])for p in pp],s=12 if len(pp)>100 else 32,alpha=.5 if len(pp)>100 else 1,color=colors[i%4],label=s)\n ax.set_xlabel(xl,labelpad=10,fontsize=11);ax.set_ylabel(yl,labelpad=10,fontsize=11);ax.xaxis.set_major_locator(MaxNLocator(3));ax.yaxis.set_major_locator(MaxNLocator(4));ax.grid(alpha=.18);ax.legend(loc='lower left',bbox_to_anchor=(0,1.01),fontsize=9,frameon=False);fig.suptitle(title,fontsize=9,y=.99);fig.savefig(out/'plot.svg',metadata={'Date':None});plt.close(fig);print(', '.join(k+'='+display(v)for k,v in summary.items()))\nif __name__=='__main__':\n import sys\n try:run_fixed(API,INPUT,sys.argv[1]if len(sys.argv)>1 else'fixed-results',sys.argv[2]if len(sys.argv)>2 else'ml09-sources')\n except ValueError as error:print('Rejected declared input: '+str(error),file=sys.stderr);sys.exit(2)\n",
        "code": "\"\"\"ML09 exact Fraction reproduction from native source fields.\n\npython ml09-public-analysis.py --source-dir ml09-sources --output-dir results\n\nThis authored educational implementation uses direct-centered leaf losses and\nexhaustive midpoint partitions. It reads no JS engine, model contract, checker,\nstored target answers or derived-result CSV. Its five tree arithmetic helpers\nwere copied from the author's own separate Fraction reference, not an independent\npeer. Parser/work budgets and display rounding of the production JS are separate.\nNumerical predictions/proper scores do not certify causal effects, calibration,\nIID OOB validity, survey representativeness or production parameter optimality.\n\"\"\"\nfrom pathlib import Path\nfrom fractions import Fraction as Q\nimport csv,json,math,itertools,argparse\n\ndef normalized(rows,task='regression'):\n return [dict(id=r.get('id',i),x=[None if x is None else Q(x)for x in r.get('x',[])],y=None if r['y']is None else str(r['y'])if task=='classification'else Q(r['y']),w=Q(r.get('weight',1)))for i,r in enumerate(rows)]\n\ndef totals(rows,task,classes):\n W=sum((r['w']for r in rows),Q());mu=sum((r['w']*r['y']for r in rows),Q())/W if task=='regression'and W else None\n probs=[sum((r['w']for r in rows if r['y']==c),Q())/W for c in classes]if task=='classification'and W else[]\n risk=sum((r['w']*(r['y']-mu)**2 for r in rows),Q())if task=='regression'and W else W*sum((p*(1-p)for p in probs),Q())\n return dict(n=len(rows),w=W,mu=mu,p=probs,risk=risk,pred=mu if task=='regression'else classes[max(range(len(probs)),key=lambda i:probs[i])]if probs else None)\n\ndef fit(rows,a,task,classes,schedule=None):\n good=[r for r in rows if r['w']>0 and r['y']is not None];root=totals(good,task,classes)['w'];depth=a.get('maxDepth',2);minimum=a.get('minLeaf',1);minmass=Q(a.get('minLeafWeight',0));mingain=Q(a.get('minGain',0));route=a.get('missingRoute','best')\n def build(rr,d,path):\n  st=totals(rr,task,classes);n=dict(rows=rr,st=st,split=None,left=None,right=None,path=path)\n  if d==depth:return n\n  best=None\n  for j in range(len(rr[0]['x'])):\n   if schedule is not None and j not in schedule[path]:continue\n   values=sorted({r['x'][j]for r in rr if r['x'][j]is not None});missing=[r for r in rr if r['x'][j]is None];observed=[r for r in rr if r['x'][j]is not None]\n   candidates=[]\n   for lo,hi in zip(values,values[1:]):\n    q=(lo+hi)/2;left=[r for r in observed if r['x'][j]<=q];right=[r for r in observed if r['x'][j]>q];directions=[route]if route!='best'else['left','right']if missing else['left'if len(left)>=len(right)else'right']\n    for direction in directions:candidates.append(('threshold',q,direction,left+missing if direction=='left'else left,right+missing if direction=='right'else right))\n   if missing and observed:candidates.append(('missing-only',None,'left',missing,observed))\n   for kind,q,direction,left,right in candidates:\n    l=totals(left,task,classes);r=totals(right,task,classes)\n    if min(l['n'],r['n'])<minimum or min(l['w'],r['w'])<minmass or min(l['w'],r['w'])<=0:continue\n    gain=(st['risk']-l['risk']-r['risk'])/root\n    if best is None or gain>best['gain']:best=dict(feature=j,kind=kind,threshold=q,missingRoute=direction,left=left,right=right,gain=gain)\n  if best and best['gain']>0 and best['gain']>mingain:\n   j=best['feature'];go=lambda r:r['x'][j]is None if best['kind']=='missing-only'else best['missingRoute']=='left'if r['x'][j]is None else r['x'][j]<=best['threshold'];n['split']=best;n['left']=build([r for r in rr if go(r)],d+1,path+'L');n['right']=build([r for r in rr if not go(r)],d+1,path+'R')\n  return n\n return build(good,0,'')\n\ndef predict(tree,x):\n n=tree\n while n['split']:\n  s=n['split'];v=x[s['feature']];left=v is None if s['kind']=='missing-only'else s['missingRoute']=='left'if v is None else v<=s['threshold'];n=n['left'if left else'right']\n return dict(prediction=n['st']['pred'],probabilities=n['st']['p'])\n\ndef combine(preds,w,task,classes,mode='probabilities'):\n mass=sum(w,Q())\n if not preds or not mass:return dict(prediction=None,probabilities=[],vote=None,prob=None)\n if task=='regression':return dict(prediction=sum((p['prediction']*v for p,v in zip(preds,w)),Q())/mass,probabilities=[],vote=None,prob=None)\n votes=[sum((v for p,v in zip(preds,w)if p['prediction']==c),Q())/mass for c in classes];ps=[sum((p['probabilities'][j]*v for p,v in zip(preds,w)),Q())/mass for j in range(len(classes))];vote=classes[max(range(len(classes)),key=lambda j:votes[j])];prob=classes[max(range(len(classes)),key=lambda j:ps[j])];return dict(prediction=vote if mode=='votes'else prob,probabilities=ps,vote=vote,prob=prob,votes=votes)\ndef number(v):\n if v is None or isinstance(v,bool):raise ValueError('explicit null/bool is not a numeric parameter')\n return Q(v)\ndef variance(a):\n B=a['B'];v=number(a['marginalVariance']);rho=number(a.get('rho',0))\n if not isinstance(B,int)or isinstance(B,bool)or B<1 or v<0:raise ValueError('positive integer B/nonnegative variance')\n if B>1 and v and not -Q(1,B-1)<=rho<=1:raise ValueError('equicorrelation PSD bound')\n return dict(B=B,marginalVariance=v,correlationApplicable=B>1 and bool(v),varianceOfMean=v if B==1 else v*(1+(B-1)*rho)/B)\ndef aggregate(a):\n task=a.get('task','regression');classes=[str(c)for c in a.get('classes',[])];members=a['members'];w=[number(v)for v in a.get('memberWeights',[1]*len(members))]\n if not members or min(w)<0 or sum(w)<=0:raise ValueError('nonnegative member weights/positive total')\n order=[p.get('id',i)for i,p in enumerate(members[0]['predictions'])];keys=lambda x:(type(x).__name__,x);lookup=[{keys(p.get('id',i)):p for i,p in enumerate(m['predictions'])}for m in members]\n if any(set(m)!={keys(v)for v in order}for m in lookup):raise ValueError('same query ID set')\n out=[]\n for pid in order:\n  predictions=[dict(prediction=number(m[keys(pid)]['value']),probabilities=[])if task=='regression'else dict(prediction=str(m[keys(pid)]['label']),probabilities=[number(v)for v in m[keys(pid)]['probabilities']])for m in lookup]\n  if task=='classification'and any(min(p['probabilities'])<0 or sum(p['probabilities'])!=1 for p in predictions):raise ValueError('probability simplex')\n  out.append(dict(id=pid,**combine(predictions,w,task,classes,a.get('aggregation','probabilities'))))\n return dict(task=task,classes=classes,predictions=out)\ndef scored(preds,rows,task,classes):\n mass=loss=absolute=errors=voteerrors=Q();out=[]\n for p,r in zip(preds,rows):\n  ok=p['prediction']is not None and r['y']is not None and r['w']>0;v=None\n  if ok:\n   mass+=r['w']\n   if task=='regression':e=r['y']-p['prediction'];v=e*e;absolute+=r['w']*abs(e)\n   else:v=sum(((q-(1 if r['y']==c else 0))**2 for c,q in zip(classes,p['probabilities'])),Q());errors+=r['w']*(p['prediction']!=r['y']);voteerrors+=r['w']*(p['vote']!=r['y'])\n   loss+=r['w']*v\n  out.append(dict(p,actual=r['y'],weight=r['w'],scoreEligible=ok,loss=v))\n return dict(rows=out,eligibleRows=sum(r['scoreEligible']for r in out),weight=mass,totalLoss=loss,meanLoss=loss/mass if mass else None,MAE=absolute/mass if mass and task=='regression'else None,errorRate=errors/mass if mass and task=='classification'else None,labelVoteErrorRate=voteerrors/mass if mass and task=='classification'else None)\ndef ensemble(a,forest=False):\n task=a.get('task','regression');classes=[str(v)for v in(a.get('classes')or[])];rr=normalized(a['rows'],task);key=lambda x:(type(x).__name__,x);lookup={key(r['id']):r for r in rr};weights=[number(v)for v in a.get('memberWeights',[1]*len(a['bootstrapDraws']))]\n if not any(r['w']>0 and r['y']is not None for r in rr)or min(weights)<0 or sum(weights)<=0:raise ValueError('positive eligible training and member weight')\n members=[]\n for i,draw in enumerate(a['bootstrapDraws']):\n  data=[lookup[key(v)]for v in draw];schedule=a['nodeFeatures'][i]if forest else None;model=fit(data,a,task,classes,schedule);inbag={key(v)for v in draw};members.append(dict(tree=model,draw=draw,inbag=inbag,weight=weights[i]))\n predictions=[]\n for q in a.get('queries',[]):predictions.append(dict(id=q['id'],**combine([predict(m['tree'],[None if v is None else number(v)for v in q['x']])for m in members],weights,task,classes,a.get('aggregation','probabilities'))))\n oob=[]\n for r in rr:\n  applicable=[i for i,m in enumerate(members)if key(r['id'])not in m['inbag']];p=combine([predict(members[i]['tree'],r['x'])for i in applicable],[weights[i]for i in applicable],task,classes,a.get('aggregation','probabilities'));oob.append(dict(id=r['id'],applicable=applicable,positiveMembers=sum(weights[i]>0 for i in applicable),**p))\n return dict(task=task,classes=classes,members=members,predictions=predictions,outOfBag=scored(oob,rr,task,classes))\ndef boost(a):\n if a.get('task','regression')!='regression':raise ValueError('regression boosting only')\n rr=normalized(a['rows']);good=[r for r in rr if r['w']and r['y']is not None];W=sum((r['w']for r in good),Q())\n if not W:raise ValueError('positive eligible training')\n eta=number(a.get('learningRate','1/2'));stages=a.get('stages',3)\n if not 0<=eta<=1 or not isinstance(stages,int)or isinstance(stages,bool)or not 0<=stages<=8:raise ValueError('supported rate/stages')\n initial=number(a['initial'])if'initial'in a else sum((r['w']*r['y']for r in good),Q())/W;training=[[initial]for r in rr];queries=[[initial]for q in a.get('queries',[])];fits=[];losses=[]\n for stage in range(stages+1):\n  sse=sum((r['w']*(r['y']-p[-1])**2 for r,p in zip(rr,training)if r['w']and r['y']is not None),Q());losses.append(dict(stage=stage,rawWeightedSSE=sse,MSE=sse/W,meanHalfSquaredLoss=sse/(2*W)))\n  if stage==stages:break\n  residuals=[dict(r,y=None if r['y']is None else r['y']-p[-1])for r,p in zip(rr,training)];tree=fit(residuals,a,'regression',[]);h=[predict(tree,r['x'])['prediction']for r in rr];qh=[predict(tree,[None if v is None else number(v)for v in q['x']])['prediction']for q in a.get('queries',[])];norm=sum((r['w']*v*v for r,v in zip(rr,h)if r['y']is not None),Q());stageRows=[]\n  for i,(r,p)in enumerate(zip(rr,training)):\n   residual=None if r['y']is None else r['y']-p[-1];stageRows.append(dict(id=r['id'],before=p[-1],residual=residual,negativeCoordinateDerivative=None if residual is None else r['w']*residual/W,fit=h[i],addition=eta*h[i],after=p[-1]+eta*h[i]));p.append(p[-1]+eta*h[i])\n  for p,v in zip(queries,qh):p.append(p[-1]+eta*v)\n  fits.append(dict(stage=stage+1,tree=tree,rows=stageRows,queryFits=qh,norm=norm,predictedSSEDecrease=eta*(2-eta)*norm))\n return dict(task='regression',initial=initial,learningRate=eta,stages=stages,training=training,queries=queries,fits=fits,losses=losses,predictions=[dict(id=q['id'],prediction=p[-1],probabilities=[],vote=None,prob=None)for q,p in zip(a.get('queries',[]),queries)])\nclass Stream:\n def __init__(self,state):self.state=state\n def choose(self,n):\n  limit=(1<<32)-((1<<32)%n)\n  while True:\n   self.state=(1664525*self.state+1013904223)&0xffffffff\n   if self.state<limit:return self.state%n\ndef fixed_schedules(ids,p,seed):\n stream=Stream(seed);draws=[];schedules=[];paths=['']+[p for d in[1,2]for p in map(''.join,itertools.product('LR',repeat=d))]\n for member in range(4):\n  draws.append([ids[stream.choose(len(ids))]for _ in range(len(ids))]);schedule={}\n  for path in paths:\n   order=list(range(p))\n   for j in range(p-1,0,-1):k=stream.choose(j+1);order[j],order[k]=order[k],order[j]\n   schedule[path]=sorted(order[:max(1,int(math.sqrt(p)))])\n  schedules.append(schedule)\n return draws,schedules\ndef csvread(file):\n with Path(file).open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))\ndef read_sources(source):\n source=Path(source);raw=csvread(source/'actual320-country-four-indicators-original-2020-2024.csv');lookup={(r['countryISO3'],int(r['date']),r['indicatorID']):r for r in raw};country=[]\n for code in sorted({r['countryISO3']for r in raw}):\n  for year in range(2020,2025):\n   cols=['NY.GDP.PCAP.KD','NY.GDP.MKTP.KD.ZG','FP.CPI.TOTL.ZG','SP.DYN.LE00.IN'];v=[lookup[code,year,k]['originalValueToken']for k in cols];x=[None if not z else Q(z)for z in v[:3]];x[0]=None if x[0]is None else x[0]/10000;y=None if not v[3]else Q(v[3]);eligible=y is not None and None not in x;country.append(dict(id=code+':'+str(year),sourceRow=code+':'+str(year),originalID=code,year=year,x=x,y=y,weight='1',role='excluded'if not eligible else'outer-test'if year==2024 else'train'))\n person=[]\n for i,r in enumerate(csvread(source/'actual3613-NLS-original52-fields-and-selection.csv'),1):\n  v=lambda k:None if r[k]=='.'else Q(r[k]);x=[v('ed76'),v('age76')];y=None if v('wage76')is None else v('wage76')/100;eligible=y is not None and None not in x;person.append(dict(id='person:'+str(i),sourceRow=str(i),originalID=r['id'],x=x,y=y,weight='1',role='excluded'if not eligible else'outer-test'if i%5==0 else'train'))\n company=[]\n for i,r in enumerate(csvread(source/'actual3150-churn-original14-fields-and-selection.csv'),1):company.append(dict(id='customer:'+str(i),sourceRow=str(i),originalID='',x=[Q(r[k])for k in['Call  Failure','Subscription  Length','Charge  Amount']],y=r['Churn'],weight='1',role='outer-test'if i%5==0 else'train'))\n models={}\n for index,(kind,rr,task,leaf)in enumerate([('country',country,'regression',4),('person',person,'regression',50),('company',company,'classification',30)]):\n  ids=[r['id']for r in rr if r['role']=='train'];draws,schedules=fixed_schedules(ids,len(rr[0]['x']),20261102+7919*index);models[kind]=dict(records=rr,task=task,classes=['0','1']if task=='classification'else[],draws=draws,schedules=schedules,minLeaf=leaf)\n return models\n_OMITTED=object()\ndef realdata(models,kind,options=_OMITTED):\n options={}if options is _OMITTED else options\n if not isinstance(options,dict):raise ValueError('options object required, not explicit null')\n m=models[kind];train=[r for r in m['records']if r['role']=='train'];test=[r for r in m['records']if r['role']=='outer-test'];method=options.get('method','forest');depth=options.get('maxDepth',2);count=options.get('memberCount',3);a=dict(rows=train,queries=[dict(id=r['id'],x=r['x'])for r in test],task=m['task'],classes=m['classes'],maxDepth=depth,minLeaf=options.get('minLeaf',m['minLeaf']),minLeafWeight='0',minGain='0',missingRoute='best',learningRate=options.get('learningRate','1/2'),stages=options.get('stages',3))\n if method not in ['bagging','forest','boost']:raise ValueError('known source method')\n if not isinstance(depth,int)or isinstance(depth,bool)or not 0<=depth<=3:raise ValueError('source depth0..3')\n if method!='boost'and(not isinstance(count,int)or isinstance(count,bool)or not 1<=count<=4):raise ValueError('source member count1..4')\n if method=='boost':result=boost(a)\n else:\n  a.update(bootstrapDraws=m['draws'][:count],nodeFeatures=[{p:v for p,v in s.items()if len(p)<depth}for s in m['schedules'][:count]]);result=ensemble(a,method=='forest')\n outer=scored(result['predictions'],normalized(test,m['task']),m['task'],m['classes']);st=totals([r for r in normalized(train,m['task'])if r['w']and r['y']is not None],m['task'],m['classes']);constant=dict(prediction=st['pred'],probabilities=st['p'],vote=st['pred'],prob=st['pred']);baseline=scored([dict(id=r['id'],**constant)for r in test],normalized(test,m['task']),m['task'],m['classes']);return dict(kind=kind,method=method,settings=a,train=train,test=test,result=result,outer=outer,baseline=baseline)\ndef serial(x):\n if isinstance(x,Q):return str(x)\n if isinstance(x,dict):return{k:serial(v)for k,v in x.items()if k not in['inbag','tree']}\n if isinstance(x,(list,tuple)):return[serial(v)for v in x]\n return x\ndef writecsv(file,heads,rows):\n with Path(file).open('w',encoding='utf8',newline='')as f:\n  w=csv.writer(f);w.writerow(heads);w.writerows([[''if v is None else str(v)for v in r]for r in rows])\nAPI='variance'\nINPUT={'B': 4, 'marginalVariance': 4, 'rho': '-1/3'}\n\ndef run_fixed(api,a,out,src):\n import matplotlib\n matplotlib.use('svg')\n import matplotlib.pyplot as plt\n from matplotlib.ticker import MaxNLocator\n plt.rcParams.update({'font.size':14,'svg.fonttype':'none','svg.hashsalt':'ml09-fixed-v1'})\n result=variance(a)if api=='variance'else aggregate(a)if api=='aggregate'else ensemble(a,api=='forest')if api in ['bagging','forest']else boost(a)if api=='boost'else realdata(read_sources(src),a['kind'])\n out=Path(out);out.mkdir(parents=True,exist_ok=True);summary={};points=[]\n def add(x,y,s):\n  if y is not None:points.append([x,y,s])\n if api=='variance':\n  summary={'B':result['B'],'varianceOfMean':result['varianceOfMean']};add(result['B'],result['varianceOfMean'],'Specified finite-B variance');xl='Number of members B';yl='Variance, stipulated units squared';title='Declared covariance model, not fitted trees'\n elif api=='aggregate':\n  p=result['predictions'][0];classification=a.get('task')=='classification';summary={'selectedPrediction':p['prediction']}\n  if classification:\n   summary.update(voteLabel=p['vote'],probabilityLabel=p['prob'],meanProbability1=p['probabilities'][1]);add(1,p['probabilities'][1],'Mean probability of class 1');add(2,p['votes'][1],'Label-vote share of class 1');xl='Aggregation (1=probability, 2=vote)';yl='Probability or vote share'\n  else:\n   for i,m in enumerate(a['members']):add(i+1,Q(m['predictions'][0]['value']),'Member prediction')\n   add(3,p['prediction'],'Weighted mean');xl='Member 1, member 2, aggregate 3';yl='Prediction, assumed units'\n  title='Votes and probabilities are distinct objects'\n elif api in ['bagging','forest']:\n  summary={'queryPrediction':result['predictions'][0]['prediction'],'OOB.scoreable':result['outOfBag']['eligibleRows'],'OOB.meanLoss':result['outOfBag']['meanLoss']}\n  for i,r in enumerate(a['rows']):add(i+1,Q(r['y']),'Observed training outcome')\n  for i,p in enumerate(result['outOfBag']['rows']):add(i+1,p['prediction'],'OOB prediction, when defined')\n  xl='Original training ID order';yl='Outcome, assumed units';title='Repeated draws and ID-level OOB membership'\n elif api=='boost':\n  summary={'initial':result['initial'],'finalMSE':result['losses'][-1]['MSE'],'stages':result['stages']}\n  for r in result['losses']:add(r['stage'],r['MSE'],'Training MSE')\n  xl='Boosting stage (0=initial)';yl='Weighted MSE, outcome units squared';title='Training descent does not certify held-out gain'\n else:\n  summary={'outer.scoreable':result['outer']['eligibleRows'],'outer.meanLoss':result['outer']['meanLoss'],'baseline.meanLoss':result['baseline']['meanLoss'],'OOB.scoreable':result['result']['outOfBag']['eligibleRows'],'OOB.meanLoss':result['result']['outOfBag']['meanLoss']}\n  for i,p in enumerate(result['outer']['rows']):\n   add(i+1,Q(p['actual']),'Observed outcome');add(i+1,p['probabilities'][1]if a['kind']=='company'else p['prediction'],'Forest probability of class 1'if a['kind']=='company'else'Forest prediction')\n  xl='Outer-test source order, not a time path';yl='Churn label / probability'if a['kind']=='company'else'Period life expectancy, years'if a['kind']=='country'else'Nominal 1976 USD per hour';title='Fixed forest; outer labels did not fit the trees'\n def display(v):return 'undefined'if v is None else format(float(v),'.9f')\n writecsv(out/'summary.csv',['metric','value'],[[k,display(v)]for k,v in summary.items()]);writecsv(out/'plot-points.csv',['x','y','series'],points);(out/'full.json').write_text(json.dumps(serial(result),indent=2)+'\\n',encoding='utf8')\n fig,ax=plt.subplots(figsize=(5.6,4.6));fig.subplots_adjust(left=.24,right=.96,bottom=.24,top=.76);colors=['#355c72','#a55336','#507956','#78568b']\n for i,s in enumerate(dict.fromkeys(p[2]for p in points)):\n  pp=[p for p in points if p[2]==s];ax.scatter([float(p[0])for p in pp],[float(p[1])for p in pp],s=12 if len(pp)>100 else 32,alpha=.5 if len(pp)>100 else 1,color=colors[i%4],label=s)\n ax.set_xlabel(xl,labelpad=10,fontsize=11);ax.set_ylabel(yl,labelpad=10,fontsize=11);ax.xaxis.set_major_locator(MaxNLocator(3));ax.yaxis.set_major_locator(MaxNLocator(4));ax.grid(alpha=.18);ax.legend(loc='lower left',bbox_to_anchor=(0,1.01),fontsize=9,frameon=False);fig.suptitle(title,fontsize=9,y=.99);fig.savefig(out/'plot.svg',metadata={'Date':None});plt.close(fig);print(', '.join(k+'='+display(v)for k,v in summary.items()))\nif __name__=='__main__':\n import sys\n try:run_fixed(API,INPUT,sys.argv[1]if len(sys.argv)>1 else'fixed-results',sys.argv[2]if len(sys.argv)>2 else'ml09-sources')\n except ValueError as error:print('Rejected declared input: '+str(error),file=sys.stderr);sys.exit(2)\n",
        "inputFiles": [],
        "input": {
          "B": 4,
          "marginalVariance": 4,
          "rho": "-1/3"
        },
        "returnCode": 0,
        "expectedFailure": false,
        "stdout": "B=4.000000000, varianceOfMean=0.000000000\n",
        "stderr": "",
        "summary": {
          "B": "4.000000000",
          "varianceOfMean": "0.000000000"
        },
        "plotPoints": [
          {
            "x": "4",
            "y": "0",
            "series": "Specified finite-B variance"
          }
        ],
        "plotFile": "ml09-fixed-results/variance-PSD-boundary-python/plot.svg",
        "plotSHA256": "76aa286aabe22e7379d748f8910e00593dc957622ef60992a44cf1218af9ef4b",
        "files": [
          {
            "file": "ml09-fixed-results/variance-PSD-boundary-python/full.json",
            "sha256": "23957d883ffcc62ac24fe52916269596c7ea5844041e2c1b93981aca1d3b67cb"
          },
          {
            "file": "ml09-fixed-results/variance-PSD-boundary-python/plot-points.csv",
            "sha256": "040ea3ebe4d78b7ec61fa14e603a819f3cc4936e26f4d4cd14cdb3008a8e736b"
          },
          {
            "file": "ml09-fixed-results/variance-PSD-boundary-python/plot.svg",
            "sha256": "76aa286aabe22e7379d748f8910e00593dc957622ef60992a44cf1218af9ef4b"
          },
          {
            "file": "ml09-fixed-results/variance-PSD-boundary-python/summary.csv",
            "sha256": "97f04ed0e1a73a84769c8c35bdd3986787386bc2a5a8a660a52e1c8b6f765c61"
          }
        ],
        "scope": "Actually executed self-contained fixed example; current web controls execute separately. Python Fraction and finite-precision base R. Author gate, not independent peer."
      },
      "reject-non-PSD": {
        "api": "variance",
        "variant": "reject-non-PSD",
        "language": "python",
        "codeFile": "ml09-code/variance-reject-non-PSD.py",
        "codeSHA256": "be81829bd7a2814026dcbb9fd91b9dec3da8a2dd914a457b25b0d75770822c5d",
        "codeText": "\"\"\"ML09 exact Fraction reproduction from native source fields.\n\npython ml09-public-analysis.py --source-dir ml09-sources --output-dir results\n\nThis authored educational implementation uses direct-centered leaf losses and\nexhaustive midpoint partitions. It reads no JS engine, model contract, checker,\nstored target answers or derived-result CSV. Its five tree arithmetic helpers\nwere copied from the author's own separate Fraction reference, not an independent\npeer. Parser/work budgets and display rounding of the production JS are separate.\nNumerical predictions/proper scores do not certify causal effects, calibration,\nIID OOB validity, survey representativeness or production parameter optimality.\n\"\"\"\nfrom pathlib import Path\nfrom fractions import Fraction as Q\nimport csv,json,math,itertools,argparse\n\ndef normalized(rows,task='regression'):\n return [dict(id=r.get('id',i),x=[None if x is None else Q(x)for x in r.get('x',[])],y=None if r['y']is None else str(r['y'])if task=='classification'else Q(r['y']),w=Q(r.get('weight',1)))for i,r in enumerate(rows)]\n\ndef totals(rows,task,classes):\n W=sum((r['w']for r in rows),Q());mu=sum((r['w']*r['y']for r in rows),Q())/W if task=='regression'and W else None\n probs=[sum((r['w']for r in rows if r['y']==c),Q())/W for c in classes]if task=='classification'and W else[]\n risk=sum((r['w']*(r['y']-mu)**2 for r in rows),Q())if task=='regression'and W else W*sum((p*(1-p)for p in probs),Q())\n return dict(n=len(rows),w=W,mu=mu,p=probs,risk=risk,pred=mu if task=='regression'else classes[max(range(len(probs)),key=lambda i:probs[i])]if probs else None)\n\ndef fit(rows,a,task,classes,schedule=None):\n good=[r for r in rows if r['w']>0 and r['y']is not None];root=totals(good,task,classes)['w'];depth=a.get('maxDepth',2);minimum=a.get('minLeaf',1);minmass=Q(a.get('minLeafWeight',0));mingain=Q(a.get('minGain',0));route=a.get('missingRoute','best')\n def build(rr,d,path):\n  st=totals(rr,task,classes);n=dict(rows=rr,st=st,split=None,left=None,right=None,path=path)\n  if d==depth:return n\n  best=None\n  for j in range(len(rr[0]['x'])):\n   if schedule is not None and j not in schedule[path]:continue\n   values=sorted({r['x'][j]for r in rr if r['x'][j]is not None});missing=[r for r in rr if r['x'][j]is None];observed=[r for r in rr if r['x'][j]is not None]\n   candidates=[]\n   for lo,hi in zip(values,values[1:]):\n    q=(lo+hi)/2;left=[r for r in observed if r['x'][j]<=q];right=[r for r in observed if r['x'][j]>q];directions=[route]if route!='best'else['left','right']if missing else['left'if len(left)>=len(right)else'right']\n    for direction in directions:candidates.append(('threshold',q,direction,left+missing if direction=='left'else left,right+missing if direction=='right'else right))\n   if missing and observed:candidates.append(('missing-only',None,'left',missing,observed))\n   for kind,q,direction,left,right in candidates:\n    l=totals(left,task,classes);r=totals(right,task,classes)\n    if min(l['n'],r['n'])<minimum or min(l['w'],r['w'])<minmass or min(l['w'],r['w'])<=0:continue\n    gain=(st['risk']-l['risk']-r['risk'])/root\n    if best is None or gain>best['gain']:best=dict(feature=j,kind=kind,threshold=q,missingRoute=direction,left=left,right=right,gain=gain)\n  if best and best['gain']>0 and best['gain']>mingain:\n   j=best['feature'];go=lambda r:r['x'][j]is None if best['kind']=='missing-only'else best['missingRoute']=='left'if r['x'][j]is None else r['x'][j]<=best['threshold'];n['split']=best;n['left']=build([r for r in rr if go(r)],d+1,path+'L');n['right']=build([r for r in rr if not go(r)],d+1,path+'R')\n  return n\n return build(good,0,'')\n\ndef predict(tree,x):\n n=tree\n while n['split']:\n  s=n['split'];v=x[s['feature']];left=v is None if s['kind']=='missing-only'else s['missingRoute']=='left'if v is None else v<=s['threshold'];n=n['left'if left else'right']\n return dict(prediction=n['st']['pred'],probabilities=n['st']['p'])\n\ndef combine(preds,w,task,classes,mode='probabilities'):\n mass=sum(w,Q())\n if not preds or not mass:return dict(prediction=None,probabilities=[],vote=None,prob=None)\n if task=='regression':return dict(prediction=sum((p['prediction']*v for p,v in zip(preds,w)),Q())/mass,probabilities=[],vote=None,prob=None)\n votes=[sum((v for p,v in zip(preds,w)if p['prediction']==c),Q())/mass for c in classes];ps=[sum((p['probabilities'][j]*v for p,v in zip(preds,w)),Q())/mass for j in range(len(classes))];vote=classes[max(range(len(classes)),key=lambda j:votes[j])];prob=classes[max(range(len(classes)),key=lambda j:ps[j])];return dict(prediction=vote if mode=='votes'else prob,probabilities=ps,vote=vote,prob=prob,votes=votes)\ndef number(v):\n if v is None or isinstance(v,bool):raise ValueError('explicit null/bool is not a numeric parameter')\n return Q(v)\ndef variance(a):\n B=a['B'];v=number(a['marginalVariance']);rho=number(a.get('rho',0))\n if not isinstance(B,int)or isinstance(B,bool)or B<1 or v<0:raise ValueError('positive integer B/nonnegative variance')\n if B>1 and v and not -Q(1,B-1)<=rho<=1:raise ValueError('equicorrelation PSD bound')\n return dict(B=B,marginalVariance=v,correlationApplicable=B>1 and bool(v),varianceOfMean=v if B==1 else v*(1+(B-1)*rho)/B)\ndef aggregate(a):\n task=a.get('task','regression');classes=[str(c)for c in a.get('classes',[])];members=a['members'];w=[number(v)for v in a.get('memberWeights',[1]*len(members))]\n if not members or min(w)<0 or sum(w)<=0:raise ValueError('nonnegative member weights/positive total')\n order=[p.get('id',i)for i,p in enumerate(members[0]['predictions'])];keys=lambda x:(type(x).__name__,x);lookup=[{keys(p.get('id',i)):p for i,p in enumerate(m['predictions'])}for m in members]\n if any(set(m)!={keys(v)for v in order}for m in lookup):raise ValueError('same query ID set')\n out=[]\n for pid in order:\n  predictions=[dict(prediction=number(m[keys(pid)]['value']),probabilities=[])if task=='regression'else dict(prediction=str(m[keys(pid)]['label']),probabilities=[number(v)for v in m[keys(pid)]['probabilities']])for m in lookup]\n  if task=='classification'and any(min(p['probabilities'])<0 or sum(p['probabilities'])!=1 for p in predictions):raise ValueError('probability simplex')\n  out.append(dict(id=pid,**combine(predictions,w,task,classes,a.get('aggregation','probabilities'))))\n return dict(task=task,classes=classes,predictions=out)\ndef scored(preds,rows,task,classes):\n mass=loss=absolute=errors=voteerrors=Q();out=[]\n for p,r in zip(preds,rows):\n  ok=p['prediction']is not None and r['y']is not None and r['w']>0;v=None\n  if ok:\n   mass+=r['w']\n   if task=='regression':e=r['y']-p['prediction'];v=e*e;absolute+=r['w']*abs(e)\n   else:v=sum(((q-(1 if r['y']==c else 0))**2 for c,q in zip(classes,p['probabilities'])),Q());errors+=r['w']*(p['prediction']!=r['y']);voteerrors+=r['w']*(p['vote']!=r['y'])\n   loss+=r['w']*v\n  out.append(dict(p,actual=r['y'],weight=r['w'],scoreEligible=ok,loss=v))\n return dict(rows=out,eligibleRows=sum(r['scoreEligible']for r in out),weight=mass,totalLoss=loss,meanLoss=loss/mass if mass else None,MAE=absolute/mass if mass and task=='regression'else None,errorRate=errors/mass if mass and task=='classification'else None,labelVoteErrorRate=voteerrors/mass if mass and task=='classification'else None)\ndef ensemble(a,forest=False):\n task=a.get('task','regression');classes=[str(v)for v in(a.get('classes')or[])];rr=normalized(a['rows'],task);key=lambda x:(type(x).__name__,x);lookup={key(r['id']):r for r in rr};weights=[number(v)for v in a.get('memberWeights',[1]*len(a['bootstrapDraws']))]\n if not any(r['w']>0 and r['y']is not None for r in rr)or min(weights)<0 or sum(weights)<=0:raise ValueError('positive eligible training and member weight')\n members=[]\n for i,draw in enumerate(a['bootstrapDraws']):\n  data=[lookup[key(v)]for v in draw];schedule=a['nodeFeatures'][i]if forest else None;model=fit(data,a,task,classes,schedule);inbag={key(v)for v in draw};members.append(dict(tree=model,draw=draw,inbag=inbag,weight=weights[i]))\n predictions=[]\n for q in a.get('queries',[]):predictions.append(dict(id=q['id'],**combine([predict(m['tree'],[None if v is None else number(v)for v in q['x']])for m in members],weights,task,classes,a.get('aggregation','probabilities'))))\n oob=[]\n for r in rr:\n  applicable=[i for i,m in enumerate(members)if key(r['id'])not in m['inbag']];p=combine([predict(members[i]['tree'],r['x'])for i in applicable],[weights[i]for i in applicable],task,classes,a.get('aggregation','probabilities'));oob.append(dict(id=r['id'],applicable=applicable,positiveMembers=sum(weights[i]>0 for i in applicable),**p))\n return dict(task=task,classes=classes,members=members,predictions=predictions,outOfBag=scored(oob,rr,task,classes))\ndef boost(a):\n if a.get('task','regression')!='regression':raise ValueError('regression boosting only')\n rr=normalized(a['rows']);good=[r for r in rr if r['w']and r['y']is not None];W=sum((r['w']for r in good),Q())\n if not W:raise ValueError('positive eligible training')\n eta=number(a.get('learningRate','1/2'));stages=a.get('stages',3)\n if not 0<=eta<=1 or not isinstance(stages,int)or isinstance(stages,bool)or not 0<=stages<=8:raise ValueError('supported rate/stages')\n initial=number(a['initial'])if'initial'in a else sum((r['w']*r['y']for r in good),Q())/W;training=[[initial]for r in rr];queries=[[initial]for q in a.get('queries',[])];fits=[];losses=[]\n for stage in range(stages+1):\n  sse=sum((r['w']*(r['y']-p[-1])**2 for r,p in zip(rr,training)if r['w']and r['y']is not None),Q());losses.append(dict(stage=stage,rawWeightedSSE=sse,MSE=sse/W,meanHalfSquaredLoss=sse/(2*W)))\n  if stage==stages:break\n  residuals=[dict(r,y=None if r['y']is None else r['y']-p[-1])for r,p in zip(rr,training)];tree=fit(residuals,a,'regression',[]);h=[predict(tree,r['x'])['prediction']for r in rr];qh=[predict(tree,[None if v is None else number(v)for v in q['x']])['prediction']for q in a.get('queries',[])];norm=sum((r['w']*v*v for r,v in zip(rr,h)if r['y']is not None),Q());stageRows=[]\n  for i,(r,p)in enumerate(zip(rr,training)):\n   residual=None if r['y']is None else r['y']-p[-1];stageRows.append(dict(id=r['id'],before=p[-1],residual=residual,negativeCoordinateDerivative=None if residual is None else r['w']*residual/W,fit=h[i],addition=eta*h[i],after=p[-1]+eta*h[i]));p.append(p[-1]+eta*h[i])\n  for p,v in zip(queries,qh):p.append(p[-1]+eta*v)\n  fits.append(dict(stage=stage+1,tree=tree,rows=stageRows,queryFits=qh,norm=norm,predictedSSEDecrease=eta*(2-eta)*norm))\n return dict(task='regression',initial=initial,learningRate=eta,stages=stages,training=training,queries=queries,fits=fits,losses=losses,predictions=[dict(id=q['id'],prediction=p[-1],probabilities=[],vote=None,prob=None)for q,p in zip(a.get('queries',[]),queries)])\nclass Stream:\n def __init__(self,state):self.state=state\n def choose(self,n):\n  limit=(1<<32)-((1<<32)%n)\n  while True:\n   self.state=(1664525*self.state+1013904223)&0xffffffff\n   if self.state<limit:return self.state%n\ndef fixed_schedules(ids,p,seed):\n stream=Stream(seed);draws=[];schedules=[];paths=['']+[p for d in[1,2]for p in map(''.join,itertools.product('LR',repeat=d))]\n for member in range(4):\n  draws.append([ids[stream.choose(len(ids))]for _ in range(len(ids))]);schedule={}\n  for path in paths:\n   order=list(range(p))\n   for j in range(p-1,0,-1):k=stream.choose(j+1);order[j],order[k]=order[k],order[j]\n   schedule[path]=sorted(order[:max(1,int(math.sqrt(p)))])\n  schedules.append(schedule)\n return draws,schedules\ndef csvread(file):\n with Path(file).open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))\ndef read_sources(source):\n source=Path(source);raw=csvread(source/'actual320-country-four-indicators-original-2020-2024.csv');lookup={(r['countryISO3'],int(r['date']),r['indicatorID']):r for r in raw};country=[]\n for code in sorted({r['countryISO3']for r in raw}):\n  for year in range(2020,2025):\n   cols=['NY.GDP.PCAP.KD','NY.GDP.MKTP.KD.ZG','FP.CPI.TOTL.ZG','SP.DYN.LE00.IN'];v=[lookup[code,year,k]['originalValueToken']for k in cols];x=[None if not z else Q(z)for z in v[:3]];x[0]=None if x[0]is None else x[0]/10000;y=None if not v[3]else Q(v[3]);eligible=y is not None and None not in x;country.append(dict(id=code+':'+str(year),sourceRow=code+':'+str(year),originalID=code,year=year,x=x,y=y,weight='1',role='excluded'if not eligible else'outer-test'if year==2024 else'train'))\n person=[]\n for i,r in enumerate(csvread(source/'actual3613-NLS-original52-fields-and-selection.csv'),1):\n  v=lambda k:None if r[k]=='.'else Q(r[k]);x=[v('ed76'),v('age76')];y=None if v('wage76')is None else v('wage76')/100;eligible=y is not None and None not in x;person.append(dict(id='person:'+str(i),sourceRow=str(i),originalID=r['id'],x=x,y=y,weight='1',role='excluded'if not eligible else'outer-test'if i%5==0 else'train'))\n company=[]\n for i,r in enumerate(csvread(source/'actual3150-churn-original14-fields-and-selection.csv'),1):company.append(dict(id='customer:'+str(i),sourceRow=str(i),originalID='',x=[Q(r[k])for k in['Call  Failure','Subscription  Length','Charge  Amount']],y=r['Churn'],weight='1',role='outer-test'if i%5==0 else'train'))\n models={}\n for index,(kind,rr,task,leaf)in enumerate([('country',country,'regression',4),('person',person,'regression',50),('company',company,'classification',30)]):\n  ids=[r['id']for r in rr if r['role']=='train'];draws,schedules=fixed_schedules(ids,len(rr[0]['x']),20261102+7919*index);models[kind]=dict(records=rr,task=task,classes=['0','1']if task=='classification'else[],draws=draws,schedules=schedules,minLeaf=leaf)\n return models\n_OMITTED=object()\ndef realdata(models,kind,options=_OMITTED):\n options={}if options is _OMITTED else options\n if not isinstance(options,dict):raise ValueError('options object required, not explicit null')\n m=models[kind];train=[r for r in m['records']if r['role']=='train'];test=[r for r in m['records']if r['role']=='outer-test'];method=options.get('method','forest');depth=options.get('maxDepth',2);count=options.get('memberCount',3);a=dict(rows=train,queries=[dict(id=r['id'],x=r['x'])for r in test],task=m['task'],classes=m['classes'],maxDepth=depth,minLeaf=options.get('minLeaf',m['minLeaf']),minLeafWeight='0',minGain='0',missingRoute='best',learningRate=options.get('learningRate','1/2'),stages=options.get('stages',3))\n if method not in ['bagging','forest','boost']:raise ValueError('known source method')\n if not isinstance(depth,int)or isinstance(depth,bool)or not 0<=depth<=3:raise ValueError('source depth0..3')\n if method!='boost'and(not isinstance(count,int)or isinstance(count,bool)or not 1<=count<=4):raise ValueError('source member count1..4')\n if method=='boost':result=boost(a)\n else:\n  a.update(bootstrapDraws=m['draws'][:count],nodeFeatures=[{p:v for p,v in s.items()if len(p)<depth}for s in m['schedules'][:count]]);result=ensemble(a,method=='forest')\n outer=scored(result['predictions'],normalized(test,m['task']),m['task'],m['classes']);st=totals([r for r in normalized(train,m['task'])if r['w']and r['y']is not None],m['task'],m['classes']);constant=dict(prediction=st['pred'],probabilities=st['p'],vote=st['pred'],prob=st['pred']);baseline=scored([dict(id=r['id'],**constant)for r in test],normalized(test,m['task']),m['task'],m['classes']);return dict(kind=kind,method=method,settings=a,train=train,test=test,result=result,outer=outer,baseline=baseline)\ndef serial(x):\n if isinstance(x,Q):return str(x)\n if isinstance(x,dict):return{k:serial(v)for k,v in x.items()if k not in['inbag','tree']}\n if isinstance(x,(list,tuple)):return[serial(v)for v in x]\n return x\ndef writecsv(file,heads,rows):\n with Path(file).open('w',encoding='utf8',newline='')as f:\n  w=csv.writer(f);w.writerow(heads);w.writerows([[''if v is None else str(v)for v in r]for r in rows])\nAPI='variance'\nINPUT={'B': 4, 'marginalVariance': 4, 'rho': '-1/2'}\n\ndef run_fixed(api,a,out,src):\n import matplotlib\n matplotlib.use('svg')\n import matplotlib.pyplot as plt\n from matplotlib.ticker import MaxNLocator\n plt.rcParams.update({'font.size':14,'svg.fonttype':'none','svg.hashsalt':'ml09-fixed-v1'})\n result=variance(a)if api=='variance'else aggregate(a)if api=='aggregate'else ensemble(a,api=='forest')if api in ['bagging','forest']else boost(a)if api=='boost'else realdata(read_sources(src),a['kind'])\n out=Path(out);out.mkdir(parents=True,exist_ok=True);summary={};points=[]\n def add(x,y,s):\n  if y is not None:points.append([x,y,s])\n if api=='variance':\n  summary={'B':result['B'],'varianceOfMean':result['varianceOfMean']};add(result['B'],result['varianceOfMean'],'Specified finite-B variance');xl='Number of members B';yl='Variance, stipulated units squared';title='Declared covariance model, not fitted trees'\n elif api=='aggregate':\n  p=result['predictions'][0];classification=a.get('task')=='classification';summary={'selectedPrediction':p['prediction']}\n  if classification:\n   summary.update(voteLabel=p['vote'],probabilityLabel=p['prob'],meanProbability1=p['probabilities'][1]);add(1,p['probabilities'][1],'Mean probability of class 1');add(2,p['votes'][1],'Label-vote share of class 1');xl='Aggregation (1=probability, 2=vote)';yl='Probability or vote share'\n  else:\n   for i,m in enumerate(a['members']):add(i+1,Q(m['predictions'][0]['value']),'Member prediction')\n   add(3,p['prediction'],'Weighted mean');xl='Member 1, member 2, aggregate 3';yl='Prediction, assumed units'\n  title='Votes and probabilities are distinct objects'\n elif api in ['bagging','forest']:\n  summary={'queryPrediction':result['predictions'][0]['prediction'],'OOB.scoreable':result['outOfBag']['eligibleRows'],'OOB.meanLoss':result['outOfBag']['meanLoss']}\n  for i,r in enumerate(a['rows']):add(i+1,Q(r['y']),'Observed training outcome')\n  for i,p in enumerate(result['outOfBag']['rows']):add(i+1,p['prediction'],'OOB prediction, when defined')\n  xl='Original training ID order';yl='Outcome, assumed units';title='Repeated draws and ID-level OOB membership'\n elif api=='boost':\n  summary={'initial':result['initial'],'finalMSE':result['losses'][-1]['MSE'],'stages':result['stages']}\n  for r in result['losses']:add(r['stage'],r['MSE'],'Training MSE')\n  xl='Boosting stage (0=initial)';yl='Weighted MSE, outcome units squared';title='Training descent does not certify held-out gain'\n else:\n  summary={'outer.scoreable':result['outer']['eligibleRows'],'outer.meanLoss':result['outer']['meanLoss'],'baseline.meanLoss':result['baseline']['meanLoss'],'OOB.scoreable':result['result']['outOfBag']['eligibleRows'],'OOB.meanLoss':result['result']['outOfBag']['meanLoss']}\n  for i,p in enumerate(result['outer']['rows']):\n   add(i+1,Q(p['actual']),'Observed outcome');add(i+1,p['probabilities'][1]if a['kind']=='company'else p['prediction'],'Forest probability of class 1'if a['kind']=='company'else'Forest prediction')\n  xl='Outer-test source order, not a time path';yl='Churn label / probability'if a['kind']=='company'else'Period life expectancy, years'if a['kind']=='country'else'Nominal 1976 USD per hour';title='Fixed forest; outer labels did not fit the trees'\n def display(v):return 'undefined'if v is None else format(float(v),'.9f')\n writecsv(out/'summary.csv',['metric','value'],[[k,display(v)]for k,v in summary.items()]);writecsv(out/'plot-points.csv',['x','y','series'],points);(out/'full.json').write_text(json.dumps(serial(result),indent=2)+'\\n',encoding='utf8')\n fig,ax=plt.subplots(figsize=(5.6,4.6));fig.subplots_adjust(left=.24,right=.96,bottom=.24,top=.76);colors=['#355c72','#a55336','#507956','#78568b']\n for i,s in enumerate(dict.fromkeys(p[2]for p in points)):\n  pp=[p for p in points if p[2]==s];ax.scatter([float(p[0])for p in pp],[float(p[1])for p in pp],s=12 if len(pp)>100 else 32,alpha=.5 if len(pp)>100 else 1,color=colors[i%4],label=s)\n ax.set_xlabel(xl,labelpad=10,fontsize=11);ax.set_ylabel(yl,labelpad=10,fontsize=11);ax.xaxis.set_major_locator(MaxNLocator(3));ax.yaxis.set_major_locator(MaxNLocator(4));ax.grid(alpha=.18);ax.legend(loc='lower left',bbox_to_anchor=(0,1.01),fontsize=9,frameon=False);fig.suptitle(title,fontsize=9,y=.99);fig.savefig(out/'plot.svg',metadata={'Date':None});plt.close(fig);print(', '.join(k+'='+display(v)for k,v in summary.items()))\nif __name__=='__main__':\n import sys\n try:run_fixed(API,INPUT,sys.argv[1]if len(sys.argv)>1 else'fixed-results',sys.argv[2]if len(sys.argv)>2 else'ml09-sources')\n except ValueError as error:print('Rejected declared input: '+str(error),file=sys.stderr);sys.exit(2)\n",
        "code": "\"\"\"ML09 exact Fraction reproduction from native source fields.\n\npython ml09-public-analysis.py --source-dir ml09-sources --output-dir results\n\nThis authored educational implementation uses direct-centered leaf losses and\nexhaustive midpoint partitions. It reads no JS engine, model contract, checker,\nstored target answers or derived-result CSV. Its five tree arithmetic helpers\nwere copied from the author's own separate Fraction reference, not an independent\npeer. Parser/work budgets and display rounding of the production JS are separate.\nNumerical predictions/proper scores do not certify causal effects, calibration,\nIID OOB validity, survey representativeness or production parameter optimality.\n\"\"\"\nfrom pathlib import Path\nfrom fractions import Fraction as Q\nimport csv,json,math,itertools,argparse\n\ndef normalized(rows,task='regression'):\n return [dict(id=r.get('id',i),x=[None if x is None else Q(x)for x in r.get('x',[])],y=None if r['y']is None else str(r['y'])if task=='classification'else Q(r['y']),w=Q(r.get('weight',1)))for i,r in enumerate(rows)]\n\ndef totals(rows,task,classes):\n W=sum((r['w']for r in rows),Q());mu=sum((r['w']*r['y']for r in rows),Q())/W if task=='regression'and W else None\n probs=[sum((r['w']for r in rows if r['y']==c),Q())/W for c in classes]if task=='classification'and W else[]\n risk=sum((r['w']*(r['y']-mu)**2 for r in rows),Q())if task=='regression'and W else W*sum((p*(1-p)for p in probs),Q())\n return dict(n=len(rows),w=W,mu=mu,p=probs,risk=risk,pred=mu if task=='regression'else classes[max(range(len(probs)),key=lambda i:probs[i])]if probs else None)\n\ndef fit(rows,a,task,classes,schedule=None):\n good=[r for r in rows if r['w']>0 and r['y']is not None];root=totals(good,task,classes)['w'];depth=a.get('maxDepth',2);minimum=a.get('minLeaf',1);minmass=Q(a.get('minLeafWeight',0));mingain=Q(a.get('minGain',0));route=a.get('missingRoute','best')\n def build(rr,d,path):\n  st=totals(rr,task,classes);n=dict(rows=rr,st=st,split=None,left=None,right=None,path=path)\n  if d==depth:return n\n  best=None\n  for j in range(len(rr[0]['x'])):\n   if schedule is not None and j not in schedule[path]:continue\n   values=sorted({r['x'][j]for r in rr if r['x'][j]is not None});missing=[r for r in rr if r['x'][j]is None];observed=[r for r in rr if r['x'][j]is not None]\n   candidates=[]\n   for lo,hi in zip(values,values[1:]):\n    q=(lo+hi)/2;left=[r for r in observed if r['x'][j]<=q];right=[r for r in observed if r['x'][j]>q];directions=[route]if route!='best'else['left','right']if missing else['left'if len(left)>=len(right)else'right']\n    for direction in directions:candidates.append(('threshold',q,direction,left+missing if direction=='left'else left,right+missing if direction=='right'else right))\n   if missing and observed:candidates.append(('missing-only',None,'left',missing,observed))\n   for kind,q,direction,left,right in candidates:\n    l=totals(left,task,classes);r=totals(right,task,classes)\n    if min(l['n'],r['n'])<minimum or min(l['w'],r['w'])<minmass or min(l['w'],r['w'])<=0:continue\n    gain=(st['risk']-l['risk']-r['risk'])/root\n    if best is None or gain>best['gain']:best=dict(feature=j,kind=kind,threshold=q,missingRoute=direction,left=left,right=right,gain=gain)\n  if best and best['gain']>0 and best['gain']>mingain:\n   j=best['feature'];go=lambda r:r['x'][j]is None if best['kind']=='missing-only'else best['missingRoute']=='left'if r['x'][j]is None else r['x'][j]<=best['threshold'];n['split']=best;n['left']=build([r for r in rr if go(r)],d+1,path+'L');n['right']=build([r for r in rr if not go(r)],d+1,path+'R')\n  return n\n return build(good,0,'')\n\ndef predict(tree,x):\n n=tree\n while n['split']:\n  s=n['split'];v=x[s['feature']];left=v is None if s['kind']=='missing-only'else s['missingRoute']=='left'if v is None else v<=s['threshold'];n=n['left'if left else'right']\n return dict(prediction=n['st']['pred'],probabilities=n['st']['p'])\n\ndef combine(preds,w,task,classes,mode='probabilities'):\n mass=sum(w,Q())\n if not preds or not mass:return dict(prediction=None,probabilities=[],vote=None,prob=None)\n if task=='regression':return dict(prediction=sum((p['prediction']*v for p,v in zip(preds,w)),Q())/mass,probabilities=[],vote=None,prob=None)\n votes=[sum((v for p,v in zip(preds,w)if p['prediction']==c),Q())/mass for c in classes];ps=[sum((p['probabilities'][j]*v for p,v in zip(preds,w)),Q())/mass for j in range(len(classes))];vote=classes[max(range(len(classes)),key=lambda j:votes[j])];prob=classes[max(range(len(classes)),key=lambda j:ps[j])];return dict(prediction=vote if mode=='votes'else prob,probabilities=ps,vote=vote,prob=prob,votes=votes)\ndef number(v):\n if v is None or isinstance(v,bool):raise ValueError('explicit null/bool is not a numeric parameter')\n return Q(v)\ndef variance(a):\n B=a['B'];v=number(a['marginalVariance']);rho=number(a.get('rho',0))\n if not isinstance(B,int)or isinstance(B,bool)or B<1 or v<0:raise ValueError('positive integer B/nonnegative variance')\n if B>1 and v and not -Q(1,B-1)<=rho<=1:raise ValueError('equicorrelation PSD bound')\n return dict(B=B,marginalVariance=v,correlationApplicable=B>1 and bool(v),varianceOfMean=v if B==1 else v*(1+(B-1)*rho)/B)\ndef aggregate(a):\n task=a.get('task','regression');classes=[str(c)for c in a.get('classes',[])];members=a['members'];w=[number(v)for v in a.get('memberWeights',[1]*len(members))]\n if not members or min(w)<0 or sum(w)<=0:raise ValueError('nonnegative member weights/positive total')\n order=[p.get('id',i)for i,p in enumerate(members[0]['predictions'])];keys=lambda x:(type(x).__name__,x);lookup=[{keys(p.get('id',i)):p for i,p in enumerate(m['predictions'])}for m in members]\n if any(set(m)!={keys(v)for v in order}for m in lookup):raise ValueError('same query ID set')\n out=[]\n for pid in order:\n  predictions=[dict(prediction=number(m[keys(pid)]['value']),probabilities=[])if task=='regression'else dict(prediction=str(m[keys(pid)]['label']),probabilities=[number(v)for v in m[keys(pid)]['probabilities']])for m in lookup]\n  if task=='classification'and any(min(p['probabilities'])<0 or sum(p['probabilities'])!=1 for p in predictions):raise ValueError('probability simplex')\n  out.append(dict(id=pid,**combine(predictions,w,task,classes,a.get('aggregation','probabilities'))))\n return dict(task=task,classes=classes,predictions=out)\ndef scored(preds,rows,task,classes):\n mass=loss=absolute=errors=voteerrors=Q();out=[]\n for p,r in zip(preds,rows):\n  ok=p['prediction']is not None and r['y']is not None and r['w']>0;v=None\n  if ok:\n   mass+=r['w']\n   if task=='regression':e=r['y']-p['prediction'];v=e*e;absolute+=r['w']*abs(e)\n   else:v=sum(((q-(1 if r['y']==c else 0))**2 for c,q in zip(classes,p['probabilities'])),Q());errors+=r['w']*(p['prediction']!=r['y']);voteerrors+=r['w']*(p['vote']!=r['y'])\n   loss+=r['w']*v\n  out.append(dict(p,actual=r['y'],weight=r['w'],scoreEligible=ok,loss=v))\n return dict(rows=out,eligibleRows=sum(r['scoreEligible']for r in out),weight=mass,totalLoss=loss,meanLoss=loss/mass if mass else None,MAE=absolute/mass if mass and task=='regression'else None,errorRate=errors/mass if mass and task=='classification'else None,labelVoteErrorRate=voteerrors/mass if mass and task=='classification'else None)\ndef ensemble(a,forest=False):\n task=a.get('task','regression');classes=[str(v)for v in(a.get('classes')or[])];rr=normalized(a['rows'],task);key=lambda x:(type(x).__name__,x);lookup={key(r['id']):r for r in rr};weights=[number(v)for v in a.get('memberWeights',[1]*len(a['bootstrapDraws']))]\n if not any(r['w']>0 and r['y']is not None for r in rr)or min(weights)<0 or sum(weights)<=0:raise ValueError('positive eligible training and member weight')\n members=[]\n for i,draw in enumerate(a['bootstrapDraws']):\n  data=[lookup[key(v)]for v in draw];schedule=a['nodeFeatures'][i]if forest else None;model=fit(data,a,task,classes,schedule);inbag={key(v)for v in draw};members.append(dict(tree=model,draw=draw,inbag=inbag,weight=weights[i]))\n predictions=[]\n for q in a.get('queries',[]):predictions.append(dict(id=q['id'],**combine([predict(m['tree'],[None if v is None else number(v)for v in q['x']])for m in members],weights,task,classes,a.get('aggregation','probabilities'))))\n oob=[]\n for r in rr:\n  applicable=[i for i,m in enumerate(members)if key(r['id'])not in m['inbag']];p=combine([predict(members[i]['tree'],r['x'])for i in applicable],[weights[i]for i in applicable],task,classes,a.get('aggregation','probabilities'));oob.append(dict(id=r['id'],applicable=applicable,positiveMembers=sum(weights[i]>0 for i in applicable),**p))\n return dict(task=task,classes=classes,members=members,predictions=predictions,outOfBag=scored(oob,rr,task,classes))\ndef boost(a):\n if a.get('task','regression')!='regression':raise ValueError('regression boosting only')\n rr=normalized(a['rows']);good=[r for r in rr if r['w']and r['y']is not None];W=sum((r['w']for r in good),Q())\n if not W:raise ValueError('positive eligible training')\n eta=number(a.get('learningRate','1/2'));stages=a.get('stages',3)\n if not 0<=eta<=1 or not isinstance(stages,int)or isinstance(stages,bool)or not 0<=stages<=8:raise ValueError('supported rate/stages')\n initial=number(a['initial'])if'initial'in a else sum((r['w']*r['y']for r in good),Q())/W;training=[[initial]for r in rr];queries=[[initial]for q in a.get('queries',[])];fits=[];losses=[]\n for stage in range(stages+1):\n  sse=sum((r['w']*(r['y']-p[-1])**2 for r,p in zip(rr,training)if r['w']and r['y']is not None),Q());losses.append(dict(stage=stage,rawWeightedSSE=sse,MSE=sse/W,meanHalfSquaredLoss=sse/(2*W)))\n  if stage==stages:break\n  residuals=[dict(r,y=None if r['y']is None else r['y']-p[-1])for r,p in zip(rr,training)];tree=fit(residuals,a,'regression',[]);h=[predict(tree,r['x'])['prediction']for r in rr];qh=[predict(tree,[None if v is None else number(v)for v in q['x']])['prediction']for q in a.get('queries',[])];norm=sum((r['w']*v*v for r,v in zip(rr,h)if r['y']is not None),Q());stageRows=[]\n  for i,(r,p)in enumerate(zip(rr,training)):\n   residual=None if r['y']is None else r['y']-p[-1];stageRows.append(dict(id=r['id'],before=p[-1],residual=residual,negativeCoordinateDerivative=None if residual is None else r['w']*residual/W,fit=h[i],addition=eta*h[i],after=p[-1]+eta*h[i]));p.append(p[-1]+eta*h[i])\n  for p,v in zip(queries,qh):p.append(p[-1]+eta*v)\n  fits.append(dict(stage=stage+1,tree=tree,rows=stageRows,queryFits=qh,norm=norm,predictedSSEDecrease=eta*(2-eta)*norm))\n return dict(task='regression',initial=initial,learningRate=eta,stages=stages,training=training,queries=queries,fits=fits,losses=losses,predictions=[dict(id=q['id'],prediction=p[-1],probabilities=[],vote=None,prob=None)for q,p in zip(a.get('queries',[]),queries)])\nclass Stream:\n def __init__(self,state):self.state=state\n def choose(self,n):\n  limit=(1<<32)-((1<<32)%n)\n  while True:\n   self.state=(1664525*self.state+1013904223)&0xffffffff\n   if self.state<limit:return self.state%n\ndef fixed_schedules(ids,p,seed):\n stream=Stream(seed);draws=[];schedules=[];paths=['']+[p for d in[1,2]for p in map(''.join,itertools.product('LR',repeat=d))]\n for member in range(4):\n  draws.append([ids[stream.choose(len(ids))]for _ in range(len(ids))]);schedule={}\n  for path in paths:\n   order=list(range(p))\n   for j in range(p-1,0,-1):k=stream.choose(j+1);order[j],order[k]=order[k],order[j]\n   schedule[path]=sorted(order[:max(1,int(math.sqrt(p)))])\n  schedules.append(schedule)\n return draws,schedules\ndef csvread(file):\n with Path(file).open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))\ndef read_sources(source):\n source=Path(source);raw=csvread(source/'actual320-country-four-indicators-original-2020-2024.csv');lookup={(r['countryISO3'],int(r['date']),r['indicatorID']):r for r in raw};country=[]\n for code in sorted({r['countryISO3']for r in raw}):\n  for year in range(2020,2025):\n   cols=['NY.GDP.PCAP.KD','NY.GDP.MKTP.KD.ZG','FP.CPI.TOTL.ZG','SP.DYN.LE00.IN'];v=[lookup[code,year,k]['originalValueToken']for k in cols];x=[None if not z else Q(z)for z in v[:3]];x[0]=None if x[0]is None else x[0]/10000;y=None if not v[3]else Q(v[3]);eligible=y is not None and None not in x;country.append(dict(id=code+':'+str(year),sourceRow=code+':'+str(year),originalID=code,year=year,x=x,y=y,weight='1',role='excluded'if not eligible else'outer-test'if year==2024 else'train'))\n person=[]\n for i,r in enumerate(csvread(source/'actual3613-NLS-original52-fields-and-selection.csv'),1):\n  v=lambda k:None if r[k]=='.'else Q(r[k]);x=[v('ed76'),v('age76')];y=None if v('wage76')is None else v('wage76')/100;eligible=y is not None and None not in x;person.append(dict(id='person:'+str(i),sourceRow=str(i),originalID=r['id'],x=x,y=y,weight='1',role='excluded'if not eligible else'outer-test'if i%5==0 else'train'))\n company=[]\n for i,r in enumerate(csvread(source/'actual3150-churn-original14-fields-and-selection.csv'),1):company.append(dict(id='customer:'+str(i),sourceRow=str(i),originalID='',x=[Q(r[k])for k in['Call  Failure','Subscription  Length','Charge  Amount']],y=r['Churn'],weight='1',role='outer-test'if i%5==0 else'train'))\n models={}\n for index,(kind,rr,task,leaf)in enumerate([('country',country,'regression',4),('person',person,'regression',50),('company',company,'classification',30)]):\n  ids=[r['id']for r in rr if r['role']=='train'];draws,schedules=fixed_schedules(ids,len(rr[0]['x']),20261102+7919*index);models[kind]=dict(records=rr,task=task,classes=['0','1']if task=='classification'else[],draws=draws,schedules=schedules,minLeaf=leaf)\n return models\n_OMITTED=object()\ndef realdata(models,kind,options=_OMITTED):\n options={}if options is _OMITTED else options\n if not isinstance(options,dict):raise ValueError('options object required, not explicit null')\n m=models[kind];train=[r for r in m['records']if r['role']=='train'];test=[r for r in m['records']if r['role']=='outer-test'];method=options.get('method','forest');depth=options.get('maxDepth',2);count=options.get('memberCount',3);a=dict(rows=train,queries=[dict(id=r['id'],x=r['x'])for r in test],task=m['task'],classes=m['classes'],maxDepth=depth,minLeaf=options.get('minLeaf',m['minLeaf']),minLeafWeight='0',minGain='0',missingRoute='best',learningRate=options.get('learningRate','1/2'),stages=options.get('stages',3))\n if method not in ['bagging','forest','boost']:raise ValueError('known source method')\n if not isinstance(depth,int)or isinstance(depth,bool)or not 0<=depth<=3:raise ValueError('source depth0..3')\n if method!='boost'and(not isinstance(count,int)or isinstance(count,bool)or not 1<=count<=4):raise ValueError('source member count1..4')\n if method=='boost':result=boost(a)\n else:\n  a.update(bootstrapDraws=m['draws'][:count],nodeFeatures=[{p:v for p,v in s.items()if len(p)<depth}for s in m['schedules'][:count]]);result=ensemble(a,method=='forest')\n outer=scored(result['predictions'],normalized(test,m['task']),m['task'],m['classes']);st=totals([r for r in normalized(train,m['task'])if r['w']and r['y']is not None],m['task'],m['classes']);constant=dict(prediction=st['pred'],probabilities=st['p'],vote=st['pred'],prob=st['pred']);baseline=scored([dict(id=r['id'],**constant)for r in test],normalized(test,m['task']),m['task'],m['classes']);return dict(kind=kind,method=method,settings=a,train=train,test=test,result=result,outer=outer,baseline=baseline)\ndef serial(x):\n if isinstance(x,Q):return str(x)\n if isinstance(x,dict):return{k:serial(v)for k,v in x.items()if k not in['inbag','tree']}\n if isinstance(x,(list,tuple)):return[serial(v)for v in x]\n return x\ndef writecsv(file,heads,rows):\n with Path(file).open('w',encoding='utf8',newline='')as f:\n  w=csv.writer(f);w.writerow(heads);w.writerows([[''if v is None else str(v)for v in r]for r in rows])\nAPI='variance'\nINPUT={'B': 4, 'marginalVariance': 4, 'rho': '-1/2'}\n\ndef run_fixed(api,a,out,src):\n import matplotlib\n matplotlib.use('svg')\n import matplotlib.pyplot as plt\n from matplotlib.ticker import MaxNLocator\n plt.rcParams.update({'font.size':14,'svg.fonttype':'none','svg.hashsalt':'ml09-fixed-v1'})\n result=variance(a)if api=='variance'else aggregate(a)if api=='aggregate'else ensemble(a,api=='forest')if api in ['bagging','forest']else boost(a)if api=='boost'else realdata(read_sources(src),a['kind'])\n out=Path(out);out.mkdir(parents=True,exist_ok=True);summary={};points=[]\n def add(x,y,s):\n  if y is not None:points.append([x,y,s])\n if api=='variance':\n  summary={'B':result['B'],'varianceOfMean':result['varianceOfMean']};add(result['B'],result['varianceOfMean'],'Specified finite-B variance');xl='Number of members B';yl='Variance, stipulated units squared';title='Declared covariance model, not fitted trees'\n elif api=='aggregate':\n  p=result['predictions'][0];classification=a.get('task')=='classification';summary={'selectedPrediction':p['prediction']}\n  if classification:\n   summary.update(voteLabel=p['vote'],probabilityLabel=p['prob'],meanProbability1=p['probabilities'][1]);add(1,p['probabilities'][1],'Mean probability of class 1');add(2,p['votes'][1],'Label-vote share of class 1');xl='Aggregation (1=probability, 2=vote)';yl='Probability or vote share'\n  else:\n   for i,m in enumerate(a['members']):add(i+1,Q(m['predictions'][0]['value']),'Member prediction')\n   add(3,p['prediction'],'Weighted mean');xl='Member 1, member 2, aggregate 3';yl='Prediction, assumed units'\n  title='Votes and probabilities are distinct objects'\n elif api in ['bagging','forest']:\n  summary={'queryPrediction':result['predictions'][0]['prediction'],'OOB.scoreable':result['outOfBag']['eligibleRows'],'OOB.meanLoss':result['outOfBag']['meanLoss']}\n  for i,r in enumerate(a['rows']):add(i+1,Q(r['y']),'Observed training outcome')\n  for i,p in enumerate(result['outOfBag']['rows']):add(i+1,p['prediction'],'OOB prediction, when defined')\n  xl='Original training ID order';yl='Outcome, assumed units';title='Repeated draws and ID-level OOB membership'\n elif api=='boost':\n  summary={'initial':result['initial'],'finalMSE':result['losses'][-1]['MSE'],'stages':result['stages']}\n  for r in result['losses']:add(r['stage'],r['MSE'],'Training MSE')\n  xl='Boosting stage (0=initial)';yl='Weighted MSE, outcome units squared';title='Training descent does not certify held-out gain'\n else:\n  summary={'outer.scoreable':result['outer']['eligibleRows'],'outer.meanLoss':result['outer']['meanLoss'],'baseline.meanLoss':result['baseline']['meanLoss'],'OOB.scoreable':result['result']['outOfBag']['eligibleRows'],'OOB.meanLoss':result['result']['outOfBag']['meanLoss']}\n  for i,p in enumerate(result['outer']['rows']):\n   add(i+1,Q(p['actual']),'Observed outcome');add(i+1,p['probabilities'][1]if a['kind']=='company'else p['prediction'],'Forest probability of class 1'if a['kind']=='company'else'Forest prediction')\n  xl='Outer-test source order, not a time path';yl='Churn label / probability'if a['kind']=='company'else'Period life expectancy, years'if a['kind']=='country'else'Nominal 1976 USD per hour';title='Fixed forest; outer labels did not fit the trees'\n def display(v):return 'undefined'if v is None else format(float(v),'.9f')\n writecsv(out/'summary.csv',['metric','value'],[[k,display(v)]for k,v in summary.items()]);writecsv(out/'plot-points.csv',['x','y','series'],points);(out/'full.json').write_text(json.dumps(serial(result),indent=2)+'\\n',encoding='utf8')\n fig,ax=plt.subplots(figsize=(5.6,4.6));fig.subplots_adjust(left=.24,right=.96,bottom=.24,top=.76);colors=['#355c72','#a55336','#507956','#78568b']\n for i,s in enumerate(dict.fromkeys(p[2]for p in points)):\n  pp=[p for p in points if p[2]==s];ax.scatter([float(p[0])for p in pp],[float(p[1])for p in pp],s=12 if len(pp)>100 else 32,alpha=.5 if len(pp)>100 else 1,color=colors[i%4],label=s)\n ax.set_xlabel(xl,labelpad=10,fontsize=11);ax.set_ylabel(yl,labelpad=10,fontsize=11);ax.xaxis.set_major_locator(MaxNLocator(3));ax.yaxis.set_major_locator(MaxNLocator(4));ax.grid(alpha=.18);ax.legend(loc='lower left',bbox_to_anchor=(0,1.01),fontsize=9,frameon=False);fig.suptitle(title,fontsize=9,y=.99);fig.savefig(out/'plot.svg',metadata={'Date':None});plt.close(fig);print(', '.join(k+'='+display(v)for k,v in summary.items()))\nif __name__=='__main__':\n import sys\n try:run_fixed(API,INPUT,sys.argv[1]if len(sys.argv)>1 else'fixed-results',sys.argv[2]if len(sys.argv)>2 else'ml09-sources')\n except ValueError as error:print('Rejected declared input: '+str(error),file=sys.stderr);sys.exit(2)\n",
        "inputFiles": [],
        "input": {
          "B": 4,
          "marginalVariance": 4,
          "rho": "-1/2"
        },
        "returnCode": 2,
        "expectedFailure": true,
        "stdout": "",
        "stderr": "Rejected declared input: equicorrelation PSD bound\n",
        "summary": {},
        "plotPoints": [],
        "plotFile": null,
        "plotSHA256": null,
        "files": [],
        "scope": "Actually executed self-contained fixed example; current web controls execute separately. Python Fraction and finite-precision base R. Author gate, not independent peer."
      }
    },
    "r": {
      "correlated": {
        "api": "variance",
        "variant": "correlated",
        "language": "r",
        "codeFile": "ml09-code/variance-correlated.R",
        "codeSHA256": "f45a8a2a7234aaed0b32a8adba8af184dfded3bd2bcbb3a817179c3448092f8b",
        "codeText": "# ML09 base-R reproduction from native original-field CSVs.\n# Rscript ml09-public-analysis.R ml09-sources results-r\n# Separately written vectorized direct-centered squared/Gini losses.\n# No Python/JS/model-contract/stored-answer/derived-result reader or package.\n# Numeric arithmetic is binary64:1e-12 relative tie tolerance stabilizes exact\n# source ties,but does not certify tiny margins/underflow like Fraction JS/Python.\n# Data-frame rows use x0,x1,...,y,weight; original IDs remain attached to draws.\noptions(stringsAsFactors=FALSE,digits=17)\nnum<-function(v){if(is.null(v)||length(v)!=1||is.na(v))stop('numeric parameter required, not explicit NULL');p<-strsplit(as.character(v),'/',fixed=TRUE)[[1]];z<-if(length(p)==2)as.numeric(p[1])/as.numeric(p[2])else as.numeric(v);if(!is.finite(z))stop('finite numeric parameter');z}\noption<-function(a,k,default){if(k%in%names(a))a[[k]]else default}\nnormrows<-function(d,task){if(!'weight'%in%names(d))d$weight<-1;if(!'id'%in%names(d))d$id<-as.character(seq_len(nrow(d))-1);d$weight<-as.numeric(d$weight);if(anyNA(d$weight)||any(d$weight<0))stop('nonnegative weights');if(task=='regression')d$y<-as.numeric(d$y)else d$y<-as.character(d$y);d}\nstat<-function(d,task,classes){W<-sum(d$weight);mu<-if(task=='regression'&&W)sum(d$weight*d$y)/W else NA_real_;p<-if(task=='classification'&&W)vapply(classes,function(c)sum(d$weight[d$y==c])/W,0)else numeric();risk<-if(task=='regression'&&W)sum(d$weight*(d$y-mu)^2)else W*sum(p*(1-p));list(n=nrow(d),w=W,mu=mu,p=unname(p),risk=risk,pred=if(task=='regression')mu else if(W)classes[which.max(p)]else NA_character_)}\nfit<-function(d,a,task,classes,schedule=NULL){d<-d[d$weight>0&!is.na(d$y),,drop=FALSE];if(!nrow(d))stop('positive observed training');W<-sum(d$weight);depth<-option(a,'maxDepth',2);minimum<-option(a,'minLeaf',1);minmass<-num(option(a,'minLeafWeight',0));mingain<-num(option(a,'minGain',0));route<-option(a,'missingRoute','best');features<-grep('^x[0-9]+$',names(d),value=TRUE)\n build<-function(rr,level,path){st<-stat(rr,task,classes);node<-list(rows=rr,st=st,split=NULL,left=NULL,right=NULL,path=path);if(level==depth)return(node);best<-NULL;allowed<-if(is.null(schedule))seq_along(features)-1L else schedule[[match(path,names(schedule))]]\n  for(j in seq_along(features)-1L){if(!j%in%allowed)next;v<-rr[[features[j+1L]]];values<-sort(unique(v[!is.na(v)]));candidates<-list()\n   if(length(values)>1)for(k in seq_len(length(values)-1L)){threshold<-(values[k]+values[k+1L])/2;missing<-is.na(v);left<-!missing&v<=threshold;right<-!missing&v>threshold;directions<-if(route!='best')route else if(any(missing))c('left','right')else if(sum(left)>=sum(right))'left'else'right';for(direction in directions)candidates[[length(candidates)+1L]]<-list(kind='threshold',threshold=threshold,missingRoute=direction,left=if(direction=='left')left|missing else left,right=if(direction=='right')right|missing else right)}\n   if(anyNA(v)&&any(!is.na(v)))candidates[[length(candidates)+1L]]<-list(kind='missing-only',threshold=NA_real_,missingRoute='left',left=is.na(v),right=!is.na(v))\n   for(candidate in candidates){l<-rr[candidate$left,,drop=FALSE];r<-rr[candidate$right,,drop=FALSE];ls<-stat(l,task,classes);rs<-stat(r,task,classes);if(min(ls$n,rs$n)<minimum||min(ls$w,rs$w)<minmass||min(ls$w,rs$w)<=0)next;gain<-(st$risk-ls$risk-rs$risk)/W;tol<-1e-12*max(1,abs(gain),if(is.null(best))0 else abs(best$gain));if(is.null(best)||gain>best$gain+tol)best<-c(candidate,list(feature=j,gain=gain,l=l,r=r))}\n  }\n  if(!is.null(best)&&best$gain>max(mingain,1e-12)){node$split<-best;node$left<-build(best$l,level+1L,paste0(path,'L'));node$right<-build(best$r,level+1L,paste0(path,'R'))};node\n };build(d,0L,'')\n}\npredict_one<-function(tree,row){n<-tree;while(!is.null(n$split)){s<-n$split;v<-as.numeric(row[[paste0('x',s$feature)]]);left<-if(s$kind=='missing-only')is.na(v)else if(is.na(v))s$missingRoute=='left'else v<=s$threshold;n<-if(left)n$left else n$right};list(prediction=n$st$pred,probabilities=n$st$p)}\ncombine<-function(pp,w,task,classes,mode='probabilities'){W<-sum(w);if(!length(pp)||!W)return(list(prediction=if(task=='regression')NA_real_ else NA_character_,probabilities=numeric(),vote=NA_character_,prob=NA_character_));if(task=='regression')return(list(prediction=sum(vapply(pp,function(p)p$prediction,0)*w)/W,probabilities=numeric(),vote=NA_character_,prob=NA_character_));votes<-vapply(classes,function(c)sum(w[vapply(pp,function(p)p$prediction==c,FALSE)])/W,0);probs<-vapply(seq_along(classes),function(j)sum(vapply(pp,function(p)p$probabilities[j],0)*w)/W,0);vote<-classes[which.max(votes)];prob<-classes[which.max(probs)];list(prediction=if(mode=='votes')vote else prob,probabilities=unname(probs),vote=vote,prob=prob,votes=unname(votes))}\nvariance<-function(a){B<-num(a$B);v<-num(a$marginalVariance);rho<-num(option(a,'rho',0));if(B<1||B!=floor(B)||v<0)stop('integer B/nonnegative variance');if(B>1&&v>0&&(rho< -1/(B-1)||rho>1))stop('PSD correlation');list(B=B,marginalVariance=v,correlationApplicable=B>1&&v>0,varianceOfMean=if(B==1)v else v*(1+(B-1)*rho)/B)}\naggregate<-function(a){task<-option(a,'task','regression');classes<-option(a,'classes',character());w<-vapply(option(a,'memberWeights',as.list(rep(1,length(a$members)))),num,0);if(any(w<0)||sum(w)<=0)stop('positive member mass');ids<-a$members[[1]]$predictions$id;pp<-lapply(ids,function(id){members<-lapply(a$members,function(m){r<-m$predictions[match(id,m$predictions$id),,drop=FALSE];if(task=='regression')list(prediction=num(r$value),probabilities=numeric())else list(prediction=as.character(r$label),probabilities=as.numeric(r[paste0('p',seq_along(classes)-1L)]))});c(list(id=id),combine(members,w,task,classes,option(a,'aggregation','probabilities')))});list(task=task,classes=classes,predictions=pp)}\nscored<-function(preds,d,task,classes){W<-loss<-absolute<-errors<-voteerrors<-0;count<-0L;out<-lapply(seq_len(nrow(d)),function(i){r<-d[i,,drop=FALSE];p<-preds[[i]];ok<-!is.na(p$prediction)&&!is.na(r$y)&&r$weight>0;value<-NA_real_;if(ok){count<<-count+1L;W<<-W+r$weight;if(task=='regression'){e<-r$y-p$prediction;value<-e*e;absolute<<-absolute+r$weight*abs(e)}else{value<-sum((p$probabilities-as.numeric(classes==r$y))^2);errors<<-errors+r$weight*(p$prediction!=r$y);voteerrors<<-voteerrors+r$weight*(p$vote!=r$y)};loss<<-loss+r$weight*value};c(p,list(actual=r$y,weight=r$weight,scoreEligible=ok,loss=value))});list(rows=out,eligibleRows=count,weight=W,totalLoss=loss,meanLoss=if(W)loss/W else NA_real_,MAE=if(W&&task=='regression')absolute/W else NA_real_,errorRate=if(W&&task=='classification')errors/W else NA_real_,labelVoteErrorRate=if(W&&task=='classification')voteerrors/W else NA_real_)}\nensemble<-function(a,forest=FALSE){task<-option(a,'task','regression');classes<-option(a,'classes',character());d<-normrows(a$rows,task);w<-vapply(option(a,'memberWeights',as.list(rep(1,length(a$bootstrapDraws)))),num,0);if(any(w<0)||sum(w)<=0)stop('positive member mass');members<-lapply(seq_along(a$bootstrapDraws),function(i){draw<-a$bootstrapDraws[[i]];indices<-match(draw,d$id);if(anyNA(indices))stop('unknown draw source');tree<-fit(d[indices,,drop=FALSE],a,task,classes,if(forest)a$nodeFeatures[[i]]else NULL);list(tree=tree,draw=draw,inbag=unique(draw),weight=w[i])});queries<-a$queries;preds<-lapply(seq_len(nrow(queries)),function(i)c(list(id=queries$id[i]),combine(lapply(members,function(m)predict_one(m$tree,queries[i,,drop=FALSE])),w,task,classes,option(a,'aggregation','probabilities'))));oob<-lapply(seq_len(nrow(d)),function(i){app<-which(!vapply(members,function(m)d$id[i]%in%m$inbag,FALSE));pp<-combine(lapply(app,function(j)predict_one(members[[j]]$tree,d[i,,drop=FALSE])),w[app],task,classes,option(a,'aggregation','probabilities'));c(list(id=d$id[i],applicable=app-1L,positiveMembers=sum(w[app]>0)),pp)});list(task=task,classes=classes,members=members,predictions=preds,outOfBag=scored(oob,d,task,classes))}\nboost<-function(a){if(option(a,'task','regression')!='regression')stop('regression boosting only');d<-normrows(a$rows,'regression');eligible<-d$weight>0&!is.na(d$y);W<-sum(d$weight[eligible]);if(!W)stop('positive eligible training');eta<-num(option(a,'learningRate','1/2'));stages<-option(a,'stages',3);if(is.null(stages)||stages!=floor(stages)||stages<0||stages>8||eta<0||eta>1)stop('supported rate/stages');initial<-if('initial'%in%names(a))num(a$initial)else sum(d$weight[eligible]*d$y[eligible])/W;train<-matrix(initial,nrow(d),stages+1L);query<-matrix(initial,nrow(a$queries),stages+1L);losses<-fits<-list();for(stage in 0:stages){sse<-sum(d$weight[eligible]*(d$y[eligible]-train[eligible,stage+1L])^2);losses[[stage+1L]]<-list(stage=stage,rawWeightedSSE=sse,MSE=sse/W,meanHalfSquaredLoss=sse/(2*W));if(stage==stages)break;residual<-d;residual$y<-d$y-train[,stage+1L];tree<-fit(residual,a,'regression',character());h<-vapply(seq_len(nrow(d)),function(i)predict_one(tree,d[i,,drop=FALSE])$prediction,0);qh<-vapply(seq_len(nrow(a$queries)),function(i)predict_one(tree,a$queries[i,,drop=FALSE])$prediction,0);stageRows<-lapply(seq_len(nrow(d)),function(i)list(id=d$id[i],before=train[i,stage+1L],residual=residual$y[i],negativeCoordinateDerivative=d$weight[i]*residual$y[i]/W,fit=h[i],addition=eta*h[i],after=train[i,stage+1L]+eta*h[i]));train[,stage+2L]<-train[,stage+1L]+eta*h;query[,stage+2L]<-query[,stage+1L]+eta*qh;norm<-sum(d$weight[eligible]*h[eligible]^2);fits[[stage+1L]]<-list(stage=stage+1L,tree=tree,rows=stageRows,queryFits=qh,norm=norm,predictedSSEDecrease=eta*(2-eta)*norm)};list(task='regression',initial=initial,learningRate=eta,stages=stages,training=train,queries=query,fits=fits,losses=losses,predictions=lapply(seq_len(nrow(a$queries)),function(i)list(id=a$queries$id[i],prediction=query[i,stages+1L],probabilities=numeric(),vote=NA_character_,prob=NA_character_)))}\nfixed_schedules<-function(ids,p,seed){state<-seed;choose<-function(n){limit<-floor(4294967296/n)*n;repeat{state<<-(1664525*state+1013904223)%%4294967296;if(state<limit)return(as.integer(state%%n))}};draws<-schedules<-list();for(member in 1:4){draws[[member]]<-vapply(seq_along(ids),function(i)ids[choose(length(ids))+1L],'');schedule<-setNames(vector('list',7),c('','L','R','LL','LR','RL','RR'));for(path in names(schedule)){order<-seq_len(p)-1L;if(p>1)for(j in seq(p-1L,1L)){k<-choose(j+1L);temp<-order[j+1L];order[j+1L]<-order[k+1L];order[k+1L]<-temp};schedule[[match(path,names(schedule))]]<-sort(order[seq_len(max(1L,floor(sqrt(p))))])};schedules[[member]]<-schedule};list(draws=draws,schedules=schedules)}\nread_sources<-function(src){read<-function(name)read.csv(file.path(src,name),check.names=FALSE,colClasses='character',na.strings=character(),fileEncoding='UTF-8-BOM');raw<-read('actual320-country-four-indicators-original-2020-2024.csv');country<-do.call(rbind,lapply(sort(unique(raw$countryISO3)),function(code)do.call(rbind,lapply(2020:2024,function(year){keys<-c('NY.GDP.PCAP.KD','NY.GDP.MKTP.KD.ZG','FP.CPI.TOTL.ZG','SP.DYN.LE00.IN');v<-vapply(keys,function(k)as.numeric(raw$originalValueToken[raw$countryISO3==code&raw$date==as.character(year)&raw$indicatorID==k]),0);data.frame(id=paste0(code,':',year),sourceRow=paste0(code,':',year),originalID=code,year=year,x0=v[1]/10000,x1=v[2],x2=v[3],y=v[4],weight=1,role=if(anyNA(v))'excluded'else if(year==2024)'outer-test'else'train')}))));raw<-read('actual3613-NLS-original52-fields-and-selection.csv');i<-seq_len(nrow(raw));x0<-suppressWarnings(as.numeric(raw$ed76));x1<-suppressWarnings(as.numeric(raw$age76));y<-suppressWarnings(as.numeric(raw$wage76))/100;person<-data.frame(id=paste0('person:',i),sourceRow=as.character(i),originalID=raw$id,x0=x0,x1=x1,y=y,weight=1,role=ifelse(is.na(x0)|is.na(x1)|is.na(y),'excluded',ifelse(i%%5==0,'outer-test','train')));raw<-read('actual3150-churn-original14-fields-and-selection.csv');i<-seq_len(nrow(raw));company<-data.frame(id=paste0('customer:',i),sourceRow=as.character(i),originalID='',x0=as.numeric(raw[['Call  Failure']]),x1=as.numeric(raw[['Subscription  Length']]),x2=as.numeric(raw[['Charge  Amount']]),y=raw$Churn,weight=1,role=ifelse(i%%5==0,'outer-test','train'));models<-list();for(index in 1:3){kind<-c('country','person','company')[index];d<-list(country,person,company)[[index]];task<-if(kind=='company')'classification'else'regression';s<-fixed_schedules(d$id[d$role=='train'],if(kind=='person')2L else 3L,20261102+7919*(index-1L));models[[kind]]<-list(records=d,task=task,classes=if(task=='classification')c('0','1')else character(),draws=s$draws,schedules=s$schedules,minLeaf=c(4L,50L,30L)[index])};models}\nrealdata<-function(models,kind,options=list()){if(is.null(options)||!is.list(options))stop('options object');m<-models[[kind]];d<-m$records;train<-d[d$role=='train',,drop=FALSE];test<-d[d$role=='outer-test',,drop=FALSE];method<-option(options,'method','forest');depth<-option(options,'maxDepth',2);count<-option(options,'memberCount',3);if(!method%in%c('bagging','forest','boost'))stop('known method');a<-list(rows=train,queries=test,task=m$task,classes=m$classes,maxDepth=depth,minLeaf=option(options,'minLeaf',m$minLeaf),minLeafWeight=0,minGain=0,missingRoute='best',learningRate=option(options,'learningRate','1/2'),stages=option(options,'stages',3));if(method=='boost')result<-boost(a)else{a$bootstrapDraws<-m$draws[seq_len(count)];a$nodeFeatures<-lapply(m$schedules[seq_len(count)],function(s)s[nchar(names(s))<depth]);result<-ensemble(a,method=='forest')};outer<-scored(result$predictions,normrows(test,m$task),m$task,m$classes);st<-stat(normrows(train,m$task),m$task,m$classes);constant<-list(prediction=st$pred,probabilities=st$p,vote=st$pred,prob=st$pred);baseline<-scored(lapply(test$id,function(id)c(list(id=id),constant)),normrows(test,m$task),m$task,m$classes);list(kind=kind,method=method,settings=a,train=train,test=test,result=result,outer=outer,baseline=baseline)}\nAPI<-\"variance\"\nINPUT<-list(B=4,marginalVariance=4,rho=\"1/2\")\n\nrun_fixed<-function(api,a,out,src){\n r<-if(api=='variance')variance(a)else if(api=='aggregate')aggregate(a)else if(api%in%c('bagging','forest'))ensemble(a,api=='forest')else if(api=='boost')boost(a)else realdata(read_sources(src),a$kind)\n dir.create(out,recursive=TRUE,showWarnings=FALSE);summary<-list();points<-list();add<-function(x,y,s){if(!is.null(y)&&!is.na(y))points[[length(points)+1L]]<<-data.frame(x=x,y=as.numeric(y),series=s)}\n if(api=='variance'){summary<-r[c('B','varianceOfMean')];add(r$B,r$varianceOfMean,'Specified finite-B variance');xl<-'Number of members B';yl<-'Variance, stipulated units squared';title<-'Declared covariance model, not fitted trees'\n }else if(api=='aggregate'){p<-r$predictions[[1]];summary<-list(selectedPrediction=p$prediction);classification<-identical(a$task,'classification');if(classification){summary<-c(summary,list(voteLabel=p$vote,probabilityLabel=p$prob,meanProbability1=p$probabilities[2]));add(1,p$probabilities[2],'Mean probability of class 1');add(2,p$votes[2],'Label-vote share of class 1');xl<-'Aggregation (1=probability, 2=vote)';yl<-'Probability or vote share'}else{for(i in seq_along(a$members))add(i,num(a$members[[i]]$predictions$value[1]),'Member prediction');add(3,p$prediction,'Weighted mean');xl<-'Member 1, member 2, aggregate 3';yl<-'Prediction, assumed units'};title<-'Votes and probabilities are distinct objects'\n }else if(api%in%c('bagging','forest')){summary<-list(queryPrediction=r$predictions[[1]]$prediction,OOB.scoreable=r$outOfBag$eligibleRows,OOB.meanLoss=r$outOfBag$meanLoss);for(i in seq_len(nrow(a$rows)))add(i,a$rows$y[i],'Observed training outcome');for(i in seq_along(r$outOfBag$rows))add(i,r$outOfBag$rows[[i]]$prediction,'OOB prediction, when defined');xl<-'Original training ID order';yl<-'Outcome, assumed units';title<-'Repeated draws and ID-level OOB membership'\n }else if(api=='boost'){summary<-list(initial=r$initial,finalMSE=r$losses[[length(r$losses)]]$MSE,stages=r$stages);for(v in r$losses)add(v$stage,v$MSE,'Training MSE');xl<-'Boosting stage (0=initial)';yl<-'Weighted MSE, outcome units squared';title<-'Training descent does not certify held-out gain'\n }else{summary<-list(outer.scoreable=r$outer$eligibleRows,outer.meanLoss=r$outer$meanLoss,baseline.meanLoss=r$baseline$meanLoss,OOB.scoreable=r$result$outOfBag$eligibleRows,OOB.meanLoss=r$result$outOfBag$meanLoss);for(i in seq_along(r$outer$rows)){p<-r$outer$rows[[i]];add(i,as.numeric(p$actual),'Observed outcome');add(i,if(a$kind=='company')p$probabilities[2]else p$prediction,if(a$kind=='company')'Forest probability of class 1'else'Forest prediction')};xl<-'Outer-test source order, not a time path';yl<-if(a$kind=='company')'Churn label / probability'else if(a$kind=='country')'Period life expectancy, years'else'Nominal 1976 USD per hour';title<-'Fixed forest; outer labels did not fit the trees'}\n display<-function(v)if(is.null(v)||is.na(v))'undefined'else sprintf('%.9f',as.numeric(v));write.csv(data.frame(metric=names(summary),value=vapply(summary,display,'')),file.path(out,'summary.csv'),row.names=FALSE);pp<-do.call(rbind,points);write.csv(pp,file.path(out,'plot-points.csv'),row.names=FALSE);dput(r,file.path(out,'full-result.Rtext'));svg(file.path(out,'plot.svg'),width=5.6,height=4.6,pointsize=14);par(mar=c(5.8,5.8,5.3,1.2),mgp=c(3.7,1,0));xr<-range(pp$x);yr<-range(pp$y);if(diff(xr)==0)xr<-xr+c(-.5,.5);if(diff(yr)==0)yr<-yr+c(-.5,.5);plot(xr,yr,type='n',xlab=xl,ylab=yl,cex.lab=.78,axes=FALSE);axis(1,at=pretty(xr,3));axis(2,at=pretty(yr,4),las=1,cex.axis=.82);box();grid(col='#dddddd');cols<-c('#355c72','#a55336','#507956','#78568b');ss<-unique(pp$series);for(i in seq_along(ss)){v<-pp[pp$series==ss[i],];points(v$x,v$y,pch=16,cex=if(nrow(v)>100).35 else .85,col=adjustcolor(cols[i],if(nrow(v)>100).5 else 1))};legend('topleft',legend=ss,col=cols[seq_along(ss)],lty=0,pch=16,cex=.65,bty='n',inset=c(0,-.32),xpd=NA);mtext(title,side=3,line=3.9,cex=.6);dev.off();cat(paste(names(summary),vapply(summary,display,''),sep='=',collapse=', '),'\\n')\n}\nargs<-commandArgs(trailingOnly=TRUE)\ntryCatch(run_fixed(API,INPUT,if(length(args))args[1]else'fixed-results',if(length(args)>1)args[2]else'ml09-sources'),error=function(e){cat('Rejected declared input: ',conditionMessage(e),'\\n',file=stderr());quit(status=2)})\n",
        "code": "# ML09 base-R reproduction from native original-field CSVs.\n# Rscript ml09-public-analysis.R ml09-sources results-r\n# Separately written vectorized direct-centered squared/Gini losses.\n# No Python/JS/model-contract/stored-answer/derived-result reader or package.\n# Numeric arithmetic is binary64:1e-12 relative tie tolerance stabilizes exact\n# source ties,but does not certify tiny margins/underflow like Fraction JS/Python.\n# Data-frame rows use x0,x1,...,y,weight; original IDs remain attached to draws.\noptions(stringsAsFactors=FALSE,digits=17)\nnum<-function(v){if(is.null(v)||length(v)!=1||is.na(v))stop('numeric parameter required, not explicit NULL');p<-strsplit(as.character(v),'/',fixed=TRUE)[[1]];z<-if(length(p)==2)as.numeric(p[1])/as.numeric(p[2])else as.numeric(v);if(!is.finite(z))stop('finite numeric parameter');z}\noption<-function(a,k,default){if(k%in%names(a))a[[k]]else default}\nnormrows<-function(d,task){if(!'weight'%in%names(d))d$weight<-1;if(!'id'%in%names(d))d$id<-as.character(seq_len(nrow(d))-1);d$weight<-as.numeric(d$weight);if(anyNA(d$weight)||any(d$weight<0))stop('nonnegative weights');if(task=='regression')d$y<-as.numeric(d$y)else d$y<-as.character(d$y);d}\nstat<-function(d,task,classes){W<-sum(d$weight);mu<-if(task=='regression'&&W)sum(d$weight*d$y)/W else NA_real_;p<-if(task=='classification'&&W)vapply(classes,function(c)sum(d$weight[d$y==c])/W,0)else numeric();risk<-if(task=='regression'&&W)sum(d$weight*(d$y-mu)^2)else W*sum(p*(1-p));list(n=nrow(d),w=W,mu=mu,p=unname(p),risk=risk,pred=if(task=='regression')mu else if(W)classes[which.max(p)]else NA_character_)}\nfit<-function(d,a,task,classes,schedule=NULL){d<-d[d$weight>0&!is.na(d$y),,drop=FALSE];if(!nrow(d))stop('positive observed training');W<-sum(d$weight);depth<-option(a,'maxDepth',2);minimum<-option(a,'minLeaf',1);minmass<-num(option(a,'minLeafWeight',0));mingain<-num(option(a,'minGain',0));route<-option(a,'missingRoute','best');features<-grep('^x[0-9]+$',names(d),value=TRUE)\n build<-function(rr,level,path){st<-stat(rr,task,classes);node<-list(rows=rr,st=st,split=NULL,left=NULL,right=NULL,path=path);if(level==depth)return(node);best<-NULL;allowed<-if(is.null(schedule))seq_along(features)-1L else schedule[[match(path,names(schedule))]]\n  for(j in seq_along(features)-1L){if(!j%in%allowed)next;v<-rr[[features[j+1L]]];values<-sort(unique(v[!is.na(v)]));candidates<-list()\n   if(length(values)>1)for(k in seq_len(length(values)-1L)){threshold<-(values[k]+values[k+1L])/2;missing<-is.na(v);left<-!missing&v<=threshold;right<-!missing&v>threshold;directions<-if(route!='best')route else if(any(missing))c('left','right')else if(sum(left)>=sum(right))'left'else'right';for(direction in directions)candidates[[length(candidates)+1L]]<-list(kind='threshold',threshold=threshold,missingRoute=direction,left=if(direction=='left')left|missing else left,right=if(direction=='right')right|missing else right)}\n   if(anyNA(v)&&any(!is.na(v)))candidates[[length(candidates)+1L]]<-list(kind='missing-only',threshold=NA_real_,missingRoute='left',left=is.na(v),right=!is.na(v))\n   for(candidate in candidates){l<-rr[candidate$left,,drop=FALSE];r<-rr[candidate$right,,drop=FALSE];ls<-stat(l,task,classes);rs<-stat(r,task,classes);if(min(ls$n,rs$n)<minimum||min(ls$w,rs$w)<minmass||min(ls$w,rs$w)<=0)next;gain<-(st$risk-ls$risk-rs$risk)/W;tol<-1e-12*max(1,abs(gain),if(is.null(best))0 else abs(best$gain));if(is.null(best)||gain>best$gain+tol)best<-c(candidate,list(feature=j,gain=gain,l=l,r=r))}\n  }\n  if(!is.null(best)&&best$gain>max(mingain,1e-12)){node$split<-best;node$left<-build(best$l,level+1L,paste0(path,'L'));node$right<-build(best$r,level+1L,paste0(path,'R'))};node\n };build(d,0L,'')\n}\npredict_one<-function(tree,row){n<-tree;while(!is.null(n$split)){s<-n$split;v<-as.numeric(row[[paste0('x',s$feature)]]);left<-if(s$kind=='missing-only')is.na(v)else if(is.na(v))s$missingRoute=='left'else v<=s$threshold;n<-if(left)n$left else n$right};list(prediction=n$st$pred,probabilities=n$st$p)}\ncombine<-function(pp,w,task,classes,mode='probabilities'){W<-sum(w);if(!length(pp)||!W)return(list(prediction=if(task=='regression')NA_real_ else NA_character_,probabilities=numeric(),vote=NA_character_,prob=NA_character_));if(task=='regression')return(list(prediction=sum(vapply(pp,function(p)p$prediction,0)*w)/W,probabilities=numeric(),vote=NA_character_,prob=NA_character_));votes<-vapply(classes,function(c)sum(w[vapply(pp,function(p)p$prediction==c,FALSE)])/W,0);probs<-vapply(seq_along(classes),function(j)sum(vapply(pp,function(p)p$probabilities[j],0)*w)/W,0);vote<-classes[which.max(votes)];prob<-classes[which.max(probs)];list(prediction=if(mode=='votes')vote else prob,probabilities=unname(probs),vote=vote,prob=prob,votes=unname(votes))}\nvariance<-function(a){B<-num(a$B);v<-num(a$marginalVariance);rho<-num(option(a,'rho',0));if(B<1||B!=floor(B)||v<0)stop('integer B/nonnegative variance');if(B>1&&v>0&&(rho< -1/(B-1)||rho>1))stop('PSD correlation');list(B=B,marginalVariance=v,correlationApplicable=B>1&&v>0,varianceOfMean=if(B==1)v else v*(1+(B-1)*rho)/B)}\naggregate<-function(a){task<-option(a,'task','regression');classes<-option(a,'classes',character());w<-vapply(option(a,'memberWeights',as.list(rep(1,length(a$members)))),num,0);if(any(w<0)||sum(w)<=0)stop('positive member mass');ids<-a$members[[1]]$predictions$id;pp<-lapply(ids,function(id){members<-lapply(a$members,function(m){r<-m$predictions[match(id,m$predictions$id),,drop=FALSE];if(task=='regression')list(prediction=num(r$value),probabilities=numeric())else list(prediction=as.character(r$label),probabilities=as.numeric(r[paste0('p',seq_along(classes)-1L)]))});c(list(id=id),combine(members,w,task,classes,option(a,'aggregation','probabilities')))});list(task=task,classes=classes,predictions=pp)}\nscored<-function(preds,d,task,classes){W<-loss<-absolute<-errors<-voteerrors<-0;count<-0L;out<-lapply(seq_len(nrow(d)),function(i){r<-d[i,,drop=FALSE];p<-preds[[i]];ok<-!is.na(p$prediction)&&!is.na(r$y)&&r$weight>0;value<-NA_real_;if(ok){count<<-count+1L;W<<-W+r$weight;if(task=='regression'){e<-r$y-p$prediction;value<-e*e;absolute<<-absolute+r$weight*abs(e)}else{value<-sum((p$probabilities-as.numeric(classes==r$y))^2);errors<<-errors+r$weight*(p$prediction!=r$y);voteerrors<<-voteerrors+r$weight*(p$vote!=r$y)};loss<<-loss+r$weight*value};c(p,list(actual=r$y,weight=r$weight,scoreEligible=ok,loss=value))});list(rows=out,eligibleRows=count,weight=W,totalLoss=loss,meanLoss=if(W)loss/W else NA_real_,MAE=if(W&&task=='regression')absolute/W else NA_real_,errorRate=if(W&&task=='classification')errors/W else NA_real_,labelVoteErrorRate=if(W&&task=='classification')voteerrors/W else NA_real_)}\nensemble<-function(a,forest=FALSE){task<-option(a,'task','regression');classes<-option(a,'classes',character());d<-normrows(a$rows,task);w<-vapply(option(a,'memberWeights',as.list(rep(1,length(a$bootstrapDraws)))),num,0);if(any(w<0)||sum(w)<=0)stop('positive member mass');members<-lapply(seq_along(a$bootstrapDraws),function(i){draw<-a$bootstrapDraws[[i]];indices<-match(draw,d$id);if(anyNA(indices))stop('unknown draw source');tree<-fit(d[indices,,drop=FALSE],a,task,classes,if(forest)a$nodeFeatures[[i]]else NULL);list(tree=tree,draw=draw,inbag=unique(draw),weight=w[i])});queries<-a$queries;preds<-lapply(seq_len(nrow(queries)),function(i)c(list(id=queries$id[i]),combine(lapply(members,function(m)predict_one(m$tree,queries[i,,drop=FALSE])),w,task,classes,option(a,'aggregation','probabilities'))));oob<-lapply(seq_len(nrow(d)),function(i){app<-which(!vapply(members,function(m)d$id[i]%in%m$inbag,FALSE));pp<-combine(lapply(app,function(j)predict_one(members[[j]]$tree,d[i,,drop=FALSE])),w[app],task,classes,option(a,'aggregation','probabilities'));c(list(id=d$id[i],applicable=app-1L,positiveMembers=sum(w[app]>0)),pp)});list(task=task,classes=classes,members=members,predictions=preds,outOfBag=scored(oob,d,task,classes))}\nboost<-function(a){if(option(a,'task','regression')!='regression')stop('regression boosting only');d<-normrows(a$rows,'regression');eligible<-d$weight>0&!is.na(d$y);W<-sum(d$weight[eligible]);if(!W)stop('positive eligible training');eta<-num(option(a,'learningRate','1/2'));stages<-option(a,'stages',3);if(is.null(stages)||stages!=floor(stages)||stages<0||stages>8||eta<0||eta>1)stop('supported rate/stages');initial<-if('initial'%in%names(a))num(a$initial)else sum(d$weight[eligible]*d$y[eligible])/W;train<-matrix(initial,nrow(d),stages+1L);query<-matrix(initial,nrow(a$queries),stages+1L);losses<-fits<-list();for(stage in 0:stages){sse<-sum(d$weight[eligible]*(d$y[eligible]-train[eligible,stage+1L])^2);losses[[stage+1L]]<-list(stage=stage,rawWeightedSSE=sse,MSE=sse/W,meanHalfSquaredLoss=sse/(2*W));if(stage==stages)break;residual<-d;residual$y<-d$y-train[,stage+1L];tree<-fit(residual,a,'regression',character());h<-vapply(seq_len(nrow(d)),function(i)predict_one(tree,d[i,,drop=FALSE])$prediction,0);qh<-vapply(seq_len(nrow(a$queries)),function(i)predict_one(tree,a$queries[i,,drop=FALSE])$prediction,0);stageRows<-lapply(seq_len(nrow(d)),function(i)list(id=d$id[i],before=train[i,stage+1L],residual=residual$y[i],negativeCoordinateDerivative=d$weight[i]*residual$y[i]/W,fit=h[i],addition=eta*h[i],after=train[i,stage+1L]+eta*h[i]));train[,stage+2L]<-train[,stage+1L]+eta*h;query[,stage+2L]<-query[,stage+1L]+eta*qh;norm<-sum(d$weight[eligible]*h[eligible]^2);fits[[stage+1L]]<-list(stage=stage+1L,tree=tree,rows=stageRows,queryFits=qh,norm=norm,predictedSSEDecrease=eta*(2-eta)*norm)};list(task='regression',initial=initial,learningRate=eta,stages=stages,training=train,queries=query,fits=fits,losses=losses,predictions=lapply(seq_len(nrow(a$queries)),function(i)list(id=a$queries$id[i],prediction=query[i,stages+1L],probabilities=numeric(),vote=NA_character_,prob=NA_character_)))}\nfixed_schedules<-function(ids,p,seed){state<-seed;choose<-function(n){limit<-floor(4294967296/n)*n;repeat{state<<-(1664525*state+1013904223)%%4294967296;if(state<limit)return(as.integer(state%%n))}};draws<-schedules<-list();for(member in 1:4){draws[[member]]<-vapply(seq_along(ids),function(i)ids[choose(length(ids))+1L],'');schedule<-setNames(vector('list',7),c('','L','R','LL','LR','RL','RR'));for(path in names(schedule)){order<-seq_len(p)-1L;if(p>1)for(j in seq(p-1L,1L)){k<-choose(j+1L);temp<-order[j+1L];order[j+1L]<-order[k+1L];order[k+1L]<-temp};schedule[[match(path,names(schedule))]]<-sort(order[seq_len(max(1L,floor(sqrt(p))))])};schedules[[member]]<-schedule};list(draws=draws,schedules=schedules)}\nread_sources<-function(src){read<-function(name)read.csv(file.path(src,name),check.names=FALSE,colClasses='character',na.strings=character(),fileEncoding='UTF-8-BOM');raw<-read('actual320-country-four-indicators-original-2020-2024.csv');country<-do.call(rbind,lapply(sort(unique(raw$countryISO3)),function(code)do.call(rbind,lapply(2020:2024,function(year){keys<-c('NY.GDP.PCAP.KD','NY.GDP.MKTP.KD.ZG','FP.CPI.TOTL.ZG','SP.DYN.LE00.IN');v<-vapply(keys,function(k)as.numeric(raw$originalValueToken[raw$countryISO3==code&raw$date==as.character(year)&raw$indicatorID==k]),0);data.frame(id=paste0(code,':',year),sourceRow=paste0(code,':',year),originalID=code,year=year,x0=v[1]/10000,x1=v[2],x2=v[3],y=v[4],weight=1,role=if(anyNA(v))'excluded'else if(year==2024)'outer-test'else'train')}))));raw<-read('actual3613-NLS-original52-fields-and-selection.csv');i<-seq_len(nrow(raw));x0<-suppressWarnings(as.numeric(raw$ed76));x1<-suppressWarnings(as.numeric(raw$age76));y<-suppressWarnings(as.numeric(raw$wage76))/100;person<-data.frame(id=paste0('person:',i),sourceRow=as.character(i),originalID=raw$id,x0=x0,x1=x1,y=y,weight=1,role=ifelse(is.na(x0)|is.na(x1)|is.na(y),'excluded',ifelse(i%%5==0,'outer-test','train')));raw<-read('actual3150-churn-original14-fields-and-selection.csv');i<-seq_len(nrow(raw));company<-data.frame(id=paste0('customer:',i),sourceRow=as.character(i),originalID='',x0=as.numeric(raw[['Call  Failure']]),x1=as.numeric(raw[['Subscription  Length']]),x2=as.numeric(raw[['Charge  Amount']]),y=raw$Churn,weight=1,role=ifelse(i%%5==0,'outer-test','train'));models<-list();for(index in 1:3){kind<-c('country','person','company')[index];d<-list(country,person,company)[[index]];task<-if(kind=='company')'classification'else'regression';s<-fixed_schedules(d$id[d$role=='train'],if(kind=='person')2L else 3L,20261102+7919*(index-1L));models[[kind]]<-list(records=d,task=task,classes=if(task=='classification')c('0','1')else character(),draws=s$draws,schedules=s$schedules,minLeaf=c(4L,50L,30L)[index])};models}\nrealdata<-function(models,kind,options=list()){if(is.null(options)||!is.list(options))stop('options object');m<-models[[kind]];d<-m$records;train<-d[d$role=='train',,drop=FALSE];test<-d[d$role=='outer-test',,drop=FALSE];method<-option(options,'method','forest');depth<-option(options,'maxDepth',2);count<-option(options,'memberCount',3);if(!method%in%c('bagging','forest','boost'))stop('known method');a<-list(rows=train,queries=test,task=m$task,classes=m$classes,maxDepth=depth,minLeaf=option(options,'minLeaf',m$minLeaf),minLeafWeight=0,minGain=0,missingRoute='best',learningRate=option(options,'learningRate','1/2'),stages=option(options,'stages',3));if(method=='boost')result<-boost(a)else{a$bootstrapDraws<-m$draws[seq_len(count)];a$nodeFeatures<-lapply(m$schedules[seq_len(count)],function(s)s[nchar(names(s))<depth]);result<-ensemble(a,method=='forest')};outer<-scored(result$predictions,normrows(test,m$task),m$task,m$classes);st<-stat(normrows(train,m$task),m$task,m$classes);constant<-list(prediction=st$pred,probabilities=st$p,vote=st$pred,prob=st$pred);baseline<-scored(lapply(test$id,function(id)c(list(id=id),constant)),normrows(test,m$task),m$task,m$classes);list(kind=kind,method=method,settings=a,train=train,test=test,result=result,outer=outer,baseline=baseline)}\nAPI<-\"variance\"\nINPUT<-list(B=4,marginalVariance=4,rho=\"1/2\")\n\nrun_fixed<-function(api,a,out,src){\n r<-if(api=='variance')variance(a)else if(api=='aggregate')aggregate(a)else if(api%in%c('bagging','forest'))ensemble(a,api=='forest')else if(api=='boost')boost(a)else realdata(read_sources(src),a$kind)\n dir.create(out,recursive=TRUE,showWarnings=FALSE);summary<-list();points<-list();add<-function(x,y,s){if(!is.null(y)&&!is.na(y))points[[length(points)+1L]]<<-data.frame(x=x,y=as.numeric(y),series=s)}\n if(api=='variance'){summary<-r[c('B','varianceOfMean')];add(r$B,r$varianceOfMean,'Specified finite-B variance');xl<-'Number of members B';yl<-'Variance, stipulated units squared';title<-'Declared covariance model, not fitted trees'\n }else if(api=='aggregate'){p<-r$predictions[[1]];summary<-list(selectedPrediction=p$prediction);classification<-identical(a$task,'classification');if(classification){summary<-c(summary,list(voteLabel=p$vote,probabilityLabel=p$prob,meanProbability1=p$probabilities[2]));add(1,p$probabilities[2],'Mean probability of class 1');add(2,p$votes[2],'Label-vote share of class 1');xl<-'Aggregation (1=probability, 2=vote)';yl<-'Probability or vote share'}else{for(i in seq_along(a$members))add(i,num(a$members[[i]]$predictions$value[1]),'Member prediction');add(3,p$prediction,'Weighted mean');xl<-'Member 1, member 2, aggregate 3';yl<-'Prediction, assumed units'};title<-'Votes and probabilities are distinct objects'\n }else if(api%in%c('bagging','forest')){summary<-list(queryPrediction=r$predictions[[1]]$prediction,OOB.scoreable=r$outOfBag$eligibleRows,OOB.meanLoss=r$outOfBag$meanLoss);for(i in seq_len(nrow(a$rows)))add(i,a$rows$y[i],'Observed training outcome');for(i in seq_along(r$outOfBag$rows))add(i,r$outOfBag$rows[[i]]$prediction,'OOB prediction, when defined');xl<-'Original training ID order';yl<-'Outcome, assumed units';title<-'Repeated draws and ID-level OOB membership'\n }else if(api=='boost'){summary<-list(initial=r$initial,finalMSE=r$losses[[length(r$losses)]]$MSE,stages=r$stages);for(v in r$losses)add(v$stage,v$MSE,'Training MSE');xl<-'Boosting stage (0=initial)';yl<-'Weighted MSE, outcome units squared';title<-'Training descent does not certify held-out gain'\n }else{summary<-list(outer.scoreable=r$outer$eligibleRows,outer.meanLoss=r$outer$meanLoss,baseline.meanLoss=r$baseline$meanLoss,OOB.scoreable=r$result$outOfBag$eligibleRows,OOB.meanLoss=r$result$outOfBag$meanLoss);for(i in seq_along(r$outer$rows)){p<-r$outer$rows[[i]];add(i,as.numeric(p$actual),'Observed outcome');add(i,if(a$kind=='company')p$probabilities[2]else p$prediction,if(a$kind=='company')'Forest probability of class 1'else'Forest prediction')};xl<-'Outer-test source order, not a time path';yl<-if(a$kind=='company')'Churn label / probability'else if(a$kind=='country')'Period life expectancy, years'else'Nominal 1976 USD per hour';title<-'Fixed forest; outer labels did not fit the trees'}\n display<-function(v)if(is.null(v)||is.na(v))'undefined'else sprintf('%.9f',as.numeric(v));write.csv(data.frame(metric=names(summary),value=vapply(summary,display,'')),file.path(out,'summary.csv'),row.names=FALSE);pp<-do.call(rbind,points);write.csv(pp,file.path(out,'plot-points.csv'),row.names=FALSE);dput(r,file.path(out,'full-result.Rtext'));svg(file.path(out,'plot.svg'),width=5.6,height=4.6,pointsize=14);par(mar=c(5.8,5.8,5.3,1.2),mgp=c(3.7,1,0));xr<-range(pp$x);yr<-range(pp$y);if(diff(xr)==0)xr<-xr+c(-.5,.5);if(diff(yr)==0)yr<-yr+c(-.5,.5);plot(xr,yr,type='n',xlab=xl,ylab=yl,cex.lab=.78,axes=FALSE);axis(1,at=pretty(xr,3));axis(2,at=pretty(yr,4),las=1,cex.axis=.82);box();grid(col='#dddddd');cols<-c('#355c72','#a55336','#507956','#78568b');ss<-unique(pp$series);for(i in seq_along(ss)){v<-pp[pp$series==ss[i],];points(v$x,v$y,pch=16,cex=if(nrow(v)>100).35 else .85,col=adjustcolor(cols[i],if(nrow(v)>100).5 else 1))};legend('topleft',legend=ss,col=cols[seq_along(ss)],lty=0,pch=16,cex=.65,bty='n',inset=c(0,-.32),xpd=NA);mtext(title,side=3,line=3.9,cex=.6);dev.off();cat(paste(names(summary),vapply(summary,display,''),sep='=',collapse=', '),'\\n')\n}\nargs<-commandArgs(trailingOnly=TRUE)\ntryCatch(run_fixed(API,INPUT,if(length(args))args[1]else'fixed-results',if(length(args)>1)args[2]else'ml09-sources'),error=function(e){cat('Rejected declared input: ',conditionMessage(e),'\\n',file=stderr());quit(status=2)})\n",
        "inputFiles": [],
        "input": {
          "B": 4,
          "marginalVariance": 4,
          "rho": "1/2"
        },
        "returnCode": 0,
        "expectedFailure": false,
        "stdout": "B=4.000000000, varianceOfMean=2.500000000 \n",
        "stderr": "During startup - Warning messages:\n1: Setting LC_COLLATE=C.UTF-8 failed \n2: Setting LC_CTYPE=C.UTF-8 failed \n3: Setting LC_MONETARY=C.UTF-8 failed \n4: Setting LC_TIME=C.UTF-8 failed \n",
        "summary": {
          "B": "4.000000000",
          "varianceOfMean": "2.500000000"
        },
        "plotPoints": [
          {
            "x": "4",
            "y": "2.5",
            "series": "Specified finite-B variance"
          }
        ],
        "plotFile": "ml09-fixed-results/variance-correlated-r/plot.svg",
        "plotSHA256": "09c919625020c8e160acf78bf6d28703452931cd8df00ffb92a20072778b1a85",
        "files": [
          {
            "file": "ml09-fixed-results/variance-correlated-r/full-result.Rtext",
            "sha256": "8b9173d4896f7591014006e7a3916adb341950e7a5615a6472fa662472a11065"
          },
          {
            "file": "ml09-fixed-results/variance-correlated-r/plot-points.csv",
            "sha256": "f052fc7fc0604b19eb0a1c44c6dbe3e1affbaae45849bcf21369586c91b60275"
          },
          {
            "file": "ml09-fixed-results/variance-correlated-r/plot.svg",
            "sha256": "09c919625020c8e160acf78bf6d28703452931cd8df00ffb92a20072778b1a85"
          },
          {
            "file": "ml09-fixed-results/variance-correlated-r/summary.csv",
            "sha256": "5f9e2d88e83cc4dd1c142e2325cffe1efad045cd4b7c6e2cfd7eb7f8c4d32335"
          }
        ],
        "scope": "Actually executed self-contained fixed example; current web controls execute separately. Python Fraction and finite-precision base R. Author gate, not independent peer."
      },
      "independent": {
        "api": "variance",
        "variant": "independent",
        "language": "r",
        "codeFile": "ml09-code/variance-independent.R",
        "codeSHA256": "aa6b453103e97e38f0f5699c4d31ba0c2565b5a23a5e571caf50c56c8a33957e",
        "codeText": "# ML09 base-R reproduction from native original-field CSVs.\n# Rscript ml09-public-analysis.R ml09-sources results-r\n# Separately written vectorized direct-centered squared/Gini losses.\n# No Python/JS/model-contract/stored-answer/derived-result reader or package.\n# Numeric arithmetic is binary64:1e-12 relative tie tolerance stabilizes exact\n# source ties,but does not certify tiny margins/underflow like Fraction JS/Python.\n# Data-frame rows use x0,x1,...,y,weight; original IDs remain attached to draws.\noptions(stringsAsFactors=FALSE,digits=17)\nnum<-function(v){if(is.null(v)||length(v)!=1||is.na(v))stop('numeric parameter required, not explicit NULL');p<-strsplit(as.character(v),'/',fixed=TRUE)[[1]];z<-if(length(p)==2)as.numeric(p[1])/as.numeric(p[2])else as.numeric(v);if(!is.finite(z))stop('finite numeric parameter');z}\noption<-function(a,k,default){if(k%in%names(a))a[[k]]else default}\nnormrows<-function(d,task){if(!'weight'%in%names(d))d$weight<-1;if(!'id'%in%names(d))d$id<-as.character(seq_len(nrow(d))-1);d$weight<-as.numeric(d$weight);if(anyNA(d$weight)||any(d$weight<0))stop('nonnegative weights');if(task=='regression')d$y<-as.numeric(d$y)else d$y<-as.character(d$y);d}\nstat<-function(d,task,classes){W<-sum(d$weight);mu<-if(task=='regression'&&W)sum(d$weight*d$y)/W else NA_real_;p<-if(task=='classification'&&W)vapply(classes,function(c)sum(d$weight[d$y==c])/W,0)else numeric();risk<-if(task=='regression'&&W)sum(d$weight*(d$y-mu)^2)else W*sum(p*(1-p));list(n=nrow(d),w=W,mu=mu,p=unname(p),risk=risk,pred=if(task=='regression')mu else if(W)classes[which.max(p)]else NA_character_)}\nfit<-function(d,a,task,classes,schedule=NULL){d<-d[d$weight>0&!is.na(d$y),,drop=FALSE];if(!nrow(d))stop('positive observed training');W<-sum(d$weight);depth<-option(a,'maxDepth',2);minimum<-option(a,'minLeaf',1);minmass<-num(option(a,'minLeafWeight',0));mingain<-num(option(a,'minGain',0));route<-option(a,'missingRoute','best');features<-grep('^x[0-9]+$',names(d),value=TRUE)\n build<-function(rr,level,path){st<-stat(rr,task,classes);node<-list(rows=rr,st=st,split=NULL,left=NULL,right=NULL,path=path);if(level==depth)return(node);best<-NULL;allowed<-if(is.null(schedule))seq_along(features)-1L else schedule[[match(path,names(schedule))]]\n  for(j in seq_along(features)-1L){if(!j%in%allowed)next;v<-rr[[features[j+1L]]];values<-sort(unique(v[!is.na(v)]));candidates<-list()\n   if(length(values)>1)for(k in seq_len(length(values)-1L)){threshold<-(values[k]+values[k+1L])/2;missing<-is.na(v);left<-!missing&v<=threshold;right<-!missing&v>threshold;directions<-if(route!='best')route else if(any(missing))c('left','right')else if(sum(left)>=sum(right))'left'else'right';for(direction in directions)candidates[[length(candidates)+1L]]<-list(kind='threshold',threshold=threshold,missingRoute=direction,left=if(direction=='left')left|missing else left,right=if(direction=='right')right|missing else right)}\n   if(anyNA(v)&&any(!is.na(v)))candidates[[length(candidates)+1L]]<-list(kind='missing-only',threshold=NA_real_,missingRoute='left',left=is.na(v),right=!is.na(v))\n   for(candidate in candidates){l<-rr[candidate$left,,drop=FALSE];r<-rr[candidate$right,,drop=FALSE];ls<-stat(l,task,classes);rs<-stat(r,task,classes);if(min(ls$n,rs$n)<minimum||min(ls$w,rs$w)<minmass||min(ls$w,rs$w)<=0)next;gain<-(st$risk-ls$risk-rs$risk)/W;tol<-1e-12*max(1,abs(gain),if(is.null(best))0 else abs(best$gain));if(is.null(best)||gain>best$gain+tol)best<-c(candidate,list(feature=j,gain=gain,l=l,r=r))}\n  }\n  if(!is.null(best)&&best$gain>max(mingain,1e-12)){node$split<-best;node$left<-build(best$l,level+1L,paste0(path,'L'));node$right<-build(best$r,level+1L,paste0(path,'R'))};node\n };build(d,0L,'')\n}\npredict_one<-function(tree,row){n<-tree;while(!is.null(n$split)){s<-n$split;v<-as.numeric(row[[paste0('x',s$feature)]]);left<-if(s$kind=='missing-only')is.na(v)else if(is.na(v))s$missingRoute=='left'else v<=s$threshold;n<-if(left)n$left else n$right};list(prediction=n$st$pred,probabilities=n$st$p)}\ncombine<-function(pp,w,task,classes,mode='probabilities'){W<-sum(w);if(!length(pp)||!W)return(list(prediction=if(task=='regression')NA_real_ else NA_character_,probabilities=numeric(),vote=NA_character_,prob=NA_character_));if(task=='regression')return(list(prediction=sum(vapply(pp,function(p)p$prediction,0)*w)/W,probabilities=numeric(),vote=NA_character_,prob=NA_character_));votes<-vapply(classes,function(c)sum(w[vapply(pp,function(p)p$prediction==c,FALSE)])/W,0);probs<-vapply(seq_along(classes),function(j)sum(vapply(pp,function(p)p$probabilities[j],0)*w)/W,0);vote<-classes[which.max(votes)];prob<-classes[which.max(probs)];list(prediction=if(mode=='votes')vote else prob,probabilities=unname(probs),vote=vote,prob=prob,votes=unname(votes))}\nvariance<-function(a){B<-num(a$B);v<-num(a$marginalVariance);rho<-num(option(a,'rho',0));if(B<1||B!=floor(B)||v<0)stop('integer B/nonnegative variance');if(B>1&&v>0&&(rho< -1/(B-1)||rho>1))stop('PSD correlation');list(B=B,marginalVariance=v,correlationApplicable=B>1&&v>0,varianceOfMean=if(B==1)v else v*(1+(B-1)*rho)/B)}\naggregate<-function(a){task<-option(a,'task','regression');classes<-option(a,'classes',character());w<-vapply(option(a,'memberWeights',as.list(rep(1,length(a$members)))),num,0);if(any(w<0)||sum(w)<=0)stop('positive member mass');ids<-a$members[[1]]$predictions$id;pp<-lapply(ids,function(id){members<-lapply(a$members,function(m){r<-m$predictions[match(id,m$predictions$id),,drop=FALSE];if(task=='regression')list(prediction=num(r$value),probabilities=numeric())else list(prediction=as.character(r$label),probabilities=as.numeric(r[paste0('p',seq_along(classes)-1L)]))});c(list(id=id),combine(members,w,task,classes,option(a,'aggregation','probabilities')))});list(task=task,classes=classes,predictions=pp)}\nscored<-function(preds,d,task,classes){W<-loss<-absolute<-errors<-voteerrors<-0;count<-0L;out<-lapply(seq_len(nrow(d)),function(i){r<-d[i,,drop=FALSE];p<-preds[[i]];ok<-!is.na(p$prediction)&&!is.na(r$y)&&r$weight>0;value<-NA_real_;if(ok){count<<-count+1L;W<<-W+r$weight;if(task=='regression'){e<-r$y-p$prediction;value<-e*e;absolute<<-absolute+r$weight*abs(e)}else{value<-sum((p$probabilities-as.numeric(classes==r$y))^2);errors<<-errors+r$weight*(p$prediction!=r$y);voteerrors<<-voteerrors+r$weight*(p$vote!=r$y)};loss<<-loss+r$weight*value};c(p,list(actual=r$y,weight=r$weight,scoreEligible=ok,loss=value))});list(rows=out,eligibleRows=count,weight=W,totalLoss=loss,meanLoss=if(W)loss/W else NA_real_,MAE=if(W&&task=='regression')absolute/W else NA_real_,errorRate=if(W&&task=='classification')errors/W else NA_real_,labelVoteErrorRate=if(W&&task=='classification')voteerrors/W else NA_real_)}\nensemble<-function(a,forest=FALSE){task<-option(a,'task','regression');classes<-option(a,'classes',character());d<-normrows(a$rows,task);w<-vapply(option(a,'memberWeights',as.list(rep(1,length(a$bootstrapDraws)))),num,0);if(any(w<0)||sum(w)<=0)stop('positive member mass');members<-lapply(seq_along(a$bootstrapDraws),function(i){draw<-a$bootstrapDraws[[i]];indices<-match(draw,d$id);if(anyNA(indices))stop('unknown draw source');tree<-fit(d[indices,,drop=FALSE],a,task,classes,if(forest)a$nodeFeatures[[i]]else NULL);list(tree=tree,draw=draw,inbag=unique(draw),weight=w[i])});queries<-a$queries;preds<-lapply(seq_len(nrow(queries)),function(i)c(list(id=queries$id[i]),combine(lapply(members,function(m)predict_one(m$tree,queries[i,,drop=FALSE])),w,task,classes,option(a,'aggregation','probabilities'))));oob<-lapply(seq_len(nrow(d)),function(i){app<-which(!vapply(members,function(m)d$id[i]%in%m$inbag,FALSE));pp<-combine(lapply(app,function(j)predict_one(members[[j]]$tree,d[i,,drop=FALSE])),w[app],task,classes,option(a,'aggregation','probabilities'));c(list(id=d$id[i],applicable=app-1L,positiveMembers=sum(w[app]>0)),pp)});list(task=task,classes=classes,members=members,predictions=preds,outOfBag=scored(oob,d,task,classes))}\nboost<-function(a){if(option(a,'task','regression')!='regression')stop('regression boosting only');d<-normrows(a$rows,'regression');eligible<-d$weight>0&!is.na(d$y);W<-sum(d$weight[eligible]);if(!W)stop('positive eligible training');eta<-num(option(a,'learningRate','1/2'));stages<-option(a,'stages',3);if(is.null(stages)||stages!=floor(stages)||stages<0||stages>8||eta<0||eta>1)stop('supported rate/stages');initial<-if('initial'%in%names(a))num(a$initial)else sum(d$weight[eligible]*d$y[eligible])/W;train<-matrix(initial,nrow(d),stages+1L);query<-matrix(initial,nrow(a$queries),stages+1L);losses<-fits<-list();for(stage in 0:stages){sse<-sum(d$weight[eligible]*(d$y[eligible]-train[eligible,stage+1L])^2);losses[[stage+1L]]<-list(stage=stage,rawWeightedSSE=sse,MSE=sse/W,meanHalfSquaredLoss=sse/(2*W));if(stage==stages)break;residual<-d;residual$y<-d$y-train[,stage+1L];tree<-fit(residual,a,'regression',character());h<-vapply(seq_len(nrow(d)),function(i)predict_one(tree,d[i,,drop=FALSE])$prediction,0);qh<-vapply(seq_len(nrow(a$queries)),function(i)predict_one(tree,a$queries[i,,drop=FALSE])$prediction,0);stageRows<-lapply(seq_len(nrow(d)),function(i)list(id=d$id[i],before=train[i,stage+1L],residual=residual$y[i],negativeCoordinateDerivative=d$weight[i]*residual$y[i]/W,fit=h[i],addition=eta*h[i],after=train[i,stage+1L]+eta*h[i]));train[,stage+2L]<-train[,stage+1L]+eta*h;query[,stage+2L]<-query[,stage+1L]+eta*qh;norm<-sum(d$weight[eligible]*h[eligible]^2);fits[[stage+1L]]<-list(stage=stage+1L,tree=tree,rows=stageRows,queryFits=qh,norm=norm,predictedSSEDecrease=eta*(2-eta)*norm)};list(task='regression',initial=initial,learningRate=eta,stages=stages,training=train,queries=query,fits=fits,losses=losses,predictions=lapply(seq_len(nrow(a$queries)),function(i)list(id=a$queries$id[i],prediction=query[i,stages+1L],probabilities=numeric(),vote=NA_character_,prob=NA_character_)))}\nfixed_schedules<-function(ids,p,seed){state<-seed;choose<-function(n){limit<-floor(4294967296/n)*n;repeat{state<<-(1664525*state+1013904223)%%4294967296;if(state<limit)return(as.integer(state%%n))}};draws<-schedules<-list();for(member in 1:4){draws[[member]]<-vapply(seq_along(ids),function(i)ids[choose(length(ids))+1L],'');schedule<-setNames(vector('list',7),c('','L','R','LL','LR','RL','RR'));for(path in names(schedule)){order<-seq_len(p)-1L;if(p>1)for(j in seq(p-1L,1L)){k<-choose(j+1L);temp<-order[j+1L];order[j+1L]<-order[k+1L];order[k+1L]<-temp};schedule[[match(path,names(schedule))]]<-sort(order[seq_len(max(1L,floor(sqrt(p))))])};schedules[[member]]<-schedule};list(draws=draws,schedules=schedules)}\nread_sources<-function(src){read<-function(name)read.csv(file.path(src,name),check.names=FALSE,colClasses='character',na.strings=character(),fileEncoding='UTF-8-BOM');raw<-read('actual320-country-four-indicators-original-2020-2024.csv');country<-do.call(rbind,lapply(sort(unique(raw$countryISO3)),function(code)do.call(rbind,lapply(2020:2024,function(year){keys<-c('NY.GDP.PCAP.KD','NY.GDP.MKTP.KD.ZG','FP.CPI.TOTL.ZG','SP.DYN.LE00.IN');v<-vapply(keys,function(k)as.numeric(raw$originalValueToken[raw$countryISO3==code&raw$date==as.character(year)&raw$indicatorID==k]),0);data.frame(id=paste0(code,':',year),sourceRow=paste0(code,':',year),originalID=code,year=year,x0=v[1]/10000,x1=v[2],x2=v[3],y=v[4],weight=1,role=if(anyNA(v))'excluded'else if(year==2024)'outer-test'else'train')}))));raw<-read('actual3613-NLS-original52-fields-and-selection.csv');i<-seq_len(nrow(raw));x0<-suppressWarnings(as.numeric(raw$ed76));x1<-suppressWarnings(as.numeric(raw$age76));y<-suppressWarnings(as.numeric(raw$wage76))/100;person<-data.frame(id=paste0('person:',i),sourceRow=as.character(i),originalID=raw$id,x0=x0,x1=x1,y=y,weight=1,role=ifelse(is.na(x0)|is.na(x1)|is.na(y),'excluded',ifelse(i%%5==0,'outer-test','train')));raw<-read('actual3150-churn-original14-fields-and-selection.csv');i<-seq_len(nrow(raw));company<-data.frame(id=paste0('customer:',i),sourceRow=as.character(i),originalID='',x0=as.numeric(raw[['Call  Failure']]),x1=as.numeric(raw[['Subscription  Length']]),x2=as.numeric(raw[['Charge  Amount']]),y=raw$Churn,weight=1,role=ifelse(i%%5==0,'outer-test','train'));models<-list();for(index in 1:3){kind<-c('country','person','company')[index];d<-list(country,person,company)[[index]];task<-if(kind=='company')'classification'else'regression';s<-fixed_schedules(d$id[d$role=='train'],if(kind=='person')2L else 3L,20261102+7919*(index-1L));models[[kind]]<-list(records=d,task=task,classes=if(task=='classification')c('0','1')else character(),draws=s$draws,schedules=s$schedules,minLeaf=c(4L,50L,30L)[index])};models}\nrealdata<-function(models,kind,options=list()){if(is.null(options)||!is.list(options))stop('options object');m<-models[[kind]];d<-m$records;train<-d[d$role=='train',,drop=FALSE];test<-d[d$role=='outer-test',,drop=FALSE];method<-option(options,'method','forest');depth<-option(options,'maxDepth',2);count<-option(options,'memberCount',3);if(!method%in%c('bagging','forest','boost'))stop('known method');a<-list(rows=train,queries=test,task=m$task,classes=m$classes,maxDepth=depth,minLeaf=option(options,'minLeaf',m$minLeaf),minLeafWeight=0,minGain=0,missingRoute='best',learningRate=option(options,'learningRate','1/2'),stages=option(options,'stages',3));if(method=='boost')result<-boost(a)else{a$bootstrapDraws<-m$draws[seq_len(count)];a$nodeFeatures<-lapply(m$schedules[seq_len(count)],function(s)s[nchar(names(s))<depth]);result<-ensemble(a,method=='forest')};outer<-scored(result$predictions,normrows(test,m$task),m$task,m$classes);st<-stat(normrows(train,m$task),m$task,m$classes);constant<-list(prediction=st$pred,probabilities=st$p,vote=st$pred,prob=st$pred);baseline<-scored(lapply(test$id,function(id)c(list(id=id),constant)),normrows(test,m$task),m$task,m$classes);list(kind=kind,method=method,settings=a,train=train,test=test,result=result,outer=outer,baseline=baseline)}\nAPI<-\"variance\"\nINPUT<-list(B=10,marginalVariance=4,rho=0)\n\nrun_fixed<-function(api,a,out,src){\n r<-if(api=='variance')variance(a)else if(api=='aggregate')aggregate(a)else if(api%in%c('bagging','forest'))ensemble(a,api=='forest')else if(api=='boost')boost(a)else realdata(read_sources(src),a$kind)\n dir.create(out,recursive=TRUE,showWarnings=FALSE);summary<-list();points<-list();add<-function(x,y,s){if(!is.null(y)&&!is.na(y))points[[length(points)+1L]]<<-data.frame(x=x,y=as.numeric(y),series=s)}\n if(api=='variance'){summary<-r[c('B','varianceOfMean')];add(r$B,r$varianceOfMean,'Specified finite-B variance');xl<-'Number of members B';yl<-'Variance, stipulated units squared';title<-'Declared covariance model, not fitted trees'\n }else if(api=='aggregate'){p<-r$predictions[[1]];summary<-list(selectedPrediction=p$prediction);classification<-identical(a$task,'classification');if(classification){summary<-c(summary,list(voteLabel=p$vote,probabilityLabel=p$prob,meanProbability1=p$probabilities[2]));add(1,p$probabilities[2],'Mean probability of class 1');add(2,p$votes[2],'Label-vote share of class 1');xl<-'Aggregation (1=probability, 2=vote)';yl<-'Probability or vote share'}else{for(i in seq_along(a$members))add(i,num(a$members[[i]]$predictions$value[1]),'Member prediction');add(3,p$prediction,'Weighted mean');xl<-'Member 1, member 2, aggregate 3';yl<-'Prediction, assumed units'};title<-'Votes and probabilities are distinct objects'\n }else if(api%in%c('bagging','forest')){summary<-list(queryPrediction=r$predictions[[1]]$prediction,OOB.scoreable=r$outOfBag$eligibleRows,OOB.meanLoss=r$outOfBag$meanLoss);for(i in seq_len(nrow(a$rows)))add(i,a$rows$y[i],'Observed training outcome');for(i in seq_along(r$outOfBag$rows))add(i,r$outOfBag$rows[[i]]$prediction,'OOB prediction, when defined');xl<-'Original training ID order';yl<-'Outcome, assumed units';title<-'Repeated draws and ID-level OOB membership'\n }else if(api=='boost'){summary<-list(initial=r$initial,finalMSE=r$losses[[length(r$losses)]]$MSE,stages=r$stages);for(v in r$losses)add(v$stage,v$MSE,'Training MSE');xl<-'Boosting stage (0=initial)';yl<-'Weighted MSE, outcome units squared';title<-'Training descent does not certify held-out gain'\n }else{summary<-list(outer.scoreable=r$outer$eligibleRows,outer.meanLoss=r$outer$meanLoss,baseline.meanLoss=r$baseline$meanLoss,OOB.scoreable=r$result$outOfBag$eligibleRows,OOB.meanLoss=r$result$outOfBag$meanLoss);for(i in seq_along(r$outer$rows)){p<-r$outer$rows[[i]];add(i,as.numeric(p$actual),'Observed outcome');add(i,if(a$kind=='company')p$probabilities[2]else p$prediction,if(a$kind=='company')'Forest probability of class 1'else'Forest prediction')};xl<-'Outer-test source order, not a time path';yl<-if(a$kind=='company')'Churn label / probability'else if(a$kind=='country')'Period life expectancy, years'else'Nominal 1976 USD per hour';title<-'Fixed forest; outer labels did not fit the trees'}\n display<-function(v)if(is.null(v)||is.na(v))'undefined'else sprintf('%.9f',as.numeric(v));write.csv(data.frame(metric=names(summary),value=vapply(summary,display,'')),file.path(out,'summary.csv'),row.names=FALSE);pp<-do.call(rbind,points);write.csv(pp,file.path(out,'plot-points.csv'),row.names=FALSE);dput(r,file.path(out,'full-result.Rtext'));svg(file.path(out,'plot.svg'),width=5.6,height=4.6,pointsize=14);par(mar=c(5.8,5.8,5.3,1.2),mgp=c(3.7,1,0));xr<-range(pp$x);yr<-range(pp$y);if(diff(xr)==0)xr<-xr+c(-.5,.5);if(diff(yr)==0)yr<-yr+c(-.5,.5);plot(xr,yr,type='n',xlab=xl,ylab=yl,cex.lab=.78,axes=FALSE);axis(1,at=pretty(xr,3));axis(2,at=pretty(yr,4),las=1,cex.axis=.82);box();grid(col='#dddddd');cols<-c('#355c72','#a55336','#507956','#78568b');ss<-unique(pp$series);for(i in seq_along(ss)){v<-pp[pp$series==ss[i],];points(v$x,v$y,pch=16,cex=if(nrow(v)>100).35 else .85,col=adjustcolor(cols[i],if(nrow(v)>100).5 else 1))};legend('topleft',legend=ss,col=cols[seq_along(ss)],lty=0,pch=16,cex=.65,bty='n',inset=c(0,-.32),xpd=NA);mtext(title,side=3,line=3.9,cex=.6);dev.off();cat(paste(names(summary),vapply(summary,display,''),sep='=',collapse=', '),'\\n')\n}\nargs<-commandArgs(trailingOnly=TRUE)\ntryCatch(run_fixed(API,INPUT,if(length(args))args[1]else'fixed-results',if(length(args)>1)args[2]else'ml09-sources'),error=function(e){cat('Rejected declared input: ',conditionMessage(e),'\\n',file=stderr());quit(status=2)})\n",
        "code": "# ML09 base-R reproduction from native original-field CSVs.\n# Rscript ml09-public-analysis.R ml09-sources results-r\n# Separately written vectorized direct-centered squared/Gini losses.\n# No Python/JS/model-contract/stored-answer/derived-result reader or package.\n# Numeric arithmetic is binary64:1e-12 relative tie tolerance stabilizes exact\n# source ties,but does not certify tiny margins/underflow like Fraction JS/Python.\n# Data-frame rows use x0,x1,...,y,weight; original IDs remain attached to draws.\noptions(stringsAsFactors=FALSE,digits=17)\nnum<-function(v){if(is.null(v)||length(v)!=1||is.na(v))stop('numeric parameter required, not explicit NULL');p<-strsplit(as.character(v),'/',fixed=TRUE)[[1]];z<-if(length(p)==2)as.numeric(p[1])/as.numeric(p[2])else as.numeric(v);if(!is.finite(z))stop('finite numeric parameter');z}\noption<-function(a,k,default){if(k%in%names(a))a[[k]]else default}\nnormrows<-function(d,task){if(!'weight'%in%names(d))d$weight<-1;if(!'id'%in%names(d))d$id<-as.character(seq_len(nrow(d))-1);d$weight<-as.numeric(d$weight);if(anyNA(d$weight)||any(d$weight<0))stop('nonnegative weights');if(task=='regression')d$y<-as.numeric(d$y)else d$y<-as.character(d$y);d}\nstat<-function(d,task,classes){W<-sum(d$weight);mu<-if(task=='regression'&&W)sum(d$weight*d$y)/W else NA_real_;p<-if(task=='classification'&&W)vapply(classes,function(c)sum(d$weight[d$y==c])/W,0)else numeric();risk<-if(task=='regression'&&W)sum(d$weight*(d$y-mu)^2)else W*sum(p*(1-p));list(n=nrow(d),w=W,mu=mu,p=unname(p),risk=risk,pred=if(task=='regression')mu else if(W)classes[which.max(p)]else NA_character_)}\nfit<-function(d,a,task,classes,schedule=NULL){d<-d[d$weight>0&!is.na(d$y),,drop=FALSE];if(!nrow(d))stop('positive observed training');W<-sum(d$weight);depth<-option(a,'maxDepth',2);minimum<-option(a,'minLeaf',1);minmass<-num(option(a,'minLeafWeight',0));mingain<-num(option(a,'minGain',0));route<-option(a,'missingRoute','best');features<-grep('^x[0-9]+$',names(d),value=TRUE)\n build<-function(rr,level,path){st<-stat(rr,task,classes);node<-list(rows=rr,st=st,split=NULL,left=NULL,right=NULL,path=path);if(level==depth)return(node);best<-NULL;allowed<-if(is.null(schedule))seq_along(features)-1L else schedule[[match(path,names(schedule))]]\n  for(j in seq_along(features)-1L){if(!j%in%allowed)next;v<-rr[[features[j+1L]]];values<-sort(unique(v[!is.na(v)]));candidates<-list()\n   if(length(values)>1)for(k in seq_len(length(values)-1L)){threshold<-(values[k]+values[k+1L])/2;missing<-is.na(v);left<-!missing&v<=threshold;right<-!missing&v>threshold;directions<-if(route!='best')route else if(any(missing))c('left','right')else if(sum(left)>=sum(right))'left'else'right';for(direction in directions)candidates[[length(candidates)+1L]]<-list(kind='threshold',threshold=threshold,missingRoute=direction,left=if(direction=='left')left|missing else left,right=if(direction=='right')right|missing else right)}\n   if(anyNA(v)&&any(!is.na(v)))candidates[[length(candidates)+1L]]<-list(kind='missing-only',threshold=NA_real_,missingRoute='left',left=is.na(v),right=!is.na(v))\n   for(candidate in candidates){l<-rr[candidate$left,,drop=FALSE];r<-rr[candidate$right,,drop=FALSE];ls<-stat(l,task,classes);rs<-stat(r,task,classes);if(min(ls$n,rs$n)<minimum||min(ls$w,rs$w)<minmass||min(ls$w,rs$w)<=0)next;gain<-(st$risk-ls$risk-rs$risk)/W;tol<-1e-12*max(1,abs(gain),if(is.null(best))0 else abs(best$gain));if(is.null(best)||gain>best$gain+tol)best<-c(candidate,list(feature=j,gain=gain,l=l,r=r))}\n  }\n  if(!is.null(best)&&best$gain>max(mingain,1e-12)){node$split<-best;node$left<-build(best$l,level+1L,paste0(path,'L'));node$right<-build(best$r,level+1L,paste0(path,'R'))};node\n };build(d,0L,'')\n}\npredict_one<-function(tree,row){n<-tree;while(!is.null(n$split)){s<-n$split;v<-as.numeric(row[[paste0('x',s$feature)]]);left<-if(s$kind=='missing-only')is.na(v)else if(is.na(v))s$missingRoute=='left'else v<=s$threshold;n<-if(left)n$left else n$right};list(prediction=n$st$pred,probabilities=n$st$p)}\ncombine<-function(pp,w,task,classes,mode='probabilities'){W<-sum(w);if(!length(pp)||!W)return(list(prediction=if(task=='regression')NA_real_ else NA_character_,probabilities=numeric(),vote=NA_character_,prob=NA_character_));if(task=='regression')return(list(prediction=sum(vapply(pp,function(p)p$prediction,0)*w)/W,probabilities=numeric(),vote=NA_character_,prob=NA_character_));votes<-vapply(classes,function(c)sum(w[vapply(pp,function(p)p$prediction==c,FALSE)])/W,0);probs<-vapply(seq_along(classes),function(j)sum(vapply(pp,function(p)p$probabilities[j],0)*w)/W,0);vote<-classes[which.max(votes)];prob<-classes[which.max(probs)];list(prediction=if(mode=='votes')vote else prob,probabilities=unname(probs),vote=vote,prob=prob,votes=unname(votes))}\nvariance<-function(a){B<-num(a$B);v<-num(a$marginalVariance);rho<-num(option(a,'rho',0));if(B<1||B!=floor(B)||v<0)stop('integer B/nonnegative variance');if(B>1&&v>0&&(rho< -1/(B-1)||rho>1))stop('PSD correlation');list(B=B,marginalVariance=v,correlationApplicable=B>1&&v>0,varianceOfMean=if(B==1)v else v*(1+(B-1)*rho)/B)}\naggregate<-function(a){task<-option(a,'task','regression');classes<-option(a,'classes',character());w<-vapply(option(a,'memberWeights',as.list(rep(1,length(a$members)))),num,0);if(any(w<0)||sum(w)<=0)stop('positive member mass');ids<-a$members[[1]]$predictions$id;pp<-lapply(ids,function(id){members<-lapply(a$members,function(m){r<-m$predictions[match(id,m$predictions$id),,drop=FALSE];if(task=='regression')list(prediction=num(r$value),probabilities=numeric())else list(prediction=as.character(r$label),probabilities=as.numeric(r[paste0('p',seq_along(classes)-1L)]))});c(list(id=id),combine(members,w,task,classes,option(a,'aggregation','probabilities')))});list(task=task,classes=classes,predictions=pp)}\nscored<-function(preds,d,task,classes){W<-loss<-absolute<-errors<-voteerrors<-0;count<-0L;out<-lapply(seq_len(nrow(d)),function(i){r<-d[i,,drop=FALSE];p<-preds[[i]];ok<-!is.na(p$prediction)&&!is.na(r$y)&&r$weight>0;value<-NA_real_;if(ok){count<<-count+1L;W<<-W+r$weight;if(task=='regression'){e<-r$y-p$prediction;value<-e*e;absolute<<-absolute+r$weight*abs(e)}else{value<-sum((p$probabilities-as.numeric(classes==r$y))^2);errors<<-errors+r$weight*(p$prediction!=r$y);voteerrors<<-voteerrors+r$weight*(p$vote!=r$y)};loss<<-loss+r$weight*value};c(p,list(actual=r$y,weight=r$weight,scoreEligible=ok,loss=value))});list(rows=out,eligibleRows=count,weight=W,totalLoss=loss,meanLoss=if(W)loss/W else NA_real_,MAE=if(W&&task=='regression')absolute/W else NA_real_,errorRate=if(W&&task=='classification')errors/W else NA_real_,labelVoteErrorRate=if(W&&task=='classification')voteerrors/W else NA_real_)}\nensemble<-function(a,forest=FALSE){task<-option(a,'task','regression');classes<-option(a,'classes',character());d<-normrows(a$rows,task);w<-vapply(option(a,'memberWeights',as.list(rep(1,length(a$bootstrapDraws)))),num,0);if(any(w<0)||sum(w)<=0)stop('positive member mass');members<-lapply(seq_along(a$bootstrapDraws),function(i){draw<-a$bootstrapDraws[[i]];indices<-match(draw,d$id);if(anyNA(indices))stop('unknown draw source');tree<-fit(d[indices,,drop=FALSE],a,task,classes,if(forest)a$nodeFeatures[[i]]else NULL);list(tree=tree,draw=draw,inbag=unique(draw),weight=w[i])});queries<-a$queries;preds<-lapply(seq_len(nrow(queries)),function(i)c(list(id=queries$id[i]),combine(lapply(members,function(m)predict_one(m$tree,queries[i,,drop=FALSE])),w,task,classes,option(a,'aggregation','probabilities'))));oob<-lapply(seq_len(nrow(d)),function(i){app<-which(!vapply(members,function(m)d$id[i]%in%m$inbag,FALSE));pp<-combine(lapply(app,function(j)predict_one(members[[j]]$tree,d[i,,drop=FALSE])),w[app],task,classes,option(a,'aggregation','probabilities'));c(list(id=d$id[i],applicable=app-1L,positiveMembers=sum(w[app]>0)),pp)});list(task=task,classes=classes,members=members,predictions=preds,outOfBag=scored(oob,d,task,classes))}\nboost<-function(a){if(option(a,'task','regression')!='regression')stop('regression boosting only');d<-normrows(a$rows,'regression');eligible<-d$weight>0&!is.na(d$y);W<-sum(d$weight[eligible]);if(!W)stop('positive eligible training');eta<-num(option(a,'learningRate','1/2'));stages<-option(a,'stages',3);if(is.null(stages)||stages!=floor(stages)||stages<0||stages>8||eta<0||eta>1)stop('supported rate/stages');initial<-if('initial'%in%names(a))num(a$initial)else sum(d$weight[eligible]*d$y[eligible])/W;train<-matrix(initial,nrow(d),stages+1L);query<-matrix(initial,nrow(a$queries),stages+1L);losses<-fits<-list();for(stage in 0:stages){sse<-sum(d$weight[eligible]*(d$y[eligible]-train[eligible,stage+1L])^2);losses[[stage+1L]]<-list(stage=stage,rawWeightedSSE=sse,MSE=sse/W,meanHalfSquaredLoss=sse/(2*W));if(stage==stages)break;residual<-d;residual$y<-d$y-train[,stage+1L];tree<-fit(residual,a,'regression',character());h<-vapply(seq_len(nrow(d)),function(i)predict_one(tree,d[i,,drop=FALSE])$prediction,0);qh<-vapply(seq_len(nrow(a$queries)),function(i)predict_one(tree,a$queries[i,,drop=FALSE])$prediction,0);stageRows<-lapply(seq_len(nrow(d)),function(i)list(id=d$id[i],before=train[i,stage+1L],residual=residual$y[i],negativeCoordinateDerivative=d$weight[i]*residual$y[i]/W,fit=h[i],addition=eta*h[i],after=train[i,stage+1L]+eta*h[i]));train[,stage+2L]<-train[,stage+1L]+eta*h;query[,stage+2L]<-query[,stage+1L]+eta*qh;norm<-sum(d$weight[eligible]*h[eligible]^2);fits[[stage+1L]]<-list(stage=stage+1L,tree=tree,rows=stageRows,queryFits=qh,norm=norm,predictedSSEDecrease=eta*(2-eta)*norm)};list(task='regression',initial=initial,learningRate=eta,stages=stages,training=train,queries=query,fits=fits,losses=losses,predictions=lapply(seq_len(nrow(a$queries)),function(i)list(id=a$queries$id[i],prediction=query[i,stages+1L],probabilities=numeric(),vote=NA_character_,prob=NA_character_)))}\nfixed_schedules<-function(ids,p,seed){state<-seed;choose<-function(n){limit<-floor(4294967296/n)*n;repeat{state<<-(1664525*state+1013904223)%%4294967296;if(state<limit)return(as.integer(state%%n))}};draws<-schedules<-list();for(member in 1:4){draws[[member]]<-vapply(seq_along(ids),function(i)ids[choose(length(ids))+1L],'');schedule<-setNames(vector('list',7),c('','L','R','LL','LR','RL','RR'));for(path in names(schedule)){order<-seq_len(p)-1L;if(p>1)for(j in seq(p-1L,1L)){k<-choose(j+1L);temp<-order[j+1L];order[j+1L]<-order[k+1L];order[k+1L]<-temp};schedule[[match(path,names(schedule))]]<-sort(order[seq_len(max(1L,floor(sqrt(p))))])};schedules[[member]]<-schedule};list(draws=draws,schedules=schedules)}\nread_sources<-function(src){read<-function(name)read.csv(file.path(src,name),check.names=FALSE,colClasses='character',na.strings=character(),fileEncoding='UTF-8-BOM');raw<-read('actual320-country-four-indicators-original-2020-2024.csv');country<-do.call(rbind,lapply(sort(unique(raw$countryISO3)),function(code)do.call(rbind,lapply(2020:2024,function(year){keys<-c('NY.GDP.PCAP.KD','NY.GDP.MKTP.KD.ZG','FP.CPI.TOTL.ZG','SP.DYN.LE00.IN');v<-vapply(keys,function(k)as.numeric(raw$originalValueToken[raw$countryISO3==code&raw$date==as.character(year)&raw$indicatorID==k]),0);data.frame(id=paste0(code,':',year),sourceRow=paste0(code,':',year),originalID=code,year=year,x0=v[1]/10000,x1=v[2],x2=v[3],y=v[4],weight=1,role=if(anyNA(v))'excluded'else if(year==2024)'outer-test'else'train')}))));raw<-read('actual3613-NLS-original52-fields-and-selection.csv');i<-seq_len(nrow(raw));x0<-suppressWarnings(as.numeric(raw$ed76));x1<-suppressWarnings(as.numeric(raw$age76));y<-suppressWarnings(as.numeric(raw$wage76))/100;person<-data.frame(id=paste0('person:',i),sourceRow=as.character(i),originalID=raw$id,x0=x0,x1=x1,y=y,weight=1,role=ifelse(is.na(x0)|is.na(x1)|is.na(y),'excluded',ifelse(i%%5==0,'outer-test','train')));raw<-read('actual3150-churn-original14-fields-and-selection.csv');i<-seq_len(nrow(raw));company<-data.frame(id=paste0('customer:',i),sourceRow=as.character(i),originalID='',x0=as.numeric(raw[['Call  Failure']]),x1=as.numeric(raw[['Subscription  Length']]),x2=as.numeric(raw[['Charge  Amount']]),y=raw$Churn,weight=1,role=ifelse(i%%5==0,'outer-test','train'));models<-list();for(index in 1:3){kind<-c('country','person','company')[index];d<-list(country,person,company)[[index]];task<-if(kind=='company')'classification'else'regression';s<-fixed_schedules(d$id[d$role=='train'],if(kind=='person')2L else 3L,20261102+7919*(index-1L));models[[kind]]<-list(records=d,task=task,classes=if(task=='classification')c('0','1')else character(),draws=s$draws,schedules=s$schedules,minLeaf=c(4L,50L,30L)[index])};models}\nrealdata<-function(models,kind,options=list()){if(is.null(options)||!is.list(options))stop('options object');m<-models[[kind]];d<-m$records;train<-d[d$role=='train',,drop=FALSE];test<-d[d$role=='outer-test',,drop=FALSE];method<-option(options,'method','forest');depth<-option(options,'maxDepth',2);count<-option(options,'memberCount',3);if(!method%in%c('bagging','forest','boost'))stop('known method');a<-list(rows=train,queries=test,task=m$task,classes=m$classes,maxDepth=depth,minLeaf=option(options,'minLeaf',m$minLeaf),minLeafWeight=0,minGain=0,missingRoute='best',learningRate=option(options,'learningRate','1/2'),stages=option(options,'stages',3));if(method=='boost')result<-boost(a)else{a$bootstrapDraws<-m$draws[seq_len(count)];a$nodeFeatures<-lapply(m$schedules[seq_len(count)],function(s)s[nchar(names(s))<depth]);result<-ensemble(a,method=='forest')};outer<-scored(result$predictions,normrows(test,m$task),m$task,m$classes);st<-stat(normrows(train,m$task),m$task,m$classes);constant<-list(prediction=st$pred,probabilities=st$p,vote=st$pred,prob=st$pred);baseline<-scored(lapply(test$id,function(id)c(list(id=id),constant)),normrows(test,m$task),m$task,m$classes);list(kind=kind,method=method,settings=a,train=train,test=test,result=result,outer=outer,baseline=baseline)}\nAPI<-\"variance\"\nINPUT<-list(B=10,marginalVariance=4,rho=0)\n\nrun_fixed<-function(api,a,out,src){\n r<-if(api=='variance')variance(a)else if(api=='aggregate')aggregate(a)else if(api%in%c('bagging','forest'))ensemble(a,api=='forest')else if(api=='boost')boost(a)else realdata(read_sources(src),a$kind)\n dir.create(out,recursive=TRUE,showWarnings=FALSE);summary<-list();points<-list();add<-function(x,y,s){if(!is.null(y)&&!is.na(y))points[[length(points)+1L]]<<-data.frame(x=x,y=as.numeric(y),series=s)}\n if(api=='variance'){summary<-r[c('B','varianceOfMean')];add(r$B,r$varianceOfMean,'Specified finite-B variance');xl<-'Number of members B';yl<-'Variance, stipulated units squared';title<-'Declared covariance model, not fitted trees'\n }else if(api=='aggregate'){p<-r$predictions[[1]];summary<-list(selectedPrediction=p$prediction);classification<-identical(a$task,'classification');if(classification){summary<-c(summary,list(voteLabel=p$vote,probabilityLabel=p$prob,meanProbability1=p$probabilities[2]));add(1,p$probabilities[2],'Mean probability of class 1');add(2,p$votes[2],'Label-vote share of class 1');xl<-'Aggregation (1=probability, 2=vote)';yl<-'Probability or vote share'}else{for(i in seq_along(a$members))add(i,num(a$members[[i]]$predictions$value[1]),'Member prediction');add(3,p$prediction,'Weighted mean');xl<-'Member 1, member 2, aggregate 3';yl<-'Prediction, assumed units'};title<-'Votes and probabilities are distinct objects'\n }else if(api%in%c('bagging','forest')){summary<-list(queryPrediction=r$predictions[[1]]$prediction,OOB.scoreable=r$outOfBag$eligibleRows,OOB.meanLoss=r$outOfBag$meanLoss);for(i in seq_len(nrow(a$rows)))add(i,a$rows$y[i],'Observed training outcome');for(i in seq_along(r$outOfBag$rows))add(i,r$outOfBag$rows[[i]]$prediction,'OOB prediction, when defined');xl<-'Original training ID order';yl<-'Outcome, assumed units';title<-'Repeated draws and ID-level OOB membership'\n }else if(api=='boost'){summary<-list(initial=r$initial,finalMSE=r$losses[[length(r$losses)]]$MSE,stages=r$stages);for(v in r$losses)add(v$stage,v$MSE,'Training MSE');xl<-'Boosting stage (0=initial)';yl<-'Weighted MSE, outcome units squared';title<-'Training descent does not certify held-out gain'\n }else{summary<-list(outer.scoreable=r$outer$eligibleRows,outer.meanLoss=r$outer$meanLoss,baseline.meanLoss=r$baseline$meanLoss,OOB.scoreable=r$result$outOfBag$eligibleRows,OOB.meanLoss=r$result$outOfBag$meanLoss);for(i in seq_along(r$outer$rows)){p<-r$outer$rows[[i]];add(i,as.numeric(p$actual),'Observed outcome');add(i,if(a$kind=='company')p$probabilities[2]else p$prediction,if(a$kind=='company')'Forest probability of class 1'else'Forest prediction')};xl<-'Outer-test source order, not a time path';yl<-if(a$kind=='company')'Churn label / probability'else if(a$kind=='country')'Period life expectancy, years'else'Nominal 1976 USD per hour';title<-'Fixed forest; outer labels did not fit the trees'}\n display<-function(v)if(is.null(v)||is.na(v))'undefined'else sprintf('%.9f',as.numeric(v));write.csv(data.frame(metric=names(summary),value=vapply(summary,display,'')),file.path(out,'summary.csv'),row.names=FALSE);pp<-do.call(rbind,points);write.csv(pp,file.path(out,'plot-points.csv'),row.names=FALSE);dput(r,file.path(out,'full-result.Rtext'));svg(file.path(out,'plot.svg'),width=5.6,height=4.6,pointsize=14);par(mar=c(5.8,5.8,5.3,1.2),mgp=c(3.7,1,0));xr<-range(pp$x);yr<-range(pp$y);if(diff(xr)==0)xr<-xr+c(-.5,.5);if(diff(yr)==0)yr<-yr+c(-.5,.5);plot(xr,yr,type='n',xlab=xl,ylab=yl,cex.lab=.78,axes=FALSE);axis(1,at=pretty(xr,3));axis(2,at=pretty(yr,4),las=1,cex.axis=.82);box();grid(col='#dddddd');cols<-c('#355c72','#a55336','#507956','#78568b');ss<-unique(pp$series);for(i in seq_along(ss)){v<-pp[pp$series==ss[i],];points(v$x,v$y,pch=16,cex=if(nrow(v)>100).35 else .85,col=adjustcolor(cols[i],if(nrow(v)>100).5 else 1))};legend('topleft',legend=ss,col=cols[seq_along(ss)],lty=0,pch=16,cex=.65,bty='n',inset=c(0,-.32),xpd=NA);mtext(title,side=3,line=3.9,cex=.6);dev.off();cat(paste(names(summary),vapply(summary,display,''),sep='=',collapse=', '),'\\n')\n}\nargs<-commandArgs(trailingOnly=TRUE)\ntryCatch(run_fixed(API,INPUT,if(length(args))args[1]else'fixed-results',if(length(args)>1)args[2]else'ml09-sources'),error=function(e){cat('Rejected declared input: ',conditionMessage(e),'\\n',file=stderr());quit(status=2)})\n",
        "inputFiles": [],
        "input": {
          "B": 10,
          "marginalVariance": 4,
          "rho": 0
        },
        "returnCode": 0,
        "expectedFailure": false,
        "stdout": "B=10.000000000, varianceOfMean=0.400000000 \n",
        "stderr": "During startup - Warning messages:\n1: Setting LC_COLLATE=C.UTF-8 failed \n2: Setting LC_CTYPE=C.UTF-8 failed \n3: Setting LC_MONETARY=C.UTF-8 failed \n4: Setting LC_TIME=C.UTF-8 failed \n",
        "summary": {
          "B": "10.000000000",
          "varianceOfMean": "0.400000000"
        },
        "plotPoints": [
          {
            "x": "10",
            "y": "0.4",
            "series": "Specified finite-B variance"
          }
        ],
        "plotFile": "ml09-fixed-results/variance-independent-r/plot.svg",
        "plotSHA256": "e0b25c2a43be2c01e9f37c3ef8f2db086c77473e92568e18443b075056b86d4e",
        "files": [
          {
            "file": "ml09-fixed-results/variance-independent-r/full-result.Rtext",
            "sha256": "0bc3037d7bfd6b7528e601880d113c9f54e6eb35faafd02720e5e79e6dc18aea"
          },
          {
            "file": "ml09-fixed-results/variance-independent-r/plot-points.csv",
            "sha256": "3a403bb8923a356187afe94a973134c69cada1be582dbb9534262003ea1ca5dc"
          },
          {
            "file": "ml09-fixed-results/variance-independent-r/plot.svg",
            "sha256": "e0b25c2a43be2c01e9f37c3ef8f2db086c77473e92568e18443b075056b86d4e"
          },
          {
            "file": "ml09-fixed-results/variance-independent-r/summary.csv",
            "sha256": "55e869321b8040aeafa313af8e95d860caeab9ea237670a5258126e1cd5a534f"
          }
        ],
        "scope": "Actually executed self-contained fixed example; current web controls execute separately. Python Fraction and finite-precision base R. Author gate, not independent peer."
      },
      "PSD-boundary": {
        "api": "variance",
        "variant": "PSD-boundary",
        "language": "r",
        "codeFile": "ml09-code/variance-PSD-boundary.R",
        "codeSHA256": "bc76d559918f3225c9430cd0cce9d4ed87b51efb95c35590019a392444b9f395",
        "codeText": "# ML09 base-R reproduction from native original-field CSVs.\n# Rscript ml09-public-analysis.R ml09-sources results-r\n# Separately written vectorized direct-centered squared/Gini losses.\n# No Python/JS/model-contract/stored-answer/derived-result reader or package.\n# Numeric arithmetic is binary64:1e-12 relative tie tolerance stabilizes exact\n# source ties,but does not certify tiny margins/underflow like Fraction JS/Python.\n# Data-frame rows use x0,x1,...,y,weight; original IDs remain attached to draws.\noptions(stringsAsFactors=FALSE,digits=17)\nnum<-function(v){if(is.null(v)||length(v)!=1||is.na(v))stop('numeric parameter required, not explicit NULL');p<-strsplit(as.character(v),'/',fixed=TRUE)[[1]];z<-if(length(p)==2)as.numeric(p[1])/as.numeric(p[2])else as.numeric(v);if(!is.finite(z))stop('finite numeric parameter');z}\noption<-function(a,k,default){if(k%in%names(a))a[[k]]else default}\nnormrows<-function(d,task){if(!'weight'%in%names(d))d$weight<-1;if(!'id'%in%names(d))d$id<-as.character(seq_len(nrow(d))-1);d$weight<-as.numeric(d$weight);if(anyNA(d$weight)||any(d$weight<0))stop('nonnegative weights');if(task=='regression')d$y<-as.numeric(d$y)else d$y<-as.character(d$y);d}\nstat<-function(d,task,classes){W<-sum(d$weight);mu<-if(task=='regression'&&W)sum(d$weight*d$y)/W else NA_real_;p<-if(task=='classification'&&W)vapply(classes,function(c)sum(d$weight[d$y==c])/W,0)else numeric();risk<-if(task=='regression'&&W)sum(d$weight*(d$y-mu)^2)else W*sum(p*(1-p));list(n=nrow(d),w=W,mu=mu,p=unname(p),risk=risk,pred=if(task=='regression')mu else if(W)classes[which.max(p)]else NA_character_)}\nfit<-function(d,a,task,classes,schedule=NULL){d<-d[d$weight>0&!is.na(d$y),,drop=FALSE];if(!nrow(d))stop('positive observed training');W<-sum(d$weight);depth<-option(a,'maxDepth',2);minimum<-option(a,'minLeaf',1);minmass<-num(option(a,'minLeafWeight',0));mingain<-num(option(a,'minGain',0));route<-option(a,'missingRoute','best');features<-grep('^x[0-9]+$',names(d),value=TRUE)\n build<-function(rr,level,path){st<-stat(rr,task,classes);node<-list(rows=rr,st=st,split=NULL,left=NULL,right=NULL,path=path);if(level==depth)return(node);best<-NULL;allowed<-if(is.null(schedule))seq_along(features)-1L else schedule[[match(path,names(schedule))]]\n  for(j in seq_along(features)-1L){if(!j%in%allowed)next;v<-rr[[features[j+1L]]];values<-sort(unique(v[!is.na(v)]));candidates<-list()\n   if(length(values)>1)for(k in seq_len(length(values)-1L)){threshold<-(values[k]+values[k+1L])/2;missing<-is.na(v);left<-!missing&v<=threshold;right<-!missing&v>threshold;directions<-if(route!='best')route else if(any(missing))c('left','right')else if(sum(left)>=sum(right))'left'else'right';for(direction in directions)candidates[[length(candidates)+1L]]<-list(kind='threshold',threshold=threshold,missingRoute=direction,left=if(direction=='left')left|missing else left,right=if(direction=='right')right|missing else right)}\n   if(anyNA(v)&&any(!is.na(v)))candidates[[length(candidates)+1L]]<-list(kind='missing-only',threshold=NA_real_,missingRoute='left',left=is.na(v),right=!is.na(v))\n   for(candidate in candidates){l<-rr[candidate$left,,drop=FALSE];r<-rr[candidate$right,,drop=FALSE];ls<-stat(l,task,classes);rs<-stat(r,task,classes);if(min(ls$n,rs$n)<minimum||min(ls$w,rs$w)<minmass||min(ls$w,rs$w)<=0)next;gain<-(st$risk-ls$risk-rs$risk)/W;tol<-1e-12*max(1,abs(gain),if(is.null(best))0 else abs(best$gain));if(is.null(best)||gain>best$gain+tol)best<-c(candidate,list(feature=j,gain=gain,l=l,r=r))}\n  }\n  if(!is.null(best)&&best$gain>max(mingain,1e-12)){node$split<-best;node$left<-build(best$l,level+1L,paste0(path,'L'));node$right<-build(best$r,level+1L,paste0(path,'R'))};node\n };build(d,0L,'')\n}\npredict_one<-function(tree,row){n<-tree;while(!is.null(n$split)){s<-n$split;v<-as.numeric(row[[paste0('x',s$feature)]]);left<-if(s$kind=='missing-only')is.na(v)else if(is.na(v))s$missingRoute=='left'else v<=s$threshold;n<-if(left)n$left else n$right};list(prediction=n$st$pred,probabilities=n$st$p)}\ncombine<-function(pp,w,task,classes,mode='probabilities'){W<-sum(w);if(!length(pp)||!W)return(list(prediction=if(task=='regression')NA_real_ else NA_character_,probabilities=numeric(),vote=NA_character_,prob=NA_character_));if(task=='regression')return(list(prediction=sum(vapply(pp,function(p)p$prediction,0)*w)/W,probabilities=numeric(),vote=NA_character_,prob=NA_character_));votes<-vapply(classes,function(c)sum(w[vapply(pp,function(p)p$prediction==c,FALSE)])/W,0);probs<-vapply(seq_along(classes),function(j)sum(vapply(pp,function(p)p$probabilities[j],0)*w)/W,0);vote<-classes[which.max(votes)];prob<-classes[which.max(probs)];list(prediction=if(mode=='votes')vote else prob,probabilities=unname(probs),vote=vote,prob=prob,votes=unname(votes))}\nvariance<-function(a){B<-num(a$B);v<-num(a$marginalVariance);rho<-num(option(a,'rho',0));if(B<1||B!=floor(B)||v<0)stop('integer B/nonnegative variance');if(B>1&&v>0&&(rho< -1/(B-1)||rho>1))stop('PSD correlation');list(B=B,marginalVariance=v,correlationApplicable=B>1&&v>0,varianceOfMean=if(B==1)v else v*(1+(B-1)*rho)/B)}\naggregate<-function(a){task<-option(a,'task','regression');classes<-option(a,'classes',character());w<-vapply(option(a,'memberWeights',as.list(rep(1,length(a$members)))),num,0);if(any(w<0)||sum(w)<=0)stop('positive member mass');ids<-a$members[[1]]$predictions$id;pp<-lapply(ids,function(id){members<-lapply(a$members,function(m){r<-m$predictions[match(id,m$predictions$id),,drop=FALSE];if(task=='regression')list(prediction=num(r$value),probabilities=numeric())else list(prediction=as.character(r$label),probabilities=as.numeric(r[paste0('p',seq_along(classes)-1L)]))});c(list(id=id),combine(members,w,task,classes,option(a,'aggregation','probabilities')))});list(task=task,classes=classes,predictions=pp)}\nscored<-function(preds,d,task,classes){W<-loss<-absolute<-errors<-voteerrors<-0;count<-0L;out<-lapply(seq_len(nrow(d)),function(i){r<-d[i,,drop=FALSE];p<-preds[[i]];ok<-!is.na(p$prediction)&&!is.na(r$y)&&r$weight>0;value<-NA_real_;if(ok){count<<-count+1L;W<<-W+r$weight;if(task=='regression'){e<-r$y-p$prediction;value<-e*e;absolute<<-absolute+r$weight*abs(e)}else{value<-sum((p$probabilities-as.numeric(classes==r$y))^2);errors<<-errors+r$weight*(p$prediction!=r$y);voteerrors<<-voteerrors+r$weight*(p$vote!=r$y)};loss<<-loss+r$weight*value};c(p,list(actual=r$y,weight=r$weight,scoreEligible=ok,loss=value))});list(rows=out,eligibleRows=count,weight=W,totalLoss=loss,meanLoss=if(W)loss/W else NA_real_,MAE=if(W&&task=='regression')absolute/W else NA_real_,errorRate=if(W&&task=='classification')errors/W else NA_real_,labelVoteErrorRate=if(W&&task=='classification')voteerrors/W else NA_real_)}\nensemble<-function(a,forest=FALSE){task<-option(a,'task','regression');classes<-option(a,'classes',character());d<-normrows(a$rows,task);w<-vapply(option(a,'memberWeights',as.list(rep(1,length(a$bootstrapDraws)))),num,0);if(any(w<0)||sum(w)<=0)stop('positive member mass');members<-lapply(seq_along(a$bootstrapDraws),function(i){draw<-a$bootstrapDraws[[i]];indices<-match(draw,d$id);if(anyNA(indices))stop('unknown draw source');tree<-fit(d[indices,,drop=FALSE],a,task,classes,if(forest)a$nodeFeatures[[i]]else NULL);list(tree=tree,draw=draw,inbag=unique(draw),weight=w[i])});queries<-a$queries;preds<-lapply(seq_len(nrow(queries)),function(i)c(list(id=queries$id[i]),combine(lapply(members,function(m)predict_one(m$tree,queries[i,,drop=FALSE])),w,task,classes,option(a,'aggregation','probabilities'))));oob<-lapply(seq_len(nrow(d)),function(i){app<-which(!vapply(members,function(m)d$id[i]%in%m$inbag,FALSE));pp<-combine(lapply(app,function(j)predict_one(members[[j]]$tree,d[i,,drop=FALSE])),w[app],task,classes,option(a,'aggregation','probabilities'));c(list(id=d$id[i],applicable=app-1L,positiveMembers=sum(w[app]>0)),pp)});list(task=task,classes=classes,members=members,predictions=preds,outOfBag=scored(oob,d,task,classes))}\nboost<-function(a){if(option(a,'task','regression')!='regression')stop('regression boosting only');d<-normrows(a$rows,'regression');eligible<-d$weight>0&!is.na(d$y);W<-sum(d$weight[eligible]);if(!W)stop('positive eligible training');eta<-num(option(a,'learningRate','1/2'));stages<-option(a,'stages',3);if(is.null(stages)||stages!=floor(stages)||stages<0||stages>8||eta<0||eta>1)stop('supported rate/stages');initial<-if('initial'%in%names(a))num(a$initial)else sum(d$weight[eligible]*d$y[eligible])/W;train<-matrix(initial,nrow(d),stages+1L);query<-matrix(initial,nrow(a$queries),stages+1L);losses<-fits<-list();for(stage in 0:stages){sse<-sum(d$weight[eligible]*(d$y[eligible]-train[eligible,stage+1L])^2);losses[[stage+1L]]<-list(stage=stage,rawWeightedSSE=sse,MSE=sse/W,meanHalfSquaredLoss=sse/(2*W));if(stage==stages)break;residual<-d;residual$y<-d$y-train[,stage+1L];tree<-fit(residual,a,'regression',character());h<-vapply(seq_len(nrow(d)),function(i)predict_one(tree,d[i,,drop=FALSE])$prediction,0);qh<-vapply(seq_len(nrow(a$queries)),function(i)predict_one(tree,a$queries[i,,drop=FALSE])$prediction,0);stageRows<-lapply(seq_len(nrow(d)),function(i)list(id=d$id[i],before=train[i,stage+1L],residual=residual$y[i],negativeCoordinateDerivative=d$weight[i]*residual$y[i]/W,fit=h[i],addition=eta*h[i],after=train[i,stage+1L]+eta*h[i]));train[,stage+2L]<-train[,stage+1L]+eta*h;query[,stage+2L]<-query[,stage+1L]+eta*qh;norm<-sum(d$weight[eligible]*h[eligible]^2);fits[[stage+1L]]<-list(stage=stage+1L,tree=tree,rows=stageRows,queryFits=qh,norm=norm,predictedSSEDecrease=eta*(2-eta)*norm)};list(task='regression',initial=initial,learningRate=eta,stages=stages,training=train,queries=query,fits=fits,losses=losses,predictions=lapply(seq_len(nrow(a$queries)),function(i)list(id=a$queries$id[i],prediction=query[i,stages+1L],probabilities=numeric(),vote=NA_character_,prob=NA_character_)))}\nfixed_schedules<-function(ids,p,seed){state<-seed;choose<-function(n){limit<-floor(4294967296/n)*n;repeat{state<<-(1664525*state+1013904223)%%4294967296;if(state<limit)return(as.integer(state%%n))}};draws<-schedules<-list();for(member in 1:4){draws[[member]]<-vapply(seq_along(ids),function(i)ids[choose(length(ids))+1L],'');schedule<-setNames(vector('list',7),c('','L','R','LL','LR','RL','RR'));for(path in names(schedule)){order<-seq_len(p)-1L;if(p>1)for(j in seq(p-1L,1L)){k<-choose(j+1L);temp<-order[j+1L];order[j+1L]<-order[k+1L];order[k+1L]<-temp};schedule[[match(path,names(schedule))]]<-sort(order[seq_len(max(1L,floor(sqrt(p))))])};schedules[[member]]<-schedule};list(draws=draws,schedules=schedules)}\nread_sources<-function(src){read<-function(name)read.csv(file.path(src,name),check.names=FALSE,colClasses='character',na.strings=character(),fileEncoding='UTF-8-BOM');raw<-read('actual320-country-four-indicators-original-2020-2024.csv');country<-do.call(rbind,lapply(sort(unique(raw$countryISO3)),function(code)do.call(rbind,lapply(2020:2024,function(year){keys<-c('NY.GDP.PCAP.KD','NY.GDP.MKTP.KD.ZG','FP.CPI.TOTL.ZG','SP.DYN.LE00.IN');v<-vapply(keys,function(k)as.numeric(raw$originalValueToken[raw$countryISO3==code&raw$date==as.character(year)&raw$indicatorID==k]),0);data.frame(id=paste0(code,':',year),sourceRow=paste0(code,':',year),originalID=code,year=year,x0=v[1]/10000,x1=v[2],x2=v[3],y=v[4],weight=1,role=if(anyNA(v))'excluded'else if(year==2024)'outer-test'else'train')}))));raw<-read('actual3613-NLS-original52-fields-and-selection.csv');i<-seq_len(nrow(raw));x0<-suppressWarnings(as.numeric(raw$ed76));x1<-suppressWarnings(as.numeric(raw$age76));y<-suppressWarnings(as.numeric(raw$wage76))/100;person<-data.frame(id=paste0('person:',i),sourceRow=as.character(i),originalID=raw$id,x0=x0,x1=x1,y=y,weight=1,role=ifelse(is.na(x0)|is.na(x1)|is.na(y),'excluded',ifelse(i%%5==0,'outer-test','train')));raw<-read('actual3150-churn-original14-fields-and-selection.csv');i<-seq_len(nrow(raw));company<-data.frame(id=paste0('customer:',i),sourceRow=as.character(i),originalID='',x0=as.numeric(raw[['Call  Failure']]),x1=as.numeric(raw[['Subscription  Length']]),x2=as.numeric(raw[['Charge  Amount']]),y=raw$Churn,weight=1,role=ifelse(i%%5==0,'outer-test','train'));models<-list();for(index in 1:3){kind<-c('country','person','company')[index];d<-list(country,person,company)[[index]];task<-if(kind=='company')'classification'else'regression';s<-fixed_schedules(d$id[d$role=='train'],if(kind=='person')2L else 3L,20261102+7919*(index-1L));models[[kind]]<-list(records=d,task=task,classes=if(task=='classification')c('0','1')else character(),draws=s$draws,schedules=s$schedules,minLeaf=c(4L,50L,30L)[index])};models}\nrealdata<-function(models,kind,options=list()){if(is.null(options)||!is.list(options))stop('options object');m<-models[[kind]];d<-m$records;train<-d[d$role=='train',,drop=FALSE];test<-d[d$role=='outer-test',,drop=FALSE];method<-option(options,'method','forest');depth<-option(options,'maxDepth',2);count<-option(options,'memberCount',3);if(!method%in%c('bagging','forest','boost'))stop('known method');a<-list(rows=train,queries=test,task=m$task,classes=m$classes,maxDepth=depth,minLeaf=option(options,'minLeaf',m$minLeaf),minLeafWeight=0,minGain=0,missingRoute='best',learningRate=option(options,'learningRate','1/2'),stages=option(options,'stages',3));if(method=='boost')result<-boost(a)else{a$bootstrapDraws<-m$draws[seq_len(count)];a$nodeFeatures<-lapply(m$schedules[seq_len(count)],function(s)s[nchar(names(s))<depth]);result<-ensemble(a,method=='forest')};outer<-scored(result$predictions,normrows(test,m$task),m$task,m$classes);st<-stat(normrows(train,m$task),m$task,m$classes);constant<-list(prediction=st$pred,probabilities=st$p,vote=st$pred,prob=st$pred);baseline<-scored(lapply(test$id,function(id)c(list(id=id),constant)),normrows(test,m$task),m$task,m$classes);list(kind=kind,method=method,settings=a,train=train,test=test,result=result,outer=outer,baseline=baseline)}\nAPI<-\"variance\"\nINPUT<-list(B=4,marginalVariance=4,rho=\"-1/3\")\n\nrun_fixed<-function(api,a,out,src){\n r<-if(api=='variance')variance(a)else if(api=='aggregate')aggregate(a)else if(api%in%c('bagging','forest'))ensemble(a,api=='forest')else if(api=='boost')boost(a)else realdata(read_sources(src),a$kind)\n dir.create(out,recursive=TRUE,showWarnings=FALSE);summary<-list();points<-list();add<-function(x,y,s){if(!is.null(y)&&!is.na(y))points[[length(points)+1L]]<<-data.frame(x=x,y=as.numeric(y),series=s)}\n if(api=='variance'){summary<-r[c('B','varianceOfMean')];add(r$B,r$varianceOfMean,'Specified finite-B variance');xl<-'Number of members B';yl<-'Variance, stipulated units squared';title<-'Declared covariance model, not fitted trees'\n }else if(api=='aggregate'){p<-r$predictions[[1]];summary<-list(selectedPrediction=p$prediction);classification<-identical(a$task,'classification');if(classification){summary<-c(summary,list(voteLabel=p$vote,probabilityLabel=p$prob,meanProbability1=p$probabilities[2]));add(1,p$probabilities[2],'Mean probability of class 1');add(2,p$votes[2],'Label-vote share of class 1');xl<-'Aggregation (1=probability, 2=vote)';yl<-'Probability or vote share'}else{for(i in seq_along(a$members))add(i,num(a$members[[i]]$predictions$value[1]),'Member prediction');add(3,p$prediction,'Weighted mean');xl<-'Member 1, member 2, aggregate 3';yl<-'Prediction, assumed units'};title<-'Votes and probabilities are distinct objects'\n }else if(api%in%c('bagging','forest')){summary<-list(queryPrediction=r$predictions[[1]]$prediction,OOB.scoreable=r$outOfBag$eligibleRows,OOB.meanLoss=r$outOfBag$meanLoss);for(i in seq_len(nrow(a$rows)))add(i,a$rows$y[i],'Observed training outcome');for(i in seq_along(r$outOfBag$rows))add(i,r$outOfBag$rows[[i]]$prediction,'OOB prediction, when defined');xl<-'Original training ID order';yl<-'Outcome, assumed units';title<-'Repeated draws and ID-level OOB membership'\n }else if(api=='boost'){summary<-list(initial=r$initial,finalMSE=r$losses[[length(r$losses)]]$MSE,stages=r$stages);for(v in r$losses)add(v$stage,v$MSE,'Training MSE');xl<-'Boosting stage (0=initial)';yl<-'Weighted MSE, outcome units squared';title<-'Training descent does not certify held-out gain'\n }else{summary<-list(outer.scoreable=r$outer$eligibleRows,outer.meanLoss=r$outer$meanLoss,baseline.meanLoss=r$baseline$meanLoss,OOB.scoreable=r$result$outOfBag$eligibleRows,OOB.meanLoss=r$result$outOfBag$meanLoss);for(i in seq_along(r$outer$rows)){p<-r$outer$rows[[i]];add(i,as.numeric(p$actual),'Observed outcome');add(i,if(a$kind=='company')p$probabilities[2]else p$prediction,if(a$kind=='company')'Forest probability of class 1'else'Forest prediction')};xl<-'Outer-test source order, not a time path';yl<-if(a$kind=='company')'Churn label / probability'else if(a$kind=='country')'Period life expectancy, years'else'Nominal 1976 USD per hour';title<-'Fixed forest; outer labels did not fit the trees'}\n display<-function(v)if(is.null(v)||is.na(v))'undefined'else sprintf('%.9f',as.numeric(v));write.csv(data.frame(metric=names(summary),value=vapply(summary,display,'')),file.path(out,'summary.csv'),row.names=FALSE);pp<-do.call(rbind,points);write.csv(pp,file.path(out,'plot-points.csv'),row.names=FALSE);dput(r,file.path(out,'full-result.Rtext'));svg(file.path(out,'plot.svg'),width=5.6,height=4.6,pointsize=14);par(mar=c(5.8,5.8,5.3,1.2),mgp=c(3.7,1,0));xr<-range(pp$x);yr<-range(pp$y);if(diff(xr)==0)xr<-xr+c(-.5,.5);if(diff(yr)==0)yr<-yr+c(-.5,.5);plot(xr,yr,type='n',xlab=xl,ylab=yl,cex.lab=.78,axes=FALSE);axis(1,at=pretty(xr,3));axis(2,at=pretty(yr,4),las=1,cex.axis=.82);box();grid(col='#dddddd');cols<-c('#355c72','#a55336','#507956','#78568b');ss<-unique(pp$series);for(i in seq_along(ss)){v<-pp[pp$series==ss[i],];points(v$x,v$y,pch=16,cex=if(nrow(v)>100).35 else .85,col=adjustcolor(cols[i],if(nrow(v)>100).5 else 1))};legend('topleft',legend=ss,col=cols[seq_along(ss)],lty=0,pch=16,cex=.65,bty='n',inset=c(0,-.32),xpd=NA);mtext(title,side=3,line=3.9,cex=.6);dev.off();cat(paste(names(summary),vapply(summary,display,''),sep='=',collapse=', '),'\\n')\n}\nargs<-commandArgs(trailingOnly=TRUE)\ntryCatch(run_fixed(API,INPUT,if(length(args))args[1]else'fixed-results',if(length(args)>1)args[2]else'ml09-sources'),error=function(e){cat('Rejected declared input: ',conditionMessage(e),'\\n',file=stderr());quit(status=2)})\n",
        "code": "# ML09 base-R reproduction from native original-field CSVs.\n# Rscript ml09-public-analysis.R ml09-sources results-r\n# Separately written vectorized direct-centered squared/Gini losses.\n# No Python/JS/model-contract/stored-answer/derived-result reader or package.\n# Numeric arithmetic is binary64:1e-12 relative tie tolerance stabilizes exact\n# source ties,but does not certify tiny margins/underflow like Fraction JS/Python.\n# Data-frame rows use x0,x1,...,y,weight; original IDs remain attached to draws.\noptions(stringsAsFactors=FALSE,digits=17)\nnum<-function(v){if(is.null(v)||length(v)!=1||is.na(v))stop('numeric parameter required, not explicit NULL');p<-strsplit(as.character(v),'/',fixed=TRUE)[[1]];z<-if(length(p)==2)as.numeric(p[1])/as.numeric(p[2])else as.numeric(v);if(!is.finite(z))stop('finite numeric parameter');z}\noption<-function(a,k,default){if(k%in%names(a))a[[k]]else default}\nnormrows<-function(d,task){if(!'weight'%in%names(d))d$weight<-1;if(!'id'%in%names(d))d$id<-as.character(seq_len(nrow(d))-1);d$weight<-as.numeric(d$weight);if(anyNA(d$weight)||any(d$weight<0))stop('nonnegative weights');if(task=='regression')d$y<-as.numeric(d$y)else d$y<-as.character(d$y);d}\nstat<-function(d,task,classes){W<-sum(d$weight);mu<-if(task=='regression'&&W)sum(d$weight*d$y)/W else NA_real_;p<-if(task=='classification'&&W)vapply(classes,function(c)sum(d$weight[d$y==c])/W,0)else numeric();risk<-if(task=='regression'&&W)sum(d$weight*(d$y-mu)^2)else W*sum(p*(1-p));list(n=nrow(d),w=W,mu=mu,p=unname(p),risk=risk,pred=if(task=='regression')mu else if(W)classes[which.max(p)]else NA_character_)}\nfit<-function(d,a,task,classes,schedule=NULL){d<-d[d$weight>0&!is.na(d$y),,drop=FALSE];if(!nrow(d))stop('positive observed training');W<-sum(d$weight);depth<-option(a,'maxDepth',2);minimum<-option(a,'minLeaf',1);minmass<-num(option(a,'minLeafWeight',0));mingain<-num(option(a,'minGain',0));route<-option(a,'missingRoute','best');features<-grep('^x[0-9]+$',names(d),value=TRUE)\n build<-function(rr,level,path){st<-stat(rr,task,classes);node<-list(rows=rr,st=st,split=NULL,left=NULL,right=NULL,path=path);if(level==depth)return(node);best<-NULL;allowed<-if(is.null(schedule))seq_along(features)-1L else schedule[[match(path,names(schedule))]]\n  for(j in seq_along(features)-1L){if(!j%in%allowed)next;v<-rr[[features[j+1L]]];values<-sort(unique(v[!is.na(v)]));candidates<-list()\n   if(length(values)>1)for(k in seq_len(length(values)-1L)){threshold<-(values[k]+values[k+1L])/2;missing<-is.na(v);left<-!missing&v<=threshold;right<-!missing&v>threshold;directions<-if(route!='best')route else if(any(missing))c('left','right')else if(sum(left)>=sum(right))'left'else'right';for(direction in directions)candidates[[length(candidates)+1L]]<-list(kind='threshold',threshold=threshold,missingRoute=direction,left=if(direction=='left')left|missing else left,right=if(direction=='right')right|missing else right)}\n   if(anyNA(v)&&any(!is.na(v)))candidates[[length(candidates)+1L]]<-list(kind='missing-only',threshold=NA_real_,missingRoute='left',left=is.na(v),right=!is.na(v))\n   for(candidate in candidates){l<-rr[candidate$left,,drop=FALSE];r<-rr[candidate$right,,drop=FALSE];ls<-stat(l,task,classes);rs<-stat(r,task,classes);if(min(ls$n,rs$n)<minimum||min(ls$w,rs$w)<minmass||min(ls$w,rs$w)<=0)next;gain<-(st$risk-ls$risk-rs$risk)/W;tol<-1e-12*max(1,abs(gain),if(is.null(best))0 else abs(best$gain));if(is.null(best)||gain>best$gain+tol)best<-c(candidate,list(feature=j,gain=gain,l=l,r=r))}\n  }\n  if(!is.null(best)&&best$gain>max(mingain,1e-12)){node$split<-best;node$left<-build(best$l,level+1L,paste0(path,'L'));node$right<-build(best$r,level+1L,paste0(path,'R'))};node\n };build(d,0L,'')\n}\npredict_one<-function(tree,row){n<-tree;while(!is.null(n$split)){s<-n$split;v<-as.numeric(row[[paste0('x',s$feature)]]);left<-if(s$kind=='missing-only')is.na(v)else if(is.na(v))s$missingRoute=='left'else v<=s$threshold;n<-if(left)n$left else n$right};list(prediction=n$st$pred,probabilities=n$st$p)}\ncombine<-function(pp,w,task,classes,mode='probabilities'){W<-sum(w);if(!length(pp)||!W)return(list(prediction=if(task=='regression')NA_real_ else NA_character_,probabilities=numeric(),vote=NA_character_,prob=NA_character_));if(task=='regression')return(list(prediction=sum(vapply(pp,function(p)p$prediction,0)*w)/W,probabilities=numeric(),vote=NA_character_,prob=NA_character_));votes<-vapply(classes,function(c)sum(w[vapply(pp,function(p)p$prediction==c,FALSE)])/W,0);probs<-vapply(seq_along(classes),function(j)sum(vapply(pp,function(p)p$probabilities[j],0)*w)/W,0);vote<-classes[which.max(votes)];prob<-classes[which.max(probs)];list(prediction=if(mode=='votes')vote else prob,probabilities=unname(probs),vote=vote,prob=prob,votes=unname(votes))}\nvariance<-function(a){B<-num(a$B);v<-num(a$marginalVariance);rho<-num(option(a,'rho',0));if(B<1||B!=floor(B)||v<0)stop('integer B/nonnegative variance');if(B>1&&v>0&&(rho< -1/(B-1)||rho>1))stop('PSD correlation');list(B=B,marginalVariance=v,correlationApplicable=B>1&&v>0,varianceOfMean=if(B==1)v else v*(1+(B-1)*rho)/B)}\naggregate<-function(a){task<-option(a,'task','regression');classes<-option(a,'classes',character());w<-vapply(option(a,'memberWeights',as.list(rep(1,length(a$members)))),num,0);if(any(w<0)||sum(w)<=0)stop('positive member mass');ids<-a$members[[1]]$predictions$id;pp<-lapply(ids,function(id){members<-lapply(a$members,function(m){r<-m$predictions[match(id,m$predictions$id),,drop=FALSE];if(task=='regression')list(prediction=num(r$value),probabilities=numeric())else list(prediction=as.character(r$label),probabilities=as.numeric(r[paste0('p',seq_along(classes)-1L)]))});c(list(id=id),combine(members,w,task,classes,option(a,'aggregation','probabilities')))});list(task=task,classes=classes,predictions=pp)}\nscored<-function(preds,d,task,classes){W<-loss<-absolute<-errors<-voteerrors<-0;count<-0L;out<-lapply(seq_len(nrow(d)),function(i){r<-d[i,,drop=FALSE];p<-preds[[i]];ok<-!is.na(p$prediction)&&!is.na(r$y)&&r$weight>0;value<-NA_real_;if(ok){count<<-count+1L;W<<-W+r$weight;if(task=='regression'){e<-r$y-p$prediction;value<-e*e;absolute<<-absolute+r$weight*abs(e)}else{value<-sum((p$probabilities-as.numeric(classes==r$y))^2);errors<<-errors+r$weight*(p$prediction!=r$y);voteerrors<<-voteerrors+r$weight*(p$vote!=r$y)};loss<<-loss+r$weight*value};c(p,list(actual=r$y,weight=r$weight,scoreEligible=ok,loss=value))});list(rows=out,eligibleRows=count,weight=W,totalLoss=loss,meanLoss=if(W)loss/W else NA_real_,MAE=if(W&&task=='regression')absolute/W else NA_real_,errorRate=if(W&&task=='classification')errors/W else NA_real_,labelVoteErrorRate=if(W&&task=='classification')voteerrors/W else NA_real_)}\nensemble<-function(a,forest=FALSE){task<-option(a,'task','regression');classes<-option(a,'classes',character());d<-normrows(a$rows,task);w<-vapply(option(a,'memberWeights',as.list(rep(1,length(a$bootstrapDraws)))),num,0);if(any(w<0)||sum(w)<=0)stop('positive member mass');members<-lapply(seq_along(a$bootstrapDraws),function(i){draw<-a$bootstrapDraws[[i]];indices<-match(draw,d$id);if(anyNA(indices))stop('unknown draw source');tree<-fit(d[indices,,drop=FALSE],a,task,classes,if(forest)a$nodeFeatures[[i]]else NULL);list(tree=tree,draw=draw,inbag=unique(draw),weight=w[i])});queries<-a$queries;preds<-lapply(seq_len(nrow(queries)),function(i)c(list(id=queries$id[i]),combine(lapply(members,function(m)predict_one(m$tree,queries[i,,drop=FALSE])),w,task,classes,option(a,'aggregation','probabilities'))));oob<-lapply(seq_len(nrow(d)),function(i){app<-which(!vapply(members,function(m)d$id[i]%in%m$inbag,FALSE));pp<-combine(lapply(app,function(j)predict_one(members[[j]]$tree,d[i,,drop=FALSE])),w[app],task,classes,option(a,'aggregation','probabilities'));c(list(id=d$id[i],applicable=app-1L,positiveMembers=sum(w[app]>0)),pp)});list(task=task,classes=classes,members=members,predictions=preds,outOfBag=scored(oob,d,task,classes))}\nboost<-function(a){if(option(a,'task','regression')!='regression')stop('regression boosting only');d<-normrows(a$rows,'regression');eligible<-d$weight>0&!is.na(d$y);W<-sum(d$weight[eligible]);if(!W)stop('positive eligible training');eta<-num(option(a,'learningRate','1/2'));stages<-option(a,'stages',3);if(is.null(stages)||stages!=floor(stages)||stages<0||stages>8||eta<0||eta>1)stop('supported rate/stages');initial<-if('initial'%in%names(a))num(a$initial)else sum(d$weight[eligible]*d$y[eligible])/W;train<-matrix(initial,nrow(d),stages+1L);query<-matrix(initial,nrow(a$queries),stages+1L);losses<-fits<-list();for(stage in 0:stages){sse<-sum(d$weight[eligible]*(d$y[eligible]-train[eligible,stage+1L])^2);losses[[stage+1L]]<-list(stage=stage,rawWeightedSSE=sse,MSE=sse/W,meanHalfSquaredLoss=sse/(2*W));if(stage==stages)break;residual<-d;residual$y<-d$y-train[,stage+1L];tree<-fit(residual,a,'regression',character());h<-vapply(seq_len(nrow(d)),function(i)predict_one(tree,d[i,,drop=FALSE])$prediction,0);qh<-vapply(seq_len(nrow(a$queries)),function(i)predict_one(tree,a$queries[i,,drop=FALSE])$prediction,0);stageRows<-lapply(seq_len(nrow(d)),function(i)list(id=d$id[i],before=train[i,stage+1L],residual=residual$y[i],negativeCoordinateDerivative=d$weight[i]*residual$y[i]/W,fit=h[i],addition=eta*h[i],after=train[i,stage+1L]+eta*h[i]));train[,stage+2L]<-train[,stage+1L]+eta*h;query[,stage+2L]<-query[,stage+1L]+eta*qh;norm<-sum(d$weight[eligible]*h[eligible]^2);fits[[stage+1L]]<-list(stage=stage+1L,tree=tree,rows=stageRows,queryFits=qh,norm=norm,predictedSSEDecrease=eta*(2-eta)*norm)};list(task='regression',initial=initial,learningRate=eta,stages=stages,training=train,queries=query,fits=fits,losses=losses,predictions=lapply(seq_len(nrow(a$queries)),function(i)list(id=a$queries$id[i],prediction=query[i,stages+1L],probabilities=numeric(),vote=NA_character_,prob=NA_character_)))}\nfixed_schedules<-function(ids,p,seed){state<-seed;choose<-function(n){limit<-floor(4294967296/n)*n;repeat{state<<-(1664525*state+1013904223)%%4294967296;if(state<limit)return(as.integer(state%%n))}};draws<-schedules<-list();for(member in 1:4){draws[[member]]<-vapply(seq_along(ids),function(i)ids[choose(length(ids))+1L],'');schedule<-setNames(vector('list',7),c('','L','R','LL','LR','RL','RR'));for(path in names(schedule)){order<-seq_len(p)-1L;if(p>1)for(j in seq(p-1L,1L)){k<-choose(j+1L);temp<-order[j+1L];order[j+1L]<-order[k+1L];order[k+1L]<-temp};schedule[[match(path,names(schedule))]]<-sort(order[seq_len(max(1L,floor(sqrt(p))))])};schedules[[member]]<-schedule};list(draws=draws,schedules=schedules)}\nread_sources<-function(src){read<-function(name)read.csv(file.path(src,name),check.names=FALSE,colClasses='character',na.strings=character(),fileEncoding='UTF-8-BOM');raw<-read('actual320-country-four-indicators-original-2020-2024.csv');country<-do.call(rbind,lapply(sort(unique(raw$countryISO3)),function(code)do.call(rbind,lapply(2020:2024,function(year){keys<-c('NY.GDP.PCAP.KD','NY.GDP.MKTP.KD.ZG','FP.CPI.TOTL.ZG','SP.DYN.LE00.IN');v<-vapply(keys,function(k)as.numeric(raw$originalValueToken[raw$countryISO3==code&raw$date==as.character(year)&raw$indicatorID==k]),0);data.frame(id=paste0(code,':',year),sourceRow=paste0(code,':',year),originalID=code,year=year,x0=v[1]/10000,x1=v[2],x2=v[3],y=v[4],weight=1,role=if(anyNA(v))'excluded'else if(year==2024)'outer-test'else'train')}))));raw<-read('actual3613-NLS-original52-fields-and-selection.csv');i<-seq_len(nrow(raw));x0<-suppressWarnings(as.numeric(raw$ed76));x1<-suppressWarnings(as.numeric(raw$age76));y<-suppressWarnings(as.numeric(raw$wage76))/100;person<-data.frame(id=paste0('person:',i),sourceRow=as.character(i),originalID=raw$id,x0=x0,x1=x1,y=y,weight=1,role=ifelse(is.na(x0)|is.na(x1)|is.na(y),'excluded',ifelse(i%%5==0,'outer-test','train')));raw<-read('actual3150-churn-original14-fields-and-selection.csv');i<-seq_len(nrow(raw));company<-data.frame(id=paste0('customer:',i),sourceRow=as.character(i),originalID='',x0=as.numeric(raw[['Call  Failure']]),x1=as.numeric(raw[['Subscription  Length']]),x2=as.numeric(raw[['Charge  Amount']]),y=raw$Churn,weight=1,role=ifelse(i%%5==0,'outer-test','train'));models<-list();for(index in 1:3){kind<-c('country','person','company')[index];d<-list(country,person,company)[[index]];task<-if(kind=='company')'classification'else'regression';s<-fixed_schedules(d$id[d$role=='train'],if(kind=='person')2L else 3L,20261102+7919*(index-1L));models[[kind]]<-list(records=d,task=task,classes=if(task=='classification')c('0','1')else character(),draws=s$draws,schedules=s$schedules,minLeaf=c(4L,50L,30L)[index])};models}\nrealdata<-function(models,kind,options=list()){if(is.null(options)||!is.list(options))stop('options object');m<-models[[kind]];d<-m$records;train<-d[d$role=='train',,drop=FALSE];test<-d[d$role=='outer-test',,drop=FALSE];method<-option(options,'method','forest');depth<-option(options,'maxDepth',2);count<-option(options,'memberCount',3);if(!method%in%c('bagging','forest','boost'))stop('known method');a<-list(rows=train,queries=test,task=m$task,classes=m$classes,maxDepth=depth,minLeaf=option(options,'minLeaf',m$minLeaf),minLeafWeight=0,minGain=0,missingRoute='best',learningRate=option(options,'learningRate','1/2'),stages=option(options,'stages',3));if(method=='boost')result<-boost(a)else{a$bootstrapDraws<-m$draws[seq_len(count)];a$nodeFeatures<-lapply(m$schedules[seq_len(count)],function(s)s[nchar(names(s))<depth]);result<-ensemble(a,method=='forest')};outer<-scored(result$predictions,normrows(test,m$task),m$task,m$classes);st<-stat(normrows(train,m$task),m$task,m$classes);constant<-list(prediction=st$pred,probabilities=st$p,vote=st$pred,prob=st$pred);baseline<-scored(lapply(test$id,function(id)c(list(id=id),constant)),normrows(test,m$task),m$task,m$classes);list(kind=kind,method=method,settings=a,train=train,test=test,result=result,outer=outer,baseline=baseline)}\nAPI<-\"variance\"\nINPUT<-list(B=4,marginalVariance=4,rho=\"-1/3\")\n\nrun_fixed<-function(api,a,out,src){\n r<-if(api=='variance')variance(a)else if(api=='aggregate')aggregate(a)else if(api%in%c('bagging','forest'))ensemble(a,api=='forest')else if(api=='boost')boost(a)else realdata(read_sources(src),a$kind)\n dir.create(out,recursive=TRUE,showWarnings=FALSE);summary<-list();points<-list();add<-function(x,y,s){if(!is.null(y)&&!is.na(y))points[[length(points)+1L]]<<-data.frame(x=x,y=as.numeric(y),series=s)}\n if(api=='variance'){summary<-r[c('B','varianceOfMean')];add(r$B,r$varianceOfMean,'Specified finite-B variance');xl<-'Number of members B';yl<-'Variance, stipulated units squared';title<-'Declared covariance model, not fitted trees'\n }else if(api=='aggregate'){p<-r$predictions[[1]];summary<-list(selectedPrediction=p$prediction);classification<-identical(a$task,'classification');if(classification){summary<-c(summary,list(voteLabel=p$vote,probabilityLabel=p$prob,meanProbability1=p$probabilities[2]));add(1,p$probabilities[2],'Mean probability of class 1');add(2,p$votes[2],'Label-vote share of class 1');xl<-'Aggregation (1=probability, 2=vote)';yl<-'Probability or vote share'}else{for(i in seq_along(a$members))add(i,num(a$members[[i]]$predictions$value[1]),'Member prediction');add(3,p$prediction,'Weighted mean');xl<-'Member 1, member 2, aggregate 3';yl<-'Prediction, assumed units'};title<-'Votes and probabilities are distinct objects'\n }else if(api%in%c('bagging','forest')){summary<-list(queryPrediction=r$predictions[[1]]$prediction,OOB.scoreable=r$outOfBag$eligibleRows,OOB.meanLoss=r$outOfBag$meanLoss);for(i in seq_len(nrow(a$rows)))add(i,a$rows$y[i],'Observed training outcome');for(i in seq_along(r$outOfBag$rows))add(i,r$outOfBag$rows[[i]]$prediction,'OOB prediction, when defined');xl<-'Original training ID order';yl<-'Outcome, assumed units';title<-'Repeated draws and ID-level OOB membership'\n }else if(api=='boost'){summary<-list(initial=r$initial,finalMSE=r$losses[[length(r$losses)]]$MSE,stages=r$stages);for(v in r$losses)add(v$stage,v$MSE,'Training MSE');xl<-'Boosting stage (0=initial)';yl<-'Weighted MSE, outcome units squared';title<-'Training descent does not certify held-out gain'\n }else{summary<-list(outer.scoreable=r$outer$eligibleRows,outer.meanLoss=r$outer$meanLoss,baseline.meanLoss=r$baseline$meanLoss,OOB.scoreable=r$result$outOfBag$eligibleRows,OOB.meanLoss=r$result$outOfBag$meanLoss);for(i in seq_along(r$outer$rows)){p<-r$outer$rows[[i]];add(i,as.numeric(p$actual),'Observed outcome');add(i,if(a$kind=='company')p$probabilities[2]else p$prediction,if(a$kind=='company')'Forest probability of class 1'else'Forest prediction')};xl<-'Outer-test source order, not a time path';yl<-if(a$kind=='company')'Churn label / probability'else if(a$kind=='country')'Period life expectancy, years'else'Nominal 1976 USD per hour';title<-'Fixed forest; outer labels did not fit the trees'}\n display<-function(v)if(is.null(v)||is.na(v))'undefined'else sprintf('%.9f',as.numeric(v));write.csv(data.frame(metric=names(summary),value=vapply(summary,display,'')),file.path(out,'summary.csv'),row.names=FALSE);pp<-do.call(rbind,points);write.csv(pp,file.path(out,'plot-points.csv'),row.names=FALSE);dput(r,file.path(out,'full-result.Rtext'));svg(file.path(out,'plot.svg'),width=5.6,height=4.6,pointsize=14);par(mar=c(5.8,5.8,5.3,1.2),mgp=c(3.7,1,0));xr<-range(pp$x);yr<-range(pp$y);if(diff(xr)==0)xr<-xr+c(-.5,.5);if(diff(yr)==0)yr<-yr+c(-.5,.5);plot(xr,yr,type='n',xlab=xl,ylab=yl,cex.lab=.78,axes=FALSE);axis(1,at=pretty(xr,3));axis(2,at=pretty(yr,4),las=1,cex.axis=.82);box();grid(col='#dddddd');cols<-c('#355c72','#a55336','#507956','#78568b');ss<-unique(pp$series);for(i in seq_along(ss)){v<-pp[pp$series==ss[i],];points(v$x,v$y,pch=16,cex=if(nrow(v)>100).35 else .85,col=adjustcolor(cols[i],if(nrow(v)>100).5 else 1))};legend('topleft',legend=ss,col=cols[seq_along(ss)],lty=0,pch=16,cex=.65,bty='n',inset=c(0,-.32),xpd=NA);mtext(title,side=3,line=3.9,cex=.6);dev.off();cat(paste(names(summary),vapply(summary,display,''),sep='=',collapse=', '),'\\n')\n}\nargs<-commandArgs(trailingOnly=TRUE)\ntryCatch(run_fixed(API,INPUT,if(length(args))args[1]else'fixed-results',if(length(args)>1)args[2]else'ml09-sources'),error=function(e){cat('Rejected declared input: ',conditionMessage(e),'\\n',file=stderr());quit(status=2)})\n",
        "inputFiles": [],
        "input": {
          "B": 4,
          "marginalVariance": 4,
          "rho": "-1/3"
        },
        "returnCode": 0,
        "expectedFailure": false,
        "stdout": "B=4.000000000, varianceOfMean=0.000000000 \n",
        "stderr": "During startup - Warning messages:\n1: Setting LC_COLLATE=C.UTF-8 failed \n2: Setting LC_CTYPE=C.UTF-8 failed \n3: Setting LC_MONETARY=C.UTF-8 failed \n4: Setting LC_TIME=C.UTF-8 failed \n",
        "summary": {
          "B": "4.000000000",
          "varianceOfMean": "0.000000000"
        },
        "plotPoints": [
          {
            "x": "4",
            "y": "0",
            "series": "Specified finite-B variance"
          }
        ],
        "plotFile": "ml09-fixed-results/variance-PSD-boundary-r/plot.svg",
        "plotSHA256": "0a3c593689ff37f0788e6f7aa4ca7717a554650ee2f476930dbfaf8790b635f2",
        "files": [
          {
            "file": "ml09-fixed-results/variance-PSD-boundary-r/full-result.Rtext",
            "sha256": "4e687462a973be158799fd9d51a94c954b0ba8fe7de55d878d08f793b11c3ae6"
          },
          {
            "file": "ml09-fixed-results/variance-PSD-boundary-r/plot-points.csv",
            "sha256": "3ab24bf496f12da33878416881534daa18abc248d3d95df99373d04c4152836d"
          },
          {
            "file": "ml09-fixed-results/variance-PSD-boundary-r/plot.svg",
            "sha256": "0a3c593689ff37f0788e6f7aa4ca7717a554650ee2f476930dbfaf8790b635f2"
          },
          {
            "file": "ml09-fixed-results/variance-PSD-boundary-r/summary.csv",
            "sha256": "af755e1832f2951334616e95cbf576a41ccf1c4be82bfa8693350f74322ba832"
          }
        ],
        "scope": "Actually executed self-contained fixed example; current web controls execute separately. Python Fraction and finite-precision base R. Author gate, not independent peer."
      },
      "reject-non-PSD": {
        "api": "variance",
        "variant": "reject-non-PSD",
        "language": "r",
        "codeFile": "ml09-code/variance-reject-non-PSD.R",
        "codeSHA256": "3c7c8f0047cd5249ad5abf1c3c89c33cdf748adff4dce9518af6d4f22b02626d",
        "codeText": "# ML09 base-R reproduction from native original-field CSVs.\n# Rscript ml09-public-analysis.R ml09-sources results-r\n# Separately written vectorized direct-centered squared/Gini losses.\n# No Python/JS/model-contract/stored-answer/derived-result reader or package.\n# Numeric arithmetic is binary64:1e-12 relative tie tolerance stabilizes exact\n# source ties,but does not certify tiny margins/underflow like Fraction JS/Python.\n# Data-frame rows use x0,x1,...,y,weight; original IDs remain attached to draws.\noptions(stringsAsFactors=FALSE,digits=17)\nnum<-function(v){if(is.null(v)||length(v)!=1||is.na(v))stop('numeric parameter required, not explicit NULL');p<-strsplit(as.character(v),'/',fixed=TRUE)[[1]];z<-if(length(p)==2)as.numeric(p[1])/as.numeric(p[2])else as.numeric(v);if(!is.finite(z))stop('finite numeric parameter');z}\noption<-function(a,k,default){if(k%in%names(a))a[[k]]else default}\nnormrows<-function(d,task){if(!'weight'%in%names(d))d$weight<-1;if(!'id'%in%names(d))d$id<-as.character(seq_len(nrow(d))-1);d$weight<-as.numeric(d$weight);if(anyNA(d$weight)||any(d$weight<0))stop('nonnegative weights');if(task=='regression')d$y<-as.numeric(d$y)else d$y<-as.character(d$y);d}\nstat<-function(d,task,classes){W<-sum(d$weight);mu<-if(task=='regression'&&W)sum(d$weight*d$y)/W else NA_real_;p<-if(task=='classification'&&W)vapply(classes,function(c)sum(d$weight[d$y==c])/W,0)else numeric();risk<-if(task=='regression'&&W)sum(d$weight*(d$y-mu)^2)else W*sum(p*(1-p));list(n=nrow(d),w=W,mu=mu,p=unname(p),risk=risk,pred=if(task=='regression')mu else if(W)classes[which.max(p)]else NA_character_)}\nfit<-function(d,a,task,classes,schedule=NULL){d<-d[d$weight>0&!is.na(d$y),,drop=FALSE];if(!nrow(d))stop('positive observed training');W<-sum(d$weight);depth<-option(a,'maxDepth',2);minimum<-option(a,'minLeaf',1);minmass<-num(option(a,'minLeafWeight',0));mingain<-num(option(a,'minGain',0));route<-option(a,'missingRoute','best');features<-grep('^x[0-9]+$',names(d),value=TRUE)\n build<-function(rr,level,path){st<-stat(rr,task,classes);node<-list(rows=rr,st=st,split=NULL,left=NULL,right=NULL,path=path);if(level==depth)return(node);best<-NULL;allowed<-if(is.null(schedule))seq_along(features)-1L else schedule[[match(path,names(schedule))]]\n  for(j in seq_along(features)-1L){if(!j%in%allowed)next;v<-rr[[features[j+1L]]];values<-sort(unique(v[!is.na(v)]));candidates<-list()\n   if(length(values)>1)for(k in seq_len(length(values)-1L)){threshold<-(values[k]+values[k+1L])/2;missing<-is.na(v);left<-!missing&v<=threshold;right<-!missing&v>threshold;directions<-if(route!='best')route else if(any(missing))c('left','right')else if(sum(left)>=sum(right))'left'else'right';for(direction in directions)candidates[[length(candidates)+1L]]<-list(kind='threshold',threshold=threshold,missingRoute=direction,left=if(direction=='left')left|missing else left,right=if(direction=='right')right|missing else right)}\n   if(anyNA(v)&&any(!is.na(v)))candidates[[length(candidates)+1L]]<-list(kind='missing-only',threshold=NA_real_,missingRoute='left',left=is.na(v),right=!is.na(v))\n   for(candidate in candidates){l<-rr[candidate$left,,drop=FALSE];r<-rr[candidate$right,,drop=FALSE];ls<-stat(l,task,classes);rs<-stat(r,task,classes);if(min(ls$n,rs$n)<minimum||min(ls$w,rs$w)<minmass||min(ls$w,rs$w)<=0)next;gain<-(st$risk-ls$risk-rs$risk)/W;tol<-1e-12*max(1,abs(gain),if(is.null(best))0 else abs(best$gain));if(is.null(best)||gain>best$gain+tol)best<-c(candidate,list(feature=j,gain=gain,l=l,r=r))}\n  }\n  if(!is.null(best)&&best$gain>max(mingain,1e-12)){node$split<-best;node$left<-build(best$l,level+1L,paste0(path,'L'));node$right<-build(best$r,level+1L,paste0(path,'R'))};node\n };build(d,0L,'')\n}\npredict_one<-function(tree,row){n<-tree;while(!is.null(n$split)){s<-n$split;v<-as.numeric(row[[paste0('x',s$feature)]]);left<-if(s$kind=='missing-only')is.na(v)else if(is.na(v))s$missingRoute=='left'else v<=s$threshold;n<-if(left)n$left else n$right};list(prediction=n$st$pred,probabilities=n$st$p)}\ncombine<-function(pp,w,task,classes,mode='probabilities'){W<-sum(w);if(!length(pp)||!W)return(list(prediction=if(task=='regression')NA_real_ else NA_character_,probabilities=numeric(),vote=NA_character_,prob=NA_character_));if(task=='regression')return(list(prediction=sum(vapply(pp,function(p)p$prediction,0)*w)/W,probabilities=numeric(),vote=NA_character_,prob=NA_character_));votes<-vapply(classes,function(c)sum(w[vapply(pp,function(p)p$prediction==c,FALSE)])/W,0);probs<-vapply(seq_along(classes),function(j)sum(vapply(pp,function(p)p$probabilities[j],0)*w)/W,0);vote<-classes[which.max(votes)];prob<-classes[which.max(probs)];list(prediction=if(mode=='votes')vote else prob,probabilities=unname(probs),vote=vote,prob=prob,votes=unname(votes))}\nvariance<-function(a){B<-num(a$B);v<-num(a$marginalVariance);rho<-num(option(a,'rho',0));if(B<1||B!=floor(B)||v<0)stop('integer B/nonnegative variance');if(B>1&&v>0&&(rho< -1/(B-1)||rho>1))stop('PSD correlation');list(B=B,marginalVariance=v,correlationApplicable=B>1&&v>0,varianceOfMean=if(B==1)v else v*(1+(B-1)*rho)/B)}\naggregate<-function(a){task<-option(a,'task','regression');classes<-option(a,'classes',character());w<-vapply(option(a,'memberWeights',as.list(rep(1,length(a$members)))),num,0);if(any(w<0)||sum(w)<=0)stop('positive member mass');ids<-a$members[[1]]$predictions$id;pp<-lapply(ids,function(id){members<-lapply(a$members,function(m){r<-m$predictions[match(id,m$predictions$id),,drop=FALSE];if(task=='regression')list(prediction=num(r$value),probabilities=numeric())else list(prediction=as.character(r$label),probabilities=as.numeric(r[paste0('p',seq_along(classes)-1L)]))});c(list(id=id),combine(members,w,task,classes,option(a,'aggregation','probabilities')))});list(task=task,classes=classes,predictions=pp)}\nscored<-function(preds,d,task,classes){W<-loss<-absolute<-errors<-voteerrors<-0;count<-0L;out<-lapply(seq_len(nrow(d)),function(i){r<-d[i,,drop=FALSE];p<-preds[[i]];ok<-!is.na(p$prediction)&&!is.na(r$y)&&r$weight>0;value<-NA_real_;if(ok){count<<-count+1L;W<<-W+r$weight;if(task=='regression'){e<-r$y-p$prediction;value<-e*e;absolute<<-absolute+r$weight*abs(e)}else{value<-sum((p$probabilities-as.numeric(classes==r$y))^2);errors<<-errors+r$weight*(p$prediction!=r$y);voteerrors<<-voteerrors+r$weight*(p$vote!=r$y)};loss<<-loss+r$weight*value};c(p,list(actual=r$y,weight=r$weight,scoreEligible=ok,loss=value))});list(rows=out,eligibleRows=count,weight=W,totalLoss=loss,meanLoss=if(W)loss/W else NA_real_,MAE=if(W&&task=='regression')absolute/W else NA_real_,errorRate=if(W&&task=='classification')errors/W else NA_real_,labelVoteErrorRate=if(W&&task=='classification')voteerrors/W else NA_real_)}\nensemble<-function(a,forest=FALSE){task<-option(a,'task','regression');classes<-option(a,'classes',character());d<-normrows(a$rows,task);w<-vapply(option(a,'memberWeights',as.list(rep(1,length(a$bootstrapDraws)))),num,0);if(any(w<0)||sum(w)<=0)stop('positive member mass');members<-lapply(seq_along(a$bootstrapDraws),function(i){draw<-a$bootstrapDraws[[i]];indices<-match(draw,d$id);if(anyNA(indices))stop('unknown draw source');tree<-fit(d[indices,,drop=FALSE],a,task,classes,if(forest)a$nodeFeatures[[i]]else NULL);list(tree=tree,draw=draw,inbag=unique(draw),weight=w[i])});queries<-a$queries;preds<-lapply(seq_len(nrow(queries)),function(i)c(list(id=queries$id[i]),combine(lapply(members,function(m)predict_one(m$tree,queries[i,,drop=FALSE])),w,task,classes,option(a,'aggregation','probabilities'))));oob<-lapply(seq_len(nrow(d)),function(i){app<-which(!vapply(members,function(m)d$id[i]%in%m$inbag,FALSE));pp<-combine(lapply(app,function(j)predict_one(members[[j]]$tree,d[i,,drop=FALSE])),w[app],task,classes,option(a,'aggregation','probabilities'));c(list(id=d$id[i],applicable=app-1L,positiveMembers=sum(w[app]>0)),pp)});list(task=task,classes=classes,members=members,predictions=preds,outOfBag=scored(oob,d,task,classes))}\nboost<-function(a){if(option(a,'task','regression')!='regression')stop('regression boosting only');d<-normrows(a$rows,'regression');eligible<-d$weight>0&!is.na(d$y);W<-sum(d$weight[eligible]);if(!W)stop('positive eligible training');eta<-num(option(a,'learningRate','1/2'));stages<-option(a,'stages',3);if(is.null(stages)||stages!=floor(stages)||stages<0||stages>8||eta<0||eta>1)stop('supported rate/stages');initial<-if('initial'%in%names(a))num(a$initial)else sum(d$weight[eligible]*d$y[eligible])/W;train<-matrix(initial,nrow(d),stages+1L);query<-matrix(initial,nrow(a$queries),stages+1L);losses<-fits<-list();for(stage in 0:stages){sse<-sum(d$weight[eligible]*(d$y[eligible]-train[eligible,stage+1L])^2);losses[[stage+1L]]<-list(stage=stage,rawWeightedSSE=sse,MSE=sse/W,meanHalfSquaredLoss=sse/(2*W));if(stage==stages)break;residual<-d;residual$y<-d$y-train[,stage+1L];tree<-fit(residual,a,'regression',character());h<-vapply(seq_len(nrow(d)),function(i)predict_one(tree,d[i,,drop=FALSE])$prediction,0);qh<-vapply(seq_len(nrow(a$queries)),function(i)predict_one(tree,a$queries[i,,drop=FALSE])$prediction,0);stageRows<-lapply(seq_len(nrow(d)),function(i)list(id=d$id[i],before=train[i,stage+1L],residual=residual$y[i],negativeCoordinateDerivative=d$weight[i]*residual$y[i]/W,fit=h[i],addition=eta*h[i],after=train[i,stage+1L]+eta*h[i]));train[,stage+2L]<-train[,stage+1L]+eta*h;query[,stage+2L]<-query[,stage+1L]+eta*qh;norm<-sum(d$weight[eligible]*h[eligible]^2);fits[[stage+1L]]<-list(stage=stage+1L,tree=tree,rows=stageRows,queryFits=qh,norm=norm,predictedSSEDecrease=eta*(2-eta)*norm)};list(task='regression',initial=initial,learningRate=eta,stages=stages,training=train,queries=query,fits=fits,losses=losses,predictions=lapply(seq_len(nrow(a$queries)),function(i)list(id=a$queries$id[i],prediction=query[i,stages+1L],probabilities=numeric(),vote=NA_character_,prob=NA_character_)))}\nfixed_schedules<-function(ids,p,seed){state<-seed;choose<-function(n){limit<-floor(4294967296/n)*n;repeat{state<<-(1664525*state+1013904223)%%4294967296;if(state<limit)return(as.integer(state%%n))}};draws<-schedules<-list();for(member in 1:4){draws[[member]]<-vapply(seq_along(ids),function(i)ids[choose(length(ids))+1L],'');schedule<-setNames(vector('list',7),c('','L','R','LL','LR','RL','RR'));for(path in names(schedule)){order<-seq_len(p)-1L;if(p>1)for(j in seq(p-1L,1L)){k<-choose(j+1L);temp<-order[j+1L];order[j+1L]<-order[k+1L];order[k+1L]<-temp};schedule[[match(path,names(schedule))]]<-sort(order[seq_len(max(1L,floor(sqrt(p))))])};schedules[[member]]<-schedule};list(draws=draws,schedules=schedules)}\nread_sources<-function(src){read<-function(name)read.csv(file.path(src,name),check.names=FALSE,colClasses='character',na.strings=character(),fileEncoding='UTF-8-BOM');raw<-read('actual320-country-four-indicators-original-2020-2024.csv');country<-do.call(rbind,lapply(sort(unique(raw$countryISO3)),function(code)do.call(rbind,lapply(2020:2024,function(year){keys<-c('NY.GDP.PCAP.KD','NY.GDP.MKTP.KD.ZG','FP.CPI.TOTL.ZG','SP.DYN.LE00.IN');v<-vapply(keys,function(k)as.numeric(raw$originalValueToken[raw$countryISO3==code&raw$date==as.character(year)&raw$indicatorID==k]),0);data.frame(id=paste0(code,':',year),sourceRow=paste0(code,':',year),originalID=code,year=year,x0=v[1]/10000,x1=v[2],x2=v[3],y=v[4],weight=1,role=if(anyNA(v))'excluded'else if(year==2024)'outer-test'else'train')}))));raw<-read('actual3613-NLS-original52-fields-and-selection.csv');i<-seq_len(nrow(raw));x0<-suppressWarnings(as.numeric(raw$ed76));x1<-suppressWarnings(as.numeric(raw$age76));y<-suppressWarnings(as.numeric(raw$wage76))/100;person<-data.frame(id=paste0('person:',i),sourceRow=as.character(i),originalID=raw$id,x0=x0,x1=x1,y=y,weight=1,role=ifelse(is.na(x0)|is.na(x1)|is.na(y),'excluded',ifelse(i%%5==0,'outer-test','train')));raw<-read('actual3150-churn-original14-fields-and-selection.csv');i<-seq_len(nrow(raw));company<-data.frame(id=paste0('customer:',i),sourceRow=as.character(i),originalID='',x0=as.numeric(raw[['Call  Failure']]),x1=as.numeric(raw[['Subscription  Length']]),x2=as.numeric(raw[['Charge  Amount']]),y=raw$Churn,weight=1,role=ifelse(i%%5==0,'outer-test','train'));models<-list();for(index in 1:3){kind<-c('country','person','company')[index];d<-list(country,person,company)[[index]];task<-if(kind=='company')'classification'else'regression';s<-fixed_schedules(d$id[d$role=='train'],if(kind=='person')2L else 3L,20261102+7919*(index-1L));models[[kind]]<-list(records=d,task=task,classes=if(task=='classification')c('0','1')else character(),draws=s$draws,schedules=s$schedules,minLeaf=c(4L,50L,30L)[index])};models}\nrealdata<-function(models,kind,options=list()){if(is.null(options)||!is.list(options))stop('options object');m<-models[[kind]];d<-m$records;train<-d[d$role=='train',,drop=FALSE];test<-d[d$role=='outer-test',,drop=FALSE];method<-option(options,'method','forest');depth<-option(options,'maxDepth',2);count<-option(options,'memberCount',3);if(!method%in%c('bagging','forest','boost'))stop('known method');a<-list(rows=train,queries=test,task=m$task,classes=m$classes,maxDepth=depth,minLeaf=option(options,'minLeaf',m$minLeaf),minLeafWeight=0,minGain=0,missingRoute='best',learningRate=option(options,'learningRate','1/2'),stages=option(options,'stages',3));if(method=='boost')result<-boost(a)else{a$bootstrapDraws<-m$draws[seq_len(count)];a$nodeFeatures<-lapply(m$schedules[seq_len(count)],function(s)s[nchar(names(s))<depth]);result<-ensemble(a,method=='forest')};outer<-scored(result$predictions,normrows(test,m$task),m$task,m$classes);st<-stat(normrows(train,m$task),m$task,m$classes);constant<-list(prediction=st$pred,probabilities=st$p,vote=st$pred,prob=st$pred);baseline<-scored(lapply(test$id,function(id)c(list(id=id),constant)),normrows(test,m$task),m$task,m$classes);list(kind=kind,method=method,settings=a,train=train,test=test,result=result,outer=outer,baseline=baseline)}\nAPI<-\"variance\"\nINPUT<-list(B=4,marginalVariance=4,rho=\"-1/2\")\n\nrun_fixed<-function(api,a,out,src){\n r<-if(api=='variance')variance(a)else if(api=='aggregate')aggregate(a)else if(api%in%c('bagging','forest'))ensemble(a,api=='forest')else if(api=='boost')boost(a)else realdata(read_sources(src),a$kind)\n dir.create(out,recursive=TRUE,showWarnings=FALSE);summary<-list();points<-list();add<-function(x,y,s){if(!is.null(y)&&!is.na(y))points[[length(points)+1L]]<<-data.frame(x=x,y=as.numeric(y),series=s)}\n if(api=='variance'){summary<-r[c('B','varianceOfMean')];add(r$B,r$varianceOfMean,'Specified finite-B variance');xl<-'Number of members B';yl<-'Variance, stipulated units squared';title<-'Declared covariance model, not fitted trees'\n }else if(api=='aggregate'){p<-r$predictions[[1]];summary<-list(selectedPrediction=p$prediction);classification<-identical(a$task,'classification');if(classification){summary<-c(summary,list(voteLabel=p$vote,probabilityLabel=p$prob,meanProbability1=p$probabilities[2]));add(1,p$probabilities[2],'Mean probability of class 1');add(2,p$votes[2],'Label-vote share of class 1');xl<-'Aggregation (1=probability, 2=vote)';yl<-'Probability or vote share'}else{for(i in seq_along(a$members))add(i,num(a$members[[i]]$predictions$value[1]),'Member prediction');add(3,p$prediction,'Weighted mean');xl<-'Member 1, member 2, aggregate 3';yl<-'Prediction, assumed units'};title<-'Votes and probabilities are distinct objects'\n }else if(api%in%c('bagging','forest')){summary<-list(queryPrediction=r$predictions[[1]]$prediction,OOB.scoreable=r$outOfBag$eligibleRows,OOB.meanLoss=r$outOfBag$meanLoss);for(i in seq_len(nrow(a$rows)))add(i,a$rows$y[i],'Observed training outcome');for(i in seq_along(r$outOfBag$rows))add(i,r$outOfBag$rows[[i]]$prediction,'OOB prediction, when defined');xl<-'Original training ID order';yl<-'Outcome, assumed units';title<-'Repeated draws and ID-level OOB membership'\n }else if(api=='boost'){summary<-list(initial=r$initial,finalMSE=r$losses[[length(r$losses)]]$MSE,stages=r$stages);for(v in r$losses)add(v$stage,v$MSE,'Training MSE');xl<-'Boosting stage (0=initial)';yl<-'Weighted MSE, outcome units squared';title<-'Training descent does not certify held-out gain'\n }else{summary<-list(outer.scoreable=r$outer$eligibleRows,outer.meanLoss=r$outer$meanLoss,baseline.meanLoss=r$baseline$meanLoss,OOB.scoreable=r$result$outOfBag$eligibleRows,OOB.meanLoss=r$result$outOfBag$meanLoss);for(i in seq_along(r$outer$rows)){p<-r$outer$rows[[i]];add(i,as.numeric(p$actual),'Observed outcome');add(i,if(a$kind=='company')p$probabilities[2]else p$prediction,if(a$kind=='company')'Forest probability of class 1'else'Forest prediction')};xl<-'Outer-test source order, not a time path';yl<-if(a$kind=='company')'Churn label / probability'else if(a$kind=='country')'Period life expectancy, years'else'Nominal 1976 USD per hour';title<-'Fixed forest; outer labels did not fit the trees'}\n display<-function(v)if(is.null(v)||is.na(v))'undefined'else sprintf('%.9f',as.numeric(v));write.csv(data.frame(metric=names(summary),value=vapply(summary,display,'')),file.path(out,'summary.csv'),row.names=FALSE);pp<-do.call(rbind,points);write.csv(pp,file.path(out,'plot-points.csv'),row.names=FALSE);dput(r,file.path(out,'full-result.Rtext'));svg(file.path(out,'plot.svg'),width=5.6,height=4.6,pointsize=14);par(mar=c(5.8,5.8,5.3,1.2),mgp=c(3.7,1,0));xr<-range(pp$x);yr<-range(pp$y);if(diff(xr)==0)xr<-xr+c(-.5,.5);if(diff(yr)==0)yr<-yr+c(-.5,.5);plot(xr,yr,type='n',xlab=xl,ylab=yl,cex.lab=.78,axes=FALSE);axis(1,at=pretty(xr,3));axis(2,at=pretty(yr,4),las=1,cex.axis=.82);box();grid(col='#dddddd');cols<-c('#355c72','#a55336','#507956','#78568b');ss<-unique(pp$series);for(i in seq_along(ss)){v<-pp[pp$series==ss[i],];points(v$x,v$y,pch=16,cex=if(nrow(v)>100).35 else .85,col=adjustcolor(cols[i],if(nrow(v)>100).5 else 1))};legend('topleft',legend=ss,col=cols[seq_along(ss)],lty=0,pch=16,cex=.65,bty='n',inset=c(0,-.32),xpd=NA);mtext(title,side=3,line=3.9,cex=.6);dev.off();cat(paste(names(summary),vapply(summary,display,''),sep='=',collapse=', '),'\\n')\n}\nargs<-commandArgs(trailingOnly=TRUE)\ntryCatch(run_fixed(API,INPUT,if(length(args))args[1]else'fixed-results',if(length(args)>1)args[2]else'ml09-sources'),error=function(e){cat('Rejected declared input: ',conditionMessage(e),'\\n',file=stderr());quit(status=2)})\n",
        "code": "# ML09 base-R reproduction from native original-field CSVs.\n# Rscript ml09-public-analysis.R ml09-sources results-r\n# Separately written vectorized direct-centered squared/Gini losses.\n# No Python/JS/model-contract/stored-answer/derived-result reader or package.\n# Numeric arithmetic is binary64:1e-12 relative tie tolerance stabilizes exact\n# source ties,but does not certify tiny margins/underflow like Fraction JS/Python.\n# Data-frame rows use x0,x1,...,y,weight; original IDs remain attached to draws.\noptions(stringsAsFactors=FALSE,digits=17)\nnum<-function(v){if(is.null(v)||length(v)!=1||is.na(v))stop('numeric parameter required, not explicit NULL');p<-strsplit(as.character(v),'/',fixed=TRUE)[[1]];z<-if(length(p)==2)as.numeric(p[1])/as.numeric(p[2])else as.numeric(v);if(!is.finite(z))stop('finite numeric parameter');z}\noption<-function(a,k,default){if(k%in%names(a))a[[k]]else default}\nnormrows<-function(d,task){if(!'weight'%in%names(d))d$weight<-1;if(!'id'%in%names(d))d$id<-as.character(seq_len(nrow(d))-1);d$weight<-as.numeric(d$weight);if(anyNA(d$weight)||any(d$weight<0))stop('nonnegative weights');if(task=='regression')d$y<-as.numeric(d$y)else d$y<-as.character(d$y);d}\nstat<-function(d,task,classes){W<-sum(d$weight);mu<-if(task=='regression'&&W)sum(d$weight*d$y)/W else NA_real_;p<-if(task=='classification'&&W)vapply(classes,function(c)sum(d$weight[d$y==c])/W,0)else numeric();risk<-if(task=='regression'&&W)sum(d$weight*(d$y-mu)^2)else W*sum(p*(1-p));list(n=nrow(d),w=W,mu=mu,p=unname(p),risk=risk,pred=if(task=='regression')mu else if(W)classes[which.max(p)]else NA_character_)}\nfit<-function(d,a,task,classes,schedule=NULL){d<-d[d$weight>0&!is.na(d$y),,drop=FALSE];if(!nrow(d))stop('positive observed training');W<-sum(d$weight);depth<-option(a,'maxDepth',2);minimum<-option(a,'minLeaf',1);minmass<-num(option(a,'minLeafWeight',0));mingain<-num(option(a,'minGain',0));route<-option(a,'missingRoute','best');features<-grep('^x[0-9]+$',names(d),value=TRUE)\n build<-function(rr,level,path){st<-stat(rr,task,classes);node<-list(rows=rr,st=st,split=NULL,left=NULL,right=NULL,path=path);if(level==depth)return(node);best<-NULL;allowed<-if(is.null(schedule))seq_along(features)-1L else schedule[[match(path,names(schedule))]]\n  for(j in seq_along(features)-1L){if(!j%in%allowed)next;v<-rr[[features[j+1L]]];values<-sort(unique(v[!is.na(v)]));candidates<-list()\n   if(length(values)>1)for(k in seq_len(length(values)-1L)){threshold<-(values[k]+values[k+1L])/2;missing<-is.na(v);left<-!missing&v<=threshold;right<-!missing&v>threshold;directions<-if(route!='best')route else if(any(missing))c('left','right')else if(sum(left)>=sum(right))'left'else'right';for(direction in directions)candidates[[length(candidates)+1L]]<-list(kind='threshold',threshold=threshold,missingRoute=direction,left=if(direction=='left')left|missing else left,right=if(direction=='right')right|missing else right)}\n   if(anyNA(v)&&any(!is.na(v)))candidates[[length(candidates)+1L]]<-list(kind='missing-only',threshold=NA_real_,missingRoute='left',left=is.na(v),right=!is.na(v))\n   for(candidate in candidates){l<-rr[candidate$left,,drop=FALSE];r<-rr[candidate$right,,drop=FALSE];ls<-stat(l,task,classes);rs<-stat(r,task,classes);if(min(ls$n,rs$n)<minimum||min(ls$w,rs$w)<minmass||min(ls$w,rs$w)<=0)next;gain<-(st$risk-ls$risk-rs$risk)/W;tol<-1e-12*max(1,abs(gain),if(is.null(best))0 else abs(best$gain));if(is.null(best)||gain>best$gain+tol)best<-c(candidate,list(feature=j,gain=gain,l=l,r=r))}\n  }\n  if(!is.null(best)&&best$gain>max(mingain,1e-12)){node$split<-best;node$left<-build(best$l,level+1L,paste0(path,'L'));node$right<-build(best$r,level+1L,paste0(path,'R'))};node\n };build(d,0L,'')\n}\npredict_one<-function(tree,row){n<-tree;while(!is.null(n$split)){s<-n$split;v<-as.numeric(row[[paste0('x',s$feature)]]);left<-if(s$kind=='missing-only')is.na(v)else if(is.na(v))s$missingRoute=='left'else v<=s$threshold;n<-if(left)n$left else n$right};list(prediction=n$st$pred,probabilities=n$st$p)}\ncombine<-function(pp,w,task,classes,mode='probabilities'){W<-sum(w);if(!length(pp)||!W)return(list(prediction=if(task=='regression')NA_real_ else NA_character_,probabilities=numeric(),vote=NA_character_,prob=NA_character_));if(task=='regression')return(list(prediction=sum(vapply(pp,function(p)p$prediction,0)*w)/W,probabilities=numeric(),vote=NA_character_,prob=NA_character_));votes<-vapply(classes,function(c)sum(w[vapply(pp,function(p)p$prediction==c,FALSE)])/W,0);probs<-vapply(seq_along(classes),function(j)sum(vapply(pp,function(p)p$probabilities[j],0)*w)/W,0);vote<-classes[which.max(votes)];prob<-classes[which.max(probs)];list(prediction=if(mode=='votes')vote else prob,probabilities=unname(probs),vote=vote,prob=prob,votes=unname(votes))}\nvariance<-function(a){B<-num(a$B);v<-num(a$marginalVariance);rho<-num(option(a,'rho',0));if(B<1||B!=floor(B)||v<0)stop('integer B/nonnegative variance');if(B>1&&v>0&&(rho< -1/(B-1)||rho>1))stop('PSD correlation');list(B=B,marginalVariance=v,correlationApplicable=B>1&&v>0,varianceOfMean=if(B==1)v else v*(1+(B-1)*rho)/B)}\naggregate<-function(a){task<-option(a,'task','regression');classes<-option(a,'classes',character());w<-vapply(option(a,'memberWeights',as.list(rep(1,length(a$members)))),num,0);if(any(w<0)||sum(w)<=0)stop('positive member mass');ids<-a$members[[1]]$predictions$id;pp<-lapply(ids,function(id){members<-lapply(a$members,function(m){r<-m$predictions[match(id,m$predictions$id),,drop=FALSE];if(task=='regression')list(prediction=num(r$value),probabilities=numeric())else list(prediction=as.character(r$label),probabilities=as.numeric(r[paste0('p',seq_along(classes)-1L)]))});c(list(id=id),combine(members,w,task,classes,option(a,'aggregation','probabilities')))});list(task=task,classes=classes,predictions=pp)}\nscored<-function(preds,d,task,classes){W<-loss<-absolute<-errors<-voteerrors<-0;count<-0L;out<-lapply(seq_len(nrow(d)),function(i){r<-d[i,,drop=FALSE];p<-preds[[i]];ok<-!is.na(p$prediction)&&!is.na(r$y)&&r$weight>0;value<-NA_real_;if(ok){count<<-count+1L;W<<-W+r$weight;if(task=='regression'){e<-r$y-p$prediction;value<-e*e;absolute<<-absolute+r$weight*abs(e)}else{value<-sum((p$probabilities-as.numeric(classes==r$y))^2);errors<<-errors+r$weight*(p$prediction!=r$y);voteerrors<<-voteerrors+r$weight*(p$vote!=r$y)};loss<<-loss+r$weight*value};c(p,list(actual=r$y,weight=r$weight,scoreEligible=ok,loss=value))});list(rows=out,eligibleRows=count,weight=W,totalLoss=loss,meanLoss=if(W)loss/W else NA_real_,MAE=if(W&&task=='regression')absolute/W else NA_real_,errorRate=if(W&&task=='classification')errors/W else NA_real_,labelVoteErrorRate=if(W&&task=='classification')voteerrors/W else NA_real_)}\nensemble<-function(a,forest=FALSE){task<-option(a,'task','regression');classes<-option(a,'classes',character());d<-normrows(a$rows,task);w<-vapply(option(a,'memberWeights',as.list(rep(1,length(a$bootstrapDraws)))),num,0);if(any(w<0)||sum(w)<=0)stop('positive member mass');members<-lapply(seq_along(a$bootstrapDraws),function(i){draw<-a$bootstrapDraws[[i]];indices<-match(draw,d$id);if(anyNA(indices))stop('unknown draw source');tree<-fit(d[indices,,drop=FALSE],a,task,classes,if(forest)a$nodeFeatures[[i]]else NULL);list(tree=tree,draw=draw,inbag=unique(draw),weight=w[i])});queries<-a$queries;preds<-lapply(seq_len(nrow(queries)),function(i)c(list(id=queries$id[i]),combine(lapply(members,function(m)predict_one(m$tree,queries[i,,drop=FALSE])),w,task,classes,option(a,'aggregation','probabilities'))));oob<-lapply(seq_len(nrow(d)),function(i){app<-which(!vapply(members,function(m)d$id[i]%in%m$inbag,FALSE));pp<-combine(lapply(app,function(j)predict_one(members[[j]]$tree,d[i,,drop=FALSE])),w[app],task,classes,option(a,'aggregation','probabilities'));c(list(id=d$id[i],applicable=app-1L,positiveMembers=sum(w[app]>0)),pp)});list(task=task,classes=classes,members=members,predictions=preds,outOfBag=scored(oob,d,task,classes))}\nboost<-function(a){if(option(a,'task','regression')!='regression')stop('regression boosting only');d<-normrows(a$rows,'regression');eligible<-d$weight>0&!is.na(d$y);W<-sum(d$weight[eligible]);if(!W)stop('positive eligible training');eta<-num(option(a,'learningRate','1/2'));stages<-option(a,'stages',3);if(is.null(stages)||stages!=floor(stages)||stages<0||stages>8||eta<0||eta>1)stop('supported rate/stages');initial<-if('initial'%in%names(a))num(a$initial)else sum(d$weight[eligible]*d$y[eligible])/W;train<-matrix(initial,nrow(d),stages+1L);query<-matrix(initial,nrow(a$queries),stages+1L);losses<-fits<-list();for(stage in 0:stages){sse<-sum(d$weight[eligible]*(d$y[eligible]-train[eligible,stage+1L])^2);losses[[stage+1L]]<-list(stage=stage,rawWeightedSSE=sse,MSE=sse/W,meanHalfSquaredLoss=sse/(2*W));if(stage==stages)break;residual<-d;residual$y<-d$y-train[,stage+1L];tree<-fit(residual,a,'regression',character());h<-vapply(seq_len(nrow(d)),function(i)predict_one(tree,d[i,,drop=FALSE])$prediction,0);qh<-vapply(seq_len(nrow(a$queries)),function(i)predict_one(tree,a$queries[i,,drop=FALSE])$prediction,0);stageRows<-lapply(seq_len(nrow(d)),function(i)list(id=d$id[i],before=train[i,stage+1L],residual=residual$y[i],negativeCoordinateDerivative=d$weight[i]*residual$y[i]/W,fit=h[i],addition=eta*h[i],after=train[i,stage+1L]+eta*h[i]));train[,stage+2L]<-train[,stage+1L]+eta*h;query[,stage+2L]<-query[,stage+1L]+eta*qh;norm<-sum(d$weight[eligible]*h[eligible]^2);fits[[stage+1L]]<-list(stage=stage+1L,tree=tree,rows=stageRows,queryFits=qh,norm=norm,predictedSSEDecrease=eta*(2-eta)*norm)};list(task='regression',initial=initial,learningRate=eta,stages=stages,training=train,queries=query,fits=fits,losses=losses,predictions=lapply(seq_len(nrow(a$queries)),function(i)list(id=a$queries$id[i],prediction=query[i,stages+1L],probabilities=numeric(),vote=NA_character_,prob=NA_character_)))}\nfixed_schedules<-function(ids,p,seed){state<-seed;choose<-function(n){limit<-floor(4294967296/n)*n;repeat{state<<-(1664525*state+1013904223)%%4294967296;if(state<limit)return(as.integer(state%%n))}};draws<-schedules<-list();for(member in 1:4){draws[[member]]<-vapply(seq_along(ids),function(i)ids[choose(length(ids))+1L],'');schedule<-setNames(vector('list',7),c('','L','R','LL','LR','RL','RR'));for(path in names(schedule)){order<-seq_len(p)-1L;if(p>1)for(j in seq(p-1L,1L)){k<-choose(j+1L);temp<-order[j+1L];order[j+1L]<-order[k+1L];order[k+1L]<-temp};schedule[[match(path,names(schedule))]]<-sort(order[seq_len(max(1L,floor(sqrt(p))))])};schedules[[member]]<-schedule};list(draws=draws,schedules=schedules)}\nread_sources<-function(src){read<-function(name)read.csv(file.path(src,name),check.names=FALSE,colClasses='character',na.strings=character(),fileEncoding='UTF-8-BOM');raw<-read('actual320-country-four-indicators-original-2020-2024.csv');country<-do.call(rbind,lapply(sort(unique(raw$countryISO3)),function(code)do.call(rbind,lapply(2020:2024,function(year){keys<-c('NY.GDP.PCAP.KD','NY.GDP.MKTP.KD.ZG','FP.CPI.TOTL.ZG','SP.DYN.LE00.IN');v<-vapply(keys,function(k)as.numeric(raw$originalValueToken[raw$countryISO3==code&raw$date==as.character(year)&raw$indicatorID==k]),0);data.frame(id=paste0(code,':',year),sourceRow=paste0(code,':',year),originalID=code,year=year,x0=v[1]/10000,x1=v[2],x2=v[3],y=v[4],weight=1,role=if(anyNA(v))'excluded'else if(year==2024)'outer-test'else'train')}))));raw<-read('actual3613-NLS-original52-fields-and-selection.csv');i<-seq_len(nrow(raw));x0<-suppressWarnings(as.numeric(raw$ed76));x1<-suppressWarnings(as.numeric(raw$age76));y<-suppressWarnings(as.numeric(raw$wage76))/100;person<-data.frame(id=paste0('person:',i),sourceRow=as.character(i),originalID=raw$id,x0=x0,x1=x1,y=y,weight=1,role=ifelse(is.na(x0)|is.na(x1)|is.na(y),'excluded',ifelse(i%%5==0,'outer-test','train')));raw<-read('actual3150-churn-original14-fields-and-selection.csv');i<-seq_len(nrow(raw));company<-data.frame(id=paste0('customer:',i),sourceRow=as.character(i),originalID='',x0=as.numeric(raw[['Call  Failure']]),x1=as.numeric(raw[['Subscription  Length']]),x2=as.numeric(raw[['Charge  Amount']]),y=raw$Churn,weight=1,role=ifelse(i%%5==0,'outer-test','train'));models<-list();for(index in 1:3){kind<-c('country','person','company')[index];d<-list(country,person,company)[[index]];task<-if(kind=='company')'classification'else'regression';s<-fixed_schedules(d$id[d$role=='train'],if(kind=='person')2L else 3L,20261102+7919*(index-1L));models[[kind]]<-list(records=d,task=task,classes=if(task=='classification')c('0','1')else character(),draws=s$draws,schedules=s$schedules,minLeaf=c(4L,50L,30L)[index])};models}\nrealdata<-function(models,kind,options=list()){if(is.null(options)||!is.list(options))stop('options object');m<-models[[kind]];d<-m$records;train<-d[d$role=='train',,drop=FALSE];test<-d[d$role=='outer-test',,drop=FALSE];method<-option(options,'method','forest');depth<-option(options,'maxDepth',2);count<-option(options,'memberCount',3);if(!method%in%c('bagging','forest','boost'))stop('known method');a<-list(rows=train,queries=test,task=m$task,classes=m$classes,maxDepth=depth,minLeaf=option(options,'minLeaf',m$minLeaf),minLeafWeight=0,minGain=0,missingRoute='best',learningRate=option(options,'learningRate','1/2'),stages=option(options,'stages',3));if(method=='boost')result<-boost(a)else{a$bootstrapDraws<-m$draws[seq_len(count)];a$nodeFeatures<-lapply(m$schedules[seq_len(count)],function(s)s[nchar(names(s))<depth]);result<-ensemble(a,method=='forest')};outer<-scored(result$predictions,normrows(test,m$task),m$task,m$classes);st<-stat(normrows(train,m$task),m$task,m$classes);constant<-list(prediction=st$pred,probabilities=st$p,vote=st$pred,prob=st$pred);baseline<-scored(lapply(test$id,function(id)c(list(id=id),constant)),normrows(test,m$task),m$task,m$classes);list(kind=kind,method=method,settings=a,train=train,test=test,result=result,outer=outer,baseline=baseline)}\nAPI<-\"variance\"\nINPUT<-list(B=4,marginalVariance=4,rho=\"-1/2\")\n\nrun_fixed<-function(api,a,out,src){\n r<-if(api=='variance')variance(a)else if(api=='aggregate')aggregate(a)else if(api%in%c('bagging','forest'))ensemble(a,api=='forest')else if(api=='boost')boost(a)else realdata(read_sources(src),a$kind)\n dir.create(out,recursive=TRUE,showWarnings=FALSE);summary<-list();points<-list();add<-function(x,y,s){if(!is.null(y)&&!is.na(y))points[[length(points)+1L]]<<-data.frame(x=x,y=as.numeric(y),series=s)}\n if(api=='variance'){summary<-r[c('B','varianceOfMean')];add(r$B,r$varianceOfMean,'Specified finite-B variance');xl<-'Number of members B';yl<-'Variance, stipulated units squared';title<-'Declared covariance model, not fitted trees'\n }else if(api=='aggregate'){p<-r$predictions[[1]];summary<-list(selectedPrediction=p$prediction);classification<-identical(a$task,'classification');if(classification){summary<-c(summary,list(voteLabel=p$vote,probabilityLabel=p$prob,meanProbability1=p$probabilities[2]));add(1,p$probabilities[2],'Mean probability of class 1');add(2,p$votes[2],'Label-vote share of class 1');xl<-'Aggregation (1=probability, 2=vote)';yl<-'Probability or vote share'}else{for(i in seq_along(a$members))add(i,num(a$members[[i]]$predictions$value[1]),'Member prediction');add(3,p$prediction,'Weighted mean');xl<-'Member 1, member 2, aggregate 3';yl<-'Prediction, assumed units'};title<-'Votes and probabilities are distinct objects'\n }else if(api%in%c('bagging','forest')){summary<-list(queryPrediction=r$predictions[[1]]$prediction,OOB.scoreable=r$outOfBag$eligibleRows,OOB.meanLoss=r$outOfBag$meanLoss);for(i in seq_len(nrow(a$rows)))add(i,a$rows$y[i],'Observed training outcome');for(i in seq_along(r$outOfBag$rows))add(i,r$outOfBag$rows[[i]]$prediction,'OOB prediction, when defined');xl<-'Original training ID order';yl<-'Outcome, assumed units';title<-'Repeated draws and ID-level OOB membership'\n }else if(api=='boost'){summary<-list(initial=r$initial,finalMSE=r$losses[[length(r$losses)]]$MSE,stages=r$stages);for(v in r$losses)add(v$stage,v$MSE,'Training MSE');xl<-'Boosting stage (0=initial)';yl<-'Weighted MSE, outcome units squared';title<-'Training descent does not certify held-out gain'\n }else{summary<-list(outer.scoreable=r$outer$eligibleRows,outer.meanLoss=r$outer$meanLoss,baseline.meanLoss=r$baseline$meanLoss,OOB.scoreable=r$result$outOfBag$eligibleRows,OOB.meanLoss=r$result$outOfBag$meanLoss);for(i in seq_along(r$outer$rows)){p<-r$outer$rows[[i]];add(i,as.numeric(p$actual),'Observed outcome');add(i,if(a$kind=='company')p$probabilities[2]else p$prediction,if(a$kind=='company')'Forest probability of class 1'else'Forest prediction')};xl<-'Outer-test source order, not a time path';yl<-if(a$kind=='company')'Churn label / probability'else if(a$kind=='country')'Period life expectancy, years'else'Nominal 1976 USD per hour';title<-'Fixed forest; outer labels did not fit the trees'}\n display<-function(v)if(is.null(v)||is.na(v))'undefined'else sprintf('%.9f',as.numeric(v));write.csv(data.frame(metric=names(summary),value=vapply(summary,display,'')),file.path(out,'summary.csv'),row.names=FALSE);pp<-do.call(rbind,points);write.csv(pp,file.path(out,'plot-points.csv'),row.names=FALSE);dput(r,file.path(out,'full-result.Rtext'));svg(file.path(out,'plot.svg'),width=5.6,height=4.6,pointsize=14);par(mar=c(5.8,5.8,5.3,1.2),mgp=c(3.7,1,0));xr<-range(pp$x);yr<-range(pp$y);if(diff(xr)==0)xr<-xr+c(-.5,.5);if(diff(yr)==0)yr<-yr+c(-.5,.5);plot(xr,yr,type='n',xlab=xl,ylab=yl,cex.lab=.78,axes=FALSE);axis(1,at=pretty(xr,3));axis(2,at=pretty(yr,4),las=1,cex.axis=.82);box();grid(col='#dddddd');cols<-c('#355c72','#a55336','#507956','#78568b');ss<-unique(pp$series);for(i in seq_along(ss)){v<-pp[pp$series==ss[i],];points(v$x,v$y,pch=16,cex=if(nrow(v)>100).35 else .85,col=adjustcolor(cols[i],if(nrow(v)>100).5 else 1))};legend('topleft',legend=ss,col=cols[seq_along(ss)],lty=0,pch=16,cex=.65,bty='n',inset=c(0,-.32),xpd=NA);mtext(title,side=3,line=3.9,cex=.6);dev.off();cat(paste(names(summary),vapply(summary,display,''),sep='=',collapse=', '),'\\n')\n}\nargs<-commandArgs(trailingOnly=TRUE)\ntryCatch(run_fixed(API,INPUT,if(length(args))args[1]else'fixed-results',if(length(args)>1)args[2]else'ml09-sources'),error=function(e){cat('Rejected declared input: ',conditionMessage(e),'\\n',file=stderr());quit(status=2)})\n",
        "inputFiles": [],
        "input": {
          "B": 4,
          "marginalVariance": 4,
          "rho": "-1/2"
        },
        "returnCode": 2,
        "expectedFailure": true,
        "stdout": "",
        "stderr": "During startup - Warning messages:\n1: Setting LC_COLLATE=C.UTF-8 failed \n2: Setting LC_CTYPE=C.UTF-8 failed \n3: Setting LC_MONETARY=C.UTF-8 failed \n4: Setting LC_TIME=C.UTF-8 failed \nRejected declared input:  PSD correlation \n",
        "summary": {},
        "plotPoints": [],
        "plotFile": null,
        "plotSHA256": null,
        "files": [],
        "scope": "Actually executed self-contained fixed example; current web controls execute separately. Python Fraction and finite-precision base R. Author gate, not independent peer."
      }
    }
  },
  "aggregate": {
    "python": {
      "weighted-mean": {
        "api": "aggregate",
        "variant": "weighted-mean",
        "language": "python",
        "codeFile": "ml09-code/aggregate-weighted-mean.py",
        "codeSHA256": "c9f56693fe359a2cb321c27c9a024466366ccce30115d334e15229b089afb1d0",
        "codeText": "\"\"\"ML09 exact Fraction reproduction from native source fields.\n\npython ml09-public-analysis.py --source-dir ml09-sources --output-dir results\n\nThis authored educational implementation uses direct-centered leaf losses and\nexhaustive midpoint partitions. It reads no JS engine, model contract, checker,\nstored target answers or derived-result CSV. Its five tree arithmetic helpers\nwere copied from the author's own separate Fraction reference, not an independent\npeer. Parser/work budgets and display rounding of the production JS are separate.\nNumerical predictions/proper scores do not certify causal effects, calibration,\nIID OOB validity, survey representativeness or production parameter optimality.\n\"\"\"\nfrom pathlib import Path\nfrom fractions import Fraction as Q\nimport csv,json,math,itertools,argparse\n\ndef normalized(rows,task='regression'):\n return [dict(id=r.get('id',i),x=[None if x is None else Q(x)for x in r.get('x',[])],y=None if r['y']is None else str(r['y'])if task=='classification'else Q(r['y']),w=Q(r.get('weight',1)))for i,r in enumerate(rows)]\n\ndef totals(rows,task,classes):\n W=sum((r['w']for r in rows),Q());mu=sum((r['w']*r['y']for r in rows),Q())/W if task=='regression'and W else None\n probs=[sum((r['w']for r in rows if r['y']==c),Q())/W for c in classes]if task=='classification'and W else[]\n risk=sum((r['w']*(r['y']-mu)**2 for r in rows),Q())if task=='regression'and W else W*sum((p*(1-p)for p in probs),Q())\n return dict(n=len(rows),w=W,mu=mu,p=probs,risk=risk,pred=mu if task=='regression'else classes[max(range(len(probs)),key=lambda i:probs[i])]if probs else None)\n\ndef fit(rows,a,task,classes,schedule=None):\n good=[r for r in rows if r['w']>0 and r['y']is not None];root=totals(good,task,classes)['w'];depth=a.get('maxDepth',2);minimum=a.get('minLeaf',1);minmass=Q(a.get('minLeafWeight',0));mingain=Q(a.get('minGain',0));route=a.get('missingRoute','best')\n def build(rr,d,path):\n  st=totals(rr,task,classes);n=dict(rows=rr,st=st,split=None,left=None,right=None,path=path)\n  if d==depth:return n\n  best=None\n  for j in range(len(rr[0]['x'])):\n   if schedule is not None and j not in schedule[path]:continue\n   values=sorted({r['x'][j]for r in rr if r['x'][j]is not None});missing=[r for r in rr if r['x'][j]is None];observed=[r for r in rr if r['x'][j]is not None]\n   candidates=[]\n   for lo,hi in zip(values,values[1:]):\n    q=(lo+hi)/2;left=[r for r in observed if r['x'][j]<=q];right=[r for r in observed if r['x'][j]>q];directions=[route]if route!='best'else['left','right']if missing else['left'if len(left)>=len(right)else'right']\n    for direction in directions:candidates.append(('threshold',q,direction,left+missing if direction=='left'else left,right+missing if direction=='right'else right))\n   if missing and observed:candidates.append(('missing-only',None,'left',missing,observed))\n   for kind,q,direction,left,right in candidates:\n    l=totals(left,task,classes);r=totals(right,task,classes)\n    if min(l['n'],r['n'])<minimum or min(l['w'],r['w'])<minmass or min(l['w'],r['w'])<=0:continue\n    gain=(st['risk']-l['risk']-r['risk'])/root\n    if best is None or gain>best['gain']:best=dict(feature=j,kind=kind,threshold=q,missingRoute=direction,left=left,right=right,gain=gain)\n  if best and best['gain']>0 and best['gain']>mingain:\n   j=best['feature'];go=lambda r:r['x'][j]is None if best['kind']=='missing-only'else best['missingRoute']=='left'if r['x'][j]is None else r['x'][j]<=best['threshold'];n['split']=best;n['left']=build([r for r in rr if go(r)],d+1,path+'L');n['right']=build([r for r in rr if not go(r)],d+1,path+'R')\n  return n\n return build(good,0,'')\n\ndef predict(tree,x):\n n=tree\n while n['split']:\n  s=n['split'];v=x[s['feature']];left=v is None if s['kind']=='missing-only'else s['missingRoute']=='left'if v is None else v<=s['threshold'];n=n['left'if left else'right']\n return dict(prediction=n['st']['pred'],probabilities=n['st']['p'])\n\ndef combine(preds,w,task,classes,mode='probabilities'):\n mass=sum(w,Q())\n if not preds or not mass:return dict(prediction=None,probabilities=[],vote=None,prob=None)\n if task=='regression':return dict(prediction=sum((p['prediction']*v for p,v in zip(preds,w)),Q())/mass,probabilities=[],vote=None,prob=None)\n votes=[sum((v for p,v in zip(preds,w)if p['prediction']==c),Q())/mass for c in classes];ps=[sum((p['probabilities'][j]*v for p,v in zip(preds,w)),Q())/mass for j in range(len(classes))];vote=classes[max(range(len(classes)),key=lambda j:votes[j])];prob=classes[max(range(len(classes)),key=lambda j:ps[j])];return dict(prediction=vote if mode=='votes'else prob,probabilities=ps,vote=vote,prob=prob,votes=votes)\ndef number(v):\n if v is None or isinstance(v,bool):raise ValueError('explicit null/bool is not a numeric parameter')\n return Q(v)\ndef variance(a):\n B=a['B'];v=number(a['marginalVariance']);rho=number(a.get('rho',0))\n if not isinstance(B,int)or isinstance(B,bool)or B<1 or v<0:raise ValueError('positive integer B/nonnegative variance')\n if B>1 and v and not -Q(1,B-1)<=rho<=1:raise ValueError('equicorrelation PSD bound')\n return dict(B=B,marginalVariance=v,correlationApplicable=B>1 and bool(v),varianceOfMean=v if B==1 else v*(1+(B-1)*rho)/B)\ndef aggregate(a):\n task=a.get('task','regression');classes=[str(c)for c in a.get('classes',[])];members=a['members'];w=[number(v)for v in a.get('memberWeights',[1]*len(members))]\n if not members or min(w)<0 or sum(w)<=0:raise ValueError('nonnegative member weights/positive total')\n order=[p.get('id',i)for i,p in enumerate(members[0]['predictions'])];keys=lambda x:(type(x).__name__,x);lookup=[{keys(p.get('id',i)):p for i,p in enumerate(m['predictions'])}for m in members]\n if any(set(m)!={keys(v)for v in order}for m in lookup):raise ValueError('same query ID set')\n out=[]\n for pid in order:\n  predictions=[dict(prediction=number(m[keys(pid)]['value']),probabilities=[])if task=='regression'else dict(prediction=str(m[keys(pid)]['label']),probabilities=[number(v)for v in m[keys(pid)]['probabilities']])for m in lookup]\n  if task=='classification'and any(min(p['probabilities'])<0 or sum(p['probabilities'])!=1 for p in predictions):raise ValueError('probability simplex')\n  out.append(dict(id=pid,**combine(predictions,w,task,classes,a.get('aggregation','probabilities'))))\n return dict(task=task,classes=classes,predictions=out)\ndef scored(preds,rows,task,classes):\n mass=loss=absolute=errors=voteerrors=Q();out=[]\n for p,r in zip(preds,rows):\n  ok=p['prediction']is not None and r['y']is not None and r['w']>0;v=None\n  if ok:\n   mass+=r['w']\n   if task=='regression':e=r['y']-p['prediction'];v=e*e;absolute+=r['w']*abs(e)\n   else:v=sum(((q-(1 if r['y']==c else 0))**2 for c,q in zip(classes,p['probabilities'])),Q());errors+=r['w']*(p['prediction']!=r['y']);voteerrors+=r['w']*(p['vote']!=r['y'])\n   loss+=r['w']*v\n  out.append(dict(p,actual=r['y'],weight=r['w'],scoreEligible=ok,loss=v))\n return dict(rows=out,eligibleRows=sum(r['scoreEligible']for r in out),weight=mass,totalLoss=loss,meanLoss=loss/mass if mass else None,MAE=absolute/mass if mass and task=='regression'else None,errorRate=errors/mass if mass and task=='classification'else None,labelVoteErrorRate=voteerrors/mass if mass and task=='classification'else None)\ndef ensemble(a,forest=False):\n task=a.get('task','regression');classes=[str(v)for v in(a.get('classes')or[])];rr=normalized(a['rows'],task);key=lambda x:(type(x).__name__,x);lookup={key(r['id']):r for r in rr};weights=[number(v)for v in a.get('memberWeights',[1]*len(a['bootstrapDraws']))]\n if not any(r['w']>0 and r['y']is not None for r in rr)or min(weights)<0 or sum(weights)<=0:raise ValueError('positive eligible training and member weight')\n members=[]\n for i,draw in enumerate(a['bootstrapDraws']):\n  data=[lookup[key(v)]for v in draw];schedule=a['nodeFeatures'][i]if forest else None;model=fit(data,a,task,classes,schedule);inbag={key(v)for v in draw};members.append(dict(tree=model,draw=draw,inbag=inbag,weight=weights[i]))\n predictions=[]\n for q in a.get('queries',[]):predictions.append(dict(id=q['id'],**combine([predict(m['tree'],[None if v is None else number(v)for v in q['x']])for m in members],weights,task,classes,a.get('aggregation','probabilities'))))\n oob=[]\n for r in rr:\n  applicable=[i for i,m in enumerate(members)if key(r['id'])not in m['inbag']];p=combine([predict(members[i]['tree'],r['x'])for i in applicable],[weights[i]for i in applicable],task,classes,a.get('aggregation','probabilities'));oob.append(dict(id=r['id'],applicable=applicable,positiveMembers=sum(weights[i]>0 for i in applicable),**p))\n return dict(task=task,classes=classes,members=members,predictions=predictions,outOfBag=scored(oob,rr,task,classes))\ndef boost(a):\n if a.get('task','regression')!='regression':raise ValueError('regression boosting only')\n rr=normalized(a['rows']);good=[r for r in rr if r['w']and r['y']is not None];W=sum((r['w']for r in good),Q())\n if not W:raise ValueError('positive eligible training')\n eta=number(a.get('learningRate','1/2'));stages=a.get('stages',3)\n if not 0<=eta<=1 or not isinstance(stages,int)or isinstance(stages,bool)or not 0<=stages<=8:raise ValueError('supported rate/stages')\n initial=number(a['initial'])if'initial'in a else sum((r['w']*r['y']for r in good),Q())/W;training=[[initial]for r in rr];queries=[[initial]for q in a.get('queries',[])];fits=[];losses=[]\n for stage in range(stages+1):\n  sse=sum((r['w']*(r['y']-p[-1])**2 for r,p in zip(rr,training)if r['w']and r['y']is not None),Q());losses.append(dict(stage=stage,rawWeightedSSE=sse,MSE=sse/W,meanHalfSquaredLoss=sse/(2*W)))\n  if stage==stages:break\n  residuals=[dict(r,y=None if r['y']is None else r['y']-p[-1])for r,p in zip(rr,training)];tree=fit(residuals,a,'regression',[]);h=[predict(tree,r['x'])['prediction']for r in rr];qh=[predict(tree,[None if v is None else number(v)for v in q['x']])['prediction']for q in a.get('queries',[])];norm=sum((r['w']*v*v for r,v in zip(rr,h)if r['y']is not None),Q());stageRows=[]\n  for i,(r,p)in enumerate(zip(rr,training)):\n   residual=None if r['y']is None else r['y']-p[-1];stageRows.append(dict(id=r['id'],before=p[-1],residual=residual,negativeCoordinateDerivative=None if residual is None else r['w']*residual/W,fit=h[i],addition=eta*h[i],after=p[-1]+eta*h[i]));p.append(p[-1]+eta*h[i])\n  for p,v in zip(queries,qh):p.append(p[-1]+eta*v)\n  fits.append(dict(stage=stage+1,tree=tree,rows=stageRows,queryFits=qh,norm=norm,predictedSSEDecrease=eta*(2-eta)*norm))\n return dict(task='regression',initial=initial,learningRate=eta,stages=stages,training=training,queries=queries,fits=fits,losses=losses,predictions=[dict(id=q['id'],prediction=p[-1],probabilities=[],vote=None,prob=None)for q,p in zip(a.get('queries',[]),queries)])\nclass Stream:\n def __init__(self,state):self.state=state\n def choose(self,n):\n  limit=(1<<32)-((1<<32)%n)\n  while True:\n   self.state=(1664525*self.state+1013904223)&0xffffffff\n   if self.state<limit:return self.state%n\ndef fixed_schedules(ids,p,seed):\n stream=Stream(seed);draws=[];schedules=[];paths=['']+[p for d in[1,2]for p in map(''.join,itertools.product('LR',repeat=d))]\n for member in range(4):\n  draws.append([ids[stream.choose(len(ids))]for _ in range(len(ids))]);schedule={}\n  for path in paths:\n   order=list(range(p))\n   for j in range(p-1,0,-1):k=stream.choose(j+1);order[j],order[k]=order[k],order[j]\n   schedule[path]=sorted(order[:max(1,int(math.sqrt(p)))])\n  schedules.append(schedule)\n return draws,schedules\ndef csvread(file):\n with Path(file).open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))\ndef read_sources(source):\n source=Path(source);raw=csvread(source/'actual320-country-four-indicators-original-2020-2024.csv');lookup={(r['countryISO3'],int(r['date']),r['indicatorID']):r for r in raw};country=[]\n for code in sorted({r['countryISO3']for r in raw}):\n  for year in range(2020,2025):\n   cols=['NY.GDP.PCAP.KD','NY.GDP.MKTP.KD.ZG','FP.CPI.TOTL.ZG','SP.DYN.LE00.IN'];v=[lookup[code,year,k]['originalValueToken']for k in cols];x=[None if not z else Q(z)for z in v[:3]];x[0]=None if x[0]is None else x[0]/10000;y=None if not v[3]else Q(v[3]);eligible=y is not None and None not in x;country.append(dict(id=code+':'+str(year),sourceRow=code+':'+str(year),originalID=code,year=year,x=x,y=y,weight='1',role='excluded'if not eligible else'outer-test'if year==2024 else'train'))\n person=[]\n for i,r in enumerate(csvread(source/'actual3613-NLS-original52-fields-and-selection.csv'),1):\n  v=lambda k:None if r[k]=='.'else Q(r[k]);x=[v('ed76'),v('age76')];y=None if v('wage76')is None else v('wage76')/100;eligible=y is not None and None not in x;person.append(dict(id='person:'+str(i),sourceRow=str(i),originalID=r['id'],x=x,y=y,weight='1',role='excluded'if not eligible else'outer-test'if i%5==0 else'train'))\n company=[]\n for i,r in enumerate(csvread(source/'actual3150-churn-original14-fields-and-selection.csv'),1):company.append(dict(id='customer:'+str(i),sourceRow=str(i),originalID='',x=[Q(r[k])for k in['Call  Failure','Subscription  Length','Charge  Amount']],y=r['Churn'],weight='1',role='outer-test'if i%5==0 else'train'))\n models={}\n for index,(kind,rr,task,leaf)in enumerate([('country',country,'regression',4),('person',person,'regression',50),('company',company,'classification',30)]):\n  ids=[r['id']for r in rr if r['role']=='train'];draws,schedules=fixed_schedules(ids,len(rr[0]['x']),20261102+7919*index);models[kind]=dict(records=rr,task=task,classes=['0','1']if task=='classification'else[],draws=draws,schedules=schedules,minLeaf=leaf)\n return models\n_OMITTED=object()\ndef realdata(models,kind,options=_OMITTED):\n options={}if options is _OMITTED else options\n if not isinstance(options,dict):raise ValueError('options object required, not explicit null')\n m=models[kind];train=[r for r in m['records']if r['role']=='train'];test=[r for r in m['records']if r['role']=='outer-test'];method=options.get('method','forest');depth=options.get('maxDepth',2);count=options.get('memberCount',3);a=dict(rows=train,queries=[dict(id=r['id'],x=r['x'])for r in test],task=m['task'],classes=m['classes'],maxDepth=depth,minLeaf=options.get('minLeaf',m['minLeaf']),minLeafWeight='0',minGain='0',missingRoute='best',learningRate=options.get('learningRate','1/2'),stages=options.get('stages',3))\n if method not in ['bagging','forest','boost']:raise ValueError('known source method')\n if not isinstance(depth,int)or isinstance(depth,bool)or not 0<=depth<=3:raise ValueError('source depth0..3')\n if method!='boost'and(not isinstance(count,int)or isinstance(count,bool)or not 1<=count<=4):raise ValueError('source member count1..4')\n if method=='boost':result=boost(a)\n else:\n  a.update(bootstrapDraws=m['draws'][:count],nodeFeatures=[{p:v for p,v in s.items()if len(p)<depth}for s in m['schedules'][:count]]);result=ensemble(a,method=='forest')\n outer=scored(result['predictions'],normalized(test,m['task']),m['task'],m['classes']);st=totals([r for r in normalized(train,m['task'])if r['w']and r['y']is not None],m['task'],m['classes']);constant=dict(prediction=st['pred'],probabilities=st['p'],vote=st['pred'],prob=st['pred']);baseline=scored([dict(id=r['id'],**constant)for r in test],normalized(test,m['task']),m['task'],m['classes']);return dict(kind=kind,method=method,settings=a,train=train,test=test,result=result,outer=outer,baseline=baseline)\ndef serial(x):\n if isinstance(x,Q):return str(x)\n if isinstance(x,dict):return{k:serial(v)for k,v in x.items()if k not in['inbag','tree']}\n if isinstance(x,(list,tuple)):return[serial(v)for v in x]\n return x\ndef writecsv(file,heads,rows):\n with Path(file).open('w',encoding='utf8',newline='')as f:\n  w=csv.writer(f);w.writerow(heads);w.writerows([[''if v is None else str(v)for v in r]for r in rows])\nAPI='aggregate'\nINPUT={'members': [{'id': 'm1', 'predictions': [{'id': 'q', 'value': 1}]}, {'id': 'm2', 'predictions': [{'id': 'q', 'value': 3}]}], 'memberWeights': [1, 3]}\n\ndef run_fixed(api,a,out,src):\n import matplotlib\n matplotlib.use('svg')\n import matplotlib.pyplot as plt\n from matplotlib.ticker import MaxNLocator\n plt.rcParams.update({'font.size':14,'svg.fonttype':'none','svg.hashsalt':'ml09-fixed-v1'})\n result=variance(a)if api=='variance'else aggregate(a)if api=='aggregate'else ensemble(a,api=='forest')if api in ['bagging','forest']else boost(a)if api=='boost'else realdata(read_sources(src),a['kind'])\n out=Path(out);out.mkdir(parents=True,exist_ok=True);summary={};points=[]\n def add(x,y,s):\n  if y is not None:points.append([x,y,s])\n if api=='variance':\n  summary={'B':result['B'],'varianceOfMean':result['varianceOfMean']};add(result['B'],result['varianceOfMean'],'Specified finite-B variance');xl='Number of members B';yl='Variance, stipulated units squared';title='Declared covariance model, not fitted trees'\n elif api=='aggregate':\n  p=result['predictions'][0];classification=a.get('task')=='classification';summary={'selectedPrediction':p['prediction']}\n  if classification:\n   summary.update(voteLabel=p['vote'],probabilityLabel=p['prob'],meanProbability1=p['probabilities'][1]);add(1,p['probabilities'][1],'Mean probability of class 1');add(2,p['votes'][1],'Label-vote share of class 1');xl='Aggregation (1=probability, 2=vote)';yl='Probability or vote share'\n  else:\n   for i,m in enumerate(a['members']):add(i+1,Q(m['predictions'][0]['value']),'Member prediction')\n   add(3,p['prediction'],'Weighted mean');xl='Member 1, member 2, aggregate 3';yl='Prediction, assumed units'\n  title='Votes and probabilities are distinct objects'\n elif api in ['bagging','forest']:\n  summary={'queryPrediction':result['predictions'][0]['prediction'],'OOB.scoreable':result['outOfBag']['eligibleRows'],'OOB.meanLoss':result['outOfBag']['meanLoss']}\n  for i,r in enumerate(a['rows']):add(i+1,Q(r['y']),'Observed training outcome')\n  for i,p in enumerate(result['outOfBag']['rows']):add(i+1,p['prediction'],'OOB prediction, when defined')\n  xl='Original training ID order';yl='Outcome, assumed units';title='Repeated draws and ID-level OOB membership'\n elif api=='boost':\n  summary={'initial':result['initial'],'finalMSE':result['losses'][-1]['MSE'],'stages':result['stages']}\n  for r in result['losses']:add(r['stage'],r['MSE'],'Training MSE')\n  xl='Boosting stage (0=initial)';yl='Weighted MSE, outcome units squared';title='Training descent does not certify held-out gain'\n else:\n  summary={'outer.scoreable':result['outer']['eligibleRows'],'outer.meanLoss':result['outer']['meanLoss'],'baseline.meanLoss':result['baseline']['meanLoss'],'OOB.scoreable':result['result']['outOfBag']['eligibleRows'],'OOB.meanLoss':result['result']['outOfBag']['meanLoss']}\n  for i,p in enumerate(result['outer']['rows']):\n   add(i+1,Q(p['actual']),'Observed outcome');add(i+1,p['probabilities'][1]if a['kind']=='company'else p['prediction'],'Forest probability of class 1'if a['kind']=='company'else'Forest prediction')\n  xl='Outer-test source order, not a time path';yl='Churn label / probability'if a['kind']=='company'else'Period life expectancy, years'if a['kind']=='country'else'Nominal 1976 USD per hour';title='Fixed forest; outer labels did not fit the trees'\n def display(v):return 'undefined'if v is None else format(float(v),'.9f')\n writecsv(out/'summary.csv',['metric','value'],[[k,display(v)]for k,v in summary.items()]);writecsv(out/'plot-points.csv',['x','y','series'],points);(out/'full.json').write_text(json.dumps(serial(result),indent=2)+'\\n',encoding='utf8')\n fig,ax=plt.subplots(figsize=(5.6,4.6));fig.subplots_adjust(left=.24,right=.96,bottom=.24,top=.76);colors=['#355c72','#a55336','#507956','#78568b']\n for i,s in enumerate(dict.fromkeys(p[2]for p in points)):\n  pp=[p for p in points if p[2]==s];ax.scatter([float(p[0])for p in pp],[float(p[1])for p in pp],s=12 if len(pp)>100 else 32,alpha=.5 if len(pp)>100 else 1,color=colors[i%4],label=s)\n ax.set_xlabel(xl,labelpad=10,fontsize=11);ax.set_ylabel(yl,labelpad=10,fontsize=11);ax.xaxis.set_major_locator(MaxNLocator(3));ax.yaxis.set_major_locator(MaxNLocator(4));ax.grid(alpha=.18);ax.legend(loc='lower left',bbox_to_anchor=(0,1.01),fontsize=9,frameon=False);fig.suptitle(title,fontsize=9,y=.99);fig.savefig(out/'plot.svg',metadata={'Date':None});plt.close(fig);print(', '.join(k+'='+display(v)for k,v in summary.items()))\nif __name__=='__main__':\n import sys\n try:run_fixed(API,INPUT,sys.argv[1]if len(sys.argv)>1 else'fixed-results',sys.argv[2]if len(sys.argv)>2 else'ml09-sources')\n except ValueError as error:print('Rejected declared input: '+str(error),file=sys.stderr);sys.exit(2)\n",
        "code": "\"\"\"ML09 exact Fraction reproduction from native source fields.\n\npython ml09-public-analysis.py --source-dir ml09-sources --output-dir results\n\nThis authored educational implementation uses direct-centered leaf losses and\nexhaustive midpoint partitions. It reads no JS engine, model contract, checker,\nstored target answers or derived-result CSV. Its five tree arithmetic helpers\nwere copied from the author's own separate Fraction reference, not an independent\npeer. Parser/work budgets and display rounding of the production JS are separate.\nNumerical predictions/proper scores do not certify causal effects, calibration,\nIID OOB validity, survey representativeness or production parameter optimality.\n\"\"\"\nfrom pathlib import Path\nfrom fractions import Fraction as Q\nimport csv,json,math,itertools,argparse\n\ndef normalized(rows,task='regression'):\n return [dict(id=r.get('id',i),x=[None if x is None else Q(x)for x in r.get('x',[])],y=None if r['y']is None else str(r['y'])if task=='classification'else Q(r['y']),w=Q(r.get('weight',1)))for i,r in enumerate(rows)]\n\ndef totals(rows,task,classes):\n W=sum((r['w']for r in rows),Q());mu=sum((r['w']*r['y']for r in rows),Q())/W if task=='regression'and W else None\n probs=[sum((r['w']for r in rows if r['y']==c),Q())/W for c in classes]if task=='classification'and W else[]\n risk=sum((r['w']*(r['y']-mu)**2 for r in rows),Q())if task=='regression'and W else W*sum((p*(1-p)for p in probs),Q())\n return dict(n=len(rows),w=W,mu=mu,p=probs,risk=risk,pred=mu if task=='regression'else classes[max(range(len(probs)),key=lambda i:probs[i])]if probs else None)\n\ndef fit(rows,a,task,classes,schedule=None):\n good=[r for r in rows if r['w']>0 and r['y']is not None];root=totals(good,task,classes)['w'];depth=a.get('maxDepth',2);minimum=a.get('minLeaf',1);minmass=Q(a.get('minLeafWeight',0));mingain=Q(a.get('minGain',0));route=a.get('missingRoute','best')\n def build(rr,d,path):\n  st=totals(rr,task,classes);n=dict(rows=rr,st=st,split=None,left=None,right=None,path=path)\n  if d==depth:return n\n  best=None\n  for j in range(len(rr[0]['x'])):\n   if schedule is not None and j not in schedule[path]:continue\n   values=sorted({r['x'][j]for r in rr if r['x'][j]is not None});missing=[r for r in rr if r['x'][j]is None];observed=[r for r in rr if r['x'][j]is not None]\n   candidates=[]\n   for lo,hi in zip(values,values[1:]):\n    q=(lo+hi)/2;left=[r for r in observed if r['x'][j]<=q];right=[r for r in observed if r['x'][j]>q];directions=[route]if route!='best'else['left','right']if missing else['left'if len(left)>=len(right)else'right']\n    for direction in directions:candidates.append(('threshold',q,direction,left+missing if direction=='left'else left,right+missing if direction=='right'else right))\n   if missing and observed:candidates.append(('missing-only',None,'left',missing,observed))\n   for kind,q,direction,left,right in candidates:\n    l=totals(left,task,classes);r=totals(right,task,classes)\n    if min(l['n'],r['n'])<minimum or min(l['w'],r['w'])<minmass or min(l['w'],r['w'])<=0:continue\n    gain=(st['risk']-l['risk']-r['risk'])/root\n    if best is None or gain>best['gain']:best=dict(feature=j,kind=kind,threshold=q,missingRoute=direction,left=left,right=right,gain=gain)\n  if best and best['gain']>0 and best['gain']>mingain:\n   j=best['feature'];go=lambda r:r['x'][j]is None if best['kind']=='missing-only'else best['missingRoute']=='left'if r['x'][j]is None else r['x'][j]<=best['threshold'];n['split']=best;n['left']=build([r for r in rr if go(r)],d+1,path+'L');n['right']=build([r for r in rr if not go(r)],d+1,path+'R')\n  return n\n return build(good,0,'')\n\ndef predict(tree,x):\n n=tree\n while n['split']:\n  s=n['split'];v=x[s['feature']];left=v is None if s['kind']=='missing-only'else s['missingRoute']=='left'if v is None else v<=s['threshold'];n=n['left'if left else'right']\n return dict(prediction=n['st']['pred'],probabilities=n['st']['p'])\n\ndef combine(preds,w,task,classes,mode='probabilities'):\n mass=sum(w,Q())\n if not preds or not mass:return dict(prediction=None,probabilities=[],vote=None,prob=None)\n if task=='regression':return dict(prediction=sum((p['prediction']*v for p,v in zip(preds,w)),Q())/mass,probabilities=[],vote=None,prob=None)\n votes=[sum((v for p,v in zip(preds,w)if p['prediction']==c),Q())/mass for c in classes];ps=[sum((p['probabilities'][j]*v for p,v in zip(preds,w)),Q())/mass for j in range(len(classes))];vote=classes[max(range(len(classes)),key=lambda j:votes[j])];prob=classes[max(range(len(classes)),key=lambda j:ps[j])];return dict(prediction=vote if mode=='votes'else prob,probabilities=ps,vote=vote,prob=prob,votes=votes)\ndef number(v):\n if v is None or isinstance(v,bool):raise ValueError('explicit null/bool is not a numeric parameter')\n return Q(v)\ndef variance(a):\n B=a['B'];v=number(a['marginalVariance']);rho=number(a.get('rho',0))\n if not isinstance(B,int)or isinstance(B,bool)or B<1 or v<0:raise ValueError('positive integer B/nonnegative variance')\n if B>1 and v and not -Q(1,B-1)<=rho<=1:raise ValueError('equicorrelation PSD bound')\n return dict(B=B,marginalVariance=v,correlationApplicable=B>1 and bool(v),varianceOfMean=v if B==1 else v*(1+(B-1)*rho)/B)\ndef aggregate(a):\n task=a.get('task','regression');classes=[str(c)for c in a.get('classes',[])];members=a['members'];w=[number(v)for v in a.get('memberWeights',[1]*len(members))]\n if not members or min(w)<0 or sum(w)<=0:raise ValueError('nonnegative member weights/positive total')\n order=[p.get('id',i)for i,p in enumerate(members[0]['predictions'])];keys=lambda x:(type(x).__name__,x);lookup=[{keys(p.get('id',i)):p for i,p in enumerate(m['predictions'])}for m in members]\n if any(set(m)!={keys(v)for v in order}for m in lookup):raise ValueError('same query ID set')\n out=[]\n for pid in order:\n  predictions=[dict(prediction=number(m[keys(pid)]['value']),probabilities=[])if task=='regression'else dict(prediction=str(m[keys(pid)]['label']),probabilities=[number(v)for v in m[keys(pid)]['probabilities']])for m in lookup]\n  if task=='classification'and any(min(p['probabilities'])<0 or sum(p['probabilities'])!=1 for p in predictions):raise ValueError('probability simplex')\n  out.append(dict(id=pid,**combine(predictions,w,task,classes,a.get('aggregation','probabilities'))))\n return dict(task=task,classes=classes,predictions=out)\ndef scored(preds,rows,task,classes):\n mass=loss=absolute=errors=voteerrors=Q();out=[]\n for p,r in zip(preds,rows):\n  ok=p['prediction']is not None and r['y']is not None and r['w']>0;v=None\n  if ok:\n   mass+=r['w']\n   if task=='regression':e=r['y']-p['prediction'];v=e*e;absolute+=r['w']*abs(e)\n   else:v=sum(((q-(1 if r['y']==c else 0))**2 for c,q in zip(classes,p['probabilities'])),Q());errors+=r['w']*(p['prediction']!=r['y']);voteerrors+=r['w']*(p['vote']!=r['y'])\n   loss+=r['w']*v\n  out.append(dict(p,actual=r['y'],weight=r['w'],scoreEligible=ok,loss=v))\n return dict(rows=out,eligibleRows=sum(r['scoreEligible']for r in out),weight=mass,totalLoss=loss,meanLoss=loss/mass if mass else None,MAE=absolute/mass if mass and task=='regression'else None,errorRate=errors/mass if mass and task=='classification'else None,labelVoteErrorRate=voteerrors/mass if mass and task=='classification'else None)\ndef ensemble(a,forest=False):\n task=a.get('task','regression');classes=[str(v)for v in(a.get('classes')or[])];rr=normalized(a['rows'],task);key=lambda x:(type(x).__name__,x);lookup={key(r['id']):r for r in rr};weights=[number(v)for v in a.get('memberWeights',[1]*len(a['bootstrapDraws']))]\n if not any(r['w']>0 and r['y']is not None for r in rr)or min(weights)<0 or sum(weights)<=0:raise ValueError('positive eligible training and member weight')\n members=[]\n for i,draw in enumerate(a['bootstrapDraws']):\n  data=[lookup[key(v)]for v in draw];schedule=a['nodeFeatures'][i]if forest else None;model=fit(data,a,task,classes,schedule);inbag={key(v)for v in draw};members.append(dict(tree=model,draw=draw,inbag=inbag,weight=weights[i]))\n predictions=[]\n for q in a.get('queries',[]):predictions.append(dict(id=q['id'],**combine([predict(m['tree'],[None if v is None else number(v)for v in q['x']])for m in members],weights,task,classes,a.get('aggregation','probabilities'))))\n oob=[]\n for r in rr:\n  applicable=[i for i,m in enumerate(members)if key(r['id'])not in m['inbag']];p=combine([predict(members[i]['tree'],r['x'])for i in applicable],[weights[i]for i in applicable],task,classes,a.get('aggregation','probabilities'));oob.append(dict(id=r['id'],applicable=applicable,positiveMembers=sum(weights[i]>0 for i in applicable),**p))\n return dict(task=task,classes=classes,members=members,predictions=predictions,outOfBag=scored(oob,rr,task,classes))\ndef boost(a):\n if a.get('task','regression')!='regression':raise ValueError('regression boosting only')\n rr=normalized(a['rows']);good=[r for r in rr if r['w']and r['y']is not None];W=sum((r['w']for r in good),Q())\n if not W:raise ValueError('positive eligible training')\n eta=number(a.get('learningRate','1/2'));stages=a.get('stages',3)\n if not 0<=eta<=1 or not isinstance(stages,int)or isinstance(stages,bool)or not 0<=stages<=8:raise ValueError('supported rate/stages')\n initial=number(a['initial'])if'initial'in a else sum((r['w']*r['y']for r in good),Q())/W;training=[[initial]for r in rr];queries=[[initial]for q in a.get('queries',[])];fits=[];losses=[]\n for stage in range(stages+1):\n  sse=sum((r['w']*(r['y']-p[-1])**2 for r,p in zip(rr,training)if r['w']and r['y']is not None),Q());losses.append(dict(stage=stage,rawWeightedSSE=sse,MSE=sse/W,meanHalfSquaredLoss=sse/(2*W)))\n  if stage==stages:break\n  residuals=[dict(r,y=None if r['y']is None else r['y']-p[-1])for r,p in zip(rr,training)];tree=fit(residuals,a,'regression',[]);h=[predict(tree,r['x'])['prediction']for r in rr];qh=[predict(tree,[None if v is None else number(v)for v in q['x']])['prediction']for q in a.get('queries',[])];norm=sum((r['w']*v*v for r,v in zip(rr,h)if r['y']is not None),Q());stageRows=[]\n  for i,(r,p)in enumerate(zip(rr,training)):\n   residual=None if r['y']is None else r['y']-p[-1];stageRows.append(dict(id=r['id'],before=p[-1],residual=residual,negativeCoordinateDerivative=None if residual is None else r['w']*residual/W,fit=h[i],addition=eta*h[i],after=p[-1]+eta*h[i]));p.append(p[-1]+eta*h[i])\n  for p,v in zip(queries,qh):p.append(p[-1]+eta*v)\n  fits.append(dict(stage=stage+1,tree=tree,rows=stageRows,queryFits=qh,norm=norm,predictedSSEDecrease=eta*(2-eta)*norm))\n return dict(task='regression',initial=initial,learningRate=eta,stages=stages,training=training,queries=queries,fits=fits,losses=losses,predictions=[dict(id=q['id'],prediction=p[-1],probabilities=[],vote=None,prob=None)for q,p in zip(a.get('queries',[]),queries)])\nclass Stream:\n def __init__(self,state):self.state=state\n def choose(self,n):\n  limit=(1<<32)-((1<<32)%n)\n  while True:\n   self.state=(1664525*self.state+1013904223)&0xffffffff\n   if self.state<limit:return self.state%n\ndef fixed_schedules(ids,p,seed):\n stream=Stream(seed);draws=[];schedules=[];paths=['']+[p for d in[1,2]for p in map(''.join,itertools.product('LR',repeat=d))]\n for member in range(4):\n  draws.append([ids[stream.choose(len(ids))]for _ in range(len(ids))]);schedule={}\n  for path in paths:\n   order=list(range(p))\n   for j in range(p-1,0,-1):k=stream.choose(j+1);order[j],order[k]=order[k],order[j]\n   schedule[path]=sorted(order[:max(1,int(math.sqrt(p)))])\n  schedules.append(schedule)\n return draws,schedules\ndef csvread(file):\n with Path(file).open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))\ndef read_sources(source):\n source=Path(source);raw=csvread(source/'actual320-country-four-indicators-original-2020-2024.csv');lookup={(r['countryISO3'],int(r['date']),r['indicatorID']):r for r in raw};country=[]\n for code in sorted({r['countryISO3']for r in raw}):\n  for year in range(2020,2025):\n   cols=['NY.GDP.PCAP.KD','NY.GDP.MKTP.KD.ZG','FP.CPI.TOTL.ZG','SP.DYN.LE00.IN'];v=[lookup[code,year,k]['originalValueToken']for k in cols];x=[None if not z else Q(z)for z in v[:3]];x[0]=None if x[0]is None else x[0]/10000;y=None if not v[3]else Q(v[3]);eligible=y is not None and None not in x;country.append(dict(id=code+':'+str(year),sourceRow=code+':'+str(year),originalID=code,year=year,x=x,y=y,weight='1',role='excluded'if not eligible else'outer-test'if year==2024 else'train'))\n person=[]\n for i,r in enumerate(csvread(source/'actual3613-NLS-original52-fields-and-selection.csv'),1):\n  v=lambda k:None if r[k]=='.'else Q(r[k]);x=[v('ed76'),v('age76')];y=None if v('wage76')is None else v('wage76')/100;eligible=y is not None and None not in x;person.append(dict(id='person:'+str(i),sourceRow=str(i),originalID=r['id'],x=x,y=y,weight='1',role='excluded'if not eligible else'outer-test'if i%5==0 else'train'))\n company=[]\n for i,r in enumerate(csvread(source/'actual3150-churn-original14-fields-and-selection.csv'),1):company.append(dict(id='customer:'+str(i),sourceRow=str(i),originalID='',x=[Q(r[k])for k in['Call  Failure','Subscription  Length','Charge  Amount']],y=r['Churn'],weight='1',role='outer-test'if i%5==0 else'train'))\n models={}\n for index,(kind,rr,task,leaf)in enumerate([('country',country,'regression',4),('person',person,'regression',50),('company',company,'classification',30)]):\n  ids=[r['id']for r in rr if r['role']=='train'];draws,schedules=fixed_schedules(ids,len(rr[0]['x']),20261102+7919*index);models[kind]=dict(records=rr,task=task,classes=['0','1']if task=='classification'else[],draws=draws,schedules=schedules,minLeaf=leaf)\n return models\n_OMITTED=object()\ndef realdata(models,kind,options=_OMITTED):\n options={}if options is _OMITTED else options\n if not isinstance(options,dict):raise ValueError('options object required, not explicit null')\n m=models[kind];train=[r for r in m['records']if r['role']=='train'];test=[r for r in m['records']if r['role']=='outer-test'];method=options.get('method','forest');depth=options.get('maxDepth',2);count=options.get('memberCount',3);a=dict(rows=train,queries=[dict(id=r['id'],x=r['x'])for r in test],task=m['task'],classes=m['classes'],maxDepth=depth,minLeaf=options.get('minLeaf',m['minLeaf']),minLeafWeight='0',minGain='0',missingRoute='best',learningRate=options.get('learningRate','1/2'),stages=options.get('stages',3))\n if method not in ['bagging','forest','boost']:raise ValueError('known source method')\n if not isinstance(depth,int)or isinstance(depth,bool)or not 0<=depth<=3:raise ValueError('source depth0..3')\n if method!='boost'and(not isinstance(count,int)or isinstance(count,bool)or not 1<=count<=4):raise ValueError('source member count1..4')\n if method=='boost':result=boost(a)\n else:\n  a.update(bootstrapDraws=m['draws'][:count],nodeFeatures=[{p:v for p,v in s.items()if len(p)<depth}for s in m['schedules'][:count]]);result=ensemble(a,method=='forest')\n outer=scored(result['predictions'],normalized(test,m['task']),m['task'],m['classes']);st=totals([r for r in normalized(train,m['task'])if r['w']and r['y']is not None],m['task'],m['classes']);constant=dict(prediction=st['pred'],probabilities=st['p'],vote=st['pred'],prob=st['pred']);baseline=scored([dict(id=r['id'],**constant)for r in test],normalized(test,m['task']),m['task'],m['classes']);return dict(kind=kind,method=method,settings=a,train=train,test=test,result=result,outer=outer,baseline=baseline)\ndef serial(x):\n if isinstance(x,Q):return str(x)\n if isinstance(x,dict):return{k:serial(v)for k,v in x.items()if k not in['inbag','tree']}\n if isinstance(x,(list,tuple)):return[serial(v)for v in x]\n return x\ndef writecsv(file,heads,rows):\n with Path(file).open('w',encoding='utf8',newline='')as f:\n  w=csv.writer(f);w.writerow(heads);w.writerows([[''if v is None else str(v)for v in r]for r in rows])\nAPI='aggregate'\nINPUT={'members': [{'id': 'm1', 'predictions': [{'id': 'q', 'value': 1}]}, {'id': 'm2', 'predictions': [{'id': 'q', 'value': 3}]}], 'memberWeights': [1, 3]}\n\ndef run_fixed(api,a,out,src):\n import matplotlib\n matplotlib.use('svg')\n import matplotlib.pyplot as plt\n from matplotlib.ticker import MaxNLocator\n plt.rcParams.update({'font.size':14,'svg.fonttype':'none','svg.hashsalt':'ml09-fixed-v1'})\n result=variance(a)if api=='variance'else aggregate(a)if api=='aggregate'else ensemble(a,api=='forest')if api in ['bagging','forest']else boost(a)if api=='boost'else realdata(read_sources(src),a['kind'])\n out=Path(out);out.mkdir(parents=True,exist_ok=True);summary={};points=[]\n def add(x,y,s):\n  if y is not None:points.append([x,y,s])\n if api=='variance':\n  summary={'B':result['B'],'varianceOfMean':result['varianceOfMean']};add(result['B'],result['varianceOfMean'],'Specified finite-B variance');xl='Number of members B';yl='Variance, stipulated units squared';title='Declared covariance model, not fitted trees'\n elif api=='aggregate':\n  p=result['predictions'][0];classification=a.get('task')=='classification';summary={'selectedPrediction':p['prediction']}\n  if classification:\n   summary.update(voteLabel=p['vote'],probabilityLabel=p['prob'],meanProbability1=p['probabilities'][1]);add(1,p['probabilities'][1],'Mean probability of class 1');add(2,p['votes'][1],'Label-vote share of class 1');xl='Aggregation (1=probability, 2=vote)';yl='Probability or vote share'\n  else:\n   for i,m in enumerate(a['members']):add(i+1,Q(m['predictions'][0]['value']),'Member prediction')\n   add(3,p['prediction'],'Weighted mean');xl='Member 1, member 2, aggregate 3';yl='Prediction, assumed units'\n  title='Votes and probabilities are distinct objects'\n elif api in ['bagging','forest']:\n  summary={'queryPrediction':result['predictions'][0]['prediction'],'OOB.scoreable':result['outOfBag']['eligibleRows'],'OOB.meanLoss':result['outOfBag']['meanLoss']}\n  for i,r in enumerate(a['rows']):add(i+1,Q(r['y']),'Observed training outcome')\n  for i,p in enumerate(result['outOfBag']['rows']):add(i+1,p['prediction'],'OOB prediction, when defined')\n  xl='Original training ID order';yl='Outcome, assumed units';title='Repeated draws and ID-level OOB membership'\n elif api=='boost':\n  summary={'initial':result['initial'],'finalMSE':result['losses'][-1]['MSE'],'stages':result['stages']}\n  for r in result['losses']:add(r['stage'],r['MSE'],'Training MSE')\n  xl='Boosting stage (0=initial)';yl='Weighted MSE, outcome units squared';title='Training descent does not certify held-out gain'\n else:\n  summary={'outer.scoreable':result['outer']['eligibleRows'],'outer.meanLoss':result['outer']['meanLoss'],'baseline.meanLoss':result['baseline']['meanLoss'],'OOB.scoreable':result['result']['outOfBag']['eligibleRows'],'OOB.meanLoss':result['result']['outOfBag']['meanLoss']}\n  for i,p in enumerate(result['outer']['rows']):\n   add(i+1,Q(p['actual']),'Observed outcome');add(i+1,p['probabilities'][1]if a['kind']=='company'else p['prediction'],'Forest probability of class 1'if a['kind']=='company'else'Forest prediction')\n  xl='Outer-test source order, not a time path';yl='Churn label / probability'if a['kind']=='company'else'Period life expectancy, years'if a['kind']=='country'else'Nominal 1976 USD per hour';title='Fixed forest; outer labels did not fit the trees'\n def display(v):return 'undefined'if v is None else format(float(v),'.9f')\n writecsv(out/'summary.csv',['metric','value'],[[k,display(v)]for k,v in summary.items()]);writecsv(out/'plot-points.csv',['x','y','series'],points);(out/'full.json').write_text(json.dumps(serial(result),indent=2)+'\\n',encoding='utf8')\n fig,ax=plt.subplots(figsize=(5.6,4.6));fig.subplots_adjust(left=.24,right=.96,bottom=.24,top=.76);colors=['#355c72','#a55336','#507956','#78568b']\n for i,s in enumerate(dict.fromkeys(p[2]for p in points)):\n  pp=[p for p in points if p[2]==s];ax.scatter([float(p[0])for p in pp],[float(p[1])for p in pp],s=12 if len(pp)>100 else 32,alpha=.5 if len(pp)>100 else 1,color=colors[i%4],label=s)\n ax.set_xlabel(xl,labelpad=10,fontsize=11);ax.set_ylabel(yl,labelpad=10,fontsize=11);ax.xaxis.set_major_locator(MaxNLocator(3));ax.yaxis.set_major_locator(MaxNLocator(4));ax.grid(alpha=.18);ax.legend(loc='lower left',bbox_to_anchor=(0,1.01),fontsize=9,frameon=False);fig.suptitle(title,fontsize=9,y=.99);fig.savefig(out/'plot.svg',metadata={'Date':None});plt.close(fig);print(', '.join(k+'='+display(v)for k,v in summary.items()))\nif __name__=='__main__':\n import sys\n try:run_fixed(API,INPUT,sys.argv[1]if len(sys.argv)>1 else'fixed-results',sys.argv[2]if len(sys.argv)>2 else'ml09-sources')\n except ValueError as error:print('Rejected declared input: '+str(error),file=sys.stderr);sys.exit(2)\n",
        "inputFiles": [],
        "input": {
          "members": [
            {
              "id": "m1",
              "predictions": [
                {
                  "id": "q",
                  "value": 1
                }
              ]
            },
            {
              "id": "m2",
              "predictions": [
                {
                  "id": "q",
                  "value": 3
                }
              ]
            }
          ],
          "memberWeights": [
            1,
            3
          ]
        },
        "returnCode": 0,
        "expectedFailure": false,
        "stdout": "selectedPrediction=2.500000000\n",
        "stderr": "",
        "summary": {
          "selectedPrediction": "2.500000000"
        },
        "plotPoints": [
          {
            "x": "1",
            "y": "1",
            "series": "Member prediction"
          },
          {
            "x": "2",
            "y": "3",
            "series": "Member prediction"
          },
          {
            "x": "3",
            "y": "5/2",
            "series": "Weighted mean"
          }
        ],
        "plotFile": "ml09-fixed-results/aggregate-weighted-mean-python/plot.svg",
        "plotSHA256": "8f8268290442557b452c6099e27a54eb43bb3f0f9db6261f8888926a1a0b76eb",
        "files": [
          {
            "file": "ml09-fixed-results/aggregate-weighted-mean-python/full.json",
            "sha256": "f46db3b142af8420fce031f37519d628c7f844af7eb5dfa6715277911e1e8bc7"
          },
          {
            "file": "ml09-fixed-results/aggregate-weighted-mean-python/plot-points.csv",
            "sha256": "2f96c7ef3a041e14eda6fa949c23d335a717a71b3e8676020a354dca9038b622"
          },
          {
            "file": "ml09-fixed-results/aggregate-weighted-mean-python/plot.svg",
            "sha256": "8f8268290442557b452c6099e27a54eb43bb3f0f9db6261f8888926a1a0b76eb"
          },
          {
            "file": "ml09-fixed-results/aggregate-weighted-mean-python/summary.csv",
            "sha256": "941793b3441f2feab14bc0ca7b58a6281c9b9241ca3445c719654b7e7e72da32"
          }
        ],
        "scope": "Actually executed self-contained fixed example; current web controls execute separately. Python Fraction and finite-precision base R. Author gate, not independent peer."
      },
      "votes-versus-probabilities": {
        "api": "aggregate",
        "variant": "votes-versus-probabilities",
        "language": "python",
        "codeFile": "ml09-code/aggregate-votes-versus-probabilities.py",
        "codeSHA256": "f39a109f46be140009e43676dbb68ce981e9f23aa4517f2d7675a87e8e461f75",
        "codeText": "\"\"\"ML09 exact Fraction reproduction from native source fields.\n\npython ml09-public-analysis.py --source-dir ml09-sources --output-dir results\n\nThis authored educational implementation uses direct-centered leaf losses and\nexhaustive midpoint partitions. It reads no JS engine, model contract, checker,\nstored target answers or derived-result CSV. Its five tree arithmetic helpers\nwere copied from the author's own separate Fraction reference, not an independent\npeer. Parser/work budgets and display rounding of the production JS are separate.\nNumerical predictions/proper scores do not certify causal effects, calibration,\nIID OOB validity, survey representativeness or production parameter optimality.\n\"\"\"\nfrom pathlib import Path\nfrom fractions import Fraction as Q\nimport csv,json,math,itertools,argparse\n\ndef normalized(rows,task='regression'):\n return [dict(id=r.get('id',i),x=[None if x is None else Q(x)for x in r.get('x',[])],y=None if r['y']is None else str(r['y'])if task=='classification'else Q(r['y']),w=Q(r.get('weight',1)))for i,r in enumerate(rows)]\n\ndef totals(rows,task,classes):\n W=sum((r['w']for r in rows),Q());mu=sum((r['w']*r['y']for r in rows),Q())/W if task=='regression'and W else None\n probs=[sum((r['w']for r in rows if r['y']==c),Q())/W for c in classes]if task=='classification'and W else[]\n risk=sum((r['w']*(r['y']-mu)**2 for r in rows),Q())if task=='regression'and W else W*sum((p*(1-p)for p in probs),Q())\n return dict(n=len(rows),w=W,mu=mu,p=probs,risk=risk,pred=mu if task=='regression'else classes[max(range(len(probs)),key=lambda i:probs[i])]if probs else None)\n\ndef fit(rows,a,task,classes,schedule=None):\n good=[r for r in rows if r['w']>0 and r['y']is not None];root=totals(good,task,classes)['w'];depth=a.get('maxDepth',2);minimum=a.get('minLeaf',1);minmass=Q(a.get('minLeafWeight',0));mingain=Q(a.get('minGain',0));route=a.get('missingRoute','best')\n def build(rr,d,path):\n  st=totals(rr,task,classes);n=dict(rows=rr,st=st,split=None,left=None,right=None,path=path)\n  if d==depth:return n\n  best=None\n  for j in range(len(rr[0]['x'])):\n   if schedule is not None and j not in schedule[path]:continue\n   values=sorted({r['x'][j]for r in rr if r['x'][j]is not None});missing=[r for r in rr if r['x'][j]is None];observed=[r for r in rr if r['x'][j]is not None]\n   candidates=[]\n   for lo,hi in zip(values,values[1:]):\n    q=(lo+hi)/2;left=[r for r in observed if r['x'][j]<=q];right=[r for r in observed if r['x'][j]>q];directions=[route]if route!='best'else['left','right']if missing else['left'if len(left)>=len(right)else'right']\n    for direction in directions:candidates.append(('threshold',q,direction,left+missing if direction=='left'else left,right+missing if direction=='right'else right))\n   if missing and observed:candidates.append(('missing-only',None,'left',missing,observed))\n   for kind,q,direction,left,right in candidates:\n    l=totals(left,task,classes);r=totals(right,task,classes)\n    if min(l['n'],r['n'])<minimum or min(l['w'],r['w'])<minmass or min(l['w'],r['w'])<=0:continue\n    gain=(st['risk']-l['risk']-r['risk'])/root\n    if best is None or gain>best['gain']:best=dict(feature=j,kind=kind,threshold=q,missingRoute=direction,left=left,right=right,gain=gain)\n  if best and best['gain']>0 and best['gain']>mingain:\n   j=best['feature'];go=lambda r:r['x'][j]is None if best['kind']=='missing-only'else best['missingRoute']=='left'if r['x'][j]is None else r['x'][j]<=best['threshold'];n['split']=best;n['left']=build([r for r in rr if go(r)],d+1,path+'L');n['right']=build([r for r in rr if not go(r)],d+1,path+'R')\n  return n\n return build(good,0,'')\n\ndef predict(tree,x):\n n=tree\n while n['split']:\n  s=n['split'];v=x[s['feature']];left=v is None if s['kind']=='missing-only'else s['missingRoute']=='left'if v is None else v<=s['threshold'];n=n['left'if left else'right']\n return dict(prediction=n['st']['pred'],probabilities=n['st']['p'])\n\ndef combine(preds,w,task,classes,mode='probabilities'):\n mass=sum(w,Q())\n if not preds or not mass:return dict(prediction=None,probabilities=[],vote=None,prob=None)\n if task=='regression':return dict(prediction=sum((p['prediction']*v for p,v in zip(preds,w)),Q())/mass,probabilities=[],vote=None,prob=None)\n votes=[sum((v for p,v in zip(preds,w)if p['prediction']==c),Q())/mass for c in classes];ps=[sum((p['probabilities'][j]*v for p,v in zip(preds,w)),Q())/mass for j in range(len(classes))];vote=classes[max(range(len(classes)),key=lambda j:votes[j])];prob=classes[max(range(len(classes)),key=lambda j:ps[j])];return dict(prediction=vote if mode=='votes'else prob,probabilities=ps,vote=vote,prob=prob,votes=votes)\ndef number(v):\n if v is None or isinstance(v,bool):raise ValueError('explicit null/bool is not a numeric parameter')\n return Q(str(v))\ndef variance(a):\n B=a['B'];v=number(a['marginalVariance']);rho=number(a.get('rho',0))\n if not isinstance(B,int)or isinstance(B,bool)or B<1 or v<0:raise ValueError('positive integer B/nonnegative variance')\n if B>1 and v and not -Q(1,B-1)<=rho<=1:raise ValueError('equicorrelation PSD bound')\n return dict(B=B,marginalVariance=v,correlationApplicable=B>1 and bool(v),varianceOfMean=v if B==1 else v*(1+(B-1)*rho)/B)\ndef aggregate(a):\n task=a.get('task','regression');classes=[str(c)for c in a.get('classes',[])];members=a['members'];w=[number(v)for v in a.get('memberWeights',[1]*len(members))]\n if not members or min(w)<0 or sum(w)<=0:raise ValueError('nonnegative member weights/positive total')\n order=[p.get('id',i)for i,p in enumerate(members[0]['predictions'])];keys=lambda x:(type(x).__name__,x);lookup=[{keys(p.get('id',i)):p for i,p in enumerate(m['predictions'])}for m in members]\n if any(set(m)!={keys(v)for v in order}for m in lookup):raise ValueError('same query ID set')\n out=[]\n for pid in order:\n  predictions=[dict(prediction=number(m[keys(pid)]['value']),probabilities=[])if task=='regression'else dict(prediction=str(m[keys(pid)]['label']),probabilities=[number(v)for v in m[keys(pid)]['probabilities']])for m in lookup]\n  if task=='classification'and any(min(p['probabilities'])<0 or sum(p['probabilities'])!=1 for p in predictions):raise ValueError('probability simplex')\n  out.append(dict(id=pid,**combine(predictions,w,task,classes,a.get('aggregation','probabilities'))))\n return dict(task=task,classes=classes,predictions=out)\ndef scored(preds,rows,task,classes):\n mass=loss=absolute=errors=voteerrors=Q();out=[]\n for p,r in zip(preds,rows):\n  ok=p['prediction']is not None and r['y']is not None and r['w']>0;v=None\n  if ok:\n   mass+=r['w']\n   if task=='regression':e=r['y']-p['prediction'];v=e*e;absolute+=r['w']*abs(e)\n   else:v=sum(((q-(1 if r['y']==c else 0))**2 for c,q in zip(classes,p['probabilities'])),Q());errors+=r['w']*(p['prediction']!=r['y']);voteerrors+=r['w']*(p['vote']!=r['y'])\n   loss+=r['w']*v\n  out.append(dict(p,actual=r['y'],weight=r['w'],scoreEligible=ok,loss=v))\n return dict(rows=out,eligibleRows=sum(r['scoreEligible']for r in out),weight=mass,totalLoss=loss,meanLoss=loss/mass if mass else None,MAE=absolute/mass if mass and task=='regression'else None,errorRate=errors/mass if mass and task=='classification'else None,labelVoteErrorRate=voteerrors/mass if mass and task=='classification'else None)\ndef ensemble(a,forest=False):\n task=a.get('task','regression');classes=[str(v)for v in(a.get('classes')or[])];rr=normalized(a['rows'],task);key=lambda x:(type(x).__name__,x);lookup={key(r['id']):r for r in rr};weights=[number(v)for v in a.get('memberWeights',[1]*len(a['bootstrapDraws']))]\n if not any(r['w']>0 and r['y']is not None for r in rr)or min(weights)<0 or sum(weights)<=0:raise ValueError('positive eligible training and member weight')\n members=[]\n for i,draw in enumerate(a['bootstrapDraws']):\n  data=[lookup[key(v)]for v in draw];schedule=a['nodeFeatures'][i]if forest else None;model=fit(data,a,task,classes,schedule);inbag={key(v)for v in draw};members.append(dict(tree=model,draw=draw,inbag=inbag,weight=weights[i]))\n predictions=[]\n for q in a.get('queries',[]):predictions.append(dict(id=q['id'],**combine([predict(m['tree'],[None if v is None else number(v)for v in q['x']])for m in members],weights,task,classes,a.get('aggregation','probabilities'))))\n oob=[]\n for r in rr:\n  applicable=[i for i,m in enumerate(members)if key(r['id'])not in m['inbag']];p=combine([predict(members[i]['tree'],r['x'])for i in applicable],[weights[i]for i in applicable],task,classes,a.get('aggregation','probabilities'));oob.append(dict(id=r['id'],applicable=applicable,positiveMembers=sum(weights[i]>0 for i in applicable),**p))\n return dict(task=task,classes=classes,members=members,predictions=predictions,outOfBag=scored(oob,rr,task,classes))\ndef boost(a):\n if a.get('task','regression')!='regression':raise ValueError('regression boosting only')\n rr=normalized(a['rows']);good=[r for r in rr if r['w']and r['y']is not None];W=sum((r['w']for r in good),Q())\n if not W:raise ValueError('positive eligible training')\n eta=number(a.get('learningRate','1/2'));stages=a.get('stages',3)\n if not 0<=eta<=1 or not isinstance(stages,int)or isinstance(stages,bool)or not 0<=stages<=8:raise ValueError('supported rate/stages')\n initial=number(a['initial'])if'initial'in a else sum((r['w']*r['y']for r in good),Q())/W;training=[[initial]for r in rr];queries=[[initial]for q in a.get('queries',[])];fits=[];losses=[]\n for stage in range(stages+1):\n  sse=sum((r['w']*(r['y']-p[-1])**2 for r,p in zip(rr,training)if r['w']and r['y']is not None),Q());losses.append(dict(stage=stage,rawWeightedSSE=sse,MSE=sse/W,meanHalfSquaredLoss=sse/(2*W)))\n  if stage==stages:break\n  residuals=[dict(r,y=None if r['y']is None else r['y']-p[-1])for r,p in zip(rr,training)];tree=fit(residuals,a,'regression',[]);h=[predict(tree,r['x'])['prediction']for r in rr];qh=[predict(tree,[None if v is None else number(v)for v in q['x']])['prediction']for q in a.get('queries',[])];norm=sum((r['w']*v*v for r,v in zip(rr,h)if r['y']is not None),Q());stageRows=[]\n  for i,(r,p)in enumerate(zip(rr,training)):\n   residual=None if r['y']is None else r['y']-p[-1];stageRows.append(dict(id=r['id'],before=p[-1],residual=residual,negativeCoordinateDerivative=None if residual is None else r['w']*residual/W,fit=h[i],addition=eta*h[i],after=p[-1]+eta*h[i]));p.append(p[-1]+eta*h[i])\n  for p,v in zip(queries,qh):p.append(p[-1]+eta*v)\n  fits.append(dict(stage=stage+1,tree=tree,rows=stageRows,queryFits=qh,norm=norm,predictedSSEDecrease=eta*(2-eta)*norm))\n return dict(task='regression',initial=initial,learningRate=eta,stages=stages,training=training,queries=queries,fits=fits,losses=losses,predictions=[dict(id=q['id'],prediction=p[-1],probabilities=[],vote=None,prob=None)for q,p in zip(a.get('queries',[]),queries)])\nclass Stream:\n def __init__(self,state):self.state=state\n def choose(self,n):\n  limit=(1<<32)-((1<<32)%n)\n  while True:\n   self.state=(1664525*self.state+1013904223)&0xffffffff\n   if self.state<limit:return self.state%n\ndef fixed_schedules(ids,p,seed):\n stream=Stream(seed);draws=[];schedules=[];paths=['']+[p for d in[1,2]for p in map(''.join,itertools.product('LR',repeat=d))]\n for member in range(4):\n  draws.append([ids[stream.choose(len(ids))]for _ in range(len(ids))]);schedule={}\n  for path in paths:\n   order=list(range(p))\n   for j in range(p-1,0,-1):k=stream.choose(j+1);order[j],order[k]=order[k],order[j]\n   schedule[path]=sorted(order[:max(1,int(math.sqrt(p)))])\n  schedules.append(schedule)\n return draws,schedules\ndef csvread(file):\n with Path(file).open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))\ndef read_sources(source):\n source=Path(source);raw=csvread(source/'actual320-country-four-indicators-original-2020-2024.csv');lookup={(r['countryISO3'],int(r['date']),r['indicatorID']):r for r in raw};country=[]\n for code in sorted({r['countryISO3']for r in raw}):\n  for year in range(2020,2025):\n   cols=['NY.GDP.PCAP.KD','NY.GDP.MKTP.KD.ZG','FP.CPI.TOTL.ZG','SP.DYN.LE00.IN'];v=[lookup[code,year,k]['originalValueToken']for k in cols];x=[None if not z else Q(z)for z in v[:3]];x[0]=None if x[0]is None else x[0]/10000;y=None if not v[3]else Q(v[3]);eligible=y is not None and None not in x;country.append(dict(id=code+':'+str(year),sourceRow=code+':'+str(year),originalID=code,year=year,x=x,y=y,weight='1',role='excluded'if not eligible else'outer-test'if year==2024 else'train'))\n person=[]\n for i,r in enumerate(csvread(source/'actual3613-NLS-original52-fields-and-selection.csv'),1):\n  v=lambda k:None if r[k]=='.'else Q(r[k]);x=[v('ed76'),v('age76')];y=None if v('wage76')is None else v('wage76')/100;eligible=y is not None and None not in x;person.append(dict(id='person:'+str(i),sourceRow=str(i),originalID=r['id'],x=x,y=y,weight='1',role='excluded'if not eligible else'outer-test'if i%5==0 else'train'))\n company=[]\n for i,r in enumerate(csvread(source/'actual3150-churn-original14-fields-and-selection.csv'),1):company.append(dict(id='customer:'+str(i),sourceRow=str(i),originalID='',x=[Q(r[k])for k in['Call  Failure','Subscription  Length','Charge  Amount']],y=r['Churn'],weight='1',role='outer-test'if i%5==0 else'train'))\n models={}\n for index,(kind,rr,task,leaf)in enumerate([('country',country,'regression',4),('person',person,'regression',50),('company',company,'classification',30)]):\n  ids=[r['id']for r in rr if r['role']=='train'];draws,schedules=fixed_schedules(ids,len(rr[0]['x']),20261102+7919*index);models[kind]=dict(records=rr,task=task,classes=['0','1']if task=='classification'else[],draws=draws,schedules=schedules,minLeaf=leaf)\n return models\n_OMITTED=object()\ndef realdata(models,kind,options=_OMITTED):\n options={}if options is _OMITTED else options\n if not isinstance(options,dict):raise ValueError('options object required, not explicit null')\n m=models[kind];train=[r for r in m['records']if r['role']=='train'];test=[r for r in m['records']if r['role']=='outer-test'];method=options.get('method','forest');depth=options.get('maxDepth',2);count=options.get('memberCount',3);a=dict(rows=train,queries=[dict(id=r['id'],x=r['x'])for r in test],task=m['task'],classes=m['classes'],maxDepth=depth,minLeaf=options.get('minLeaf',m['minLeaf']),minLeafWeight='0',minGain='0',missingRoute='best',learningRate=options.get('learningRate','1/2'),stages=options.get('stages',3))\n if method not in ['bagging','forest','boost']:raise ValueError('known source method')\n if not isinstance(depth,int)or isinstance(depth,bool)or not 0<=depth<=3:raise ValueError('source depth0..3')\n if method!='boost'and(not isinstance(count,int)or isinstance(count,bool)or not 1<=count<=4):raise ValueError('source member count1..4')\n if method=='boost':result=boost(a)\n else:\n  a.update(bootstrapDraws=m['draws'][:count],nodeFeatures=[{p:v for p,v in s.items()if len(p)<depth}for s in m['schedules'][:count]]);result=ensemble(a,method=='forest')\n outer=scored(result['predictions'],normalized(test,m['task']),m['task'],m['classes']);st=totals([r for r in normalized(train,m['task'])if r['w']and r['y']is not None],m['task'],m['classes']);constant=dict(prediction=st['pred'],probabilities=st['p'],vote=st['pred'],prob=st['pred']);baseline=scored([dict(id=r['id'],**constant)for r in test],normalized(test,m['task']),m['task'],m['classes']);return dict(kind=kind,method=method,settings=a,train=train,test=test,result=result,outer=outer,baseline=baseline)\ndef serial(x):\n if isinstance(x,Q):return str(x)\n if isinstance(x,dict):return{k:serial(v)for k,v in x.items()if k not in['inbag','tree']}\n if isinstance(x,(list,tuple)):return[serial(v)for v in x]\n return x\ndef writecsv(file,heads,rows):\n with Path(file).open('w',encoding='utf8',newline='')as f:\n  w=csv.writer(f);w.writerow(heads);w.writerows([[''if v is None else str(v)for v in r]for r in rows])\nAPI='aggregate'\nINPUT={'task': 'classification', 'classes': ['0', '1'], 'members': [{'id': '0', 'predictions': [{'id': 'q', 'label': '0', 'probabilities': [0.51, 0.49]}]}, {'id': '1', 'predictions': [{'id': 'q', 'label': '0', 'probabilities': [0.51, 0.49]}]}, {'id': '2', 'predictions': [{'id': 'q', 'label': '1', 'probabilities': [0, 1]}]}], 'aggregation': 'probabilities'}\n\ndef run_fixed(api,a,out,src):\n import matplotlib\n matplotlib.use('svg')\n import matplotlib.pyplot as plt\n from matplotlib.ticker import MaxNLocator\n plt.rcParams.update({'font.size':14,'svg.fonttype':'none','svg.hashsalt':'ml09-fixed-v1'})\n result=variance(a)if api=='variance'else aggregate(a)if api=='aggregate'else ensemble(a,api=='forest')if api in ['bagging','forest']else boost(a)if api=='boost'else realdata(read_sources(src),a['kind'])\n out=Path(out);out.mkdir(parents=True,exist_ok=True);summary={};points=[]\n def add(x,y,s):\n  if y is not None:points.append([x,y,s])\n if api=='variance':\n  summary={'B':result['B'],'varianceOfMean':result['varianceOfMean']};add(result['B'],result['varianceOfMean'],'Specified finite-B variance');xl='Number of members B';yl='Variance, stipulated units squared';title='Declared covariance model, not fitted trees'\n elif api=='aggregate':\n  p=result['predictions'][0];classification=a.get('task')=='classification';summary={'selectedPrediction':p['prediction']}\n  if classification:\n   summary.update(voteLabel=p['vote'],probabilityLabel=p['prob'],meanProbability1=p['probabilities'][1]);add(1,p['probabilities'][1],'Mean probability of class 1');add(2,p['votes'][1],'Label-vote share of class 1');xl='Aggregation (1=probability, 2=vote)';yl='Probability or vote share'\n  else:\n   for i,m in enumerate(a['members']):add(i+1,Q(m['predictions'][0]['value']),'Member prediction')\n   add(3,p['prediction'],'Weighted mean');xl='Member 1, member 2, aggregate 3';yl='Prediction, assumed units'\n  title='Votes and probabilities are distinct objects'\n elif api in ['bagging','forest']:\n  summary={'queryPrediction':result['predictions'][0]['prediction'],'OOB.scoreable':result['outOfBag']['eligibleRows'],'OOB.meanLoss':result['outOfBag']['meanLoss']}\n  for i,r in enumerate(a['rows']):add(i+1,Q(r['y']),'Observed training outcome')\n  for i,p in enumerate(result['outOfBag']['rows']):add(i+1,p['prediction'],'OOB prediction, when defined')\n  xl='Original training ID order';yl='Outcome, assumed units';title='Repeated draws and ID-level OOB membership'\n elif api=='boost':\n  summary={'initial':result['initial'],'finalMSE':result['losses'][-1]['MSE'],'stages':result['stages']}\n  for r in result['losses']:add(r['stage'],r['MSE'],'Training MSE')\n  xl='Boosting stage (0=initial)';yl='Weighted MSE, outcome units squared';title='Training descent does not certify held-out gain'\n else:\n  summary={'outer.scoreable':result['outer']['eligibleRows'],'outer.meanLoss':result['outer']['meanLoss'],'baseline.meanLoss':result['baseline']['meanLoss'],'OOB.scoreable':result['result']['outOfBag']['eligibleRows'],'OOB.meanLoss':result['result']['outOfBag']['meanLoss']}\n  for i,p in enumerate(result['outer']['rows']):\n   add(i+1,Q(p['actual']),'Observed outcome');add(i+1,p['probabilities'][1]if a['kind']=='company'else p['prediction'],'Forest probability of class 1'if a['kind']=='company'else'Forest prediction')\n  xl='Outer-test source order, not a time path';yl='Churn label / probability'if a['kind']=='company'else'Period life expectancy, years'if a['kind']=='country'else'Nominal 1976 USD per hour';title='Fixed forest; outer labels did not fit the trees'\n def display(v):return 'undefined'if v is None else format(float(v),'.9f')\n writecsv(out/'summary.csv',['metric','value'],[[k,display(v)]for k,v in summary.items()]);writecsv(out/'plot-points.csv',['x','y','series'],points);(out/'full.json').write_text(json.dumps(serial(result),indent=2)+'\\n',encoding='utf8')\n fig,ax=plt.subplots(figsize=(5.6,4.6));fig.subplots_adjust(left=.24,right=.96,bottom=.24,top=.76);colors=['#355c72','#a55336','#507956','#78568b']\n for i,s in enumerate(dict.fromkeys(p[2]for p in points)):\n  pp=[p for p in points if p[2]==s];ax.scatter([float(p[0])for p in pp],[float(p[1])for p in pp],s=12 if len(pp)>100 else 32,alpha=.5 if len(pp)>100 else 1,color=colors[i%4],label=s)\n ax.set_xlabel(xl,labelpad=10,fontsize=11);ax.set_ylabel(yl,labelpad=10,fontsize=11);ax.xaxis.set_major_locator(MaxNLocator(3));ax.yaxis.set_major_locator(MaxNLocator(4));ax.grid(alpha=.18);ax.legend(loc='lower left',bbox_to_anchor=(0,1.01),fontsize=9,frameon=False);fig.suptitle(title,fontsize=9,y=.99);fig.savefig(out/'plot.svg',metadata={'Date':None});plt.close(fig);print(', '.join(k+'='+display(v)for k,v in summary.items()))\nif __name__=='__main__':\n import sys\n try:run_fixed(API,INPUT,sys.argv[1]if len(sys.argv)>1 else'fixed-results',sys.argv[2]if len(sys.argv)>2 else'ml09-sources')\n except ValueError as error:print('Rejected declared input: '+str(error),file=sys.stderr);sys.exit(2)\n",
        "code": "\"\"\"ML09 exact Fraction reproduction from native source fields.\n\npython ml09-public-analysis.py --source-dir ml09-sources --output-dir results\n\nThis authored educational implementation uses direct-centered leaf losses and\nexhaustive midpoint partitions. It reads no JS engine, model contract, checker,\nstored target answers or derived-result CSV. Its five tree arithmetic helpers\nwere copied from the author's own separate Fraction reference, not an independent\npeer. Parser/work budgets and display rounding of the production JS are separate.\nNumerical predictions/proper scores do not certify causal effects, calibration,\nIID OOB validity, survey representativeness or production parameter optimality.\n\"\"\"\nfrom pathlib import Path\nfrom fractions import Fraction as Q\nimport csv,json,math,itertools,argparse\n\ndef normalized(rows,task='regression'):\n return [dict(id=r.get('id',i),x=[None if x is None else Q(x)for x in r.get('x',[])],y=None if r['y']is None else str(r['y'])if task=='classification'else Q(r['y']),w=Q(r.get('weight',1)))for i,r in enumerate(rows)]\n\ndef totals(rows,task,classes):\n W=sum((r['w']for r in rows),Q());mu=sum((r['w']*r['y']for r in rows),Q())/W if task=='regression'and W else None\n probs=[sum((r['w']for r in rows if r['y']==c),Q())/W for c in classes]if task=='classification'and W else[]\n risk=sum((r['w']*(r['y']-mu)**2 for r in rows),Q())if task=='regression'and W else W*sum((p*(1-p)for p in probs),Q())\n return dict(n=len(rows),w=W,mu=mu,p=probs,risk=risk,pred=mu if task=='regression'else classes[max(range(len(probs)),key=lambda i:probs[i])]if probs else None)\n\ndef fit(rows,a,task,classes,schedule=None):\n good=[r for r in rows if r['w']>0 and r['y']is not None];root=totals(good,task,classes)['w'];depth=a.get('maxDepth',2);minimum=a.get('minLeaf',1);minmass=Q(a.get('minLeafWeight',0));mingain=Q(a.get('minGain',0));route=a.get('missingRoute','best')\n def build(rr,d,path):\n  st=totals(rr,task,classes);n=dict(rows=rr,st=st,split=None,left=None,right=None,path=path)\n  if d==depth:return n\n  best=None\n  for j in range(len(rr[0]['x'])):\n   if schedule is not None and j not in schedule[path]:continue\n   values=sorted({r['x'][j]for r in rr if r['x'][j]is not None});missing=[r for r in rr if r['x'][j]is None];observed=[r for r in rr if r['x'][j]is not None]\n   candidates=[]\n   for lo,hi in zip(values,values[1:]):\n    q=(lo+hi)/2;left=[r for r in observed if r['x'][j]<=q];right=[r for r in observed if r['x'][j]>q];directions=[route]if route!='best'else['left','right']if missing else['left'if len(left)>=len(right)else'right']\n    for direction in directions:candidates.append(('threshold',q,direction,left+missing if direction=='left'else left,right+missing if direction=='right'else right))\n   if missing and observed:candidates.append(('missing-only',None,'left',missing,observed))\n   for kind,q,direction,left,right in candidates:\n    l=totals(left,task,classes);r=totals(right,task,classes)\n    if min(l['n'],r['n'])<minimum or min(l['w'],r['w'])<minmass or min(l['w'],r['w'])<=0:continue\n    gain=(st['risk']-l['risk']-r['risk'])/root\n    if best is None or gain>best['gain']:best=dict(feature=j,kind=kind,threshold=q,missingRoute=direction,left=left,right=right,gain=gain)\n  if best and best['gain']>0 and best['gain']>mingain:\n   j=best['feature'];go=lambda r:r['x'][j]is None if best['kind']=='missing-only'else best['missingRoute']=='left'if r['x'][j]is None else r['x'][j]<=best['threshold'];n['split']=best;n['left']=build([r for r in rr if go(r)],d+1,path+'L');n['right']=build([r for r in rr if not go(r)],d+1,path+'R')\n  return n\n return build(good,0,'')\n\ndef predict(tree,x):\n n=tree\n while n['split']:\n  s=n['split'];v=x[s['feature']];left=v is None if s['kind']=='missing-only'else s['missingRoute']=='left'if v is None else v<=s['threshold'];n=n['left'if left else'right']\n return dict(prediction=n['st']['pred'],probabilities=n['st']['p'])\n\ndef combine(preds,w,task,classes,mode='probabilities'):\n mass=sum(w,Q())\n if not preds or not mass:return dict(prediction=None,probabilities=[],vote=None,prob=None)\n if task=='regression':return dict(prediction=sum((p['prediction']*v for p,v in zip(preds,w)),Q())/mass,probabilities=[],vote=None,prob=None)\n votes=[sum((v for p,v in zip(preds,w)if p['prediction']==c),Q())/mass for c in classes];ps=[sum((p['probabilities'][j]*v for p,v in zip(preds,w)),Q())/mass for j in range(len(classes))];vote=classes[max(range(len(classes)),key=lambda j:votes[j])];prob=classes[max(range(len(classes)),key=lambda j:ps[j])];return dict(prediction=vote if mode=='votes'else prob,probabilities=ps,vote=vote,prob=prob,votes=votes)\ndef number(v):\n if v is None or isinstance(v,bool):raise ValueError('explicit null/bool is not a numeric parameter')\n return Q(str(v))\ndef variance(a):\n B=a['B'];v=number(a['marginalVariance']);rho=number(a.get('rho',0))\n if not isinstance(B,int)or isinstance(B,bool)or B<1 or v<0:raise ValueError('positive integer B/nonnegative variance')\n if B>1 and v and not -Q(1,B-1)<=rho<=1:raise ValueError('equicorrelation PSD bound')\n return dict(B=B,marginalVariance=v,correlationApplicable=B>1 and bool(v),varianceOfMean=v if B==1 else v*(1+(B-1)*rho)/B)\ndef aggregate(a):\n task=a.get('task','regression');classes=[str(c)for c in a.get('classes',[])];members=a['members'];w=[number(v)for v in a.get('memberWeights',[1]*len(members))]\n if not members or min(w)<0 or sum(w)<=0:raise ValueError('nonnegative member weights/positive total')\n order=[p.get('id',i)for i,p in enumerate(members[0]['predictions'])];keys=lambda x:(type(x).__name__,x);lookup=[{keys(p.get('id',i)):p for i,p in enumerate(m['predictions'])}for m in members]\n if any(set(m)!={keys(v)for v in order}for m in lookup):raise ValueError('same query ID set')\n out=[]\n for pid in order:\n  predictions=[dict(prediction=number(m[keys(pid)]['value']),probabilities=[])if task=='regression'else dict(prediction=str(m[keys(pid)]['label']),probabilities=[number(v)for v in m[keys(pid)]['probabilities']])for m in lookup]\n  if task=='classification'and any(min(p['probabilities'])<0 or sum(p['probabilities'])!=1 for p in predictions):raise ValueError('probability simplex')\n  out.append(dict(id=pid,**combine(predictions,w,task,classes,a.get('aggregation','probabilities'))))\n return dict(task=task,classes=classes,predictions=out)\ndef scored(preds,rows,task,classes):\n mass=loss=absolute=errors=voteerrors=Q();out=[]\n for p,r in zip(preds,rows):\n  ok=p['prediction']is not None and r['y']is not None and r['w']>0;v=None\n  if ok:\n   mass+=r['w']\n   if task=='regression':e=r['y']-p['prediction'];v=e*e;absolute+=r['w']*abs(e)\n   else:v=sum(((q-(1 if r['y']==c else 0))**2 for c,q in zip(classes,p['probabilities'])),Q());errors+=r['w']*(p['prediction']!=r['y']);voteerrors+=r['w']*(p['vote']!=r['y'])\n   loss+=r['w']*v\n  out.append(dict(p,actual=r['y'],weight=r['w'],scoreEligible=ok,loss=v))\n return dict(rows=out,eligibleRows=sum(r['scoreEligible']for r in out),weight=mass,totalLoss=loss,meanLoss=loss/mass if mass else None,MAE=absolute/mass if mass and task=='regression'else None,errorRate=errors/mass if mass and task=='classification'else None,labelVoteErrorRate=voteerrors/mass if mass and task=='classification'else None)\ndef ensemble(a,forest=False):\n task=a.get('task','regression');classes=[str(v)for v in(a.get('classes')or[])];rr=normalized(a['rows'],task);key=lambda x:(type(x).__name__,x);lookup={key(r['id']):r for r in rr};weights=[number(v)for v in a.get('memberWeights',[1]*len(a['bootstrapDraws']))]\n if not any(r['w']>0 and r['y']is not None for r in rr)or min(weights)<0 or sum(weights)<=0:raise ValueError('positive eligible training and member weight')\n members=[]\n for i,draw in enumerate(a['bootstrapDraws']):\n  data=[lookup[key(v)]for v in draw];schedule=a['nodeFeatures'][i]if forest else None;model=fit(data,a,task,classes,schedule);inbag={key(v)for v in draw};members.append(dict(tree=model,draw=draw,inbag=inbag,weight=weights[i]))\n predictions=[]\n for q in a.get('queries',[]):predictions.append(dict(id=q['id'],**combine([predict(m['tree'],[None if v is None else number(v)for v in q['x']])for m in members],weights,task,classes,a.get('aggregation','probabilities'))))\n oob=[]\n for r in rr:\n  applicable=[i for i,m in enumerate(members)if key(r['id'])not in m['inbag']];p=combine([predict(members[i]['tree'],r['x'])for i in applicable],[weights[i]for i in applicable],task,classes,a.get('aggregation','probabilities'));oob.append(dict(id=r['id'],applicable=applicable,positiveMembers=sum(weights[i]>0 for i in applicable),**p))\n return dict(task=task,classes=classes,members=members,predictions=predictions,outOfBag=scored(oob,rr,task,classes))\ndef boost(a):\n if a.get('task','regression')!='regression':raise ValueError('regression boosting only')\n rr=normalized(a['rows']);good=[r for r in rr if r['w']and r['y']is not None];W=sum((r['w']for r in good),Q())\n if not W:raise ValueError('positive eligible training')\n eta=number(a.get('learningRate','1/2'));stages=a.get('stages',3)\n if not 0<=eta<=1 or not isinstance(stages,int)or isinstance(stages,bool)or not 0<=stages<=8:raise ValueError('supported rate/stages')\n initial=number(a['initial'])if'initial'in a else sum((r['w']*r['y']for r in good),Q())/W;training=[[initial]for r in rr];queries=[[initial]for q in a.get('queries',[])];fits=[];losses=[]\n for stage in range(stages+1):\n  sse=sum((r['w']*(r['y']-p[-1])**2 for r,p in zip(rr,training)if r['w']and r['y']is not None),Q());losses.append(dict(stage=stage,rawWeightedSSE=sse,MSE=sse/W,meanHalfSquaredLoss=sse/(2*W)))\n  if stage==stages:break\n  residuals=[dict(r,y=None if r['y']is None else r['y']-p[-1])for r,p in zip(rr,training)];tree=fit(residuals,a,'regression',[]);h=[predict(tree,r['x'])['prediction']for r in rr];qh=[predict(tree,[None if v is None else number(v)for v in q['x']])['prediction']for q in a.get('queries',[])];norm=sum((r['w']*v*v for r,v in zip(rr,h)if r['y']is not None),Q());stageRows=[]\n  for i,(r,p)in enumerate(zip(rr,training)):\n   residual=None if r['y']is None else r['y']-p[-1];stageRows.append(dict(id=r['id'],before=p[-1],residual=residual,negativeCoordinateDerivative=None if residual is None else r['w']*residual/W,fit=h[i],addition=eta*h[i],after=p[-1]+eta*h[i]));p.append(p[-1]+eta*h[i])\n  for p,v in zip(queries,qh):p.append(p[-1]+eta*v)\n  fits.append(dict(stage=stage+1,tree=tree,rows=stageRows,queryFits=qh,norm=norm,predictedSSEDecrease=eta*(2-eta)*norm))\n return dict(task='regression',initial=initial,learningRate=eta,stages=stages,training=training,queries=queries,fits=fits,losses=losses,predictions=[dict(id=q['id'],prediction=p[-1],probabilities=[],vote=None,prob=None)for q,p in zip(a.get('queries',[]),queries)])\nclass Stream:\n def __init__(self,state):self.state=state\n def choose(self,n):\n  limit=(1<<32)-((1<<32)%n)\n  while True:\n   self.state=(1664525*self.state+1013904223)&0xffffffff\n   if self.state<limit:return self.state%n\ndef fixed_schedules(ids,p,seed):\n stream=Stream(seed);draws=[];schedules=[];paths=['']+[p for d in[1,2]for p in map(''.join,itertools.product('LR',repeat=d))]\n for member in range(4):\n  draws.append([ids[stream.choose(len(ids))]for _ in range(len(ids))]);schedule={}\n  for path in paths:\n   order=list(range(p))\n   for j in range(p-1,0,-1):k=stream.choose(j+1);order[j],order[k]=order[k],order[j]\n   schedule[path]=sorted(order[:max(1,int(math.sqrt(p)))])\n  schedules.append(schedule)\n return draws,schedules\ndef csvread(file):\n with Path(file).open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))\ndef read_sources(source):\n source=Path(source);raw=csvread(source/'actual320-country-four-indicators-original-2020-2024.csv');lookup={(r['countryISO3'],int(r['date']),r['indicatorID']):r for r in raw};country=[]\n for code in sorted({r['countryISO3']for r in raw}):\n  for year in range(2020,2025):\n   cols=['NY.GDP.PCAP.KD','NY.GDP.MKTP.KD.ZG','FP.CPI.TOTL.ZG','SP.DYN.LE00.IN'];v=[lookup[code,year,k]['originalValueToken']for k in cols];x=[None if not z else Q(z)for z in v[:3]];x[0]=None if x[0]is None else x[0]/10000;y=None if not v[3]else Q(v[3]);eligible=y is not None and None not in x;country.append(dict(id=code+':'+str(year),sourceRow=code+':'+str(year),originalID=code,year=year,x=x,y=y,weight='1',role='excluded'if not eligible else'outer-test'if year==2024 else'train'))\n person=[]\n for i,r in enumerate(csvread(source/'actual3613-NLS-original52-fields-and-selection.csv'),1):\n  v=lambda k:None if r[k]=='.'else Q(r[k]);x=[v('ed76'),v('age76')];y=None if v('wage76')is None else v('wage76')/100;eligible=y is not None and None not in x;person.append(dict(id='person:'+str(i),sourceRow=str(i),originalID=r['id'],x=x,y=y,weight='1',role='excluded'if not eligible else'outer-test'if i%5==0 else'train'))\n company=[]\n for i,r in enumerate(csvread(source/'actual3150-churn-original14-fields-and-selection.csv'),1):company.append(dict(id='customer:'+str(i),sourceRow=str(i),originalID='',x=[Q(r[k])for k in['Call  Failure','Subscription  Length','Charge  Amount']],y=r['Churn'],weight='1',role='outer-test'if i%5==0 else'train'))\n models={}\n for index,(kind,rr,task,leaf)in enumerate([('country',country,'regression',4),('person',person,'regression',50),('company',company,'classification',30)]):\n  ids=[r['id']for r in rr if r['role']=='train'];draws,schedules=fixed_schedules(ids,len(rr[0]['x']),20261102+7919*index);models[kind]=dict(records=rr,task=task,classes=['0','1']if task=='classification'else[],draws=draws,schedules=schedules,minLeaf=leaf)\n return models\n_OMITTED=object()\ndef realdata(models,kind,options=_OMITTED):\n options={}if options is _OMITTED else options\n if not isinstance(options,dict):raise ValueError('options object required, not explicit null')\n m=models[kind];train=[r for r in m['records']if r['role']=='train'];test=[r for r in m['records']if r['role']=='outer-test'];method=options.get('method','forest');depth=options.get('maxDepth',2);count=options.get('memberCount',3);a=dict(rows=train,queries=[dict(id=r['id'],x=r['x'])for r in test],task=m['task'],classes=m['classes'],maxDepth=depth,minLeaf=options.get('minLeaf',m['minLeaf']),minLeafWeight='0',minGain='0',missingRoute='best',learningRate=options.get('learningRate','1/2'),stages=options.get('stages',3))\n if method not in ['bagging','forest','boost']:raise ValueError('known source method')\n if not isinstance(depth,int)or isinstance(depth,bool)or not 0<=depth<=3:raise ValueError('source depth0..3')\n if method!='boost'and(not isinstance(count,int)or isinstance(count,bool)or not 1<=count<=4):raise ValueError('source member count1..4')\n if method=='boost':result=boost(a)\n else:\n  a.update(bootstrapDraws=m['draws'][:count],nodeFeatures=[{p:v for p,v in s.items()if len(p)<depth}for s in m['schedules'][:count]]);result=ensemble(a,method=='forest')\n outer=scored(result['predictions'],normalized(test,m['task']),m['task'],m['classes']);st=totals([r for r in normalized(train,m['task'])if r['w']and r['y']is not None],m['task'],m['classes']);constant=dict(prediction=st['pred'],probabilities=st['p'],vote=st['pred'],prob=st['pred']);baseline=scored([dict(id=r['id'],**constant)for r in test],normalized(test,m['task']),m['task'],m['classes']);return dict(kind=kind,method=method,settings=a,train=train,test=test,result=result,outer=outer,baseline=baseline)\ndef serial(x):\n if isinstance(x,Q):return str(x)\n if isinstance(x,dict):return{k:serial(v)for k,v in x.items()if k not in['inbag','tree']}\n if isinstance(x,(list,tuple)):return[serial(v)for v in x]\n return x\ndef writecsv(file,heads,rows):\n with Path(file).open('w',encoding='utf8',newline='')as f:\n  w=csv.writer(f);w.writerow(heads);w.writerows([[''if v is None else str(v)for v in r]for r in rows])\nAPI='aggregate'\nINPUT={'task': 'classification', 'classes': ['0', '1'], 'members': [{'id': '0', 'predictions': [{'id': 'q', 'label': '0', 'probabilities': [0.51, 0.49]}]}, {'id': '1', 'predictions': [{'id': 'q', 'label': '0', 'probabilities': [0.51, 0.49]}]}, {'id': '2', 'predictions': [{'id': 'q', 'label': '1', 'probabilities': [0, 1]}]}], 'aggregation': 'probabilities'}\n\ndef run_fixed(api,a,out,src):\n import matplotlib\n matplotlib.use('svg')\n import matplotlib.pyplot as plt\n from matplotlib.ticker import MaxNLocator\n plt.rcParams.update({'font.size':14,'svg.fonttype':'none','svg.hashsalt':'ml09-fixed-v1'})\n result=variance(a)if api=='variance'else aggregate(a)if api=='aggregate'else ensemble(a,api=='forest')if api in ['bagging','forest']else boost(a)if api=='boost'else realdata(read_sources(src),a['kind'])\n out=Path(out);out.mkdir(parents=True,exist_ok=True);summary={};points=[]\n def add(x,y,s):\n  if y is not None:points.append([x,y,s])\n if api=='variance':\n  summary={'B':result['B'],'varianceOfMean':result['varianceOfMean']};add(result['B'],result['varianceOfMean'],'Specified finite-B variance');xl='Number of members B';yl='Variance, stipulated units squared';title='Declared covariance model, not fitted trees'\n elif api=='aggregate':\n  p=result['predictions'][0];classification=a.get('task')=='classification';summary={'selectedPrediction':p['prediction']}\n  if classification:\n   summary.update(voteLabel=p['vote'],probabilityLabel=p['prob'],meanProbability1=p['probabilities'][1]);add(1,p['probabilities'][1],'Mean probability of class 1');add(2,p['votes'][1],'Label-vote share of class 1');xl='Aggregation (1=probability, 2=vote)';yl='Probability or vote share'\n  else:\n   for i,m in enumerate(a['members']):add(i+1,Q(m['predictions'][0]['value']),'Member prediction')\n   add(3,p['prediction'],'Weighted mean');xl='Member 1, member 2, aggregate 3';yl='Prediction, assumed units'\n  title='Votes and probabilities are distinct objects'\n elif api in ['bagging','forest']:\n  summary={'queryPrediction':result['predictions'][0]['prediction'],'OOB.scoreable':result['outOfBag']['eligibleRows'],'OOB.meanLoss':result['outOfBag']['meanLoss']}\n  for i,r in enumerate(a['rows']):add(i+1,Q(r['y']),'Observed training outcome')\n  for i,p in enumerate(result['outOfBag']['rows']):add(i+1,p['prediction'],'OOB prediction, when defined')\n  xl='Original training ID order';yl='Outcome, assumed units';title='Repeated draws and ID-level OOB membership'\n elif api=='boost':\n  summary={'initial':result['initial'],'finalMSE':result['losses'][-1]['MSE'],'stages':result['stages']}\n  for r in result['losses']:add(r['stage'],r['MSE'],'Training MSE')\n  xl='Boosting stage (0=initial)';yl='Weighted MSE, outcome units squared';title='Training descent does not certify held-out gain'\n else:\n  summary={'outer.scoreable':result['outer']['eligibleRows'],'outer.meanLoss':result['outer']['meanLoss'],'baseline.meanLoss':result['baseline']['meanLoss'],'OOB.scoreable':result['result']['outOfBag']['eligibleRows'],'OOB.meanLoss':result['result']['outOfBag']['meanLoss']}\n  for i,p in enumerate(result['outer']['rows']):\n   add(i+1,Q(p['actual']),'Observed outcome');add(i+1,p['probabilities'][1]if a['kind']=='company'else p['prediction'],'Forest probability of class 1'if a['kind']=='company'else'Forest prediction')\n  xl='Outer-test source order, not a time path';yl='Churn label / probability'if a['kind']=='company'else'Period life expectancy, years'if a['kind']=='country'else'Nominal 1976 USD per hour';title='Fixed forest; outer labels did not fit the trees'\n def display(v):return 'undefined'if v is None else format(float(v),'.9f')\n writecsv(out/'summary.csv',['metric','value'],[[k,display(v)]for k,v in summary.items()]);writecsv(out/'plot-points.csv',['x','y','series'],points);(out/'full.json').write_text(json.dumps(serial(result),indent=2)+'\\n',encoding='utf8')\n fig,ax=plt.subplots(figsize=(5.6,4.6));fig.subplots_adjust(left=.24,right=.96,bottom=.24,top=.76);colors=['#355c72','#a55336','#507956','#78568b']\n for i,s in enumerate(dict.fromkeys(p[2]for p in points)):\n  pp=[p for p in points if p[2]==s];ax.scatter([float(p[0])for p in pp],[float(p[1])for p in pp],s=12 if len(pp)>100 else 32,alpha=.5 if len(pp)>100 else 1,color=colors[i%4],label=s)\n ax.set_xlabel(xl,labelpad=10,fontsize=11);ax.set_ylabel(yl,labelpad=10,fontsize=11);ax.xaxis.set_major_locator(MaxNLocator(3));ax.yaxis.set_major_locator(MaxNLocator(4));ax.grid(alpha=.18);ax.legend(loc='lower left',bbox_to_anchor=(0,1.01),fontsize=9,frameon=False);fig.suptitle(title,fontsize=9,y=.99);fig.savefig(out/'plot.svg',metadata={'Date':None});plt.close(fig);print(', '.join(k+'='+display(v)for k,v in summary.items()))\nif __name__=='__main__':\n import sys\n try:run_fixed(API,INPUT,sys.argv[1]if len(sys.argv)>1 else'fixed-results',sys.argv[2]if len(sys.argv)>2 else'ml09-sources')\n except ValueError as error:print('Rejected declared input: '+str(error),file=sys.stderr);sys.exit(2)\n",
        "inputFiles": [],
        "input": {
          "task": "classification",
          "classes": [
            "0",
            "1"
          ],
          "members": [
            {
              "id": "0",
              "predictions": [
                {
                  "id": "q",
                  "label": "0",
                  "probabilities": [
                    0.51,
                    0.49
                  ]
                }
              ]
            },
            {
              "id": "1",
              "predictions": [
                {
                  "id": "q",
                  "label": "0",
                  "probabilities": [
                    0.51,
                    0.49
                  ]
                }
              ]
            },
            {
              "id": "2",
              "predictions": [
                {
                  "id": "q",
                  "label": "1",
                  "probabilities": [
                    0,
                    1
                  ]
                }
              ]
            }
          ],
          "aggregation": "probabilities"
        },
        "returnCode": 0,
        "expectedFailure": false,
        "stdout": "selectedPrediction=1.000000000, voteLabel=0.000000000, probabilityLabel=1.000000000, meanProbability1=0.660000000\n",
        "stderr": "",
        "summary": {
          "selectedPrediction": "1.000000000",
          "voteLabel": "0.000000000",
          "probabilityLabel": "1.000000000",
          "meanProbability1": "0.660000000"
        },
        "plotPoints": [
          {
            "x": "1",
            "y": "33/50",
            "series": "Mean probability of class 1"
          },
          {
            "x": "2",
            "y": "1/3",
            "series": "Label-vote share of class 1"
          }
        ],
        "plotFile": "ml09-fixed-results/aggregate-votes-versus-probabilities-python/plot.svg",
        "plotSHA256": "7eb87d50928808713bce0a5d5762fe84b1fd27790b401d92eb9bd5e17a0c9da7",
        "files": [
          {
            "file": "ml09-fixed-results/aggregate-votes-versus-probabilities-python/full.json",
            "sha256": "897d3dccf84ab317f34bb4e4adfbb05d14c3d60b39d29097437bc773060c2634"
          },
          {
            "file": "ml09-fixed-results/aggregate-votes-versus-probabilities-python/plot-points.csv",
            "sha256": "782dbc13a497d0c55595a6f1d87bd95b106ddf45a7c5db22f131149daaafd69c"
          },
          {
            "file": "ml09-fixed-results/aggregate-votes-versus-probabilities-python/plot.svg",
            "sha256": "7eb87d50928808713bce0a5d5762fe84b1fd27790b401d92eb9bd5e17a0c9da7"
          },
          {
            "file": "ml09-fixed-results/aggregate-votes-versus-probabilities-python/summary.csv",
            "sha256": "a12170d217fc69ae3c2827fb6138b9d400e3483abe78731041b60eac10b1a25e"
          }
        ],
        "scope": "Actually executed self-contained fixed example; current web controls execute separately. Python Fraction and finite-precision base R. Author gate, not independent peer."
      }
    },
    "r": {
      "weighted-mean": {
        "api": "aggregate",
        "variant": "weighted-mean",
        "language": "r",
        "codeFile": "ml09-code/aggregate-weighted-mean.R",
        "codeSHA256": "af19813262cd283d2927e57eb378d985501b434f19ff9d662ff3c702b2a0a2f4",
        "codeText": "# ML09 base-R reproduction from native original-field CSVs.\n# Rscript ml09-public-analysis.R ml09-sources results-r\n# Separately written vectorized direct-centered squared/Gini losses.\n# No Python/JS/model-contract/stored-answer/derived-result reader or package.\n# Numeric arithmetic is binary64:1e-12 relative tie tolerance stabilizes exact\n# source ties,but does not certify tiny margins/underflow like Fraction JS/Python.\n# Data-frame rows use x0,x1,...,y,weight; original IDs remain attached to draws.\noptions(stringsAsFactors=FALSE,digits=17)\nnum<-function(v){if(is.null(v)||length(v)!=1||is.na(v))stop('numeric parameter required, not explicit NULL');p<-strsplit(as.character(v),'/',fixed=TRUE)[[1]];z<-if(length(p)==2)as.numeric(p[1])/as.numeric(p[2])else as.numeric(v);if(!is.finite(z))stop('finite numeric parameter');z}\noption<-function(a,k,default){if(k%in%names(a))a[[k]]else default}\nnormrows<-function(d,task){if(!'weight'%in%names(d))d$weight<-1;if(!'id'%in%names(d))d$id<-as.character(seq_len(nrow(d))-1);d$weight<-as.numeric(d$weight);if(anyNA(d$weight)||any(d$weight<0))stop('nonnegative weights');if(task=='regression')d$y<-as.numeric(d$y)else d$y<-as.character(d$y);d}\nstat<-function(d,task,classes){W<-sum(d$weight);mu<-if(task=='regression'&&W)sum(d$weight*d$y)/W else NA_real_;p<-if(task=='classification'&&W)vapply(classes,function(c)sum(d$weight[d$y==c])/W,0)else numeric();risk<-if(task=='regression'&&W)sum(d$weight*(d$y-mu)^2)else W*sum(p*(1-p));list(n=nrow(d),w=W,mu=mu,p=unname(p),risk=risk,pred=if(task=='regression')mu else if(W)classes[which.max(p)]else NA_character_)}\nfit<-function(d,a,task,classes,schedule=NULL){d<-d[d$weight>0&!is.na(d$y),,drop=FALSE];if(!nrow(d))stop('positive observed training');W<-sum(d$weight);depth<-option(a,'maxDepth',2);minimum<-option(a,'minLeaf',1);minmass<-num(option(a,'minLeafWeight',0));mingain<-num(option(a,'minGain',0));route<-option(a,'missingRoute','best');features<-grep('^x[0-9]+$',names(d),value=TRUE)\n build<-function(rr,level,path){st<-stat(rr,task,classes);node<-list(rows=rr,st=st,split=NULL,left=NULL,right=NULL,path=path);if(level==depth)return(node);best<-NULL;allowed<-if(is.null(schedule))seq_along(features)-1L else schedule[[match(path,names(schedule))]]\n  for(j in seq_along(features)-1L){if(!j%in%allowed)next;v<-rr[[features[j+1L]]];values<-sort(unique(v[!is.na(v)]));candidates<-list()\n   if(length(values)>1)for(k in seq_len(length(values)-1L)){threshold<-(values[k]+values[k+1L])/2;missing<-is.na(v);left<-!missing&v<=threshold;right<-!missing&v>threshold;directions<-if(route!='best')route else if(any(missing))c('left','right')else if(sum(left)>=sum(right))'left'else'right';for(direction in directions)candidates[[length(candidates)+1L]]<-list(kind='threshold',threshold=threshold,missingRoute=direction,left=if(direction=='left')left|missing else left,right=if(direction=='right')right|missing else right)}\n   if(anyNA(v)&&any(!is.na(v)))candidates[[length(candidates)+1L]]<-list(kind='missing-only',threshold=NA_real_,missingRoute='left',left=is.na(v),right=!is.na(v))\n   for(candidate in candidates){l<-rr[candidate$left,,drop=FALSE];r<-rr[candidate$right,,drop=FALSE];ls<-stat(l,task,classes);rs<-stat(r,task,classes);if(min(ls$n,rs$n)<minimum||min(ls$w,rs$w)<minmass||min(ls$w,rs$w)<=0)next;gain<-(st$risk-ls$risk-rs$risk)/W;tol<-1e-12*max(1,abs(gain),if(is.null(best))0 else abs(best$gain));if(is.null(best)||gain>best$gain+tol)best<-c(candidate,list(feature=j,gain=gain,l=l,r=r))}\n  }\n  if(!is.null(best)&&best$gain>max(mingain,1e-12)){node$split<-best;node$left<-build(best$l,level+1L,paste0(path,'L'));node$right<-build(best$r,level+1L,paste0(path,'R'))};node\n };build(d,0L,'')\n}\npredict_one<-function(tree,row){n<-tree;while(!is.null(n$split)){s<-n$split;v<-as.numeric(row[[paste0('x',s$feature)]]);left<-if(s$kind=='missing-only')is.na(v)else if(is.na(v))s$missingRoute=='left'else v<=s$threshold;n<-if(left)n$left else n$right};list(prediction=n$st$pred,probabilities=n$st$p)}\ncombine<-function(pp,w,task,classes,mode='probabilities'){W<-sum(w);if(!length(pp)||!W)return(list(prediction=if(task=='regression')NA_real_ else NA_character_,probabilities=numeric(),vote=NA_character_,prob=NA_character_));if(task=='regression')return(list(prediction=sum(vapply(pp,function(p)p$prediction,0)*w)/W,probabilities=numeric(),vote=NA_character_,prob=NA_character_));votes<-vapply(classes,function(c)sum(w[vapply(pp,function(p)p$prediction==c,FALSE)])/W,0);probs<-vapply(seq_along(classes),function(j)sum(vapply(pp,function(p)p$probabilities[j],0)*w)/W,0);vote<-classes[which.max(votes)];prob<-classes[which.max(probs)];list(prediction=if(mode=='votes')vote else prob,probabilities=unname(probs),vote=vote,prob=prob,votes=unname(votes))}\nvariance<-function(a){B<-num(a$B);v<-num(a$marginalVariance);rho<-num(option(a,'rho',0));if(B<1||B!=floor(B)||v<0)stop('integer B/nonnegative variance');if(B>1&&v>0&&(rho< -1/(B-1)||rho>1))stop('PSD correlation');list(B=B,marginalVariance=v,correlationApplicable=B>1&&v>0,varianceOfMean=if(B==1)v else v*(1+(B-1)*rho)/B)}\naggregate<-function(a){task<-option(a,'task','regression');classes<-option(a,'classes',character());w<-vapply(option(a,'memberWeights',as.list(rep(1,length(a$members)))),num,0);if(any(w<0)||sum(w)<=0)stop('positive member mass');ids<-a$members[[1]]$predictions$id;pp<-lapply(ids,function(id){members<-lapply(a$members,function(m){r<-m$predictions[match(id,m$predictions$id),,drop=FALSE];if(task=='regression')list(prediction=num(r$value),probabilities=numeric())else list(prediction=as.character(r$label),probabilities=as.numeric(r[paste0('p',seq_along(classes)-1L)]))});c(list(id=id),combine(members,w,task,classes,option(a,'aggregation','probabilities')))});list(task=task,classes=classes,predictions=pp)}\nscored<-function(preds,d,task,classes){W<-loss<-absolute<-errors<-voteerrors<-0;count<-0L;out<-lapply(seq_len(nrow(d)),function(i){r<-d[i,,drop=FALSE];p<-preds[[i]];ok<-!is.na(p$prediction)&&!is.na(r$y)&&r$weight>0;value<-NA_real_;if(ok){count<<-count+1L;W<<-W+r$weight;if(task=='regression'){e<-r$y-p$prediction;value<-e*e;absolute<<-absolute+r$weight*abs(e)}else{value<-sum((p$probabilities-as.numeric(classes==r$y))^2);errors<<-errors+r$weight*(p$prediction!=r$y);voteerrors<<-voteerrors+r$weight*(p$vote!=r$y)};loss<<-loss+r$weight*value};c(p,list(actual=r$y,weight=r$weight,scoreEligible=ok,loss=value))});list(rows=out,eligibleRows=count,weight=W,totalLoss=loss,meanLoss=if(W)loss/W else NA_real_,MAE=if(W&&task=='regression')absolute/W else NA_real_,errorRate=if(W&&task=='classification')errors/W else NA_real_,labelVoteErrorRate=if(W&&task=='classification')voteerrors/W else NA_real_)}\nensemble<-function(a,forest=FALSE){task<-option(a,'task','regression');classes<-option(a,'classes',character());d<-normrows(a$rows,task);w<-vapply(option(a,'memberWeights',as.list(rep(1,length(a$bootstrapDraws)))),num,0);if(any(w<0)||sum(w)<=0)stop('positive member mass');members<-lapply(seq_along(a$bootstrapDraws),function(i){draw<-a$bootstrapDraws[[i]];indices<-match(draw,d$id);if(anyNA(indices))stop('unknown draw source');tree<-fit(d[indices,,drop=FALSE],a,task,classes,if(forest)a$nodeFeatures[[i]]else NULL);list(tree=tree,draw=draw,inbag=unique(draw),weight=w[i])});queries<-a$queries;preds<-lapply(seq_len(nrow(queries)),function(i)c(list(id=queries$id[i]),combine(lapply(members,function(m)predict_one(m$tree,queries[i,,drop=FALSE])),w,task,classes,option(a,'aggregation','probabilities'))));oob<-lapply(seq_len(nrow(d)),function(i){app<-which(!vapply(members,function(m)d$id[i]%in%m$inbag,FALSE));pp<-combine(lapply(app,function(j)predict_one(members[[j]]$tree,d[i,,drop=FALSE])),w[app],task,classes,option(a,'aggregation','probabilities'));c(list(id=d$id[i],applicable=app-1L,positiveMembers=sum(w[app]>0)),pp)});list(task=task,classes=classes,members=members,predictions=preds,outOfBag=scored(oob,d,task,classes))}\nboost<-function(a){if(option(a,'task','regression')!='regression')stop('regression boosting only');d<-normrows(a$rows,'regression');eligible<-d$weight>0&!is.na(d$y);W<-sum(d$weight[eligible]);if(!W)stop('positive eligible training');eta<-num(option(a,'learningRate','1/2'));stages<-option(a,'stages',3);if(is.null(stages)||stages!=floor(stages)||stages<0||stages>8||eta<0||eta>1)stop('supported rate/stages');initial<-if('initial'%in%names(a))num(a$initial)else sum(d$weight[eligible]*d$y[eligible])/W;train<-matrix(initial,nrow(d),stages+1L);query<-matrix(initial,nrow(a$queries),stages+1L);losses<-fits<-list();for(stage in 0:stages){sse<-sum(d$weight[eligible]*(d$y[eligible]-train[eligible,stage+1L])^2);losses[[stage+1L]]<-list(stage=stage,rawWeightedSSE=sse,MSE=sse/W,meanHalfSquaredLoss=sse/(2*W));if(stage==stages)break;residual<-d;residual$y<-d$y-train[,stage+1L];tree<-fit(residual,a,'regression',character());h<-vapply(seq_len(nrow(d)),function(i)predict_one(tree,d[i,,drop=FALSE])$prediction,0);qh<-vapply(seq_len(nrow(a$queries)),function(i)predict_one(tree,a$queries[i,,drop=FALSE])$prediction,0);stageRows<-lapply(seq_len(nrow(d)),function(i)list(id=d$id[i],before=train[i,stage+1L],residual=residual$y[i],negativeCoordinateDerivative=d$weight[i]*residual$y[i]/W,fit=h[i],addition=eta*h[i],after=train[i,stage+1L]+eta*h[i]));train[,stage+2L]<-train[,stage+1L]+eta*h;query[,stage+2L]<-query[,stage+1L]+eta*qh;norm<-sum(d$weight[eligible]*h[eligible]^2);fits[[stage+1L]]<-list(stage=stage+1L,tree=tree,rows=stageRows,queryFits=qh,norm=norm,predictedSSEDecrease=eta*(2-eta)*norm)};list(task='regression',initial=initial,learningRate=eta,stages=stages,training=train,queries=query,fits=fits,losses=losses,predictions=lapply(seq_len(nrow(a$queries)),function(i)list(id=a$queries$id[i],prediction=query[i,stages+1L],probabilities=numeric(),vote=NA_character_,prob=NA_character_)))}\nfixed_schedules<-function(ids,p,seed){state<-seed;choose<-function(n){limit<-floor(4294967296/n)*n;repeat{state<<-(1664525*state+1013904223)%%4294967296;if(state<limit)return(as.integer(state%%n))}};draws<-schedules<-list();for(member in 1:4){draws[[member]]<-vapply(seq_along(ids),function(i)ids[choose(length(ids))+1L],'');schedule<-setNames(vector('list',7),c('','L','R','LL','LR','RL','RR'));for(path in names(schedule)){order<-seq_len(p)-1L;if(p>1)for(j in seq(p-1L,1L)){k<-choose(j+1L);temp<-order[j+1L];order[j+1L]<-order[k+1L];order[k+1L]<-temp};schedule[[match(path,names(schedule))]]<-sort(order[seq_len(max(1L,floor(sqrt(p))))])};schedules[[member]]<-schedule};list(draws=draws,schedules=schedules)}\nread_sources<-function(src){read<-function(name)read.csv(file.path(src,name),check.names=FALSE,colClasses='character',na.strings=character(),fileEncoding='UTF-8-BOM');raw<-read('actual320-country-four-indicators-original-2020-2024.csv');country<-do.call(rbind,lapply(sort(unique(raw$countryISO3)),function(code)do.call(rbind,lapply(2020:2024,function(year){keys<-c('NY.GDP.PCAP.KD','NY.GDP.MKTP.KD.ZG','FP.CPI.TOTL.ZG','SP.DYN.LE00.IN');v<-vapply(keys,function(k)as.numeric(raw$originalValueToken[raw$countryISO3==code&raw$date==as.character(year)&raw$indicatorID==k]),0);data.frame(id=paste0(code,':',year),sourceRow=paste0(code,':',year),originalID=code,year=year,x0=v[1]/10000,x1=v[2],x2=v[3],y=v[4],weight=1,role=if(anyNA(v))'excluded'else if(year==2024)'outer-test'else'train')}))));raw<-read('actual3613-NLS-original52-fields-and-selection.csv');i<-seq_len(nrow(raw));x0<-suppressWarnings(as.numeric(raw$ed76));x1<-suppressWarnings(as.numeric(raw$age76));y<-suppressWarnings(as.numeric(raw$wage76))/100;person<-data.frame(id=paste0('person:',i),sourceRow=as.character(i),originalID=raw$id,x0=x0,x1=x1,y=y,weight=1,role=ifelse(is.na(x0)|is.na(x1)|is.na(y),'excluded',ifelse(i%%5==0,'outer-test','train')));raw<-read('actual3150-churn-original14-fields-and-selection.csv');i<-seq_len(nrow(raw));company<-data.frame(id=paste0('customer:',i),sourceRow=as.character(i),originalID='',x0=as.numeric(raw[['Call  Failure']]),x1=as.numeric(raw[['Subscription  Length']]),x2=as.numeric(raw[['Charge  Amount']]),y=raw$Churn,weight=1,role=ifelse(i%%5==0,'outer-test','train'));models<-list();for(index in 1:3){kind<-c('country','person','company')[index];d<-list(country,person,company)[[index]];task<-if(kind=='company')'classification'else'regression';s<-fixed_schedules(d$id[d$role=='train'],if(kind=='person')2L else 3L,20261102+7919*(index-1L));models[[kind]]<-list(records=d,task=task,classes=if(task=='classification')c('0','1')else character(),draws=s$draws,schedules=s$schedules,minLeaf=c(4L,50L,30L)[index])};models}\nrealdata<-function(models,kind,options=list()){if(is.null(options)||!is.list(options))stop('options object');m<-models[[kind]];d<-m$records;train<-d[d$role=='train',,drop=FALSE];test<-d[d$role=='outer-test',,drop=FALSE];method<-option(options,'method','forest');depth<-option(options,'maxDepth',2);count<-option(options,'memberCount',3);if(!method%in%c('bagging','forest','boost'))stop('known method');a<-list(rows=train,queries=test,task=m$task,classes=m$classes,maxDepth=depth,minLeaf=option(options,'minLeaf',m$minLeaf),minLeafWeight=0,minGain=0,missingRoute='best',learningRate=option(options,'learningRate','1/2'),stages=option(options,'stages',3));if(method=='boost')result<-boost(a)else{a$bootstrapDraws<-m$draws[seq_len(count)];a$nodeFeatures<-lapply(m$schedules[seq_len(count)],function(s)s[nchar(names(s))<depth]);result<-ensemble(a,method=='forest')};outer<-scored(result$predictions,normrows(test,m$task),m$task,m$classes);st<-stat(normrows(train,m$task),m$task,m$classes);constant<-list(prediction=st$pred,probabilities=st$p,vote=st$pred,prob=st$pred);baseline<-scored(lapply(test$id,function(id)c(list(id=id),constant)),normrows(test,m$task),m$task,m$classes);list(kind=kind,method=method,settings=a,train=train,test=test,result=result,outer=outer,baseline=baseline)}\nAPI<-\"aggregate\"\nINPUT<-list(members=list(list(id=\"m1\",predictions=data.frame(id=c(\"q\"),value=c(1),stringsAsFactors=FALSE)),list(id=\"m2\",predictions=data.frame(id=c(\"q\"),value=c(3),stringsAsFactors=FALSE))),memberWeights=list(1,3))\n\nrun_fixed<-function(api,a,out,src){\n r<-if(api=='variance')variance(a)else if(api=='aggregate')aggregate(a)else if(api%in%c('bagging','forest'))ensemble(a,api=='forest')else if(api=='boost')boost(a)else realdata(read_sources(src),a$kind)\n dir.create(out,recursive=TRUE,showWarnings=FALSE);summary<-list();points<-list();add<-function(x,y,s){if(!is.null(y)&&!is.na(y))points[[length(points)+1L]]<<-data.frame(x=x,y=as.numeric(y),series=s)}\n if(api=='variance'){summary<-r[c('B','varianceOfMean')];add(r$B,r$varianceOfMean,'Specified finite-B variance');xl<-'Number of members B';yl<-'Variance, stipulated units squared';title<-'Declared covariance model, not fitted trees'\n }else if(api=='aggregate'){p<-r$predictions[[1]];summary<-list(selectedPrediction=p$prediction);classification<-identical(a$task,'classification');if(classification){summary<-c(summary,list(voteLabel=p$vote,probabilityLabel=p$prob,meanProbability1=p$probabilities[2]));add(1,p$probabilities[2],'Mean probability of class 1');add(2,p$votes[2],'Label-vote share of class 1');xl<-'Aggregation (1=probability, 2=vote)';yl<-'Probability or vote share'}else{for(i in seq_along(a$members))add(i,num(a$members[[i]]$predictions$value[1]),'Member prediction');add(3,p$prediction,'Weighted mean');xl<-'Member 1, member 2, aggregate 3';yl<-'Prediction, assumed units'};title<-'Votes and probabilities are distinct objects'\n }else if(api%in%c('bagging','forest')){summary<-list(queryPrediction=r$predictions[[1]]$prediction,OOB.scoreable=r$outOfBag$eligibleRows,OOB.meanLoss=r$outOfBag$meanLoss);for(i in seq_len(nrow(a$rows)))add(i,a$rows$y[i],'Observed training outcome');for(i in seq_along(r$outOfBag$rows))add(i,r$outOfBag$rows[[i]]$prediction,'OOB prediction, when defined');xl<-'Original training ID order';yl<-'Outcome, assumed units';title<-'Repeated draws and ID-level OOB membership'\n }else if(api=='boost'){summary<-list(initial=r$initial,finalMSE=r$losses[[length(r$losses)]]$MSE,stages=r$stages);for(v in r$losses)add(v$stage,v$MSE,'Training MSE');xl<-'Boosting stage (0=initial)';yl<-'Weighted MSE, outcome units squared';title<-'Training descent does not certify held-out gain'\n }else{summary<-list(outer.scoreable=r$outer$eligibleRows,outer.meanLoss=r$outer$meanLoss,baseline.meanLoss=r$baseline$meanLoss,OOB.scoreable=r$result$outOfBag$eligibleRows,OOB.meanLoss=r$result$outOfBag$meanLoss);for(i in seq_along(r$outer$rows)){p<-r$outer$rows[[i]];add(i,as.numeric(p$actual),'Observed outcome');add(i,if(a$kind=='company')p$probabilities[2]else p$prediction,if(a$kind=='company')'Forest probability of class 1'else'Forest prediction')};xl<-'Outer-test source order, not a time path';yl<-if(a$kind=='company')'Churn label / probability'else if(a$kind=='country')'Period life expectancy, years'else'Nominal 1976 USD per hour';title<-'Fixed forest; outer labels did not fit the trees'}\n display<-function(v)if(is.null(v)||is.na(v))'undefined'else sprintf('%.9f',as.numeric(v));write.csv(data.frame(metric=names(summary),value=vapply(summary,display,'')),file.path(out,'summary.csv'),row.names=FALSE);pp<-do.call(rbind,points);write.csv(pp,file.path(out,'plot-points.csv'),row.names=FALSE);dput(r,file.path(out,'full-result.Rtext'));svg(file.path(out,'plot.svg'),width=5.6,height=4.6,pointsize=14);par(mar=c(5.8,5.8,5.3,1.2),mgp=c(3.7,1,0));xr<-range(pp$x);yr<-range(pp$y);if(diff(xr)==0)xr<-xr+c(-.5,.5);if(diff(yr)==0)yr<-yr+c(-.5,.5);plot(xr,yr,type='n',xlab=xl,ylab=yl,cex.lab=.78,axes=FALSE);axis(1,at=pretty(xr,3));axis(2,at=pretty(yr,4),las=1,cex.axis=.82);box();grid(col='#dddddd');cols<-c('#355c72','#a55336','#507956','#78568b');ss<-unique(pp$series);for(i in seq_along(ss)){v<-pp[pp$series==ss[i],];points(v$x,v$y,pch=16,cex=if(nrow(v)>100).35 else .85,col=adjustcolor(cols[i],if(nrow(v)>100).5 else 1))};legend('topleft',legend=ss,col=cols[seq_along(ss)],lty=0,pch=16,cex=.65,bty='n',inset=c(0,-.32),xpd=NA);mtext(title,side=3,line=3.9,cex=.6);dev.off();cat(paste(names(summary),vapply(summary,display,''),sep='=',collapse=', '),'\\n')\n}\nargs<-commandArgs(trailingOnly=TRUE)\ntryCatch(run_fixed(API,INPUT,if(length(args))args[1]else'fixed-results',if(length(args)>1)args[2]else'ml09-sources'),error=function(e){cat('Rejected declared input: ',conditionMessage(e),'\\n',file=stderr());quit(status=2)})\n",
        "code": "# ML09 base-R reproduction from native original-field CSVs.\n# Rscript ml09-public-analysis.R ml09-sources results-r\n# Separately written vectorized direct-centered squared/Gini losses.\n# No Python/JS/model-contract/stored-answer/derived-result reader or package.\n# Numeric arithmetic is binary64:1e-12 relative tie tolerance stabilizes exact\n# source ties,but does not certify tiny margins/underflow like Fraction JS/Python.\n# Data-frame rows use x0,x1,...,y,weight; original IDs remain attached to draws.\noptions(stringsAsFactors=FALSE,digits=17)\nnum<-function(v){if(is.null(v)||length(v)!=1||is.na(v))stop('numeric parameter required, not explicit NULL');p<-strsplit(as.character(v),'/',fixed=TRUE)[[1]];z<-if(length(p)==2)as.numeric(p[1])/as.numeric(p[2])else as.numeric(v);if(!is.finite(z))stop('finite numeric parameter');z}\noption<-function(a,k,default){if(k%in%names(a))a[[k]]else default}\nnormrows<-function(d,task){if(!'weight'%in%names(d))d$weight<-1;if(!'id'%in%names(d))d$id<-as.character(seq_len(nrow(d))-1);d$weight<-as.numeric(d$weight);if(anyNA(d$weight)||any(d$weight<0))stop('nonnegative weights');if(task=='regression')d$y<-as.numeric(d$y)else d$y<-as.character(d$y);d}\nstat<-function(d,task,classes){W<-sum(d$weight);mu<-if(task=='regression'&&W)sum(d$weight*d$y)/W else NA_real_;p<-if(task=='classification'&&W)vapply(classes,function(c)sum(d$weight[d$y==c])/W,0)else numeric();risk<-if(task=='regression'&&W)sum(d$weight*(d$y-mu)^2)else W*sum(p*(1-p));list(n=nrow(d),w=W,mu=mu,p=unname(p),risk=risk,pred=if(task=='regression')mu else if(W)classes[which.max(p)]else NA_character_)}\nfit<-function(d,a,task,classes,schedule=NULL){d<-d[d$weight>0&!is.na(d$y),,drop=FALSE];if(!nrow(d))stop('positive observed training');W<-sum(d$weight);depth<-option(a,'maxDepth',2);minimum<-option(a,'minLeaf',1);minmass<-num(option(a,'minLeafWeight',0));mingain<-num(option(a,'minGain',0));route<-option(a,'missingRoute','best');features<-grep('^x[0-9]+$',names(d),value=TRUE)\n build<-function(rr,level,path){st<-stat(rr,task,classes);node<-list(rows=rr,st=st,split=NULL,left=NULL,right=NULL,path=path);if(level==depth)return(node);best<-NULL;allowed<-if(is.null(schedule))seq_along(features)-1L else schedule[[match(path,names(schedule))]]\n  for(j in seq_along(features)-1L){if(!j%in%allowed)next;v<-rr[[features[j+1L]]];values<-sort(unique(v[!is.na(v)]));candidates<-list()\n   if(length(values)>1)for(k in seq_len(length(values)-1L)){threshold<-(values[k]+values[k+1L])/2;missing<-is.na(v);left<-!missing&v<=threshold;right<-!missing&v>threshold;directions<-if(route!='best')route else if(any(missing))c('left','right')else if(sum(left)>=sum(right))'left'else'right';for(direction in directions)candidates[[length(candidates)+1L]]<-list(kind='threshold',threshold=threshold,missingRoute=direction,left=if(direction=='left')left|missing else left,right=if(direction=='right')right|missing else right)}\n   if(anyNA(v)&&any(!is.na(v)))candidates[[length(candidates)+1L]]<-list(kind='missing-only',threshold=NA_real_,missingRoute='left',left=is.na(v),right=!is.na(v))\n   for(candidate in candidates){l<-rr[candidate$left,,drop=FALSE];r<-rr[candidate$right,,drop=FALSE];ls<-stat(l,task,classes);rs<-stat(r,task,classes);if(min(ls$n,rs$n)<minimum||min(ls$w,rs$w)<minmass||min(ls$w,rs$w)<=0)next;gain<-(st$risk-ls$risk-rs$risk)/W;tol<-1e-12*max(1,abs(gain),if(is.null(best))0 else abs(best$gain));if(is.null(best)||gain>best$gain+tol)best<-c(candidate,list(feature=j,gain=gain,l=l,r=r))}\n  }\n  if(!is.null(best)&&best$gain>max(mingain,1e-12)){node$split<-best;node$left<-build(best$l,level+1L,paste0(path,'L'));node$right<-build(best$r,level+1L,paste0(path,'R'))};node\n };build(d,0L,'')\n}\npredict_one<-function(tree,row){n<-tree;while(!is.null(n$split)){s<-n$split;v<-as.numeric(row[[paste0('x',s$feature)]]);left<-if(s$kind=='missing-only')is.na(v)else if(is.na(v))s$missingRoute=='left'else v<=s$threshold;n<-if(left)n$left else n$right};list(prediction=n$st$pred,probabilities=n$st$p)}\ncombine<-function(pp,w,task,classes,mode='probabilities'){W<-sum(w);if(!length(pp)||!W)return(list(prediction=if(task=='regression')NA_real_ else NA_character_,probabilities=numeric(),vote=NA_character_,prob=NA_character_));if(task=='regression')return(list(prediction=sum(vapply(pp,function(p)p$prediction,0)*w)/W,probabilities=numeric(),vote=NA_character_,prob=NA_character_));votes<-vapply(classes,function(c)sum(w[vapply(pp,function(p)p$prediction==c,FALSE)])/W,0);probs<-vapply(seq_along(classes),function(j)sum(vapply(pp,function(p)p$probabilities[j],0)*w)/W,0);vote<-classes[which.max(votes)];prob<-classes[which.max(probs)];list(prediction=if(mode=='votes')vote else prob,probabilities=unname(probs),vote=vote,prob=prob,votes=unname(votes))}\nvariance<-function(a){B<-num(a$B);v<-num(a$marginalVariance);rho<-num(option(a,'rho',0));if(B<1||B!=floor(B)||v<0)stop('integer B/nonnegative variance');if(B>1&&v>0&&(rho< -1/(B-1)||rho>1))stop('PSD correlation');list(B=B,marginalVariance=v,correlationApplicable=B>1&&v>0,varianceOfMean=if(B==1)v else v*(1+(B-1)*rho)/B)}\naggregate<-function(a){task<-option(a,'task','regression');classes<-option(a,'classes',character());w<-vapply(option(a,'memberWeights',as.list(rep(1,length(a$members)))),num,0);if(any(w<0)||sum(w)<=0)stop('positive member mass');ids<-a$members[[1]]$predictions$id;pp<-lapply(ids,function(id){members<-lapply(a$members,function(m){r<-m$predictions[match(id,m$predictions$id),,drop=FALSE];if(task=='regression')list(prediction=num(r$value),probabilities=numeric())else list(prediction=as.character(r$label),probabilities=as.numeric(r[paste0('p',seq_along(classes)-1L)]))});c(list(id=id),combine(members,w,task,classes,option(a,'aggregation','probabilities')))});list(task=task,classes=classes,predictions=pp)}\nscored<-function(preds,d,task,classes){W<-loss<-absolute<-errors<-voteerrors<-0;count<-0L;out<-lapply(seq_len(nrow(d)),function(i){r<-d[i,,drop=FALSE];p<-preds[[i]];ok<-!is.na(p$prediction)&&!is.na(r$y)&&r$weight>0;value<-NA_real_;if(ok){count<<-count+1L;W<<-W+r$weight;if(task=='regression'){e<-r$y-p$prediction;value<-e*e;absolute<<-absolute+r$weight*abs(e)}else{value<-sum((p$probabilities-as.numeric(classes==r$y))^2);errors<<-errors+r$weight*(p$prediction!=r$y);voteerrors<<-voteerrors+r$weight*(p$vote!=r$y)};loss<<-loss+r$weight*value};c(p,list(actual=r$y,weight=r$weight,scoreEligible=ok,loss=value))});list(rows=out,eligibleRows=count,weight=W,totalLoss=loss,meanLoss=if(W)loss/W else NA_real_,MAE=if(W&&task=='regression')absolute/W else NA_real_,errorRate=if(W&&task=='classification')errors/W else NA_real_,labelVoteErrorRate=if(W&&task=='classification')voteerrors/W else NA_real_)}\nensemble<-function(a,forest=FALSE){task<-option(a,'task','regression');classes<-option(a,'classes',character());d<-normrows(a$rows,task);w<-vapply(option(a,'memberWeights',as.list(rep(1,length(a$bootstrapDraws)))),num,0);if(any(w<0)||sum(w)<=0)stop('positive member mass');members<-lapply(seq_along(a$bootstrapDraws),function(i){draw<-a$bootstrapDraws[[i]];indices<-match(draw,d$id);if(anyNA(indices))stop('unknown draw source');tree<-fit(d[indices,,drop=FALSE],a,task,classes,if(forest)a$nodeFeatures[[i]]else NULL);list(tree=tree,draw=draw,inbag=unique(draw),weight=w[i])});queries<-a$queries;preds<-lapply(seq_len(nrow(queries)),function(i)c(list(id=queries$id[i]),combine(lapply(members,function(m)predict_one(m$tree,queries[i,,drop=FALSE])),w,task,classes,option(a,'aggregation','probabilities'))));oob<-lapply(seq_len(nrow(d)),function(i){app<-which(!vapply(members,function(m)d$id[i]%in%m$inbag,FALSE));pp<-combine(lapply(app,function(j)predict_one(members[[j]]$tree,d[i,,drop=FALSE])),w[app],task,classes,option(a,'aggregation','probabilities'));c(list(id=d$id[i],applicable=app-1L,positiveMembers=sum(w[app]>0)),pp)});list(task=task,classes=classes,members=members,predictions=preds,outOfBag=scored(oob,d,task,classes))}\nboost<-function(a){if(option(a,'task','regression')!='regression')stop('regression boosting only');d<-normrows(a$rows,'regression');eligible<-d$weight>0&!is.na(d$y);W<-sum(d$weight[eligible]);if(!W)stop('positive eligible training');eta<-num(option(a,'learningRate','1/2'));stages<-option(a,'stages',3);if(is.null(stages)||stages!=floor(stages)||stages<0||stages>8||eta<0||eta>1)stop('supported rate/stages');initial<-if('initial'%in%names(a))num(a$initial)else sum(d$weight[eligible]*d$y[eligible])/W;train<-matrix(initial,nrow(d),stages+1L);query<-matrix(initial,nrow(a$queries),stages+1L);losses<-fits<-list();for(stage in 0:stages){sse<-sum(d$weight[eligible]*(d$y[eligible]-train[eligible,stage+1L])^2);losses[[stage+1L]]<-list(stage=stage,rawWeightedSSE=sse,MSE=sse/W,meanHalfSquaredLoss=sse/(2*W));if(stage==stages)break;residual<-d;residual$y<-d$y-train[,stage+1L];tree<-fit(residual,a,'regression',character());h<-vapply(seq_len(nrow(d)),function(i)predict_one(tree,d[i,,drop=FALSE])$prediction,0);qh<-vapply(seq_len(nrow(a$queries)),function(i)predict_one(tree,a$queries[i,,drop=FALSE])$prediction,0);stageRows<-lapply(seq_len(nrow(d)),function(i)list(id=d$id[i],before=train[i,stage+1L],residual=residual$y[i],negativeCoordinateDerivative=d$weight[i]*residual$y[i]/W,fit=h[i],addition=eta*h[i],after=train[i,stage+1L]+eta*h[i]));train[,stage+2L]<-train[,stage+1L]+eta*h;query[,stage+2L]<-query[,stage+1L]+eta*qh;norm<-sum(d$weight[eligible]*h[eligible]^2);fits[[stage+1L]]<-list(stage=stage+1L,tree=tree,rows=stageRows,queryFits=qh,norm=norm,predictedSSEDecrease=eta*(2-eta)*norm)};list(task='regression',initial=initial,learningRate=eta,stages=stages,training=train,queries=query,fits=fits,losses=losses,predictions=lapply(seq_len(nrow(a$queries)),function(i)list(id=a$queries$id[i],prediction=query[i,stages+1L],probabilities=numeric(),vote=NA_character_,prob=NA_character_)))}\nfixed_schedules<-function(ids,p,seed){state<-seed;choose<-function(n){limit<-floor(4294967296/n)*n;repeat{state<<-(1664525*state+1013904223)%%4294967296;if(state<limit)return(as.integer(state%%n))}};draws<-schedules<-list();for(member in 1:4){draws[[member]]<-vapply(seq_along(ids),function(i)ids[choose(length(ids))+1L],'');schedule<-setNames(vector('list',7),c('','L','R','LL','LR','RL','RR'));for(path in names(schedule)){order<-seq_len(p)-1L;if(p>1)for(j in seq(p-1L,1L)){k<-choose(j+1L);temp<-order[j+1L];order[j+1L]<-order[k+1L];order[k+1L]<-temp};schedule[[match(path,names(schedule))]]<-sort(order[seq_len(max(1L,floor(sqrt(p))))])};schedules[[member]]<-schedule};list(draws=draws,schedules=schedules)}\nread_sources<-function(src){read<-function(name)read.csv(file.path(src,name),check.names=FALSE,colClasses='character',na.strings=character(),fileEncoding='UTF-8-BOM');raw<-read('actual320-country-four-indicators-original-2020-2024.csv');country<-do.call(rbind,lapply(sort(unique(raw$countryISO3)),function(code)do.call(rbind,lapply(2020:2024,function(year){keys<-c('NY.GDP.PCAP.KD','NY.GDP.MKTP.KD.ZG','FP.CPI.TOTL.ZG','SP.DYN.LE00.IN');v<-vapply(keys,function(k)as.numeric(raw$originalValueToken[raw$countryISO3==code&raw$date==as.character(year)&raw$indicatorID==k]),0);data.frame(id=paste0(code,':',year),sourceRow=paste0(code,':',year),originalID=code,year=year,x0=v[1]/10000,x1=v[2],x2=v[3],y=v[4],weight=1,role=if(anyNA(v))'excluded'else if(year==2024)'outer-test'else'train')}))));raw<-read('actual3613-NLS-original52-fields-and-selection.csv');i<-seq_len(nrow(raw));x0<-suppressWarnings(as.numeric(raw$ed76));x1<-suppressWarnings(as.numeric(raw$age76));y<-suppressWarnings(as.numeric(raw$wage76))/100;person<-data.frame(id=paste0('person:',i),sourceRow=as.character(i),originalID=raw$id,x0=x0,x1=x1,y=y,weight=1,role=ifelse(is.na(x0)|is.na(x1)|is.na(y),'excluded',ifelse(i%%5==0,'outer-test','train')));raw<-read('actual3150-churn-original14-fields-and-selection.csv');i<-seq_len(nrow(raw));company<-data.frame(id=paste0('customer:',i),sourceRow=as.character(i),originalID='',x0=as.numeric(raw[['Call  Failure']]),x1=as.numeric(raw[['Subscription  Length']]),x2=as.numeric(raw[['Charge  Amount']]),y=raw$Churn,weight=1,role=ifelse(i%%5==0,'outer-test','train'));models<-list();for(index in 1:3){kind<-c('country','person','company')[index];d<-list(country,person,company)[[index]];task<-if(kind=='company')'classification'else'regression';s<-fixed_schedules(d$id[d$role=='train'],if(kind=='person')2L else 3L,20261102+7919*(index-1L));models[[kind]]<-list(records=d,task=task,classes=if(task=='classification')c('0','1')else character(),draws=s$draws,schedules=s$schedules,minLeaf=c(4L,50L,30L)[index])};models}\nrealdata<-function(models,kind,options=list()){if(is.null(options)||!is.list(options))stop('options object');m<-models[[kind]];d<-m$records;train<-d[d$role=='train',,drop=FALSE];test<-d[d$role=='outer-test',,drop=FALSE];method<-option(options,'method','forest');depth<-option(options,'maxDepth',2);count<-option(options,'memberCount',3);if(!method%in%c('bagging','forest','boost'))stop('known method');a<-list(rows=train,queries=test,task=m$task,classes=m$classes,maxDepth=depth,minLeaf=option(options,'minLeaf',m$minLeaf),minLeafWeight=0,minGain=0,missingRoute='best',learningRate=option(options,'learningRate','1/2'),stages=option(options,'stages',3));if(method=='boost')result<-boost(a)else{a$bootstrapDraws<-m$draws[seq_len(count)];a$nodeFeatures<-lapply(m$schedules[seq_len(count)],function(s)s[nchar(names(s))<depth]);result<-ensemble(a,method=='forest')};outer<-scored(result$predictions,normrows(test,m$task),m$task,m$classes);st<-stat(normrows(train,m$task),m$task,m$classes);constant<-list(prediction=st$pred,probabilities=st$p,vote=st$pred,prob=st$pred);baseline<-scored(lapply(test$id,function(id)c(list(id=id),constant)),normrows(test,m$task),m$task,m$classes);list(kind=kind,method=method,settings=a,train=train,test=test,result=result,outer=outer,baseline=baseline)}\nAPI<-\"aggregate\"\nINPUT<-list(members=list(list(id=\"m1\",predictions=data.frame(id=c(\"q\"),value=c(1),stringsAsFactors=FALSE)),list(id=\"m2\",predictions=data.frame(id=c(\"q\"),value=c(3),stringsAsFactors=FALSE))),memberWeights=list(1,3))\n\nrun_fixed<-function(api,a,out,src){\n r<-if(api=='variance')variance(a)else if(api=='aggregate')aggregate(a)else if(api%in%c('bagging','forest'))ensemble(a,api=='forest')else if(api=='boost')boost(a)else realdata(read_sources(src),a$kind)\n dir.create(out,recursive=TRUE,showWarnings=FALSE);summary<-list();points<-list();add<-function(x,y,s){if(!is.null(y)&&!is.na(y))points[[length(points)+1L]]<<-data.frame(x=x,y=as.numeric(y),series=s)}\n if(api=='variance'){summary<-r[c('B','varianceOfMean')];add(r$B,r$varianceOfMean,'Specified finite-B variance');xl<-'Number of members B';yl<-'Variance, stipulated units squared';title<-'Declared covariance model, not fitted trees'\n }else if(api=='aggregate'){p<-r$predictions[[1]];summary<-list(selectedPrediction=p$prediction);classification<-identical(a$task,'classification');if(classification){summary<-c(summary,list(voteLabel=p$vote,probabilityLabel=p$prob,meanProbability1=p$probabilities[2]));add(1,p$probabilities[2],'Mean probability of class 1');add(2,p$votes[2],'Label-vote share of class 1');xl<-'Aggregation (1=probability, 2=vote)';yl<-'Probability or vote share'}else{for(i in seq_along(a$members))add(i,num(a$members[[i]]$predictions$value[1]),'Member prediction');add(3,p$prediction,'Weighted mean');xl<-'Member 1, member 2, aggregate 3';yl<-'Prediction, assumed units'};title<-'Votes and probabilities are distinct objects'\n }else if(api%in%c('bagging','forest')){summary<-list(queryPrediction=r$predictions[[1]]$prediction,OOB.scoreable=r$outOfBag$eligibleRows,OOB.meanLoss=r$outOfBag$meanLoss);for(i in seq_len(nrow(a$rows)))add(i,a$rows$y[i],'Observed training outcome');for(i in seq_along(r$outOfBag$rows))add(i,r$outOfBag$rows[[i]]$prediction,'OOB prediction, when defined');xl<-'Original training ID order';yl<-'Outcome, assumed units';title<-'Repeated draws and ID-level OOB membership'\n }else if(api=='boost'){summary<-list(initial=r$initial,finalMSE=r$losses[[length(r$losses)]]$MSE,stages=r$stages);for(v in r$losses)add(v$stage,v$MSE,'Training MSE');xl<-'Boosting stage (0=initial)';yl<-'Weighted MSE, outcome units squared';title<-'Training descent does not certify held-out gain'\n }else{summary<-list(outer.scoreable=r$outer$eligibleRows,outer.meanLoss=r$outer$meanLoss,baseline.meanLoss=r$baseline$meanLoss,OOB.scoreable=r$result$outOfBag$eligibleRows,OOB.meanLoss=r$result$outOfBag$meanLoss);for(i in seq_along(r$outer$rows)){p<-r$outer$rows[[i]];add(i,as.numeric(p$actual),'Observed outcome');add(i,if(a$kind=='company')p$probabilities[2]else p$prediction,if(a$kind=='company')'Forest probability of class 1'else'Forest prediction')};xl<-'Outer-test source order, not a time path';yl<-if(a$kind=='company')'Churn label / probability'else if(a$kind=='country')'Period life expectancy, years'else'Nominal 1976 USD per hour';title<-'Fixed forest; outer labels did not fit the trees'}\n display<-function(v)if(is.null(v)||is.na(v))'undefined'else sprintf('%.9f',as.numeric(v));write.csv(data.frame(metric=names(summary),value=vapply(summary,display,'')),file.path(out,'summary.csv'),row.names=FALSE);pp<-do.call(rbind,points);write.csv(pp,file.path(out,'plot-points.csv'),row.names=FALSE);dput(r,file.path(out,'full-result.Rtext'));svg(file.path(out,'plot.svg'),width=5.6,height=4.6,pointsize=14);par(mar=c(5.8,5.8,5.3,1.2),mgp=c(3.7,1,0));xr<-range(pp$x);yr<-range(pp$y);if(diff(xr)==0)xr<-xr+c(-.5,.5);if(diff(yr)==0)yr<-yr+c(-.5,.5);plot(xr,yr,type='n',xlab=xl,ylab=yl,cex.lab=.78,axes=FALSE);axis(1,at=pretty(xr,3));axis(2,at=pretty(yr,4),las=1,cex.axis=.82);box();grid(col='#dddddd');cols<-c('#355c72','#a55336','#507956','#78568b');ss<-unique(pp$series);for(i in seq_along(ss)){v<-pp[pp$series==ss[i],];points(v$x,v$y,pch=16,cex=if(nrow(v)>100).35 else .85,col=adjustcolor(cols[i],if(nrow(v)>100).5 else 1))};legend('topleft',legend=ss,col=cols[seq_along(ss)],lty=0,pch=16,cex=.65,bty='n',inset=c(0,-.32),xpd=NA);mtext(title,side=3,line=3.9,cex=.6);dev.off();cat(paste(names(summary),vapply(summary,display,''),sep='=',collapse=', '),'\\n')\n}\nargs<-commandArgs(trailingOnly=TRUE)\ntryCatch(run_fixed(API,INPUT,if(length(args))args[1]else'fixed-results',if(length(args)>1)args[2]else'ml09-sources'),error=function(e){cat('Rejected declared input: ',conditionMessage(e),'\\n',file=stderr());quit(status=2)})\n",
        "inputFiles": [],
        "input": {
          "members": [
            {
              "id": "m1",
              "predictions": [
                {
                  "id": "q",
                  "value": 1
                }
              ]
            },
            {
              "id": "m2",
              "predictions": [
                {
                  "id": "q",
                  "value": 3
                }
              ]
            }
          ],
          "memberWeights": [
            1,
            3
          ]
        },
        "returnCode": 0,
        "expectedFailure": false,
        "stdout": "selectedPrediction=2.500000000 \n",
        "stderr": "During startup - Warning messages:\n1: Setting LC_COLLATE=C.UTF-8 failed \n2: Setting LC_CTYPE=C.UTF-8 failed \n3: Setting LC_MONETARY=C.UTF-8 failed \n4: Setting LC_TIME=C.UTF-8 failed \n",
        "summary": {
          "selectedPrediction": "2.500000000"
        },
        "plotPoints": [
          {
            "x": "1",
            "y": "1",
            "series": "Member prediction"
          },
          {
            "x": "2",
            "y": "3",
            "series": "Member prediction"
          },
          {
            "x": "3",
            "y": "2.5",
            "series": "Weighted mean"
          }
        ],
        "plotFile": "ml09-fixed-results/aggregate-weighted-mean-r/plot.svg",
        "plotSHA256": "5513a9b0cb897313706c1eab70d7283ef63c3abb3fa3abe441ff4469c8063eb0",
        "files": [
          {
            "file": "ml09-fixed-results/aggregate-weighted-mean-r/full-result.Rtext",
            "sha256": "fae71833cb74fdc0da4969d349dd9e25d094f19bfc0ce96c95ab76e76e7adef1"
          },
          {
            "file": "ml09-fixed-results/aggregate-weighted-mean-r/plot-points.csv",
            "sha256": "efa3a2d28089280d7910ae22fd5f5adb021a0b67fd2a9f640b8b14ac7e5ac7cb"
          },
          {
            "file": "ml09-fixed-results/aggregate-weighted-mean-r/plot.svg",
            "sha256": "5513a9b0cb897313706c1eab70d7283ef63c3abb3fa3abe441ff4469c8063eb0"
          },
          {
            "file": "ml09-fixed-results/aggregate-weighted-mean-r/summary.csv",
            "sha256": "5cede489733790ef3d4e0fb0829311f19018cdfa9c0a367718411a344082f02d"
          }
        ],
        "scope": "Actually executed self-contained fixed example; current web controls execute separately. Python Fraction and finite-precision base R. Author gate, not independent peer."
      },
      "votes-versus-probabilities": {
        "api": "aggregate",
        "variant": "votes-versus-probabilities",
        "language": "r",
        "codeFile": "ml09-code/aggregate-votes-versus-probabilities.R",
        "codeSHA256": "ad05ecac7482330d008442d8f0262f6c1ca8a4ac6a4640ac3b1759516dd3cd63",
        "codeText": "# ML09 base-R reproduction from native original-field CSVs.\n# Rscript ml09-public-analysis.R ml09-sources results-r\n# Separately written vectorized direct-centered squared/Gini losses.\n# No Python/JS/model-contract/stored-answer/derived-result reader or package.\n# Numeric arithmetic is binary64:1e-12 relative tie tolerance stabilizes exact\n# source ties,but does not certify tiny margins/underflow like Fraction JS/Python.\n# Data-frame rows use x0,x1,...,y,weight; original IDs remain attached to draws.\noptions(stringsAsFactors=FALSE,digits=17)\nnum<-function(v){if(is.null(v)||length(v)!=1||is.na(v))stop('numeric parameter required, not explicit NULL');p<-strsplit(as.character(v),'/',fixed=TRUE)[[1]];z<-if(length(p)==2)as.numeric(p[1])/as.numeric(p[2])else as.numeric(v);if(!is.finite(z))stop('finite numeric parameter');z}\noption<-function(a,k,default){if(k%in%names(a))a[[k]]else default}\nnormrows<-function(d,task){if(!'weight'%in%names(d))d$weight<-1;if(!'id'%in%names(d))d$id<-as.character(seq_len(nrow(d))-1);d$weight<-as.numeric(d$weight);if(anyNA(d$weight)||any(d$weight<0))stop('nonnegative weights');if(task=='regression')d$y<-as.numeric(d$y)else d$y<-as.character(d$y);d}\nstat<-function(d,task,classes){W<-sum(d$weight);mu<-if(task=='regression'&&W)sum(d$weight*d$y)/W else NA_real_;p<-if(task=='classification'&&W)vapply(classes,function(c)sum(d$weight[d$y==c])/W,0)else numeric();risk<-if(task=='regression'&&W)sum(d$weight*(d$y-mu)^2)else W*sum(p*(1-p));list(n=nrow(d),w=W,mu=mu,p=unname(p),risk=risk,pred=if(task=='regression')mu else if(W)classes[which.max(p)]else NA_character_)}\nfit<-function(d,a,task,classes,schedule=NULL){d<-d[d$weight>0&!is.na(d$y),,drop=FALSE];if(!nrow(d))stop('positive observed training');W<-sum(d$weight);depth<-option(a,'maxDepth',2);minimum<-option(a,'minLeaf',1);minmass<-num(option(a,'minLeafWeight',0));mingain<-num(option(a,'minGain',0));route<-option(a,'missingRoute','best');features<-grep('^x[0-9]+$',names(d),value=TRUE)\n build<-function(rr,level,path){st<-stat(rr,task,classes);node<-list(rows=rr,st=st,split=NULL,left=NULL,right=NULL,path=path);if(level==depth)return(node);best<-NULL;allowed<-if(is.null(schedule))seq_along(features)-1L else schedule[[match(path,names(schedule))]]\n  for(j in seq_along(features)-1L){if(!j%in%allowed)next;v<-rr[[features[j+1L]]];values<-sort(unique(v[!is.na(v)]));candidates<-list()\n   if(length(values)>1)for(k in seq_len(length(values)-1L)){threshold<-(values[k]+values[k+1L])/2;missing<-is.na(v);left<-!missing&v<=threshold;right<-!missing&v>threshold;directions<-if(route!='best')route else if(any(missing))c('left','right')else if(sum(left)>=sum(right))'left'else'right';for(direction in directions)candidates[[length(candidates)+1L]]<-list(kind='threshold',threshold=threshold,missingRoute=direction,left=if(direction=='left')left|missing else left,right=if(direction=='right')right|missing else right)}\n   if(anyNA(v)&&any(!is.na(v)))candidates[[length(candidates)+1L]]<-list(kind='missing-only',threshold=NA_real_,missingRoute='left',left=is.na(v),right=!is.na(v))\n   for(candidate in candidates){l<-rr[candidate$left,,drop=FALSE];r<-rr[candidate$right,,drop=FALSE];ls<-stat(l,task,classes);rs<-stat(r,task,classes);if(min(ls$n,rs$n)<minimum||min(ls$w,rs$w)<minmass||min(ls$w,rs$w)<=0)next;gain<-(st$risk-ls$risk-rs$risk)/W;tol<-1e-12*max(1,abs(gain),if(is.null(best))0 else abs(best$gain));if(is.null(best)||gain>best$gain+tol)best<-c(candidate,list(feature=j,gain=gain,l=l,r=r))}\n  }\n  if(!is.null(best)&&best$gain>max(mingain,1e-12)){node$split<-best;node$left<-build(best$l,level+1L,paste0(path,'L'));node$right<-build(best$r,level+1L,paste0(path,'R'))};node\n };build(d,0L,'')\n}\npredict_one<-function(tree,row){n<-tree;while(!is.null(n$split)){s<-n$split;v<-as.numeric(row[[paste0('x',s$feature)]]);left<-if(s$kind=='missing-only')is.na(v)else if(is.na(v))s$missingRoute=='left'else v<=s$threshold;n<-if(left)n$left else n$right};list(prediction=n$st$pred,probabilities=n$st$p)}\ncombine<-function(pp,w,task,classes,mode='probabilities'){W<-sum(w);if(!length(pp)||!W)return(list(prediction=if(task=='regression')NA_real_ else NA_character_,probabilities=numeric(),vote=NA_character_,prob=NA_character_));if(task=='regression')return(list(prediction=sum(vapply(pp,function(p)p$prediction,0)*w)/W,probabilities=numeric(),vote=NA_character_,prob=NA_character_));votes<-vapply(classes,function(c)sum(w[vapply(pp,function(p)p$prediction==c,FALSE)])/W,0);probs<-vapply(seq_along(classes),function(j)sum(vapply(pp,function(p)p$probabilities[j],0)*w)/W,0);vote<-classes[which.max(votes)];prob<-classes[which.max(probs)];list(prediction=if(mode=='votes')vote else prob,probabilities=unname(probs),vote=vote,prob=prob,votes=unname(votes))}\nvariance<-function(a){B<-num(a$B);v<-num(a$marginalVariance);rho<-num(option(a,'rho',0));if(B<1||B!=floor(B)||v<0)stop('integer B/nonnegative variance');if(B>1&&v>0&&(rho< -1/(B-1)||rho>1))stop('PSD correlation');list(B=B,marginalVariance=v,correlationApplicable=B>1&&v>0,varianceOfMean=if(B==1)v else v*(1+(B-1)*rho)/B)}\naggregate<-function(a){task<-option(a,'task','regression');classes<-option(a,'classes',character());w<-vapply(option(a,'memberWeights',as.list(rep(1,length(a$members)))),num,0);if(any(w<0)||sum(w)<=0)stop('positive member mass');ids<-a$members[[1]]$predictions$id;pp<-lapply(ids,function(id){members<-lapply(a$members,function(m){r<-m$predictions[match(id,m$predictions$id),,drop=FALSE];if(task=='regression')list(prediction=num(r$value),probabilities=numeric())else list(prediction=as.character(r$label),probabilities=as.numeric(r[paste0('p',seq_along(classes)-1L)]))});c(list(id=id),combine(members,w,task,classes,option(a,'aggregation','probabilities')))});list(task=task,classes=classes,predictions=pp)}\nscored<-function(preds,d,task,classes){W<-loss<-absolute<-errors<-voteerrors<-0;count<-0L;out<-lapply(seq_len(nrow(d)),function(i){r<-d[i,,drop=FALSE];p<-preds[[i]];ok<-!is.na(p$prediction)&&!is.na(r$y)&&r$weight>0;value<-NA_real_;if(ok){count<<-count+1L;W<<-W+r$weight;if(task=='regression'){e<-r$y-p$prediction;value<-e*e;absolute<<-absolute+r$weight*abs(e)}else{value<-sum((p$probabilities-as.numeric(classes==r$y))^2);errors<<-errors+r$weight*(p$prediction!=r$y);voteerrors<<-voteerrors+r$weight*(p$vote!=r$y)};loss<<-loss+r$weight*value};c(p,list(actual=r$y,weight=r$weight,scoreEligible=ok,loss=value))});list(rows=out,eligibleRows=count,weight=W,totalLoss=loss,meanLoss=if(W)loss/W else NA_real_,MAE=if(W&&task=='regression')absolute/W else NA_real_,errorRate=if(W&&task=='classification')errors/W else NA_real_,labelVoteErrorRate=if(W&&task=='classification')voteerrors/W else NA_real_)}\nensemble<-function(a,forest=FALSE){task<-option(a,'task','regression');classes<-option(a,'classes',character());d<-normrows(a$rows,task);w<-vapply(option(a,'memberWeights',as.list(rep(1,length(a$bootstrapDraws)))),num,0);if(any(w<0)||sum(w)<=0)stop('positive member mass');members<-lapply(seq_along(a$bootstrapDraws),function(i){draw<-a$bootstrapDraws[[i]];indices<-match(draw,d$id);if(anyNA(indices))stop('unknown draw source');tree<-fit(d[indices,,drop=FALSE],a,task,classes,if(forest)a$nodeFeatures[[i]]else NULL);list(tree=tree,draw=draw,inbag=unique(draw),weight=w[i])});queries<-a$queries;preds<-lapply(seq_len(nrow(queries)),function(i)c(list(id=queries$id[i]),combine(lapply(members,function(m)predict_one(m$tree,queries[i,,drop=FALSE])),w,task,classes,option(a,'aggregation','probabilities'))));oob<-lapply(seq_len(nrow(d)),function(i){app<-which(!vapply(members,function(m)d$id[i]%in%m$inbag,FALSE));pp<-combine(lapply(app,function(j)predict_one(members[[j]]$tree,d[i,,drop=FALSE])),w[app],task,classes,option(a,'aggregation','probabilities'));c(list(id=d$id[i],applicable=app-1L,positiveMembers=sum(w[app]>0)),pp)});list(task=task,classes=classes,members=members,predictions=preds,outOfBag=scored(oob,d,task,classes))}\nboost<-function(a){if(option(a,'task','regression')!='regression')stop('regression boosting only');d<-normrows(a$rows,'regression');eligible<-d$weight>0&!is.na(d$y);W<-sum(d$weight[eligible]);if(!W)stop('positive eligible training');eta<-num(option(a,'learningRate','1/2'));stages<-option(a,'stages',3);if(is.null(stages)||stages!=floor(stages)||stages<0||stages>8||eta<0||eta>1)stop('supported rate/stages');initial<-if('initial'%in%names(a))num(a$initial)else sum(d$weight[eligible]*d$y[eligible])/W;train<-matrix(initial,nrow(d),stages+1L);query<-matrix(initial,nrow(a$queries),stages+1L);losses<-fits<-list();for(stage in 0:stages){sse<-sum(d$weight[eligible]*(d$y[eligible]-train[eligible,stage+1L])^2);losses[[stage+1L]]<-list(stage=stage,rawWeightedSSE=sse,MSE=sse/W,meanHalfSquaredLoss=sse/(2*W));if(stage==stages)break;residual<-d;residual$y<-d$y-train[,stage+1L];tree<-fit(residual,a,'regression',character());h<-vapply(seq_len(nrow(d)),function(i)predict_one(tree,d[i,,drop=FALSE])$prediction,0);qh<-vapply(seq_len(nrow(a$queries)),function(i)predict_one(tree,a$queries[i,,drop=FALSE])$prediction,0);stageRows<-lapply(seq_len(nrow(d)),function(i)list(id=d$id[i],before=train[i,stage+1L],residual=residual$y[i],negativeCoordinateDerivative=d$weight[i]*residual$y[i]/W,fit=h[i],addition=eta*h[i],after=train[i,stage+1L]+eta*h[i]));train[,stage+2L]<-train[,stage+1L]+eta*h;query[,stage+2L]<-query[,stage+1L]+eta*qh;norm<-sum(d$weight[eligible]*h[eligible]^2);fits[[stage+1L]]<-list(stage=stage+1L,tree=tree,rows=stageRows,queryFits=qh,norm=norm,predictedSSEDecrease=eta*(2-eta)*norm)};list(task='regression',initial=initial,learningRate=eta,stages=stages,training=train,queries=query,fits=fits,losses=losses,predictions=lapply(seq_len(nrow(a$queries)),function(i)list(id=a$queries$id[i],prediction=query[i,stages+1L],probabilities=numeric(),vote=NA_character_,prob=NA_character_)))}\nfixed_schedules<-function(ids,p,seed){state<-seed;choose<-function(n){limit<-floor(4294967296/n)*n;repeat{state<<-(1664525*state+1013904223)%%4294967296;if(state<limit)return(as.integer(state%%n))}};draws<-schedules<-list();for(member in 1:4){draws[[member]]<-vapply(seq_along(ids),function(i)ids[choose(length(ids))+1L],'');schedule<-setNames(vector('list',7),c('','L','R','LL','LR','RL','RR'));for(path in names(schedule)){order<-seq_len(p)-1L;if(p>1)for(j in seq(p-1L,1L)){k<-choose(j+1L);temp<-order[j+1L];order[j+1L]<-order[k+1L];order[k+1L]<-temp};schedule[[match(path,names(schedule))]]<-sort(order[seq_len(max(1L,floor(sqrt(p))))])};schedules[[member]]<-schedule};list(draws=draws,schedules=schedules)}\nread_sources<-function(src){read<-function(name)read.csv(file.path(src,name),check.names=FALSE,colClasses='character',na.strings=character(),fileEncoding='UTF-8-BOM');raw<-read('actual320-country-four-indicators-original-2020-2024.csv');country<-do.call(rbind,lapply(sort(unique(raw$countryISO3)),function(code)do.call(rbind,lapply(2020:2024,function(year){keys<-c('NY.GDP.PCAP.KD','NY.GDP.MKTP.KD.ZG','FP.CPI.TOTL.ZG','SP.DYN.LE00.IN');v<-vapply(keys,function(k)as.numeric(raw$originalValueToken[raw$countryISO3==code&raw$date==as.character(year)&raw$indicatorID==k]),0);data.frame(id=paste0(code,':',year),sourceRow=paste0(code,':',year),originalID=code,year=year,x0=v[1]/10000,x1=v[2],x2=v[3],y=v[4],weight=1,role=if(anyNA(v))'excluded'else if(year==2024)'outer-test'else'train')}))));raw<-read('actual3613-NLS-original52-fields-and-selection.csv');i<-seq_len(nrow(raw));x0<-suppressWarnings(as.numeric(raw$ed76));x1<-suppressWarnings(as.numeric(raw$age76));y<-suppressWarnings(as.numeric(raw$wage76))/100;person<-data.frame(id=paste0('person:',i),sourceRow=as.character(i),originalID=raw$id,x0=x0,x1=x1,y=y,weight=1,role=ifelse(is.na(x0)|is.na(x1)|is.na(y),'excluded',ifelse(i%%5==0,'outer-test','train')));raw<-read('actual3150-churn-original14-fields-and-selection.csv');i<-seq_len(nrow(raw));company<-data.frame(id=paste0('customer:',i),sourceRow=as.character(i),originalID='',x0=as.numeric(raw[['Call  Failure']]),x1=as.numeric(raw[['Subscription  Length']]),x2=as.numeric(raw[['Charge  Amount']]),y=raw$Churn,weight=1,role=ifelse(i%%5==0,'outer-test','train'));models<-list();for(index in 1:3){kind<-c('country','person','company')[index];d<-list(country,person,company)[[index]];task<-if(kind=='company')'classification'else'regression';s<-fixed_schedules(d$id[d$role=='train'],if(kind=='person')2L else 3L,20261102+7919*(index-1L));models[[kind]]<-list(records=d,task=task,classes=if(task=='classification')c('0','1')else character(),draws=s$draws,schedules=s$schedules,minLeaf=c(4L,50L,30L)[index])};models}\nrealdata<-function(models,kind,options=list()){if(is.null(options)||!is.list(options))stop('options object');m<-models[[kind]];d<-m$records;train<-d[d$role=='train',,drop=FALSE];test<-d[d$role=='outer-test',,drop=FALSE];method<-option(options,'method','forest');depth<-option(options,'maxDepth',2);count<-option(options,'memberCount',3);if(!method%in%c('bagging','forest','boost'))stop('known method');a<-list(rows=train,queries=test,task=m$task,classes=m$classes,maxDepth=depth,minLeaf=option(options,'minLeaf',m$minLeaf),minLeafWeight=0,minGain=0,missingRoute='best',learningRate=option(options,'learningRate','1/2'),stages=option(options,'stages',3));if(method=='boost')result<-boost(a)else{a$bootstrapDraws<-m$draws[seq_len(count)];a$nodeFeatures<-lapply(m$schedules[seq_len(count)],function(s)s[nchar(names(s))<depth]);result<-ensemble(a,method=='forest')};outer<-scored(result$predictions,normrows(test,m$task),m$task,m$classes);st<-stat(normrows(train,m$task),m$task,m$classes);constant<-list(prediction=st$pred,probabilities=st$p,vote=st$pred,prob=st$pred);baseline<-scored(lapply(test$id,function(id)c(list(id=id),constant)),normrows(test,m$task),m$task,m$classes);list(kind=kind,method=method,settings=a,train=train,test=test,result=result,outer=outer,baseline=baseline)}\nAPI<-\"aggregate\"\nINPUT<-list(task=\"classification\",classes=c(\"0\",\"1\"),members=list(list(id=\"0\",predictions=data.frame(id=c(\"q\"),label=c(\"0\"),p0=c(0.51),p1=c(0.49),stringsAsFactors=FALSE)),list(id=\"1\",predictions=data.frame(id=c(\"q\"),label=c(\"0\"),p0=c(0.51),p1=c(0.49),stringsAsFactors=FALSE)),list(id=\"2\",predictions=data.frame(id=c(\"q\"),label=c(\"1\"),p0=c(0),p1=c(1),stringsAsFactors=FALSE))),aggregation=\"probabilities\")\n\nrun_fixed<-function(api,a,out,src){\n r<-if(api=='variance')variance(a)else if(api=='aggregate')aggregate(a)else if(api%in%c('bagging','forest'))ensemble(a,api=='forest')else if(api=='boost')boost(a)else realdata(read_sources(src),a$kind)\n dir.create(out,recursive=TRUE,showWarnings=FALSE);summary<-list();points<-list();add<-function(x,y,s){if(!is.null(y)&&!is.na(y))points[[length(points)+1L]]<<-data.frame(x=x,y=as.numeric(y),series=s)}\n if(api=='variance'){summary<-r[c('B','varianceOfMean')];add(r$B,r$varianceOfMean,'Specified finite-B variance');xl<-'Number of members B';yl<-'Variance, stipulated units squared';title<-'Declared covariance model, not fitted trees'\n }else if(api=='aggregate'){p<-r$predictions[[1]];summary<-list(selectedPrediction=p$prediction);classification<-identical(a$task,'classification');if(classification){summary<-c(summary,list(voteLabel=p$vote,probabilityLabel=p$prob,meanProbability1=p$probabilities[2]));add(1,p$probabilities[2],'Mean probability of class 1');add(2,p$votes[2],'Label-vote share of class 1');xl<-'Aggregation (1=probability, 2=vote)';yl<-'Probability or vote share'}else{for(i in seq_along(a$members))add(i,num(a$members[[i]]$predictions$value[1]),'Member prediction');add(3,p$prediction,'Weighted mean');xl<-'Member 1, member 2, aggregate 3';yl<-'Prediction, assumed units'};title<-'Votes and probabilities are distinct objects'\n }else if(api%in%c('bagging','forest')){summary<-list(queryPrediction=r$predictions[[1]]$prediction,OOB.scoreable=r$outOfBag$eligibleRows,OOB.meanLoss=r$outOfBag$meanLoss);for(i in seq_len(nrow(a$rows)))add(i,a$rows$y[i],'Observed training outcome');for(i in seq_along(r$outOfBag$rows))add(i,r$outOfBag$rows[[i]]$prediction,'OOB prediction, when defined');xl<-'Original training ID order';yl<-'Outcome, assumed units';title<-'Repeated draws and ID-level OOB membership'\n }else if(api=='boost'){summary<-list(initial=r$initial,finalMSE=r$losses[[length(r$losses)]]$MSE,stages=r$stages);for(v in r$losses)add(v$stage,v$MSE,'Training MSE');xl<-'Boosting stage (0=initial)';yl<-'Weighted MSE, outcome units squared';title<-'Training descent does not certify held-out gain'\n }else{summary<-list(outer.scoreable=r$outer$eligibleRows,outer.meanLoss=r$outer$meanLoss,baseline.meanLoss=r$baseline$meanLoss,OOB.scoreable=r$result$outOfBag$eligibleRows,OOB.meanLoss=r$result$outOfBag$meanLoss);for(i in seq_along(r$outer$rows)){p<-r$outer$rows[[i]];add(i,as.numeric(p$actual),'Observed outcome');add(i,if(a$kind=='company')p$probabilities[2]else p$prediction,if(a$kind=='company')'Forest probability of class 1'else'Forest prediction')};xl<-'Outer-test source order, not a time path';yl<-if(a$kind=='company')'Churn label / probability'else if(a$kind=='country')'Period life expectancy, years'else'Nominal 1976 USD per hour';title<-'Fixed forest; outer labels did not fit the trees'}\n display<-function(v)if(is.null(v)||is.na(v))'undefined'else sprintf('%.9f',as.numeric(v));write.csv(data.frame(metric=names(summary),value=vapply(summary,display,'')),file.path(out,'summary.csv'),row.names=FALSE);pp<-do.call(rbind,points);write.csv(pp,file.path(out,'plot-points.csv'),row.names=FALSE);dput(r,file.path(out,'full-result.Rtext'));svg(file.path(out,'plot.svg'),width=5.6,height=4.6,pointsize=14);par(mar=c(5.8,5.8,5.3,1.2),mgp=c(3.7,1,0));xr<-range(pp$x);yr<-range(pp$y);if(diff(xr)==0)xr<-xr+c(-.5,.5);if(diff(yr)==0)yr<-yr+c(-.5,.5);plot(xr,yr,type='n',xlab=xl,ylab=yl,cex.lab=.78,axes=FALSE);axis(1,at=pretty(xr,3));axis(2,at=pretty(yr,4),las=1,cex.axis=.82);box();grid(col='#dddddd');cols<-c('#355c72','#a55336','#507956','#78568b');ss<-unique(pp$series);for(i in seq_along(ss)){v<-pp[pp$series==ss[i],];points(v$x,v$y,pch=16,cex=if(nrow(v)>100).35 else .85,col=adjustcolor(cols[i],if(nrow(v)>100).5 else 1))};legend('topleft',legend=ss,col=cols[seq_along(ss)],lty=0,pch=16,cex=.65,bty='n',inset=c(0,-.32),xpd=NA);mtext(title,side=3,line=3.9,cex=.6);dev.off();cat(paste(names(summary),vapply(summary,display,''),sep='=',collapse=', '),'\\n')\n}\nargs<-commandArgs(trailingOnly=TRUE)\ntryCatch(run_fixed(API,INPUT,if(length(args))args[1]else'fixed-results',if(length(args)>1)args[2]else'ml09-sources'),error=function(e){cat('Rejected declared input: ',conditionMessage(e),'\\n',file=stderr());quit(status=2)})\n",
        "code": "# ML09 base-R reproduction from native original-field CSVs.\n# Rscript ml09-public-analysis.R ml09-sources results-r\n# Separately written vectorized direct-centered squared/Gini losses.\n# No Python/JS/model-contract/stored-answer/derived-result reader or package.\n# Numeric arithmetic is binary64:1e-12 relative tie tolerance stabilizes exact\n# source ties,but does not certify tiny margins/underflow like Fraction JS/Python.\n# Data-frame rows use x0,x1,...,y,weight; original IDs remain attached to draws.\noptions(stringsAsFactors=FALSE,digits=17)\nnum<-function(v){if(is.null(v)||length(v)!=1||is.na(v))stop('numeric parameter required, not explicit NULL');p<-strsplit(as.character(v),'/',fixed=TRUE)[[1]];z<-if(length(p)==2)as.numeric(p[1])/as.numeric(p[2])else as.numeric(v);if(!is.finite(z))stop('finite numeric parameter');z}\noption<-function(a,k,default){if(k%in%names(a))a[[k]]else default}\nnormrows<-function(d,task){if(!'weight'%in%names(d))d$weight<-1;if(!'id'%in%names(d))d$id<-as.character(seq_len(nrow(d))-1);d$weight<-as.numeric(d$weight);if(anyNA(d$weight)||any(d$weight<0))stop('nonnegative weights');if(task=='regression')d$y<-as.numeric(d$y)else d$y<-as.character(d$y);d}\nstat<-function(d,task,classes){W<-sum(d$weight);mu<-if(task=='regression'&&W)sum(d$weight*d$y)/W else NA_real_;p<-if(task=='classification'&&W)vapply(classes,function(c)sum(d$weight[d$y==c])/W,0)else numeric();risk<-if(task=='regression'&&W)sum(d$weight*(d$y-mu)^2)else W*sum(p*(1-p));list(n=nrow(d),w=W,mu=mu,p=unname(p),risk=risk,pred=if(task=='regression')mu else if(W)classes[which.max(p)]else NA_character_)}\nfit<-function(d,a,task,classes,schedule=NULL){d<-d[d$weight>0&!is.na(d$y),,drop=FALSE];if(!nrow(d))stop('positive observed training');W<-sum(d$weight);depth<-option(a,'maxDepth',2);minimum<-option(a,'minLeaf',1);minmass<-num(option(a,'minLeafWeight',0));mingain<-num(option(a,'minGain',0));route<-option(a,'missingRoute','best');features<-grep('^x[0-9]+$',names(d),value=TRUE)\n build<-function(rr,level,path){st<-stat(rr,task,classes);node<-list(rows=rr,st=st,split=NULL,left=NULL,right=NULL,path=path);if(level==depth)return(node);best<-NULL;allowed<-if(is.null(schedule))seq_along(features)-1L else schedule[[match(path,names(schedule))]]\n  for(j in seq_along(features)-1L){if(!j%in%allowed)next;v<-rr[[features[j+1L]]];values<-sort(unique(v[!is.na(v)]));candidates<-list()\n   if(length(values)>1)for(k in seq_len(length(values)-1L)){threshold<-(values[k]+values[k+1L])/2;missing<-is.na(v);left<-!missing&v<=threshold;right<-!missing&v>threshold;directions<-if(route!='best')route else if(any(missing))c('left','right')else if(sum(left)>=sum(right))'left'else'right';for(direction in directions)candidates[[length(candidates)+1L]]<-list(kind='threshold',threshold=threshold,missingRoute=direction,left=if(direction=='left')left|missing else left,right=if(direction=='right')right|missing else right)}\n   if(anyNA(v)&&any(!is.na(v)))candidates[[length(candidates)+1L]]<-list(kind='missing-only',threshold=NA_real_,missingRoute='left',left=is.na(v),right=!is.na(v))\n   for(candidate in candidates){l<-rr[candidate$left,,drop=FALSE];r<-rr[candidate$right,,drop=FALSE];ls<-stat(l,task,classes);rs<-stat(r,task,classes);if(min(ls$n,rs$n)<minimum||min(ls$w,rs$w)<minmass||min(ls$w,rs$w)<=0)next;gain<-(st$risk-ls$risk-rs$risk)/W;tol<-1e-12*max(1,abs(gain),if(is.null(best))0 else abs(best$gain));if(is.null(best)||gain>best$gain+tol)best<-c(candidate,list(feature=j,gain=gain,l=l,r=r))}\n  }\n  if(!is.null(best)&&best$gain>max(mingain,1e-12)){node$split<-best;node$left<-build(best$l,level+1L,paste0(path,'L'));node$right<-build(best$r,level+1L,paste0(path,'R'))};node\n };build(d,0L,'')\n}\npredict_one<-function(tree,row){n<-tree;while(!is.null(n$split)){s<-n$split;v<-as.numeric(row[[paste0('x',s$feature)]]);left<-if(s$kind=='missing-only')is.na(v)else if(is.na(v))s$missingRoute=='left'else v<=s$threshold;n<-if(left)n$left else n$right};list(prediction=n$st$pred,probabilities=n$st$p)}\ncombine<-function(pp,w,task,classes,mode='probabilities'){W<-sum(w);if(!length(pp)||!W)return(list(prediction=if(task=='regression')NA_real_ else NA_character_,probabilities=numeric(),vote=NA_character_,prob=NA_character_));if(task=='regression')return(list(prediction=sum(vapply(pp,function(p)p$prediction,0)*w)/W,probabilities=numeric(),vote=NA_character_,prob=NA_character_));votes<-vapply(classes,function(c)sum(w[vapply(pp,function(p)p$prediction==c,FALSE)])/W,0);probs<-vapply(seq_along(classes),function(j)sum(vapply(pp,function(p)p$probabilities[j],0)*w)/W,0);vote<-classes[which.max(votes)];prob<-classes[which.max(probs)];list(prediction=if(mode=='votes')vote else prob,probabilities=unname(probs),vote=vote,prob=prob,votes=unname(votes))}\nvariance<-function(a){B<-num(a$B);v<-num(a$marginalVariance);rho<-num(option(a,'rho',0));if(B<1||B!=floor(B)||v<0)stop('integer B/nonnegative variance');if(B>1&&v>0&&(rho< -1/(B-1)||rho>1))stop('PSD correlation');list(B=B,marginalVariance=v,correlationApplicable=B>1&&v>0,varianceOfMean=if(B==1)v else v*(1+(B-1)*rho)/B)}\naggregate<-function(a){task<-option(a,'task','regression');classes<-option(a,'classes',character());w<-vapply(option(a,'memberWeights',as.list(rep(1,length(a$members)))),num,0);if(any(w<0)||sum(w)<=0)stop('positive member mass');ids<-a$members[[1]]$predictions$id;pp<-lapply(ids,function(id){members<-lapply(a$members,function(m){r<-m$predictions[match(id,m$predictions$id),,drop=FALSE];if(task=='regression')list(prediction=num(r$value),probabilities=numeric())else list(prediction=as.character(r$label),probabilities=as.numeric(r[paste0('p',seq_along(classes)-1L)]))});c(list(id=id),combine(members,w,task,classes,option(a,'aggregation','probabilities')))});list(task=task,classes=classes,predictions=pp)}\nscored<-function(preds,d,task,classes){W<-loss<-absolute<-errors<-voteerrors<-0;count<-0L;out<-lapply(seq_len(nrow(d)),function(i){r<-d[i,,drop=FALSE];p<-preds[[i]];ok<-!is.na(p$prediction)&&!is.na(r$y)&&r$weight>0;value<-NA_real_;if(ok){count<<-count+1L;W<<-W+r$weight;if(task=='regression'){e<-r$y-p$prediction;value<-e*e;absolute<<-absolute+r$weight*abs(e)}else{value<-sum((p$probabilities-as.numeric(classes==r$y))^2);errors<<-errors+r$weight*(p$prediction!=r$y);voteerrors<<-voteerrors+r$weight*(p$vote!=r$y)};loss<<-loss+r$weight*value};c(p,list(actual=r$y,weight=r$weight,scoreEligible=ok,loss=value))});list(rows=out,eligibleRows=count,weight=W,totalLoss=loss,meanLoss=if(W)loss/W else NA_real_,MAE=if(W&&task=='regression')absolute/W else NA_real_,errorRate=if(W&&task=='classification')errors/W else NA_real_,labelVoteErrorRate=if(W&&task=='classification')voteerrors/W else NA_real_)}\nensemble<-function(a,forest=FALSE){task<-option(a,'task','regression');classes<-option(a,'classes',character());d<-normrows(a$rows,task);w<-vapply(option(a,'memberWeights',as.list(rep(1,length(a$bootstrapDraws)))),num,0);if(any(w<0)||sum(w)<=0)stop('positive member mass');members<-lapply(seq_along(a$bootstrapDraws),function(i){draw<-a$bootstrapDraws[[i]];indices<-match(draw,d$id);if(anyNA(indices))stop('unknown draw source');tree<-fit(d[indices,,drop=FALSE],a,task,classes,if(forest)a$nodeFeatures[[i]]else NULL);list(tree=tree,draw=draw,inbag=unique(draw),weight=w[i])});queries<-a$queries;preds<-lapply(seq_len(nrow(queries)),function(i)c(list(id=queries$id[i]),combine(lapply(members,function(m)predict_one(m$tree,queries[i,,drop=FALSE])),w,task,classes,option(a,'aggregation','probabilities'))));oob<-lapply(seq_len(nrow(d)),function(i){app<-which(!vapply(members,function(m)d$id[i]%in%m$inbag,FALSE));pp<-combine(lapply(app,function(j)predict_one(members[[j]]$tree,d[i,,drop=FALSE])),w[app],task,classes,option(a,'aggregation','probabilities'));c(list(id=d$id[i],applicable=app-1L,positiveMembers=sum(w[app]>0)),pp)});list(task=task,classes=classes,members=members,predictions=preds,outOfBag=scored(oob,d,task,classes))}\nboost<-function(a){if(option(a,'task','regression')!='regression')stop('regression boosting only');d<-normrows(a$rows,'regression');eligible<-d$weight>0&!is.na(d$y);W<-sum(d$weight[eligible]);if(!W)stop('positive eligible training');eta<-num(option(a,'learningRate','1/2'));stages<-option(a,'stages',3);if(is.null(stages)||stages!=floor(stages)||stages<0||stages>8||eta<0||eta>1)stop('supported rate/stages');initial<-if('initial'%in%names(a))num(a$initial)else sum(d$weight[eligible]*d$y[eligible])/W;train<-matrix(initial,nrow(d),stages+1L);query<-matrix(initial,nrow(a$queries),stages+1L);losses<-fits<-list();for(stage in 0:stages){sse<-sum(d$weight[eligible]*(d$y[eligible]-train[eligible,stage+1L])^2);losses[[stage+1L]]<-list(stage=stage,rawWeightedSSE=sse,MSE=sse/W,meanHalfSquaredLoss=sse/(2*W));if(stage==stages)break;residual<-d;residual$y<-d$y-train[,stage+1L];tree<-fit(residual,a,'regression',character());h<-vapply(seq_len(nrow(d)),function(i)predict_one(tree,d[i,,drop=FALSE])$prediction,0);qh<-vapply(seq_len(nrow(a$queries)),function(i)predict_one(tree,a$queries[i,,drop=FALSE])$prediction,0);stageRows<-lapply(seq_len(nrow(d)),function(i)list(id=d$id[i],before=train[i,stage+1L],residual=residual$y[i],negativeCoordinateDerivative=d$weight[i]*residual$y[i]/W,fit=h[i],addition=eta*h[i],after=train[i,stage+1L]+eta*h[i]));train[,stage+2L]<-train[,stage+1L]+eta*h;query[,stage+2L]<-query[,stage+1L]+eta*qh;norm<-sum(d$weight[eligible]*h[eligible]^2);fits[[stage+1L]]<-list(stage=stage+1L,tree=tree,rows=stageRows,queryFits=qh,norm=norm,predictedSSEDecrease=eta*(2-eta)*norm)};list(task='regression',initial=initial,learningRate=eta,stages=stages,training=train,queries=query,fits=fits,losses=losses,predictions=lapply(seq_len(nrow(a$queries)),function(i)list(id=a$queries$id[i],prediction=query[i,stages+1L],probabilities=numeric(),vote=NA_character_,prob=NA_character_)))}\nfixed_schedules<-function(ids,p,seed){state<-seed;choose<-function(n){limit<-floor(4294967296/n)*n;repeat{state<<-(1664525*state+1013904223)%%4294967296;if(state<limit)return(as.integer(state%%n))}};draws<-schedules<-list();for(member in 1:4){draws[[member]]<-vapply(seq_along(ids),function(i)ids[choose(length(ids))+1L],'');schedule<-setNames(vector('list',7),c('','L','R','LL','LR','RL','RR'));for(path in names(schedule)){order<-seq_len(p)-1L;if(p>1)for(j in seq(p-1L,1L)){k<-choose(j+1L);temp<-order[j+1L];order[j+1L]<-order[k+1L];order[k+1L]<-temp};schedule[[match(path,names(schedule))]]<-sort(order[seq_len(max(1L,floor(sqrt(p))))])};schedules[[member]]<-schedule};list(draws=draws,schedules=schedules)}\nread_sources<-function(src){read<-function(name)read.csv(file.path(src,name),check.names=FALSE,colClasses='character',na.strings=character(),fileEncoding='UTF-8-BOM');raw<-read('actual320-country-four-indicators-original-2020-2024.csv');country<-do.call(rbind,lapply(sort(unique(raw$countryISO3)),function(code)do.call(rbind,lapply(2020:2024,function(year){keys<-c('NY.GDP.PCAP.KD','NY.GDP.MKTP.KD.ZG','FP.CPI.TOTL.ZG','SP.DYN.LE00.IN');v<-vapply(keys,function(k)as.numeric(raw$originalValueToken[raw$countryISO3==code&raw$date==as.character(year)&raw$indicatorID==k]),0);data.frame(id=paste0(code,':',year),sourceRow=paste0(code,':',year),originalID=code,year=year,x0=v[1]/10000,x1=v[2],x2=v[3],y=v[4],weight=1,role=if(anyNA(v))'excluded'else if(year==2024)'outer-test'else'train')}))));raw<-read('actual3613-NLS-original52-fields-and-selection.csv');i<-seq_len(nrow(raw));x0<-suppressWarnings(as.numeric(raw$ed76));x1<-suppressWarnings(as.numeric(raw$age76));y<-suppressWarnings(as.numeric(raw$wage76))/100;person<-data.frame(id=paste0('person:',i),sourceRow=as.character(i),originalID=raw$id,x0=x0,x1=x1,y=y,weight=1,role=ifelse(is.na(x0)|is.na(x1)|is.na(y),'excluded',ifelse(i%%5==0,'outer-test','train')));raw<-read('actual3150-churn-original14-fields-and-selection.csv');i<-seq_len(nrow(raw));company<-data.frame(id=paste0('customer:',i),sourceRow=as.character(i),originalID='',x0=as.numeric(raw[['Call  Failure']]),x1=as.numeric(raw[['Subscription  Length']]),x2=as.numeric(raw[['Charge  Amount']]),y=raw$Churn,weight=1,role=ifelse(i%%5==0,'outer-test','train'));models<-list();for(index in 1:3){kind<-c('country','person','company')[index];d<-list(country,person,company)[[index]];task<-if(kind=='company')'classification'else'regression';s<-fixed_schedules(d$id[d$role=='train'],if(kind=='person')2L else 3L,20261102+7919*(index-1L));models[[kind]]<-list(records=d,task=task,classes=if(task=='classification')c('0','1')else character(),draws=s$draws,schedules=s$schedules,minLeaf=c(4L,50L,30L)[index])};models}\nrealdata<-function(models,kind,options=list()){if(is.null(options)||!is.list(options))stop('options object');m<-models[[kind]];d<-m$records;train<-d[d$role=='train',,drop=FALSE];test<-d[d$role=='outer-test',,drop=FALSE];method<-option(options,'method','forest');depth<-option(options,'maxDepth',2);count<-option(options,'memberCount',3);if(!method%in%c('bagging','forest','boost'))stop('known method');a<-list(rows=train,queries=test,task=m$task,classes=m$classes,maxDepth=depth,minLeaf=option(options,'minLeaf',m$minLeaf),minLeafWeight=0,minGain=0,missingRoute='best',learningRate=option(options,'learningRate','1/2'),stages=option(options,'stages',3));if(method=='boost')result<-boost(a)else{a$bootstrapDraws<-m$draws[seq_len(count)];a$nodeFeatures<-lapply(m$schedules[seq_len(count)],function(s)s[nchar(names(s))<depth]);result<-ensemble(a,method=='forest')};outer<-scored(result$predictions,normrows(test,m$task),m$task,m$classes);st<-stat(normrows(train,m$task),m$task,m$classes);constant<-list(prediction=st$pred,probabilities=st$p,vote=st$pred,prob=st$pred);baseline<-scored(lapply(test$id,function(id)c(list(id=id),constant)),normrows(test,m$task),m$task,m$classes);list(kind=kind,method=method,settings=a,train=train,test=test,result=result,outer=outer,baseline=baseline)}\nAPI<-\"aggregate\"\nINPUT<-list(task=\"classification\",classes=c(\"0\",\"1\"),members=list(list(id=\"0\",predictions=data.frame(id=c(\"q\"),label=c(\"0\"),p0=c(0.51),p1=c(0.49),stringsAsFactors=FALSE)),list(id=\"1\",predictions=data.frame(id=c(\"q\"),label=c(\"0\"),p0=c(0.51),p1=c(0.49),stringsAsFactors=FALSE)),list(id=\"2\",predictions=data.frame(id=c(\"q\"),label=c(\"1\"),p0=c(0),p1=c(1),stringsAsFactors=FALSE))),aggregation=\"probabilities\")\n\nrun_fixed<-function(api,a,out,src){\n r<-if(api=='variance')variance(a)else if(api=='aggregate')aggregate(a)else if(api%in%c('bagging','forest'))ensemble(a,api=='forest')else if(api=='boost')boost(a)else realdata(read_sources(src),a$kind)\n dir.create(out,recursive=TRUE,showWarnings=FALSE);summary<-list();points<-list();add<-function(x,y,s){if(!is.null(y)&&!is.na(y))points[[length(points)+1L]]<<-data.frame(x=x,y=as.numeric(y),series=s)}\n if(api=='variance'){summary<-r[c('B','varianceOfMean')];add(r$B,r$varianceOfMean,'Specified finite-B variance');xl<-'Number of members B';yl<-'Variance, stipulated units squared';title<-'Declared covariance model, not fitted trees'\n }else if(api=='aggregate'){p<-r$predictions[[1]];summary<-list(selectedPrediction=p$prediction);classification<-identical(a$task,'classification');if(classification){summary<-c(summary,list(voteLabel=p$vote,probabilityLabel=p$prob,meanProbability1=p$probabilities[2]));add(1,p$probabilities[2],'Mean probability of class 1');add(2,p$votes[2],'Label-vote share of class 1');xl<-'Aggregation (1=probability, 2=vote)';yl<-'Probability or vote share'}else{for(i in seq_along(a$members))add(i,num(a$members[[i]]$predictions$value[1]),'Member prediction');add(3,p$prediction,'Weighted mean');xl<-'Member 1, member 2, aggregate 3';yl<-'Prediction, assumed units'};title<-'Votes and probabilities are distinct objects'\n }else if(api%in%c('bagging','forest')){summary<-list(queryPrediction=r$predictions[[1]]$prediction,OOB.scoreable=r$outOfBag$eligibleRows,OOB.meanLoss=r$outOfBag$meanLoss);for(i in seq_len(nrow(a$rows)))add(i,a$rows$y[i],'Observed training outcome');for(i in seq_along(r$outOfBag$rows))add(i,r$outOfBag$rows[[i]]$prediction,'OOB prediction, when defined');xl<-'Original training ID order';yl<-'Outcome, assumed units';title<-'Repeated draws and ID-level OOB membership'\n }else if(api=='boost'){summary<-list(initial=r$initial,finalMSE=r$losses[[length(r$losses)]]$MSE,stages=r$stages);for(v in r$losses)add(v$stage,v$MSE,'Training MSE');xl<-'Boosting stage (0=initial)';yl<-'Weighted MSE, outcome units squared';title<-'Training descent does not certify held-out gain'\n }else{summary<-list(outer.scoreable=r$outer$eligibleRows,outer.meanLoss=r$outer$meanLoss,baseline.meanLoss=r$baseline$meanLoss,OOB.scoreable=r$result$outOfBag$eligibleRows,OOB.meanLoss=r$result$outOfBag$meanLoss);for(i in seq_along(r$outer$rows)){p<-r$outer$rows[[i]];add(i,as.numeric(p$actual),'Observed outcome');add(i,if(a$kind=='company')p$probabilities[2]else p$prediction,if(a$kind=='company')'Forest probability of class 1'else'Forest prediction')};xl<-'Outer-test source order, not a time path';yl<-if(a$kind=='company')'Churn label / probability'else if(a$kind=='country')'Period life expectancy, years'else'Nominal 1976 USD per hour';title<-'Fixed forest; outer labels did not fit the trees'}\n display<-function(v)if(is.null(v)||is.na(v))'undefined'else sprintf('%.9f',as.numeric(v));write.csv(data.frame(metric=names(summary),value=vapply(summary,display,'')),file.path(out,'summary.csv'),row.names=FALSE);pp<-do.call(rbind,points);write.csv(pp,file.path(out,'plot-points.csv'),row.names=FALSE);dput(r,file.path(out,'full-result.Rtext'));svg(file.path(out,'plot.svg'),width=5.6,height=4.6,pointsize=14);par(mar=c(5.8,5.8,5.3,1.2),mgp=c(3.7,1,0));xr<-range(pp$x);yr<-range(pp$y);if(diff(xr)==0)xr<-xr+c(-.5,.5);if(diff(yr)==0)yr<-yr+c(-.5,.5);plot(xr,yr,type='n',xlab=xl,ylab=yl,cex.lab=.78,axes=FALSE);axis(1,at=pretty(xr,3));axis(2,at=pretty(yr,4),las=1,cex.axis=.82);box();grid(col='#dddddd');cols<-c('#355c72','#a55336','#507956','#78568b');ss<-unique(pp$series);for(i in seq_along(ss)){v<-pp[pp$series==ss[i],];points(v$x,v$y,pch=16,cex=if(nrow(v)>100).35 else .85,col=adjustcolor(cols[i],if(nrow(v)>100).5 else 1))};legend('topleft',legend=ss,col=cols[seq_along(ss)],lty=0,pch=16,cex=.65,bty='n',inset=c(0,-.32),xpd=NA);mtext(title,side=3,line=3.9,cex=.6);dev.off();cat(paste(names(summary),vapply(summary,display,''),sep='=',collapse=', '),'\\n')\n}\nargs<-commandArgs(trailingOnly=TRUE)\ntryCatch(run_fixed(API,INPUT,if(length(args))args[1]else'fixed-results',if(length(args)>1)args[2]else'ml09-sources'),error=function(e){cat('Rejected declared input: ',conditionMessage(e),'\\n',file=stderr());quit(status=2)})\n",
        "inputFiles": [],
        "input": {
          "task": "classification",
          "classes": [
            "0",
            "1"
          ],
          "members": [
            {
              "id": "0",
              "predictions": [
                {
                  "id": "q",
                  "label": "0",
                  "probabilities": [
                    0.51,
                    0.49
                  ]
                }
              ]
            },
            {
              "id": "1",
              "predictions": [
                {
                  "id": "q",
                  "label": "0",
                  "probabilities": [
                    0.51,
                    0.49
                  ]
                }
              ]
            },
            {
              "id": "2",
              "predictions": [
                {
                  "id": "q",
                  "label": "1",
                  "probabilities": [
                    0,
                    1
                  ]
                }
              ]
            }
          ],
          "aggregation": "probabilities"
        },
        "returnCode": 0,
        "expectedFailure": false,
        "stdout": "selectedPrediction=1.000000000, voteLabel=0.000000000, probabilityLabel=1.000000000, meanProbability1=0.660000000 \n",
        "stderr": "During startup - Warning messages:\n1: Setting LC_COLLATE=C.UTF-8 failed \n2: Setting LC_CTYPE=C.UTF-8 failed \n3: Setting LC_MONETARY=C.UTF-8 failed \n4: Setting LC_TIME=C.UTF-8 failed \n",
        "summary": {
          "selectedPrediction": "1.000000000",
          "voteLabel": "0.000000000",
          "probabilityLabel": "1.000000000",
          "meanProbability1": "0.660000000"
        },
        "plotPoints": [
          {
            "x": "1",
            "y": "0.66",
            "series": "Mean probability of class 1"
          },
          {
            "x": "2",
            "y": "0.333333333333333",
            "series": "Label-vote share of class 1"
          }
        ],
        "plotFile": "ml09-fixed-results/aggregate-votes-versus-probabilities-r/plot.svg",
        "plotSHA256": "092dbdf75cc5022e673349a3b48cb8027562ede88511cceac1f00b6f13862fa4",
        "files": [
          {
            "file": "ml09-fixed-results/aggregate-votes-versus-probabilities-r/full-result.Rtext",
            "sha256": "0521b5023dc502ece5d9365ffc41395f7244bb01f6aae5f7296d8ceedeec9b10"
          },
          {
            "file": "ml09-fixed-results/aggregate-votes-versus-probabilities-r/plot-points.csv",
            "sha256": "5b5942230684497e234d53120b8772c0b6c85f453f685e4c6f15f84af1cb77c6"
          },
          {
            "file": "ml09-fixed-results/aggregate-votes-versus-probabilities-r/plot.svg",
            "sha256": "092dbdf75cc5022e673349a3b48cb8027562ede88511cceac1f00b6f13862fa4"
          },
          {
            "file": "ml09-fixed-results/aggregate-votes-versus-probabilities-r/summary.csv",
            "sha256": "72d36efc84591c75414e068346a028ba66cd4b78d45e8bc9e1ac91979aaf44df"
          }
        ],
        "scope": "Actually executed self-contained fixed example; current web controls execute separately. Python Fraction and finite-precision base R. Author gate, not independent peer."
      }
    }
  },
  "bagging": {
    "python": {
      "repeated-occurrences": {
        "api": "bagging",
        "variant": "repeated-occurrences",
        "language": "python",
        "codeFile": "ml09-code/bagging-repeated-occurrences.py",
        "codeSHA256": "1725d7dbbb5f7b1eaa734a264c07d5843dcae95b514733776bf697c40d54af8d",
        "codeText": "\"\"\"ML09 exact Fraction reproduction from native source fields.\n\npython ml09-public-analysis.py --source-dir ml09-sources --output-dir results\n\nThis authored educational implementation uses direct-centered leaf losses and\nexhaustive midpoint partitions. It reads no JS engine, model contract, checker,\nstored target answers or derived-result CSV. Its five tree arithmetic helpers\nwere copied from the author's own separate Fraction reference, not an independent\npeer. Parser/work budgets and display rounding of the production JS are separate.\nNumerical predictions/proper scores do not certify causal effects, calibration,\nIID OOB validity, survey representativeness or production parameter optimality.\n\"\"\"\nfrom pathlib import Path\nfrom fractions import Fraction as Q\nimport csv,json,math,itertools,argparse\n\ndef normalized(rows,task='regression'):\n return [dict(id=r.get('id',i),x=[None if x is None else Q(x)for x in r.get('x',[])],y=None if r['y']is None else str(r['y'])if task=='classification'else Q(r['y']),w=Q(r.get('weight',1)))for i,r in enumerate(rows)]\n\ndef totals(rows,task,classes):\n W=sum((r['w']for r in rows),Q());mu=sum((r['w']*r['y']for r in rows),Q())/W if task=='regression'and W else None\n probs=[sum((r['w']for r in rows if r['y']==c),Q())/W for c in classes]if task=='classification'and W else[]\n risk=sum((r['w']*(r['y']-mu)**2 for r in rows),Q())if task=='regression'and W else W*sum((p*(1-p)for p in probs),Q())\n return dict(n=len(rows),w=W,mu=mu,p=probs,risk=risk,pred=mu if task=='regression'else classes[max(range(len(probs)),key=lambda i:probs[i])]if probs else None)\n\ndef fit(rows,a,task,classes,schedule=None):\n good=[r for r in rows if r['w']>0 and r['y']is not None];root=totals(good,task,classes)['w'];depth=a.get('maxDepth',2);minimum=a.get('minLeaf',1);minmass=Q(a.get('minLeafWeight',0));mingain=Q(a.get('minGain',0));route=a.get('missingRoute','best')\n def build(rr,d,path):\n  st=totals(rr,task,classes);n=dict(rows=rr,st=st,split=None,left=None,right=None,path=path)\n  if d==depth:return n\n  best=None\n  for j in range(len(rr[0]['x'])):\n   if schedule is not None and j not in schedule[path]:continue\n   values=sorted({r['x'][j]for r in rr if r['x'][j]is not None});missing=[r for r in rr if r['x'][j]is None];observed=[r for r in rr if r['x'][j]is not None]\n   candidates=[]\n   for lo,hi in zip(values,values[1:]):\n    q=(lo+hi)/2;left=[r for r in observed if r['x'][j]<=q];right=[r for r in observed if r['x'][j]>q];directions=[route]if route!='best'else['left','right']if missing else['left'if len(left)>=len(right)else'right']\n    for direction in directions:candidates.append(('threshold',q,direction,left+missing if direction=='left'else left,right+missing if direction=='right'else right))\n   if missing and observed:candidates.append(('missing-only',None,'left',missing,observed))\n   for kind,q,direction,left,right in candidates:\n    l=totals(left,task,classes);r=totals(right,task,classes)\n    if min(l['n'],r['n'])<minimum or min(l['w'],r['w'])<minmass or min(l['w'],r['w'])<=0:continue\n    gain=(st['risk']-l['risk']-r['risk'])/root\n    if best is None or gain>best['gain']:best=dict(feature=j,kind=kind,threshold=q,missingRoute=direction,left=left,right=right,gain=gain)\n  if best and best['gain']>0 and best['gain']>mingain:\n   j=best['feature'];go=lambda r:r['x'][j]is None if best['kind']=='missing-only'else best['missingRoute']=='left'if r['x'][j]is None else r['x'][j]<=best['threshold'];n['split']=best;n['left']=build([r for r in rr if go(r)],d+1,path+'L');n['right']=build([r for r in rr if not go(r)],d+1,path+'R')\n  return n\n return build(good,0,'')\n\ndef predict(tree,x):\n n=tree\n while n['split']:\n  s=n['split'];v=x[s['feature']];left=v is None if s['kind']=='missing-only'else s['missingRoute']=='left'if v is None else v<=s['threshold'];n=n['left'if left else'right']\n return dict(prediction=n['st']['pred'],probabilities=n['st']['p'])\n\ndef combine(preds,w,task,classes,mode='probabilities'):\n mass=sum(w,Q())\n if not preds or not mass:return dict(prediction=None,probabilities=[],vote=None,prob=None)\n if task=='regression':return dict(prediction=sum((p['prediction']*v for p,v in zip(preds,w)),Q())/mass,probabilities=[],vote=None,prob=None)\n votes=[sum((v for p,v in zip(preds,w)if p['prediction']==c),Q())/mass for c in classes];ps=[sum((p['probabilities'][j]*v for p,v in zip(preds,w)),Q())/mass for j in range(len(classes))];vote=classes[max(range(len(classes)),key=lambda j:votes[j])];prob=classes[max(range(len(classes)),key=lambda j:ps[j])];return dict(prediction=vote if mode=='votes'else prob,probabilities=ps,vote=vote,prob=prob,votes=votes)\ndef number(v):\n if v is None or isinstance(v,bool):raise ValueError('explicit null/bool is not a numeric parameter')\n return Q(v)\ndef variance(a):\n B=a['B'];v=number(a['marginalVariance']);rho=number(a.get('rho',0))\n if not isinstance(B,int)or isinstance(B,bool)or B<1 or v<0:raise ValueError('positive integer B/nonnegative variance')\n if B>1 and v and not -Q(1,B-1)<=rho<=1:raise ValueError('equicorrelation PSD bound')\n return dict(B=B,marginalVariance=v,correlationApplicable=B>1 and bool(v),varianceOfMean=v if B==1 else v*(1+(B-1)*rho)/B)\ndef aggregate(a):\n task=a.get('task','regression');classes=[str(c)for c in a.get('classes',[])];members=a['members'];w=[number(v)for v in a.get('memberWeights',[1]*len(members))]\n if not members or min(w)<0 or sum(w)<=0:raise ValueError('nonnegative member weights/positive total')\n order=[p.get('id',i)for i,p in enumerate(members[0]['predictions'])];keys=lambda x:(type(x).__name__,x);lookup=[{keys(p.get('id',i)):p for i,p in enumerate(m['predictions'])}for m in members]\n if any(set(m)!={keys(v)for v in order}for m in lookup):raise ValueError('same query ID set')\n out=[]\n for pid in order:\n  predictions=[dict(prediction=number(m[keys(pid)]['value']),probabilities=[])if task=='regression'else dict(prediction=str(m[keys(pid)]['label']),probabilities=[number(v)for v in m[keys(pid)]['probabilities']])for m in lookup]\n  if task=='classification'and any(min(p['probabilities'])<0 or sum(p['probabilities'])!=1 for p in predictions):raise ValueError('probability simplex')\n  out.append(dict(id=pid,**combine(predictions,w,task,classes,a.get('aggregation','probabilities'))))\n return dict(task=task,classes=classes,predictions=out)\ndef scored(preds,rows,task,classes):\n mass=loss=absolute=errors=voteerrors=Q();out=[]\n for p,r in zip(preds,rows):\n  ok=p['prediction']is not None and r['y']is not None and r['w']>0;v=None\n  if ok:\n   mass+=r['w']\n   if task=='regression':e=r['y']-p['prediction'];v=e*e;absolute+=r['w']*abs(e)\n   else:v=sum(((q-(1 if r['y']==c else 0))**2 for c,q in zip(classes,p['probabilities'])),Q());errors+=r['w']*(p['prediction']!=r['y']);voteerrors+=r['w']*(p['vote']!=r['y'])\n   loss+=r['w']*v\n  out.append(dict(p,actual=r['y'],weight=r['w'],scoreEligible=ok,loss=v))\n return dict(rows=out,eligibleRows=sum(r['scoreEligible']for r in out),weight=mass,totalLoss=loss,meanLoss=loss/mass if mass else None,MAE=absolute/mass if mass and task=='regression'else None,errorRate=errors/mass if mass and task=='classification'else None,labelVoteErrorRate=voteerrors/mass if mass and task=='classification'else None)\ndef ensemble(a,forest=False):\n task=a.get('task','regression');classes=[str(v)for v in(a.get('classes')or[])];rr=normalized(a['rows'],task);key=lambda x:(type(x).__name__,x);lookup={key(r['id']):r for r in rr};weights=[number(v)for v in a.get('memberWeights',[1]*len(a['bootstrapDraws']))]\n if not any(r['w']>0 and r['y']is not None for r in rr)or min(weights)<0 or sum(weights)<=0:raise ValueError('positive eligible training and member weight')\n members=[]\n for i,draw in enumerate(a['bootstrapDraws']):\n  data=[lookup[key(v)]for v in draw];schedule=a['nodeFeatures'][i]if forest else None;model=fit(data,a,task,classes,schedule);inbag={key(v)for v in draw};members.append(dict(tree=model,draw=draw,inbag=inbag,weight=weights[i]))\n predictions=[]\n for q in a.get('queries',[]):predictions.append(dict(id=q['id'],**combine([predict(m['tree'],[None if v is None else number(v)for v in q['x']])for m in members],weights,task,classes,a.get('aggregation','probabilities'))))\n oob=[]\n for r in rr:\n  applicable=[i for i,m in enumerate(members)if key(r['id'])not in m['inbag']];p=combine([predict(members[i]['tree'],r['x'])for i in applicable],[weights[i]for i in applicable],task,classes,a.get('aggregation','probabilities'));oob.append(dict(id=r['id'],applicable=applicable,positiveMembers=sum(weights[i]>0 for i in applicable),**p))\n return dict(task=task,classes=classes,members=members,predictions=predictions,outOfBag=scored(oob,rr,task,classes))\ndef boost(a):\n if a.get('task','regression')!='regression':raise ValueError('regression boosting only')\n rr=normalized(a['rows']);good=[r for r in rr if r['w']and r['y']is not None];W=sum((r['w']for r in good),Q())\n if not W:raise ValueError('positive eligible training')\n eta=number(a.get('learningRate','1/2'));stages=a.get('stages',3)\n if not 0<=eta<=1 or not isinstance(stages,int)or isinstance(stages,bool)or not 0<=stages<=8:raise ValueError('supported rate/stages')\n initial=number(a['initial'])if'initial'in a else sum((r['w']*r['y']for r in good),Q())/W;training=[[initial]for r in rr];queries=[[initial]for q in a.get('queries',[])];fits=[];losses=[]\n for stage in range(stages+1):\n  sse=sum((r['w']*(r['y']-p[-1])**2 for r,p in zip(rr,training)if r['w']and r['y']is not None),Q());losses.append(dict(stage=stage,rawWeightedSSE=sse,MSE=sse/W,meanHalfSquaredLoss=sse/(2*W)))\n  if stage==stages:break\n  residuals=[dict(r,y=None if r['y']is None else r['y']-p[-1])for r,p in zip(rr,training)];tree=fit(residuals,a,'regression',[]);h=[predict(tree,r['x'])['prediction']for r in rr];qh=[predict(tree,[None if v is None else number(v)for v in q['x']])['prediction']for q in a.get('queries',[])];norm=sum((r['w']*v*v for r,v in zip(rr,h)if r['y']is not None),Q());stageRows=[]\n  for i,(r,p)in enumerate(zip(rr,training)):\n   residual=None if r['y']is None else r['y']-p[-1];stageRows.append(dict(id=r['id'],before=p[-1],residual=residual,negativeCoordinateDerivative=None if residual is None else r['w']*residual/W,fit=h[i],addition=eta*h[i],after=p[-1]+eta*h[i]));p.append(p[-1]+eta*h[i])\n  for p,v in zip(queries,qh):p.append(p[-1]+eta*v)\n  fits.append(dict(stage=stage+1,tree=tree,rows=stageRows,queryFits=qh,norm=norm,predictedSSEDecrease=eta*(2-eta)*norm))\n return dict(task='regression',initial=initial,learningRate=eta,stages=stages,training=training,queries=queries,fits=fits,losses=losses,predictions=[dict(id=q['id'],prediction=p[-1],probabilities=[],vote=None,prob=None)for q,p in zip(a.get('queries',[]),queries)])\nclass Stream:\n def __init__(self,state):self.state=state\n def choose(self,n):\n  limit=(1<<32)-((1<<32)%n)\n  while True:\n   self.state=(1664525*self.state+1013904223)&0xffffffff\n   if self.state<limit:return self.state%n\ndef fixed_schedules(ids,p,seed):\n stream=Stream(seed);draws=[];schedules=[];paths=['']+[p for d in[1,2]for p in map(''.join,itertools.product('LR',repeat=d))]\n for member in range(4):\n  draws.append([ids[stream.choose(len(ids))]for _ in range(len(ids))]);schedule={}\n  for path in paths:\n   order=list(range(p))\n   for j in range(p-1,0,-1):k=stream.choose(j+1);order[j],order[k]=order[k],order[j]\n   schedule[path]=sorted(order[:max(1,int(math.sqrt(p)))])\n  schedules.append(schedule)\n return draws,schedules\ndef csvread(file):\n with Path(file).open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))\ndef read_sources(source):\n source=Path(source);raw=csvread(source/'actual320-country-four-indicators-original-2020-2024.csv');lookup={(r['countryISO3'],int(r['date']),r['indicatorID']):r for r in raw};country=[]\n for code in sorted({r['countryISO3']for r in raw}):\n  for year in range(2020,2025):\n   cols=['NY.GDP.PCAP.KD','NY.GDP.MKTP.KD.ZG','FP.CPI.TOTL.ZG','SP.DYN.LE00.IN'];v=[lookup[code,year,k]['originalValueToken']for k in cols];x=[None if not z else Q(z)for z in v[:3]];x[0]=None if x[0]is None else x[0]/10000;y=None if not v[3]else Q(v[3]);eligible=y is not None and None not in x;country.append(dict(id=code+':'+str(year),sourceRow=code+':'+str(year),originalID=code,year=year,x=x,y=y,weight='1',role='excluded'if not eligible else'outer-test'if year==2024 else'train'))\n person=[]\n for i,r in enumerate(csvread(source/'actual3613-NLS-original52-fields-and-selection.csv'),1):\n  v=lambda k:None if r[k]=='.'else Q(r[k]);x=[v('ed76'),v('age76')];y=None if v('wage76')is None else v('wage76')/100;eligible=y is not None and None not in x;person.append(dict(id='person:'+str(i),sourceRow=str(i),originalID=r['id'],x=x,y=y,weight='1',role='excluded'if not eligible else'outer-test'if i%5==0 else'train'))\n company=[]\n for i,r in enumerate(csvread(source/'actual3150-churn-original14-fields-and-selection.csv'),1):company.append(dict(id='customer:'+str(i),sourceRow=str(i),originalID='',x=[Q(r[k])for k in['Call  Failure','Subscription  Length','Charge  Amount']],y=r['Churn'],weight='1',role='outer-test'if i%5==0 else'train'))\n models={}\n for index,(kind,rr,task,leaf)in enumerate([('country',country,'regression',4),('person',person,'regression',50),('company',company,'classification',30)]):\n  ids=[r['id']for r in rr if r['role']=='train'];draws,schedules=fixed_schedules(ids,len(rr[0]['x']),20261102+7919*index);models[kind]=dict(records=rr,task=task,classes=['0','1']if task=='classification'else[],draws=draws,schedules=schedules,minLeaf=leaf)\n return models\n_OMITTED=object()\ndef realdata(models,kind,options=_OMITTED):\n options={}if options is _OMITTED else options\n if not isinstance(options,dict):raise ValueError('options object required, not explicit null')\n m=models[kind];train=[r for r in m['records']if r['role']=='train'];test=[r for r in m['records']if r['role']=='outer-test'];method=options.get('method','forest');depth=options.get('maxDepth',2);count=options.get('memberCount',3);a=dict(rows=train,queries=[dict(id=r['id'],x=r['x'])for r in test],task=m['task'],classes=m['classes'],maxDepth=depth,minLeaf=options.get('minLeaf',m['minLeaf']),minLeafWeight='0',minGain='0',missingRoute='best',learningRate=options.get('learningRate','1/2'),stages=options.get('stages',3))\n if method not in ['bagging','forest','boost']:raise ValueError('known source method')\n if not isinstance(depth,int)or isinstance(depth,bool)or not 0<=depth<=3:raise ValueError('source depth0..3')\n if method!='boost'and(not isinstance(count,int)or isinstance(count,bool)or not 1<=count<=4):raise ValueError('source member count1..4')\n if method=='boost':result=boost(a)\n else:\n  a.update(bootstrapDraws=m['draws'][:count],nodeFeatures=[{p:v for p,v in s.items()if len(p)<depth}for s in m['schedules'][:count]]);result=ensemble(a,method=='forest')\n outer=scored(result['predictions'],normalized(test,m['task']),m['task'],m['classes']);st=totals([r for r in normalized(train,m['task'])if r['w']and r['y']is not None],m['task'],m['classes']);constant=dict(prediction=st['pred'],probabilities=st['p'],vote=st['pred'],prob=st['pred']);baseline=scored([dict(id=r['id'],**constant)for r in test],normalized(test,m['task']),m['task'],m['classes']);return dict(kind=kind,method=method,settings=a,train=train,test=test,result=result,outer=outer,baseline=baseline)\ndef serial(x):\n if isinstance(x,Q):return str(x)\n if isinstance(x,dict):return{k:serial(v)for k,v in x.items()if k not in['inbag','tree']}\n if isinstance(x,(list,tuple)):return[serial(v)for v in x]\n return x\ndef writecsv(file,heads,rows):\n with Path(file).open('w',encoding='utf8',newline='')as f:\n  w=csv.writer(f);w.writerow(heads);w.writerows([[''if v is None else str(v)for v in r]for r in rows])\nAPI='bagging'\nINPUT={'rows': [{'id': 'a', 'x': [0, 0], 'y': 0}, {'id': 'b', 'x': [1, 1], 'y': 1}, {'id': 'c', 'x': [2, 0], 'y': 3}, {'id': 'd', 'x': [3, 1], 'y': 4}], 'queries': [{'id': 'q', 'x': ['3/2', 0]}], 'bootstrapDraws': [['a', 'a', 'b', 'c'], ['b', 'c', 'd', 'd']], 'maxDepth': 2}\n\ndef run_fixed(api,a,out,src):\n import matplotlib\n matplotlib.use('svg')\n import matplotlib.pyplot as plt\n from matplotlib.ticker import MaxNLocator\n plt.rcParams.update({'font.size':14,'svg.fonttype':'none','svg.hashsalt':'ml09-fixed-v1'})\n result=variance(a)if api=='variance'else aggregate(a)if api=='aggregate'else ensemble(a,api=='forest')if api in ['bagging','forest']else boost(a)if api=='boost'else realdata(read_sources(src),a['kind'])\n out=Path(out);out.mkdir(parents=True,exist_ok=True);summary={};points=[]\n def add(x,y,s):\n  if y is not None:points.append([x,y,s])\n if api=='variance':\n  summary={'B':result['B'],'varianceOfMean':result['varianceOfMean']};add(result['B'],result['varianceOfMean'],'Specified finite-B variance');xl='Number of members B';yl='Variance, stipulated units squared';title='Declared covariance model, not fitted trees'\n elif api=='aggregate':\n  p=result['predictions'][0];classification=a.get('task')=='classification';summary={'selectedPrediction':p['prediction']}\n  if classification:\n   summary.update(voteLabel=p['vote'],probabilityLabel=p['prob'],meanProbability1=p['probabilities'][1]);add(1,p['probabilities'][1],'Mean probability of class 1');add(2,p['votes'][1],'Label-vote share of class 1');xl='Aggregation (1=probability, 2=vote)';yl='Probability or vote share'\n  else:\n   for i,m in enumerate(a['members']):add(i+1,Q(m['predictions'][0]['value']),'Member prediction')\n   add(3,p['prediction'],'Weighted mean');xl='Member 1, member 2, aggregate 3';yl='Prediction, assumed units'\n  title='Votes and probabilities are distinct objects'\n elif api in ['bagging','forest']:\n  summary={'queryPrediction':result['predictions'][0]['prediction'],'OOB.scoreable':result['outOfBag']['eligibleRows'],'OOB.meanLoss':result['outOfBag']['meanLoss']}\n  for i,r in enumerate(a['rows']):add(i+1,Q(r['y']),'Observed training outcome')\n  for i,p in enumerate(result['outOfBag']['rows']):add(i+1,p['prediction'],'OOB prediction, when defined')\n  xl='Original training ID order';yl='Outcome, assumed units';title='Repeated draws and ID-level OOB membership'\n elif api=='boost':\n  summary={'initial':result['initial'],'finalMSE':result['losses'][-1]['MSE'],'stages':result['stages']}\n  for r in result['losses']:add(r['stage'],r['MSE'],'Training MSE')\n  xl='Boosting stage (0=initial)';yl='Weighted MSE, outcome units squared';title='Training descent does not certify held-out gain'\n else:\n  summary={'outer.scoreable':result['outer']['eligibleRows'],'outer.meanLoss':result['outer']['meanLoss'],'baseline.meanLoss':result['baseline']['meanLoss'],'OOB.scoreable':result['result']['outOfBag']['eligibleRows'],'OOB.meanLoss':result['result']['outOfBag']['meanLoss']}\n  for i,p in enumerate(result['outer']['rows']):\n   add(i+1,Q(p['actual']),'Observed outcome');add(i+1,p['probabilities'][1]if a['kind']=='company'else p['prediction'],'Forest probability of class 1'if a['kind']=='company'else'Forest prediction')\n  xl='Outer-test source order, not a time path';yl='Churn label / probability'if a['kind']=='company'else'Period life expectancy, years'if a['kind']=='country'else'Nominal 1976 USD per hour';title='Fixed forest; outer labels did not fit the trees'\n def display(v):return 'undefined'if v is None else format(float(v),'.9f')\n writecsv(out/'summary.csv',['metric','value'],[[k,display(v)]for k,v in summary.items()]);writecsv(out/'plot-points.csv',['x','y','series'],points);(out/'full.json').write_text(json.dumps(serial(result),indent=2)+'\\n',encoding='utf8')\n fig,ax=plt.subplots(figsize=(5.6,4.6));fig.subplots_adjust(left=.24,right=.96,bottom=.24,top=.76);colors=['#355c72','#a55336','#507956','#78568b']\n for i,s in enumerate(dict.fromkeys(p[2]for p in points)):\n  pp=[p for p in points if p[2]==s];ax.scatter([float(p[0])for p in pp],[float(p[1])for p in pp],s=12 if len(pp)>100 else 32,alpha=.5 if len(pp)>100 else 1,color=colors[i%4],label=s)\n ax.set_xlabel(xl,labelpad=10,fontsize=11);ax.set_ylabel(yl,labelpad=10,fontsize=11);ax.xaxis.set_major_locator(MaxNLocator(3));ax.yaxis.set_major_locator(MaxNLocator(4));ax.grid(alpha=.18);ax.legend(loc='lower left',bbox_to_anchor=(0,1.01),fontsize=9,frameon=False);fig.suptitle(title,fontsize=9,y=.99);fig.savefig(out/'plot.svg',metadata={'Date':None});plt.close(fig);print(', '.join(k+'='+display(v)for k,v in summary.items()))\nif __name__=='__main__':\n import sys\n try:run_fixed(API,INPUT,sys.argv[1]if len(sys.argv)>1 else'fixed-results',sys.argv[2]if len(sys.argv)>2 else'ml09-sources')\n except ValueError as error:print('Rejected declared input: '+str(error),file=sys.stderr);sys.exit(2)\n",
        "code": "\"\"\"ML09 exact Fraction reproduction from native source fields.\n\npython ml09-public-analysis.py --source-dir ml09-sources --output-dir results\n\nThis authored educational implementation uses direct-centered leaf losses and\nexhaustive midpoint partitions. It reads no JS engine, model contract, checker,\nstored target answers or derived-result CSV. Its five tree arithmetic helpers\nwere copied from the author's own separate Fraction reference, not an independent\npeer. Parser/work budgets and display rounding of the production JS are separate.\nNumerical predictions/proper scores do not certify causal effects, calibration,\nIID OOB validity, survey representativeness or production parameter optimality.\n\"\"\"\nfrom pathlib import Path\nfrom fractions import Fraction as Q\nimport csv,json,math,itertools,argparse\n\ndef normalized(rows,task='regression'):\n return [dict(id=r.get('id',i),x=[None if x is None else Q(x)for x in r.get('x',[])],y=None if r['y']is None else str(r['y'])if task=='classification'else Q(r['y']),w=Q(r.get('weight',1)))for i,r in enumerate(rows)]\n\ndef totals(rows,task,classes):\n W=sum((r['w']for r in rows),Q());mu=sum((r['w']*r['y']for r in rows),Q())/W if task=='regression'and W else None\n probs=[sum((r['w']for r in rows if r['y']==c),Q())/W for c in classes]if task=='classification'and W else[]\n risk=sum((r['w']*(r['y']-mu)**2 for r in rows),Q())if task=='regression'and W else W*sum((p*(1-p)for p in probs),Q())\n return dict(n=len(rows),w=W,mu=mu,p=probs,risk=risk,pred=mu if task=='regression'else classes[max(range(len(probs)),key=lambda i:probs[i])]if probs else None)\n\ndef fit(rows,a,task,classes,schedule=None):\n good=[r for r in rows if r['w']>0 and r['y']is not None];root=totals(good,task,classes)['w'];depth=a.get('maxDepth',2);minimum=a.get('minLeaf',1);minmass=Q(a.get('minLeafWeight',0));mingain=Q(a.get('minGain',0));route=a.get('missingRoute','best')\n def build(rr,d,path):\n  st=totals(rr,task,classes);n=dict(rows=rr,st=st,split=None,left=None,right=None,path=path)\n  if d==depth:return n\n  best=None\n  for j in range(len(rr[0]['x'])):\n   if schedule is not None and j not in schedule[path]:continue\n   values=sorted({r['x'][j]for r in rr if r['x'][j]is not None});missing=[r for r in rr if r['x'][j]is None];observed=[r for r in rr if r['x'][j]is not None]\n   candidates=[]\n   for lo,hi in zip(values,values[1:]):\n    q=(lo+hi)/2;left=[r for r in observed if r['x'][j]<=q];right=[r for r in observed if r['x'][j]>q];directions=[route]if route!='best'else['left','right']if missing else['left'if len(left)>=len(right)else'right']\n    for direction in directions:candidates.append(('threshold',q,direction,left+missing if direction=='left'else left,right+missing if direction=='right'else right))\n   if missing and observed:candidates.append(('missing-only',None,'left',missing,observed))\n   for kind,q,direction,left,right in candidates:\n    l=totals(left,task,classes);r=totals(right,task,classes)\n    if min(l['n'],r['n'])<minimum or min(l['w'],r['w'])<minmass or min(l['w'],r['w'])<=0:continue\n    gain=(st['risk']-l['risk']-r['risk'])/root\n    if best is None or gain>best['gain']:best=dict(feature=j,kind=kind,threshold=q,missingRoute=direction,left=left,right=right,gain=gain)\n  if best and best['gain']>0 and best['gain']>mingain:\n   j=best['feature'];go=lambda r:r['x'][j]is None if best['kind']=='missing-only'else best['missingRoute']=='left'if r['x'][j]is None else r['x'][j]<=best['threshold'];n['split']=best;n['left']=build([r for r in rr if go(r)],d+1,path+'L');n['right']=build([r for r in rr if not go(r)],d+1,path+'R')\n  return n\n return build(good,0,'')\n\ndef predict(tree,x):\n n=tree\n while n['split']:\n  s=n['split'];v=x[s['feature']];left=v is None if s['kind']=='missing-only'else s['missingRoute']=='left'if v is None else v<=s['threshold'];n=n['left'if left else'right']\n return dict(prediction=n['st']['pred'],probabilities=n['st']['p'])\n\ndef combine(preds,w,task,classes,mode='probabilities'):\n mass=sum(w,Q())\n if not preds or not mass:return dict(prediction=None,probabilities=[],vote=None,prob=None)\n if task=='regression':return dict(prediction=sum((p['prediction']*v for p,v in zip(preds,w)),Q())/mass,probabilities=[],vote=None,prob=None)\n votes=[sum((v for p,v in zip(preds,w)if p['prediction']==c),Q())/mass for c in classes];ps=[sum((p['probabilities'][j]*v for p,v in zip(preds,w)),Q())/mass for j in range(len(classes))];vote=classes[max(range(len(classes)),key=lambda j:votes[j])];prob=classes[max(range(len(classes)),key=lambda j:ps[j])];return dict(prediction=vote if mode=='votes'else prob,probabilities=ps,vote=vote,prob=prob,votes=votes)\ndef number(v):\n if v is None or isinstance(v,bool):raise ValueError('explicit null/bool is not a numeric parameter')\n return Q(v)\ndef variance(a):\n B=a['B'];v=number(a['marginalVariance']);rho=number(a.get('rho',0))\n if not isinstance(B,int)or isinstance(B,bool)or B<1 or v<0:raise ValueError('positive integer B/nonnegative variance')\n if B>1 and v and not -Q(1,B-1)<=rho<=1:raise ValueError('equicorrelation PSD bound')\n return dict(B=B,marginalVariance=v,correlationApplicable=B>1 and bool(v),varianceOfMean=v if B==1 else v*(1+(B-1)*rho)/B)\ndef aggregate(a):\n task=a.get('task','regression');classes=[str(c)for c in a.get('classes',[])];members=a['members'];w=[number(v)for v in a.get('memberWeights',[1]*len(members))]\n if not members or min(w)<0 or sum(w)<=0:raise ValueError('nonnegative member weights/positive total')\n order=[p.get('id',i)for i,p in enumerate(members[0]['predictions'])];keys=lambda x:(type(x).__name__,x);lookup=[{keys(p.get('id',i)):p for i,p in enumerate(m['predictions'])}for m in members]\n if any(set(m)!={keys(v)for v in order}for m in lookup):raise ValueError('same query ID set')\n out=[]\n for pid in order:\n  predictions=[dict(prediction=number(m[keys(pid)]['value']),probabilities=[])if task=='regression'else dict(prediction=str(m[keys(pid)]['label']),probabilities=[number(v)for v in m[keys(pid)]['probabilities']])for m in lookup]\n  if task=='classification'and any(min(p['probabilities'])<0 or sum(p['probabilities'])!=1 for p in predictions):raise ValueError('probability simplex')\n  out.append(dict(id=pid,**combine(predictions,w,task,classes,a.get('aggregation','probabilities'))))\n return dict(task=task,classes=classes,predictions=out)\ndef scored(preds,rows,task,classes):\n mass=loss=absolute=errors=voteerrors=Q();out=[]\n for p,r in zip(preds,rows):\n  ok=p['prediction']is not None and r['y']is not None and r['w']>0;v=None\n  if ok:\n   mass+=r['w']\n   if task=='regression':e=r['y']-p['prediction'];v=e*e;absolute+=r['w']*abs(e)\n   else:v=sum(((q-(1 if r['y']==c else 0))**2 for c,q in zip(classes,p['probabilities'])),Q());errors+=r['w']*(p['prediction']!=r['y']);voteerrors+=r['w']*(p['vote']!=r['y'])\n   loss+=r['w']*v\n  out.append(dict(p,actual=r['y'],weight=r['w'],scoreEligible=ok,loss=v))\n return dict(rows=out,eligibleRows=sum(r['scoreEligible']for r in out),weight=mass,totalLoss=loss,meanLoss=loss/mass if mass else None,MAE=absolute/mass if mass and task=='regression'else None,errorRate=errors/mass if mass and task=='classification'else None,labelVoteErrorRate=voteerrors/mass if mass and task=='classification'else None)\ndef ensemble(a,forest=False):\n task=a.get('task','regression');classes=[str(v)for v in(a.get('classes')or[])];rr=normalized(a['rows'],task);key=lambda x:(type(x).__name__,x);lookup={key(r['id']):r for r in rr};weights=[number(v)for v in a.get('memberWeights',[1]*len(a['bootstrapDraws']))]\n if not any(r['w']>0 and r['y']is not None for r in rr)or min(weights)<0 or sum(weights)<=0:raise ValueError('positive eligible training and member weight')\n members=[]\n for i,draw in enumerate(a['bootstrapDraws']):\n  data=[lookup[key(v)]for v in draw];schedule=a['nodeFeatures'][i]if forest else None;model=fit(data,a,task,classes,schedule);inbag={key(v)for v in draw};members.append(dict(tree=model,draw=draw,inbag=inbag,weight=weights[i]))\n predictions=[]\n for q in a.get('queries',[]):predictions.append(dict(id=q['id'],**combine([predict(m['tree'],[None if v is None else number(v)for v in q['x']])for m in members],weights,task,classes,a.get('aggregation','probabilities'))))\n oob=[]\n for r in rr:\n  applicable=[i for i,m in enumerate(members)if key(r['id'])not in m['inbag']];p=combine([predict(members[i]['tree'],r['x'])for i in applicable],[weights[i]for i in applicable],task,classes,a.get('aggregation','probabilities'));oob.append(dict(id=r['id'],applicable=applicable,positiveMembers=sum(weights[i]>0 for i in applicable),**p))\n return dict(task=task,classes=classes,members=members,predictions=predictions,outOfBag=scored(oob,rr,task,classes))\ndef boost(a):\n if a.get('task','regression')!='regression':raise ValueError('regression boosting only')\n rr=normalized(a['rows']);good=[r for r in rr if r['w']and r['y']is not None];W=sum((r['w']for r in good),Q())\n if not W:raise ValueError('positive eligible training')\n eta=number(a.get('learningRate','1/2'));stages=a.get('stages',3)\n if not 0<=eta<=1 or not isinstance(stages,int)or isinstance(stages,bool)or not 0<=stages<=8:raise ValueError('supported rate/stages')\n initial=number(a['initial'])if'initial'in a else sum((r['w']*r['y']for r in good),Q())/W;training=[[initial]for r in rr];queries=[[initial]for q in a.get('queries',[])];fits=[];losses=[]\n for stage in range(stages+1):\n  sse=sum((r['w']*(r['y']-p[-1])**2 for r,p in zip(rr,training)if r['w']and r['y']is not None),Q());losses.append(dict(stage=stage,rawWeightedSSE=sse,MSE=sse/W,meanHalfSquaredLoss=sse/(2*W)))\n  if stage==stages:break\n  residuals=[dict(r,y=None if r['y']is None else r['y']-p[-1])for r,p in zip(rr,training)];tree=fit(residuals,a,'regression',[]);h=[predict(tree,r['x'])['prediction']for r in rr];qh=[predict(tree,[None if v is None else number(v)for v in q['x']])['prediction']for q in a.get('queries',[])];norm=sum((r['w']*v*v for r,v in zip(rr,h)if r['y']is not None),Q());stageRows=[]\n  for i,(r,p)in enumerate(zip(rr,training)):\n   residual=None if r['y']is None else r['y']-p[-1];stageRows.append(dict(id=r['id'],before=p[-1],residual=residual,negativeCoordinateDerivative=None if residual is None else r['w']*residual/W,fit=h[i],addition=eta*h[i],after=p[-1]+eta*h[i]));p.append(p[-1]+eta*h[i])\n  for p,v in zip(queries,qh):p.append(p[-1]+eta*v)\n  fits.append(dict(stage=stage+1,tree=tree,rows=stageRows,queryFits=qh,norm=norm,predictedSSEDecrease=eta*(2-eta)*norm))\n return dict(task='regression',initial=initial,learningRate=eta,stages=stages,training=training,queries=queries,fits=fits,losses=losses,predictions=[dict(id=q['id'],prediction=p[-1],probabilities=[],vote=None,prob=None)for q,p in zip(a.get('queries',[]),queries)])\nclass Stream:\n def __init__(self,state):self.state=state\n def choose(self,n):\n  limit=(1<<32)-((1<<32)%n)\n  while True:\n   self.state=(1664525*self.state+1013904223)&0xffffffff\n   if self.state<limit:return self.state%n\ndef fixed_schedules(ids,p,seed):\n stream=Stream(seed);draws=[];schedules=[];paths=['']+[p for d in[1,2]for p in map(''.join,itertools.product('LR',repeat=d))]\n for member in range(4):\n  draws.append([ids[stream.choose(len(ids))]for _ in range(len(ids))]);schedule={}\n  for path in paths:\n   order=list(range(p))\n   for j in range(p-1,0,-1):k=stream.choose(j+1);order[j],order[k]=order[k],order[j]\n   schedule[path]=sorted(order[:max(1,int(math.sqrt(p)))])\n  schedules.append(schedule)\n return draws,schedules\ndef csvread(file):\n with Path(file).open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))\ndef read_sources(source):\n source=Path(source);raw=csvread(source/'actual320-country-four-indicators-original-2020-2024.csv');lookup={(r['countryISO3'],int(r['date']),r['indicatorID']):r for r in raw};country=[]\n for code in sorted({r['countryISO3']for r in raw}):\n  for year in range(2020,2025):\n   cols=['NY.GDP.PCAP.KD','NY.GDP.MKTP.KD.ZG','FP.CPI.TOTL.ZG','SP.DYN.LE00.IN'];v=[lookup[code,year,k]['originalValueToken']for k in cols];x=[None if not z else Q(z)for z in v[:3]];x[0]=None if x[0]is None else x[0]/10000;y=None if not v[3]else Q(v[3]);eligible=y is not None and None not in x;country.append(dict(id=code+':'+str(year),sourceRow=code+':'+str(year),originalID=code,year=year,x=x,y=y,weight='1',role='excluded'if not eligible else'outer-test'if year==2024 else'train'))\n person=[]\n for i,r in enumerate(csvread(source/'actual3613-NLS-original52-fields-and-selection.csv'),1):\n  v=lambda k:None if r[k]=='.'else Q(r[k]);x=[v('ed76'),v('age76')];y=None if v('wage76')is None else v('wage76')/100;eligible=y is not None and None not in x;person.append(dict(id='person:'+str(i),sourceRow=str(i),originalID=r['id'],x=x,y=y,weight='1',role='excluded'if not eligible else'outer-test'if i%5==0 else'train'))\n company=[]\n for i,r in enumerate(csvread(source/'actual3150-churn-original14-fields-and-selection.csv'),1):company.append(dict(id='customer:'+str(i),sourceRow=str(i),originalID='',x=[Q(r[k])for k in['Call  Failure','Subscription  Length','Charge  Amount']],y=r['Churn'],weight='1',role='outer-test'if i%5==0 else'train'))\n models={}\n for index,(kind,rr,task,leaf)in enumerate([('country',country,'regression',4),('person',person,'regression',50),('company',company,'classification',30)]):\n  ids=[r['id']for r in rr if r['role']=='train'];draws,schedules=fixed_schedules(ids,len(rr[0]['x']),20261102+7919*index);models[kind]=dict(records=rr,task=task,classes=['0','1']if task=='classification'else[],draws=draws,schedules=schedules,minLeaf=leaf)\n return models\n_OMITTED=object()\ndef realdata(models,kind,options=_OMITTED):\n options={}if options is _OMITTED else options\n if not isinstance(options,dict):raise ValueError('options object required, not explicit null')\n m=models[kind];train=[r for r in m['records']if r['role']=='train'];test=[r for r in m['records']if r['role']=='outer-test'];method=options.get('method','forest');depth=options.get('maxDepth',2);count=options.get('memberCount',3);a=dict(rows=train,queries=[dict(id=r['id'],x=r['x'])for r in test],task=m['task'],classes=m['classes'],maxDepth=depth,minLeaf=options.get('minLeaf',m['minLeaf']),minLeafWeight='0',minGain='0',missingRoute='best',learningRate=options.get('learningRate','1/2'),stages=options.get('stages',3))\n if method not in ['bagging','forest','boost']:raise ValueError('known source method')\n if not isinstance(depth,int)or isinstance(depth,bool)or not 0<=depth<=3:raise ValueError('source depth0..3')\n if method!='boost'and(not isinstance(count,int)or isinstance(count,bool)or not 1<=count<=4):raise ValueError('source member count1..4')\n if method=='boost':result=boost(a)\n else:\n  a.update(bootstrapDraws=m['draws'][:count],nodeFeatures=[{p:v for p,v in s.items()if len(p)<depth}for s in m['schedules'][:count]]);result=ensemble(a,method=='forest')\n outer=scored(result['predictions'],normalized(test,m['task']),m['task'],m['classes']);st=totals([r for r in normalized(train,m['task'])if r['w']and r['y']is not None],m['task'],m['classes']);constant=dict(prediction=st['pred'],probabilities=st['p'],vote=st['pred'],prob=st['pred']);baseline=scored([dict(id=r['id'],**constant)for r in test],normalized(test,m['task']),m['task'],m['classes']);return dict(kind=kind,method=method,settings=a,train=train,test=test,result=result,outer=outer,baseline=baseline)\ndef serial(x):\n if isinstance(x,Q):return str(x)\n if isinstance(x,dict):return{k:serial(v)for k,v in x.items()if k not in['inbag','tree']}\n if isinstance(x,(list,tuple)):return[serial(v)for v in x]\n return x\ndef writecsv(file,heads,rows):\n with Path(file).open('w',encoding='utf8',newline='')as f:\n  w=csv.writer(f);w.writerow(heads);w.writerows([[''if v is None else str(v)for v in r]for r in rows])\nAPI='bagging'\nINPUT={'rows': [{'id': 'a', 'x': [0, 0], 'y': 0}, {'id': 'b', 'x': [1, 1], 'y': 1}, {'id': 'c', 'x': [2, 0], 'y': 3}, {'id': 'd', 'x': [3, 1], 'y': 4}], 'queries': [{'id': 'q', 'x': ['3/2', 0]}], 'bootstrapDraws': [['a', 'a', 'b', 'c'], ['b', 'c', 'd', 'd']], 'maxDepth': 2}\n\ndef run_fixed(api,a,out,src):\n import matplotlib\n matplotlib.use('svg')\n import matplotlib.pyplot as plt\n from matplotlib.ticker import MaxNLocator\n plt.rcParams.update({'font.size':14,'svg.fonttype':'none','svg.hashsalt':'ml09-fixed-v1'})\n result=variance(a)if api=='variance'else aggregate(a)if api=='aggregate'else ensemble(a,api=='forest')if api in ['bagging','forest']else boost(a)if api=='boost'else realdata(read_sources(src),a['kind'])\n out=Path(out);out.mkdir(parents=True,exist_ok=True);summary={};points=[]\n def add(x,y,s):\n  if y is not None:points.append([x,y,s])\n if api=='variance':\n  summary={'B':result['B'],'varianceOfMean':result['varianceOfMean']};add(result['B'],result['varianceOfMean'],'Specified finite-B variance');xl='Number of members B';yl='Variance, stipulated units squared';title='Declared covariance model, not fitted trees'\n elif api=='aggregate':\n  p=result['predictions'][0];classification=a.get('task')=='classification';summary={'selectedPrediction':p['prediction']}\n  if classification:\n   summary.update(voteLabel=p['vote'],probabilityLabel=p['prob'],meanProbability1=p['probabilities'][1]);add(1,p['probabilities'][1],'Mean probability of class 1');add(2,p['votes'][1],'Label-vote share of class 1');xl='Aggregation (1=probability, 2=vote)';yl='Probability or vote share'\n  else:\n   for i,m in enumerate(a['members']):add(i+1,Q(m['predictions'][0]['value']),'Member prediction')\n   add(3,p['prediction'],'Weighted mean');xl='Member 1, member 2, aggregate 3';yl='Prediction, assumed units'\n  title='Votes and probabilities are distinct objects'\n elif api in ['bagging','forest']:\n  summary={'queryPrediction':result['predictions'][0]['prediction'],'OOB.scoreable':result['outOfBag']['eligibleRows'],'OOB.meanLoss':result['outOfBag']['meanLoss']}\n  for i,r in enumerate(a['rows']):add(i+1,Q(r['y']),'Observed training outcome')\n  for i,p in enumerate(result['outOfBag']['rows']):add(i+1,p['prediction'],'OOB prediction, when defined')\n  xl='Original training ID order';yl='Outcome, assumed units';title='Repeated draws and ID-level OOB membership'\n elif api=='boost':\n  summary={'initial':result['initial'],'finalMSE':result['losses'][-1]['MSE'],'stages':result['stages']}\n  for r in result['losses']:add(r['stage'],r['MSE'],'Training MSE')\n  xl='Boosting stage (0=initial)';yl='Weighted MSE, outcome units squared';title='Training descent does not certify held-out gain'\n else:\n  summary={'outer.scoreable':result['outer']['eligibleRows'],'outer.meanLoss':result['outer']['meanLoss'],'baseline.meanLoss':result['baseline']['meanLoss'],'OOB.scoreable':result['result']['outOfBag']['eligibleRows'],'OOB.meanLoss':result['result']['outOfBag']['meanLoss']}\n  for i,p in enumerate(result['outer']['rows']):\n   add(i+1,Q(p['actual']),'Observed outcome');add(i+1,p['probabilities'][1]if a['kind']=='company'else p['prediction'],'Forest probability of class 1'if a['kind']=='company'else'Forest prediction')\n  xl='Outer-test source order, not a time path';yl='Churn label / probability'if a['kind']=='company'else'Period life expectancy, years'if a['kind']=='country'else'Nominal 1976 USD per hour';title='Fixed forest; outer labels did not fit the trees'\n def display(v):return 'undefined'if v is None else format(float(v),'.9f')\n writecsv(out/'summary.csv',['metric','value'],[[k,display(v)]for k,v in summary.items()]);writecsv(out/'plot-points.csv',['x','y','series'],points);(out/'full.json').write_text(json.dumps(serial(result),indent=2)+'\\n',encoding='utf8')\n fig,ax=plt.subplots(figsize=(5.6,4.6));fig.subplots_adjust(left=.24,right=.96,bottom=.24,top=.76);colors=['#355c72','#a55336','#507956','#78568b']\n for i,s in enumerate(dict.fromkeys(p[2]for p in points)):\n  pp=[p for p in points if p[2]==s];ax.scatter([float(p[0])for p in pp],[float(p[1])for p in pp],s=12 if len(pp)>100 else 32,alpha=.5 if len(pp)>100 else 1,color=colors[i%4],label=s)\n ax.set_xlabel(xl,labelpad=10,fontsize=11);ax.set_ylabel(yl,labelpad=10,fontsize=11);ax.xaxis.set_major_locator(MaxNLocator(3));ax.yaxis.set_major_locator(MaxNLocator(4));ax.grid(alpha=.18);ax.legend(loc='lower left',bbox_to_anchor=(0,1.01),fontsize=9,frameon=False);fig.suptitle(title,fontsize=9,y=.99);fig.savefig(out/'plot.svg',metadata={'Date':None});plt.close(fig);print(', '.join(k+'='+display(v)for k,v in summary.items()))\nif __name__=='__main__':\n import sys\n try:run_fixed(API,INPUT,sys.argv[1]if len(sys.argv)>1 else'fixed-results',sys.argv[2]if len(sys.argv)>2 else'ml09-sources')\n except ValueError as error:print('Rejected declared input: '+str(error),file=sys.stderr);sys.exit(2)\n",
        "inputFiles": [],
        "input": {
          "rows": [
            {
              "id": "a",
              "x": [
                0,
                0
              ],
              "y": 0
            },
            {
              "id": "b",
              "x": [
                1,
                1
              ],
              "y": 1
            },
            {
              "id": "c",
              "x": [
                2,
                0
              ],
              "y": 3
            },
            {
              "id": "d",
              "x": [
                3,
                1
              ],
              "y": 4
            }
          ],
          "queries": [
            {
              "id": "q",
              "x": [
                "3/2",
                0
              ]
            }
          ],
          "bootstrapDraws": [
            [
              "a",
              "a",
              "b",
              "c"
            ],
            [
              "b",
              "c",
              "d",
              "d"
            ]
          ],
          "maxDepth": 2
        },
        "returnCode": 0,
        "expectedFailure": false,
        "stdout": "queryPrediction=1.000000000, OOB.scoreable=2.000000000, OOB.meanLoss=1.000000000\n",
        "stderr": "",
        "summary": {
          "queryPrediction": "1.000000000",
          "OOB.scoreable": "2.000000000",
          "OOB.meanLoss": "1.000000000"
        },
        "plotPoints": [
          {
            "x": "1",
            "y": "0",
            "series": "Observed training outcome"
          },
          {
            "x": "2",
            "y": "1",
            "series": "Observed training outcome"
          },
          {
            "x": "3",
            "y": "3",
            "series": "Observed training outcome"
          },
          {
            "x": "4",
            "y": "4",
            "series": "Observed training outcome"
          },
          {
            "x": "1",
            "y": "1",
            "series": "OOB prediction, when defined"
          },
          {
            "x": "4",
            "y": "3",
            "series": "OOB prediction, when defined"
          }
        ],
        "plotFile": "ml09-fixed-results/bagging-repeated-occurrences-python/plot.svg",
        "plotSHA256": "65605f5b31eed5e80830941bf2a8344a0619cf52c2149cd6cf29f607223b9327",
        "files": [
          {
            "file": "ml09-fixed-results/bagging-repeated-occurrences-python/full.json",
            "sha256": "be2bff1776f1d7b13d9e4ce251502e3d88cdb42231c97dd9256d83a601b6f853"
          },
          {
            "file": "ml09-fixed-results/bagging-repeated-occurrences-python/plot-points.csv",
            "sha256": "ac560064c75d39eee5a72d203eadecdb69683865bfdc27f22b65afd5158a9391"
          },
          {
            "file": "ml09-fixed-results/bagging-repeated-occurrences-python/plot.svg",
            "sha256": "65605f5b31eed5e80830941bf2a8344a0619cf52c2149cd6cf29f607223b9327"
          },
          {
            "file": "ml09-fixed-results/bagging-repeated-occurrences-python/summary.csv",
            "sha256": "fa04040821930458fa52f31153e0112be640e0abbc1731899e3c046b08fac943"
          }
        ],
        "scope": "Actually executed self-contained fixed example; current web controls execute separately. Python Fraction and finite-precision base R. Author gate, not independent peer."
      },
      "no-OOB-members": {
        "api": "bagging",
        "variant": "no-OOB-members",
        "language": "python",
        "codeFile": "ml09-code/bagging-no-OOB-members.py",
        "codeSHA256": "e1d86c3217fa954981b4fa3586e4808d0c7c27e64b1aff4fad297be9f44a28d3",
        "codeText": "\"\"\"ML09 exact Fraction reproduction from native source fields.\n\npython ml09-public-analysis.py --source-dir ml09-sources --output-dir results\n\nThis authored educational implementation uses direct-centered leaf losses and\nexhaustive midpoint partitions. It reads no JS engine, model contract, checker,\nstored target answers or derived-result CSV. Its five tree arithmetic helpers\nwere copied from the author's own separate Fraction reference, not an independent\npeer. Parser/work budgets and display rounding of the production JS are separate.\nNumerical predictions/proper scores do not certify causal effects, calibration,\nIID OOB validity, survey representativeness or production parameter optimality.\n\"\"\"\nfrom pathlib import Path\nfrom fractions import Fraction as Q\nimport csv,json,math,itertools,argparse\n\ndef normalized(rows,task='regression'):\n return [dict(id=r.get('id',i),x=[None if x is None else Q(x)for x in r.get('x',[])],y=None if r['y']is None else str(r['y'])if task=='classification'else Q(r['y']),w=Q(r.get('weight',1)))for i,r in enumerate(rows)]\n\ndef totals(rows,task,classes):\n W=sum((r['w']for r in rows),Q());mu=sum((r['w']*r['y']for r in rows),Q())/W if task=='regression'and W else None\n probs=[sum((r['w']for r in rows if r['y']==c),Q())/W for c in classes]if task=='classification'and W else[]\n risk=sum((r['w']*(r['y']-mu)**2 for r in rows),Q())if task=='regression'and W else W*sum((p*(1-p)for p in probs),Q())\n return dict(n=len(rows),w=W,mu=mu,p=probs,risk=risk,pred=mu if task=='regression'else classes[max(range(len(probs)),key=lambda i:probs[i])]if probs else None)\n\ndef fit(rows,a,task,classes,schedule=None):\n good=[r for r in rows if r['w']>0 and r['y']is not None];root=totals(good,task,classes)['w'];depth=a.get('maxDepth',2);minimum=a.get('minLeaf',1);minmass=Q(a.get('minLeafWeight',0));mingain=Q(a.get('minGain',0));route=a.get('missingRoute','best')\n def build(rr,d,path):\n  st=totals(rr,task,classes);n=dict(rows=rr,st=st,split=None,left=None,right=None,path=path)\n  if d==depth:return n\n  best=None\n  for j in range(len(rr[0]['x'])):\n   if schedule is not None and j not in schedule[path]:continue\n   values=sorted({r['x'][j]for r in rr if r['x'][j]is not None});missing=[r for r in rr if r['x'][j]is None];observed=[r for r in rr if r['x'][j]is not None]\n   candidates=[]\n   for lo,hi in zip(values,values[1:]):\n    q=(lo+hi)/2;left=[r for r in observed if r['x'][j]<=q];right=[r for r in observed if r['x'][j]>q];directions=[route]if route!='best'else['left','right']if missing else['left'if len(left)>=len(right)else'right']\n    for direction in directions:candidates.append(('threshold',q,direction,left+missing if direction=='left'else left,right+missing if direction=='right'else right))\n   if missing and observed:candidates.append(('missing-only',None,'left',missing,observed))\n   for kind,q,direction,left,right in candidates:\n    l=totals(left,task,classes);r=totals(right,task,classes)\n    if min(l['n'],r['n'])<minimum or min(l['w'],r['w'])<minmass or min(l['w'],r['w'])<=0:continue\n    gain=(st['risk']-l['risk']-r['risk'])/root\n    if best is None or gain>best['gain']:best=dict(feature=j,kind=kind,threshold=q,missingRoute=direction,left=left,right=right,gain=gain)\n  if best and best['gain']>0 and best['gain']>mingain:\n   j=best['feature'];go=lambda r:r['x'][j]is None if best['kind']=='missing-only'else best['missingRoute']=='left'if r['x'][j]is None else r['x'][j]<=best['threshold'];n['split']=best;n['left']=build([r for r in rr if go(r)],d+1,path+'L');n['right']=build([r for r in rr if not go(r)],d+1,path+'R')\n  return n\n return build(good,0,'')\n\ndef predict(tree,x):\n n=tree\n while n['split']:\n  s=n['split'];v=x[s['feature']];left=v is None if s['kind']=='missing-only'else s['missingRoute']=='left'if v is None else v<=s['threshold'];n=n['left'if left else'right']\n return dict(prediction=n['st']['pred'],probabilities=n['st']['p'])\n\ndef combine(preds,w,task,classes,mode='probabilities'):\n mass=sum(w,Q())\n if not preds or not mass:return dict(prediction=None,probabilities=[],vote=None,prob=None)\n if task=='regression':return dict(prediction=sum((p['prediction']*v for p,v in zip(preds,w)),Q())/mass,probabilities=[],vote=None,prob=None)\n votes=[sum((v for p,v in zip(preds,w)if p['prediction']==c),Q())/mass for c in classes];ps=[sum((p['probabilities'][j]*v for p,v in zip(preds,w)),Q())/mass for j in range(len(classes))];vote=classes[max(range(len(classes)),key=lambda j:votes[j])];prob=classes[max(range(len(classes)),key=lambda j:ps[j])];return dict(prediction=vote if mode=='votes'else prob,probabilities=ps,vote=vote,prob=prob,votes=votes)\ndef number(v):\n if v is None or isinstance(v,bool):raise ValueError('explicit null/bool is not a numeric parameter')\n return Q(v)\ndef variance(a):\n B=a['B'];v=number(a['marginalVariance']);rho=number(a.get('rho',0))\n if not isinstance(B,int)or isinstance(B,bool)or B<1 or v<0:raise ValueError('positive integer B/nonnegative variance')\n if B>1 and v and not -Q(1,B-1)<=rho<=1:raise ValueError('equicorrelation PSD bound')\n return dict(B=B,marginalVariance=v,correlationApplicable=B>1 and bool(v),varianceOfMean=v if B==1 else v*(1+(B-1)*rho)/B)\ndef aggregate(a):\n task=a.get('task','regression');classes=[str(c)for c in a.get('classes',[])];members=a['members'];w=[number(v)for v in a.get('memberWeights',[1]*len(members))]\n if not members or min(w)<0 or sum(w)<=0:raise ValueError('nonnegative member weights/positive total')\n order=[p.get('id',i)for i,p in enumerate(members[0]['predictions'])];keys=lambda x:(type(x).__name__,x);lookup=[{keys(p.get('id',i)):p for i,p in enumerate(m['predictions'])}for m in members]\n if any(set(m)!={keys(v)for v in order}for m in lookup):raise ValueError('same query ID set')\n out=[]\n for pid in order:\n  predictions=[dict(prediction=number(m[keys(pid)]['value']),probabilities=[])if task=='regression'else dict(prediction=str(m[keys(pid)]['label']),probabilities=[number(v)for v in m[keys(pid)]['probabilities']])for m in lookup]\n  if task=='classification'and any(min(p['probabilities'])<0 or sum(p['probabilities'])!=1 for p in predictions):raise ValueError('probability simplex')\n  out.append(dict(id=pid,**combine(predictions,w,task,classes,a.get('aggregation','probabilities'))))\n return dict(task=task,classes=classes,predictions=out)\ndef scored(preds,rows,task,classes):\n mass=loss=absolute=errors=voteerrors=Q();out=[]\n for p,r in zip(preds,rows):\n  ok=p['prediction']is not None and r['y']is not None and r['w']>0;v=None\n  if ok:\n   mass+=r['w']\n   if task=='regression':e=r['y']-p['prediction'];v=e*e;absolute+=r['w']*abs(e)\n   else:v=sum(((q-(1 if r['y']==c else 0))**2 for c,q in zip(classes,p['probabilities'])),Q());errors+=r['w']*(p['prediction']!=r['y']);voteerrors+=r['w']*(p['vote']!=r['y'])\n   loss+=r['w']*v\n  out.append(dict(p,actual=r['y'],weight=r['w'],scoreEligible=ok,loss=v))\n return dict(rows=out,eligibleRows=sum(r['scoreEligible']for r in out),weight=mass,totalLoss=loss,meanLoss=loss/mass if mass else None,MAE=absolute/mass if mass and task=='regression'else None,errorRate=errors/mass if mass and task=='classification'else None,labelVoteErrorRate=voteerrors/mass if mass and task=='classification'else None)\ndef ensemble(a,forest=False):\n task=a.get('task','regression');classes=[str(v)for v in(a.get('classes')or[])];rr=normalized(a['rows'],task);key=lambda x:(type(x).__name__,x);lookup={key(r['id']):r for r in rr};weights=[number(v)for v in a.get('memberWeights',[1]*len(a['bootstrapDraws']))]\n if not any(r['w']>0 and r['y']is not None for r in rr)or min(weights)<0 or sum(weights)<=0:raise ValueError('positive eligible training and member weight')\n members=[]\n for i,draw in enumerate(a['bootstrapDraws']):\n  data=[lookup[key(v)]for v in draw];schedule=a['nodeFeatures'][i]if forest else None;model=fit(data,a,task,classes,schedule);inbag={key(v)for v in draw};members.append(dict(tree=model,draw=draw,inbag=inbag,weight=weights[i]))\n predictions=[]\n for q in a.get('queries',[]):predictions.append(dict(id=q['id'],**combine([predict(m['tree'],[None if v is None else number(v)for v in q['x']])for m in members],weights,task,classes,a.get('aggregation','probabilities'))))\n oob=[]\n for r in rr:\n  applicable=[i for i,m in enumerate(members)if key(r['id'])not in m['inbag']];p=combine([predict(members[i]['tree'],r['x'])for i in applicable],[weights[i]for i in applicable],task,classes,a.get('aggregation','probabilities'));oob.append(dict(id=r['id'],applicable=applicable,positiveMembers=sum(weights[i]>0 for i in applicable),**p))\n return dict(task=task,classes=classes,members=members,predictions=predictions,outOfBag=scored(oob,rr,task,classes))\ndef boost(a):\n if a.get('task','regression')!='regression':raise ValueError('regression boosting only')\n rr=normalized(a['rows']);good=[r for r in rr if r['w']and r['y']is not None];W=sum((r['w']for r in good),Q())\n if not W:raise ValueError('positive eligible training')\n eta=number(a.get('learningRate','1/2'));stages=a.get('stages',3)\n if not 0<=eta<=1 or not isinstance(stages,int)or isinstance(stages,bool)or not 0<=stages<=8:raise ValueError('supported rate/stages')\n initial=number(a['initial'])if'initial'in a else sum((r['w']*r['y']for r in good),Q())/W;training=[[initial]for r in rr];queries=[[initial]for q in a.get('queries',[])];fits=[];losses=[]\n for stage in range(stages+1):\n  sse=sum((r['w']*(r['y']-p[-1])**2 for r,p in zip(rr,training)if r['w']and r['y']is not None),Q());losses.append(dict(stage=stage,rawWeightedSSE=sse,MSE=sse/W,meanHalfSquaredLoss=sse/(2*W)))\n  if stage==stages:break\n  residuals=[dict(r,y=None if r['y']is None else r['y']-p[-1])for r,p in zip(rr,training)];tree=fit(residuals,a,'regression',[]);h=[predict(tree,r['x'])['prediction']for r in rr];qh=[predict(tree,[None if v is None else number(v)for v in q['x']])['prediction']for q in a.get('queries',[])];norm=sum((r['w']*v*v for r,v in zip(rr,h)if r['y']is not None),Q());stageRows=[]\n  for i,(r,p)in enumerate(zip(rr,training)):\n   residual=None if r['y']is None else r['y']-p[-1];stageRows.append(dict(id=r['id'],before=p[-1],residual=residual,negativeCoordinateDerivative=None if residual is None else r['w']*residual/W,fit=h[i],addition=eta*h[i],after=p[-1]+eta*h[i]));p.append(p[-1]+eta*h[i])\n  for p,v in zip(queries,qh):p.append(p[-1]+eta*v)\n  fits.append(dict(stage=stage+1,tree=tree,rows=stageRows,queryFits=qh,norm=norm,predictedSSEDecrease=eta*(2-eta)*norm))\n return dict(task='regression',initial=initial,learningRate=eta,stages=stages,training=training,queries=queries,fits=fits,losses=losses,predictions=[dict(id=q['id'],prediction=p[-1],probabilities=[],vote=None,prob=None)for q,p in zip(a.get('queries',[]),queries)])\nclass Stream:\n def __init__(self,state):self.state=state\n def choose(self,n):\n  limit=(1<<32)-((1<<32)%n)\n  while True:\n   self.state=(1664525*self.state+1013904223)&0xffffffff\n   if self.state<limit:return self.state%n\ndef fixed_schedules(ids,p,seed):\n stream=Stream(seed);draws=[];schedules=[];paths=['']+[p for d in[1,2]for p in map(''.join,itertools.product('LR',repeat=d))]\n for member in range(4):\n  draws.append([ids[stream.choose(len(ids))]for _ in range(len(ids))]);schedule={}\n  for path in paths:\n   order=list(range(p))\n   for j in range(p-1,0,-1):k=stream.choose(j+1);order[j],order[k]=order[k],order[j]\n   schedule[path]=sorted(order[:max(1,int(math.sqrt(p)))])\n  schedules.append(schedule)\n return draws,schedules\ndef csvread(file):\n with Path(file).open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))\ndef read_sources(source):\n source=Path(source);raw=csvread(source/'actual320-country-four-indicators-original-2020-2024.csv');lookup={(r['countryISO3'],int(r['date']),r['indicatorID']):r for r in raw};country=[]\n for code in sorted({r['countryISO3']for r in raw}):\n  for year in range(2020,2025):\n   cols=['NY.GDP.PCAP.KD','NY.GDP.MKTP.KD.ZG','FP.CPI.TOTL.ZG','SP.DYN.LE00.IN'];v=[lookup[code,year,k]['originalValueToken']for k in cols];x=[None if not z else Q(z)for z in v[:3]];x[0]=None if x[0]is None else x[0]/10000;y=None if not v[3]else Q(v[3]);eligible=y is not None and None not in x;country.append(dict(id=code+':'+str(year),sourceRow=code+':'+str(year),originalID=code,year=year,x=x,y=y,weight='1',role='excluded'if not eligible else'outer-test'if year==2024 else'train'))\n person=[]\n for i,r in enumerate(csvread(source/'actual3613-NLS-original52-fields-and-selection.csv'),1):\n  v=lambda k:None if r[k]=='.'else Q(r[k]);x=[v('ed76'),v('age76')];y=None if v('wage76')is None else v('wage76')/100;eligible=y is not None and None not in x;person.append(dict(id='person:'+str(i),sourceRow=str(i),originalID=r['id'],x=x,y=y,weight='1',role='excluded'if not eligible else'outer-test'if i%5==0 else'train'))\n company=[]\n for i,r in enumerate(csvread(source/'actual3150-churn-original14-fields-and-selection.csv'),1):company.append(dict(id='customer:'+str(i),sourceRow=str(i),originalID='',x=[Q(r[k])for k in['Call  Failure','Subscription  Length','Charge  Amount']],y=r['Churn'],weight='1',role='outer-test'if i%5==0 else'train'))\n models={}\n for index,(kind,rr,task,leaf)in enumerate([('country',country,'regression',4),('person',person,'regression',50),('company',company,'classification',30)]):\n  ids=[r['id']for r in rr if r['role']=='train'];draws,schedules=fixed_schedules(ids,len(rr[0]['x']),20261102+7919*index);models[kind]=dict(records=rr,task=task,classes=['0','1']if task=='classification'else[],draws=draws,schedules=schedules,minLeaf=leaf)\n return models\n_OMITTED=object()\ndef realdata(models,kind,options=_OMITTED):\n options={}if options is _OMITTED else options\n if not isinstance(options,dict):raise ValueError('options object required, not explicit null')\n m=models[kind];train=[r for r in m['records']if r['role']=='train'];test=[r for r in m['records']if r['role']=='outer-test'];method=options.get('method','forest');depth=options.get('maxDepth',2);count=options.get('memberCount',3);a=dict(rows=train,queries=[dict(id=r['id'],x=r['x'])for r in test],task=m['task'],classes=m['classes'],maxDepth=depth,minLeaf=options.get('minLeaf',m['minLeaf']),minLeafWeight='0',minGain='0',missingRoute='best',learningRate=options.get('learningRate','1/2'),stages=options.get('stages',3))\n if method not in ['bagging','forest','boost']:raise ValueError('known source method')\n if not isinstance(depth,int)or isinstance(depth,bool)or not 0<=depth<=3:raise ValueError('source depth0..3')\n if method!='boost'and(not isinstance(count,int)or isinstance(count,bool)or not 1<=count<=4):raise ValueError('source member count1..4')\n if method=='boost':result=boost(a)\n else:\n  a.update(bootstrapDraws=m['draws'][:count],nodeFeatures=[{p:v for p,v in s.items()if len(p)<depth}for s in m['schedules'][:count]]);result=ensemble(a,method=='forest')\n outer=scored(result['predictions'],normalized(test,m['task']),m['task'],m['classes']);st=totals([r for r in normalized(train,m['task'])if r['w']and r['y']is not None],m['task'],m['classes']);constant=dict(prediction=st['pred'],probabilities=st['p'],vote=st['pred'],prob=st['pred']);baseline=scored([dict(id=r['id'],**constant)for r in test],normalized(test,m['task']),m['task'],m['classes']);return dict(kind=kind,method=method,settings=a,train=train,test=test,result=result,outer=outer,baseline=baseline)\ndef serial(x):\n if isinstance(x,Q):return str(x)\n if isinstance(x,dict):return{k:serial(v)for k,v in x.items()if k not in['inbag','tree']}\n if isinstance(x,(list,tuple)):return[serial(v)for v in x]\n return x\ndef writecsv(file,heads,rows):\n with Path(file).open('w',encoding='utf8',newline='')as f:\n  w=csv.writer(f);w.writerow(heads);w.writerows([[''if v is None else str(v)for v in r]for r in rows])\nAPI='bagging'\nINPUT={'rows': [{'id': 'a', 'x': [0, 0], 'y': 0}, {'id': 'b', 'x': [1, 1], 'y': 1}, {'id': 'c', 'x': [2, 0], 'y': 3}, {'id': 'd', 'x': [3, 1], 'y': 4}], 'queries': [{'id': 'q', 'x': ['3/2', 0]}], 'bootstrapDraws': [['a', 'b', 'c', 'd'], ['a', 'b', 'c', 'd']], 'maxDepth': 2}\n\ndef run_fixed(api,a,out,src):\n import matplotlib\n matplotlib.use('svg')\n import matplotlib.pyplot as plt\n from matplotlib.ticker import MaxNLocator\n plt.rcParams.update({'font.size':14,'svg.fonttype':'none','svg.hashsalt':'ml09-fixed-v1'})\n result=variance(a)if api=='variance'else aggregate(a)if api=='aggregate'else ensemble(a,api=='forest')if api in ['bagging','forest']else boost(a)if api=='boost'else realdata(read_sources(src),a['kind'])\n out=Path(out);out.mkdir(parents=True,exist_ok=True);summary={};points=[]\n def add(x,y,s):\n  if y is not None:points.append([x,y,s])\n if api=='variance':\n  summary={'B':result['B'],'varianceOfMean':result['varianceOfMean']};add(result['B'],result['varianceOfMean'],'Specified finite-B variance');xl='Number of members B';yl='Variance, stipulated units squared';title='Declared covariance model, not fitted trees'\n elif api=='aggregate':\n  p=result['predictions'][0];classification=a.get('task')=='classification';summary={'selectedPrediction':p['prediction']}\n  if classification:\n   summary.update(voteLabel=p['vote'],probabilityLabel=p['prob'],meanProbability1=p['probabilities'][1]);add(1,p['probabilities'][1],'Mean probability of class 1');add(2,p['votes'][1],'Label-vote share of class 1');xl='Aggregation (1=probability, 2=vote)';yl='Probability or vote share'\n  else:\n   for i,m in enumerate(a['members']):add(i+1,Q(m['predictions'][0]['value']),'Member prediction')\n   add(3,p['prediction'],'Weighted mean');xl='Member 1, member 2, aggregate 3';yl='Prediction, assumed units'\n  title='Votes and probabilities are distinct objects'\n elif api in ['bagging','forest']:\n  summary={'queryPrediction':result['predictions'][0]['prediction'],'OOB.scoreable':result['outOfBag']['eligibleRows'],'OOB.meanLoss':result['outOfBag']['meanLoss']}\n  for i,r in enumerate(a['rows']):add(i+1,Q(r['y']),'Observed training outcome')\n  for i,p in enumerate(result['outOfBag']['rows']):add(i+1,p['prediction'],'OOB prediction, when defined')\n  xl='Original training ID order';yl='Outcome, assumed units';title='Repeated draws and ID-level OOB membership'\n elif api=='boost':\n  summary={'initial':result['initial'],'finalMSE':result['losses'][-1]['MSE'],'stages':result['stages']}\n  for r in result['losses']:add(r['stage'],r['MSE'],'Training MSE')\n  xl='Boosting stage (0=initial)';yl='Weighted MSE, outcome units squared';title='Training descent does not certify held-out gain'\n else:\n  summary={'outer.scoreable':result['outer']['eligibleRows'],'outer.meanLoss':result['outer']['meanLoss'],'baseline.meanLoss':result['baseline']['meanLoss'],'OOB.scoreable':result['result']['outOfBag']['eligibleRows'],'OOB.meanLoss':result['result']['outOfBag']['meanLoss']}\n  for i,p in enumerate(result['outer']['rows']):\n   add(i+1,Q(p['actual']),'Observed outcome');add(i+1,p['probabilities'][1]if a['kind']=='company'else p['prediction'],'Forest probability of class 1'if a['kind']=='company'else'Forest prediction')\n  xl='Outer-test source order, not a time path';yl='Churn label / probability'if a['kind']=='company'else'Period life expectancy, years'if a['kind']=='country'else'Nominal 1976 USD per hour';title='Fixed forest; outer labels did not fit the trees'\n def display(v):return 'undefined'if v is None else format(float(v),'.9f')\n writecsv(out/'summary.csv',['metric','value'],[[k,display(v)]for k,v in summary.items()]);writecsv(out/'plot-points.csv',['x','y','series'],points);(out/'full.json').write_text(json.dumps(serial(result),indent=2)+'\\n',encoding='utf8')\n fig,ax=plt.subplots(figsize=(5.6,4.6));fig.subplots_adjust(left=.24,right=.96,bottom=.24,top=.76);colors=['#355c72','#a55336','#507956','#78568b']\n for i,s in enumerate(dict.fromkeys(p[2]for p in points)):\n  pp=[p for p in points if p[2]==s];ax.scatter([float(p[0])for p in pp],[float(p[1])for p in pp],s=12 if len(pp)>100 else 32,alpha=.5 if len(pp)>100 else 1,color=colors[i%4],label=s)\n ax.set_xlabel(xl,labelpad=10,fontsize=11);ax.set_ylabel(yl,labelpad=10,fontsize=11);ax.xaxis.set_major_locator(MaxNLocator(3));ax.yaxis.set_major_locator(MaxNLocator(4));ax.grid(alpha=.18);ax.legend(loc='lower left',bbox_to_anchor=(0,1.01),fontsize=9,frameon=False);fig.suptitle(title,fontsize=9,y=.99);fig.savefig(out/'plot.svg',metadata={'Date':None});plt.close(fig);print(', '.join(k+'='+display(v)for k,v in summary.items()))\nif __name__=='__main__':\n import sys\n try:run_fixed(API,INPUT,sys.argv[1]if len(sys.argv)>1 else'fixed-results',sys.argv[2]if len(sys.argv)>2 else'ml09-sources')\n except ValueError as error:print('Rejected declared input: '+str(error),file=sys.stderr);sys.exit(2)\n",
        "code": "\"\"\"ML09 exact Fraction reproduction from native source fields.\n\npython ml09-public-analysis.py --source-dir ml09-sources --output-dir results\n\nThis authored educational implementation uses direct-centered leaf losses and\nexhaustive midpoint partitions. It reads no JS engine, model contract, checker,\nstored target answers or derived-result CSV. Its five tree arithmetic helpers\nwere copied from the author's own separate Fraction reference, not an independent\npeer. Parser/work budgets and display rounding of the production JS are separate.\nNumerical predictions/proper scores do not certify causal effects, calibration,\nIID OOB validity, survey representativeness or production parameter optimality.\n\"\"\"\nfrom pathlib import Path\nfrom fractions import Fraction as Q\nimport csv,json,math,itertools,argparse\n\ndef normalized(rows,task='regression'):\n return [dict(id=r.get('id',i),x=[None if x is None else Q(x)for x in r.get('x',[])],y=None if r['y']is None else str(r['y'])if task=='classification'else Q(r['y']),w=Q(r.get('weight',1)))for i,r in enumerate(rows)]\n\ndef totals(rows,task,classes):\n W=sum((r['w']for r in rows),Q());mu=sum((r['w']*r['y']for r in rows),Q())/W if task=='regression'and W else None\n probs=[sum((r['w']for r in rows if r['y']==c),Q())/W for c in classes]if task=='classification'and W else[]\n risk=sum((r['w']*(r['y']-mu)**2 for r in rows),Q())if task=='regression'and W else W*sum((p*(1-p)for p in probs),Q())\n return dict(n=len(rows),w=W,mu=mu,p=probs,risk=risk,pred=mu if task=='regression'else classes[max(range(len(probs)),key=lambda i:probs[i])]if probs else None)\n\ndef fit(rows,a,task,classes,schedule=None):\n good=[r for r in rows if r['w']>0 and r['y']is not None];root=totals(good,task,classes)['w'];depth=a.get('maxDepth',2);minimum=a.get('minLeaf',1);minmass=Q(a.get('minLeafWeight',0));mingain=Q(a.get('minGain',0));route=a.get('missingRoute','best')\n def build(rr,d,path):\n  st=totals(rr,task,classes);n=dict(rows=rr,st=st,split=None,left=None,right=None,path=path)\n  if d==depth:return n\n  best=None\n  for j in range(len(rr[0]['x'])):\n   if schedule is not None and j not in schedule[path]:continue\n   values=sorted({r['x'][j]for r in rr if r['x'][j]is not None});missing=[r for r in rr if r['x'][j]is None];observed=[r for r in rr if r['x'][j]is not None]\n   candidates=[]\n   for lo,hi in zip(values,values[1:]):\n    q=(lo+hi)/2;left=[r for r in observed if r['x'][j]<=q];right=[r for r in observed if r['x'][j]>q];directions=[route]if route!='best'else['left','right']if missing else['left'if len(left)>=len(right)else'right']\n    for direction in directions:candidates.append(('threshold',q,direction,left+missing if direction=='left'else left,right+missing if direction=='right'else right))\n   if missing and observed:candidates.append(('missing-only',None,'left',missing,observed))\n   for kind,q,direction,left,right in candidates:\n    l=totals(left,task,classes);r=totals(right,task,classes)\n    if min(l['n'],r['n'])<minimum or min(l['w'],r['w'])<minmass or min(l['w'],r['w'])<=0:continue\n    gain=(st['risk']-l['risk']-r['risk'])/root\n    if best is None or gain>best['gain']:best=dict(feature=j,kind=kind,threshold=q,missingRoute=direction,left=left,right=right,gain=gain)\n  if best and best['gain']>0 and best['gain']>mingain:\n   j=best['feature'];go=lambda r:r['x'][j]is None if best['kind']=='missing-only'else best['missingRoute']=='left'if r['x'][j]is None else r['x'][j]<=best['threshold'];n['split']=best;n['left']=build([r for r in rr if go(r)],d+1,path+'L');n['right']=build([r for r in rr if not go(r)],d+1,path+'R')\n  return n\n return build(good,0,'')\n\ndef predict(tree,x):\n n=tree\n while n['split']:\n  s=n['split'];v=x[s['feature']];left=v is None if s['kind']=='missing-only'else s['missingRoute']=='left'if v is None else v<=s['threshold'];n=n['left'if left else'right']\n return dict(prediction=n['st']['pred'],probabilities=n['st']['p'])\n\ndef combine(preds,w,task,classes,mode='probabilities'):\n mass=sum(w,Q())\n if not preds or not mass:return dict(prediction=None,probabilities=[],vote=None,prob=None)\n if task=='regression':return dict(prediction=sum((p['prediction']*v for p,v in zip(preds,w)),Q())/mass,probabilities=[],vote=None,prob=None)\n votes=[sum((v for p,v in zip(preds,w)if p['prediction']==c),Q())/mass for c in classes];ps=[sum((p['probabilities'][j]*v for p,v in zip(preds,w)),Q())/mass for j in range(len(classes))];vote=classes[max(range(len(classes)),key=lambda j:votes[j])];prob=classes[max(range(len(classes)),key=lambda j:ps[j])];return dict(prediction=vote if mode=='votes'else prob,probabilities=ps,vote=vote,prob=prob,votes=votes)\ndef number(v):\n if v is None or isinstance(v,bool):raise ValueError('explicit null/bool is not a numeric parameter')\n return Q(v)\ndef variance(a):\n B=a['B'];v=number(a['marginalVariance']);rho=number(a.get('rho',0))\n if not isinstance(B,int)or isinstance(B,bool)or B<1 or v<0:raise ValueError('positive integer B/nonnegative variance')\n if B>1 and v and not -Q(1,B-1)<=rho<=1:raise ValueError('equicorrelation PSD bound')\n return dict(B=B,marginalVariance=v,correlationApplicable=B>1 and bool(v),varianceOfMean=v if B==1 else v*(1+(B-1)*rho)/B)\ndef aggregate(a):\n task=a.get('task','regression');classes=[str(c)for c in a.get('classes',[])];members=a['members'];w=[number(v)for v in a.get('memberWeights',[1]*len(members))]\n if not members or min(w)<0 or sum(w)<=0:raise ValueError('nonnegative member weights/positive total')\n order=[p.get('id',i)for i,p in enumerate(members[0]['predictions'])];keys=lambda x:(type(x).__name__,x);lookup=[{keys(p.get('id',i)):p for i,p in enumerate(m['predictions'])}for m in members]\n if any(set(m)!={keys(v)for v in order}for m in lookup):raise ValueError('same query ID set')\n out=[]\n for pid in order:\n  predictions=[dict(prediction=number(m[keys(pid)]['value']),probabilities=[])if task=='regression'else dict(prediction=str(m[keys(pid)]['label']),probabilities=[number(v)for v in m[keys(pid)]['probabilities']])for m in lookup]\n  if task=='classification'and any(min(p['probabilities'])<0 or sum(p['probabilities'])!=1 for p in predictions):raise ValueError('probability simplex')\n  out.append(dict(id=pid,**combine(predictions,w,task,classes,a.get('aggregation','probabilities'))))\n return dict(task=task,classes=classes,predictions=out)\ndef scored(preds,rows,task,classes):\n mass=loss=absolute=errors=voteerrors=Q();out=[]\n for p,r in zip(preds,rows):\n  ok=p['prediction']is not None and r['y']is not None and r['w']>0;v=None\n  if ok:\n   mass+=r['w']\n   if task=='regression':e=r['y']-p['prediction'];v=e*e;absolute+=r['w']*abs(e)\n   else:v=sum(((q-(1 if r['y']==c else 0))**2 for c,q in zip(classes,p['probabilities'])),Q());errors+=r['w']*(p['prediction']!=r['y']);voteerrors+=r['w']*(p['vote']!=r['y'])\n   loss+=r['w']*v\n  out.append(dict(p,actual=r['y'],weight=r['w'],scoreEligible=ok,loss=v))\n return dict(rows=out,eligibleRows=sum(r['scoreEligible']for r in out),weight=mass,totalLoss=loss,meanLoss=loss/mass if mass else None,MAE=absolute/mass if mass and task=='regression'else None,errorRate=errors/mass if mass and task=='classification'else None,labelVoteErrorRate=voteerrors/mass if mass and task=='classification'else None)\ndef ensemble(a,forest=False):\n task=a.get('task','regression');classes=[str(v)for v in(a.get('classes')or[])];rr=normalized(a['rows'],task);key=lambda x:(type(x).__name__,x);lookup={key(r['id']):r for r in rr};weights=[number(v)for v in a.get('memberWeights',[1]*len(a['bootstrapDraws']))]\n if not any(r['w']>0 and r['y']is not None for r in rr)or min(weights)<0 or sum(weights)<=0:raise ValueError('positive eligible training and member weight')\n members=[]\n for i,draw in enumerate(a['bootstrapDraws']):\n  data=[lookup[key(v)]for v in draw];schedule=a['nodeFeatures'][i]if forest else None;model=fit(data,a,task,classes,schedule);inbag={key(v)for v in draw};members.append(dict(tree=model,draw=draw,inbag=inbag,weight=weights[i]))\n predictions=[]\n for q in a.get('queries',[]):predictions.append(dict(id=q['id'],**combine([predict(m['tree'],[None if v is None else number(v)for v in q['x']])for m in members],weights,task,classes,a.get('aggregation','probabilities'))))\n oob=[]\n for r in rr:\n  applicable=[i for i,m in enumerate(members)if key(r['id'])not in m['inbag']];p=combine([predict(members[i]['tree'],r['x'])for i in applicable],[weights[i]for i in applicable],task,classes,a.get('aggregation','probabilities'));oob.append(dict(id=r['id'],applicable=applicable,positiveMembers=sum(weights[i]>0 for i in applicable),**p))\n return dict(task=task,classes=classes,members=members,predictions=predictions,outOfBag=scored(oob,rr,task,classes))\ndef boost(a):\n if a.get('task','regression')!='regression':raise ValueError('regression boosting only')\n rr=normalized(a['rows']);good=[r for r in rr if r['w']and r['y']is not None];W=sum((r['w']for r in good),Q())\n if not W:raise ValueError('positive eligible training')\n eta=number(a.get('learningRate','1/2'));stages=a.get('stages',3)\n if not 0<=eta<=1 or not isinstance(stages,int)or isinstance(stages,bool)or not 0<=stages<=8:raise ValueError('supported rate/stages')\n initial=number(a['initial'])if'initial'in a else sum((r['w']*r['y']for r in good),Q())/W;training=[[initial]for r in rr];queries=[[initial]for q in a.get('queries',[])];fits=[];losses=[]\n for stage in range(stages+1):\n  sse=sum((r['w']*(r['y']-p[-1])**2 for r,p in zip(rr,training)if r['w']and r['y']is not None),Q());losses.append(dict(stage=stage,rawWeightedSSE=sse,MSE=sse/W,meanHalfSquaredLoss=sse/(2*W)))\n  if stage==stages:break\n  residuals=[dict(r,y=None if r['y']is None else r['y']-p[-1])for r,p in zip(rr,training)];tree=fit(residuals,a,'regression',[]);h=[predict(tree,r['x'])['prediction']for r in rr];qh=[predict(tree,[None if v is None else number(v)for v in q['x']])['prediction']for q in a.get('queries',[])];norm=sum((r['w']*v*v for r,v in zip(rr,h)if r['y']is not None),Q());stageRows=[]\n  for i,(r,p)in enumerate(zip(rr,training)):\n   residual=None if r['y']is None else r['y']-p[-1];stageRows.append(dict(id=r['id'],before=p[-1],residual=residual,negativeCoordinateDerivative=None if residual is None else r['w']*residual/W,fit=h[i],addition=eta*h[i],after=p[-1]+eta*h[i]));p.append(p[-1]+eta*h[i])\n  for p,v in zip(queries,qh):p.append(p[-1]+eta*v)\n  fits.append(dict(stage=stage+1,tree=tree,rows=stageRows,queryFits=qh,norm=norm,predictedSSEDecrease=eta*(2-eta)*norm))\n return dict(task='regression',initial=initial,learningRate=eta,stages=stages,training=training,queries=queries,fits=fits,losses=losses,predictions=[dict(id=q['id'],prediction=p[-1],probabilities=[],vote=None,prob=None)for q,p in zip(a.get('queries',[]),queries)])\nclass Stream:\n def __init__(self,state):self.state=state\n def choose(self,n):\n  limit=(1<<32)-((1<<32)%n)\n  while True:\n   self.state=(1664525*self.state+1013904223)&0xffffffff\n   if self.state<limit:return self.state%n\ndef fixed_schedules(ids,p,seed):\n stream=Stream(seed);draws=[];schedules=[];paths=['']+[p for d in[1,2]for p in map(''.join,itertools.product('LR',repeat=d))]\n for member in range(4):\n  draws.append([ids[stream.choose(len(ids))]for _ in range(len(ids))]);schedule={}\n  for path in paths:\n   order=list(range(p))\n   for j in range(p-1,0,-1):k=stream.choose(j+1);order[j],order[k]=order[k],order[j]\n   schedule[path]=sorted(order[:max(1,int(math.sqrt(p)))])\n  schedules.append(schedule)\n return draws,schedules\ndef csvread(file):\n with Path(file).open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))\ndef read_sources(source):\n source=Path(source);raw=csvread(source/'actual320-country-four-indicators-original-2020-2024.csv');lookup={(r['countryISO3'],int(r['date']),r['indicatorID']):r for r in raw};country=[]\n for code in sorted({r['countryISO3']for r in raw}):\n  for year in range(2020,2025):\n   cols=['NY.GDP.PCAP.KD','NY.GDP.MKTP.KD.ZG','FP.CPI.TOTL.ZG','SP.DYN.LE00.IN'];v=[lookup[code,year,k]['originalValueToken']for k in cols];x=[None if not z else Q(z)for z in v[:3]];x[0]=None if x[0]is None else x[0]/10000;y=None if not v[3]else Q(v[3]);eligible=y is not None and None not in x;country.append(dict(id=code+':'+str(year),sourceRow=code+':'+str(year),originalID=code,year=year,x=x,y=y,weight='1',role='excluded'if not eligible else'outer-test'if year==2024 else'train'))\n person=[]\n for i,r in enumerate(csvread(source/'actual3613-NLS-original52-fields-and-selection.csv'),1):\n  v=lambda k:None if r[k]=='.'else Q(r[k]);x=[v('ed76'),v('age76')];y=None if v('wage76')is None else v('wage76')/100;eligible=y is not None and None not in x;person.append(dict(id='person:'+str(i),sourceRow=str(i),originalID=r['id'],x=x,y=y,weight='1',role='excluded'if not eligible else'outer-test'if i%5==0 else'train'))\n company=[]\n for i,r in enumerate(csvread(source/'actual3150-churn-original14-fields-and-selection.csv'),1):company.append(dict(id='customer:'+str(i),sourceRow=str(i),originalID='',x=[Q(r[k])for k in['Call  Failure','Subscription  Length','Charge  Amount']],y=r['Churn'],weight='1',role='outer-test'if i%5==0 else'train'))\n models={}\n for index,(kind,rr,task,leaf)in enumerate([('country',country,'regression',4),('person',person,'regression',50),('company',company,'classification',30)]):\n  ids=[r['id']for r in rr if r['role']=='train'];draws,schedules=fixed_schedules(ids,len(rr[0]['x']),20261102+7919*index);models[kind]=dict(records=rr,task=task,classes=['0','1']if task=='classification'else[],draws=draws,schedules=schedules,minLeaf=leaf)\n return models\n_OMITTED=object()\ndef realdata(models,kind,options=_OMITTED):\n options={}if options is _OMITTED else options\n if not isinstance(options,dict):raise ValueError('options object required, not explicit null')\n m=models[kind];train=[r for r in m['records']if r['role']=='train'];test=[r for r in m['records']if r['role']=='outer-test'];method=options.get('method','forest');depth=options.get('maxDepth',2);count=options.get('memberCount',3);a=dict(rows=train,queries=[dict(id=r['id'],x=r['x'])for r in test],task=m['task'],classes=m['classes'],maxDepth=depth,minLeaf=options.get('minLeaf',m['minLeaf']),minLeafWeight='0',minGain='0',missingRoute='best',learningRate=options.get('learningRate','1/2'),stages=options.get('stages',3))\n if method not in ['bagging','forest','boost']:raise ValueError('known source method')\n if not isinstance(depth,int)or isinstance(depth,bool)or not 0<=depth<=3:raise ValueError('source depth0..3')\n if method!='boost'and(not isinstance(count,int)or isinstance(count,bool)or not 1<=count<=4):raise ValueError('source member count1..4')\n if method=='boost':result=boost(a)\n else:\n  a.update(bootstrapDraws=m['draws'][:count],nodeFeatures=[{p:v for p,v in s.items()if len(p)<depth}for s in m['schedules'][:count]]);result=ensemble(a,method=='forest')\n outer=scored(result['predictions'],normalized(test,m['task']),m['task'],m['classes']);st=totals([r for r in normalized(train,m['task'])if r['w']and r['y']is not None],m['task'],m['classes']);constant=dict(prediction=st['pred'],probabilities=st['p'],vote=st['pred'],prob=st['pred']);baseline=scored([dict(id=r['id'],**constant)for r in test],normalized(test,m['task']),m['task'],m['classes']);return dict(kind=kind,method=method,settings=a,train=train,test=test,result=result,outer=outer,baseline=baseline)\ndef serial(x):\n if isinstance(x,Q):return str(x)\n if isinstance(x,dict):return{k:serial(v)for k,v in x.items()if k not in['inbag','tree']}\n if isinstance(x,(list,tuple)):return[serial(v)for v in x]\n return x\ndef writecsv(file,heads,rows):\n with Path(file).open('w',encoding='utf8',newline='')as f:\n  w=csv.writer(f);w.writerow(heads);w.writerows([[''if v is None else str(v)for v in r]for r in rows])\nAPI='bagging'\nINPUT={'rows': [{'id': 'a', 'x': [0, 0], 'y': 0}, {'id': 'b', 'x': [1, 1], 'y': 1}, {'id': 'c', 'x': [2, 0], 'y': 3}, {'id': 'd', 'x': [3, 1], 'y': 4}], 'queries': [{'id': 'q', 'x': ['3/2', 0]}], 'bootstrapDraws': [['a', 'b', 'c', 'd'], ['a', 'b', 'c', 'd']], 'maxDepth': 2}\n\ndef run_fixed(api,a,out,src):\n import matplotlib\n matplotlib.use('svg')\n import matplotlib.pyplot as plt\n from matplotlib.ticker import MaxNLocator\n plt.rcParams.update({'font.size':14,'svg.fonttype':'none','svg.hashsalt':'ml09-fixed-v1'})\n result=variance(a)if api=='variance'else aggregate(a)if api=='aggregate'else ensemble(a,api=='forest')if api in ['bagging','forest']else boost(a)if api=='boost'else realdata(read_sources(src),a['kind'])\n out=Path(out);out.mkdir(parents=True,exist_ok=True);summary={};points=[]\n def add(x,y,s):\n  if y is not None:points.append([x,y,s])\n if api=='variance':\n  summary={'B':result['B'],'varianceOfMean':result['varianceOfMean']};add(result['B'],result['varianceOfMean'],'Specified finite-B variance');xl='Number of members B';yl='Variance, stipulated units squared';title='Declared covariance model, not fitted trees'\n elif api=='aggregate':\n  p=result['predictions'][0];classification=a.get('task')=='classification';summary={'selectedPrediction':p['prediction']}\n  if classification:\n   summary.update(voteLabel=p['vote'],probabilityLabel=p['prob'],meanProbability1=p['probabilities'][1]);add(1,p['probabilities'][1],'Mean probability of class 1');add(2,p['votes'][1],'Label-vote share of class 1');xl='Aggregation (1=probability, 2=vote)';yl='Probability or vote share'\n  else:\n   for i,m in enumerate(a['members']):add(i+1,Q(m['predictions'][0]['value']),'Member prediction')\n   add(3,p['prediction'],'Weighted mean');xl='Member 1, member 2, aggregate 3';yl='Prediction, assumed units'\n  title='Votes and probabilities are distinct objects'\n elif api in ['bagging','forest']:\n  summary={'queryPrediction':result['predictions'][0]['prediction'],'OOB.scoreable':result['outOfBag']['eligibleRows'],'OOB.meanLoss':result['outOfBag']['meanLoss']}\n  for i,r in enumerate(a['rows']):add(i+1,Q(r['y']),'Observed training outcome')\n  for i,p in enumerate(result['outOfBag']['rows']):add(i+1,p['prediction'],'OOB prediction, when defined')\n  xl='Original training ID order';yl='Outcome, assumed units';title='Repeated draws and ID-level OOB membership'\n elif api=='boost':\n  summary={'initial':result['initial'],'finalMSE':result['losses'][-1]['MSE'],'stages':result['stages']}\n  for r in result['losses']:add(r['stage'],r['MSE'],'Training MSE')\n  xl='Boosting stage (0=initial)';yl='Weighted MSE, outcome units squared';title='Training descent does not certify held-out gain'\n else:\n  summary={'outer.scoreable':result['outer']['eligibleRows'],'outer.meanLoss':result['outer']['meanLoss'],'baseline.meanLoss':result['baseline']['meanLoss'],'OOB.scoreable':result['result']['outOfBag']['eligibleRows'],'OOB.meanLoss':result['result']['outOfBag']['meanLoss']}\n  for i,p in enumerate(result['outer']['rows']):\n   add(i+1,Q(p['actual']),'Observed outcome');add(i+1,p['probabilities'][1]if a['kind']=='company'else p['prediction'],'Forest probability of class 1'if a['kind']=='company'else'Forest prediction')\n  xl='Outer-test source order, not a time path';yl='Churn label / probability'if a['kind']=='company'else'Period life expectancy, years'if a['kind']=='country'else'Nominal 1976 USD per hour';title='Fixed forest; outer labels did not fit the trees'\n def display(v):return 'undefined'if v is None else format(float(v),'.9f')\n writecsv(out/'summary.csv',['metric','value'],[[k,display(v)]for k,v in summary.items()]);writecsv(out/'plot-points.csv',['x','y','series'],points);(out/'full.json').write_text(json.dumps(serial(result),indent=2)+'\\n',encoding='utf8')\n fig,ax=plt.subplots(figsize=(5.6,4.6));fig.subplots_adjust(left=.24,right=.96,bottom=.24,top=.76);colors=['#355c72','#a55336','#507956','#78568b']\n for i,s in enumerate(dict.fromkeys(p[2]for p in points)):\n  pp=[p for p in points if p[2]==s];ax.scatter([float(p[0])for p in pp],[float(p[1])for p in pp],s=12 if len(pp)>100 else 32,alpha=.5 if len(pp)>100 else 1,color=colors[i%4],label=s)\n ax.set_xlabel(xl,labelpad=10,fontsize=11);ax.set_ylabel(yl,labelpad=10,fontsize=11);ax.xaxis.set_major_locator(MaxNLocator(3));ax.yaxis.set_major_locator(MaxNLocator(4));ax.grid(alpha=.18);ax.legend(loc='lower left',bbox_to_anchor=(0,1.01),fontsize=9,frameon=False);fig.suptitle(title,fontsize=9,y=.99);fig.savefig(out/'plot.svg',metadata={'Date':None});plt.close(fig);print(', '.join(k+'='+display(v)for k,v in summary.items()))\nif __name__=='__main__':\n import sys\n try:run_fixed(API,INPUT,sys.argv[1]if len(sys.argv)>1 else'fixed-results',sys.argv[2]if len(sys.argv)>2 else'ml09-sources')\n except ValueError as error:print('Rejected declared input: '+str(error),file=sys.stderr);sys.exit(2)\n",
        "inputFiles": [],
        "input": {
          "rows": [
            {
              "id": "a",
              "x": [
                0,
                0
              ],
              "y": 0
            },
            {
              "id": "b",
              "x": [
                1,
                1
              ],
              "y": 1
            },
            {
              "id": "c",
              "x": [
                2,
                0
              ],
              "y": 3
            },
            {
              "id": "d",
              "x": [
                3,
                1
              ],
              "y": 4
            }
          ],
          "queries": [
            {
              "id": "q",
              "x": [
                "3/2",
                0
              ]
            }
          ],
          "bootstrapDraws": [
            [
              "a",
              "b",
              "c",
              "d"
            ],
            [
              "a",
              "b",
              "c",
              "d"
            ]
          ],
          "maxDepth": 2
        },
        "returnCode": 0,
        "expectedFailure": false,
        "stdout": "queryPrediction=1.000000000, OOB.scoreable=0.000000000, OOB.meanLoss=undefined\n",
        "stderr": "",
        "summary": {
          "queryPrediction": "1.000000000",
          "OOB.scoreable": "0.000000000",
          "OOB.meanLoss": "undefined"
        },
        "plotPoints": [
          {
            "x": "1",
            "y": "0",
            "series": "Observed training outcome"
          },
          {
            "x": "2",
            "y": "1",
            "series": "Observed training outcome"
          },
          {
            "x": "3",
            "y": "3",
            "series": "Observed training outcome"
          },
          {
            "x": "4",
            "y": "4",
            "series": "Observed training outcome"
          }
        ],
        "plotFile": "ml09-fixed-results/bagging-no-OOB-members-python/plot.svg",
        "plotSHA256": "a4bc6fce3b15a802c51eb5237e959c9ffdf2031211ce2d037bce89aa4b41cbb8",
        "files": [
          {
            "file": "ml09-fixed-results/bagging-no-OOB-members-python/full.json",
            "sha256": "44bcd7426f9af3b305ed86b6c20eb94be9a089b1987b7207ee4ca439ee1ecfe6"
          },
          {
            "file": "ml09-fixed-results/bagging-no-OOB-members-python/plot-points.csv",
            "sha256": "f2703eed153b793eb6d0ea8820f6e03d44cb5ecf014934c92207c4a322d62777"
          },
          {
            "file": "ml09-fixed-results/bagging-no-OOB-members-python/plot.svg",
            "sha256": "a4bc6fce3b15a802c51eb5237e959c9ffdf2031211ce2d037bce89aa4b41cbb8"
          },
          {
            "file": "ml09-fixed-results/bagging-no-OOB-members-python/summary.csv",
            "sha256": "efe53dcf096f1c5361023646410062d522cad079fa2793bc7aa546f8988a61b4"
          }
        ],
        "scope": "Actually executed self-contained fixed example; current web controls execute separately. Python Fraction and finite-precision base R. Author gate, not independent peer."
      }
    },
    "r": {
      "repeated-occurrences": {
        "api": "bagging",
        "variant": "repeated-occurrences",
        "language": "r",
        "codeFile": "ml09-code/bagging-repeated-occurrences.R",
        "codeSHA256": "149b82641e90333a079552c61eef208829bd107d3f8fcf3df68aa35cf1db774b",
        "codeText": "# ML09 base-R reproduction from native original-field CSVs.\n# Rscript ml09-public-analysis.R ml09-sources results-r\n# Separately written vectorized direct-centered squared/Gini losses.\n# No Python/JS/model-contract/stored-answer/derived-result reader or package.\n# Numeric arithmetic is binary64:1e-12 relative tie tolerance stabilizes exact\n# source ties,but does not certify tiny margins/underflow like Fraction JS/Python.\n# Data-frame rows use x0,x1,...,y,weight; original IDs remain attached to draws.\noptions(stringsAsFactors=FALSE,digits=17)\nnum<-function(v){if(is.null(v)||length(v)!=1||is.na(v))stop('numeric parameter required, not explicit NULL');p<-strsplit(as.character(v),'/',fixed=TRUE)[[1]];z<-if(length(p)==2)as.numeric(p[1])/as.numeric(p[2])else as.numeric(v);if(!is.finite(z))stop('finite numeric parameter');z}\noption<-function(a,k,default){if(k%in%names(a))a[[k]]else default}\nnormrows<-function(d,task){if(!'weight'%in%names(d))d$weight<-1;if(!'id'%in%names(d))d$id<-as.character(seq_len(nrow(d))-1);d$weight<-as.numeric(d$weight);if(anyNA(d$weight)||any(d$weight<0))stop('nonnegative weights');if(task=='regression')d$y<-as.numeric(d$y)else d$y<-as.character(d$y);d}\nstat<-function(d,task,classes){W<-sum(d$weight);mu<-if(task=='regression'&&W)sum(d$weight*d$y)/W else NA_real_;p<-if(task=='classification'&&W)vapply(classes,function(c)sum(d$weight[d$y==c])/W,0)else numeric();risk<-if(task=='regression'&&W)sum(d$weight*(d$y-mu)^2)else W*sum(p*(1-p));list(n=nrow(d),w=W,mu=mu,p=unname(p),risk=risk,pred=if(task=='regression')mu else if(W)classes[which.max(p)]else NA_character_)}\nfit<-function(d,a,task,classes,schedule=NULL){d<-d[d$weight>0&!is.na(d$y),,drop=FALSE];if(!nrow(d))stop('positive observed training');W<-sum(d$weight);depth<-option(a,'maxDepth',2);minimum<-option(a,'minLeaf',1);minmass<-num(option(a,'minLeafWeight',0));mingain<-num(option(a,'minGain',0));route<-option(a,'missingRoute','best');features<-grep('^x[0-9]+$',names(d),value=TRUE)\n build<-function(rr,level,path){st<-stat(rr,task,classes);node<-list(rows=rr,st=st,split=NULL,left=NULL,right=NULL,path=path);if(level==depth)return(node);best<-NULL;allowed<-if(is.null(schedule))seq_along(features)-1L else schedule[[match(path,names(schedule))]]\n  for(j in seq_along(features)-1L){if(!j%in%allowed)next;v<-rr[[features[j+1L]]];values<-sort(unique(v[!is.na(v)]));candidates<-list()\n   if(length(values)>1)for(k in seq_len(length(values)-1L)){threshold<-(values[k]+values[k+1L])/2;missing<-is.na(v);left<-!missing&v<=threshold;right<-!missing&v>threshold;directions<-if(route!='best')route else if(any(missing))c('left','right')else if(sum(left)>=sum(right))'left'else'right';for(direction in directions)candidates[[length(candidates)+1L]]<-list(kind='threshold',threshold=threshold,missingRoute=direction,left=if(direction=='left')left|missing else left,right=if(direction=='right')right|missing else right)}\n   if(anyNA(v)&&any(!is.na(v)))candidates[[length(candidates)+1L]]<-list(kind='missing-only',threshold=NA_real_,missingRoute='left',left=is.na(v),right=!is.na(v))\n   for(candidate in candidates){l<-rr[candidate$left,,drop=FALSE];r<-rr[candidate$right,,drop=FALSE];ls<-stat(l,task,classes);rs<-stat(r,task,classes);if(min(ls$n,rs$n)<minimum||min(ls$w,rs$w)<minmass||min(ls$w,rs$w)<=0)next;gain<-(st$risk-ls$risk-rs$risk)/W;tol<-1e-12*max(1,abs(gain),if(is.null(best))0 else abs(best$gain));if(is.null(best)||gain>best$gain+tol)best<-c(candidate,list(feature=j,gain=gain,l=l,r=r))}\n  }\n  if(!is.null(best)&&best$gain>max(mingain,1e-12)){node$split<-best;node$left<-build(best$l,level+1L,paste0(path,'L'));node$right<-build(best$r,level+1L,paste0(path,'R'))};node\n };build(d,0L,'')\n}\npredict_one<-function(tree,row){n<-tree;while(!is.null(n$split)){s<-n$split;v<-as.numeric(row[[paste0('x',s$feature)]]);left<-if(s$kind=='missing-only')is.na(v)else if(is.na(v))s$missingRoute=='left'else v<=s$threshold;n<-if(left)n$left else n$right};list(prediction=n$st$pred,probabilities=n$st$p)}\ncombine<-function(pp,w,task,classes,mode='probabilities'){W<-sum(w);if(!length(pp)||!W)return(list(prediction=if(task=='regression')NA_real_ else NA_character_,probabilities=numeric(),vote=NA_character_,prob=NA_character_));if(task=='regression')return(list(prediction=sum(vapply(pp,function(p)p$prediction,0)*w)/W,probabilities=numeric(),vote=NA_character_,prob=NA_character_));votes<-vapply(classes,function(c)sum(w[vapply(pp,function(p)p$prediction==c,FALSE)])/W,0);probs<-vapply(seq_along(classes),function(j)sum(vapply(pp,function(p)p$probabilities[j],0)*w)/W,0);vote<-classes[which.max(votes)];prob<-classes[which.max(probs)];list(prediction=if(mode=='votes')vote else prob,probabilities=unname(probs),vote=vote,prob=prob,votes=unname(votes))}\nvariance<-function(a){B<-num(a$B);v<-num(a$marginalVariance);rho<-num(option(a,'rho',0));if(B<1||B!=floor(B)||v<0)stop('integer B/nonnegative variance');if(B>1&&v>0&&(rho< -1/(B-1)||rho>1))stop('PSD correlation');list(B=B,marginalVariance=v,correlationApplicable=B>1&&v>0,varianceOfMean=if(B==1)v else v*(1+(B-1)*rho)/B)}\naggregate<-function(a){task<-option(a,'task','regression');classes<-option(a,'classes',character());w<-vapply(option(a,'memberWeights',as.list(rep(1,length(a$members)))),num,0);if(any(w<0)||sum(w)<=0)stop('positive member mass');ids<-a$members[[1]]$predictions$id;pp<-lapply(ids,function(id){members<-lapply(a$members,function(m){r<-m$predictions[match(id,m$predictions$id),,drop=FALSE];if(task=='regression')list(prediction=num(r$value),probabilities=numeric())else list(prediction=as.character(r$label),probabilities=as.numeric(r[paste0('p',seq_along(classes)-1L)]))});c(list(id=id),combine(members,w,task,classes,option(a,'aggregation','probabilities')))});list(task=task,classes=classes,predictions=pp)}\nscored<-function(preds,d,task,classes){W<-loss<-absolute<-errors<-voteerrors<-0;count<-0L;out<-lapply(seq_len(nrow(d)),function(i){r<-d[i,,drop=FALSE];p<-preds[[i]];ok<-!is.na(p$prediction)&&!is.na(r$y)&&r$weight>0;value<-NA_real_;if(ok){count<<-count+1L;W<<-W+r$weight;if(task=='regression'){e<-r$y-p$prediction;value<-e*e;absolute<<-absolute+r$weight*abs(e)}else{value<-sum((p$probabilities-as.numeric(classes==r$y))^2);errors<<-errors+r$weight*(p$prediction!=r$y);voteerrors<<-voteerrors+r$weight*(p$vote!=r$y)};loss<<-loss+r$weight*value};c(p,list(actual=r$y,weight=r$weight,scoreEligible=ok,loss=value))});list(rows=out,eligibleRows=count,weight=W,totalLoss=loss,meanLoss=if(W)loss/W else NA_real_,MAE=if(W&&task=='regression')absolute/W else NA_real_,errorRate=if(W&&task=='classification')errors/W else NA_real_,labelVoteErrorRate=if(W&&task=='classification')voteerrors/W else NA_real_)}\nensemble<-function(a,forest=FALSE){task<-option(a,'task','regression');classes<-option(a,'classes',character());d<-normrows(a$rows,task);w<-vapply(option(a,'memberWeights',as.list(rep(1,length(a$bootstrapDraws)))),num,0);if(any(w<0)||sum(w)<=0)stop('positive member mass');members<-lapply(seq_along(a$bootstrapDraws),function(i){draw<-a$bootstrapDraws[[i]];indices<-match(draw,d$id);if(anyNA(indices))stop('unknown draw source');tree<-fit(d[indices,,drop=FALSE],a,task,classes,if(forest)a$nodeFeatures[[i]]else NULL);list(tree=tree,draw=draw,inbag=unique(draw),weight=w[i])});queries<-a$queries;preds<-lapply(seq_len(nrow(queries)),function(i)c(list(id=queries$id[i]),combine(lapply(members,function(m)predict_one(m$tree,queries[i,,drop=FALSE])),w,task,classes,option(a,'aggregation','probabilities'))));oob<-lapply(seq_len(nrow(d)),function(i){app<-which(!vapply(members,function(m)d$id[i]%in%m$inbag,FALSE));pp<-combine(lapply(app,function(j)predict_one(members[[j]]$tree,d[i,,drop=FALSE])),w[app],task,classes,option(a,'aggregation','probabilities'));c(list(id=d$id[i],applicable=app-1L,positiveMembers=sum(w[app]>0)),pp)});list(task=task,classes=classes,members=members,predictions=preds,outOfBag=scored(oob,d,task,classes))}\nboost<-function(a){if(option(a,'task','regression')!='regression')stop('regression boosting only');d<-normrows(a$rows,'regression');eligible<-d$weight>0&!is.na(d$y);W<-sum(d$weight[eligible]);if(!W)stop('positive eligible training');eta<-num(option(a,'learningRate','1/2'));stages<-option(a,'stages',3);if(is.null(stages)||stages!=floor(stages)||stages<0||stages>8||eta<0||eta>1)stop('supported rate/stages');initial<-if('initial'%in%names(a))num(a$initial)else sum(d$weight[eligible]*d$y[eligible])/W;train<-matrix(initial,nrow(d),stages+1L);query<-matrix(initial,nrow(a$queries),stages+1L);losses<-fits<-list();for(stage in 0:stages){sse<-sum(d$weight[eligible]*(d$y[eligible]-train[eligible,stage+1L])^2);losses[[stage+1L]]<-list(stage=stage,rawWeightedSSE=sse,MSE=sse/W,meanHalfSquaredLoss=sse/(2*W));if(stage==stages)break;residual<-d;residual$y<-d$y-train[,stage+1L];tree<-fit(residual,a,'regression',character());h<-vapply(seq_len(nrow(d)),function(i)predict_one(tree,d[i,,drop=FALSE])$prediction,0);qh<-vapply(seq_len(nrow(a$queries)),function(i)predict_one(tree,a$queries[i,,drop=FALSE])$prediction,0);stageRows<-lapply(seq_len(nrow(d)),function(i)list(id=d$id[i],before=train[i,stage+1L],residual=residual$y[i],negativeCoordinateDerivative=d$weight[i]*residual$y[i]/W,fit=h[i],addition=eta*h[i],after=train[i,stage+1L]+eta*h[i]));train[,stage+2L]<-train[,stage+1L]+eta*h;query[,stage+2L]<-query[,stage+1L]+eta*qh;norm<-sum(d$weight[eligible]*h[eligible]^2);fits[[stage+1L]]<-list(stage=stage+1L,tree=tree,rows=stageRows,queryFits=qh,norm=norm,predictedSSEDecrease=eta*(2-eta)*norm)};list(task='regression',initial=initial,learningRate=eta,stages=stages,training=train,queries=query,fits=fits,losses=losses,predictions=lapply(seq_len(nrow(a$queries)),function(i)list(id=a$queries$id[i],prediction=query[i,stages+1L],probabilities=numeric(),vote=NA_character_,prob=NA_character_)))}\nfixed_schedules<-function(ids,p,seed){state<-seed;choose<-function(n){limit<-floor(4294967296/n)*n;repeat{state<<-(1664525*state+1013904223)%%4294967296;if(state<limit)return(as.integer(state%%n))}};draws<-schedules<-list();for(member in 1:4){draws[[member]]<-vapply(seq_along(ids),function(i)ids[choose(length(ids))+1L],'');schedule<-setNames(vector('list',7),c('','L','R','LL','LR','RL','RR'));for(path in names(schedule)){order<-seq_len(p)-1L;if(p>1)for(j in seq(p-1L,1L)){k<-choose(j+1L);temp<-order[j+1L];order[j+1L]<-order[k+1L];order[k+1L]<-temp};schedule[[match(path,names(schedule))]]<-sort(order[seq_len(max(1L,floor(sqrt(p))))])};schedules[[member]]<-schedule};list(draws=draws,schedules=schedules)}\nread_sources<-function(src){read<-function(name)read.csv(file.path(src,name),check.names=FALSE,colClasses='character',na.strings=character(),fileEncoding='UTF-8-BOM');raw<-read('actual320-country-four-indicators-original-2020-2024.csv');country<-do.call(rbind,lapply(sort(unique(raw$countryISO3)),function(code)do.call(rbind,lapply(2020:2024,function(year){keys<-c('NY.GDP.PCAP.KD','NY.GDP.MKTP.KD.ZG','FP.CPI.TOTL.ZG','SP.DYN.LE00.IN');v<-vapply(keys,function(k)as.numeric(raw$originalValueToken[raw$countryISO3==code&raw$date==as.character(year)&raw$indicatorID==k]),0);data.frame(id=paste0(code,':',year),sourceRow=paste0(code,':',year),originalID=code,year=year,x0=v[1]/10000,x1=v[2],x2=v[3],y=v[4],weight=1,role=if(anyNA(v))'excluded'else if(year==2024)'outer-test'else'train')}))));raw<-read('actual3613-NLS-original52-fields-and-selection.csv');i<-seq_len(nrow(raw));x0<-suppressWarnings(as.numeric(raw$ed76));x1<-suppressWarnings(as.numeric(raw$age76));y<-suppressWarnings(as.numeric(raw$wage76))/100;person<-data.frame(id=paste0('person:',i),sourceRow=as.character(i),originalID=raw$id,x0=x0,x1=x1,y=y,weight=1,role=ifelse(is.na(x0)|is.na(x1)|is.na(y),'excluded',ifelse(i%%5==0,'outer-test','train')));raw<-read('actual3150-churn-original14-fields-and-selection.csv');i<-seq_len(nrow(raw));company<-data.frame(id=paste0('customer:',i),sourceRow=as.character(i),originalID='',x0=as.numeric(raw[['Call  Failure']]),x1=as.numeric(raw[['Subscription  Length']]),x2=as.numeric(raw[['Charge  Amount']]),y=raw$Churn,weight=1,role=ifelse(i%%5==0,'outer-test','train'));models<-list();for(index in 1:3){kind<-c('country','person','company')[index];d<-list(country,person,company)[[index]];task<-if(kind=='company')'classification'else'regression';s<-fixed_schedules(d$id[d$role=='train'],if(kind=='person')2L else 3L,20261102+7919*(index-1L));models[[kind]]<-list(records=d,task=task,classes=if(task=='classification')c('0','1')else character(),draws=s$draws,schedules=s$schedules,minLeaf=c(4L,50L,30L)[index])};models}\nrealdata<-function(models,kind,options=list()){if(is.null(options)||!is.list(options))stop('options object');m<-models[[kind]];d<-m$records;train<-d[d$role=='train',,drop=FALSE];test<-d[d$role=='outer-test',,drop=FALSE];method<-option(options,'method','forest');depth<-option(options,'maxDepth',2);count<-option(options,'memberCount',3);if(!method%in%c('bagging','forest','boost'))stop('known method');a<-list(rows=train,queries=test,task=m$task,classes=m$classes,maxDepth=depth,minLeaf=option(options,'minLeaf',m$minLeaf),minLeafWeight=0,minGain=0,missingRoute='best',learningRate=option(options,'learningRate','1/2'),stages=option(options,'stages',3));if(method=='boost')result<-boost(a)else{a$bootstrapDraws<-m$draws[seq_len(count)];a$nodeFeatures<-lapply(m$schedules[seq_len(count)],function(s)s[nchar(names(s))<depth]);result<-ensemble(a,method=='forest')};outer<-scored(result$predictions,normrows(test,m$task),m$task,m$classes);st<-stat(normrows(train,m$task),m$task,m$classes);constant<-list(prediction=st$pred,probabilities=st$p,vote=st$pred,prob=st$pred);baseline<-scored(lapply(test$id,function(id)c(list(id=id),constant)),normrows(test,m$task),m$task,m$classes);list(kind=kind,method=method,settings=a,train=train,test=test,result=result,outer=outer,baseline=baseline)}\nAPI<-\"bagging\"\nINPUT<-list(rows=data.frame(id=c(\"a\",\"b\",\"c\",\"d\"),y=c(0,1,3,4),x0=c(0,1,2,3),x1=c(0,1,0,1),stringsAsFactors=FALSE),queries=data.frame(id=c(\"q\"),x0=c(num(\"3/2\")),x1=c(0),stringsAsFactors=FALSE),bootstrapDraws=list(c(\"a\",\"a\",\"b\",\"c\"),c(\"b\",\"c\",\"d\",\"d\")),maxDepth=2)\n\nrun_fixed<-function(api,a,out,src){\n r<-if(api=='variance')variance(a)else if(api=='aggregate')aggregate(a)else if(api%in%c('bagging','forest'))ensemble(a,api=='forest')else if(api=='boost')boost(a)else realdata(read_sources(src),a$kind)\n dir.create(out,recursive=TRUE,showWarnings=FALSE);summary<-list();points<-list();add<-function(x,y,s){if(!is.null(y)&&!is.na(y))points[[length(points)+1L]]<<-data.frame(x=x,y=as.numeric(y),series=s)}\n if(api=='variance'){summary<-r[c('B','varianceOfMean')];add(r$B,r$varianceOfMean,'Specified finite-B variance');xl<-'Number of members B';yl<-'Variance, stipulated units squared';title<-'Declared covariance model, not fitted trees'\n }else if(api=='aggregate'){p<-r$predictions[[1]];summary<-list(selectedPrediction=p$prediction);classification<-identical(a$task,'classification');if(classification){summary<-c(summary,list(voteLabel=p$vote,probabilityLabel=p$prob,meanProbability1=p$probabilities[2]));add(1,p$probabilities[2],'Mean probability of class 1');add(2,p$votes[2],'Label-vote share of class 1');xl<-'Aggregation (1=probability, 2=vote)';yl<-'Probability or vote share'}else{for(i in seq_along(a$members))add(i,num(a$members[[i]]$predictions$value[1]),'Member prediction');add(3,p$prediction,'Weighted mean');xl<-'Member 1, member 2, aggregate 3';yl<-'Prediction, assumed units'};title<-'Votes and probabilities are distinct objects'\n }else if(api%in%c('bagging','forest')){summary<-list(queryPrediction=r$predictions[[1]]$prediction,OOB.scoreable=r$outOfBag$eligibleRows,OOB.meanLoss=r$outOfBag$meanLoss);for(i in seq_len(nrow(a$rows)))add(i,a$rows$y[i],'Observed training outcome');for(i in seq_along(r$outOfBag$rows))add(i,r$outOfBag$rows[[i]]$prediction,'OOB prediction, when defined');xl<-'Original training ID order';yl<-'Outcome, assumed units';title<-'Repeated draws and ID-level OOB membership'\n }else if(api=='boost'){summary<-list(initial=r$initial,finalMSE=r$losses[[length(r$losses)]]$MSE,stages=r$stages);for(v in r$losses)add(v$stage,v$MSE,'Training MSE');xl<-'Boosting stage (0=initial)';yl<-'Weighted MSE, outcome units squared';title<-'Training descent does not certify held-out gain'\n }else{summary<-list(outer.scoreable=r$outer$eligibleRows,outer.meanLoss=r$outer$meanLoss,baseline.meanLoss=r$baseline$meanLoss,OOB.scoreable=r$result$outOfBag$eligibleRows,OOB.meanLoss=r$result$outOfBag$meanLoss);for(i in seq_along(r$outer$rows)){p<-r$outer$rows[[i]];add(i,as.numeric(p$actual),'Observed outcome');add(i,if(a$kind=='company')p$probabilities[2]else p$prediction,if(a$kind=='company')'Forest probability of class 1'else'Forest prediction')};xl<-'Outer-test source order, not a time path';yl<-if(a$kind=='company')'Churn label / probability'else if(a$kind=='country')'Period life expectancy, years'else'Nominal 1976 USD per hour';title<-'Fixed forest; outer labels did not fit the trees'}\n display<-function(v)if(is.null(v)||is.na(v))'undefined'else sprintf('%.9f',as.numeric(v));write.csv(data.frame(metric=names(summary),value=vapply(summary,display,'')),file.path(out,'summary.csv'),row.names=FALSE);pp<-do.call(rbind,points);write.csv(pp,file.path(out,'plot-points.csv'),row.names=FALSE);dput(r,file.path(out,'full-result.Rtext'));svg(file.path(out,'plot.svg'),width=5.6,height=4.6,pointsize=14);par(mar=c(5.8,5.8,5.3,1.2),mgp=c(3.7,1,0));xr<-range(pp$x);yr<-range(pp$y);if(diff(xr)==0)xr<-xr+c(-.5,.5);if(diff(yr)==0)yr<-yr+c(-.5,.5);plot(xr,yr,type='n',xlab=xl,ylab=yl,cex.lab=.78,axes=FALSE);axis(1,at=pretty(xr,3));axis(2,at=pretty(yr,4),las=1,cex.axis=.82);box();grid(col='#dddddd');cols<-c('#355c72','#a55336','#507956','#78568b');ss<-unique(pp$series);for(i in seq_along(ss)){v<-pp[pp$series==ss[i],];points(v$x,v$y,pch=16,cex=if(nrow(v)>100).35 else .85,col=adjustcolor(cols[i],if(nrow(v)>100).5 else 1))};legend('topleft',legend=ss,col=cols[seq_along(ss)],lty=0,pch=16,cex=.65,bty='n',inset=c(0,-.32),xpd=NA);mtext(title,side=3,line=3.9,cex=.6);dev.off();cat(paste(names(summary),vapply(summary,display,''),sep='=',collapse=', '),'\\n')\n}\nargs<-commandArgs(trailingOnly=TRUE)\ntryCatch(run_fixed(API,INPUT,if(length(args))args[1]else'fixed-results',if(length(args)>1)args[2]else'ml09-sources'),error=function(e){cat('Rejected declared input: ',conditionMessage(e),'\\n',file=stderr());quit(status=2)})\n",
        "code": "# ML09 base-R reproduction from native original-field CSVs.\n# Rscript ml09-public-analysis.R ml09-sources results-r\n# Separately written vectorized direct-centered squared/Gini losses.\n# No Python/JS/model-contract/stored-answer/derived-result reader or package.\n# Numeric arithmetic is binary64:1e-12 relative tie tolerance stabilizes exact\n# source ties,but does not certify tiny margins/underflow like Fraction JS/Python.\n# Data-frame rows use x0,x1,...,y,weight; original IDs remain attached to draws.\noptions(stringsAsFactors=FALSE,digits=17)\nnum<-function(v){if(is.null(v)||length(v)!=1||is.na(v))stop('numeric parameter required, not explicit NULL');p<-strsplit(as.character(v),'/',fixed=TRUE)[[1]];z<-if(length(p)==2)as.numeric(p[1])/as.numeric(p[2])else as.numeric(v);if(!is.finite(z))stop('finite numeric parameter');z}\noption<-function(a,k,default){if(k%in%names(a))a[[k]]else default}\nnormrows<-function(d,task){if(!'weight'%in%names(d))d$weight<-1;if(!'id'%in%names(d))d$id<-as.character(seq_len(nrow(d))-1);d$weight<-as.numeric(d$weight);if(anyNA(d$weight)||any(d$weight<0))stop('nonnegative weights');if(task=='regression')d$y<-as.numeric(d$y)else d$y<-as.character(d$y);d}\nstat<-function(d,task,classes){W<-sum(d$weight);mu<-if(task=='regression'&&W)sum(d$weight*d$y)/W else NA_real_;p<-if(task=='classification'&&W)vapply(classes,function(c)sum(d$weight[d$y==c])/W,0)else numeric();risk<-if(task=='regression'&&W)sum(d$weight*(d$y-mu)^2)else W*sum(p*(1-p));list(n=nrow(d),w=W,mu=mu,p=unname(p),risk=risk,pred=if(task=='regression')mu else if(W)classes[which.max(p)]else NA_character_)}\nfit<-function(d,a,task,classes,schedule=NULL){d<-d[d$weight>0&!is.na(d$y),,drop=FALSE];if(!nrow(d))stop('positive observed training');W<-sum(d$weight);depth<-option(a,'maxDepth',2);minimum<-option(a,'minLeaf',1);minmass<-num(option(a,'minLeafWeight',0));mingain<-num(option(a,'minGain',0));route<-option(a,'missingRoute','best');features<-grep('^x[0-9]+$',names(d),value=TRUE)\n build<-function(rr,level,path){st<-stat(rr,task,classes);node<-list(rows=rr,st=st,split=NULL,left=NULL,right=NULL,path=path);if(level==depth)return(node);best<-NULL;allowed<-if(is.null(schedule))seq_along(features)-1L else schedule[[match(path,names(schedule))]]\n  for(j in seq_along(features)-1L){if(!j%in%allowed)next;v<-rr[[features[j+1L]]];values<-sort(unique(v[!is.na(v)]));candidates<-list()\n   if(length(values)>1)for(k in seq_len(length(values)-1L)){threshold<-(values[k]+values[k+1L])/2;missing<-is.na(v);left<-!missing&v<=threshold;right<-!missing&v>threshold;directions<-if(route!='best')route else if(any(missing))c('left','right')else if(sum(left)>=sum(right))'left'else'right';for(direction in directions)candidates[[length(candidates)+1L]]<-list(kind='threshold',threshold=threshold,missingRoute=direction,left=if(direction=='left')left|missing else left,right=if(direction=='right')right|missing else right)}\n   if(anyNA(v)&&any(!is.na(v)))candidates[[length(candidates)+1L]]<-list(kind='missing-only',threshold=NA_real_,missingRoute='left',left=is.na(v),right=!is.na(v))\n   for(candidate in candidates){l<-rr[candidate$left,,drop=FALSE];r<-rr[candidate$right,,drop=FALSE];ls<-stat(l,task,classes);rs<-stat(r,task,classes);if(min(ls$n,rs$n)<minimum||min(ls$w,rs$w)<minmass||min(ls$w,rs$w)<=0)next;gain<-(st$risk-ls$risk-rs$risk)/W;tol<-1e-12*max(1,abs(gain),if(is.null(best))0 else abs(best$gain));if(is.null(best)||gain>best$gain+tol)best<-c(candidate,list(feature=j,gain=gain,l=l,r=r))}\n  }\n  if(!is.null(best)&&best$gain>max(mingain,1e-12)){node$split<-best;node$left<-build(best$l,level+1L,paste0(path,'L'));node$right<-build(best$r,level+1L,paste0(path,'R'))};node\n };build(d,0L,'')\n}\npredict_one<-function(tree,row){n<-tree;while(!is.null(n$split)){s<-n$split;v<-as.numeric(row[[paste0('x',s$feature)]]);left<-if(s$kind=='missing-only')is.na(v)else if(is.na(v))s$missingRoute=='left'else v<=s$threshold;n<-if(left)n$left else n$right};list(prediction=n$st$pred,probabilities=n$st$p)}\ncombine<-function(pp,w,task,classes,mode='probabilities'){W<-sum(w);if(!length(pp)||!W)return(list(prediction=if(task=='regression')NA_real_ else NA_character_,probabilities=numeric(),vote=NA_character_,prob=NA_character_));if(task=='regression')return(list(prediction=sum(vapply(pp,function(p)p$prediction,0)*w)/W,probabilities=numeric(),vote=NA_character_,prob=NA_character_));votes<-vapply(classes,function(c)sum(w[vapply(pp,function(p)p$prediction==c,FALSE)])/W,0);probs<-vapply(seq_along(classes),function(j)sum(vapply(pp,function(p)p$probabilities[j],0)*w)/W,0);vote<-classes[which.max(votes)];prob<-classes[which.max(probs)];list(prediction=if(mode=='votes')vote else prob,probabilities=unname(probs),vote=vote,prob=prob,votes=unname(votes))}\nvariance<-function(a){B<-num(a$B);v<-num(a$marginalVariance);rho<-num(option(a,'rho',0));if(B<1||B!=floor(B)||v<0)stop('integer B/nonnegative variance');if(B>1&&v>0&&(rho< -1/(B-1)||rho>1))stop('PSD correlation');list(B=B,marginalVariance=v,correlationApplicable=B>1&&v>0,varianceOfMean=if(B==1)v else v*(1+(B-1)*rho)/B)}\naggregate<-function(a){task<-option(a,'task','regression');classes<-option(a,'classes',character());w<-vapply(option(a,'memberWeights',as.list(rep(1,length(a$members)))),num,0);if(any(w<0)||sum(w)<=0)stop('positive member mass');ids<-a$members[[1]]$predictions$id;pp<-lapply(ids,function(id){members<-lapply(a$members,function(m){r<-m$predictions[match(id,m$predictions$id),,drop=FALSE];if(task=='regression')list(prediction=num(r$value),probabilities=numeric())else list(prediction=as.character(r$label),probabilities=as.numeric(r[paste0('p',seq_along(classes)-1L)]))});c(list(id=id),combine(members,w,task,classes,option(a,'aggregation','probabilities')))});list(task=task,classes=classes,predictions=pp)}\nscored<-function(preds,d,task,classes){W<-loss<-absolute<-errors<-voteerrors<-0;count<-0L;out<-lapply(seq_len(nrow(d)),function(i){r<-d[i,,drop=FALSE];p<-preds[[i]];ok<-!is.na(p$prediction)&&!is.na(r$y)&&r$weight>0;value<-NA_real_;if(ok){count<<-count+1L;W<<-W+r$weight;if(task=='regression'){e<-r$y-p$prediction;value<-e*e;absolute<<-absolute+r$weight*abs(e)}else{value<-sum((p$probabilities-as.numeric(classes==r$y))^2);errors<<-errors+r$weight*(p$prediction!=r$y);voteerrors<<-voteerrors+r$weight*(p$vote!=r$y)};loss<<-loss+r$weight*value};c(p,list(actual=r$y,weight=r$weight,scoreEligible=ok,loss=value))});list(rows=out,eligibleRows=count,weight=W,totalLoss=loss,meanLoss=if(W)loss/W else NA_real_,MAE=if(W&&task=='regression')absolute/W else NA_real_,errorRate=if(W&&task=='classification')errors/W else NA_real_,labelVoteErrorRate=if(W&&task=='classification')voteerrors/W else NA_real_)}\nensemble<-function(a,forest=FALSE){task<-option(a,'task','regression');classes<-option(a,'classes',character());d<-normrows(a$rows,task);w<-vapply(option(a,'memberWeights',as.list(rep(1,length(a$bootstrapDraws)))),num,0);if(any(w<0)||sum(w)<=0)stop('positive member mass');members<-lapply(seq_along(a$bootstrapDraws),function(i){draw<-a$bootstrapDraws[[i]];indices<-match(draw,d$id);if(anyNA(indices))stop('unknown draw source');tree<-fit(d[indices,,drop=FALSE],a,task,classes,if(forest)a$nodeFeatures[[i]]else NULL);list(tree=tree,draw=draw,inbag=unique(draw),weight=w[i])});queries<-a$queries;preds<-lapply(seq_len(nrow(queries)),function(i)c(list(id=queries$id[i]),combine(lapply(members,function(m)predict_one(m$tree,queries[i,,drop=FALSE])),w,task,classes,option(a,'aggregation','probabilities'))));oob<-lapply(seq_len(nrow(d)),function(i){app<-which(!vapply(members,function(m)d$id[i]%in%m$inbag,FALSE));pp<-combine(lapply(app,function(j)predict_one(members[[j]]$tree,d[i,,drop=FALSE])),w[app],task,classes,option(a,'aggregation','probabilities'));c(list(id=d$id[i],applicable=app-1L,positiveMembers=sum(w[app]>0)),pp)});list(task=task,classes=classes,members=members,predictions=preds,outOfBag=scored(oob,d,task,classes))}\nboost<-function(a){if(option(a,'task','regression')!='regression')stop('regression boosting only');d<-normrows(a$rows,'regression');eligible<-d$weight>0&!is.na(d$y);W<-sum(d$weight[eligible]);if(!W)stop('positive eligible training');eta<-num(option(a,'learningRate','1/2'));stages<-option(a,'stages',3);if(is.null(stages)||stages!=floor(stages)||stages<0||stages>8||eta<0||eta>1)stop('supported rate/stages');initial<-if('initial'%in%names(a))num(a$initial)else sum(d$weight[eligible]*d$y[eligible])/W;train<-matrix(initial,nrow(d),stages+1L);query<-matrix(initial,nrow(a$queries),stages+1L);losses<-fits<-list();for(stage in 0:stages){sse<-sum(d$weight[eligible]*(d$y[eligible]-train[eligible,stage+1L])^2);losses[[stage+1L]]<-list(stage=stage,rawWeightedSSE=sse,MSE=sse/W,meanHalfSquaredLoss=sse/(2*W));if(stage==stages)break;residual<-d;residual$y<-d$y-train[,stage+1L];tree<-fit(residual,a,'regression',character());h<-vapply(seq_len(nrow(d)),function(i)predict_one(tree,d[i,,drop=FALSE])$prediction,0);qh<-vapply(seq_len(nrow(a$queries)),function(i)predict_one(tree,a$queries[i,,drop=FALSE])$prediction,0);stageRows<-lapply(seq_len(nrow(d)),function(i)list(id=d$id[i],before=train[i,stage+1L],residual=residual$y[i],negativeCoordinateDerivative=d$weight[i]*residual$y[i]/W,fit=h[i],addition=eta*h[i],after=train[i,stage+1L]+eta*h[i]));train[,stage+2L]<-train[,stage+1L]+eta*h;query[,stage+2L]<-query[,stage+1L]+eta*qh;norm<-sum(d$weight[eligible]*h[eligible]^2);fits[[stage+1L]]<-list(stage=stage+1L,tree=tree,rows=stageRows,queryFits=qh,norm=norm,predictedSSEDecrease=eta*(2-eta)*norm)};list(task='regression',initial=initial,learningRate=eta,stages=stages,training=train,queries=query,fits=fits,losses=losses,predictions=lapply(seq_len(nrow(a$queries)),function(i)list(id=a$queries$id[i],prediction=query[i,stages+1L],probabilities=numeric(),vote=NA_character_,prob=NA_character_)))}\nfixed_schedules<-function(ids,p,seed){state<-seed;choose<-function(n){limit<-floor(4294967296/n)*n;repeat{state<<-(1664525*state+1013904223)%%4294967296;if(state<limit)return(as.integer(state%%n))}};draws<-schedules<-list();for(member in 1:4){draws[[member]]<-vapply(seq_along(ids),function(i)ids[choose(length(ids))+1L],'');schedule<-setNames(vector('list',7),c('','L','R','LL','LR','RL','RR'));for(path in names(schedule)){order<-seq_len(p)-1L;if(p>1)for(j in seq(p-1L,1L)){k<-choose(j+1L);temp<-order[j+1L];order[j+1L]<-order[k+1L];order[k+1L]<-temp};schedule[[match(path,names(schedule))]]<-sort(order[seq_len(max(1L,floor(sqrt(p))))])};schedules[[member]]<-schedule};list(draws=draws,schedules=schedules)}\nread_sources<-function(src){read<-function(name)read.csv(file.path(src,name),check.names=FALSE,colClasses='character',na.strings=character(),fileEncoding='UTF-8-BOM');raw<-read('actual320-country-four-indicators-original-2020-2024.csv');country<-do.call(rbind,lapply(sort(unique(raw$countryISO3)),function(code)do.call(rbind,lapply(2020:2024,function(year){keys<-c('NY.GDP.PCAP.KD','NY.GDP.MKTP.KD.ZG','FP.CPI.TOTL.ZG','SP.DYN.LE00.IN');v<-vapply(keys,function(k)as.numeric(raw$originalValueToken[raw$countryISO3==code&raw$date==as.character(year)&raw$indicatorID==k]),0);data.frame(id=paste0(code,':',year),sourceRow=paste0(code,':',year),originalID=code,year=year,x0=v[1]/10000,x1=v[2],x2=v[3],y=v[4],weight=1,role=if(anyNA(v))'excluded'else if(year==2024)'outer-test'else'train')}))));raw<-read('actual3613-NLS-original52-fields-and-selection.csv');i<-seq_len(nrow(raw));x0<-suppressWarnings(as.numeric(raw$ed76));x1<-suppressWarnings(as.numeric(raw$age76));y<-suppressWarnings(as.numeric(raw$wage76))/100;person<-data.frame(id=paste0('person:',i),sourceRow=as.character(i),originalID=raw$id,x0=x0,x1=x1,y=y,weight=1,role=ifelse(is.na(x0)|is.na(x1)|is.na(y),'excluded',ifelse(i%%5==0,'outer-test','train')));raw<-read('actual3150-churn-original14-fields-and-selection.csv');i<-seq_len(nrow(raw));company<-data.frame(id=paste0('customer:',i),sourceRow=as.character(i),originalID='',x0=as.numeric(raw[['Call  Failure']]),x1=as.numeric(raw[['Subscription  Length']]),x2=as.numeric(raw[['Charge  Amount']]),y=raw$Churn,weight=1,role=ifelse(i%%5==0,'outer-test','train'));models<-list();for(index in 1:3){kind<-c('country','person','company')[index];d<-list(country,person,company)[[index]];task<-if(kind=='company')'classification'else'regression';s<-fixed_schedules(d$id[d$role=='train'],if(kind=='person')2L else 3L,20261102+7919*(index-1L));models[[kind]]<-list(records=d,task=task,classes=if(task=='classification')c('0','1')else character(),draws=s$draws,schedules=s$schedules,minLeaf=c(4L,50L,30L)[index])};models}\nrealdata<-function(models,kind,options=list()){if(is.null(options)||!is.list(options))stop('options object');m<-models[[kind]];d<-m$records;train<-d[d$role=='train',,drop=FALSE];test<-d[d$role=='outer-test',,drop=FALSE];method<-option(options,'method','forest');depth<-option(options,'maxDepth',2);count<-option(options,'memberCount',3);if(!method%in%c('bagging','forest','boost'))stop('known method');a<-list(rows=train,queries=test,task=m$task,classes=m$classes,maxDepth=depth,minLeaf=option(options,'minLeaf',m$minLeaf),minLeafWeight=0,minGain=0,missingRoute='best',learningRate=option(options,'learningRate','1/2'),stages=option(options,'stages',3));if(method=='boost')result<-boost(a)else{a$bootstrapDraws<-m$draws[seq_len(count)];a$nodeFeatures<-lapply(m$schedules[seq_len(count)],function(s)s[nchar(names(s))<depth]);result<-ensemble(a,method=='forest')};outer<-scored(result$predictions,normrows(test,m$task),m$task,m$classes);st<-stat(normrows(train,m$task),m$task,m$classes);constant<-list(prediction=st$pred,probabilities=st$p,vote=st$pred,prob=st$pred);baseline<-scored(lapply(test$id,function(id)c(list(id=id),constant)),normrows(test,m$task),m$task,m$classes);list(kind=kind,method=method,settings=a,train=train,test=test,result=result,outer=outer,baseline=baseline)}\nAPI<-\"bagging\"\nINPUT<-list(rows=data.frame(id=c(\"a\",\"b\",\"c\",\"d\"),y=c(0,1,3,4),x0=c(0,1,2,3),x1=c(0,1,0,1),stringsAsFactors=FALSE),queries=data.frame(id=c(\"q\"),x0=c(num(\"3/2\")),x1=c(0),stringsAsFactors=FALSE),bootstrapDraws=list(c(\"a\",\"a\",\"b\",\"c\"),c(\"b\",\"c\",\"d\",\"d\")),maxDepth=2)\n\nrun_fixed<-function(api,a,out,src){\n r<-if(api=='variance')variance(a)else if(api=='aggregate')aggregate(a)else if(api%in%c('bagging','forest'))ensemble(a,api=='forest')else if(api=='boost')boost(a)else realdata(read_sources(src),a$kind)\n dir.create(out,recursive=TRUE,showWarnings=FALSE);summary<-list();points<-list();add<-function(x,y,s){if(!is.null(y)&&!is.na(y))points[[length(points)+1L]]<<-data.frame(x=x,y=as.numeric(y),series=s)}\n if(api=='variance'){summary<-r[c('B','varianceOfMean')];add(r$B,r$varianceOfMean,'Specified finite-B variance');xl<-'Number of members B';yl<-'Variance, stipulated units squared';title<-'Declared covariance model, not fitted trees'\n }else if(api=='aggregate'){p<-r$predictions[[1]];summary<-list(selectedPrediction=p$prediction);classification<-identical(a$task,'classification');if(classification){summary<-c(summary,list(voteLabel=p$vote,probabilityLabel=p$prob,meanProbability1=p$probabilities[2]));add(1,p$probabilities[2],'Mean probability of class 1');add(2,p$votes[2],'Label-vote share of class 1');xl<-'Aggregation (1=probability, 2=vote)';yl<-'Probability or vote share'}else{for(i in seq_along(a$members))add(i,num(a$members[[i]]$predictions$value[1]),'Member prediction');add(3,p$prediction,'Weighted mean');xl<-'Member 1, member 2, aggregate 3';yl<-'Prediction, assumed units'};title<-'Votes and probabilities are distinct objects'\n }else if(api%in%c('bagging','forest')){summary<-list(queryPrediction=r$predictions[[1]]$prediction,OOB.scoreable=r$outOfBag$eligibleRows,OOB.meanLoss=r$outOfBag$meanLoss);for(i in seq_len(nrow(a$rows)))add(i,a$rows$y[i],'Observed training outcome');for(i in seq_along(r$outOfBag$rows))add(i,r$outOfBag$rows[[i]]$prediction,'OOB prediction, when defined');xl<-'Original training ID order';yl<-'Outcome, assumed units';title<-'Repeated draws and ID-level OOB membership'\n }else if(api=='boost'){summary<-list(initial=r$initial,finalMSE=r$losses[[length(r$losses)]]$MSE,stages=r$stages);for(v in r$losses)add(v$stage,v$MSE,'Training MSE');xl<-'Boosting stage (0=initial)';yl<-'Weighted MSE, outcome units squared';title<-'Training descent does not certify held-out gain'\n }else{summary<-list(outer.scoreable=r$outer$eligibleRows,outer.meanLoss=r$outer$meanLoss,baseline.meanLoss=r$baseline$meanLoss,OOB.scoreable=r$result$outOfBag$eligibleRows,OOB.meanLoss=r$result$outOfBag$meanLoss);for(i in seq_along(r$outer$rows)){p<-r$outer$rows[[i]];add(i,as.numeric(p$actual),'Observed outcome');add(i,if(a$kind=='company')p$probabilities[2]else p$prediction,if(a$kind=='company')'Forest probability of class 1'else'Forest prediction')};xl<-'Outer-test source order, not a time path';yl<-if(a$kind=='company')'Churn label / probability'else if(a$kind=='country')'Period life expectancy, years'else'Nominal 1976 USD per hour';title<-'Fixed forest; outer labels did not fit the trees'}\n display<-function(v)if(is.null(v)||is.na(v))'undefined'else sprintf('%.9f',as.numeric(v));write.csv(data.frame(metric=names(summary),value=vapply(summary,display,'')),file.path(out,'summary.csv'),row.names=FALSE);pp<-do.call(rbind,points);write.csv(pp,file.path(out,'plot-points.csv'),row.names=FALSE);dput(r,file.path(out,'full-result.Rtext'));svg(file.path(out,'plot.svg'),width=5.6,height=4.6,pointsize=14);par(mar=c(5.8,5.8,5.3,1.2),mgp=c(3.7,1,0));xr<-range(pp$x);yr<-range(pp$y);if(diff(xr)==0)xr<-xr+c(-.5,.5);if(diff(yr)==0)yr<-yr+c(-.5,.5);plot(xr,yr,type='n',xlab=xl,ylab=yl,cex.lab=.78,axes=FALSE);axis(1,at=pretty(xr,3));axis(2,at=pretty(yr,4),las=1,cex.axis=.82);box();grid(col='#dddddd');cols<-c('#355c72','#a55336','#507956','#78568b');ss<-unique(pp$series);for(i in seq_along(ss)){v<-pp[pp$series==ss[i],];points(v$x,v$y,pch=16,cex=if(nrow(v)>100).35 else .85,col=adjustcolor(cols[i],if(nrow(v)>100).5 else 1))};legend('topleft',legend=ss,col=cols[seq_along(ss)],lty=0,pch=16,cex=.65,bty='n',inset=c(0,-.32),xpd=NA);mtext(title,side=3,line=3.9,cex=.6);dev.off();cat(paste(names(summary),vapply(summary,display,''),sep='=',collapse=', '),'\\n')\n}\nargs<-commandArgs(trailingOnly=TRUE)\ntryCatch(run_fixed(API,INPUT,if(length(args))args[1]else'fixed-results',if(length(args)>1)args[2]else'ml09-sources'),error=function(e){cat('Rejected declared input: ',conditionMessage(e),'\\n',file=stderr());quit(status=2)})\n",
        "inputFiles": [],
        "input": {
          "rows": [
            {
              "id": "a",
              "x": [
                0,
                0
              ],
              "y": 0
            },
            {
              "id": "b",
              "x": [
                1,
                1
              ],
              "y": 1
            },
            {
              "id": "c",
              "x": [
                2,
                0
              ],
              "y": 3
            },
            {
              "id": "d",
              "x": [
                3,
                1
              ],
              "y": 4
            }
          ],
          "queries": [
            {
              "id": "q",
              "x": [
                "3/2",
                0
              ]
            }
          ],
          "bootstrapDraws": [
            [
              "a",
              "a",
              "b",
              "c"
            ],
            [
              "b",
              "c",
              "d",
              "d"
            ]
          ],
          "maxDepth": 2
        },
        "returnCode": 0,
        "expectedFailure": false,
        "stdout": "queryPrediction=1.000000000, OOB.scoreable=2.000000000, OOB.meanLoss=1.000000000 \n",
        "stderr": "During startup - Warning messages:\n1: Setting LC_COLLATE=C.UTF-8 failed \n2: Setting LC_CTYPE=C.UTF-8 failed \n3: Setting LC_MONETARY=C.UTF-8 failed \n4: Setting LC_TIME=C.UTF-8 failed \n",
        "summary": {
          "queryPrediction": "1.000000000",
          "OOB.scoreable": "2.000000000",
          "OOB.meanLoss": "1.000000000"
        },
        "plotPoints": [
          {
            "x": "1",
            "y": "0",
            "series": "Observed training outcome"
          },
          {
            "x": "2",
            "y": "1",
            "series": "Observed training outcome"
          },
          {
            "x": "3",
            "y": "3",
            "series": "Observed training outcome"
          },
          {
            "x": "4",
            "y": "4",
            "series": "Observed training outcome"
          },
          {
            "x": "1",
            "y": "1",
            "series": "OOB prediction, when defined"
          },
          {
            "x": "4",
            "y": "3",
            "series": "OOB prediction, when defined"
          }
        ],
        "plotFile": "ml09-fixed-results/bagging-repeated-occurrences-r/plot.svg",
        "plotSHA256": "b13d88c221f12055e6b08082c0c5611ccb22aeedd860685200892f941aaf1dfa",
        "files": [
          {
            "file": "ml09-fixed-results/bagging-repeated-occurrences-r/full-result.Rtext",
            "sha256": "c585944c85a7ef6e9c3eececc403aee8430f2d47c5535a734c74825a8e0ed5aa"
          },
          {
            "file": "ml09-fixed-results/bagging-repeated-occurrences-r/plot-points.csv",
            "sha256": "1a29a1703495f2e4e66ea508ac29c533607ce094a126e0d4efd030453c5f0459"
          },
          {
            "file": "ml09-fixed-results/bagging-repeated-occurrences-r/plot.svg",
            "sha256": "b13d88c221f12055e6b08082c0c5611ccb22aeedd860685200892f941aaf1dfa"
          },
          {
            "file": "ml09-fixed-results/bagging-repeated-occurrences-r/summary.csv",
            "sha256": "2e4d3f110fc448e27313239efee3fe1e673050b99f83d25637cbad066bd9e142"
          }
        ],
        "scope": "Actually executed self-contained fixed example; current web controls execute separately. Python Fraction and finite-precision base R. Author gate, not independent peer."
      },
      "no-OOB-members": {
        "api": "bagging",
        "variant": "no-OOB-members",
        "language": "r",
        "codeFile": "ml09-code/bagging-no-OOB-members.R",
        "codeSHA256": "6fd455f09a34ecc6df16c503b7867966693b28e458fed892f8e78d937e252ea3",
        "codeText": "# ML09 base-R reproduction from native original-field CSVs.\n# Rscript ml09-public-analysis.R ml09-sources results-r\n# Separately written vectorized direct-centered squared/Gini losses.\n# No Python/JS/model-contract/stored-answer/derived-result reader or package.\n# Numeric arithmetic is binary64:1e-12 relative tie tolerance stabilizes exact\n# source ties,but does not certify tiny margins/underflow like Fraction JS/Python.\n# Data-frame rows use x0,x1,...,y,weight; original IDs remain attached to draws.\noptions(stringsAsFactors=FALSE,digits=17)\nnum<-function(v){if(is.null(v)||length(v)!=1||is.na(v))stop('numeric parameter required, not explicit NULL');p<-strsplit(as.character(v),'/',fixed=TRUE)[[1]];z<-if(length(p)==2)as.numeric(p[1])/as.numeric(p[2])else as.numeric(v);if(!is.finite(z))stop('finite numeric parameter');z}\noption<-function(a,k,default){if(k%in%names(a))a[[k]]else default}\nnormrows<-function(d,task){if(!'weight'%in%names(d))d$weight<-1;if(!'id'%in%names(d))d$id<-as.character(seq_len(nrow(d))-1);d$weight<-as.numeric(d$weight);if(anyNA(d$weight)||any(d$weight<0))stop('nonnegative weights');if(task=='regression')d$y<-as.numeric(d$y)else d$y<-as.character(d$y);d}\nstat<-function(d,task,classes){W<-sum(d$weight);mu<-if(task=='regression'&&W)sum(d$weight*d$y)/W else NA_real_;p<-if(task=='classification'&&W)vapply(classes,function(c)sum(d$weight[d$y==c])/W,0)else numeric();risk<-if(task=='regression'&&W)sum(d$weight*(d$y-mu)^2)else W*sum(p*(1-p));list(n=nrow(d),w=W,mu=mu,p=unname(p),risk=risk,pred=if(task=='regression')mu else if(W)classes[which.max(p)]else NA_character_)}\nfit<-function(d,a,task,classes,schedule=NULL){d<-d[d$weight>0&!is.na(d$y),,drop=FALSE];if(!nrow(d))stop('positive observed training');W<-sum(d$weight);depth<-option(a,'maxDepth',2);minimum<-option(a,'minLeaf',1);minmass<-num(option(a,'minLeafWeight',0));mingain<-num(option(a,'minGain',0));route<-option(a,'missingRoute','best');features<-grep('^x[0-9]+$',names(d),value=TRUE)\n build<-function(rr,level,path){st<-stat(rr,task,classes);node<-list(rows=rr,st=st,split=NULL,left=NULL,right=NULL,path=path);if(level==depth)return(node);best<-NULL;allowed<-if(is.null(schedule))seq_along(features)-1L else schedule[[match(path,names(schedule))]]\n  for(j in seq_along(features)-1L){if(!j%in%allowed)next;v<-rr[[features[j+1L]]];values<-sort(unique(v[!is.na(v)]));candidates<-list()\n   if(length(values)>1)for(k in seq_len(length(values)-1L)){threshold<-(values[k]+values[k+1L])/2;missing<-is.na(v);left<-!missing&v<=threshold;right<-!missing&v>threshold;directions<-if(route!='best')route else if(any(missing))c('left','right')else if(sum(left)>=sum(right))'left'else'right';for(direction in directions)candidates[[length(candidates)+1L]]<-list(kind='threshold',threshold=threshold,missingRoute=direction,left=if(direction=='left')left|missing else left,right=if(direction=='right')right|missing else right)}\n   if(anyNA(v)&&any(!is.na(v)))candidates[[length(candidates)+1L]]<-list(kind='missing-only',threshold=NA_real_,missingRoute='left',left=is.na(v),right=!is.na(v))\n   for(candidate in candidates){l<-rr[candidate$left,,drop=FALSE];r<-rr[candidate$right,,drop=FALSE];ls<-stat(l,task,classes);rs<-stat(r,task,classes);if(min(ls$n,rs$n)<minimum||min(ls$w,rs$w)<minmass||min(ls$w,rs$w)<=0)next;gain<-(st$risk-ls$risk-rs$risk)/W;tol<-1e-12*max(1,abs(gain),if(is.null(best))0 else abs(best$gain));if(is.null(best)||gain>best$gain+tol)best<-c(candidate,list(feature=j,gain=gain,l=l,r=r))}\n  }\n  if(!is.null(best)&&best$gain>max(mingain,1e-12)){node$split<-best;node$left<-build(best$l,level+1L,paste0(path,'L'));node$right<-build(best$r,level+1L,paste0(path,'R'))};node\n };build(d,0L,'')\n}\npredict_one<-function(tree,row){n<-tree;while(!is.null(n$split)){s<-n$split;v<-as.numeric(row[[paste0('x',s$feature)]]);left<-if(s$kind=='missing-only')is.na(v)else if(is.na(v))s$missingRoute=='left'else v<=s$threshold;n<-if(left)n$left else n$right};list(prediction=n$st$pred,probabilities=n$st$p)}\ncombine<-function(pp,w,task,classes,mode='probabilities'){W<-sum(w);if(!length(pp)||!W)return(list(prediction=if(task=='regression')NA_real_ else NA_character_,probabilities=numeric(),vote=NA_character_,prob=NA_character_));if(task=='regression')return(list(prediction=sum(vapply(pp,function(p)p$prediction,0)*w)/W,probabilities=numeric(),vote=NA_character_,prob=NA_character_));votes<-vapply(classes,function(c)sum(w[vapply(pp,function(p)p$prediction==c,FALSE)])/W,0);probs<-vapply(seq_along(classes),function(j)sum(vapply(pp,function(p)p$probabilities[j],0)*w)/W,0);vote<-classes[which.max(votes)];prob<-classes[which.max(probs)];list(prediction=if(mode=='votes')vote else prob,probabilities=unname(probs),vote=vote,prob=prob,votes=unname(votes))}\nvariance<-function(a){B<-num(a$B);v<-num(a$marginalVariance);rho<-num(option(a,'rho',0));if(B<1||B!=floor(B)||v<0)stop('integer B/nonnegative variance');if(B>1&&v>0&&(rho< -1/(B-1)||rho>1))stop('PSD correlation');list(B=B,marginalVariance=v,correlationApplicable=B>1&&v>0,varianceOfMean=if(B==1)v else v*(1+(B-1)*rho)/B)}\naggregate<-function(a){task<-option(a,'task','regression');classes<-option(a,'classes',character());w<-vapply(option(a,'memberWeights',as.list(rep(1,length(a$members)))),num,0);if(any(w<0)||sum(w)<=0)stop('positive member mass');ids<-a$members[[1]]$predictions$id;pp<-lapply(ids,function(id){members<-lapply(a$members,function(m){r<-m$predictions[match(id,m$predictions$id),,drop=FALSE];if(task=='regression')list(prediction=num(r$value),probabilities=numeric())else list(prediction=as.character(r$label),probabilities=as.numeric(r[paste0('p',seq_along(classes)-1L)]))});c(list(id=id),combine(members,w,task,classes,option(a,'aggregation','probabilities')))});list(task=task,classes=classes,predictions=pp)}\nscored<-function(preds,d,task,classes){W<-loss<-absolute<-errors<-voteerrors<-0;count<-0L;out<-lapply(seq_len(nrow(d)),function(i){r<-d[i,,drop=FALSE];p<-preds[[i]];ok<-!is.na(p$prediction)&&!is.na(r$y)&&r$weight>0;value<-NA_real_;if(ok){count<<-count+1L;W<<-W+r$weight;if(task=='regression'){e<-r$y-p$prediction;value<-e*e;absolute<<-absolute+r$weight*abs(e)}else{value<-sum((p$probabilities-as.numeric(classes==r$y))^2);errors<<-errors+r$weight*(p$prediction!=r$y);voteerrors<<-voteerrors+r$weight*(p$vote!=r$y)};loss<<-loss+r$weight*value};c(p,list(actual=r$y,weight=r$weight,scoreEligible=ok,loss=value))});list(rows=out,eligibleRows=count,weight=W,totalLoss=loss,meanLoss=if(W)loss/W else NA_real_,MAE=if(W&&task=='regression')absolute/W else NA_real_,errorRate=if(W&&task=='classification')errors/W else NA_real_,labelVoteErrorRate=if(W&&task=='classification')voteerrors/W else NA_real_)}\nensemble<-function(a,forest=FALSE){task<-option(a,'task','regression');classes<-option(a,'classes',character());d<-normrows(a$rows,task);w<-vapply(option(a,'memberWeights',as.list(rep(1,length(a$bootstrapDraws)))),num,0);if(any(w<0)||sum(w)<=0)stop('positive member mass');members<-lapply(seq_along(a$bootstrapDraws),function(i){draw<-a$bootstrapDraws[[i]];indices<-match(draw,d$id);if(anyNA(indices))stop('unknown draw source');tree<-fit(d[indices,,drop=FALSE],a,task,classes,if(forest)a$nodeFeatures[[i]]else NULL);list(tree=tree,draw=draw,inbag=unique(draw),weight=w[i])});queries<-a$queries;preds<-lapply(seq_len(nrow(queries)),function(i)c(list(id=queries$id[i]),combine(lapply(members,function(m)predict_one(m$tree,queries[i,,drop=FALSE])),w,task,classes,option(a,'aggregation','probabilities'))));oob<-lapply(seq_len(nrow(d)),function(i){app<-which(!vapply(members,function(m)d$id[i]%in%m$inbag,FALSE));pp<-combine(lapply(app,function(j)predict_one(members[[j]]$tree,d[i,,drop=FALSE])),w[app],task,classes,option(a,'aggregation','probabilities'));c(list(id=d$id[i],applicable=app-1L,positiveMembers=sum(w[app]>0)),pp)});list(task=task,classes=classes,members=members,predictions=preds,outOfBag=scored(oob,d,task,classes))}\nboost<-function(a){if(option(a,'task','regression')!='regression')stop('regression boosting only');d<-normrows(a$rows,'regression');eligible<-d$weight>0&!is.na(d$y);W<-sum(d$weight[eligible]);if(!W)stop('positive eligible training');eta<-num(option(a,'learningRate','1/2'));stages<-option(a,'stages',3);if(is.null(stages)||stages!=floor(stages)||stages<0||stages>8||eta<0||eta>1)stop('supported rate/stages');initial<-if('initial'%in%names(a))num(a$initial)else sum(d$weight[eligible]*d$y[eligible])/W;train<-matrix(initial,nrow(d),stages+1L);query<-matrix(initial,nrow(a$queries),stages+1L);losses<-fits<-list();for(stage in 0:stages){sse<-sum(d$weight[eligible]*(d$y[eligible]-train[eligible,stage+1L])^2);losses[[stage+1L]]<-list(stage=stage,rawWeightedSSE=sse,MSE=sse/W,meanHalfSquaredLoss=sse/(2*W));if(stage==stages)break;residual<-d;residual$y<-d$y-train[,stage+1L];tree<-fit(residual,a,'regression',character());h<-vapply(seq_len(nrow(d)),function(i)predict_one(tree,d[i,,drop=FALSE])$prediction,0);qh<-vapply(seq_len(nrow(a$queries)),function(i)predict_one(tree,a$queries[i,,drop=FALSE])$prediction,0);stageRows<-lapply(seq_len(nrow(d)),function(i)list(id=d$id[i],before=train[i,stage+1L],residual=residual$y[i],negativeCoordinateDerivative=d$weight[i]*residual$y[i]/W,fit=h[i],addition=eta*h[i],after=train[i,stage+1L]+eta*h[i]));train[,stage+2L]<-train[,stage+1L]+eta*h;query[,stage+2L]<-query[,stage+1L]+eta*qh;norm<-sum(d$weight[eligible]*h[eligible]^2);fits[[stage+1L]]<-list(stage=stage+1L,tree=tree,rows=stageRows,queryFits=qh,norm=norm,predictedSSEDecrease=eta*(2-eta)*norm)};list(task='regression',initial=initial,learningRate=eta,stages=stages,training=train,queries=query,fits=fits,losses=losses,predictions=lapply(seq_len(nrow(a$queries)),function(i)list(id=a$queries$id[i],prediction=query[i,stages+1L],probabilities=numeric(),vote=NA_character_,prob=NA_character_)))}\nfixed_schedules<-function(ids,p,seed){state<-seed;choose<-function(n){limit<-floor(4294967296/n)*n;repeat{state<<-(1664525*state+1013904223)%%4294967296;if(state<limit)return(as.integer(state%%n))}};draws<-schedules<-list();for(member in 1:4){draws[[member]]<-vapply(seq_along(ids),function(i)ids[choose(length(ids))+1L],'');schedule<-setNames(vector('list',7),c('','L','R','LL','LR','RL','RR'));for(path in names(schedule)){order<-seq_len(p)-1L;if(p>1)for(j in seq(p-1L,1L)){k<-choose(j+1L);temp<-order[j+1L];order[j+1L]<-order[k+1L];order[k+1L]<-temp};schedule[[match(path,names(schedule))]]<-sort(order[seq_len(max(1L,floor(sqrt(p))))])};schedules[[member]]<-schedule};list(draws=draws,schedules=schedules)}\nread_sources<-function(src){read<-function(name)read.csv(file.path(src,name),check.names=FALSE,colClasses='character',na.strings=character(),fileEncoding='UTF-8-BOM');raw<-read('actual320-country-four-indicators-original-2020-2024.csv');country<-do.call(rbind,lapply(sort(unique(raw$countryISO3)),function(code)do.call(rbind,lapply(2020:2024,function(year){keys<-c('NY.GDP.PCAP.KD','NY.GDP.MKTP.KD.ZG','FP.CPI.TOTL.ZG','SP.DYN.LE00.IN');v<-vapply(keys,function(k)as.numeric(raw$originalValueToken[raw$countryISO3==code&raw$date==as.character(year)&raw$indicatorID==k]),0);data.frame(id=paste0(code,':',year),sourceRow=paste0(code,':',year),originalID=code,year=year,x0=v[1]/10000,x1=v[2],x2=v[3],y=v[4],weight=1,role=if(anyNA(v))'excluded'else if(year==2024)'outer-test'else'train')}))));raw<-read('actual3613-NLS-original52-fields-and-selection.csv');i<-seq_len(nrow(raw));x0<-suppressWarnings(as.numeric(raw$ed76));x1<-suppressWarnings(as.numeric(raw$age76));y<-suppressWarnings(as.numeric(raw$wage76))/100;person<-data.frame(id=paste0('person:',i),sourceRow=as.character(i),originalID=raw$id,x0=x0,x1=x1,y=y,weight=1,role=ifelse(is.na(x0)|is.na(x1)|is.na(y),'excluded',ifelse(i%%5==0,'outer-test','train')));raw<-read('actual3150-churn-original14-fields-and-selection.csv');i<-seq_len(nrow(raw));company<-data.frame(id=paste0('customer:',i),sourceRow=as.character(i),originalID='',x0=as.numeric(raw[['Call  Failure']]),x1=as.numeric(raw[['Subscription  Length']]),x2=as.numeric(raw[['Charge  Amount']]),y=raw$Churn,weight=1,role=ifelse(i%%5==0,'outer-test','train'));models<-list();for(index in 1:3){kind<-c('country','person','company')[index];d<-list(country,person,company)[[index]];task<-if(kind=='company')'classification'else'regression';s<-fixed_schedules(d$id[d$role=='train'],if(kind=='person')2L else 3L,20261102+7919*(index-1L));models[[kind]]<-list(records=d,task=task,classes=if(task=='classification')c('0','1')else character(),draws=s$draws,schedules=s$schedules,minLeaf=c(4L,50L,30L)[index])};models}\nrealdata<-function(models,kind,options=list()){if(is.null(options)||!is.list(options))stop('options object');m<-models[[kind]];d<-m$records;train<-d[d$role=='train',,drop=FALSE];test<-d[d$role=='outer-test',,drop=FALSE];method<-option(options,'method','forest');depth<-option(options,'maxDepth',2);count<-option(options,'memberCount',3);if(!method%in%c('bagging','forest','boost'))stop('known method');a<-list(rows=train,queries=test,task=m$task,classes=m$classes,maxDepth=depth,minLeaf=option(options,'minLeaf',m$minLeaf),minLeafWeight=0,minGain=0,missingRoute='best',learningRate=option(options,'learningRate','1/2'),stages=option(options,'stages',3));if(method=='boost')result<-boost(a)else{a$bootstrapDraws<-m$draws[seq_len(count)];a$nodeFeatures<-lapply(m$schedules[seq_len(count)],function(s)s[nchar(names(s))<depth]);result<-ensemble(a,method=='forest')};outer<-scored(result$predictions,normrows(test,m$task),m$task,m$classes);st<-stat(normrows(train,m$task),m$task,m$classes);constant<-list(prediction=st$pred,probabilities=st$p,vote=st$pred,prob=st$pred);baseline<-scored(lapply(test$id,function(id)c(list(id=id),constant)),normrows(test,m$task),m$task,m$classes);list(kind=kind,method=method,settings=a,train=train,test=test,result=result,outer=outer,baseline=baseline)}\nAPI<-\"bagging\"\nINPUT<-list(rows=data.frame(id=c(\"a\",\"b\",\"c\",\"d\"),y=c(0,1,3,4),x0=c(0,1,2,3),x1=c(0,1,0,1),stringsAsFactors=FALSE),queries=data.frame(id=c(\"q\"),x0=c(num(\"3/2\")),x1=c(0),stringsAsFactors=FALSE),bootstrapDraws=list(c(\"a\",\"b\",\"c\",\"d\"),c(\"a\",\"b\",\"c\",\"d\")),maxDepth=2)\n\nrun_fixed<-function(api,a,out,src){\n r<-if(api=='variance')variance(a)else if(api=='aggregate')aggregate(a)else if(api%in%c('bagging','forest'))ensemble(a,api=='forest')else if(api=='boost')boost(a)else realdata(read_sources(src),a$kind)\n dir.create(out,recursive=TRUE,showWarnings=FALSE);summary<-list();points<-list();add<-function(x,y,s){if(!is.null(y)&&!is.na(y))points[[length(points)+1L]]<<-data.frame(x=x,y=as.numeric(y),series=s)}\n if(api=='variance'){summary<-r[c('B','varianceOfMean')];add(r$B,r$varianceOfMean,'Specified finite-B variance');xl<-'Number of members B';yl<-'Variance, stipulated units squared';title<-'Declared covariance model, not fitted trees'\n }else if(api=='aggregate'){p<-r$predictions[[1]];summary<-list(selectedPrediction=p$prediction);classification<-identical(a$task,'classification');if(classification){summary<-c(summary,list(voteLabel=p$vote,probabilityLabel=p$prob,meanProbability1=p$probabilities[2]));add(1,p$probabilities[2],'Mean probability of class 1');add(2,p$votes[2],'Label-vote share of class 1');xl<-'Aggregation (1=probability, 2=vote)';yl<-'Probability or vote share'}else{for(i in seq_along(a$members))add(i,num(a$members[[i]]$predictions$value[1]),'Member prediction');add(3,p$prediction,'Weighted mean');xl<-'Member 1, member 2, aggregate 3';yl<-'Prediction, assumed units'};title<-'Votes and probabilities are distinct objects'\n }else if(api%in%c('bagging','forest')){summary<-list(queryPrediction=r$predictions[[1]]$prediction,OOB.scoreable=r$outOfBag$eligibleRows,OOB.meanLoss=r$outOfBag$meanLoss);for(i in seq_len(nrow(a$rows)))add(i,a$rows$y[i],'Observed training outcome');for(i in seq_along(r$outOfBag$rows))add(i,r$outOfBag$rows[[i]]$prediction,'OOB prediction, when defined');xl<-'Original training ID order';yl<-'Outcome, assumed units';title<-'Repeated draws and ID-level OOB membership'\n }else if(api=='boost'){summary<-list(initial=r$initial,finalMSE=r$losses[[length(r$losses)]]$MSE,stages=r$stages);for(v in r$losses)add(v$stage,v$MSE,'Training MSE');xl<-'Boosting stage (0=initial)';yl<-'Weighted MSE, outcome units squared';title<-'Training descent does not certify held-out gain'\n }else{summary<-list(outer.scoreable=r$outer$eligibleRows,outer.meanLoss=r$outer$meanLoss,baseline.meanLoss=r$baseline$meanLoss,OOB.scoreable=r$result$outOfBag$eligibleRows,OOB.meanLoss=r$result$outOfBag$meanLoss);for(i in seq_along(r$outer$rows)){p<-r$outer$rows[[i]];add(i,as.numeric(p$actual),'Observed outcome');add(i,if(a$kind=='company')p$probabilities[2]else p$prediction,if(a$kind=='company')'Forest probability of class 1'else'Forest prediction')};xl<-'Outer-test source order, not a time path';yl<-if(a$kind=='company')'Churn label / probability'else if(a$kind=='country')'Period life expectancy, years'else'Nominal 1976 USD per hour';title<-'Fixed forest; outer labels did not fit the trees'}\n display<-function(v)if(is.null(v)||is.na(v))'undefined'else sprintf('%.9f',as.numeric(v));write.csv(data.frame(metric=names(summary),value=vapply(summary,display,'')),file.path(out,'summary.csv'),row.names=FALSE);pp<-do.call(rbind,points);write.csv(pp,file.path(out,'plot-points.csv'),row.names=FALSE);dput(r,file.path(out,'full-result.Rtext'));svg(file.path(out,'plot.svg'),width=5.6,height=4.6,pointsize=14);par(mar=c(5.8,5.8,5.3,1.2),mgp=c(3.7,1,0));xr<-range(pp$x);yr<-range(pp$y);if(diff(xr)==0)xr<-xr+c(-.5,.5);if(diff(yr)==0)yr<-yr+c(-.5,.5);plot(xr,yr,type='n',xlab=xl,ylab=yl,cex.lab=.78,axes=FALSE);axis(1,at=pretty(xr,3));axis(2,at=pretty(yr,4),las=1,cex.axis=.82);box();grid(col='#dddddd');cols<-c('#355c72','#a55336','#507956','#78568b');ss<-unique(pp$series);for(i in seq_along(ss)){v<-pp[pp$series==ss[i],];points(v$x,v$y,pch=16,cex=if(nrow(v)>100).35 else .85,col=adjustcolor(cols[i],if(nrow(v)>100).5 else 1))};legend('topleft',legend=ss,col=cols[seq_along(ss)],lty=0,pch=16,cex=.65,bty='n',inset=c(0,-.32),xpd=NA);mtext(title,side=3,line=3.9,cex=.6);dev.off();cat(paste(names(summary),vapply(summary,display,''),sep='=',collapse=', '),'\\n')\n}\nargs<-commandArgs(trailingOnly=TRUE)\ntryCatch(run_fixed(API,INPUT,if(length(args))args[1]else'fixed-results',if(length(args)>1)args[2]else'ml09-sources'),error=function(e){cat('Rejected declared input: ',conditionMessage(e),'\\n',file=stderr());quit(status=2)})\n",
        "code": "# ML09 base-R reproduction from native original-field CSVs.\n# Rscript ml09-public-analysis.R ml09-sources results-r\n# Separately written vectorized direct-centered squared/Gini losses.\n# No Python/JS/model-contract/stored-answer/derived-result reader or package.\n# Numeric arithmetic is binary64:1e-12 relative tie tolerance stabilizes exact\n# source ties,but does not certify tiny margins/underflow like Fraction JS/Python.\n# Data-frame rows use x0,x1,...,y,weight; original IDs remain attached to draws.\noptions(stringsAsFactors=FALSE,digits=17)\nnum<-function(v){if(is.null(v)||length(v)!=1||is.na(v))stop('numeric parameter required, not explicit NULL');p<-strsplit(as.character(v),'/',fixed=TRUE)[[1]];z<-if(length(p)==2)as.numeric(p[1])/as.numeric(p[2])else as.numeric(v);if(!is.finite(z))stop('finite numeric parameter');z}\noption<-function(a,k,default){if(k%in%names(a))a[[k]]else default}\nnormrows<-function(d,task){if(!'weight'%in%names(d))d$weight<-1;if(!'id'%in%names(d))d$id<-as.character(seq_len(nrow(d))-1);d$weight<-as.numeric(d$weight);if(anyNA(d$weight)||any(d$weight<0))stop('nonnegative weights');if(task=='regression')d$y<-as.numeric(d$y)else d$y<-as.character(d$y);d}\nstat<-function(d,task,classes){W<-sum(d$weight);mu<-if(task=='regression'&&W)sum(d$weight*d$y)/W else NA_real_;p<-if(task=='classification'&&W)vapply(classes,function(c)sum(d$weight[d$y==c])/W,0)else numeric();risk<-if(task=='regression'&&W)sum(d$weight*(d$y-mu)^2)else W*sum(p*(1-p));list(n=nrow(d),w=W,mu=mu,p=unname(p),risk=risk,pred=if(task=='regression')mu else if(W)classes[which.max(p)]else NA_character_)}\nfit<-function(d,a,task,classes,schedule=NULL){d<-d[d$weight>0&!is.na(d$y),,drop=FALSE];if(!nrow(d))stop('positive observed training');W<-sum(d$weight);depth<-option(a,'maxDepth',2);minimum<-option(a,'minLeaf',1);minmass<-num(option(a,'minLeafWeight',0));mingain<-num(option(a,'minGain',0));route<-option(a,'missingRoute','best');features<-grep('^x[0-9]+$',names(d),value=TRUE)\n build<-function(rr,level,path){st<-stat(rr,task,classes);node<-list(rows=rr,st=st,split=NULL,left=NULL,right=NULL,path=path);if(level==depth)return(node);best<-NULL;allowed<-if(is.null(schedule))seq_along(features)-1L else schedule[[match(path,names(schedule))]]\n  for(j in seq_along(features)-1L){if(!j%in%allowed)next;v<-rr[[features[j+1L]]];values<-sort(unique(v[!is.na(v)]));candidates<-list()\n   if(length(values)>1)for(k in seq_len(length(values)-1L)){threshold<-(values[k]+values[k+1L])/2;missing<-is.na(v);left<-!missing&v<=threshold;right<-!missing&v>threshold;directions<-if(route!='best')route else if(any(missing))c('left','right')else if(sum(left)>=sum(right))'left'else'right';for(direction in directions)candidates[[length(candidates)+1L]]<-list(kind='threshold',threshold=threshold,missingRoute=direction,left=if(direction=='left')left|missing else left,right=if(direction=='right')right|missing else right)}\n   if(anyNA(v)&&any(!is.na(v)))candidates[[length(candidates)+1L]]<-list(kind='missing-only',threshold=NA_real_,missingRoute='left',left=is.na(v),right=!is.na(v))\n   for(candidate in candidates){l<-rr[candidate$left,,drop=FALSE];r<-rr[candidate$right,,drop=FALSE];ls<-stat(l,task,classes);rs<-stat(r,task,classes);if(min(ls$n,rs$n)<minimum||min(ls$w,rs$w)<minmass||min(ls$w,rs$w)<=0)next;gain<-(st$risk-ls$risk-rs$risk)/W;tol<-1e-12*max(1,abs(gain),if(is.null(best))0 else abs(best$gain));if(is.null(best)||gain>best$gain+tol)best<-c(candidate,list(feature=j,gain=gain,l=l,r=r))}\n  }\n  if(!is.null(best)&&best$gain>max(mingain,1e-12)){node$split<-best;node$left<-build(best$l,level+1L,paste0(path,'L'));node$right<-build(best$r,level+1L,paste0(path,'R'))};node\n };build(d,0L,'')\n}\npredict_one<-function(tree,row){n<-tree;while(!is.null(n$split)){s<-n$split;v<-as.numeric(row[[paste0('x',s$feature)]]);left<-if(s$kind=='missing-only')is.na(v)else if(is.na(v))s$missingRoute=='left'else v<=s$threshold;n<-if(left)n$left else n$right};list(prediction=n$st$pred,probabilities=n$st$p)}\ncombine<-function(pp,w,task,classes,mode='probabilities'){W<-sum(w);if(!length(pp)||!W)return(list(prediction=if(task=='regression')NA_real_ else NA_character_,probabilities=numeric(),vote=NA_character_,prob=NA_character_));if(task=='regression')return(list(prediction=sum(vapply(pp,function(p)p$prediction,0)*w)/W,probabilities=numeric(),vote=NA_character_,prob=NA_character_));votes<-vapply(classes,function(c)sum(w[vapply(pp,function(p)p$prediction==c,FALSE)])/W,0);probs<-vapply(seq_along(classes),function(j)sum(vapply(pp,function(p)p$probabilities[j],0)*w)/W,0);vote<-classes[which.max(votes)];prob<-classes[which.max(probs)];list(prediction=if(mode=='votes')vote else prob,probabilities=unname(probs),vote=vote,prob=prob,votes=unname(votes))}\nvariance<-function(a){B<-num(a$B);v<-num(a$marginalVariance);rho<-num(option(a,'rho',0));if(B<1||B!=floor(B)||v<0)stop('integer B/nonnegative variance');if(B>1&&v>0&&(rho< -1/(B-1)||rho>1))stop('PSD correlation');list(B=B,marginalVariance=v,correlationApplicable=B>1&&v>0,varianceOfMean=if(B==1)v else v*(1+(B-1)*rho)/B)}\naggregate<-function(a){task<-option(a,'task','regression');classes<-option(a,'classes',character());w<-vapply(option(a,'memberWeights',as.list(rep(1,length(a$members)))),num,0);if(any(w<0)||sum(w)<=0)stop('positive member mass');ids<-a$members[[1]]$predictions$id;pp<-lapply(ids,function(id){members<-lapply(a$members,function(m){r<-m$predictions[match(id,m$predictions$id),,drop=FALSE];if(task=='regression')list(prediction=num(r$value),probabilities=numeric())else list(prediction=as.character(r$label),probabilities=as.numeric(r[paste0('p',seq_along(classes)-1L)]))});c(list(id=id),combine(members,w,task,classes,option(a,'aggregation','probabilities')))});list(task=task,classes=classes,predictions=pp)}\nscored<-function(preds,d,task,classes){W<-loss<-absolute<-errors<-voteerrors<-0;count<-0L;out<-lapply(seq_len(nrow(d)),function(i){r<-d[i,,drop=FALSE];p<-preds[[i]];ok<-!is.na(p$prediction)&&!is.na(r$y)&&r$weight>0;value<-NA_real_;if(ok){count<<-count+1L;W<<-W+r$weight;if(task=='regression'){e<-r$y-p$prediction;value<-e*e;absolute<<-absolute+r$weight*abs(e)}else{value<-sum((p$probabilities-as.numeric(classes==r$y))^2);errors<<-errors+r$weight*(p$prediction!=r$y);voteerrors<<-voteerrors+r$weight*(p$vote!=r$y)};loss<<-loss+r$weight*value};c(p,list(actual=r$y,weight=r$weight,scoreEligible=ok,loss=value))});list(rows=out,eligibleRows=count,weight=W,totalLoss=loss,meanLoss=if(W)loss/W else NA_real_,MAE=if(W&&task=='regression')absolute/W else NA_real_,errorRate=if(W&&task=='classification')errors/W else NA_real_,labelVoteErrorRate=if(W&&task=='classification')voteerrors/W else NA_real_)}\nensemble<-function(a,forest=FALSE){task<-option(a,'task','regression');classes<-option(a,'classes',character());d<-normrows(a$rows,task);w<-vapply(option(a,'memberWeights',as.list(rep(1,length(a$bootstrapDraws)))),num,0);if(any(w<0)||sum(w)<=0)stop('positive member mass');members<-lapply(seq_along(a$bootstrapDraws),function(i){draw<-a$bootstrapDraws[[i]];indices<-match(draw,d$id);if(anyNA(indices))stop('unknown draw source');tree<-fit(d[indices,,drop=FALSE],a,task,classes,if(forest)a$nodeFeatures[[i]]else NULL);list(tree=tree,draw=draw,inbag=unique(draw),weight=w[i])});queries<-a$queries;preds<-lapply(seq_len(nrow(queries)),function(i)c(list(id=queries$id[i]),combine(lapply(members,function(m)predict_one(m$tree,queries[i,,drop=FALSE])),w,task,classes,option(a,'aggregation','probabilities'))));oob<-lapply(seq_len(nrow(d)),function(i){app<-which(!vapply(members,function(m)d$id[i]%in%m$inbag,FALSE));pp<-combine(lapply(app,function(j)predict_one(members[[j]]$tree,d[i,,drop=FALSE])),w[app],task,classes,option(a,'aggregation','probabilities'));c(list(id=d$id[i],applicable=app-1L,positiveMembers=sum(w[app]>0)),pp)});list(task=task,classes=classes,members=members,predictions=preds,outOfBag=scored(oob,d,task,classes))}\nboost<-function(a){if(option(a,'task','regression')!='regression')stop('regression boosting only');d<-normrows(a$rows,'regression');eligible<-d$weight>0&!is.na(d$y);W<-sum(d$weight[eligible]);if(!W)stop('positive eligible training');eta<-num(option(a,'learningRate','1/2'));stages<-option(a,'stages',3);if(is.null(stages)||stages!=floor(stages)||stages<0||stages>8||eta<0||eta>1)stop('supported rate/stages');initial<-if('initial'%in%names(a))num(a$initial)else sum(d$weight[eligible]*d$y[eligible])/W;train<-matrix(initial,nrow(d),stages+1L);query<-matrix(initial,nrow(a$queries),stages+1L);losses<-fits<-list();for(stage in 0:stages){sse<-sum(d$weight[eligible]*(d$y[eligible]-train[eligible,stage+1L])^2);losses[[stage+1L]]<-list(stage=stage,rawWeightedSSE=sse,MSE=sse/W,meanHalfSquaredLoss=sse/(2*W));if(stage==stages)break;residual<-d;residual$y<-d$y-train[,stage+1L];tree<-fit(residual,a,'regression',character());h<-vapply(seq_len(nrow(d)),function(i)predict_one(tree,d[i,,drop=FALSE])$prediction,0);qh<-vapply(seq_len(nrow(a$queries)),function(i)predict_one(tree,a$queries[i,,drop=FALSE])$prediction,0);stageRows<-lapply(seq_len(nrow(d)),function(i)list(id=d$id[i],before=train[i,stage+1L],residual=residual$y[i],negativeCoordinateDerivative=d$weight[i]*residual$y[i]/W,fit=h[i],addition=eta*h[i],after=train[i,stage+1L]+eta*h[i]));train[,stage+2L]<-train[,stage+1L]+eta*h;query[,stage+2L]<-query[,stage+1L]+eta*qh;norm<-sum(d$weight[eligible]*h[eligible]^2);fits[[stage+1L]]<-list(stage=stage+1L,tree=tree,rows=stageRows,queryFits=qh,norm=norm,predictedSSEDecrease=eta*(2-eta)*norm)};list(task='regression',initial=initial,learningRate=eta,stages=stages,training=train,queries=query,fits=fits,losses=losses,predictions=lapply(seq_len(nrow(a$queries)),function(i)list(id=a$queries$id[i],prediction=query[i,stages+1L],probabilities=numeric(),vote=NA_character_,prob=NA_character_)))}\nfixed_schedules<-function(ids,p,seed){state<-seed;choose<-function(n){limit<-floor(4294967296/n)*n;repeat{state<<-(1664525*state+1013904223)%%4294967296;if(state<limit)return(as.integer(state%%n))}};draws<-schedules<-list();for(member in 1:4){draws[[member]]<-vapply(seq_along(ids),function(i)ids[choose(length(ids))+1L],'');schedule<-setNames(vector('list',7),c('','L','R','LL','LR','RL','RR'));for(path in names(schedule)){order<-seq_len(p)-1L;if(p>1)for(j in seq(p-1L,1L)){k<-choose(j+1L);temp<-order[j+1L];order[j+1L]<-order[k+1L];order[k+1L]<-temp};schedule[[match(path,names(schedule))]]<-sort(order[seq_len(max(1L,floor(sqrt(p))))])};schedules[[member]]<-schedule};list(draws=draws,schedules=schedules)}\nread_sources<-function(src){read<-function(name)read.csv(file.path(src,name),check.names=FALSE,colClasses='character',na.strings=character(),fileEncoding='UTF-8-BOM');raw<-read('actual320-country-four-indicators-original-2020-2024.csv');country<-do.call(rbind,lapply(sort(unique(raw$countryISO3)),function(code)do.call(rbind,lapply(2020:2024,function(year){keys<-c('NY.GDP.PCAP.KD','NY.GDP.MKTP.KD.ZG','FP.CPI.TOTL.ZG','SP.DYN.LE00.IN');v<-vapply(keys,function(k)as.numeric(raw$originalValueToken[raw$countryISO3==code&raw$date==as.character(year)&raw$indicatorID==k]),0);data.frame(id=paste0(code,':',year),sourceRow=paste0(code,':',year),originalID=code,year=year,x0=v[1]/10000,x1=v[2],x2=v[3],y=v[4],weight=1,role=if(anyNA(v))'excluded'else if(year==2024)'outer-test'else'train')}))));raw<-read('actual3613-NLS-original52-fields-and-selection.csv');i<-seq_len(nrow(raw));x0<-suppressWarnings(as.numeric(raw$ed76));x1<-suppressWarnings(as.numeric(raw$age76));y<-suppressWarnings(as.numeric(raw$wage76))/100;person<-data.frame(id=paste0('person:',i),sourceRow=as.character(i),originalID=raw$id,x0=x0,x1=x1,y=y,weight=1,role=ifelse(is.na(x0)|is.na(x1)|is.na(y),'excluded',ifelse(i%%5==0,'outer-test','train')));raw<-read('actual3150-churn-original14-fields-and-selection.csv');i<-seq_len(nrow(raw));company<-data.frame(id=paste0('customer:',i),sourceRow=as.character(i),originalID='',x0=as.numeric(raw[['Call  Failure']]),x1=as.numeric(raw[['Subscription  Length']]),x2=as.numeric(raw[['Charge  Amount']]),y=raw$Churn,weight=1,role=ifelse(i%%5==0,'outer-test','train'));models<-list();for(index in 1:3){kind<-c('country','person','company')[index];d<-list(country,person,company)[[index]];task<-if(kind=='company')'classification'else'regression';s<-fixed_schedules(d$id[d$role=='train'],if(kind=='person')2L else 3L,20261102+7919*(index-1L));models[[kind]]<-list(records=d,task=task,classes=if(task=='classification')c('0','1')else character(),draws=s$draws,schedules=s$schedules,minLeaf=c(4L,50L,30L)[index])};models}\nrealdata<-function(models,kind,options=list()){if(is.null(options)||!is.list(options))stop('options object');m<-models[[kind]];d<-m$records;train<-d[d$role=='train',,drop=FALSE];test<-d[d$role=='outer-test',,drop=FALSE];method<-option(options,'method','forest');depth<-option(options,'maxDepth',2);count<-option(options,'memberCount',3);if(!method%in%c('bagging','forest','boost'))stop('known method');a<-list(rows=train,queries=test,task=m$task,classes=m$classes,maxDepth=depth,minLeaf=option(options,'minLeaf',m$minLeaf),minLeafWeight=0,minGain=0,missingRoute='best',learningRate=option(options,'learningRate','1/2'),stages=option(options,'stages',3));if(method=='boost')result<-boost(a)else{a$bootstrapDraws<-m$draws[seq_len(count)];a$nodeFeatures<-lapply(m$schedules[seq_len(count)],function(s)s[nchar(names(s))<depth]);result<-ensemble(a,method=='forest')};outer<-scored(result$predictions,normrows(test,m$task),m$task,m$classes);st<-stat(normrows(train,m$task),m$task,m$classes);constant<-list(prediction=st$pred,probabilities=st$p,vote=st$pred,prob=st$pred);baseline<-scored(lapply(test$id,function(id)c(list(id=id),constant)),normrows(test,m$task),m$task,m$classes);list(kind=kind,method=method,settings=a,train=train,test=test,result=result,outer=outer,baseline=baseline)}\nAPI<-\"bagging\"\nINPUT<-list(rows=data.frame(id=c(\"a\",\"b\",\"c\",\"d\"),y=c(0,1,3,4),x0=c(0,1,2,3),x1=c(0,1,0,1),stringsAsFactors=FALSE),queries=data.frame(id=c(\"q\"),x0=c(num(\"3/2\")),x1=c(0),stringsAsFactors=FALSE),bootstrapDraws=list(c(\"a\",\"b\",\"c\",\"d\"),c(\"a\",\"b\",\"c\",\"d\")),maxDepth=2)\n\nrun_fixed<-function(api,a,out,src){\n r<-if(api=='variance')variance(a)else if(api=='aggregate')aggregate(a)else if(api%in%c('bagging','forest'))ensemble(a,api=='forest')else if(api=='boost')boost(a)else realdata(read_sources(src),a$kind)\n dir.create(out,recursive=TRUE,showWarnings=FALSE);summary<-list();points<-list();add<-function(x,y,s){if(!is.null(y)&&!is.na(y))points[[length(points)+1L]]<<-data.frame(x=x,y=as.numeric(y),series=s)}\n if(api=='variance'){summary<-r[c('B','varianceOfMean')];add(r$B,r$varianceOfMean,'Specified finite-B variance');xl<-'Number of members B';yl<-'Variance, stipulated units squared';title<-'Declared covariance model, not fitted trees'\n }else if(api=='aggregate'){p<-r$predictions[[1]];summary<-list(selectedPrediction=p$prediction);classification<-identical(a$task,'classification');if(classification){summary<-c(summary,list(voteLabel=p$vote,probabilityLabel=p$prob,meanProbability1=p$probabilities[2]));add(1,p$probabilities[2],'Mean probability of class 1');add(2,p$votes[2],'Label-vote share of class 1');xl<-'Aggregation (1=probability, 2=vote)';yl<-'Probability or vote share'}else{for(i in seq_along(a$members))add(i,num(a$members[[i]]$predictions$value[1]),'Member prediction');add(3,p$prediction,'Weighted mean');xl<-'Member 1, member 2, aggregate 3';yl<-'Prediction, assumed units'};title<-'Votes and probabilities are distinct objects'\n }else if(api%in%c('bagging','forest')){summary<-list(queryPrediction=r$predictions[[1]]$prediction,OOB.scoreable=r$outOfBag$eligibleRows,OOB.meanLoss=r$outOfBag$meanLoss);for(i in seq_len(nrow(a$rows)))add(i,a$rows$y[i],'Observed training outcome');for(i in seq_along(r$outOfBag$rows))add(i,r$outOfBag$rows[[i]]$prediction,'OOB prediction, when defined');xl<-'Original training ID order';yl<-'Outcome, assumed units';title<-'Repeated draws and ID-level OOB membership'\n }else if(api=='boost'){summary<-list(initial=r$initial,finalMSE=r$losses[[length(r$losses)]]$MSE,stages=r$stages);for(v in r$losses)add(v$stage,v$MSE,'Training MSE');xl<-'Boosting stage (0=initial)';yl<-'Weighted MSE, outcome units squared';title<-'Training descent does not certify held-out gain'\n }else{summary<-list(outer.scoreable=r$outer$eligibleRows,outer.meanLoss=r$outer$meanLoss,baseline.meanLoss=r$baseline$meanLoss,OOB.scoreable=r$result$outOfBag$eligibleRows,OOB.meanLoss=r$result$outOfBag$meanLoss);for(i in seq_along(r$outer$rows)){p<-r$outer$rows[[i]];add(i,as.numeric(p$actual),'Observed outcome');add(i,if(a$kind=='company')p$probabilities[2]else p$prediction,if(a$kind=='company')'Forest probability of class 1'else'Forest prediction')};xl<-'Outer-test source order, not a time path';yl<-if(a$kind=='company')'Churn label / probability'else if(a$kind=='country')'Period life expectancy, years'else'Nominal 1976 USD per hour';title<-'Fixed forest; outer labels did not fit the trees'}\n display<-function(v)if(is.null(v)||is.na(v))'undefined'else sprintf('%.9f',as.numeric(v));write.csv(data.frame(metric=names(summary),value=vapply(summary,display,'')),file.path(out,'summary.csv'),row.names=FALSE);pp<-do.call(rbind,points);write.csv(pp,file.path(out,'plot-points.csv'),row.names=FALSE);dput(r,file.path(out,'full-result.Rtext'));svg(file.path(out,'plot.svg'),width=5.6,height=4.6,pointsize=14);par(mar=c(5.8,5.8,5.3,1.2),mgp=c(3.7,1,0));xr<-range(pp$x);yr<-range(pp$y);if(diff(xr)==0)xr<-xr+c(-.5,.5);if(diff(yr)==0)yr<-yr+c(-.5,.5);plot(xr,yr,type='n',xlab=xl,ylab=yl,cex.lab=.78,axes=FALSE);axis(1,at=pretty(xr,3));axis(2,at=pretty(yr,4),las=1,cex.axis=.82);box();grid(col='#dddddd');cols<-c('#355c72','#a55336','#507956','#78568b');ss<-unique(pp$series);for(i in seq_along(ss)){v<-pp[pp$series==ss[i],];points(v$x,v$y,pch=16,cex=if(nrow(v)>100).35 else .85,col=adjustcolor(cols[i],if(nrow(v)>100).5 else 1))};legend('topleft',legend=ss,col=cols[seq_along(ss)],lty=0,pch=16,cex=.65,bty='n',inset=c(0,-.32),xpd=NA);mtext(title,side=3,line=3.9,cex=.6);dev.off();cat(paste(names(summary),vapply(summary,display,''),sep='=',collapse=', '),'\\n')\n}\nargs<-commandArgs(trailingOnly=TRUE)\ntryCatch(run_fixed(API,INPUT,if(length(args))args[1]else'fixed-results',if(length(args)>1)args[2]else'ml09-sources'),error=function(e){cat('Rejected declared input: ',conditionMessage(e),'\\n',file=stderr());quit(status=2)})\n",
        "inputFiles": [],
        "input": {
          "rows": [
            {
              "id": "a",
              "x": [
                0,
                0
              ],
              "y": 0
            },
            {
              "id": "b",
              "x": [
                1,
                1
              ],
              "y": 1
            },
            {
              "id": "c",
              "x": [
                2,
                0
              ],
              "y": 3
            },
            {
              "id": "d",
              "x": [
                3,
                1
              ],
              "y": 4
            }
          ],
          "queries": [
            {
              "id": "q",
              "x": [
                "3/2",
                0
              ]
            }
          ],
          "bootstrapDraws": [
            [
              "a",
              "b",
              "c",
              "d"
            ],
            [
              "a",
              "b",
              "c",
              "d"
            ]
          ],
          "maxDepth": 2
        },
        "returnCode": 0,
        "expectedFailure": false,
        "stdout": "queryPrediction=1.000000000, OOB.scoreable=0.000000000, OOB.meanLoss=undefined \n",
        "stderr": "During startup - Warning messages:\n1: Setting LC_COLLATE=C.UTF-8 failed \n2: Setting LC_CTYPE=C.UTF-8 failed \n3: Setting LC_MONETARY=C.UTF-8 failed \n4: Setting LC_TIME=C.UTF-8 failed \n",
        "summary": {
          "queryPrediction": "1.000000000",
          "OOB.scoreable": "0.000000000",
          "OOB.meanLoss": "undefined"
        },
        "plotPoints": [
          {
            "x": "1",
            "y": "0",
            "series": "Observed training outcome"
          },
          {
            "x": "2",
            "y": "1",
            "series": "Observed training outcome"
          },
          {
            "x": "3",
            "y": "3",
            "series": "Observed training outcome"
          },
          {
            "x": "4",
            "y": "4",
            "series": "Observed training outcome"
          }
        ],
        "plotFile": "ml09-fixed-results/bagging-no-OOB-members-r/plot.svg",
        "plotSHA256": "1b848be04dfc341309b778a288636525b5690f4ebf435e92e8aa36bf32081007",
        "files": [
          {
            "file": "ml09-fixed-results/bagging-no-OOB-members-r/full-result.Rtext",
            "sha256": "c1ac73e2df6d38c73f146062804ec05896c9be83d4d270efb524d6bb003c15b2"
          },
          {
            "file": "ml09-fixed-results/bagging-no-OOB-members-r/plot-points.csv",
            "sha256": "645dd05f8483390b8753face4d5b531e54f280f77519e7170ac85bef90f54e98"
          },
          {
            "file": "ml09-fixed-results/bagging-no-OOB-members-r/plot.svg",
            "sha256": "1b848be04dfc341309b778a288636525b5690f4ebf435e92e8aa36bf32081007"
          },
          {
            "file": "ml09-fixed-results/bagging-no-OOB-members-r/summary.csv",
            "sha256": "7d173912b29d30908f16837bee15e639fd4c5ebbd692fb05d8b7754bad4f9da0"
          }
        ],
        "scope": "Actually executed self-contained fixed example; current web controls execute separately. Python Fraction and finite-precision base R. Author gate, not independent peer."
      }
    }
  },
  "forest": {
    "python": {
      "node-features": {
        "api": "forest",
        "variant": "node-features",
        "language": "python",
        "codeFile": "ml09-code/forest-node-features.py",
        "codeSHA256": "e6741f9e0241a2c53e69103570f83017b0be52fc664f8a564ec9ba1ab548c3c5",
        "codeText": "\"\"\"ML09 exact Fraction reproduction from native source fields.\n\npython ml09-public-analysis.py --source-dir ml09-sources --output-dir results\n\nThis authored educational implementation uses direct-centered leaf losses and\nexhaustive midpoint partitions. It reads no JS engine, model contract, checker,\nstored target answers or derived-result CSV. Its five tree arithmetic helpers\nwere copied from the author's own separate Fraction reference, not an independent\npeer. Parser/work budgets and display rounding of the production JS are separate.\nNumerical predictions/proper scores do not certify causal effects, calibration,\nIID OOB validity, survey representativeness or production parameter optimality.\n\"\"\"\nfrom pathlib import Path\nfrom fractions import Fraction as Q\nimport csv,json,math,itertools,argparse\n\ndef normalized(rows,task='regression'):\n return [dict(id=r.get('id',i),x=[None if x is None else Q(x)for x in r.get('x',[])],y=None if r['y']is None else str(r['y'])if task=='classification'else Q(r['y']),w=Q(r.get('weight',1)))for i,r in enumerate(rows)]\n\ndef totals(rows,task,classes):\n W=sum((r['w']for r in rows),Q());mu=sum((r['w']*r['y']for r in rows),Q())/W if task=='regression'and W else None\n probs=[sum((r['w']for r in rows if r['y']==c),Q())/W for c in classes]if task=='classification'and W else[]\n risk=sum((r['w']*(r['y']-mu)**2 for r in rows),Q())if task=='regression'and W else W*sum((p*(1-p)for p in probs),Q())\n return dict(n=len(rows),w=W,mu=mu,p=probs,risk=risk,pred=mu if task=='regression'else classes[max(range(len(probs)),key=lambda i:probs[i])]if probs else None)\n\ndef fit(rows,a,task,classes,schedule=None):\n good=[r for r in rows if r['w']>0 and r['y']is not None];root=totals(good,task,classes)['w'];depth=a.get('maxDepth',2);minimum=a.get('minLeaf',1);minmass=Q(a.get('minLeafWeight',0));mingain=Q(a.get('minGain',0));route=a.get('missingRoute','best')\n def build(rr,d,path):\n  st=totals(rr,task,classes);n=dict(rows=rr,st=st,split=None,left=None,right=None,path=path)\n  if d==depth:return n\n  best=None\n  for j in range(len(rr[0]['x'])):\n   if schedule is not None and j not in schedule[path]:continue\n   values=sorted({r['x'][j]for r in rr if r['x'][j]is not None});missing=[r for r in rr if r['x'][j]is None];observed=[r for r in rr if r['x'][j]is not None]\n   candidates=[]\n   for lo,hi in zip(values,values[1:]):\n    q=(lo+hi)/2;left=[r for r in observed if r['x'][j]<=q];right=[r for r in observed if r['x'][j]>q];directions=[route]if route!='best'else['left','right']if missing else['left'if len(left)>=len(right)else'right']\n    for direction in directions:candidates.append(('threshold',q,direction,left+missing if direction=='left'else left,right+missing if direction=='right'else right))\n   if missing and observed:candidates.append(('missing-only',None,'left',missing,observed))\n   for kind,q,direction,left,right in candidates:\n    l=totals(left,task,classes);r=totals(right,task,classes)\n    if min(l['n'],r['n'])<minimum or min(l['w'],r['w'])<minmass or min(l['w'],r['w'])<=0:continue\n    gain=(st['risk']-l['risk']-r['risk'])/root\n    if best is None or gain>best['gain']:best=dict(feature=j,kind=kind,threshold=q,missingRoute=direction,left=left,right=right,gain=gain)\n  if best and best['gain']>0 and best['gain']>mingain:\n   j=best['feature'];go=lambda r:r['x'][j]is None if best['kind']=='missing-only'else best['missingRoute']=='left'if r['x'][j]is None else r['x'][j]<=best['threshold'];n['split']=best;n['left']=build([r for r in rr if go(r)],d+1,path+'L');n['right']=build([r for r in rr if not go(r)],d+1,path+'R')\n  return n\n return build(good,0,'')\n\ndef predict(tree,x):\n n=tree\n while n['split']:\n  s=n['split'];v=x[s['feature']];left=v is None if s['kind']=='missing-only'else s['missingRoute']=='left'if v is None else v<=s['threshold'];n=n['left'if left else'right']\n return dict(prediction=n['st']['pred'],probabilities=n['st']['p'])\n\ndef combine(preds,w,task,classes,mode='probabilities'):\n mass=sum(w,Q())\n if not preds or not mass:return dict(prediction=None,probabilities=[],vote=None,prob=None)\n if task=='regression':return dict(prediction=sum((p['prediction']*v for p,v in zip(preds,w)),Q())/mass,probabilities=[],vote=None,prob=None)\n votes=[sum((v for p,v in zip(preds,w)if p['prediction']==c),Q())/mass for c in classes];ps=[sum((p['probabilities'][j]*v for p,v in zip(preds,w)),Q())/mass for j in range(len(classes))];vote=classes[max(range(len(classes)),key=lambda j:votes[j])];prob=classes[max(range(len(classes)),key=lambda j:ps[j])];return dict(prediction=vote if mode=='votes'else prob,probabilities=ps,vote=vote,prob=prob,votes=votes)\ndef number(v):\n if v is None or isinstance(v,bool):raise ValueError('explicit null/bool is not a numeric parameter')\n return Q(v)\ndef variance(a):\n B=a['B'];v=number(a['marginalVariance']);rho=number(a.get('rho',0))\n if not isinstance(B,int)or isinstance(B,bool)or B<1 or v<0:raise ValueError('positive integer B/nonnegative variance')\n if B>1 and v and not -Q(1,B-1)<=rho<=1:raise ValueError('equicorrelation PSD bound')\n return dict(B=B,marginalVariance=v,correlationApplicable=B>1 and bool(v),varianceOfMean=v if B==1 else v*(1+(B-1)*rho)/B)\ndef aggregate(a):\n task=a.get('task','regression');classes=[str(c)for c in a.get('classes',[])];members=a['members'];w=[number(v)for v in a.get('memberWeights',[1]*len(members))]\n if not members or min(w)<0 or sum(w)<=0:raise ValueError('nonnegative member weights/positive total')\n order=[p.get('id',i)for i,p in enumerate(members[0]['predictions'])];keys=lambda x:(type(x).__name__,x);lookup=[{keys(p.get('id',i)):p for i,p in enumerate(m['predictions'])}for m in members]\n if any(set(m)!={keys(v)for v in order}for m in lookup):raise ValueError('same query ID set')\n out=[]\n for pid in order:\n  predictions=[dict(prediction=number(m[keys(pid)]['value']),probabilities=[])if task=='regression'else dict(prediction=str(m[keys(pid)]['label']),probabilities=[number(v)for v in m[keys(pid)]['probabilities']])for m in lookup]\n  if task=='classification'and any(min(p['probabilities'])<0 or sum(p['probabilities'])!=1 for p in predictions):raise ValueError('probability simplex')\n  out.append(dict(id=pid,**combine(predictions,w,task,classes,a.get('aggregation','probabilities'))))\n return dict(task=task,classes=classes,predictions=out)\ndef scored(preds,rows,task,classes):\n mass=loss=absolute=errors=voteerrors=Q();out=[]\n for p,r in zip(preds,rows):\n  ok=p['prediction']is not None and r['y']is not None and r['w']>0;v=None\n  if ok:\n   mass+=r['w']\n   if task=='regression':e=r['y']-p['prediction'];v=e*e;absolute+=r['w']*abs(e)\n   else:v=sum(((q-(1 if r['y']==c else 0))**2 for c,q in zip(classes,p['probabilities'])),Q());errors+=r['w']*(p['prediction']!=r['y']);voteerrors+=r['w']*(p['vote']!=r['y'])\n   loss+=r['w']*v\n  out.append(dict(p,actual=r['y'],weight=r['w'],scoreEligible=ok,loss=v))\n return dict(rows=out,eligibleRows=sum(r['scoreEligible']for r in out),weight=mass,totalLoss=loss,meanLoss=loss/mass if mass else None,MAE=absolute/mass if mass and task=='regression'else None,errorRate=errors/mass if mass and task=='classification'else None,labelVoteErrorRate=voteerrors/mass if mass and task=='classification'else None)\ndef ensemble(a,forest=False):\n task=a.get('task','regression');classes=[str(v)for v in(a.get('classes')or[])];rr=normalized(a['rows'],task);key=lambda x:(type(x).__name__,x);lookup={key(r['id']):r for r in rr};weights=[number(v)for v in a.get('memberWeights',[1]*len(a['bootstrapDraws']))]\n if not any(r['w']>0 and r['y']is not None for r in rr)or min(weights)<0 or sum(weights)<=0:raise ValueError('positive eligible training and member weight')\n members=[]\n for i,draw in enumerate(a['bootstrapDraws']):\n  data=[lookup[key(v)]for v in draw];schedule=a['nodeFeatures'][i]if forest else None;model=fit(data,a,task,classes,schedule);inbag={key(v)for v in draw};members.append(dict(tree=model,draw=draw,inbag=inbag,weight=weights[i]))\n predictions=[]\n for q in a.get('queries',[]):predictions.append(dict(id=q['id'],**combine([predict(m['tree'],[None if v is None else number(v)for v in q['x']])for m in members],weights,task,classes,a.get('aggregation','probabilities'))))\n oob=[]\n for r in rr:\n  applicable=[i for i,m in enumerate(members)if key(r['id'])not in m['inbag']];p=combine([predict(members[i]['tree'],r['x'])for i in applicable],[weights[i]for i in applicable],task,classes,a.get('aggregation','probabilities'));oob.append(dict(id=r['id'],applicable=applicable,positiveMembers=sum(weights[i]>0 for i in applicable),**p))\n return dict(task=task,classes=classes,members=members,predictions=predictions,outOfBag=scored(oob,rr,task,classes))\ndef boost(a):\n if a.get('task','regression')!='regression':raise ValueError('regression boosting only')\n rr=normalized(a['rows']);good=[r for r in rr if r['w']and r['y']is not None];W=sum((r['w']for r in good),Q())\n if not W:raise ValueError('positive eligible training')\n eta=number(a.get('learningRate','1/2'));stages=a.get('stages',3)\n if not 0<=eta<=1 or not isinstance(stages,int)or isinstance(stages,bool)or not 0<=stages<=8:raise ValueError('supported rate/stages')\n initial=number(a['initial'])if'initial'in a else sum((r['w']*r['y']for r in good),Q())/W;training=[[initial]for r in rr];queries=[[initial]for q in a.get('queries',[])];fits=[];losses=[]\n for stage in range(stages+1):\n  sse=sum((r['w']*(r['y']-p[-1])**2 for r,p in zip(rr,training)if r['w']and r['y']is not None),Q());losses.append(dict(stage=stage,rawWeightedSSE=sse,MSE=sse/W,meanHalfSquaredLoss=sse/(2*W)))\n  if stage==stages:break\n  residuals=[dict(r,y=None if r['y']is None else r['y']-p[-1])for r,p in zip(rr,training)];tree=fit(residuals,a,'regression',[]);h=[predict(tree,r['x'])['prediction']for r in rr];qh=[predict(tree,[None if v is None else number(v)for v in q['x']])['prediction']for q in a.get('queries',[])];norm=sum((r['w']*v*v for r,v in zip(rr,h)if r['y']is not None),Q());stageRows=[]\n  for i,(r,p)in enumerate(zip(rr,training)):\n   residual=None if r['y']is None else r['y']-p[-1];stageRows.append(dict(id=r['id'],before=p[-1],residual=residual,negativeCoordinateDerivative=None if residual is None else r['w']*residual/W,fit=h[i],addition=eta*h[i],after=p[-1]+eta*h[i]));p.append(p[-1]+eta*h[i])\n  for p,v in zip(queries,qh):p.append(p[-1]+eta*v)\n  fits.append(dict(stage=stage+1,tree=tree,rows=stageRows,queryFits=qh,norm=norm,predictedSSEDecrease=eta*(2-eta)*norm))\n return dict(task='regression',initial=initial,learningRate=eta,stages=stages,training=training,queries=queries,fits=fits,losses=losses,predictions=[dict(id=q['id'],prediction=p[-1],probabilities=[],vote=None,prob=None)for q,p in zip(a.get('queries',[]),queries)])\nclass Stream:\n def __init__(self,state):self.state=state\n def choose(self,n):\n  limit=(1<<32)-((1<<32)%n)\n  while True:\n   self.state=(1664525*self.state+1013904223)&0xffffffff\n   if self.state<limit:return self.state%n\ndef fixed_schedules(ids,p,seed):\n stream=Stream(seed);draws=[];schedules=[];paths=['']+[p for d in[1,2]for p in map(''.join,itertools.product('LR',repeat=d))]\n for member in range(4):\n  draws.append([ids[stream.choose(len(ids))]for _ in range(len(ids))]);schedule={}\n  for path in paths:\n   order=list(range(p))\n   for j in range(p-1,0,-1):k=stream.choose(j+1);order[j],order[k]=order[k],order[j]\n   schedule[path]=sorted(order[:max(1,int(math.sqrt(p)))])\n  schedules.append(schedule)\n return draws,schedules\ndef csvread(file):\n with Path(file).open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))\ndef read_sources(source):\n source=Path(source);raw=csvread(source/'actual320-country-four-indicators-original-2020-2024.csv');lookup={(r['countryISO3'],int(r['date']),r['indicatorID']):r for r in raw};country=[]\n for code in sorted({r['countryISO3']for r in raw}):\n  for year in range(2020,2025):\n   cols=['NY.GDP.PCAP.KD','NY.GDP.MKTP.KD.ZG','FP.CPI.TOTL.ZG','SP.DYN.LE00.IN'];v=[lookup[code,year,k]['originalValueToken']for k in cols];x=[None if not z else Q(z)for z in v[:3]];x[0]=None if x[0]is None else x[0]/10000;y=None if not v[3]else Q(v[3]);eligible=y is not None and None not in x;country.append(dict(id=code+':'+str(year),sourceRow=code+':'+str(year),originalID=code,year=year,x=x,y=y,weight='1',role='excluded'if not eligible else'outer-test'if year==2024 else'train'))\n person=[]\n for i,r in enumerate(csvread(source/'actual3613-NLS-original52-fields-and-selection.csv'),1):\n  v=lambda k:None if r[k]=='.'else Q(r[k]);x=[v('ed76'),v('age76')];y=None if v('wage76')is None else v('wage76')/100;eligible=y is not None and None not in x;person.append(dict(id='person:'+str(i),sourceRow=str(i),originalID=r['id'],x=x,y=y,weight='1',role='excluded'if not eligible else'outer-test'if i%5==0 else'train'))\n company=[]\n for i,r in enumerate(csvread(source/'actual3150-churn-original14-fields-and-selection.csv'),1):company.append(dict(id='customer:'+str(i),sourceRow=str(i),originalID='',x=[Q(r[k])for k in['Call  Failure','Subscription  Length','Charge  Amount']],y=r['Churn'],weight='1',role='outer-test'if i%5==0 else'train'))\n models={}\n for index,(kind,rr,task,leaf)in enumerate([('country',country,'regression',4),('person',person,'regression',50),('company',company,'classification',30)]):\n  ids=[r['id']for r in rr if r['role']=='train'];draws,schedules=fixed_schedules(ids,len(rr[0]['x']),20261102+7919*index);models[kind]=dict(records=rr,task=task,classes=['0','1']if task=='classification'else[],draws=draws,schedules=schedules,minLeaf=leaf)\n return models\n_OMITTED=object()\ndef realdata(models,kind,options=_OMITTED):\n options={}if options is _OMITTED else options\n if not isinstance(options,dict):raise ValueError('options object required, not explicit null')\n m=models[kind];train=[r for r in m['records']if r['role']=='train'];test=[r for r in m['records']if r['role']=='outer-test'];method=options.get('method','forest');depth=options.get('maxDepth',2);count=options.get('memberCount',3);a=dict(rows=train,queries=[dict(id=r['id'],x=r['x'])for r in test],task=m['task'],classes=m['classes'],maxDepth=depth,minLeaf=options.get('minLeaf',m['minLeaf']),minLeafWeight='0',minGain='0',missingRoute='best',learningRate=options.get('learningRate','1/2'),stages=options.get('stages',3))\n if method not in ['bagging','forest','boost']:raise ValueError('known source method')\n if not isinstance(depth,int)or isinstance(depth,bool)or not 0<=depth<=3:raise ValueError('source depth0..3')\n if method!='boost'and(not isinstance(count,int)or isinstance(count,bool)or not 1<=count<=4):raise ValueError('source member count1..4')\n if method=='boost':result=boost(a)\n else:\n  a.update(bootstrapDraws=m['draws'][:count],nodeFeatures=[{p:v for p,v in s.items()if len(p)<depth}for s in m['schedules'][:count]]);result=ensemble(a,method=='forest')\n outer=scored(result['predictions'],normalized(test,m['task']),m['task'],m['classes']);st=totals([r for r in normalized(train,m['task'])if r['w']and r['y']is not None],m['task'],m['classes']);constant=dict(prediction=st['pred'],probabilities=st['p'],vote=st['pred'],prob=st['pred']);baseline=scored([dict(id=r['id'],**constant)for r in test],normalized(test,m['task']),m['task'],m['classes']);return dict(kind=kind,method=method,settings=a,train=train,test=test,result=result,outer=outer,baseline=baseline)\ndef serial(x):\n if isinstance(x,Q):return str(x)\n if isinstance(x,dict):return{k:serial(v)for k,v in x.items()if k not in['inbag','tree']}\n if isinstance(x,(list,tuple)):return[serial(v)for v in x]\n return x\ndef writecsv(file,heads,rows):\n with Path(file).open('w',encoding='utf8',newline='')as f:\n  w=csv.writer(f);w.writerow(heads);w.writerows([[''if v is None else str(v)for v in r]for r in rows])\nAPI='forest'\nINPUT={'rows': [{'id': 'a', 'x': [0, 0], 'y': 0}, {'id': 'b', 'x': [1, 1], 'y': 1}, {'id': 'c', 'x': [2, 0], 'y': 3}, {'id': 'd', 'x': [3, 1], 'y': 4}], 'queries': [{'id': 'q', 'x': ['3/2', 0]}], 'bootstrapDraws': [['a', 'a', 'b', 'c'], ['b', 'c', 'd', 'd']], 'maxDepth': 2, 'nodeFeatures': [{'': [0], 'L': [1], 'R': [1]}, {'': [1], 'L': [0], 'R': [0]}]}\n\ndef run_fixed(api,a,out,src):\n import matplotlib\n matplotlib.use('svg')\n import matplotlib.pyplot as plt\n from matplotlib.ticker import MaxNLocator\n plt.rcParams.update({'font.size':14,'svg.fonttype':'none','svg.hashsalt':'ml09-fixed-v1'})\n result=variance(a)if api=='variance'else aggregate(a)if api=='aggregate'else ensemble(a,api=='forest')if api in ['bagging','forest']else boost(a)if api=='boost'else realdata(read_sources(src),a['kind'])\n out=Path(out);out.mkdir(parents=True,exist_ok=True);summary={};points=[]\n def add(x,y,s):\n  if y is not None:points.append([x,y,s])\n if api=='variance':\n  summary={'B':result['B'],'varianceOfMean':result['varianceOfMean']};add(result['B'],result['varianceOfMean'],'Specified finite-B variance');xl='Number of members B';yl='Variance, stipulated units squared';title='Declared covariance model, not fitted trees'\n elif api=='aggregate':\n  p=result['predictions'][0];classification=a.get('task')=='classification';summary={'selectedPrediction':p['prediction']}\n  if classification:\n   summary.update(voteLabel=p['vote'],probabilityLabel=p['prob'],meanProbability1=p['probabilities'][1]);add(1,p['probabilities'][1],'Mean probability of class 1');add(2,p['votes'][1],'Label-vote share of class 1');xl='Aggregation (1=probability, 2=vote)';yl='Probability or vote share'\n  else:\n   for i,m in enumerate(a['members']):add(i+1,Q(m['predictions'][0]['value']),'Member prediction')\n   add(3,p['prediction'],'Weighted mean');xl='Member 1, member 2, aggregate 3';yl='Prediction, assumed units'\n  title='Votes and probabilities are distinct objects'\n elif api in ['bagging','forest']:\n  summary={'queryPrediction':result['predictions'][0]['prediction'],'OOB.scoreable':result['outOfBag']['eligibleRows'],'OOB.meanLoss':result['outOfBag']['meanLoss']}\n  for i,r in enumerate(a['rows']):add(i+1,Q(r['y']),'Observed training outcome')\n  for i,p in enumerate(result['outOfBag']['rows']):add(i+1,p['prediction'],'OOB prediction, when defined')\n  xl='Original training ID order';yl='Outcome, assumed units';title='Repeated draws and ID-level OOB membership'\n elif api=='boost':\n  summary={'initial':result['initial'],'finalMSE':result['losses'][-1]['MSE'],'stages':result['stages']}\n  for r in result['losses']:add(r['stage'],r['MSE'],'Training MSE')\n  xl='Boosting stage (0=initial)';yl='Weighted MSE, outcome units squared';title='Training descent does not certify held-out gain'\n else:\n  summary={'outer.scoreable':result['outer']['eligibleRows'],'outer.meanLoss':result['outer']['meanLoss'],'baseline.meanLoss':result['baseline']['meanLoss'],'OOB.scoreable':result['result']['outOfBag']['eligibleRows'],'OOB.meanLoss':result['result']['outOfBag']['meanLoss']}\n  for i,p in enumerate(result['outer']['rows']):\n   add(i+1,Q(p['actual']),'Observed outcome');add(i+1,p['probabilities'][1]if a['kind']=='company'else p['prediction'],'Forest probability of class 1'if a['kind']=='company'else'Forest prediction')\n  xl='Outer-test source order, not a time path';yl='Churn label / probability'if a['kind']=='company'else'Period life expectancy, years'if a['kind']=='country'else'Nominal 1976 USD per hour';title='Fixed forest; outer labels did not fit the trees'\n def display(v):return 'undefined'if v is None else format(float(v),'.9f')\n writecsv(out/'summary.csv',['metric','value'],[[k,display(v)]for k,v in summary.items()]);writecsv(out/'plot-points.csv',['x','y','series'],points);(out/'full.json').write_text(json.dumps(serial(result),indent=2)+'\\n',encoding='utf8')\n fig,ax=plt.subplots(figsize=(5.6,4.6));fig.subplots_adjust(left=.24,right=.96,bottom=.24,top=.76);colors=['#355c72','#a55336','#507956','#78568b']\n for i,s in enumerate(dict.fromkeys(p[2]for p in points)):\n  pp=[p for p in points if p[2]==s];ax.scatter([float(p[0])for p in pp],[float(p[1])for p in pp],s=12 if len(pp)>100 else 32,alpha=.5 if len(pp)>100 else 1,color=colors[i%4],label=s)\n ax.set_xlabel(xl,labelpad=10,fontsize=11);ax.set_ylabel(yl,labelpad=10,fontsize=11);ax.xaxis.set_major_locator(MaxNLocator(3));ax.yaxis.set_major_locator(MaxNLocator(4));ax.grid(alpha=.18);ax.legend(loc='lower left',bbox_to_anchor=(0,1.01),fontsize=9,frameon=False);fig.suptitle(title,fontsize=9,y=.99);fig.savefig(out/'plot.svg',metadata={'Date':None});plt.close(fig);print(', '.join(k+'='+display(v)for k,v in summary.items()))\nif __name__=='__main__':\n import sys\n try:run_fixed(API,INPUT,sys.argv[1]if len(sys.argv)>1 else'fixed-results',sys.argv[2]if len(sys.argv)>2 else'ml09-sources')\n except ValueError as error:print('Rejected declared input: '+str(error),file=sys.stderr);sys.exit(2)\n",
        "code": "\"\"\"ML09 exact Fraction reproduction from native source fields.\n\npython ml09-public-analysis.py --source-dir ml09-sources --output-dir results\n\nThis authored educational implementation uses direct-centered leaf losses and\nexhaustive midpoint partitions. It reads no JS engine, model contract, checker,\nstored target answers or derived-result CSV. Its five tree arithmetic helpers\nwere copied from the author's own separate Fraction reference, not an independent\npeer. Parser/work budgets and display rounding of the production JS are separate.\nNumerical predictions/proper scores do not certify causal effects, calibration,\nIID OOB validity, survey representativeness or production parameter optimality.\n\"\"\"\nfrom pathlib import Path\nfrom fractions import Fraction as Q\nimport csv,json,math,itertools,argparse\n\ndef normalized(rows,task='regression'):\n return [dict(id=r.get('id',i),x=[None if x is None else Q(x)for x in r.get('x',[])],y=None if r['y']is None else str(r['y'])if task=='classification'else Q(r['y']),w=Q(r.get('weight',1)))for i,r in enumerate(rows)]\n\ndef totals(rows,task,classes):\n W=sum((r['w']for r in rows),Q());mu=sum((r['w']*r['y']for r in rows),Q())/W if task=='regression'and W else None\n probs=[sum((r['w']for r in rows if r['y']==c),Q())/W for c in classes]if task=='classification'and W else[]\n risk=sum((r['w']*(r['y']-mu)**2 for r in rows),Q())if task=='regression'and W else W*sum((p*(1-p)for p in probs),Q())\n return dict(n=len(rows),w=W,mu=mu,p=probs,risk=risk,pred=mu if task=='regression'else classes[max(range(len(probs)),key=lambda i:probs[i])]if probs else None)\n\ndef fit(rows,a,task,classes,schedule=None):\n good=[r for r in rows if r['w']>0 and r['y']is not None];root=totals(good,task,classes)['w'];depth=a.get('maxDepth',2);minimum=a.get('minLeaf',1);minmass=Q(a.get('minLeafWeight',0));mingain=Q(a.get('minGain',0));route=a.get('missingRoute','best')\n def build(rr,d,path):\n  st=totals(rr,task,classes);n=dict(rows=rr,st=st,split=None,left=None,right=None,path=path)\n  if d==depth:return n\n  best=None\n  for j in range(len(rr[0]['x'])):\n   if schedule is not None and j not in schedule[path]:continue\n   values=sorted({r['x'][j]for r in rr if r['x'][j]is not None});missing=[r for r in rr if r['x'][j]is None];observed=[r for r in rr if r['x'][j]is not None]\n   candidates=[]\n   for lo,hi in zip(values,values[1:]):\n    q=(lo+hi)/2;left=[r for r in observed if r['x'][j]<=q];right=[r for r in observed if r['x'][j]>q];directions=[route]if route!='best'else['left','right']if missing else['left'if len(left)>=len(right)else'right']\n    for direction in directions:candidates.append(('threshold',q,direction,left+missing if direction=='left'else left,right+missing if direction=='right'else right))\n   if missing and observed:candidates.append(('missing-only',None,'left',missing,observed))\n   for kind,q,direction,left,right in candidates:\n    l=totals(left,task,classes);r=totals(right,task,classes)\n    if min(l['n'],r['n'])<minimum or min(l['w'],r['w'])<minmass or min(l['w'],r['w'])<=0:continue\n    gain=(st['risk']-l['risk']-r['risk'])/root\n    if best is None or gain>best['gain']:best=dict(feature=j,kind=kind,threshold=q,missingRoute=direction,left=left,right=right,gain=gain)\n  if best and best['gain']>0 and best['gain']>mingain:\n   j=best['feature'];go=lambda r:r['x'][j]is None if best['kind']=='missing-only'else best['missingRoute']=='left'if r['x'][j]is None else r['x'][j]<=best['threshold'];n['split']=best;n['left']=build([r for r in rr if go(r)],d+1,path+'L');n['right']=build([r for r in rr if not go(r)],d+1,path+'R')\n  return n\n return build(good,0,'')\n\ndef predict(tree,x):\n n=tree\n while n['split']:\n  s=n['split'];v=x[s['feature']];left=v is None if s['kind']=='missing-only'else s['missingRoute']=='left'if v is None else v<=s['threshold'];n=n['left'if left else'right']\n return dict(prediction=n['st']['pred'],probabilities=n['st']['p'])\n\ndef combine(preds,w,task,classes,mode='probabilities'):\n mass=sum(w,Q())\n if not preds or not mass:return dict(prediction=None,probabilities=[],vote=None,prob=None)\n if task=='regression':return dict(prediction=sum((p['prediction']*v for p,v in zip(preds,w)),Q())/mass,probabilities=[],vote=None,prob=None)\n votes=[sum((v for p,v in zip(preds,w)if p['prediction']==c),Q())/mass for c in classes];ps=[sum((p['probabilities'][j]*v for p,v in zip(preds,w)),Q())/mass for j in range(len(classes))];vote=classes[max(range(len(classes)),key=lambda j:votes[j])];prob=classes[max(range(len(classes)),key=lambda j:ps[j])];return dict(prediction=vote if mode=='votes'else prob,probabilities=ps,vote=vote,prob=prob,votes=votes)\ndef number(v):\n if v is None or isinstance(v,bool):raise ValueError('explicit null/bool is not a numeric parameter')\n return Q(v)\ndef variance(a):\n B=a['B'];v=number(a['marginalVariance']);rho=number(a.get('rho',0))\n if not isinstance(B,int)or isinstance(B,bool)or B<1 or v<0:raise ValueError('positive integer B/nonnegative variance')\n if B>1 and v and not -Q(1,B-1)<=rho<=1:raise ValueError('equicorrelation PSD bound')\n return dict(B=B,marginalVariance=v,correlationApplicable=B>1 and bool(v),varianceOfMean=v if B==1 else v*(1+(B-1)*rho)/B)\ndef aggregate(a):\n task=a.get('task','regression');classes=[str(c)for c in a.get('classes',[])];members=a['members'];w=[number(v)for v in a.get('memberWeights',[1]*len(members))]\n if not members or min(w)<0 or sum(w)<=0:raise ValueError('nonnegative member weights/positive total')\n order=[p.get('id',i)for i,p in enumerate(members[0]['predictions'])];keys=lambda x:(type(x).__name__,x);lookup=[{keys(p.get('id',i)):p for i,p in enumerate(m['predictions'])}for m in members]\n if any(set(m)!={keys(v)for v in order}for m in lookup):raise ValueError('same query ID set')\n out=[]\n for pid in order:\n  predictions=[dict(prediction=number(m[keys(pid)]['value']),probabilities=[])if task=='regression'else dict(prediction=str(m[keys(pid)]['label']),probabilities=[number(v)for v in m[keys(pid)]['probabilities']])for m in lookup]\n  if task=='classification'and any(min(p['probabilities'])<0 or sum(p['probabilities'])!=1 for p in predictions):raise ValueError('probability simplex')\n  out.append(dict(id=pid,**combine(predictions,w,task,classes,a.get('aggregation','probabilities'))))\n return dict(task=task,classes=classes,predictions=out)\ndef scored(preds,rows,task,classes):\n mass=loss=absolute=errors=voteerrors=Q();out=[]\n for p,r in zip(preds,rows):\n  ok=p['prediction']is not None and r['y']is not None and r['w']>0;v=None\n  if ok:\n   mass+=r['w']\n   if task=='regression':e=r['y']-p['prediction'];v=e*e;absolute+=r['w']*abs(e)\n   else:v=sum(((q-(1 if r['y']==c else 0))**2 for c,q in zip(classes,p['probabilities'])),Q());errors+=r['w']*(p['prediction']!=r['y']);voteerrors+=r['w']*(p['vote']!=r['y'])\n   loss+=r['w']*v\n  out.append(dict(p,actual=r['y'],weight=r['w'],scoreEligible=ok,loss=v))\n return dict(rows=out,eligibleRows=sum(r['scoreEligible']for r in out),weight=mass,totalLoss=loss,meanLoss=loss/mass if mass else None,MAE=absolute/mass if mass and task=='regression'else None,errorRate=errors/mass if mass and task=='classification'else None,labelVoteErrorRate=voteerrors/mass if mass and task=='classification'else None)\ndef ensemble(a,forest=False):\n task=a.get('task','regression');classes=[str(v)for v in(a.get('classes')or[])];rr=normalized(a['rows'],task);key=lambda x:(type(x).__name__,x);lookup={key(r['id']):r for r in rr};weights=[number(v)for v in a.get('memberWeights',[1]*len(a['bootstrapDraws']))]\n if not any(r['w']>0 and r['y']is not None for r in rr)or min(weights)<0 or sum(weights)<=0:raise ValueError('positive eligible training and member weight')\n members=[]\n for i,draw in enumerate(a['bootstrapDraws']):\n  data=[lookup[key(v)]for v in draw];schedule=a['nodeFeatures'][i]if forest else None;model=fit(data,a,task,classes,schedule);inbag={key(v)for v in draw};members.append(dict(tree=model,draw=draw,inbag=inbag,weight=weights[i]))\n predictions=[]\n for q in a.get('queries',[]):predictions.append(dict(id=q['id'],**combine([predict(m['tree'],[None if v is None else number(v)for v in q['x']])for m in members],weights,task,classes,a.get('aggregation','probabilities'))))\n oob=[]\n for r in rr:\n  applicable=[i for i,m in enumerate(members)if key(r['id'])not in m['inbag']];p=combine([predict(members[i]['tree'],r['x'])for i in applicable],[weights[i]for i in applicable],task,classes,a.get('aggregation','probabilities'));oob.append(dict(id=r['id'],applicable=applicable,positiveMembers=sum(weights[i]>0 for i in applicable),**p))\n return dict(task=task,classes=classes,members=members,predictions=predictions,outOfBag=scored(oob,rr,task,classes))\ndef boost(a):\n if a.get('task','regression')!='regression':raise ValueError('regression boosting only')\n rr=normalized(a['rows']);good=[r for r in rr if r['w']and r['y']is not None];W=sum((r['w']for r in good),Q())\n if not W:raise ValueError('positive eligible training')\n eta=number(a.get('learningRate','1/2'));stages=a.get('stages',3)\n if not 0<=eta<=1 or not isinstance(stages,int)or isinstance(stages,bool)or not 0<=stages<=8:raise ValueError('supported rate/stages')\n initial=number(a['initial'])if'initial'in a else sum((r['w']*r['y']for r in good),Q())/W;training=[[initial]for r in rr];queries=[[initial]for q in a.get('queries',[])];fits=[];losses=[]\n for stage in range(stages+1):\n  sse=sum((r['w']*(r['y']-p[-1])**2 for r,p in zip(rr,training)if r['w']and r['y']is not None),Q());losses.append(dict(stage=stage,rawWeightedSSE=sse,MSE=sse/W,meanHalfSquaredLoss=sse/(2*W)))\n  if stage==stages:break\n  residuals=[dict(r,y=None if r['y']is None else r['y']-p[-1])for r,p in zip(rr,training)];tree=fit(residuals,a,'regression',[]);h=[predict(tree,r['x'])['prediction']for r in rr];qh=[predict(tree,[None if v is None else number(v)for v in q['x']])['prediction']for q in a.get('queries',[])];norm=sum((r['w']*v*v for r,v in zip(rr,h)if r['y']is not None),Q());stageRows=[]\n  for i,(r,p)in enumerate(zip(rr,training)):\n   residual=None if r['y']is None else r['y']-p[-1];stageRows.append(dict(id=r['id'],before=p[-1],residual=residual,negativeCoordinateDerivative=None if residual is None else r['w']*residual/W,fit=h[i],addition=eta*h[i],after=p[-1]+eta*h[i]));p.append(p[-1]+eta*h[i])\n  for p,v in zip(queries,qh):p.append(p[-1]+eta*v)\n  fits.append(dict(stage=stage+1,tree=tree,rows=stageRows,queryFits=qh,norm=norm,predictedSSEDecrease=eta*(2-eta)*norm))\n return dict(task='regression',initial=initial,learningRate=eta,stages=stages,training=training,queries=queries,fits=fits,losses=losses,predictions=[dict(id=q['id'],prediction=p[-1],probabilities=[],vote=None,prob=None)for q,p in zip(a.get('queries',[]),queries)])\nclass Stream:\n def __init__(self,state):self.state=state\n def choose(self,n):\n  limit=(1<<32)-((1<<32)%n)\n  while True:\n   self.state=(1664525*self.state+1013904223)&0xffffffff\n   if self.state<limit:return self.state%n\ndef fixed_schedules(ids,p,seed):\n stream=Stream(seed);draws=[];schedules=[];paths=['']+[p for d in[1,2]for p in map(''.join,itertools.product('LR',repeat=d))]\n for member in range(4):\n  draws.append([ids[stream.choose(len(ids))]for _ in range(len(ids))]);schedule={}\n  for path in paths:\n   order=list(range(p))\n   for j in range(p-1,0,-1):k=stream.choose(j+1);order[j],order[k]=order[k],order[j]\n   schedule[path]=sorted(order[:max(1,int(math.sqrt(p)))])\n  schedules.append(schedule)\n return draws,schedules\ndef csvread(file):\n with Path(file).open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))\ndef read_sources(source):\n source=Path(source);raw=csvread(source/'actual320-country-four-indicators-original-2020-2024.csv');lookup={(r['countryISO3'],int(r['date']),r['indicatorID']):r for r in raw};country=[]\n for code in sorted({r['countryISO3']for r in raw}):\n  for year in range(2020,2025):\n   cols=['NY.GDP.PCAP.KD','NY.GDP.MKTP.KD.ZG','FP.CPI.TOTL.ZG','SP.DYN.LE00.IN'];v=[lookup[code,year,k]['originalValueToken']for k in cols];x=[None if not z else Q(z)for z in v[:3]];x[0]=None if x[0]is None else x[0]/10000;y=None if not v[3]else Q(v[3]);eligible=y is not None and None not in x;country.append(dict(id=code+':'+str(year),sourceRow=code+':'+str(year),originalID=code,year=year,x=x,y=y,weight='1',role='excluded'if not eligible else'outer-test'if year==2024 else'train'))\n person=[]\n for i,r in enumerate(csvread(source/'actual3613-NLS-original52-fields-and-selection.csv'),1):\n  v=lambda k:None if r[k]=='.'else Q(r[k]);x=[v('ed76'),v('age76')];y=None if v('wage76')is None else v('wage76')/100;eligible=y is not None and None not in x;person.append(dict(id='person:'+str(i),sourceRow=str(i),originalID=r['id'],x=x,y=y,weight='1',role='excluded'if not eligible else'outer-test'if i%5==0 else'train'))\n company=[]\n for i,r in enumerate(csvread(source/'actual3150-churn-original14-fields-and-selection.csv'),1):company.append(dict(id='customer:'+str(i),sourceRow=str(i),originalID='',x=[Q(r[k])for k in['Call  Failure','Subscription  Length','Charge  Amount']],y=r['Churn'],weight='1',role='outer-test'if i%5==0 else'train'))\n models={}\n for index,(kind,rr,task,leaf)in enumerate([('country',country,'regression',4),('person',person,'regression',50),('company',company,'classification',30)]):\n  ids=[r['id']for r in rr if r['role']=='train'];draws,schedules=fixed_schedules(ids,len(rr[0]['x']),20261102+7919*index);models[kind]=dict(records=rr,task=task,classes=['0','1']if task=='classification'else[],draws=draws,schedules=schedules,minLeaf=leaf)\n return models\n_OMITTED=object()\ndef realdata(models,kind,options=_OMITTED):\n options={}if options is _OMITTED else options\n if not isinstance(options,dict):raise ValueError('options object required, not explicit null')\n m=models[kind];train=[r for r in m['records']if r['role']=='train'];test=[r for r in m['records']if r['role']=='outer-test'];method=options.get('method','forest');depth=options.get('maxDepth',2);count=options.get('memberCount',3);a=dict(rows=train,queries=[dict(id=r['id'],x=r['x'])for r in test],task=m['task'],classes=m['classes'],maxDepth=depth,minLeaf=options.get('minLeaf',m['minLeaf']),minLeafWeight='0',minGain='0',missingRoute='best',learningRate=options.get('learningRate','1/2'),stages=options.get('stages',3))\n if method not in ['bagging','forest','boost']:raise ValueError('known source method')\n if not isinstance(depth,int)or isinstance(depth,bool)or not 0<=depth<=3:raise ValueError('source depth0..3')\n if method!='boost'and(not isinstance(count,int)or isinstance(count,bool)or not 1<=count<=4):raise ValueError('source member count1..4')\n if method=='boost':result=boost(a)\n else:\n  a.update(bootstrapDraws=m['draws'][:count],nodeFeatures=[{p:v for p,v in s.items()if len(p)<depth}for s in m['schedules'][:count]]);result=ensemble(a,method=='forest')\n outer=scored(result['predictions'],normalized(test,m['task']),m['task'],m['classes']);st=totals([r for r in normalized(train,m['task'])if r['w']and r['y']is not None],m['task'],m['classes']);constant=dict(prediction=st['pred'],probabilities=st['p'],vote=st['pred'],prob=st['pred']);baseline=scored([dict(id=r['id'],**constant)for r in test],normalized(test,m['task']),m['task'],m['classes']);return dict(kind=kind,method=method,settings=a,train=train,test=test,result=result,outer=outer,baseline=baseline)\ndef serial(x):\n if isinstance(x,Q):return str(x)\n if isinstance(x,dict):return{k:serial(v)for k,v in x.items()if k not in['inbag','tree']}\n if isinstance(x,(list,tuple)):return[serial(v)for v in x]\n return x\ndef writecsv(file,heads,rows):\n with Path(file).open('w',encoding='utf8',newline='')as f:\n  w=csv.writer(f);w.writerow(heads);w.writerows([[''if v is None else str(v)for v in r]for r in rows])\nAPI='forest'\nINPUT={'rows': [{'id': 'a', 'x': [0, 0], 'y': 0}, {'id': 'b', 'x': [1, 1], 'y': 1}, {'id': 'c', 'x': [2, 0], 'y': 3}, {'id': 'd', 'x': [3, 1], 'y': 4}], 'queries': [{'id': 'q', 'x': ['3/2', 0]}], 'bootstrapDraws': [['a', 'a', 'b', 'c'], ['b', 'c', 'd', 'd']], 'maxDepth': 2, 'nodeFeatures': [{'': [0], 'L': [1], 'R': [1]}, {'': [1], 'L': [0], 'R': [0]}]}\n\ndef run_fixed(api,a,out,src):\n import matplotlib\n matplotlib.use('svg')\n import matplotlib.pyplot as plt\n from matplotlib.ticker import MaxNLocator\n plt.rcParams.update({'font.size':14,'svg.fonttype':'none','svg.hashsalt':'ml09-fixed-v1'})\n result=variance(a)if api=='variance'else aggregate(a)if api=='aggregate'else ensemble(a,api=='forest')if api in ['bagging','forest']else boost(a)if api=='boost'else realdata(read_sources(src),a['kind'])\n out=Path(out);out.mkdir(parents=True,exist_ok=True);summary={};points=[]\n def add(x,y,s):\n  if y is not None:points.append([x,y,s])\n if api=='variance':\n  summary={'B':result['B'],'varianceOfMean':result['varianceOfMean']};add(result['B'],result['varianceOfMean'],'Specified finite-B variance');xl='Number of members B';yl='Variance, stipulated units squared';title='Declared covariance model, not fitted trees'\n elif api=='aggregate':\n  p=result['predictions'][0];classification=a.get('task')=='classification';summary={'selectedPrediction':p['prediction']}\n  if classification:\n   summary.update(voteLabel=p['vote'],probabilityLabel=p['prob'],meanProbability1=p['probabilities'][1]);add(1,p['probabilities'][1],'Mean probability of class 1');add(2,p['votes'][1],'Label-vote share of class 1');xl='Aggregation (1=probability, 2=vote)';yl='Probability or vote share'\n  else:\n   for i,m in enumerate(a['members']):add(i+1,Q(m['predictions'][0]['value']),'Member prediction')\n   add(3,p['prediction'],'Weighted mean');xl='Member 1, member 2, aggregate 3';yl='Prediction, assumed units'\n  title='Votes and probabilities are distinct objects'\n elif api in ['bagging','forest']:\n  summary={'queryPrediction':result['predictions'][0]['prediction'],'OOB.scoreable':result['outOfBag']['eligibleRows'],'OOB.meanLoss':result['outOfBag']['meanLoss']}\n  for i,r in enumerate(a['rows']):add(i+1,Q(r['y']),'Observed training outcome')\n  for i,p in enumerate(result['outOfBag']['rows']):add(i+1,p['prediction'],'OOB prediction, when defined')\n  xl='Original training ID order';yl='Outcome, assumed units';title='Repeated draws and ID-level OOB membership'\n elif api=='boost':\n  summary={'initial':result['initial'],'finalMSE':result['losses'][-1]['MSE'],'stages':result['stages']}\n  for r in result['losses']:add(r['stage'],r['MSE'],'Training MSE')\n  xl='Boosting stage (0=initial)';yl='Weighted MSE, outcome units squared';title='Training descent does not certify held-out gain'\n else:\n  summary={'outer.scoreable':result['outer']['eligibleRows'],'outer.meanLoss':result['outer']['meanLoss'],'baseline.meanLoss':result['baseline']['meanLoss'],'OOB.scoreable':result['result']['outOfBag']['eligibleRows'],'OOB.meanLoss':result['result']['outOfBag']['meanLoss']}\n  for i,p in enumerate(result['outer']['rows']):\n   add(i+1,Q(p['actual']),'Observed outcome');add(i+1,p['probabilities'][1]if a['kind']=='company'else p['prediction'],'Forest probability of class 1'if a['kind']=='company'else'Forest prediction')\n  xl='Outer-test source order, not a time path';yl='Churn label / probability'if a['kind']=='company'else'Period life expectancy, years'if a['kind']=='country'else'Nominal 1976 USD per hour';title='Fixed forest; outer labels did not fit the trees'\n def display(v):return 'undefined'if v is None else format(float(v),'.9f')\n writecsv(out/'summary.csv',['metric','value'],[[k,display(v)]for k,v in summary.items()]);writecsv(out/'plot-points.csv',['x','y','series'],points);(out/'full.json').write_text(json.dumps(serial(result),indent=2)+'\\n',encoding='utf8')\n fig,ax=plt.subplots(figsize=(5.6,4.6));fig.subplots_adjust(left=.24,right=.96,bottom=.24,top=.76);colors=['#355c72','#a55336','#507956','#78568b']\n for i,s in enumerate(dict.fromkeys(p[2]for p in points)):\n  pp=[p for p in points if p[2]==s];ax.scatter([float(p[0])for p in pp],[float(p[1])for p in pp],s=12 if len(pp)>100 else 32,alpha=.5 if len(pp)>100 else 1,color=colors[i%4],label=s)\n ax.set_xlabel(xl,labelpad=10,fontsize=11);ax.set_ylabel(yl,labelpad=10,fontsize=11);ax.xaxis.set_major_locator(MaxNLocator(3));ax.yaxis.set_major_locator(MaxNLocator(4));ax.grid(alpha=.18);ax.legend(loc='lower left',bbox_to_anchor=(0,1.01),fontsize=9,frameon=False);fig.suptitle(title,fontsize=9,y=.99);fig.savefig(out/'plot.svg',metadata={'Date':None});plt.close(fig);print(', '.join(k+'='+display(v)for k,v in summary.items()))\nif __name__=='__main__':\n import sys\n try:run_fixed(API,INPUT,sys.argv[1]if len(sys.argv)>1 else'fixed-results',sys.argv[2]if len(sys.argv)>2 else'ml09-sources')\n except ValueError as error:print('Rejected declared input: '+str(error),file=sys.stderr);sys.exit(2)\n",
        "inputFiles": [],
        "input": {
          "rows": [
            {
              "id": "a",
              "x": [
                0,
                0
              ],
              "y": 0
            },
            {
              "id": "b",
              "x": [
                1,
                1
              ],
              "y": 1
            },
            {
              "id": "c",
              "x": [
                2,
                0
              ],
              "y": 3
            },
            {
              "id": "d",
              "x": [
                3,
                1
              ],
              "y": 4
            }
          ],
          "queries": [
            {
              "id": "q",
              "x": [
                "3/2",
                0
              ]
            }
          ],
          "bootstrapDraws": [
            [
              "a",
              "a",
              "b",
              "c"
            ],
            [
              "b",
              "c",
              "d",
              "d"
            ]
          ],
          "maxDepth": 2,
          "nodeFeatures": [
            {
              "": [
                0
              ],
              "L": [
                1
              ],
              "R": [
                1
              ]
            },
            {
              "": [
                1
              ],
              "L": [
                0
              ],
              "R": [
                0
              ]
            }
          ]
        },
        "returnCode": 0,
        "expectedFailure": false,
        "stdout": "queryPrediction=1.500000000, OOB.scoreable=2.000000000, OOB.meanLoss=5.000000000\n",
        "stderr": "",
        "summary": {
          "queryPrediction": "1.500000000",
          "OOB.scoreable": "2.000000000",
          "OOB.meanLoss": "5.000000000"
        },
        "plotPoints": [
          {
            "x": "1",
            "y": "0",
            "series": "Observed training outcome"
          },
          {
            "x": "2",
            "y": "1",
            "series": "Observed training outcome"
          },
          {
            "x": "3",
            "y": "3",
            "series": "Observed training outcome"
          },
          {
            "x": "4",
            "y": "4",
            "series": "Observed training outcome"
          },
          {
            "x": "1",
            "y": "3",
            "series": "OOB prediction, when defined"
          },
          {
            "x": "4",
            "y": "3",
            "series": "OOB prediction, when defined"
          }
        ],
        "plotFile": "ml09-fixed-results/forest-node-features-python/plot.svg",
        "plotSHA256": "9da8d85b482861f3011b0553b464de29a8f14e9ab05453568133e55845cfb166",
        "files": [
          {
            "file": "ml09-fixed-results/forest-node-features-python/full.json",
            "sha256": "a371e8e54054de0f4a72253fff493af9fc42df9d393bc50c56e8df65209dd1ae"
          },
          {
            "file": "ml09-fixed-results/forest-node-features-python/plot-points.csv",
            "sha256": "6e9e79545dbd722a0ae5b43c4774fe85f697de98e1653b539dc0855658cf8c65"
          },
          {
            "file": "ml09-fixed-results/forest-node-features-python/plot.svg",
            "sha256": "9da8d85b482861f3011b0553b464de29a8f14e9ab05453568133e55845cfb166"
          },
          {
            "file": "ml09-fixed-results/forest-node-features-python/summary.csv",
            "sha256": "aeb1cf3fe7c1e414b4cb7ec040f68faff28781a60a7014ca0bee4ae9e7cbb6e7"
          }
        ],
        "scope": "Actually executed self-contained fixed example; current web controls execute separately. Python Fraction and finite-precision base R. Author gate, not independent peer."
      },
      "weak-root": {
        "api": "forest",
        "variant": "weak-root",
        "language": "python",
        "codeFile": "ml09-code/forest-weak-root.py",
        "codeSHA256": "51e73a5ed8136b8a614953996c1bf987745381e75ce99e227b6d55a508f4f3f0",
        "codeText": "\"\"\"ML09 exact Fraction reproduction from native source fields.\n\npython ml09-public-analysis.py --source-dir ml09-sources --output-dir results\n\nThis authored educational implementation uses direct-centered leaf losses and\nexhaustive midpoint partitions. It reads no JS engine, model contract, checker,\nstored target answers or derived-result CSV. Its five tree arithmetic helpers\nwere copied from the author's own separate Fraction reference, not an independent\npeer. Parser/work budgets and display rounding of the production JS are separate.\nNumerical predictions/proper scores do not certify causal effects, calibration,\nIID OOB validity, survey representativeness or production parameter optimality.\n\"\"\"\nfrom pathlib import Path\nfrom fractions import Fraction as Q\nimport csv,json,math,itertools,argparse\n\ndef normalized(rows,task='regression'):\n return [dict(id=r.get('id',i),x=[None if x is None else Q(x)for x in r.get('x',[])],y=None if r['y']is None else str(r['y'])if task=='classification'else Q(r['y']),w=Q(r.get('weight',1)))for i,r in enumerate(rows)]\n\ndef totals(rows,task,classes):\n W=sum((r['w']for r in rows),Q());mu=sum((r['w']*r['y']for r in rows),Q())/W if task=='regression'and W else None\n probs=[sum((r['w']for r in rows if r['y']==c),Q())/W for c in classes]if task=='classification'and W else[]\n risk=sum((r['w']*(r['y']-mu)**2 for r in rows),Q())if task=='regression'and W else W*sum((p*(1-p)for p in probs),Q())\n return dict(n=len(rows),w=W,mu=mu,p=probs,risk=risk,pred=mu if task=='regression'else classes[max(range(len(probs)),key=lambda i:probs[i])]if probs else None)\n\ndef fit(rows,a,task,classes,schedule=None):\n good=[r for r in rows if r['w']>0 and r['y']is not None];root=totals(good,task,classes)['w'];depth=a.get('maxDepth',2);minimum=a.get('minLeaf',1);minmass=Q(a.get('minLeafWeight',0));mingain=Q(a.get('minGain',0));route=a.get('missingRoute','best')\n def build(rr,d,path):\n  st=totals(rr,task,classes);n=dict(rows=rr,st=st,split=None,left=None,right=None,path=path)\n  if d==depth:return n\n  best=None\n  for j in range(len(rr[0]['x'])):\n   if schedule is not None and j not in schedule[path]:continue\n   values=sorted({r['x'][j]for r in rr if r['x'][j]is not None});missing=[r for r in rr if r['x'][j]is None];observed=[r for r in rr if r['x'][j]is not None]\n   candidates=[]\n   for lo,hi in zip(values,values[1:]):\n    q=(lo+hi)/2;left=[r for r in observed if r['x'][j]<=q];right=[r for r in observed if r['x'][j]>q];directions=[route]if route!='best'else['left','right']if missing else['left'if len(left)>=len(right)else'right']\n    for direction in directions:candidates.append(('threshold',q,direction,left+missing if direction=='left'else left,right+missing if direction=='right'else right))\n   if missing and observed:candidates.append(('missing-only',None,'left',missing,observed))\n   for kind,q,direction,left,right in candidates:\n    l=totals(left,task,classes);r=totals(right,task,classes)\n    if min(l['n'],r['n'])<minimum or min(l['w'],r['w'])<minmass or min(l['w'],r['w'])<=0:continue\n    gain=(st['risk']-l['risk']-r['risk'])/root\n    if best is None or gain>best['gain']:best=dict(feature=j,kind=kind,threshold=q,missingRoute=direction,left=left,right=right,gain=gain)\n  if best and best['gain']>0 and best['gain']>mingain:\n   j=best['feature'];go=lambda r:r['x'][j]is None if best['kind']=='missing-only'else best['missingRoute']=='left'if r['x'][j]is None else r['x'][j]<=best['threshold'];n['split']=best;n['left']=build([r for r in rr if go(r)],d+1,path+'L');n['right']=build([r for r in rr if not go(r)],d+1,path+'R')\n  return n\n return build(good,0,'')\n\ndef predict(tree,x):\n n=tree\n while n['split']:\n  s=n['split'];v=x[s['feature']];left=v is None if s['kind']=='missing-only'else s['missingRoute']=='left'if v is None else v<=s['threshold'];n=n['left'if left else'right']\n return dict(prediction=n['st']['pred'],probabilities=n['st']['p'])\n\ndef combine(preds,w,task,classes,mode='probabilities'):\n mass=sum(w,Q())\n if not preds or not mass:return dict(prediction=None,probabilities=[],vote=None,prob=None)\n if task=='regression':return dict(prediction=sum((p['prediction']*v for p,v in zip(preds,w)),Q())/mass,probabilities=[],vote=None,prob=None)\n votes=[sum((v for p,v in zip(preds,w)if p['prediction']==c),Q())/mass for c in classes];ps=[sum((p['probabilities'][j]*v for p,v in zip(preds,w)),Q())/mass for j in range(len(classes))];vote=classes[max(range(len(classes)),key=lambda j:votes[j])];prob=classes[max(range(len(classes)),key=lambda j:ps[j])];return dict(prediction=vote if mode=='votes'else prob,probabilities=ps,vote=vote,prob=prob,votes=votes)\ndef number(v):\n if v is None or isinstance(v,bool):raise ValueError('explicit null/bool is not a numeric parameter')\n return Q(v)\ndef variance(a):\n B=a['B'];v=number(a['marginalVariance']);rho=number(a.get('rho',0))\n if not isinstance(B,int)or isinstance(B,bool)or B<1 or v<0:raise ValueError('positive integer B/nonnegative variance')\n if B>1 and v and not -Q(1,B-1)<=rho<=1:raise ValueError('equicorrelation PSD bound')\n return dict(B=B,marginalVariance=v,correlationApplicable=B>1 and bool(v),varianceOfMean=v if B==1 else v*(1+(B-1)*rho)/B)\ndef aggregate(a):\n task=a.get('task','regression');classes=[str(c)for c in a.get('classes',[])];members=a['members'];w=[number(v)for v in a.get('memberWeights',[1]*len(members))]\n if not members or min(w)<0 or sum(w)<=0:raise ValueError('nonnegative member weights/positive total')\n order=[p.get('id',i)for i,p in enumerate(members[0]['predictions'])];keys=lambda x:(type(x).__name__,x);lookup=[{keys(p.get('id',i)):p for i,p in enumerate(m['predictions'])}for m in members]\n if any(set(m)!={keys(v)for v in order}for m in lookup):raise ValueError('same query ID set')\n out=[]\n for pid in order:\n  predictions=[dict(prediction=number(m[keys(pid)]['value']),probabilities=[])if task=='regression'else dict(prediction=str(m[keys(pid)]['label']),probabilities=[number(v)for v in m[keys(pid)]['probabilities']])for m in lookup]\n  if task=='classification'and any(min(p['probabilities'])<0 or sum(p['probabilities'])!=1 for p in predictions):raise ValueError('probability simplex')\n  out.append(dict(id=pid,**combine(predictions,w,task,classes,a.get('aggregation','probabilities'))))\n return dict(task=task,classes=classes,predictions=out)\ndef scored(preds,rows,task,classes):\n mass=loss=absolute=errors=voteerrors=Q();out=[]\n for p,r in zip(preds,rows):\n  ok=p['prediction']is not None and r['y']is not None and r['w']>0;v=None\n  if ok:\n   mass+=r['w']\n   if task=='regression':e=r['y']-p['prediction'];v=e*e;absolute+=r['w']*abs(e)\n   else:v=sum(((q-(1 if r['y']==c else 0))**2 for c,q in zip(classes,p['probabilities'])),Q());errors+=r['w']*(p['prediction']!=r['y']);voteerrors+=r['w']*(p['vote']!=r['y'])\n   loss+=r['w']*v\n  out.append(dict(p,actual=r['y'],weight=r['w'],scoreEligible=ok,loss=v))\n return dict(rows=out,eligibleRows=sum(r['scoreEligible']for r in out),weight=mass,totalLoss=loss,meanLoss=loss/mass if mass else None,MAE=absolute/mass if mass and task=='regression'else None,errorRate=errors/mass if mass and task=='classification'else None,labelVoteErrorRate=voteerrors/mass if mass and task=='classification'else None)\ndef ensemble(a,forest=False):\n task=a.get('task','regression');classes=[str(v)for v in(a.get('classes')or[])];rr=normalized(a['rows'],task);key=lambda x:(type(x).__name__,x);lookup={key(r['id']):r for r in rr};weights=[number(v)for v in a.get('memberWeights',[1]*len(a['bootstrapDraws']))]\n if not any(r['w']>0 and r['y']is not None for r in rr)or min(weights)<0 or sum(weights)<=0:raise ValueError('positive eligible training and member weight')\n members=[]\n for i,draw in enumerate(a['bootstrapDraws']):\n  data=[lookup[key(v)]for v in draw];schedule=a['nodeFeatures'][i]if forest else None;model=fit(data,a,task,classes,schedule);inbag={key(v)for v in draw};members.append(dict(tree=model,draw=draw,inbag=inbag,weight=weights[i]))\n predictions=[]\n for q in a.get('queries',[]):predictions.append(dict(id=q['id'],**combine([predict(m['tree'],[None if v is None else number(v)for v in q['x']])for m in members],weights,task,classes,a.get('aggregation','probabilities'))))\n oob=[]\n for r in rr:\n  applicable=[i for i,m in enumerate(members)if key(r['id'])not in m['inbag']];p=combine([predict(members[i]['tree'],r['x'])for i in applicable],[weights[i]for i in applicable],task,classes,a.get('aggregation','probabilities'));oob.append(dict(id=r['id'],applicable=applicable,positiveMembers=sum(weights[i]>0 for i in applicable),**p))\n return dict(task=task,classes=classes,members=members,predictions=predictions,outOfBag=scored(oob,rr,task,classes))\ndef boost(a):\n if a.get('task','regression')!='regression':raise ValueError('regression boosting only')\n rr=normalized(a['rows']);good=[r for r in rr if r['w']and r['y']is not None];W=sum((r['w']for r in good),Q())\n if not W:raise ValueError('positive eligible training')\n eta=number(a.get('learningRate','1/2'));stages=a.get('stages',3)\n if not 0<=eta<=1 or not isinstance(stages,int)or isinstance(stages,bool)or not 0<=stages<=8:raise ValueError('supported rate/stages')\n initial=number(a['initial'])if'initial'in a else sum((r['w']*r['y']for r in good),Q())/W;training=[[initial]for r in rr];queries=[[initial]for q in a.get('queries',[])];fits=[];losses=[]\n for stage in range(stages+1):\n  sse=sum((r['w']*(r['y']-p[-1])**2 for r,p in zip(rr,training)if r['w']and r['y']is not None),Q());losses.append(dict(stage=stage,rawWeightedSSE=sse,MSE=sse/W,meanHalfSquaredLoss=sse/(2*W)))\n  if stage==stages:break\n  residuals=[dict(r,y=None if r['y']is None else r['y']-p[-1])for r,p in zip(rr,training)];tree=fit(residuals,a,'regression',[]);h=[predict(tree,r['x'])['prediction']for r in rr];qh=[predict(tree,[None if v is None else number(v)for v in q['x']])['prediction']for q in a.get('queries',[])];norm=sum((r['w']*v*v for r,v in zip(rr,h)if r['y']is not None),Q());stageRows=[]\n  for i,(r,p)in enumerate(zip(rr,training)):\n   residual=None if r['y']is None else r['y']-p[-1];stageRows.append(dict(id=r['id'],before=p[-1],residual=residual,negativeCoordinateDerivative=None if residual is None else r['w']*residual/W,fit=h[i],addition=eta*h[i],after=p[-1]+eta*h[i]));p.append(p[-1]+eta*h[i])\n  for p,v in zip(queries,qh):p.append(p[-1]+eta*v)\n  fits.append(dict(stage=stage+1,tree=tree,rows=stageRows,queryFits=qh,norm=norm,predictedSSEDecrease=eta*(2-eta)*norm))\n return dict(task='regression',initial=initial,learningRate=eta,stages=stages,training=training,queries=queries,fits=fits,losses=losses,predictions=[dict(id=q['id'],prediction=p[-1],probabilities=[],vote=None,prob=None)for q,p in zip(a.get('queries',[]),queries)])\nclass Stream:\n def __init__(self,state):self.state=state\n def choose(self,n):\n  limit=(1<<32)-((1<<32)%n)\n  while True:\n   self.state=(1664525*self.state+1013904223)&0xffffffff\n   if self.state<limit:return self.state%n\ndef fixed_schedules(ids,p,seed):\n stream=Stream(seed);draws=[];schedules=[];paths=['']+[p for d in[1,2]for p in map(''.join,itertools.product('LR',repeat=d))]\n for member in range(4):\n  draws.append([ids[stream.choose(len(ids))]for _ in range(len(ids))]);schedule={}\n  for path in paths:\n   order=list(range(p))\n   for j in range(p-1,0,-1):k=stream.choose(j+1);order[j],order[k]=order[k],order[j]\n   schedule[path]=sorted(order[:max(1,int(math.sqrt(p)))])\n  schedules.append(schedule)\n return draws,schedules\ndef csvread(file):\n with Path(file).open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))\ndef read_sources(source):\n source=Path(source);raw=csvread(source/'actual320-country-four-indicators-original-2020-2024.csv');lookup={(r['countryISO3'],int(r['date']),r['indicatorID']):r for r in raw};country=[]\n for code in sorted({r['countryISO3']for r in raw}):\n  for year in range(2020,2025):\n   cols=['NY.GDP.PCAP.KD','NY.GDP.MKTP.KD.ZG','FP.CPI.TOTL.ZG','SP.DYN.LE00.IN'];v=[lookup[code,year,k]['originalValueToken']for k in cols];x=[None if not z else Q(z)for z in v[:3]];x[0]=None if x[0]is None else x[0]/10000;y=None if not v[3]else Q(v[3]);eligible=y is not None and None not in x;country.append(dict(id=code+':'+str(year),sourceRow=code+':'+str(year),originalID=code,year=year,x=x,y=y,weight='1',role='excluded'if not eligible else'outer-test'if year==2024 else'train'))\n person=[]\n for i,r in enumerate(csvread(source/'actual3613-NLS-original52-fields-and-selection.csv'),1):\n  v=lambda k:None if r[k]=='.'else Q(r[k]);x=[v('ed76'),v('age76')];y=None if v('wage76')is None else v('wage76')/100;eligible=y is not None and None not in x;person.append(dict(id='person:'+str(i),sourceRow=str(i),originalID=r['id'],x=x,y=y,weight='1',role='excluded'if not eligible else'outer-test'if i%5==0 else'train'))\n company=[]\n for i,r in enumerate(csvread(source/'actual3150-churn-original14-fields-and-selection.csv'),1):company.append(dict(id='customer:'+str(i),sourceRow=str(i),originalID='',x=[Q(r[k])for k in['Call  Failure','Subscription  Length','Charge  Amount']],y=r['Churn'],weight='1',role='outer-test'if i%5==0 else'train'))\n models={}\n for index,(kind,rr,task,leaf)in enumerate([('country',country,'regression',4),('person',person,'regression',50),('company',company,'classification',30)]):\n  ids=[r['id']for r in rr if r['role']=='train'];draws,schedules=fixed_schedules(ids,len(rr[0]['x']),20261102+7919*index);models[kind]=dict(records=rr,task=task,classes=['0','1']if task=='classification'else[],draws=draws,schedules=schedules,minLeaf=leaf)\n return models\n_OMITTED=object()\ndef realdata(models,kind,options=_OMITTED):\n options={}if options is _OMITTED else options\n if not isinstance(options,dict):raise ValueError('options object required, not explicit null')\n m=models[kind];train=[r for r in m['records']if r['role']=='train'];test=[r for r in m['records']if r['role']=='outer-test'];method=options.get('method','forest');depth=options.get('maxDepth',2);count=options.get('memberCount',3);a=dict(rows=train,queries=[dict(id=r['id'],x=r['x'])for r in test],task=m['task'],classes=m['classes'],maxDepth=depth,minLeaf=options.get('minLeaf',m['minLeaf']),minLeafWeight='0',minGain='0',missingRoute='best',learningRate=options.get('learningRate','1/2'),stages=options.get('stages',3))\n if method not in ['bagging','forest','boost']:raise ValueError('known source method')\n if not isinstance(depth,int)or isinstance(depth,bool)or not 0<=depth<=3:raise ValueError('source depth0..3')\n if method!='boost'and(not isinstance(count,int)or isinstance(count,bool)or not 1<=count<=4):raise ValueError('source member count1..4')\n if method=='boost':result=boost(a)\n else:\n  a.update(bootstrapDraws=m['draws'][:count],nodeFeatures=[{p:v for p,v in s.items()if len(p)<depth}for s in m['schedules'][:count]]);result=ensemble(a,method=='forest')\n outer=scored(result['predictions'],normalized(test,m['task']),m['task'],m['classes']);st=totals([r for r in normalized(train,m['task'])if r['w']and r['y']is not None],m['task'],m['classes']);constant=dict(prediction=st['pred'],probabilities=st['p'],vote=st['pred'],prob=st['pred']);baseline=scored([dict(id=r['id'],**constant)for r in test],normalized(test,m['task']),m['task'],m['classes']);return dict(kind=kind,method=method,settings=a,train=train,test=test,result=result,outer=outer,baseline=baseline)\ndef serial(x):\n if isinstance(x,Q):return str(x)\n if isinstance(x,dict):return{k:serial(v)for k,v in x.items()if k not in['inbag','tree']}\n if isinstance(x,(list,tuple)):return[serial(v)for v in x]\n return x\ndef writecsv(file,heads,rows):\n with Path(file).open('w',encoding='utf8',newline='')as f:\n  w=csv.writer(f);w.writerow(heads);w.writerows([[''if v is None else str(v)for v in r]for r in rows])\nAPI='forest'\nINPUT={'rows': [{'id': '0', 'x': [0, 0], 'y': 0}, {'id': '1', 'x': [0, 1], 'y': 2}, {'id': '2', 'x': [0, 2], 'y': 4}, {'id': '3', 'x': [0, 3], 'y': 6}], 'queries': [{'id': 'q', 'x': [0, '3/2']}], 'bootstrapDraws': [['0', '1', '2', '3']], 'nodeFeatures': [{'': [0]}], 'maxDepth': 1}\n\ndef run_fixed(api,a,out,src):\n import matplotlib\n matplotlib.use('svg')\n import matplotlib.pyplot as plt\n from matplotlib.ticker import MaxNLocator\n plt.rcParams.update({'font.size':14,'svg.fonttype':'none','svg.hashsalt':'ml09-fixed-v1'})\n result=variance(a)if api=='variance'else aggregate(a)if api=='aggregate'else ensemble(a,api=='forest')if api in ['bagging','forest']else boost(a)if api=='boost'else realdata(read_sources(src),a['kind'])\n out=Path(out);out.mkdir(parents=True,exist_ok=True);summary={};points=[]\n def add(x,y,s):\n  if y is not None:points.append([x,y,s])\n if api=='variance':\n  summary={'B':result['B'],'varianceOfMean':result['varianceOfMean']};add(result['B'],result['varianceOfMean'],'Specified finite-B variance');xl='Number of members B';yl='Variance, stipulated units squared';title='Declared covariance model, not fitted trees'\n elif api=='aggregate':\n  p=result['predictions'][0];classification=a.get('task')=='classification';summary={'selectedPrediction':p['prediction']}\n  if classification:\n   summary.update(voteLabel=p['vote'],probabilityLabel=p['prob'],meanProbability1=p['probabilities'][1]);add(1,p['probabilities'][1],'Mean probability of class 1');add(2,p['votes'][1],'Label-vote share of class 1');xl='Aggregation (1=probability, 2=vote)';yl='Probability or vote share'\n  else:\n   for i,m in enumerate(a['members']):add(i+1,Q(m['predictions'][0]['value']),'Member prediction')\n   add(3,p['prediction'],'Weighted mean');xl='Member 1, member 2, aggregate 3';yl='Prediction, assumed units'\n  title='Votes and probabilities are distinct objects'\n elif api in ['bagging','forest']:\n  summary={'queryPrediction':result['predictions'][0]['prediction'],'OOB.scoreable':result['outOfBag']['eligibleRows'],'OOB.meanLoss':result['outOfBag']['meanLoss']}\n  for i,r in enumerate(a['rows']):add(i+1,Q(r['y']),'Observed training outcome')\n  for i,p in enumerate(result['outOfBag']['rows']):add(i+1,p['prediction'],'OOB prediction, when defined')\n  xl='Original training ID order';yl='Outcome, assumed units';title='Repeated draws and ID-level OOB membership'\n elif api=='boost':\n  summary={'initial':result['initial'],'finalMSE':result['losses'][-1]['MSE'],'stages':result['stages']}\n  for r in result['losses']:add(r['stage'],r['MSE'],'Training MSE')\n  xl='Boosting stage (0=initial)';yl='Weighted MSE, outcome units squared';title='Training descent does not certify held-out gain'\n else:\n  summary={'outer.scoreable':result['outer']['eligibleRows'],'outer.meanLoss':result['outer']['meanLoss'],'baseline.meanLoss':result['baseline']['meanLoss'],'OOB.scoreable':result['result']['outOfBag']['eligibleRows'],'OOB.meanLoss':result['result']['outOfBag']['meanLoss']}\n  for i,p in enumerate(result['outer']['rows']):\n   add(i+1,Q(p['actual']),'Observed outcome');add(i+1,p['probabilities'][1]if a['kind']=='company'else p['prediction'],'Forest probability of class 1'if a['kind']=='company'else'Forest prediction')\n  xl='Outer-test source order, not a time path';yl='Churn label / probability'if a['kind']=='company'else'Period life expectancy, years'if a['kind']=='country'else'Nominal 1976 USD per hour';title='Fixed forest; outer labels did not fit the trees'\n def display(v):return 'undefined'if v is None else format(float(v),'.9f')\n writecsv(out/'summary.csv',['metric','value'],[[k,display(v)]for k,v in summary.items()]);writecsv(out/'plot-points.csv',['x','y','series'],points);(out/'full.json').write_text(json.dumps(serial(result),indent=2)+'\\n',encoding='utf8')\n fig,ax=plt.subplots(figsize=(5.6,4.6));fig.subplots_adjust(left=.24,right=.96,bottom=.24,top=.76);colors=['#355c72','#a55336','#507956','#78568b']\n for i,s in enumerate(dict.fromkeys(p[2]for p in points)):\n  pp=[p for p in points if p[2]==s];ax.scatter([float(p[0])for p in pp],[float(p[1])for p in pp],s=12 if len(pp)>100 else 32,alpha=.5 if len(pp)>100 else 1,color=colors[i%4],label=s)\n ax.set_xlabel(xl,labelpad=10,fontsize=11);ax.set_ylabel(yl,labelpad=10,fontsize=11);ax.xaxis.set_major_locator(MaxNLocator(3));ax.yaxis.set_major_locator(MaxNLocator(4));ax.grid(alpha=.18);ax.legend(loc='lower left',bbox_to_anchor=(0,1.01),fontsize=9,frameon=False);fig.suptitle(title,fontsize=9,y=.99);fig.savefig(out/'plot.svg',metadata={'Date':None});plt.close(fig);print(', '.join(k+'='+display(v)for k,v in summary.items()))\nif __name__=='__main__':\n import sys\n try:run_fixed(API,INPUT,sys.argv[1]if len(sys.argv)>1 else'fixed-results',sys.argv[2]if len(sys.argv)>2 else'ml09-sources')\n except ValueError as error:print('Rejected declared input: '+str(error),file=sys.stderr);sys.exit(2)\n",
        "code": "\"\"\"ML09 exact Fraction reproduction from native source fields.\n\npython ml09-public-analysis.py --source-dir ml09-sources --output-dir results\n\nThis authored educational implementation uses direct-centered leaf losses and\nexhaustive midpoint partitions. It reads no JS engine, model contract, checker,\nstored target answers or derived-result CSV. Its five tree arithmetic helpers\nwere copied from the author's own separate Fraction reference, not an independent\npeer. Parser/work budgets and display rounding of the production JS are separate.\nNumerical predictions/proper scores do not certify causal effects, calibration,\nIID OOB validity, survey representativeness or production parameter optimality.\n\"\"\"\nfrom pathlib import Path\nfrom fractions import Fraction as Q\nimport csv,json,math,itertools,argparse\n\ndef normalized(rows,task='regression'):\n return [dict(id=r.get('id',i),x=[None if x is None else Q(x)for x in r.get('x',[])],y=None if r['y']is None else str(r['y'])if task=='classification'else Q(r['y']),w=Q(r.get('weight',1)))for i,r in enumerate(rows)]\n\ndef totals(rows,task,classes):\n W=sum((r['w']for r in rows),Q());mu=sum((r['w']*r['y']for r in rows),Q())/W if task=='regression'and W else None\n probs=[sum((r['w']for r in rows if r['y']==c),Q())/W for c in classes]if task=='classification'and W else[]\n risk=sum((r['w']*(r['y']-mu)**2 for r in rows),Q())if task=='regression'and W else W*sum((p*(1-p)for p in probs),Q())\n return dict(n=len(rows),w=W,mu=mu,p=probs,risk=risk,pred=mu if task=='regression'else classes[max(range(len(probs)),key=lambda i:probs[i])]if probs else None)\n\ndef fit(rows,a,task,classes,schedule=None):\n good=[r for r in rows if r['w']>0 and r['y']is not None];root=totals(good,task,classes)['w'];depth=a.get('maxDepth',2);minimum=a.get('minLeaf',1);minmass=Q(a.get('minLeafWeight',0));mingain=Q(a.get('minGain',0));route=a.get('missingRoute','best')\n def build(rr,d,path):\n  st=totals(rr,task,classes);n=dict(rows=rr,st=st,split=None,left=None,right=None,path=path)\n  if d==depth:return n\n  best=None\n  for j in range(len(rr[0]['x'])):\n   if schedule is not None and j not in schedule[path]:continue\n   values=sorted({r['x'][j]for r in rr if r['x'][j]is not None});missing=[r for r in rr if r['x'][j]is None];observed=[r for r in rr if r['x'][j]is not None]\n   candidates=[]\n   for lo,hi in zip(values,values[1:]):\n    q=(lo+hi)/2;left=[r for r in observed if r['x'][j]<=q];right=[r for r in observed if r['x'][j]>q];directions=[route]if route!='best'else['left','right']if missing else['left'if len(left)>=len(right)else'right']\n    for direction in directions:candidates.append(('threshold',q,direction,left+missing if direction=='left'else left,right+missing if direction=='right'else right))\n   if missing and observed:candidates.append(('missing-only',None,'left',missing,observed))\n   for kind,q,direction,left,right in candidates:\n    l=totals(left,task,classes);r=totals(right,task,classes)\n    if min(l['n'],r['n'])<minimum or min(l['w'],r['w'])<minmass or min(l['w'],r['w'])<=0:continue\n    gain=(st['risk']-l['risk']-r['risk'])/root\n    if best is None or gain>best['gain']:best=dict(feature=j,kind=kind,threshold=q,missingRoute=direction,left=left,right=right,gain=gain)\n  if best and best['gain']>0 and best['gain']>mingain:\n   j=best['feature'];go=lambda r:r['x'][j]is None if best['kind']=='missing-only'else best['missingRoute']=='left'if r['x'][j]is None else r['x'][j]<=best['threshold'];n['split']=best;n['left']=build([r for r in rr if go(r)],d+1,path+'L');n['right']=build([r for r in rr if not go(r)],d+1,path+'R')\n  return n\n return build(good,0,'')\n\ndef predict(tree,x):\n n=tree\n while n['split']:\n  s=n['split'];v=x[s['feature']];left=v is None if s['kind']=='missing-only'else s['missingRoute']=='left'if v is None else v<=s['threshold'];n=n['left'if left else'right']\n return dict(prediction=n['st']['pred'],probabilities=n['st']['p'])\n\ndef combine(preds,w,task,classes,mode='probabilities'):\n mass=sum(w,Q())\n if not preds or not mass:return dict(prediction=None,probabilities=[],vote=None,prob=None)\n if task=='regression':return dict(prediction=sum((p['prediction']*v for p,v in zip(preds,w)),Q())/mass,probabilities=[],vote=None,prob=None)\n votes=[sum((v for p,v in zip(preds,w)if p['prediction']==c),Q())/mass for c in classes];ps=[sum((p['probabilities'][j]*v for p,v in zip(preds,w)),Q())/mass for j in range(len(classes))];vote=classes[max(range(len(classes)),key=lambda j:votes[j])];prob=classes[max(range(len(classes)),key=lambda j:ps[j])];return dict(prediction=vote if mode=='votes'else prob,probabilities=ps,vote=vote,prob=prob,votes=votes)\ndef number(v):\n if v is None or isinstance(v,bool):raise ValueError('explicit null/bool is not a numeric parameter')\n return Q(v)\ndef variance(a):\n B=a['B'];v=number(a['marginalVariance']);rho=number(a.get('rho',0))\n if not isinstance(B,int)or isinstance(B,bool)or B<1 or v<0:raise ValueError('positive integer B/nonnegative variance')\n if B>1 and v and not -Q(1,B-1)<=rho<=1:raise ValueError('equicorrelation PSD bound')\n return dict(B=B,marginalVariance=v,correlationApplicable=B>1 and bool(v),varianceOfMean=v if B==1 else v*(1+(B-1)*rho)/B)\ndef aggregate(a):\n task=a.get('task','regression');classes=[str(c)for c in a.get('classes',[])];members=a['members'];w=[number(v)for v in a.get('memberWeights',[1]*len(members))]\n if not members or min(w)<0 or sum(w)<=0:raise ValueError('nonnegative member weights/positive total')\n order=[p.get('id',i)for i,p in enumerate(members[0]['predictions'])];keys=lambda x:(type(x).__name__,x);lookup=[{keys(p.get('id',i)):p for i,p in enumerate(m['predictions'])}for m in members]\n if any(set(m)!={keys(v)for v in order}for m in lookup):raise ValueError('same query ID set')\n out=[]\n for pid in order:\n  predictions=[dict(prediction=number(m[keys(pid)]['value']),probabilities=[])if task=='regression'else dict(prediction=str(m[keys(pid)]['label']),probabilities=[number(v)for v in m[keys(pid)]['probabilities']])for m in lookup]\n  if task=='classification'and any(min(p['probabilities'])<0 or sum(p['probabilities'])!=1 for p in predictions):raise ValueError('probability simplex')\n  out.append(dict(id=pid,**combine(predictions,w,task,classes,a.get('aggregation','probabilities'))))\n return dict(task=task,classes=classes,predictions=out)\ndef scored(preds,rows,task,classes):\n mass=loss=absolute=errors=voteerrors=Q();out=[]\n for p,r in zip(preds,rows):\n  ok=p['prediction']is not None and r['y']is not None and r['w']>0;v=None\n  if ok:\n   mass+=r['w']\n   if task=='regression':e=r['y']-p['prediction'];v=e*e;absolute+=r['w']*abs(e)\n   else:v=sum(((q-(1 if r['y']==c else 0))**2 for c,q in zip(classes,p['probabilities'])),Q());errors+=r['w']*(p['prediction']!=r['y']);voteerrors+=r['w']*(p['vote']!=r['y'])\n   loss+=r['w']*v\n  out.append(dict(p,actual=r['y'],weight=r['w'],scoreEligible=ok,loss=v))\n return dict(rows=out,eligibleRows=sum(r['scoreEligible']for r in out),weight=mass,totalLoss=loss,meanLoss=loss/mass if mass else None,MAE=absolute/mass if mass and task=='regression'else None,errorRate=errors/mass if mass and task=='classification'else None,labelVoteErrorRate=voteerrors/mass if mass and task=='classification'else None)\ndef ensemble(a,forest=False):\n task=a.get('task','regression');classes=[str(v)for v in(a.get('classes')or[])];rr=normalized(a['rows'],task);key=lambda x:(type(x).__name__,x);lookup={key(r['id']):r for r in rr};weights=[number(v)for v in a.get('memberWeights',[1]*len(a['bootstrapDraws']))]\n if not any(r['w']>0 and r['y']is not None for r in rr)or min(weights)<0 or sum(weights)<=0:raise ValueError('positive eligible training and member weight')\n members=[]\n for i,draw in enumerate(a['bootstrapDraws']):\n  data=[lookup[key(v)]for v in draw];schedule=a['nodeFeatures'][i]if forest else None;model=fit(data,a,task,classes,schedule);inbag={key(v)for v in draw};members.append(dict(tree=model,draw=draw,inbag=inbag,weight=weights[i]))\n predictions=[]\n for q in a.get('queries',[]):predictions.append(dict(id=q['id'],**combine([predict(m['tree'],[None if v is None else number(v)for v in q['x']])for m in members],weights,task,classes,a.get('aggregation','probabilities'))))\n oob=[]\n for r in rr:\n  applicable=[i for i,m in enumerate(members)if key(r['id'])not in m['inbag']];p=combine([predict(members[i]['tree'],r['x'])for i in applicable],[weights[i]for i in applicable],task,classes,a.get('aggregation','probabilities'));oob.append(dict(id=r['id'],applicable=applicable,positiveMembers=sum(weights[i]>0 for i in applicable),**p))\n return dict(task=task,classes=classes,members=members,predictions=predictions,outOfBag=scored(oob,rr,task,classes))\ndef boost(a):\n if a.get('task','regression')!='regression':raise ValueError('regression boosting only')\n rr=normalized(a['rows']);good=[r for r in rr if r['w']and r['y']is not None];W=sum((r['w']for r in good),Q())\n if not W:raise ValueError('positive eligible training')\n eta=number(a.get('learningRate','1/2'));stages=a.get('stages',3)\n if not 0<=eta<=1 or not isinstance(stages,int)or isinstance(stages,bool)or not 0<=stages<=8:raise ValueError('supported rate/stages')\n initial=number(a['initial'])if'initial'in a else sum((r['w']*r['y']for r in good),Q())/W;training=[[initial]for r in rr];queries=[[initial]for q in a.get('queries',[])];fits=[];losses=[]\n for stage in range(stages+1):\n  sse=sum((r['w']*(r['y']-p[-1])**2 for r,p in zip(rr,training)if r['w']and r['y']is not None),Q());losses.append(dict(stage=stage,rawWeightedSSE=sse,MSE=sse/W,meanHalfSquaredLoss=sse/(2*W)))\n  if stage==stages:break\n  residuals=[dict(r,y=None if r['y']is None else r['y']-p[-1])for r,p in zip(rr,training)];tree=fit(residuals,a,'regression',[]);h=[predict(tree,r['x'])['prediction']for r in rr];qh=[predict(tree,[None if v is None else number(v)for v in q['x']])['prediction']for q in a.get('queries',[])];norm=sum((r['w']*v*v for r,v in zip(rr,h)if r['y']is not None),Q());stageRows=[]\n  for i,(r,p)in enumerate(zip(rr,training)):\n   residual=None if r['y']is None else r['y']-p[-1];stageRows.append(dict(id=r['id'],before=p[-1],residual=residual,negativeCoordinateDerivative=None if residual is None else r['w']*residual/W,fit=h[i],addition=eta*h[i],after=p[-1]+eta*h[i]));p.append(p[-1]+eta*h[i])\n  for p,v in zip(queries,qh):p.append(p[-1]+eta*v)\n  fits.append(dict(stage=stage+1,tree=tree,rows=stageRows,queryFits=qh,norm=norm,predictedSSEDecrease=eta*(2-eta)*norm))\n return dict(task='regression',initial=initial,learningRate=eta,stages=stages,training=training,queries=queries,fits=fits,losses=losses,predictions=[dict(id=q['id'],prediction=p[-1],probabilities=[],vote=None,prob=None)for q,p in zip(a.get('queries',[]),queries)])\nclass Stream:\n def __init__(self,state):self.state=state\n def choose(self,n):\n  limit=(1<<32)-((1<<32)%n)\n  while True:\n   self.state=(1664525*self.state+1013904223)&0xffffffff\n   if self.state<limit:return self.state%n\ndef fixed_schedules(ids,p,seed):\n stream=Stream(seed);draws=[];schedules=[];paths=['']+[p for d in[1,2]for p in map(''.join,itertools.product('LR',repeat=d))]\n for member in range(4):\n  draws.append([ids[stream.choose(len(ids))]for _ in range(len(ids))]);schedule={}\n  for path in paths:\n   order=list(range(p))\n   for j in range(p-1,0,-1):k=stream.choose(j+1);order[j],order[k]=order[k],order[j]\n   schedule[path]=sorted(order[:max(1,int(math.sqrt(p)))])\n  schedules.append(schedule)\n return draws,schedules\ndef csvread(file):\n with Path(file).open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))\ndef read_sources(source):\n source=Path(source);raw=csvread(source/'actual320-country-four-indicators-original-2020-2024.csv');lookup={(r['countryISO3'],int(r['date']),r['indicatorID']):r for r in raw};country=[]\n for code in sorted({r['countryISO3']for r in raw}):\n  for year in range(2020,2025):\n   cols=['NY.GDP.PCAP.KD','NY.GDP.MKTP.KD.ZG','FP.CPI.TOTL.ZG','SP.DYN.LE00.IN'];v=[lookup[code,year,k]['originalValueToken']for k in cols];x=[None if not z else Q(z)for z in v[:3]];x[0]=None if x[0]is None else x[0]/10000;y=None if not v[3]else Q(v[3]);eligible=y is not None and None not in x;country.append(dict(id=code+':'+str(year),sourceRow=code+':'+str(year),originalID=code,year=year,x=x,y=y,weight='1',role='excluded'if not eligible else'outer-test'if year==2024 else'train'))\n person=[]\n for i,r in enumerate(csvread(source/'actual3613-NLS-original52-fields-and-selection.csv'),1):\n  v=lambda k:None if r[k]=='.'else Q(r[k]);x=[v('ed76'),v('age76')];y=None if v('wage76')is None else v('wage76')/100;eligible=y is not None and None not in x;person.append(dict(id='person:'+str(i),sourceRow=str(i),originalID=r['id'],x=x,y=y,weight='1',role='excluded'if not eligible else'outer-test'if i%5==0 else'train'))\n company=[]\n for i,r in enumerate(csvread(source/'actual3150-churn-original14-fields-and-selection.csv'),1):company.append(dict(id='customer:'+str(i),sourceRow=str(i),originalID='',x=[Q(r[k])for k in['Call  Failure','Subscription  Length','Charge  Amount']],y=r['Churn'],weight='1',role='outer-test'if i%5==0 else'train'))\n models={}\n for index,(kind,rr,task,leaf)in enumerate([('country',country,'regression',4),('person',person,'regression',50),('company',company,'classification',30)]):\n  ids=[r['id']for r in rr if r['role']=='train'];draws,schedules=fixed_schedules(ids,len(rr[0]['x']),20261102+7919*index);models[kind]=dict(records=rr,task=task,classes=['0','1']if task=='classification'else[],draws=draws,schedules=schedules,minLeaf=leaf)\n return models\n_OMITTED=object()\ndef realdata(models,kind,options=_OMITTED):\n options={}if options is _OMITTED else options\n if not isinstance(options,dict):raise ValueError('options object required, not explicit null')\n m=models[kind];train=[r for r in m['records']if r['role']=='train'];test=[r for r in m['records']if r['role']=='outer-test'];method=options.get('method','forest');depth=options.get('maxDepth',2);count=options.get('memberCount',3);a=dict(rows=train,queries=[dict(id=r['id'],x=r['x'])for r in test],task=m['task'],classes=m['classes'],maxDepth=depth,minLeaf=options.get('minLeaf',m['minLeaf']),minLeafWeight='0',minGain='0',missingRoute='best',learningRate=options.get('learningRate','1/2'),stages=options.get('stages',3))\n if method not in ['bagging','forest','boost']:raise ValueError('known source method')\n if not isinstance(depth,int)or isinstance(depth,bool)or not 0<=depth<=3:raise ValueError('source depth0..3')\n if method!='boost'and(not isinstance(count,int)or isinstance(count,bool)or not 1<=count<=4):raise ValueError('source member count1..4')\n if method=='boost':result=boost(a)\n else:\n  a.update(bootstrapDraws=m['draws'][:count],nodeFeatures=[{p:v for p,v in s.items()if len(p)<depth}for s in m['schedules'][:count]]);result=ensemble(a,method=='forest')\n outer=scored(result['predictions'],normalized(test,m['task']),m['task'],m['classes']);st=totals([r for r in normalized(train,m['task'])if r['w']and r['y']is not None],m['task'],m['classes']);constant=dict(prediction=st['pred'],probabilities=st['p'],vote=st['pred'],prob=st['pred']);baseline=scored([dict(id=r['id'],**constant)for r in test],normalized(test,m['task']),m['task'],m['classes']);return dict(kind=kind,method=method,settings=a,train=train,test=test,result=result,outer=outer,baseline=baseline)\ndef serial(x):\n if isinstance(x,Q):return str(x)\n if isinstance(x,dict):return{k:serial(v)for k,v in x.items()if k not in['inbag','tree']}\n if isinstance(x,(list,tuple)):return[serial(v)for v in x]\n return x\ndef writecsv(file,heads,rows):\n with Path(file).open('w',encoding='utf8',newline='')as f:\n  w=csv.writer(f);w.writerow(heads);w.writerows([[''if v is None else str(v)for v in r]for r in rows])\nAPI='forest'\nINPUT={'rows': [{'id': '0', 'x': [0, 0], 'y': 0}, {'id': '1', 'x': [0, 1], 'y': 2}, {'id': '2', 'x': [0, 2], 'y': 4}, {'id': '3', 'x': [0, 3], 'y': 6}], 'queries': [{'id': 'q', 'x': [0, '3/2']}], 'bootstrapDraws': [['0', '1', '2', '3']], 'nodeFeatures': [{'': [0]}], 'maxDepth': 1}\n\ndef run_fixed(api,a,out,src):\n import matplotlib\n matplotlib.use('svg')\n import matplotlib.pyplot as plt\n from matplotlib.ticker import MaxNLocator\n plt.rcParams.update({'font.size':14,'svg.fonttype':'none','svg.hashsalt':'ml09-fixed-v1'})\n result=variance(a)if api=='variance'else aggregate(a)if api=='aggregate'else ensemble(a,api=='forest')if api in ['bagging','forest']else boost(a)if api=='boost'else realdata(read_sources(src),a['kind'])\n out=Path(out);out.mkdir(parents=True,exist_ok=True);summary={};points=[]\n def add(x,y,s):\n  if y is not None:points.append([x,y,s])\n if api=='variance':\n  summary={'B':result['B'],'varianceOfMean':result['varianceOfMean']};add(result['B'],result['varianceOfMean'],'Specified finite-B variance');xl='Number of members B';yl='Variance, stipulated units squared';title='Declared covariance model, not fitted trees'\n elif api=='aggregate':\n  p=result['predictions'][0];classification=a.get('task')=='classification';summary={'selectedPrediction':p['prediction']}\n  if classification:\n   summary.update(voteLabel=p['vote'],probabilityLabel=p['prob'],meanProbability1=p['probabilities'][1]);add(1,p['probabilities'][1],'Mean probability of class 1');add(2,p['votes'][1],'Label-vote share of class 1');xl='Aggregation (1=probability, 2=vote)';yl='Probability or vote share'\n  else:\n   for i,m in enumerate(a['members']):add(i+1,Q(m['predictions'][0]['value']),'Member prediction')\n   add(3,p['prediction'],'Weighted mean');xl='Member 1, member 2, aggregate 3';yl='Prediction, assumed units'\n  title='Votes and probabilities are distinct objects'\n elif api in ['bagging','forest']:\n  summary={'queryPrediction':result['predictions'][0]['prediction'],'OOB.scoreable':result['outOfBag']['eligibleRows'],'OOB.meanLoss':result['outOfBag']['meanLoss']}\n  for i,r in enumerate(a['rows']):add(i+1,Q(r['y']),'Observed training outcome')\n  for i,p in enumerate(result['outOfBag']['rows']):add(i+1,p['prediction'],'OOB prediction, when defined')\n  xl='Original training ID order';yl='Outcome, assumed units';title='Repeated draws and ID-level OOB membership'\n elif api=='boost':\n  summary={'initial':result['initial'],'finalMSE':result['losses'][-1]['MSE'],'stages':result['stages']}\n  for r in result['losses']:add(r['stage'],r['MSE'],'Training MSE')\n  xl='Boosting stage (0=initial)';yl='Weighted MSE, outcome units squared';title='Training descent does not certify held-out gain'\n else:\n  summary={'outer.scoreable':result['outer']['eligibleRows'],'outer.meanLoss':result['outer']['meanLoss'],'baseline.meanLoss':result['baseline']['meanLoss'],'OOB.scoreable':result['result']['outOfBag']['eligibleRows'],'OOB.meanLoss':result['result']['outOfBag']['meanLoss']}\n  for i,p in enumerate(result['outer']['rows']):\n   add(i+1,Q(p['actual']),'Observed outcome');add(i+1,p['probabilities'][1]if a['kind']=='company'else p['prediction'],'Forest probability of class 1'if a['kind']=='company'else'Forest prediction')\n  xl='Outer-test source order, not a time path';yl='Churn label / probability'if a['kind']=='company'else'Period life expectancy, years'if a['kind']=='country'else'Nominal 1976 USD per hour';title='Fixed forest; outer labels did not fit the trees'\n def display(v):return 'undefined'if v is None else format(float(v),'.9f')\n writecsv(out/'summary.csv',['metric','value'],[[k,display(v)]for k,v in summary.items()]);writecsv(out/'plot-points.csv',['x','y','series'],points);(out/'full.json').write_text(json.dumps(serial(result),indent=2)+'\\n',encoding='utf8')\n fig,ax=plt.subplots(figsize=(5.6,4.6));fig.subplots_adjust(left=.24,right=.96,bottom=.24,top=.76);colors=['#355c72','#a55336','#507956','#78568b']\n for i,s in enumerate(dict.fromkeys(p[2]for p in points)):\n  pp=[p for p in points if p[2]==s];ax.scatter([float(p[0])for p in pp],[float(p[1])for p in pp],s=12 if len(pp)>100 else 32,alpha=.5 if len(pp)>100 else 1,color=colors[i%4],label=s)\n ax.set_xlabel(xl,labelpad=10,fontsize=11);ax.set_ylabel(yl,labelpad=10,fontsize=11);ax.xaxis.set_major_locator(MaxNLocator(3));ax.yaxis.set_major_locator(MaxNLocator(4));ax.grid(alpha=.18);ax.legend(loc='lower left',bbox_to_anchor=(0,1.01),fontsize=9,frameon=False);fig.suptitle(title,fontsize=9,y=.99);fig.savefig(out/'plot.svg',metadata={'Date':None});plt.close(fig);print(', '.join(k+'='+display(v)for k,v in summary.items()))\nif __name__=='__main__':\n import sys\n try:run_fixed(API,INPUT,sys.argv[1]if len(sys.argv)>1 else'fixed-results',sys.argv[2]if len(sys.argv)>2 else'ml09-sources')\n except ValueError as error:print('Rejected declared input: '+str(error),file=sys.stderr);sys.exit(2)\n",
        "inputFiles": [],
        "input": {
          "rows": [
            {
              "id": "0",
              "x": [
                0,
                0
              ],
              "y": 0
            },
            {
              "id": "1",
              "x": [
                0,
                1
              ],
              "y": 2
            },
            {
              "id": "2",
              "x": [
                0,
                2
              ],
              "y": 4
            },
            {
              "id": "3",
              "x": [
                0,
                3
              ],
              "y": 6
            }
          ],
          "queries": [
            {
              "id": "q",
              "x": [
                0,
                "3/2"
              ]
            }
          ],
          "bootstrapDraws": [
            [
              "0",
              "1",
              "2",
              "3"
            ]
          ],
          "nodeFeatures": [
            {
              "": [
                0
              ]
            }
          ],
          "maxDepth": 1
        },
        "returnCode": 0,
        "expectedFailure": false,
        "stdout": "queryPrediction=3.000000000, OOB.scoreable=0.000000000, OOB.meanLoss=undefined\n",
        "stderr": "",
        "summary": {
          "queryPrediction": "3.000000000",
          "OOB.scoreable": "0.000000000",
          "OOB.meanLoss": "undefined"
        },
        "plotPoints": [
          {
            "x": "1",
            "y": "0",
            "series": "Observed training outcome"
          },
          {
            "x": "2",
            "y": "2",
            "series": "Observed training outcome"
          },
          {
            "x": "3",
            "y": "4",
            "series": "Observed training outcome"
          },
          {
            "x": "4",
            "y": "6",
            "series": "Observed training outcome"
          }
        ],
        "plotFile": "ml09-fixed-results/forest-weak-root-python/plot.svg",
        "plotSHA256": "6fc039a11bd574b710914e47b1f2eb47287cc067c370a2bd6dd6265a38cc24c8",
        "files": [
          {
            "file": "ml09-fixed-results/forest-weak-root-python/full.json",
            "sha256": "d8186e32ea1141820a7b1e84ce41dee833b2246236d0ff20b0ef3ff4831dfb68"
          },
          {
            "file": "ml09-fixed-results/forest-weak-root-python/plot-points.csv",
            "sha256": "4c4915290de9abdec26f9e6bf5c7791cdf25dd12df4e3faeedba5301e8364329"
          },
          {
            "file": "ml09-fixed-results/forest-weak-root-python/plot.svg",
            "sha256": "6fc039a11bd574b710914e47b1f2eb47287cc067c370a2bd6dd6265a38cc24c8"
          },
          {
            "file": "ml09-fixed-results/forest-weak-root-python/summary.csv",
            "sha256": "7b18ff86455f214b902ed69879af38fdb16a68cdf1f294dcfa40d5667a79c24c"
          }
        ],
        "scope": "Actually executed self-contained fixed example; current web controls execute separately. Python Fraction and finite-precision base R. Author gate, not independent peer."
      }
    },
    "r": {
      "node-features": {
        "api": "forest",
        "variant": "node-features",
        "language": "r",
        "codeFile": "ml09-code/forest-node-features.R",
        "codeSHA256": "00d00917987a1790ee00acb77037bf05ad54a503e1f772ed99dbaf76c6c73bbc",
        "codeText": "# ML09 base-R reproduction from native original-field CSVs.\n# Rscript ml09-public-analysis.R ml09-sources results-r\n# Separately written vectorized direct-centered squared/Gini losses.\n# No Python/JS/model-contract/stored-answer/derived-result reader or package.\n# Numeric arithmetic is binary64:1e-12 relative tie tolerance stabilizes exact\n# source ties,but does not certify tiny margins/underflow like Fraction JS/Python.\n# Data-frame rows use x0,x1,...,y,weight; original IDs remain attached to draws.\noptions(stringsAsFactors=FALSE,digits=17)\nnum<-function(v){if(is.null(v)||length(v)!=1||is.na(v))stop('numeric parameter required, not explicit NULL');p<-strsplit(as.character(v),'/',fixed=TRUE)[[1]];z<-if(length(p)==2)as.numeric(p[1])/as.numeric(p[2])else as.numeric(v);if(!is.finite(z))stop('finite numeric parameter');z}\noption<-function(a,k,default){if(k%in%names(a))a[[k]]else default}\nnormrows<-function(d,task){if(!'weight'%in%names(d))d$weight<-1;if(!'id'%in%names(d))d$id<-as.character(seq_len(nrow(d))-1);d$weight<-as.numeric(d$weight);if(anyNA(d$weight)||any(d$weight<0))stop('nonnegative weights');if(task=='regression')d$y<-as.numeric(d$y)else d$y<-as.character(d$y);d}\nstat<-function(d,task,classes){W<-sum(d$weight);mu<-if(task=='regression'&&W)sum(d$weight*d$y)/W else NA_real_;p<-if(task=='classification'&&W)vapply(classes,function(c)sum(d$weight[d$y==c])/W,0)else numeric();risk<-if(task=='regression'&&W)sum(d$weight*(d$y-mu)^2)else W*sum(p*(1-p));list(n=nrow(d),w=W,mu=mu,p=unname(p),risk=risk,pred=if(task=='regression')mu else if(W)classes[which.max(p)]else NA_character_)}\nfit<-function(d,a,task,classes,schedule=NULL){d<-d[d$weight>0&!is.na(d$y),,drop=FALSE];if(!nrow(d))stop('positive observed training');W<-sum(d$weight);depth<-option(a,'maxDepth',2);minimum<-option(a,'minLeaf',1);minmass<-num(option(a,'minLeafWeight',0));mingain<-num(option(a,'minGain',0));route<-option(a,'missingRoute','best');features<-grep('^x[0-9]+$',names(d),value=TRUE)\n build<-function(rr,level,path){st<-stat(rr,task,classes);node<-list(rows=rr,st=st,split=NULL,left=NULL,right=NULL,path=path);if(level==depth)return(node);best<-NULL;allowed<-if(is.null(schedule))seq_along(features)-1L else schedule[[match(path,names(schedule))]]\n  for(j in seq_along(features)-1L){if(!j%in%allowed)next;v<-rr[[features[j+1L]]];values<-sort(unique(v[!is.na(v)]));candidates<-list()\n   if(length(values)>1)for(k in seq_len(length(values)-1L)){threshold<-(values[k]+values[k+1L])/2;missing<-is.na(v);left<-!missing&v<=threshold;right<-!missing&v>threshold;directions<-if(route!='best')route else if(any(missing))c('left','right')else if(sum(left)>=sum(right))'left'else'right';for(direction in directions)candidates[[length(candidates)+1L]]<-list(kind='threshold',threshold=threshold,missingRoute=direction,left=if(direction=='left')left|missing else left,right=if(direction=='right')right|missing else right)}\n   if(anyNA(v)&&any(!is.na(v)))candidates[[length(candidates)+1L]]<-list(kind='missing-only',threshold=NA_real_,missingRoute='left',left=is.na(v),right=!is.na(v))\n   for(candidate in candidates){l<-rr[candidate$left,,drop=FALSE];r<-rr[candidate$right,,drop=FALSE];ls<-stat(l,task,classes);rs<-stat(r,task,classes);if(min(ls$n,rs$n)<minimum||min(ls$w,rs$w)<minmass||min(ls$w,rs$w)<=0)next;gain<-(st$risk-ls$risk-rs$risk)/W;tol<-1e-12*max(1,abs(gain),if(is.null(best))0 else abs(best$gain));if(is.null(best)||gain>best$gain+tol)best<-c(candidate,list(feature=j,gain=gain,l=l,r=r))}\n  }\n  if(!is.null(best)&&best$gain>max(mingain,1e-12)){node$split<-best;node$left<-build(best$l,level+1L,paste0(path,'L'));node$right<-build(best$r,level+1L,paste0(path,'R'))};node\n };build(d,0L,'')\n}\npredict_one<-function(tree,row){n<-tree;while(!is.null(n$split)){s<-n$split;v<-as.numeric(row[[paste0('x',s$feature)]]);left<-if(s$kind=='missing-only')is.na(v)else if(is.na(v))s$missingRoute=='left'else v<=s$threshold;n<-if(left)n$left else n$right};list(prediction=n$st$pred,probabilities=n$st$p)}\ncombine<-function(pp,w,task,classes,mode='probabilities'){W<-sum(w);if(!length(pp)||!W)return(list(prediction=if(task=='regression')NA_real_ else NA_character_,probabilities=numeric(),vote=NA_character_,prob=NA_character_));if(task=='regression')return(list(prediction=sum(vapply(pp,function(p)p$prediction,0)*w)/W,probabilities=numeric(),vote=NA_character_,prob=NA_character_));votes<-vapply(classes,function(c)sum(w[vapply(pp,function(p)p$prediction==c,FALSE)])/W,0);probs<-vapply(seq_along(classes),function(j)sum(vapply(pp,function(p)p$probabilities[j],0)*w)/W,0);vote<-classes[which.max(votes)];prob<-classes[which.max(probs)];list(prediction=if(mode=='votes')vote else prob,probabilities=unname(probs),vote=vote,prob=prob,votes=unname(votes))}\nvariance<-function(a){B<-num(a$B);v<-num(a$marginalVariance);rho<-num(option(a,'rho',0));if(B<1||B!=floor(B)||v<0)stop('integer B/nonnegative variance');if(B>1&&v>0&&(rho< -1/(B-1)||rho>1))stop('PSD correlation');list(B=B,marginalVariance=v,correlationApplicable=B>1&&v>0,varianceOfMean=if(B==1)v else v*(1+(B-1)*rho)/B)}\naggregate<-function(a){task<-option(a,'task','regression');classes<-option(a,'classes',character());w<-vapply(option(a,'memberWeights',as.list(rep(1,length(a$members)))),num,0);if(any(w<0)||sum(w)<=0)stop('positive member mass');ids<-a$members[[1]]$predictions$id;pp<-lapply(ids,function(id){members<-lapply(a$members,function(m){r<-m$predictions[match(id,m$predictions$id),,drop=FALSE];if(task=='regression')list(prediction=num(r$value),probabilities=numeric())else list(prediction=as.character(r$label),probabilities=as.numeric(r[paste0('p',seq_along(classes)-1L)]))});c(list(id=id),combine(members,w,task,classes,option(a,'aggregation','probabilities')))});list(task=task,classes=classes,predictions=pp)}\nscored<-function(preds,d,task,classes){W<-loss<-absolute<-errors<-voteerrors<-0;count<-0L;out<-lapply(seq_len(nrow(d)),function(i){r<-d[i,,drop=FALSE];p<-preds[[i]];ok<-!is.na(p$prediction)&&!is.na(r$y)&&r$weight>0;value<-NA_real_;if(ok){count<<-count+1L;W<<-W+r$weight;if(task=='regression'){e<-r$y-p$prediction;value<-e*e;absolute<<-absolute+r$weight*abs(e)}else{value<-sum((p$probabilities-as.numeric(classes==r$y))^2);errors<<-errors+r$weight*(p$prediction!=r$y);voteerrors<<-voteerrors+r$weight*(p$vote!=r$y)};loss<<-loss+r$weight*value};c(p,list(actual=r$y,weight=r$weight,scoreEligible=ok,loss=value))});list(rows=out,eligibleRows=count,weight=W,totalLoss=loss,meanLoss=if(W)loss/W else NA_real_,MAE=if(W&&task=='regression')absolute/W else NA_real_,errorRate=if(W&&task=='classification')errors/W else NA_real_,labelVoteErrorRate=if(W&&task=='classification')voteerrors/W else NA_real_)}\nensemble<-function(a,forest=FALSE){task<-option(a,'task','regression');classes<-option(a,'classes',character());d<-normrows(a$rows,task);w<-vapply(option(a,'memberWeights',as.list(rep(1,length(a$bootstrapDraws)))),num,0);if(any(w<0)||sum(w)<=0)stop('positive member mass');members<-lapply(seq_along(a$bootstrapDraws),function(i){draw<-a$bootstrapDraws[[i]];indices<-match(draw,d$id);if(anyNA(indices))stop('unknown draw source');tree<-fit(d[indices,,drop=FALSE],a,task,classes,if(forest)a$nodeFeatures[[i]]else NULL);list(tree=tree,draw=draw,inbag=unique(draw),weight=w[i])});queries<-a$queries;preds<-lapply(seq_len(nrow(queries)),function(i)c(list(id=queries$id[i]),combine(lapply(members,function(m)predict_one(m$tree,queries[i,,drop=FALSE])),w,task,classes,option(a,'aggregation','probabilities'))));oob<-lapply(seq_len(nrow(d)),function(i){app<-which(!vapply(members,function(m)d$id[i]%in%m$inbag,FALSE));pp<-combine(lapply(app,function(j)predict_one(members[[j]]$tree,d[i,,drop=FALSE])),w[app],task,classes,option(a,'aggregation','probabilities'));c(list(id=d$id[i],applicable=app-1L,positiveMembers=sum(w[app]>0)),pp)});list(task=task,classes=classes,members=members,predictions=preds,outOfBag=scored(oob,d,task,classes))}\nboost<-function(a){if(option(a,'task','regression')!='regression')stop('regression boosting only');d<-normrows(a$rows,'regression');eligible<-d$weight>0&!is.na(d$y);W<-sum(d$weight[eligible]);if(!W)stop('positive eligible training');eta<-num(option(a,'learningRate','1/2'));stages<-option(a,'stages',3);if(is.null(stages)||stages!=floor(stages)||stages<0||stages>8||eta<0||eta>1)stop('supported rate/stages');initial<-if('initial'%in%names(a))num(a$initial)else sum(d$weight[eligible]*d$y[eligible])/W;train<-matrix(initial,nrow(d),stages+1L);query<-matrix(initial,nrow(a$queries),stages+1L);losses<-fits<-list();for(stage in 0:stages){sse<-sum(d$weight[eligible]*(d$y[eligible]-train[eligible,stage+1L])^2);losses[[stage+1L]]<-list(stage=stage,rawWeightedSSE=sse,MSE=sse/W,meanHalfSquaredLoss=sse/(2*W));if(stage==stages)break;residual<-d;residual$y<-d$y-train[,stage+1L];tree<-fit(residual,a,'regression',character());h<-vapply(seq_len(nrow(d)),function(i)predict_one(tree,d[i,,drop=FALSE])$prediction,0);qh<-vapply(seq_len(nrow(a$queries)),function(i)predict_one(tree,a$queries[i,,drop=FALSE])$prediction,0);stageRows<-lapply(seq_len(nrow(d)),function(i)list(id=d$id[i],before=train[i,stage+1L],residual=residual$y[i],negativeCoordinateDerivative=d$weight[i]*residual$y[i]/W,fit=h[i],addition=eta*h[i],after=train[i,stage+1L]+eta*h[i]));train[,stage+2L]<-train[,stage+1L]+eta*h;query[,stage+2L]<-query[,stage+1L]+eta*qh;norm<-sum(d$weight[eligible]*h[eligible]^2);fits[[stage+1L]]<-list(stage=stage+1L,tree=tree,rows=stageRows,queryFits=qh,norm=norm,predictedSSEDecrease=eta*(2-eta)*norm)};list(task='regression',initial=initial,learningRate=eta,stages=stages,training=train,queries=query,fits=fits,losses=losses,predictions=lapply(seq_len(nrow(a$queries)),function(i)list(id=a$queries$id[i],prediction=query[i,stages+1L],probabilities=numeric(),vote=NA_character_,prob=NA_character_)))}\nfixed_schedules<-function(ids,p,seed){state<-seed;choose<-function(n){limit<-floor(4294967296/n)*n;repeat{state<<-(1664525*state+1013904223)%%4294967296;if(state<limit)return(as.integer(state%%n))}};draws<-schedules<-list();for(member in 1:4){draws[[member]]<-vapply(seq_along(ids),function(i)ids[choose(length(ids))+1L],'');schedule<-setNames(vector('list',7),c('','L','R','LL','LR','RL','RR'));for(path in names(schedule)){order<-seq_len(p)-1L;if(p>1)for(j in seq(p-1L,1L)){k<-choose(j+1L);temp<-order[j+1L];order[j+1L]<-order[k+1L];order[k+1L]<-temp};schedule[[match(path,names(schedule))]]<-sort(order[seq_len(max(1L,floor(sqrt(p))))])};schedules[[member]]<-schedule};list(draws=draws,schedules=schedules)}\nread_sources<-function(src){read<-function(name)read.csv(file.path(src,name),check.names=FALSE,colClasses='character',na.strings=character(),fileEncoding='UTF-8-BOM');raw<-read('actual320-country-four-indicators-original-2020-2024.csv');country<-do.call(rbind,lapply(sort(unique(raw$countryISO3)),function(code)do.call(rbind,lapply(2020:2024,function(year){keys<-c('NY.GDP.PCAP.KD','NY.GDP.MKTP.KD.ZG','FP.CPI.TOTL.ZG','SP.DYN.LE00.IN');v<-vapply(keys,function(k)as.numeric(raw$originalValueToken[raw$countryISO3==code&raw$date==as.character(year)&raw$indicatorID==k]),0);data.frame(id=paste0(code,':',year),sourceRow=paste0(code,':',year),originalID=code,year=year,x0=v[1]/10000,x1=v[2],x2=v[3],y=v[4],weight=1,role=if(anyNA(v))'excluded'else if(year==2024)'outer-test'else'train')}))));raw<-read('actual3613-NLS-original52-fields-and-selection.csv');i<-seq_len(nrow(raw));x0<-suppressWarnings(as.numeric(raw$ed76));x1<-suppressWarnings(as.numeric(raw$age76));y<-suppressWarnings(as.numeric(raw$wage76))/100;person<-data.frame(id=paste0('person:',i),sourceRow=as.character(i),originalID=raw$id,x0=x0,x1=x1,y=y,weight=1,role=ifelse(is.na(x0)|is.na(x1)|is.na(y),'excluded',ifelse(i%%5==0,'outer-test','train')));raw<-read('actual3150-churn-original14-fields-and-selection.csv');i<-seq_len(nrow(raw));company<-data.frame(id=paste0('customer:',i),sourceRow=as.character(i),originalID='',x0=as.numeric(raw[['Call  Failure']]),x1=as.numeric(raw[['Subscription  Length']]),x2=as.numeric(raw[['Charge  Amount']]),y=raw$Churn,weight=1,role=ifelse(i%%5==0,'outer-test','train'));models<-list();for(index in 1:3){kind<-c('country','person','company')[index];d<-list(country,person,company)[[index]];task<-if(kind=='company')'classification'else'regression';s<-fixed_schedules(d$id[d$role=='train'],if(kind=='person')2L else 3L,20261102+7919*(index-1L));models[[kind]]<-list(records=d,task=task,classes=if(task=='classification')c('0','1')else character(),draws=s$draws,schedules=s$schedules,minLeaf=c(4L,50L,30L)[index])};models}\nrealdata<-function(models,kind,options=list()){if(is.null(options)||!is.list(options))stop('options object');m<-models[[kind]];d<-m$records;train<-d[d$role=='train',,drop=FALSE];test<-d[d$role=='outer-test',,drop=FALSE];method<-option(options,'method','forest');depth<-option(options,'maxDepth',2);count<-option(options,'memberCount',3);if(!method%in%c('bagging','forest','boost'))stop('known method');a<-list(rows=train,queries=test,task=m$task,classes=m$classes,maxDepth=depth,minLeaf=option(options,'minLeaf',m$minLeaf),minLeafWeight=0,minGain=0,missingRoute='best',learningRate=option(options,'learningRate','1/2'),stages=option(options,'stages',3));if(method=='boost')result<-boost(a)else{a$bootstrapDraws<-m$draws[seq_len(count)];a$nodeFeatures<-lapply(m$schedules[seq_len(count)],function(s)s[nchar(names(s))<depth]);result<-ensemble(a,method=='forest')};outer<-scored(result$predictions,normrows(test,m$task),m$task,m$classes);st<-stat(normrows(train,m$task),m$task,m$classes);constant<-list(prediction=st$pred,probabilities=st$p,vote=st$pred,prob=st$pred);baseline<-scored(lapply(test$id,function(id)c(list(id=id),constant)),normrows(test,m$task),m$task,m$classes);list(kind=kind,method=method,settings=a,train=train,test=test,result=result,outer=outer,baseline=baseline)}\nAPI<-\"forest\"\nINPUT<-list(rows=data.frame(id=c(\"a\",\"b\",\"c\",\"d\"),y=c(0,1,3,4),x0=c(0,1,2,3),x1=c(0,1,0,1),stringsAsFactors=FALSE),queries=data.frame(id=c(\"q\"),x0=c(num(\"3/2\")),x1=c(0),stringsAsFactors=FALSE),bootstrapDraws=list(c(\"a\",\"a\",\"b\",\"c\"),c(\"b\",\"c\",\"d\",\"d\")),maxDepth=2,nodeFeatures=list(setNames(list(c(0),c(1),c(1)),c(\"\",\"L\",\"R\")),setNames(list(c(1),c(0),c(0)),c(\"\",\"L\",\"R\"))))\n\nrun_fixed<-function(api,a,out,src){\n r<-if(api=='variance')variance(a)else if(api=='aggregate')aggregate(a)else if(api%in%c('bagging','forest'))ensemble(a,api=='forest')else if(api=='boost')boost(a)else realdata(read_sources(src),a$kind)\n dir.create(out,recursive=TRUE,showWarnings=FALSE);summary<-list();points<-list();add<-function(x,y,s){if(!is.null(y)&&!is.na(y))points[[length(points)+1L]]<<-data.frame(x=x,y=as.numeric(y),series=s)}\n if(api=='variance'){summary<-r[c('B','varianceOfMean')];add(r$B,r$varianceOfMean,'Specified finite-B variance');xl<-'Number of members B';yl<-'Variance, stipulated units squared';title<-'Declared covariance model, not fitted trees'\n }else if(api=='aggregate'){p<-r$predictions[[1]];summary<-list(selectedPrediction=p$prediction);classification<-identical(a$task,'classification');if(classification){summary<-c(summary,list(voteLabel=p$vote,probabilityLabel=p$prob,meanProbability1=p$probabilities[2]));add(1,p$probabilities[2],'Mean probability of class 1');add(2,p$votes[2],'Label-vote share of class 1');xl<-'Aggregation (1=probability, 2=vote)';yl<-'Probability or vote share'}else{for(i in seq_along(a$members))add(i,num(a$members[[i]]$predictions$value[1]),'Member prediction');add(3,p$prediction,'Weighted mean');xl<-'Member 1, member 2, aggregate 3';yl<-'Prediction, assumed units'};title<-'Votes and probabilities are distinct objects'\n }else if(api%in%c('bagging','forest')){summary<-list(queryPrediction=r$predictions[[1]]$prediction,OOB.scoreable=r$outOfBag$eligibleRows,OOB.meanLoss=r$outOfBag$meanLoss);for(i in seq_len(nrow(a$rows)))add(i,a$rows$y[i],'Observed training outcome');for(i in seq_along(r$outOfBag$rows))add(i,r$outOfBag$rows[[i]]$prediction,'OOB prediction, when defined');xl<-'Original training ID order';yl<-'Outcome, assumed units';title<-'Repeated draws and ID-level OOB membership'\n }else if(api=='boost'){summary<-list(initial=r$initial,finalMSE=r$losses[[length(r$losses)]]$MSE,stages=r$stages);for(v in r$losses)add(v$stage,v$MSE,'Training MSE');xl<-'Boosting stage (0=initial)';yl<-'Weighted MSE, outcome units squared';title<-'Training descent does not certify held-out gain'\n }else{summary<-list(outer.scoreable=r$outer$eligibleRows,outer.meanLoss=r$outer$meanLoss,baseline.meanLoss=r$baseline$meanLoss,OOB.scoreable=r$result$outOfBag$eligibleRows,OOB.meanLoss=r$result$outOfBag$meanLoss);for(i in seq_along(r$outer$rows)){p<-r$outer$rows[[i]];add(i,as.numeric(p$actual),'Observed outcome');add(i,if(a$kind=='company')p$probabilities[2]else p$prediction,if(a$kind=='company')'Forest probability of class 1'else'Forest prediction')};xl<-'Outer-test source order, not a time path';yl<-if(a$kind=='company')'Churn label / probability'else if(a$kind=='country')'Period life expectancy, years'else'Nominal 1976 USD per hour';title<-'Fixed forest; outer labels did not fit the trees'}\n display<-function(v)if(is.null(v)||is.na(v))'undefined'else sprintf('%.9f',as.numeric(v));write.csv(data.frame(metric=names(summary),value=vapply(summary,display,'')),file.path(out,'summary.csv'),row.names=FALSE);pp<-do.call(rbind,points);write.csv(pp,file.path(out,'plot-points.csv'),row.names=FALSE);dput(r,file.path(out,'full-result.Rtext'));svg(file.path(out,'plot.svg'),width=5.6,height=4.6,pointsize=14);par(mar=c(5.8,5.8,5.3,1.2),mgp=c(3.7,1,0));xr<-range(pp$x);yr<-range(pp$y);if(diff(xr)==0)xr<-xr+c(-.5,.5);if(diff(yr)==0)yr<-yr+c(-.5,.5);plot(xr,yr,type='n',xlab=xl,ylab=yl,cex.lab=.78,axes=FALSE);axis(1,at=pretty(xr,3));axis(2,at=pretty(yr,4),las=1,cex.axis=.82);box();grid(col='#dddddd');cols<-c('#355c72','#a55336','#507956','#78568b');ss<-unique(pp$series);for(i in seq_along(ss)){v<-pp[pp$series==ss[i],];points(v$x,v$y,pch=16,cex=if(nrow(v)>100).35 else .85,col=adjustcolor(cols[i],if(nrow(v)>100).5 else 1))};legend('topleft',legend=ss,col=cols[seq_along(ss)],lty=0,pch=16,cex=.65,bty='n',inset=c(0,-.32),xpd=NA);mtext(title,side=3,line=3.9,cex=.6);dev.off();cat(paste(names(summary),vapply(summary,display,''),sep='=',collapse=', '),'\\n')\n}\nargs<-commandArgs(trailingOnly=TRUE)\ntryCatch(run_fixed(API,INPUT,if(length(args))args[1]else'fixed-results',if(length(args)>1)args[2]else'ml09-sources'),error=function(e){cat('Rejected declared input: ',conditionMessage(e),'\\n',file=stderr());quit(status=2)})\n",
        "code": "# ML09 base-R reproduction from native original-field CSVs.\n# Rscript ml09-public-analysis.R ml09-sources results-r\n# Separately written vectorized direct-centered squared/Gini losses.\n# No Python/JS/model-contract/stored-answer/derived-result reader or package.\n# Numeric arithmetic is binary64:1e-12 relative tie tolerance stabilizes exact\n# source ties,but does not certify tiny margins/underflow like Fraction JS/Python.\n# Data-frame rows use x0,x1,...,y,weight; original IDs remain attached to draws.\noptions(stringsAsFactors=FALSE,digits=17)\nnum<-function(v){if(is.null(v)||length(v)!=1||is.na(v))stop('numeric parameter required, not explicit NULL');p<-strsplit(as.character(v),'/',fixed=TRUE)[[1]];z<-if(length(p)==2)as.numeric(p[1])/as.numeric(p[2])else as.numeric(v);if(!is.finite(z))stop('finite numeric parameter');z}\noption<-function(a,k,default){if(k%in%names(a))a[[k]]else default}\nnormrows<-function(d,task){if(!'weight'%in%names(d))d$weight<-1;if(!'id'%in%names(d))d$id<-as.character(seq_len(nrow(d))-1);d$weight<-as.numeric(d$weight);if(anyNA(d$weight)||any(d$weight<0))stop('nonnegative weights');if(task=='regression')d$y<-as.numeric(d$y)else d$y<-as.character(d$y);d}\nstat<-function(d,task,classes){W<-sum(d$weight);mu<-if(task=='regression'&&W)sum(d$weight*d$y)/W else NA_real_;p<-if(task=='classification'&&W)vapply(classes,function(c)sum(d$weight[d$y==c])/W,0)else numeric();risk<-if(task=='regression'&&W)sum(d$weight*(d$y-mu)^2)else W*sum(p*(1-p));list(n=nrow(d),w=W,mu=mu,p=unname(p),risk=risk,pred=if(task=='regression')mu else if(W)classes[which.max(p)]else NA_character_)}\nfit<-function(d,a,task,classes,schedule=NULL){d<-d[d$weight>0&!is.na(d$y),,drop=FALSE];if(!nrow(d))stop('positive observed training');W<-sum(d$weight);depth<-option(a,'maxDepth',2);minimum<-option(a,'minLeaf',1);minmass<-num(option(a,'minLeafWeight',0));mingain<-num(option(a,'minGain',0));route<-option(a,'missingRoute','best');features<-grep('^x[0-9]+$',names(d),value=TRUE)\n build<-function(rr,level,path){st<-stat(rr,task,classes);node<-list(rows=rr,st=st,split=NULL,left=NULL,right=NULL,path=path);if(level==depth)return(node);best<-NULL;allowed<-if(is.null(schedule))seq_along(features)-1L else schedule[[match(path,names(schedule))]]\n  for(j in seq_along(features)-1L){if(!j%in%allowed)next;v<-rr[[features[j+1L]]];values<-sort(unique(v[!is.na(v)]));candidates<-list()\n   if(length(values)>1)for(k in seq_len(length(values)-1L)){threshold<-(values[k]+values[k+1L])/2;missing<-is.na(v);left<-!missing&v<=threshold;right<-!missing&v>threshold;directions<-if(route!='best')route else if(any(missing))c('left','right')else if(sum(left)>=sum(right))'left'else'right';for(direction in directions)candidates[[length(candidates)+1L]]<-list(kind='threshold',threshold=threshold,missingRoute=direction,left=if(direction=='left')left|missing else left,right=if(direction=='right')right|missing else right)}\n   if(anyNA(v)&&any(!is.na(v)))candidates[[length(candidates)+1L]]<-list(kind='missing-only',threshold=NA_real_,missingRoute='left',left=is.na(v),right=!is.na(v))\n   for(candidate in candidates){l<-rr[candidate$left,,drop=FALSE];r<-rr[candidate$right,,drop=FALSE];ls<-stat(l,task,classes);rs<-stat(r,task,classes);if(min(ls$n,rs$n)<minimum||min(ls$w,rs$w)<minmass||min(ls$w,rs$w)<=0)next;gain<-(st$risk-ls$risk-rs$risk)/W;tol<-1e-12*max(1,abs(gain),if(is.null(best))0 else abs(best$gain));if(is.null(best)||gain>best$gain+tol)best<-c(candidate,list(feature=j,gain=gain,l=l,r=r))}\n  }\n  if(!is.null(best)&&best$gain>max(mingain,1e-12)){node$split<-best;node$left<-build(best$l,level+1L,paste0(path,'L'));node$right<-build(best$r,level+1L,paste0(path,'R'))};node\n };build(d,0L,'')\n}\npredict_one<-function(tree,row){n<-tree;while(!is.null(n$split)){s<-n$split;v<-as.numeric(row[[paste0('x',s$feature)]]);left<-if(s$kind=='missing-only')is.na(v)else if(is.na(v))s$missingRoute=='left'else v<=s$threshold;n<-if(left)n$left else n$right};list(prediction=n$st$pred,probabilities=n$st$p)}\ncombine<-function(pp,w,task,classes,mode='probabilities'){W<-sum(w);if(!length(pp)||!W)return(list(prediction=if(task=='regression')NA_real_ else NA_character_,probabilities=numeric(),vote=NA_character_,prob=NA_character_));if(task=='regression')return(list(prediction=sum(vapply(pp,function(p)p$prediction,0)*w)/W,probabilities=numeric(),vote=NA_character_,prob=NA_character_));votes<-vapply(classes,function(c)sum(w[vapply(pp,function(p)p$prediction==c,FALSE)])/W,0);probs<-vapply(seq_along(classes),function(j)sum(vapply(pp,function(p)p$probabilities[j],0)*w)/W,0);vote<-classes[which.max(votes)];prob<-classes[which.max(probs)];list(prediction=if(mode=='votes')vote else prob,probabilities=unname(probs),vote=vote,prob=prob,votes=unname(votes))}\nvariance<-function(a){B<-num(a$B);v<-num(a$marginalVariance);rho<-num(option(a,'rho',0));if(B<1||B!=floor(B)||v<0)stop('integer B/nonnegative variance');if(B>1&&v>0&&(rho< -1/(B-1)||rho>1))stop('PSD correlation');list(B=B,marginalVariance=v,correlationApplicable=B>1&&v>0,varianceOfMean=if(B==1)v else v*(1+(B-1)*rho)/B)}\naggregate<-function(a){task<-option(a,'task','regression');classes<-option(a,'classes',character());w<-vapply(option(a,'memberWeights',as.list(rep(1,length(a$members)))),num,0);if(any(w<0)||sum(w)<=0)stop('positive member mass');ids<-a$members[[1]]$predictions$id;pp<-lapply(ids,function(id){members<-lapply(a$members,function(m){r<-m$predictions[match(id,m$predictions$id),,drop=FALSE];if(task=='regression')list(prediction=num(r$value),probabilities=numeric())else list(prediction=as.character(r$label),probabilities=as.numeric(r[paste0('p',seq_along(classes)-1L)]))});c(list(id=id),combine(members,w,task,classes,option(a,'aggregation','probabilities')))});list(task=task,classes=classes,predictions=pp)}\nscored<-function(preds,d,task,classes){W<-loss<-absolute<-errors<-voteerrors<-0;count<-0L;out<-lapply(seq_len(nrow(d)),function(i){r<-d[i,,drop=FALSE];p<-preds[[i]];ok<-!is.na(p$prediction)&&!is.na(r$y)&&r$weight>0;value<-NA_real_;if(ok){count<<-count+1L;W<<-W+r$weight;if(task=='regression'){e<-r$y-p$prediction;value<-e*e;absolute<<-absolute+r$weight*abs(e)}else{value<-sum((p$probabilities-as.numeric(classes==r$y))^2);errors<<-errors+r$weight*(p$prediction!=r$y);voteerrors<<-voteerrors+r$weight*(p$vote!=r$y)};loss<<-loss+r$weight*value};c(p,list(actual=r$y,weight=r$weight,scoreEligible=ok,loss=value))});list(rows=out,eligibleRows=count,weight=W,totalLoss=loss,meanLoss=if(W)loss/W else NA_real_,MAE=if(W&&task=='regression')absolute/W else NA_real_,errorRate=if(W&&task=='classification')errors/W else NA_real_,labelVoteErrorRate=if(W&&task=='classification')voteerrors/W else NA_real_)}\nensemble<-function(a,forest=FALSE){task<-option(a,'task','regression');classes<-option(a,'classes',character());d<-normrows(a$rows,task);w<-vapply(option(a,'memberWeights',as.list(rep(1,length(a$bootstrapDraws)))),num,0);if(any(w<0)||sum(w)<=0)stop('positive member mass');members<-lapply(seq_along(a$bootstrapDraws),function(i){draw<-a$bootstrapDraws[[i]];indices<-match(draw,d$id);if(anyNA(indices))stop('unknown draw source');tree<-fit(d[indices,,drop=FALSE],a,task,classes,if(forest)a$nodeFeatures[[i]]else NULL);list(tree=tree,draw=draw,inbag=unique(draw),weight=w[i])});queries<-a$queries;preds<-lapply(seq_len(nrow(queries)),function(i)c(list(id=queries$id[i]),combine(lapply(members,function(m)predict_one(m$tree,queries[i,,drop=FALSE])),w,task,classes,option(a,'aggregation','probabilities'))));oob<-lapply(seq_len(nrow(d)),function(i){app<-which(!vapply(members,function(m)d$id[i]%in%m$inbag,FALSE));pp<-combine(lapply(app,function(j)predict_one(members[[j]]$tree,d[i,,drop=FALSE])),w[app],task,classes,option(a,'aggregation','probabilities'));c(list(id=d$id[i],applicable=app-1L,positiveMembers=sum(w[app]>0)),pp)});list(task=task,classes=classes,members=members,predictions=preds,outOfBag=scored(oob,d,task,classes))}\nboost<-function(a){if(option(a,'task','regression')!='regression')stop('regression boosting only');d<-normrows(a$rows,'regression');eligible<-d$weight>0&!is.na(d$y);W<-sum(d$weight[eligible]);if(!W)stop('positive eligible training');eta<-num(option(a,'learningRate','1/2'));stages<-option(a,'stages',3);if(is.null(stages)||stages!=floor(stages)||stages<0||stages>8||eta<0||eta>1)stop('supported rate/stages');initial<-if('initial'%in%names(a))num(a$initial)else sum(d$weight[eligible]*d$y[eligible])/W;train<-matrix(initial,nrow(d),stages+1L);query<-matrix(initial,nrow(a$queries),stages+1L);losses<-fits<-list();for(stage in 0:stages){sse<-sum(d$weight[eligible]*(d$y[eligible]-train[eligible,stage+1L])^2);losses[[stage+1L]]<-list(stage=stage,rawWeightedSSE=sse,MSE=sse/W,meanHalfSquaredLoss=sse/(2*W));if(stage==stages)break;residual<-d;residual$y<-d$y-train[,stage+1L];tree<-fit(residual,a,'regression',character());h<-vapply(seq_len(nrow(d)),function(i)predict_one(tree,d[i,,drop=FALSE])$prediction,0);qh<-vapply(seq_len(nrow(a$queries)),function(i)predict_one(tree,a$queries[i,,drop=FALSE])$prediction,0);stageRows<-lapply(seq_len(nrow(d)),function(i)list(id=d$id[i],before=train[i,stage+1L],residual=residual$y[i],negativeCoordinateDerivative=d$weight[i]*residual$y[i]/W,fit=h[i],addition=eta*h[i],after=train[i,stage+1L]+eta*h[i]));train[,stage+2L]<-train[,stage+1L]+eta*h;query[,stage+2L]<-query[,stage+1L]+eta*qh;norm<-sum(d$weight[eligible]*h[eligible]^2);fits[[stage+1L]]<-list(stage=stage+1L,tree=tree,rows=stageRows,queryFits=qh,norm=norm,predictedSSEDecrease=eta*(2-eta)*norm)};list(task='regression',initial=initial,learningRate=eta,stages=stages,training=train,queries=query,fits=fits,losses=losses,predictions=lapply(seq_len(nrow(a$queries)),function(i)list(id=a$queries$id[i],prediction=query[i,stages+1L],probabilities=numeric(),vote=NA_character_,prob=NA_character_)))}\nfixed_schedules<-function(ids,p,seed){state<-seed;choose<-function(n){limit<-floor(4294967296/n)*n;repeat{state<<-(1664525*state+1013904223)%%4294967296;if(state<limit)return(as.integer(state%%n))}};draws<-schedules<-list();for(member in 1:4){draws[[member]]<-vapply(seq_along(ids),function(i)ids[choose(length(ids))+1L],'');schedule<-setNames(vector('list',7),c('','L','R','LL','LR','RL','RR'));for(path in names(schedule)){order<-seq_len(p)-1L;if(p>1)for(j in seq(p-1L,1L)){k<-choose(j+1L);temp<-order[j+1L];order[j+1L]<-order[k+1L];order[k+1L]<-temp};schedule[[match(path,names(schedule))]]<-sort(order[seq_len(max(1L,floor(sqrt(p))))])};schedules[[member]]<-schedule};list(draws=draws,schedules=schedules)}\nread_sources<-function(src){read<-function(name)read.csv(file.path(src,name),check.names=FALSE,colClasses='character',na.strings=character(),fileEncoding='UTF-8-BOM');raw<-read('actual320-country-four-indicators-original-2020-2024.csv');country<-do.call(rbind,lapply(sort(unique(raw$countryISO3)),function(code)do.call(rbind,lapply(2020:2024,function(year){keys<-c('NY.GDP.PCAP.KD','NY.GDP.MKTP.KD.ZG','FP.CPI.TOTL.ZG','SP.DYN.LE00.IN');v<-vapply(keys,function(k)as.numeric(raw$originalValueToken[raw$countryISO3==code&raw$date==as.character(year)&raw$indicatorID==k]),0);data.frame(id=paste0(code,':',year),sourceRow=paste0(code,':',year),originalID=code,year=year,x0=v[1]/10000,x1=v[2],x2=v[3],y=v[4],weight=1,role=if(anyNA(v))'excluded'else if(year==2024)'outer-test'else'train')}))));raw<-read('actual3613-NLS-original52-fields-and-selection.csv');i<-seq_len(nrow(raw));x0<-suppressWarnings(as.numeric(raw$ed76));x1<-suppressWarnings(as.numeric(raw$age76));y<-suppressWarnings(as.numeric(raw$wage76))/100;person<-data.frame(id=paste0('person:',i),sourceRow=as.character(i),originalID=raw$id,x0=x0,x1=x1,y=y,weight=1,role=ifelse(is.na(x0)|is.na(x1)|is.na(y),'excluded',ifelse(i%%5==0,'outer-test','train')));raw<-read('actual3150-churn-original14-fields-and-selection.csv');i<-seq_len(nrow(raw));company<-data.frame(id=paste0('customer:',i),sourceRow=as.character(i),originalID='',x0=as.numeric(raw[['Call  Failure']]),x1=as.numeric(raw[['Subscription  Length']]),x2=as.numeric(raw[['Charge  Amount']]),y=raw$Churn,weight=1,role=ifelse(i%%5==0,'outer-test','train'));models<-list();for(index in 1:3){kind<-c('country','person','company')[index];d<-list(country,person,company)[[index]];task<-if(kind=='company')'classification'else'regression';s<-fixed_schedules(d$id[d$role=='train'],if(kind=='person')2L else 3L,20261102+7919*(index-1L));models[[kind]]<-list(records=d,task=task,classes=if(task=='classification')c('0','1')else character(),draws=s$draws,schedules=s$schedules,minLeaf=c(4L,50L,30L)[index])};models}\nrealdata<-function(models,kind,options=list()){if(is.null(options)||!is.list(options))stop('options object');m<-models[[kind]];d<-m$records;train<-d[d$role=='train',,drop=FALSE];test<-d[d$role=='outer-test',,drop=FALSE];method<-option(options,'method','forest');depth<-option(options,'maxDepth',2);count<-option(options,'memberCount',3);if(!method%in%c('bagging','forest','boost'))stop('known method');a<-list(rows=train,queries=test,task=m$task,classes=m$classes,maxDepth=depth,minLeaf=option(options,'minLeaf',m$minLeaf),minLeafWeight=0,minGain=0,missingRoute='best',learningRate=option(options,'learningRate','1/2'),stages=option(options,'stages',3));if(method=='boost')result<-boost(a)else{a$bootstrapDraws<-m$draws[seq_len(count)];a$nodeFeatures<-lapply(m$schedules[seq_len(count)],function(s)s[nchar(names(s))<depth]);result<-ensemble(a,method=='forest')};outer<-scored(result$predictions,normrows(test,m$task),m$task,m$classes);st<-stat(normrows(train,m$task),m$task,m$classes);constant<-list(prediction=st$pred,probabilities=st$p,vote=st$pred,prob=st$pred);baseline<-scored(lapply(test$id,function(id)c(list(id=id),constant)),normrows(test,m$task),m$task,m$classes);list(kind=kind,method=method,settings=a,train=train,test=test,result=result,outer=outer,baseline=baseline)}\nAPI<-\"forest\"\nINPUT<-list(rows=data.frame(id=c(\"a\",\"b\",\"c\",\"d\"),y=c(0,1,3,4),x0=c(0,1,2,3),x1=c(0,1,0,1),stringsAsFactors=FALSE),queries=data.frame(id=c(\"q\"),x0=c(num(\"3/2\")),x1=c(0),stringsAsFactors=FALSE),bootstrapDraws=list(c(\"a\",\"a\",\"b\",\"c\"),c(\"b\",\"c\",\"d\",\"d\")),maxDepth=2,nodeFeatures=list(setNames(list(c(0),c(1),c(1)),c(\"\",\"L\",\"R\")),setNames(list(c(1),c(0),c(0)),c(\"\",\"L\",\"R\"))))\n\nrun_fixed<-function(api,a,out,src){\n r<-if(api=='variance')variance(a)else if(api=='aggregate')aggregate(a)else if(api%in%c('bagging','forest'))ensemble(a,api=='forest')else if(api=='boost')boost(a)else realdata(read_sources(src),a$kind)\n dir.create(out,recursive=TRUE,showWarnings=FALSE);summary<-list();points<-list();add<-function(x,y,s){if(!is.null(y)&&!is.na(y))points[[length(points)+1L]]<<-data.frame(x=x,y=as.numeric(y),series=s)}\n if(api=='variance'){summary<-r[c('B','varianceOfMean')];add(r$B,r$varianceOfMean,'Specified finite-B variance');xl<-'Number of members B';yl<-'Variance, stipulated units squared';title<-'Declared covariance model, not fitted trees'\n }else if(api=='aggregate'){p<-r$predictions[[1]];summary<-list(selectedPrediction=p$prediction);classification<-identical(a$task,'classification');if(classification){summary<-c(summary,list(voteLabel=p$vote,probabilityLabel=p$prob,meanProbability1=p$probabilities[2]));add(1,p$probabilities[2],'Mean probability of class 1');add(2,p$votes[2],'Label-vote share of class 1');xl<-'Aggregation (1=probability, 2=vote)';yl<-'Probability or vote share'}else{for(i in seq_along(a$members))add(i,num(a$members[[i]]$predictions$value[1]),'Member prediction');add(3,p$prediction,'Weighted mean');xl<-'Member 1, member 2, aggregate 3';yl<-'Prediction, assumed units'};title<-'Votes and probabilities are distinct objects'\n }else if(api%in%c('bagging','forest')){summary<-list(queryPrediction=r$predictions[[1]]$prediction,OOB.scoreable=r$outOfBag$eligibleRows,OOB.meanLoss=r$outOfBag$meanLoss);for(i in seq_len(nrow(a$rows)))add(i,a$rows$y[i],'Observed training outcome');for(i in seq_along(r$outOfBag$rows))add(i,r$outOfBag$rows[[i]]$prediction,'OOB prediction, when defined');xl<-'Original training ID order';yl<-'Outcome, assumed units';title<-'Repeated draws and ID-level OOB membership'\n }else if(api=='boost'){summary<-list(initial=r$initial,finalMSE=r$losses[[length(r$losses)]]$MSE,stages=r$stages);for(v in r$losses)add(v$stage,v$MSE,'Training MSE');xl<-'Boosting stage (0=initial)';yl<-'Weighted MSE, outcome units squared';title<-'Training descent does not certify held-out gain'\n }else{summary<-list(outer.scoreable=r$outer$eligibleRows,outer.meanLoss=r$outer$meanLoss,baseline.meanLoss=r$baseline$meanLoss,OOB.scoreable=r$result$outOfBag$eligibleRows,OOB.meanLoss=r$result$outOfBag$meanLoss);for(i in seq_along(r$outer$rows)){p<-r$outer$rows[[i]];add(i,as.numeric(p$actual),'Observed outcome');add(i,if(a$kind=='company')p$probabilities[2]else p$prediction,if(a$kind=='company')'Forest probability of class 1'else'Forest prediction')};xl<-'Outer-test source order, not a time path';yl<-if(a$kind=='company')'Churn label / probability'else if(a$kind=='country')'Period life expectancy, years'else'Nominal 1976 USD per hour';title<-'Fixed forest; outer labels did not fit the trees'}\n display<-function(v)if(is.null(v)||is.na(v))'undefined'else sprintf('%.9f',as.numeric(v));write.csv(data.frame(metric=names(summary),value=vapply(summary,display,'')),file.path(out,'summary.csv'),row.names=FALSE);pp<-do.call(rbind,points);write.csv(pp,file.path(out,'plot-points.csv'),row.names=FALSE);dput(r,file.path(out,'full-result.Rtext'));svg(file.path(out,'plot.svg'),width=5.6,height=4.6,pointsize=14);par(mar=c(5.8,5.8,5.3,1.2),mgp=c(3.7,1,0));xr<-range(pp$x);yr<-range(pp$y);if(diff(xr)==0)xr<-xr+c(-.5,.5);if(diff(yr)==0)yr<-yr+c(-.5,.5);plot(xr,yr,type='n',xlab=xl,ylab=yl,cex.lab=.78,axes=FALSE);axis(1,at=pretty(xr,3));axis(2,at=pretty(yr,4),las=1,cex.axis=.82);box();grid(col='#dddddd');cols<-c('#355c72','#a55336','#507956','#78568b');ss<-unique(pp$series);for(i in seq_along(ss)){v<-pp[pp$series==ss[i],];points(v$x,v$y,pch=16,cex=if(nrow(v)>100).35 else .85,col=adjustcolor(cols[i],if(nrow(v)>100).5 else 1))};legend('topleft',legend=ss,col=cols[seq_along(ss)],lty=0,pch=16,cex=.65,bty='n',inset=c(0,-.32),xpd=NA);mtext(title,side=3,line=3.9,cex=.6);dev.off();cat(paste(names(summary),vapply(summary,display,''),sep='=',collapse=', '),'\\n')\n}\nargs<-commandArgs(trailingOnly=TRUE)\ntryCatch(run_fixed(API,INPUT,if(length(args))args[1]else'fixed-results',if(length(args)>1)args[2]else'ml09-sources'),error=function(e){cat('Rejected declared input: ',conditionMessage(e),'\\n',file=stderr());quit(status=2)})\n",
        "inputFiles": [],
        "input": {
          "rows": [
            {
              "id": "a",
              "x": [
                0,
                0
              ],
              "y": 0
            },
            {
              "id": "b",
              "x": [
                1,
                1
              ],
              "y": 1
            },
            {
              "id": "c",
              "x": [
                2,
                0
              ],
              "y": 3
            },
            {
              "id": "d",
              "x": [
                3,
                1
              ],
              "y": 4
            }
          ],
          "queries": [
            {
              "id": "q",
              "x": [
                "3/2",
                0
              ]
            }
          ],
          "bootstrapDraws": [
            [
              "a",
              "a",
              "b",
              "c"
            ],
            [
              "b",
              "c",
              "d",
              "d"
            ]
          ],
          "maxDepth": 2,
          "nodeFeatures": [
            {
              "": [
                0
              ],
              "L": [
                1
              ],
              "R": [
                1
              ]
            },
            {
              "": [
                1
              ],
              "L": [
                0
              ],
              "R": [
                0
              ]
            }
          ]
        },
        "returnCode": 0,
        "expectedFailure": false,
        "stdout": "queryPrediction=1.500000000, OOB.scoreable=2.000000000, OOB.meanLoss=5.000000000 \n",
        "stderr": "During startup - Warning messages:\n1: Setting LC_COLLATE=C.UTF-8 failed \n2: Setting LC_CTYPE=C.UTF-8 failed \n3: Setting LC_MONETARY=C.UTF-8 failed \n4: Setting LC_TIME=C.UTF-8 failed \n",
        "summary": {
          "queryPrediction": "1.500000000",
          "OOB.scoreable": "2.000000000",
          "OOB.meanLoss": "5.000000000"
        },
        "plotPoints": [
          {
            "x": "1",
            "y": "0",
            "series": "Observed training outcome"
          },
          {
            "x": "2",
            "y": "1",
            "series": "Observed training outcome"
          },
          {
            "x": "3",
            "y": "3",
            "series": "Observed training outcome"
          },
          {
            "x": "4",
            "y": "4",
            "series": "Observed training outcome"
          },
          {
            "x": "1",
            "y": "3",
            "series": "OOB prediction, when defined"
          },
          {
            "x": "4",
            "y": "3",
            "series": "OOB prediction, when defined"
          }
        ],
        "plotFile": "ml09-fixed-results/forest-node-features-r/plot.svg",
        "plotSHA256": "16d25a32530c358f500e3011dea1503955d632193caa6ee38b9247e60308ee7f",
        "files": [
          {
            "file": "ml09-fixed-results/forest-node-features-r/full-result.Rtext",
            "sha256": "330973e1b08daecfd8785337be9d0c4aa5514b6d3d29226a67dd1c2eda077a8a"
          },
          {
            "file": "ml09-fixed-results/forest-node-features-r/plot-points.csv",
            "sha256": "3fa8ecd42a97ddc40dc965bb2c133efc2451bc1d44ddc14e2b82a34e2d6be612"
          },
          {
            "file": "ml09-fixed-results/forest-node-features-r/plot.svg",
            "sha256": "16d25a32530c358f500e3011dea1503955d632193caa6ee38b9247e60308ee7f"
          },
          {
            "file": "ml09-fixed-results/forest-node-features-r/summary.csv",
            "sha256": "517dba625bfeec27ea0fb7ba74d303cc4f0a1b9d8d86f37aef7b31e42c8515e4"
          }
        ],
        "scope": "Actually executed self-contained fixed example; current web controls execute separately. Python Fraction and finite-precision base R. Author gate, not independent peer."
      },
      "weak-root": {
        "api": "forest",
        "variant": "weak-root",
        "language": "r",
        "codeFile": "ml09-code/forest-weak-root.R",
        "codeSHA256": "31d0b045f9073261e488675654ef8af0e328f750a5df397ca6fce8d63a077ed1",
        "codeText": "# ML09 base-R reproduction from native original-field CSVs.\n# Rscript ml09-public-analysis.R ml09-sources results-r\n# Separately written vectorized direct-centered squared/Gini losses.\n# No Python/JS/model-contract/stored-answer/derived-result reader or package.\n# Numeric arithmetic is binary64:1e-12 relative tie tolerance stabilizes exact\n# source ties,but does not certify tiny margins/underflow like Fraction JS/Python.\n# Data-frame rows use x0,x1,...,y,weight; original IDs remain attached to draws.\noptions(stringsAsFactors=FALSE,digits=17)\nnum<-function(v){if(is.null(v)||length(v)!=1||is.na(v))stop('numeric parameter required, not explicit NULL');p<-strsplit(as.character(v),'/',fixed=TRUE)[[1]];z<-if(length(p)==2)as.numeric(p[1])/as.numeric(p[2])else as.numeric(v);if(!is.finite(z))stop('finite numeric parameter');z}\noption<-function(a,k,default){if(k%in%names(a))a[[k]]else default}\nnormrows<-function(d,task){if(!'weight'%in%names(d))d$weight<-1;if(!'id'%in%names(d))d$id<-as.character(seq_len(nrow(d))-1);d$weight<-as.numeric(d$weight);if(anyNA(d$weight)||any(d$weight<0))stop('nonnegative weights');if(task=='regression')d$y<-as.numeric(d$y)else d$y<-as.character(d$y);d}\nstat<-function(d,task,classes){W<-sum(d$weight);mu<-if(task=='regression'&&W)sum(d$weight*d$y)/W else NA_real_;p<-if(task=='classification'&&W)vapply(classes,function(c)sum(d$weight[d$y==c])/W,0)else numeric();risk<-if(task=='regression'&&W)sum(d$weight*(d$y-mu)^2)else W*sum(p*(1-p));list(n=nrow(d),w=W,mu=mu,p=unname(p),risk=risk,pred=if(task=='regression')mu else if(W)classes[which.max(p)]else NA_character_)}\nfit<-function(d,a,task,classes,schedule=NULL){d<-d[d$weight>0&!is.na(d$y),,drop=FALSE];if(!nrow(d))stop('positive observed training');W<-sum(d$weight);depth<-option(a,'maxDepth',2);minimum<-option(a,'minLeaf',1);minmass<-num(option(a,'minLeafWeight',0));mingain<-num(option(a,'minGain',0));route<-option(a,'missingRoute','best');features<-grep('^x[0-9]+$',names(d),value=TRUE)\n build<-function(rr,level,path){st<-stat(rr,task,classes);node<-list(rows=rr,st=st,split=NULL,left=NULL,right=NULL,path=path);if(level==depth)return(node);best<-NULL;allowed<-if(is.null(schedule))seq_along(features)-1L else schedule[[match(path,names(schedule))]]\n  for(j in seq_along(features)-1L){if(!j%in%allowed)next;v<-rr[[features[j+1L]]];values<-sort(unique(v[!is.na(v)]));candidates<-list()\n   if(length(values)>1)for(k in seq_len(length(values)-1L)){threshold<-(values[k]+values[k+1L])/2;missing<-is.na(v);left<-!missing&v<=threshold;right<-!missing&v>threshold;directions<-if(route!='best')route else if(any(missing))c('left','right')else if(sum(left)>=sum(right))'left'else'right';for(direction in directions)candidates[[length(candidates)+1L]]<-list(kind='threshold',threshold=threshold,missingRoute=direction,left=if(direction=='left')left|missing else left,right=if(direction=='right')right|missing else right)}\n   if(anyNA(v)&&any(!is.na(v)))candidates[[length(candidates)+1L]]<-list(kind='missing-only',threshold=NA_real_,missingRoute='left',left=is.na(v),right=!is.na(v))\n   for(candidate in candidates){l<-rr[candidate$left,,drop=FALSE];r<-rr[candidate$right,,drop=FALSE];ls<-stat(l,task,classes);rs<-stat(r,task,classes);if(min(ls$n,rs$n)<minimum||min(ls$w,rs$w)<minmass||min(ls$w,rs$w)<=0)next;gain<-(st$risk-ls$risk-rs$risk)/W;tol<-1e-12*max(1,abs(gain),if(is.null(best))0 else abs(best$gain));if(is.null(best)||gain>best$gain+tol)best<-c(candidate,list(feature=j,gain=gain,l=l,r=r))}\n  }\n  if(!is.null(best)&&best$gain>max(mingain,1e-12)){node$split<-best;node$left<-build(best$l,level+1L,paste0(path,'L'));node$right<-build(best$r,level+1L,paste0(path,'R'))};node\n };build(d,0L,'')\n}\npredict_one<-function(tree,row){n<-tree;while(!is.null(n$split)){s<-n$split;v<-as.numeric(row[[paste0('x',s$feature)]]);left<-if(s$kind=='missing-only')is.na(v)else if(is.na(v))s$missingRoute=='left'else v<=s$threshold;n<-if(left)n$left else n$right};list(prediction=n$st$pred,probabilities=n$st$p)}\ncombine<-function(pp,w,task,classes,mode='probabilities'){W<-sum(w);if(!length(pp)||!W)return(list(prediction=if(task=='regression')NA_real_ else NA_character_,probabilities=numeric(),vote=NA_character_,prob=NA_character_));if(task=='regression')return(list(prediction=sum(vapply(pp,function(p)p$prediction,0)*w)/W,probabilities=numeric(),vote=NA_character_,prob=NA_character_));votes<-vapply(classes,function(c)sum(w[vapply(pp,function(p)p$prediction==c,FALSE)])/W,0);probs<-vapply(seq_along(classes),function(j)sum(vapply(pp,function(p)p$probabilities[j],0)*w)/W,0);vote<-classes[which.max(votes)];prob<-classes[which.max(probs)];list(prediction=if(mode=='votes')vote else prob,probabilities=unname(probs),vote=vote,prob=prob,votes=unname(votes))}\nvariance<-function(a){B<-num(a$B);v<-num(a$marginalVariance);rho<-num(option(a,'rho',0));if(B<1||B!=floor(B)||v<0)stop('integer B/nonnegative variance');if(B>1&&v>0&&(rho< -1/(B-1)||rho>1))stop('PSD correlation');list(B=B,marginalVariance=v,correlationApplicable=B>1&&v>0,varianceOfMean=if(B==1)v else v*(1+(B-1)*rho)/B)}\naggregate<-function(a){task<-option(a,'task','regression');classes<-option(a,'classes',character());w<-vapply(option(a,'memberWeights',as.list(rep(1,length(a$members)))),num,0);if(any(w<0)||sum(w)<=0)stop('positive member mass');ids<-a$members[[1]]$predictions$id;pp<-lapply(ids,function(id){members<-lapply(a$members,function(m){r<-m$predictions[match(id,m$predictions$id),,drop=FALSE];if(task=='regression')list(prediction=num(r$value),probabilities=numeric())else list(prediction=as.character(r$label),probabilities=as.numeric(r[paste0('p',seq_along(classes)-1L)]))});c(list(id=id),combine(members,w,task,classes,option(a,'aggregation','probabilities')))});list(task=task,classes=classes,predictions=pp)}\nscored<-function(preds,d,task,classes){W<-loss<-absolute<-errors<-voteerrors<-0;count<-0L;out<-lapply(seq_len(nrow(d)),function(i){r<-d[i,,drop=FALSE];p<-preds[[i]];ok<-!is.na(p$prediction)&&!is.na(r$y)&&r$weight>0;value<-NA_real_;if(ok){count<<-count+1L;W<<-W+r$weight;if(task=='regression'){e<-r$y-p$prediction;value<-e*e;absolute<<-absolute+r$weight*abs(e)}else{value<-sum((p$probabilities-as.numeric(classes==r$y))^2);errors<<-errors+r$weight*(p$prediction!=r$y);voteerrors<<-voteerrors+r$weight*(p$vote!=r$y)};loss<<-loss+r$weight*value};c(p,list(actual=r$y,weight=r$weight,scoreEligible=ok,loss=value))});list(rows=out,eligibleRows=count,weight=W,totalLoss=loss,meanLoss=if(W)loss/W else NA_real_,MAE=if(W&&task=='regression')absolute/W else NA_real_,errorRate=if(W&&task=='classification')errors/W else NA_real_,labelVoteErrorRate=if(W&&task=='classification')voteerrors/W else NA_real_)}\nensemble<-function(a,forest=FALSE){task<-option(a,'task','regression');classes<-option(a,'classes',character());d<-normrows(a$rows,task);w<-vapply(option(a,'memberWeights',as.list(rep(1,length(a$bootstrapDraws)))),num,0);if(any(w<0)||sum(w)<=0)stop('positive member mass');members<-lapply(seq_along(a$bootstrapDraws),function(i){draw<-a$bootstrapDraws[[i]];indices<-match(draw,d$id);if(anyNA(indices))stop('unknown draw source');tree<-fit(d[indices,,drop=FALSE],a,task,classes,if(forest)a$nodeFeatures[[i]]else NULL);list(tree=tree,draw=draw,inbag=unique(draw),weight=w[i])});queries<-a$queries;preds<-lapply(seq_len(nrow(queries)),function(i)c(list(id=queries$id[i]),combine(lapply(members,function(m)predict_one(m$tree,queries[i,,drop=FALSE])),w,task,classes,option(a,'aggregation','probabilities'))));oob<-lapply(seq_len(nrow(d)),function(i){app<-which(!vapply(members,function(m)d$id[i]%in%m$inbag,FALSE));pp<-combine(lapply(app,function(j)predict_one(members[[j]]$tree,d[i,,drop=FALSE])),w[app],task,classes,option(a,'aggregation','probabilities'));c(list(id=d$id[i],applicable=app-1L,positiveMembers=sum(w[app]>0)),pp)});list(task=task,classes=classes,members=members,predictions=preds,outOfBag=scored(oob,d,task,classes))}\nboost<-function(a){if(option(a,'task','regression')!='regression')stop('regression boosting only');d<-normrows(a$rows,'regression');eligible<-d$weight>0&!is.na(d$y);W<-sum(d$weight[eligible]);if(!W)stop('positive eligible training');eta<-num(option(a,'learningRate','1/2'));stages<-option(a,'stages',3);if(is.null(stages)||stages!=floor(stages)||stages<0||stages>8||eta<0||eta>1)stop('supported rate/stages');initial<-if('initial'%in%names(a))num(a$initial)else sum(d$weight[eligible]*d$y[eligible])/W;train<-matrix(initial,nrow(d),stages+1L);query<-matrix(initial,nrow(a$queries),stages+1L);losses<-fits<-list();for(stage in 0:stages){sse<-sum(d$weight[eligible]*(d$y[eligible]-train[eligible,stage+1L])^2);losses[[stage+1L]]<-list(stage=stage,rawWeightedSSE=sse,MSE=sse/W,meanHalfSquaredLoss=sse/(2*W));if(stage==stages)break;residual<-d;residual$y<-d$y-train[,stage+1L];tree<-fit(residual,a,'regression',character());h<-vapply(seq_len(nrow(d)),function(i)predict_one(tree,d[i,,drop=FALSE])$prediction,0);qh<-vapply(seq_len(nrow(a$queries)),function(i)predict_one(tree,a$queries[i,,drop=FALSE])$prediction,0);stageRows<-lapply(seq_len(nrow(d)),function(i)list(id=d$id[i],before=train[i,stage+1L],residual=residual$y[i],negativeCoordinateDerivative=d$weight[i]*residual$y[i]/W,fit=h[i],addition=eta*h[i],after=train[i,stage+1L]+eta*h[i]));train[,stage+2L]<-train[,stage+1L]+eta*h;query[,stage+2L]<-query[,stage+1L]+eta*qh;norm<-sum(d$weight[eligible]*h[eligible]^2);fits[[stage+1L]]<-list(stage=stage+1L,tree=tree,rows=stageRows,queryFits=qh,norm=norm,predictedSSEDecrease=eta*(2-eta)*norm)};list(task='regression',initial=initial,learningRate=eta,stages=stages,training=train,queries=query,fits=fits,losses=losses,predictions=lapply(seq_len(nrow(a$queries)),function(i)list(id=a$queries$id[i],prediction=query[i,stages+1L],probabilities=numeric(),vote=NA_character_,prob=NA_character_)))}\nfixed_schedules<-function(ids,p,seed){state<-seed;choose<-function(n){limit<-floor(4294967296/n)*n;repeat{state<<-(1664525*state+1013904223)%%4294967296;if(state<limit)return(as.integer(state%%n))}};draws<-schedules<-list();for(member in 1:4){draws[[member]]<-vapply(seq_along(ids),function(i)ids[choose(length(ids))+1L],'');schedule<-setNames(vector('list',7),c('','L','R','LL','LR','RL','RR'));for(path in names(schedule)){order<-seq_len(p)-1L;if(p>1)for(j in seq(p-1L,1L)){k<-choose(j+1L);temp<-order[j+1L];order[j+1L]<-order[k+1L];order[k+1L]<-temp};schedule[[match(path,names(schedule))]]<-sort(order[seq_len(max(1L,floor(sqrt(p))))])};schedules[[member]]<-schedule};list(draws=draws,schedules=schedules)}\nread_sources<-function(src){read<-function(name)read.csv(file.path(src,name),check.names=FALSE,colClasses='character',na.strings=character(),fileEncoding='UTF-8-BOM');raw<-read('actual320-country-four-indicators-original-2020-2024.csv');country<-do.call(rbind,lapply(sort(unique(raw$countryISO3)),function(code)do.call(rbind,lapply(2020:2024,function(year){keys<-c('NY.GDP.PCAP.KD','NY.GDP.MKTP.KD.ZG','FP.CPI.TOTL.ZG','SP.DYN.LE00.IN');v<-vapply(keys,function(k)as.numeric(raw$originalValueToken[raw$countryISO3==code&raw$date==as.character(year)&raw$indicatorID==k]),0);data.frame(id=paste0(code,':',year),sourceRow=paste0(code,':',year),originalID=code,year=year,x0=v[1]/10000,x1=v[2],x2=v[3],y=v[4],weight=1,role=if(anyNA(v))'excluded'else if(year==2024)'outer-test'else'train')}))));raw<-read('actual3613-NLS-original52-fields-and-selection.csv');i<-seq_len(nrow(raw));x0<-suppressWarnings(as.numeric(raw$ed76));x1<-suppressWarnings(as.numeric(raw$age76));y<-suppressWarnings(as.numeric(raw$wage76))/100;person<-data.frame(id=paste0('person:',i),sourceRow=as.character(i),originalID=raw$id,x0=x0,x1=x1,y=y,weight=1,role=ifelse(is.na(x0)|is.na(x1)|is.na(y),'excluded',ifelse(i%%5==0,'outer-test','train')));raw<-read('actual3150-churn-original14-fields-and-selection.csv');i<-seq_len(nrow(raw));company<-data.frame(id=paste0('customer:',i),sourceRow=as.character(i),originalID='',x0=as.numeric(raw[['Call  Failure']]),x1=as.numeric(raw[['Subscription  Length']]),x2=as.numeric(raw[['Charge  Amount']]),y=raw$Churn,weight=1,role=ifelse(i%%5==0,'outer-test','train'));models<-list();for(index in 1:3){kind<-c('country','person','company')[index];d<-list(country,person,company)[[index]];task<-if(kind=='company')'classification'else'regression';s<-fixed_schedules(d$id[d$role=='train'],if(kind=='person')2L else 3L,20261102+7919*(index-1L));models[[kind]]<-list(records=d,task=task,classes=if(task=='classification')c('0','1')else character(),draws=s$draws,schedules=s$schedules,minLeaf=c(4L,50L,30L)[index])};models}\nrealdata<-function(models,kind,options=list()){if(is.null(options)||!is.list(options))stop('options object');m<-models[[kind]];d<-m$records;train<-d[d$role=='train',,drop=FALSE];test<-d[d$role=='outer-test',,drop=FALSE];method<-option(options,'method','forest');depth<-option(options,'maxDepth',2);count<-option(options,'memberCount',3);if(!method%in%c('bagging','forest','boost'))stop('known method');a<-list(rows=train,queries=test,task=m$task,classes=m$classes,maxDepth=depth,minLeaf=option(options,'minLeaf',m$minLeaf),minLeafWeight=0,minGain=0,missingRoute='best',learningRate=option(options,'learningRate','1/2'),stages=option(options,'stages',3));if(method=='boost')result<-boost(a)else{a$bootstrapDraws<-m$draws[seq_len(count)];a$nodeFeatures<-lapply(m$schedules[seq_len(count)],function(s)s[nchar(names(s))<depth]);result<-ensemble(a,method=='forest')};outer<-scored(result$predictions,normrows(test,m$task),m$task,m$classes);st<-stat(normrows(train,m$task),m$task,m$classes);constant<-list(prediction=st$pred,probabilities=st$p,vote=st$pred,prob=st$pred);baseline<-scored(lapply(test$id,function(id)c(list(id=id),constant)),normrows(test,m$task),m$task,m$classes);list(kind=kind,method=method,settings=a,train=train,test=test,result=result,outer=outer,baseline=baseline)}\nAPI<-\"forest\"\nINPUT<-list(rows=data.frame(id=c(\"0\",\"1\",\"2\",\"3\"),y=c(0,2,4,6),x0=c(0,0,0,0),x1=c(0,1,2,3),stringsAsFactors=FALSE),queries=data.frame(id=c(\"q\"),x0=c(0),x1=c(num(\"3/2\")),stringsAsFactors=FALSE),bootstrapDraws=list(c(\"0\",\"1\",\"2\",\"3\")),nodeFeatures=list(setNames(list(c(0)),c(\"\"))),maxDepth=1)\n\nrun_fixed<-function(api,a,out,src){\n r<-if(api=='variance')variance(a)else if(api=='aggregate')aggregate(a)else if(api%in%c('bagging','forest'))ensemble(a,api=='forest')else if(api=='boost')boost(a)else realdata(read_sources(src),a$kind)\n dir.create(out,recursive=TRUE,showWarnings=FALSE);summary<-list();points<-list();add<-function(x,y,s){if(!is.null(y)&&!is.na(y))points[[length(points)+1L]]<<-data.frame(x=x,y=as.numeric(y),series=s)}\n if(api=='variance'){summary<-r[c('B','varianceOfMean')];add(r$B,r$varianceOfMean,'Specified finite-B variance');xl<-'Number of members B';yl<-'Variance, stipulated units squared';title<-'Declared covariance model, not fitted trees'\n }else if(api=='aggregate'){p<-r$predictions[[1]];summary<-list(selectedPrediction=p$prediction);classification<-identical(a$task,'classification');if(classification){summary<-c(summary,list(voteLabel=p$vote,probabilityLabel=p$prob,meanProbability1=p$probabilities[2]));add(1,p$probabilities[2],'Mean probability of class 1');add(2,p$votes[2],'Label-vote share of class 1');xl<-'Aggregation (1=probability, 2=vote)';yl<-'Probability or vote share'}else{for(i in seq_along(a$members))add(i,num(a$members[[i]]$predictions$value[1]),'Member prediction');add(3,p$prediction,'Weighted mean');xl<-'Member 1, member 2, aggregate 3';yl<-'Prediction, assumed units'};title<-'Votes and probabilities are distinct objects'\n }else if(api%in%c('bagging','forest')){summary<-list(queryPrediction=r$predictions[[1]]$prediction,OOB.scoreable=r$outOfBag$eligibleRows,OOB.meanLoss=r$outOfBag$meanLoss);for(i in seq_len(nrow(a$rows)))add(i,a$rows$y[i],'Observed training outcome');for(i in seq_along(r$outOfBag$rows))add(i,r$outOfBag$rows[[i]]$prediction,'OOB prediction, when defined');xl<-'Original training ID order';yl<-'Outcome, assumed units';title<-'Repeated draws and ID-level OOB membership'\n }else if(api=='boost'){summary<-list(initial=r$initial,finalMSE=r$losses[[length(r$losses)]]$MSE,stages=r$stages);for(v in r$losses)add(v$stage,v$MSE,'Training MSE');xl<-'Boosting stage (0=initial)';yl<-'Weighted MSE, outcome units squared';title<-'Training descent does not certify held-out gain'\n }else{summary<-list(outer.scoreable=r$outer$eligibleRows,outer.meanLoss=r$outer$meanLoss,baseline.meanLoss=r$baseline$meanLoss,OOB.scoreable=r$result$outOfBag$eligibleRows,OOB.meanLoss=r$result$outOfBag$meanLoss);for(i in seq_along(r$outer$rows)){p<-r$outer$rows[[i]];add(i,as.numeric(p$actual),'Observed outcome');add(i,if(a$kind=='company')p$probabilities[2]else p$prediction,if(a$kind=='company')'Forest probability of class 1'else'Forest prediction')};xl<-'Outer-test source order, not a time path';yl<-if(a$kind=='company')'Churn label / probability'else if(a$kind=='country')'Period life expectancy, years'else'Nominal 1976 USD per hour';title<-'Fixed forest; outer labels did not fit the trees'}\n display<-function(v)if(is.null(v)||is.na(v))'undefined'else sprintf('%.9f',as.numeric(v));write.csv(data.frame(metric=names(summary),value=vapply(summary,display,'')),file.path(out,'summary.csv'),row.names=FALSE);pp<-do.call(rbind,points);write.csv(pp,file.path(out,'plot-points.csv'),row.names=FALSE);dput(r,file.path(out,'full-result.Rtext'));svg(file.path(out,'plot.svg'),width=5.6,height=4.6,pointsize=14);par(mar=c(5.8,5.8,5.3,1.2),mgp=c(3.7,1,0));xr<-range(pp$x);yr<-range(pp$y);if(diff(xr)==0)xr<-xr+c(-.5,.5);if(diff(yr)==0)yr<-yr+c(-.5,.5);plot(xr,yr,type='n',xlab=xl,ylab=yl,cex.lab=.78,axes=FALSE);axis(1,at=pretty(xr,3));axis(2,at=pretty(yr,4),las=1,cex.axis=.82);box();grid(col='#dddddd');cols<-c('#355c72','#a55336','#507956','#78568b');ss<-unique(pp$series);for(i in seq_along(ss)){v<-pp[pp$series==ss[i],];points(v$x,v$y,pch=16,cex=if(nrow(v)>100).35 else .85,col=adjustcolor(cols[i],if(nrow(v)>100).5 else 1))};legend('topleft',legend=ss,col=cols[seq_along(ss)],lty=0,pch=16,cex=.65,bty='n',inset=c(0,-.32),xpd=NA);mtext(title,side=3,line=3.9,cex=.6);dev.off();cat(paste(names(summary),vapply(summary,display,''),sep='=',collapse=', '),'\\n')\n}\nargs<-commandArgs(trailingOnly=TRUE)\ntryCatch(run_fixed(API,INPUT,if(length(args))args[1]else'fixed-results',if(length(args)>1)args[2]else'ml09-sources'),error=function(e){cat('Rejected declared input: ',conditionMessage(e),'\\n',file=stderr());quit(status=2)})\n",
        "code": "# ML09 base-R reproduction from native original-field CSVs.\n# Rscript ml09-public-analysis.R ml09-sources results-r\n# Separately written vectorized direct-centered squared/Gini losses.\n# No Python/JS/model-contract/stored-answer/derived-result reader or package.\n# Numeric arithmetic is binary64:1e-12 relative tie tolerance stabilizes exact\n# source ties,but does not certify tiny margins/underflow like Fraction JS/Python.\n# Data-frame rows use x0,x1,...,y,weight; original IDs remain attached to draws.\noptions(stringsAsFactors=FALSE,digits=17)\nnum<-function(v){if(is.null(v)||length(v)!=1||is.na(v))stop('numeric parameter required, not explicit NULL');p<-strsplit(as.character(v),'/',fixed=TRUE)[[1]];z<-if(length(p)==2)as.numeric(p[1])/as.numeric(p[2])else as.numeric(v);if(!is.finite(z))stop('finite numeric parameter');z}\noption<-function(a,k,default){if(k%in%names(a))a[[k]]else default}\nnormrows<-function(d,task){if(!'weight'%in%names(d))d$weight<-1;if(!'id'%in%names(d))d$id<-as.character(seq_len(nrow(d))-1);d$weight<-as.numeric(d$weight);if(anyNA(d$weight)||any(d$weight<0))stop('nonnegative weights');if(task=='regression')d$y<-as.numeric(d$y)else d$y<-as.character(d$y);d}\nstat<-function(d,task,classes){W<-sum(d$weight);mu<-if(task=='regression'&&W)sum(d$weight*d$y)/W else NA_real_;p<-if(task=='classification'&&W)vapply(classes,function(c)sum(d$weight[d$y==c])/W,0)else numeric();risk<-if(task=='regression'&&W)sum(d$weight*(d$y-mu)^2)else W*sum(p*(1-p));list(n=nrow(d),w=W,mu=mu,p=unname(p),risk=risk,pred=if(task=='regression')mu else if(W)classes[which.max(p)]else NA_character_)}\nfit<-function(d,a,task,classes,schedule=NULL){d<-d[d$weight>0&!is.na(d$y),,drop=FALSE];if(!nrow(d))stop('positive observed training');W<-sum(d$weight);depth<-option(a,'maxDepth',2);minimum<-option(a,'minLeaf',1);minmass<-num(option(a,'minLeafWeight',0));mingain<-num(option(a,'minGain',0));route<-option(a,'missingRoute','best');features<-grep('^x[0-9]+$',names(d),value=TRUE)\n build<-function(rr,level,path){st<-stat(rr,task,classes);node<-list(rows=rr,st=st,split=NULL,left=NULL,right=NULL,path=path);if(level==depth)return(node);best<-NULL;allowed<-if(is.null(schedule))seq_along(features)-1L else schedule[[match(path,names(schedule))]]\n  for(j in seq_along(features)-1L){if(!j%in%allowed)next;v<-rr[[features[j+1L]]];values<-sort(unique(v[!is.na(v)]));candidates<-list()\n   if(length(values)>1)for(k in seq_len(length(values)-1L)){threshold<-(values[k]+values[k+1L])/2;missing<-is.na(v);left<-!missing&v<=threshold;right<-!missing&v>threshold;directions<-if(route!='best')route else if(any(missing))c('left','right')else if(sum(left)>=sum(right))'left'else'right';for(direction in directions)candidates[[length(candidates)+1L]]<-list(kind='threshold',threshold=threshold,missingRoute=direction,left=if(direction=='left')left|missing else left,right=if(direction=='right')right|missing else right)}\n   if(anyNA(v)&&any(!is.na(v)))candidates[[length(candidates)+1L]]<-list(kind='missing-only',threshold=NA_real_,missingRoute='left',left=is.na(v),right=!is.na(v))\n   for(candidate in candidates){l<-rr[candidate$left,,drop=FALSE];r<-rr[candidate$right,,drop=FALSE];ls<-stat(l,task,classes);rs<-stat(r,task,classes);if(min(ls$n,rs$n)<minimum||min(ls$w,rs$w)<minmass||min(ls$w,rs$w)<=0)next;gain<-(st$risk-ls$risk-rs$risk)/W;tol<-1e-12*max(1,abs(gain),if(is.null(best))0 else abs(best$gain));if(is.null(best)||gain>best$gain+tol)best<-c(candidate,list(feature=j,gain=gain,l=l,r=r))}\n  }\n  if(!is.null(best)&&best$gain>max(mingain,1e-12)){node$split<-best;node$left<-build(best$l,level+1L,paste0(path,'L'));node$right<-build(best$r,level+1L,paste0(path,'R'))};node\n };build(d,0L,'')\n}\npredict_one<-function(tree,row){n<-tree;while(!is.null(n$split)){s<-n$split;v<-as.numeric(row[[paste0('x',s$feature)]]);left<-if(s$kind=='missing-only')is.na(v)else if(is.na(v))s$missingRoute=='left'else v<=s$threshold;n<-if(left)n$left else n$right};list(prediction=n$st$pred,probabilities=n$st$p)}\ncombine<-function(pp,w,task,classes,mode='probabilities'){W<-sum(w);if(!length(pp)||!W)return(list(prediction=if(task=='regression')NA_real_ else NA_character_,probabilities=numeric(),vote=NA_character_,prob=NA_character_));if(task=='regression')return(list(prediction=sum(vapply(pp,function(p)p$prediction,0)*w)/W,probabilities=numeric(),vote=NA_character_,prob=NA_character_));votes<-vapply(classes,function(c)sum(w[vapply(pp,function(p)p$prediction==c,FALSE)])/W,0);probs<-vapply(seq_along(classes),function(j)sum(vapply(pp,function(p)p$probabilities[j],0)*w)/W,0);vote<-classes[which.max(votes)];prob<-classes[which.max(probs)];list(prediction=if(mode=='votes')vote else prob,probabilities=unname(probs),vote=vote,prob=prob,votes=unname(votes))}\nvariance<-function(a){B<-num(a$B);v<-num(a$marginalVariance);rho<-num(option(a,'rho',0));if(B<1||B!=floor(B)||v<0)stop('integer B/nonnegative variance');if(B>1&&v>0&&(rho< -1/(B-1)||rho>1))stop('PSD correlation');list(B=B,marginalVariance=v,correlationApplicable=B>1&&v>0,varianceOfMean=if(B==1)v else v*(1+(B-1)*rho)/B)}\naggregate<-function(a){task<-option(a,'task','regression');classes<-option(a,'classes',character());w<-vapply(option(a,'memberWeights',as.list(rep(1,length(a$members)))),num,0);if(any(w<0)||sum(w)<=0)stop('positive member mass');ids<-a$members[[1]]$predictions$id;pp<-lapply(ids,function(id){members<-lapply(a$members,function(m){r<-m$predictions[match(id,m$predictions$id),,drop=FALSE];if(task=='regression')list(prediction=num(r$value),probabilities=numeric())else list(prediction=as.character(r$label),probabilities=as.numeric(r[paste0('p',seq_along(classes)-1L)]))});c(list(id=id),combine(members,w,task,classes,option(a,'aggregation','probabilities')))});list(task=task,classes=classes,predictions=pp)}\nscored<-function(preds,d,task,classes){W<-loss<-absolute<-errors<-voteerrors<-0;count<-0L;out<-lapply(seq_len(nrow(d)),function(i){r<-d[i,,drop=FALSE];p<-preds[[i]];ok<-!is.na(p$prediction)&&!is.na(r$y)&&r$weight>0;value<-NA_real_;if(ok){count<<-count+1L;W<<-W+r$weight;if(task=='regression'){e<-r$y-p$prediction;value<-e*e;absolute<<-absolute+r$weight*abs(e)}else{value<-sum((p$probabilities-as.numeric(classes==r$y))^2);errors<<-errors+r$weight*(p$prediction!=r$y);voteerrors<<-voteerrors+r$weight*(p$vote!=r$y)};loss<<-loss+r$weight*value};c(p,list(actual=r$y,weight=r$weight,scoreEligible=ok,loss=value))});list(rows=out,eligibleRows=count,weight=W,totalLoss=loss,meanLoss=if(W)loss/W else NA_real_,MAE=if(W&&task=='regression')absolute/W else NA_real_,errorRate=if(W&&task=='classification')errors/W else NA_real_,labelVoteErrorRate=if(W&&task=='classification')voteerrors/W else NA_real_)}\nensemble<-function(a,forest=FALSE){task<-option(a,'task','regression');classes<-option(a,'classes',character());d<-normrows(a$rows,task);w<-vapply(option(a,'memberWeights',as.list(rep(1,length(a$bootstrapDraws)))),num,0);if(any(w<0)||sum(w)<=0)stop('positive member mass');members<-lapply(seq_along(a$bootstrapDraws),function(i){draw<-a$bootstrapDraws[[i]];indices<-match(draw,d$id);if(anyNA(indices))stop('unknown draw source');tree<-fit(d[indices,,drop=FALSE],a,task,classes,if(forest)a$nodeFeatures[[i]]else NULL);list(tree=tree,draw=draw,inbag=unique(draw),weight=w[i])});queries<-a$queries;preds<-lapply(seq_len(nrow(queries)),function(i)c(list(id=queries$id[i]),combine(lapply(members,function(m)predict_one(m$tree,queries[i,,drop=FALSE])),w,task,classes,option(a,'aggregation','probabilities'))));oob<-lapply(seq_len(nrow(d)),function(i){app<-which(!vapply(members,function(m)d$id[i]%in%m$inbag,FALSE));pp<-combine(lapply(app,function(j)predict_one(members[[j]]$tree,d[i,,drop=FALSE])),w[app],task,classes,option(a,'aggregation','probabilities'));c(list(id=d$id[i],applicable=app-1L,positiveMembers=sum(w[app]>0)),pp)});list(task=task,classes=classes,members=members,predictions=preds,outOfBag=scored(oob,d,task,classes))}\nboost<-function(a){if(option(a,'task','regression')!='regression')stop('regression boosting only');d<-normrows(a$rows,'regression');eligible<-d$weight>0&!is.na(d$y);W<-sum(d$weight[eligible]);if(!W)stop('positive eligible training');eta<-num(option(a,'learningRate','1/2'));stages<-option(a,'stages',3);if(is.null(stages)||stages!=floor(stages)||stages<0||stages>8||eta<0||eta>1)stop('supported rate/stages');initial<-if('initial'%in%names(a))num(a$initial)else sum(d$weight[eligible]*d$y[eligible])/W;train<-matrix(initial,nrow(d),stages+1L);query<-matrix(initial,nrow(a$queries),stages+1L);losses<-fits<-list();for(stage in 0:stages){sse<-sum(d$weight[eligible]*(d$y[eligible]-train[eligible,stage+1L])^2);losses[[stage+1L]]<-list(stage=stage,rawWeightedSSE=sse,MSE=sse/W,meanHalfSquaredLoss=sse/(2*W));if(stage==stages)break;residual<-d;residual$y<-d$y-train[,stage+1L];tree<-fit(residual,a,'regression',character());h<-vapply(seq_len(nrow(d)),function(i)predict_one(tree,d[i,,drop=FALSE])$prediction,0);qh<-vapply(seq_len(nrow(a$queries)),function(i)predict_one(tree,a$queries[i,,drop=FALSE])$prediction,0);stageRows<-lapply(seq_len(nrow(d)),function(i)list(id=d$id[i],before=train[i,stage+1L],residual=residual$y[i],negativeCoordinateDerivative=d$weight[i]*residual$y[i]/W,fit=h[i],addition=eta*h[i],after=train[i,stage+1L]+eta*h[i]));train[,stage+2L]<-train[,stage+1L]+eta*h;query[,stage+2L]<-query[,stage+1L]+eta*qh;norm<-sum(d$weight[eligible]*h[eligible]^2);fits[[stage+1L]]<-list(stage=stage+1L,tree=tree,rows=stageRows,queryFits=qh,norm=norm,predictedSSEDecrease=eta*(2-eta)*norm)};list(task='regression',initial=initial,learningRate=eta,stages=stages,training=train,queries=query,fits=fits,losses=losses,predictions=lapply(seq_len(nrow(a$queries)),function(i)list(id=a$queries$id[i],prediction=query[i,stages+1L],probabilities=numeric(),vote=NA_character_,prob=NA_character_)))}\nfixed_schedules<-function(ids,p,seed){state<-seed;choose<-function(n){limit<-floor(4294967296/n)*n;repeat{state<<-(1664525*state+1013904223)%%4294967296;if(state<limit)return(as.integer(state%%n))}};draws<-schedules<-list();for(member in 1:4){draws[[member]]<-vapply(seq_along(ids),function(i)ids[choose(length(ids))+1L],'');schedule<-setNames(vector('list',7),c('','L','R','LL','LR','RL','RR'));for(path in names(schedule)){order<-seq_len(p)-1L;if(p>1)for(j in seq(p-1L,1L)){k<-choose(j+1L);temp<-order[j+1L];order[j+1L]<-order[k+1L];order[k+1L]<-temp};schedule[[match(path,names(schedule))]]<-sort(order[seq_len(max(1L,floor(sqrt(p))))])};schedules[[member]]<-schedule};list(draws=draws,schedules=schedules)}\nread_sources<-function(src){read<-function(name)read.csv(file.path(src,name),check.names=FALSE,colClasses='character',na.strings=character(),fileEncoding='UTF-8-BOM');raw<-read('actual320-country-four-indicators-original-2020-2024.csv');country<-do.call(rbind,lapply(sort(unique(raw$countryISO3)),function(code)do.call(rbind,lapply(2020:2024,function(year){keys<-c('NY.GDP.PCAP.KD','NY.GDP.MKTP.KD.ZG','FP.CPI.TOTL.ZG','SP.DYN.LE00.IN');v<-vapply(keys,function(k)as.numeric(raw$originalValueToken[raw$countryISO3==code&raw$date==as.character(year)&raw$indicatorID==k]),0);data.frame(id=paste0(code,':',year),sourceRow=paste0(code,':',year),originalID=code,year=year,x0=v[1]/10000,x1=v[2],x2=v[3],y=v[4],weight=1,role=if(anyNA(v))'excluded'else if(year==2024)'outer-test'else'train')}))));raw<-read('actual3613-NLS-original52-fields-and-selection.csv');i<-seq_len(nrow(raw));x0<-suppressWarnings(as.numeric(raw$ed76));x1<-suppressWarnings(as.numeric(raw$age76));y<-suppressWarnings(as.numeric(raw$wage76))/100;person<-data.frame(id=paste0('person:',i),sourceRow=as.character(i),originalID=raw$id,x0=x0,x1=x1,y=y,weight=1,role=ifelse(is.na(x0)|is.na(x1)|is.na(y),'excluded',ifelse(i%%5==0,'outer-test','train')));raw<-read('actual3150-churn-original14-fields-and-selection.csv');i<-seq_len(nrow(raw));company<-data.frame(id=paste0('customer:',i),sourceRow=as.character(i),originalID='',x0=as.numeric(raw[['Call  Failure']]),x1=as.numeric(raw[['Subscription  Length']]),x2=as.numeric(raw[['Charge  Amount']]),y=raw$Churn,weight=1,role=ifelse(i%%5==0,'outer-test','train'));models<-list();for(index in 1:3){kind<-c('country','person','company')[index];d<-list(country,person,company)[[index]];task<-if(kind=='company')'classification'else'regression';s<-fixed_schedules(d$id[d$role=='train'],if(kind=='person')2L else 3L,20261102+7919*(index-1L));models[[kind]]<-list(records=d,task=task,classes=if(task=='classification')c('0','1')else character(),draws=s$draws,schedules=s$schedules,minLeaf=c(4L,50L,30L)[index])};models}\nrealdata<-function(models,kind,options=list()){if(is.null(options)||!is.list(options))stop('options object');m<-models[[kind]];d<-m$records;train<-d[d$role=='train',,drop=FALSE];test<-d[d$role=='outer-test',,drop=FALSE];method<-option(options,'method','forest');depth<-option(options,'maxDepth',2);count<-option(options,'memberCount',3);if(!method%in%c('bagging','forest','boost'))stop('known method');a<-list(rows=train,queries=test,task=m$task,classes=m$classes,maxDepth=depth,minLeaf=option(options,'minLeaf',m$minLeaf),minLeafWeight=0,minGain=0,missingRoute='best',learningRate=option(options,'learningRate','1/2'),stages=option(options,'stages',3));if(method=='boost')result<-boost(a)else{a$bootstrapDraws<-m$draws[seq_len(count)];a$nodeFeatures<-lapply(m$schedules[seq_len(count)],function(s)s[nchar(names(s))<depth]);result<-ensemble(a,method=='forest')};outer<-scored(result$predictions,normrows(test,m$task),m$task,m$classes);st<-stat(normrows(train,m$task),m$task,m$classes);constant<-list(prediction=st$pred,probabilities=st$p,vote=st$pred,prob=st$pred);baseline<-scored(lapply(test$id,function(id)c(list(id=id),constant)),normrows(test,m$task),m$task,m$classes);list(kind=kind,method=method,settings=a,train=train,test=test,result=result,outer=outer,baseline=baseline)}\nAPI<-\"forest\"\nINPUT<-list(rows=data.frame(id=c(\"0\",\"1\",\"2\",\"3\"),y=c(0,2,4,6),x0=c(0,0,0,0),x1=c(0,1,2,3),stringsAsFactors=FALSE),queries=data.frame(id=c(\"q\"),x0=c(0),x1=c(num(\"3/2\")),stringsAsFactors=FALSE),bootstrapDraws=list(c(\"0\",\"1\",\"2\",\"3\")),nodeFeatures=list(setNames(list(c(0)),c(\"\"))),maxDepth=1)\n\nrun_fixed<-function(api,a,out,src){\n r<-if(api=='variance')variance(a)else if(api=='aggregate')aggregate(a)else if(api%in%c('bagging','forest'))ensemble(a,api=='forest')else if(api=='boost')boost(a)else realdata(read_sources(src),a$kind)\n dir.create(out,recursive=TRUE,showWarnings=FALSE);summary<-list();points<-list();add<-function(x,y,s){if(!is.null(y)&&!is.na(y))points[[length(points)+1L]]<<-data.frame(x=x,y=as.numeric(y),series=s)}\n if(api=='variance'){summary<-r[c('B','varianceOfMean')];add(r$B,r$varianceOfMean,'Specified finite-B variance');xl<-'Number of members B';yl<-'Variance, stipulated units squared';title<-'Declared covariance model, not fitted trees'\n }else if(api=='aggregate'){p<-r$predictions[[1]];summary<-list(selectedPrediction=p$prediction);classification<-identical(a$task,'classification');if(classification){summary<-c(summary,list(voteLabel=p$vote,probabilityLabel=p$prob,meanProbability1=p$probabilities[2]));add(1,p$probabilities[2],'Mean probability of class 1');add(2,p$votes[2],'Label-vote share of class 1');xl<-'Aggregation (1=probability, 2=vote)';yl<-'Probability or vote share'}else{for(i in seq_along(a$members))add(i,num(a$members[[i]]$predictions$value[1]),'Member prediction');add(3,p$prediction,'Weighted mean');xl<-'Member 1, member 2, aggregate 3';yl<-'Prediction, assumed units'};title<-'Votes and probabilities are distinct objects'\n }else if(api%in%c('bagging','forest')){summary<-list(queryPrediction=r$predictions[[1]]$prediction,OOB.scoreable=r$outOfBag$eligibleRows,OOB.meanLoss=r$outOfBag$meanLoss);for(i in seq_len(nrow(a$rows)))add(i,a$rows$y[i],'Observed training outcome');for(i in seq_along(r$outOfBag$rows))add(i,r$outOfBag$rows[[i]]$prediction,'OOB prediction, when defined');xl<-'Original training ID order';yl<-'Outcome, assumed units';title<-'Repeated draws and ID-level OOB membership'\n }else if(api=='boost'){summary<-list(initial=r$initial,finalMSE=r$losses[[length(r$losses)]]$MSE,stages=r$stages);for(v in r$losses)add(v$stage,v$MSE,'Training MSE');xl<-'Boosting stage (0=initial)';yl<-'Weighted MSE, outcome units squared';title<-'Training descent does not certify held-out gain'\n }else{summary<-list(outer.scoreable=r$outer$eligibleRows,outer.meanLoss=r$outer$meanLoss,baseline.meanLoss=r$baseline$meanLoss,OOB.scoreable=r$result$outOfBag$eligibleRows,OOB.meanLoss=r$result$outOfBag$meanLoss);for(i in seq_along(r$outer$rows)){p<-r$outer$rows[[i]];add(i,as.numeric(p$actual),'Observed outcome');add(i,if(a$kind=='company')p$probabilities[2]else p$prediction,if(a$kind=='company')'Forest probability of class 1'else'Forest prediction')};xl<-'Outer-test source order, not a time path';yl<-if(a$kind=='company')'Churn label / probability'else if(a$kind=='country')'Period life expectancy, years'else'Nominal 1976 USD per hour';title<-'Fixed forest; outer labels did not fit the trees'}\n display<-function(v)if(is.null(v)||is.na(v))'undefined'else sprintf('%.9f',as.numeric(v));write.csv(data.frame(metric=names(summary),value=vapply(summary,display,'')),file.path(out,'summary.csv'),row.names=FALSE);pp<-do.call(rbind,points);write.csv(pp,file.path(out,'plot-points.csv'),row.names=FALSE);dput(r,file.path(out,'full-result.Rtext'));svg(file.path(out,'plot.svg'),width=5.6,height=4.6,pointsize=14);par(mar=c(5.8,5.8,5.3,1.2),mgp=c(3.7,1,0));xr<-range(pp$x);yr<-range(pp$y);if(diff(xr)==0)xr<-xr+c(-.5,.5);if(diff(yr)==0)yr<-yr+c(-.5,.5);plot(xr,yr,type='n',xlab=xl,ylab=yl,cex.lab=.78,axes=FALSE);axis(1,at=pretty(xr,3));axis(2,at=pretty(yr,4),las=1,cex.axis=.82);box();grid(col='#dddddd');cols<-c('#355c72','#a55336','#507956','#78568b');ss<-unique(pp$series);for(i in seq_along(ss)){v<-pp[pp$series==ss[i],];points(v$x,v$y,pch=16,cex=if(nrow(v)>100).35 else .85,col=adjustcolor(cols[i],if(nrow(v)>100).5 else 1))};legend('topleft',legend=ss,col=cols[seq_along(ss)],lty=0,pch=16,cex=.65,bty='n',inset=c(0,-.32),xpd=NA);mtext(title,side=3,line=3.9,cex=.6);dev.off();cat(paste(names(summary),vapply(summary,display,''),sep='=',collapse=', '),'\\n')\n}\nargs<-commandArgs(trailingOnly=TRUE)\ntryCatch(run_fixed(API,INPUT,if(length(args))args[1]else'fixed-results',if(length(args)>1)args[2]else'ml09-sources'),error=function(e){cat('Rejected declared input: ',conditionMessage(e),'\\n',file=stderr());quit(status=2)})\n",
        "inputFiles": [],
        "input": {
          "rows": [
            {
              "id": "0",
              "x": [
                0,
                0
              ],
              "y": 0
            },
            {
              "id": "1",
              "x": [
                0,
                1
              ],
              "y": 2
            },
            {
              "id": "2",
              "x": [
                0,
                2
              ],
              "y": 4
            },
            {
              "id": "3",
              "x": [
                0,
                3
              ],
              "y": 6
            }
          ],
          "queries": [
            {
              "id": "q",
              "x": [
                0,
                "3/2"
              ]
            }
          ],
          "bootstrapDraws": [
            [
              "0",
              "1",
              "2",
              "3"
            ]
          ],
          "nodeFeatures": [
            {
              "": [
                0
              ]
            }
          ],
          "maxDepth": 1
        },
        "returnCode": 0,
        "expectedFailure": false,
        "stdout": "queryPrediction=3.000000000, OOB.scoreable=0.000000000, OOB.meanLoss=undefined \n",
        "stderr": "During startup - Warning messages:\n1: Setting LC_COLLATE=C.UTF-8 failed \n2: Setting LC_CTYPE=C.UTF-8 failed \n3: Setting LC_MONETARY=C.UTF-8 failed \n4: Setting LC_TIME=C.UTF-8 failed \n",
        "summary": {
          "queryPrediction": "3.000000000",
          "OOB.scoreable": "0.000000000",
          "OOB.meanLoss": "undefined"
        },
        "plotPoints": [
          {
            "x": "1",
            "y": "0",
            "series": "Observed training outcome"
          },
          {
            "x": "2",
            "y": "2",
            "series": "Observed training outcome"
          },
          {
            "x": "3",
            "y": "4",
            "series": "Observed training outcome"
          },
          {
            "x": "4",
            "y": "6",
            "series": "Observed training outcome"
          }
        ],
        "plotFile": "ml09-fixed-results/forest-weak-root-r/plot.svg",
        "plotSHA256": "7eb5dfb15452e586493d9f48af74b69144782d03234d4097d4034896ce23665b",
        "files": [
          {
            "file": "ml09-fixed-results/forest-weak-root-r/full-result.Rtext",
            "sha256": "1f2ebbc800113b768607d50a66fcdee705ce1f0b9c9fce2eab59e2e9fabd9855"
          },
          {
            "file": "ml09-fixed-results/forest-weak-root-r/plot-points.csv",
            "sha256": "575fe38b04b521ed8beb3fc4573fdd7afa3df386aa18a4c1451dd395b9013dd3"
          },
          {
            "file": "ml09-fixed-results/forest-weak-root-r/plot.svg",
            "sha256": "7eb5dfb15452e586493d9f48af74b69144782d03234d4097d4034896ce23665b"
          },
          {
            "file": "ml09-fixed-results/forest-weak-root-r/summary.csv",
            "sha256": "e8c98e2e471c23ee12445eda356f4242460eb5a7d22142b05b76cb9599219bb9"
          }
        ],
        "scope": "Actually executed self-contained fixed example; current web controls execute separately. Python Fraction and finite-precision base R. Author gate, not independent peer."
      }
    }
  },
  "boost": {
    "python": {
      "two-stages": {
        "api": "boost",
        "variant": "two-stages",
        "language": "python",
        "codeFile": "ml09-code/boost-two-stages.py",
        "codeSHA256": "33943ba7b2aeb10ad276228ee789304f8687e0beaffdc88d211e4b3b8a0ba7ce",
        "codeText": "\"\"\"ML09 exact Fraction reproduction from native source fields.\n\npython ml09-public-analysis.py --source-dir ml09-sources --output-dir results\n\nThis authored educational implementation uses direct-centered leaf losses and\nexhaustive midpoint partitions. It reads no JS engine, model contract, checker,\nstored target answers or derived-result CSV. Its five tree arithmetic helpers\nwere copied from the author's own separate Fraction reference, not an independent\npeer. Parser/work budgets and display rounding of the production JS are separate.\nNumerical predictions/proper scores do not certify causal effects, calibration,\nIID OOB validity, survey representativeness or production parameter optimality.\n\"\"\"\nfrom pathlib import Path\nfrom fractions import Fraction as Q\nimport csv,json,math,itertools,argparse\n\ndef normalized(rows,task='regression'):\n return [dict(id=r.get('id',i),x=[None if x is None else Q(x)for x in r.get('x',[])],y=None if r['y']is None else str(r['y'])if task=='classification'else Q(r['y']),w=Q(r.get('weight',1)))for i,r in enumerate(rows)]\n\ndef totals(rows,task,classes):\n W=sum((r['w']for r in rows),Q());mu=sum((r['w']*r['y']for r in rows),Q())/W if task=='regression'and W else None\n probs=[sum((r['w']for r in rows if r['y']==c),Q())/W for c in classes]if task=='classification'and W else[]\n risk=sum((r['w']*(r['y']-mu)**2 for r in rows),Q())if task=='regression'and W else W*sum((p*(1-p)for p in probs),Q())\n return dict(n=len(rows),w=W,mu=mu,p=probs,risk=risk,pred=mu if task=='regression'else classes[max(range(len(probs)),key=lambda i:probs[i])]if probs else None)\n\ndef fit(rows,a,task,classes,schedule=None):\n good=[r for r in rows if r['w']>0 and r['y']is not None];root=totals(good,task,classes)['w'];depth=a.get('maxDepth',2);minimum=a.get('minLeaf',1);minmass=Q(a.get('minLeafWeight',0));mingain=Q(a.get('minGain',0));route=a.get('missingRoute','best')\n def build(rr,d,path):\n  st=totals(rr,task,classes);n=dict(rows=rr,st=st,split=None,left=None,right=None,path=path)\n  if d==depth:return n\n  best=None\n  for j in range(len(rr[0]['x'])):\n   if schedule is not None and j not in schedule[path]:continue\n   values=sorted({r['x'][j]for r in rr if r['x'][j]is not None});missing=[r for r in rr if r['x'][j]is None];observed=[r for r in rr if r['x'][j]is not None]\n   candidates=[]\n   for lo,hi in zip(values,values[1:]):\n    q=(lo+hi)/2;left=[r for r in observed if r['x'][j]<=q];right=[r for r in observed if r['x'][j]>q];directions=[route]if route!='best'else['left','right']if missing else['left'if len(left)>=len(right)else'right']\n    for direction in directions:candidates.append(('threshold',q,direction,left+missing if direction=='left'else left,right+missing if direction=='right'else right))\n   if missing and observed:candidates.append(('missing-only',None,'left',missing,observed))\n   for kind,q,direction,left,right in candidates:\n    l=totals(left,task,classes);r=totals(right,task,classes)\n    if min(l['n'],r['n'])<minimum or min(l['w'],r['w'])<minmass or min(l['w'],r['w'])<=0:continue\n    gain=(st['risk']-l['risk']-r['risk'])/root\n    if best is None or gain>best['gain']:best=dict(feature=j,kind=kind,threshold=q,missingRoute=direction,left=left,right=right,gain=gain)\n  if best and best['gain']>0 and best['gain']>mingain:\n   j=best['feature'];go=lambda r:r['x'][j]is None if best['kind']=='missing-only'else best['missingRoute']=='left'if r['x'][j]is None else r['x'][j]<=best['threshold'];n['split']=best;n['left']=build([r for r in rr if go(r)],d+1,path+'L');n['right']=build([r for r in rr if not go(r)],d+1,path+'R')\n  return n\n return build(good,0,'')\n\ndef predict(tree,x):\n n=tree\n while n['split']:\n  s=n['split'];v=x[s['feature']];left=v is None if s['kind']=='missing-only'else s['missingRoute']=='left'if v is None else v<=s['threshold'];n=n['left'if left else'right']\n return dict(prediction=n['st']['pred'],probabilities=n['st']['p'])\n\ndef combine(preds,w,task,classes,mode='probabilities'):\n mass=sum(w,Q())\n if not preds or not mass:return dict(prediction=None,probabilities=[],vote=None,prob=None)\n if task=='regression':return dict(prediction=sum((p['prediction']*v for p,v in zip(preds,w)),Q())/mass,probabilities=[],vote=None,prob=None)\n votes=[sum((v for p,v in zip(preds,w)if p['prediction']==c),Q())/mass for c in classes];ps=[sum((p['probabilities'][j]*v for p,v in zip(preds,w)),Q())/mass for j in range(len(classes))];vote=classes[max(range(len(classes)),key=lambda j:votes[j])];prob=classes[max(range(len(classes)),key=lambda j:ps[j])];return dict(prediction=vote if mode=='votes'else prob,probabilities=ps,vote=vote,prob=prob,votes=votes)\ndef number(v):\n if v is None or isinstance(v,bool):raise ValueError('explicit null/bool is not a numeric parameter')\n return Q(v)\ndef variance(a):\n B=a['B'];v=number(a['marginalVariance']);rho=number(a.get('rho',0))\n if not isinstance(B,int)or isinstance(B,bool)or B<1 or v<0:raise ValueError('positive integer B/nonnegative variance')\n if B>1 and v and not -Q(1,B-1)<=rho<=1:raise ValueError('equicorrelation PSD bound')\n return dict(B=B,marginalVariance=v,correlationApplicable=B>1 and bool(v),varianceOfMean=v if B==1 else v*(1+(B-1)*rho)/B)\ndef aggregate(a):\n task=a.get('task','regression');classes=[str(c)for c in a.get('classes',[])];members=a['members'];w=[number(v)for v in a.get('memberWeights',[1]*len(members))]\n if not members or min(w)<0 or sum(w)<=0:raise ValueError('nonnegative member weights/positive total')\n order=[p.get('id',i)for i,p in enumerate(members[0]['predictions'])];keys=lambda x:(type(x).__name__,x);lookup=[{keys(p.get('id',i)):p for i,p in enumerate(m['predictions'])}for m in members]\n if any(set(m)!={keys(v)for v in order}for m in lookup):raise ValueError('same query ID set')\n out=[]\n for pid in order:\n  predictions=[dict(prediction=number(m[keys(pid)]['value']),probabilities=[])if task=='regression'else dict(prediction=str(m[keys(pid)]['label']),probabilities=[number(v)for v in m[keys(pid)]['probabilities']])for m in lookup]\n  if task=='classification'and any(min(p['probabilities'])<0 or sum(p['probabilities'])!=1 for p in predictions):raise ValueError('probability simplex')\n  out.append(dict(id=pid,**combine(predictions,w,task,classes,a.get('aggregation','probabilities'))))\n return dict(task=task,classes=classes,predictions=out)\ndef scored(preds,rows,task,classes):\n mass=loss=absolute=errors=voteerrors=Q();out=[]\n for p,r in zip(preds,rows):\n  ok=p['prediction']is not None and r['y']is not None and r['w']>0;v=None\n  if ok:\n   mass+=r['w']\n   if task=='regression':e=r['y']-p['prediction'];v=e*e;absolute+=r['w']*abs(e)\n   else:v=sum(((q-(1 if r['y']==c else 0))**2 for c,q in zip(classes,p['probabilities'])),Q());errors+=r['w']*(p['prediction']!=r['y']);voteerrors+=r['w']*(p['vote']!=r['y'])\n   loss+=r['w']*v\n  out.append(dict(p,actual=r['y'],weight=r['w'],scoreEligible=ok,loss=v))\n return dict(rows=out,eligibleRows=sum(r['scoreEligible']for r in out),weight=mass,totalLoss=loss,meanLoss=loss/mass if mass else None,MAE=absolute/mass if mass and task=='regression'else None,errorRate=errors/mass if mass and task=='classification'else None,labelVoteErrorRate=voteerrors/mass if mass and task=='classification'else None)\ndef ensemble(a,forest=False):\n task=a.get('task','regression');classes=[str(v)for v in(a.get('classes')or[])];rr=normalized(a['rows'],task);key=lambda x:(type(x).__name__,x);lookup={key(r['id']):r for r in rr};weights=[number(v)for v in a.get('memberWeights',[1]*len(a['bootstrapDraws']))]\n if not any(r['w']>0 and r['y']is not None for r in rr)or min(weights)<0 or sum(weights)<=0:raise ValueError('positive eligible training and member weight')\n members=[]\n for i,draw in enumerate(a['bootstrapDraws']):\n  data=[lookup[key(v)]for v in draw];schedule=a['nodeFeatures'][i]if forest else None;model=fit(data,a,task,classes,schedule);inbag={key(v)for v in draw};members.append(dict(tree=model,draw=draw,inbag=inbag,weight=weights[i]))\n predictions=[]\n for q in a.get('queries',[]):predictions.append(dict(id=q['id'],**combine([predict(m['tree'],[None if v is None else number(v)for v in q['x']])for m in members],weights,task,classes,a.get('aggregation','probabilities'))))\n oob=[]\n for r in rr:\n  applicable=[i for i,m in enumerate(members)if key(r['id'])not in m['inbag']];p=combine([predict(members[i]['tree'],r['x'])for i in applicable],[weights[i]for i in applicable],task,classes,a.get('aggregation','probabilities'));oob.append(dict(id=r['id'],applicable=applicable,positiveMembers=sum(weights[i]>0 for i in applicable),**p))\n return dict(task=task,classes=classes,members=members,predictions=predictions,outOfBag=scored(oob,rr,task,classes))\ndef boost(a):\n if a.get('task','regression')!='regression':raise ValueError('regression boosting only')\n rr=normalized(a['rows']);good=[r for r in rr if r['w']and r['y']is not None];W=sum((r['w']for r in good),Q())\n if not W:raise ValueError('positive eligible training')\n eta=number(a.get('learningRate','1/2'));stages=a.get('stages',3)\n if not 0<=eta<=1 or not isinstance(stages,int)or isinstance(stages,bool)or not 0<=stages<=8:raise ValueError('supported rate/stages')\n initial=number(a['initial'])if'initial'in a else sum((r['w']*r['y']for r in good),Q())/W;training=[[initial]for r in rr];queries=[[initial]for q in a.get('queries',[])];fits=[];losses=[]\n for stage in range(stages+1):\n  sse=sum((r['w']*(r['y']-p[-1])**2 for r,p in zip(rr,training)if r['w']and r['y']is not None),Q());losses.append(dict(stage=stage,rawWeightedSSE=sse,MSE=sse/W,meanHalfSquaredLoss=sse/(2*W)))\n  if stage==stages:break\n  residuals=[dict(r,y=None if r['y']is None else r['y']-p[-1])for r,p in zip(rr,training)];tree=fit(residuals,a,'regression',[]);h=[predict(tree,r['x'])['prediction']for r in rr];qh=[predict(tree,[None if v is None else number(v)for v in q['x']])['prediction']for q in a.get('queries',[])];norm=sum((r['w']*v*v for r,v in zip(rr,h)if r['y']is not None),Q());stageRows=[]\n  for i,(r,p)in enumerate(zip(rr,training)):\n   residual=None if r['y']is None else r['y']-p[-1];stageRows.append(dict(id=r['id'],before=p[-1],residual=residual,negativeCoordinateDerivative=None if residual is None else r['w']*residual/W,fit=h[i],addition=eta*h[i],after=p[-1]+eta*h[i]));p.append(p[-1]+eta*h[i])\n  for p,v in zip(queries,qh):p.append(p[-1]+eta*v)\n  fits.append(dict(stage=stage+1,tree=tree,rows=stageRows,queryFits=qh,norm=norm,predictedSSEDecrease=eta*(2-eta)*norm))\n return dict(task='regression',initial=initial,learningRate=eta,stages=stages,training=training,queries=queries,fits=fits,losses=losses,predictions=[dict(id=q['id'],prediction=p[-1],probabilities=[],vote=None,prob=None)for q,p in zip(a.get('queries',[]),queries)])\nclass Stream:\n def __init__(self,state):self.state=state\n def choose(self,n):\n  limit=(1<<32)-((1<<32)%n)\n  while True:\n   self.state=(1664525*self.state+1013904223)&0xffffffff\n   if self.state<limit:return self.state%n\ndef fixed_schedules(ids,p,seed):\n stream=Stream(seed);draws=[];schedules=[];paths=['']+[p for d in[1,2]for p in map(''.join,itertools.product('LR',repeat=d))]\n for member in range(4):\n  draws.append([ids[stream.choose(len(ids))]for _ in range(len(ids))]);schedule={}\n  for path in paths:\n   order=list(range(p))\n   for j in range(p-1,0,-1):k=stream.choose(j+1);order[j],order[k]=order[k],order[j]\n   schedule[path]=sorted(order[:max(1,int(math.sqrt(p)))])\n  schedules.append(schedule)\n return draws,schedules\ndef csvread(file):\n with Path(file).open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))\ndef read_sources(source):\n source=Path(source);raw=csvread(source/'actual320-country-four-indicators-original-2020-2024.csv');lookup={(r['countryISO3'],int(r['date']),r['indicatorID']):r for r in raw};country=[]\n for code in sorted({r['countryISO3']for r in raw}):\n  for year in range(2020,2025):\n   cols=['NY.GDP.PCAP.KD','NY.GDP.MKTP.KD.ZG','FP.CPI.TOTL.ZG','SP.DYN.LE00.IN'];v=[lookup[code,year,k]['originalValueToken']for k in cols];x=[None if not z else Q(z)for z in v[:3]];x[0]=None if x[0]is None else x[0]/10000;y=None if not v[3]else Q(v[3]);eligible=y is not None and None not in x;country.append(dict(id=code+':'+str(year),sourceRow=code+':'+str(year),originalID=code,year=year,x=x,y=y,weight='1',role='excluded'if not eligible else'outer-test'if year==2024 else'train'))\n person=[]\n for i,r in enumerate(csvread(source/'actual3613-NLS-original52-fields-and-selection.csv'),1):\n  v=lambda k:None if r[k]=='.'else Q(r[k]);x=[v('ed76'),v('age76')];y=None if v('wage76')is None else v('wage76')/100;eligible=y is not None and None not in x;person.append(dict(id='person:'+str(i),sourceRow=str(i),originalID=r['id'],x=x,y=y,weight='1',role='excluded'if not eligible else'outer-test'if i%5==0 else'train'))\n company=[]\n for i,r in enumerate(csvread(source/'actual3150-churn-original14-fields-and-selection.csv'),1):company.append(dict(id='customer:'+str(i),sourceRow=str(i),originalID='',x=[Q(r[k])for k in['Call  Failure','Subscription  Length','Charge  Amount']],y=r['Churn'],weight='1',role='outer-test'if i%5==0 else'train'))\n models={}\n for index,(kind,rr,task,leaf)in enumerate([('country',country,'regression',4),('person',person,'regression',50),('company',company,'classification',30)]):\n  ids=[r['id']for r in rr if r['role']=='train'];draws,schedules=fixed_schedules(ids,len(rr[0]['x']),20261102+7919*index);models[kind]=dict(records=rr,task=task,classes=['0','1']if task=='classification'else[],draws=draws,schedules=schedules,minLeaf=leaf)\n return models\n_OMITTED=object()\ndef realdata(models,kind,options=_OMITTED):\n options={}if options is _OMITTED else options\n if not isinstance(options,dict):raise ValueError('options object required, not explicit null')\n m=models[kind];train=[r for r in m['records']if r['role']=='train'];test=[r for r in m['records']if r['role']=='outer-test'];method=options.get('method','forest');depth=options.get('maxDepth',2);count=options.get('memberCount',3);a=dict(rows=train,queries=[dict(id=r['id'],x=r['x'])for r in test],task=m['task'],classes=m['classes'],maxDepth=depth,minLeaf=options.get('minLeaf',m['minLeaf']),minLeafWeight='0',minGain='0',missingRoute='best',learningRate=options.get('learningRate','1/2'),stages=options.get('stages',3))\n if method not in ['bagging','forest','boost']:raise ValueError('known source method')\n if not isinstance(depth,int)or isinstance(depth,bool)or not 0<=depth<=3:raise ValueError('source depth0..3')\n if method!='boost'and(not isinstance(count,int)or isinstance(count,bool)or not 1<=count<=4):raise ValueError('source member count1..4')\n if method=='boost':result=boost(a)\n else:\n  a.update(bootstrapDraws=m['draws'][:count],nodeFeatures=[{p:v for p,v in s.items()if len(p)<depth}for s in m['schedules'][:count]]);result=ensemble(a,method=='forest')\n outer=scored(result['predictions'],normalized(test,m['task']),m['task'],m['classes']);st=totals([r for r in normalized(train,m['task'])if r['w']and r['y']is not None],m['task'],m['classes']);constant=dict(prediction=st['pred'],probabilities=st['p'],vote=st['pred'],prob=st['pred']);baseline=scored([dict(id=r['id'],**constant)for r in test],normalized(test,m['task']),m['task'],m['classes']);return dict(kind=kind,method=method,settings=a,train=train,test=test,result=result,outer=outer,baseline=baseline)\ndef serial(x):\n if isinstance(x,Q):return str(x)\n if isinstance(x,dict):return{k:serial(v)for k,v in x.items()if k not in['inbag','tree']}\n if isinstance(x,(list,tuple)):return[serial(v)for v in x]\n return x\ndef writecsv(file,heads,rows):\n with Path(file).open('w',encoding='utf8',newline='')as f:\n  w=csv.writer(f);w.writerow(heads);w.writerows([[''if v is None else str(v)for v in r]for r in rows])\nAPI='boost'\nINPUT={'rows': [{'id': '0', 'x': [0], 'y': 0}, {'id': '1', 'x': [1], 'y': 0}, {'id': '2', 'x': [2], 'y': 4}, {'id': '3', 'x': [3], 'y': 4}], 'queries': [{'id': 'q', 'x': ['3/2']}], 'maxDepth': 1, 'learningRate': '1/2', 'stages': 2}\n\ndef run_fixed(api,a,out,src):\n import matplotlib\n matplotlib.use('svg')\n import matplotlib.pyplot as plt\n from matplotlib.ticker import MaxNLocator\n plt.rcParams.update({'font.size':14,'svg.fonttype':'none','svg.hashsalt':'ml09-fixed-v1'})\n result=variance(a)if api=='variance'else aggregate(a)if api=='aggregate'else ensemble(a,api=='forest')if api in ['bagging','forest']else boost(a)if api=='boost'else realdata(read_sources(src),a['kind'])\n out=Path(out);out.mkdir(parents=True,exist_ok=True);summary={};points=[]\n def add(x,y,s):\n  if y is not None:points.append([x,y,s])\n if api=='variance':\n  summary={'B':result['B'],'varianceOfMean':result['varianceOfMean']};add(result['B'],result['varianceOfMean'],'Specified finite-B variance');xl='Number of members B';yl='Variance, stipulated units squared';title='Declared covariance model, not fitted trees'\n elif api=='aggregate':\n  p=result['predictions'][0];classification=a.get('task')=='classification';summary={'selectedPrediction':p['prediction']}\n  if classification:\n   summary.update(voteLabel=p['vote'],probabilityLabel=p['prob'],meanProbability1=p['probabilities'][1]);add(1,p['probabilities'][1],'Mean probability of class 1');add(2,p['votes'][1],'Label-vote share of class 1');xl='Aggregation (1=probability, 2=vote)';yl='Probability or vote share'\n  else:\n   for i,m in enumerate(a['members']):add(i+1,Q(m['predictions'][0]['value']),'Member prediction')\n   add(3,p['prediction'],'Weighted mean');xl='Member 1, member 2, aggregate 3';yl='Prediction, assumed units'\n  title='Votes and probabilities are distinct objects'\n elif api in ['bagging','forest']:\n  summary={'queryPrediction':result['predictions'][0]['prediction'],'OOB.scoreable':result['outOfBag']['eligibleRows'],'OOB.meanLoss':result['outOfBag']['meanLoss']}\n  for i,r in enumerate(a['rows']):add(i+1,Q(r['y']),'Observed training outcome')\n  for i,p in enumerate(result['outOfBag']['rows']):add(i+1,p['prediction'],'OOB prediction, when defined')\n  xl='Original training ID order';yl='Outcome, assumed units';title='Repeated draws and ID-level OOB membership'\n elif api=='boost':\n  summary={'initial':result['initial'],'finalMSE':result['losses'][-1]['MSE'],'stages':result['stages']}\n  for r in result['losses']:add(r['stage'],r['MSE'],'Training MSE')\n  xl='Boosting stage (0=initial)';yl='Weighted MSE, outcome units squared';title='Training descent does not certify held-out gain'\n else:\n  summary={'outer.scoreable':result['outer']['eligibleRows'],'outer.meanLoss':result['outer']['meanLoss'],'baseline.meanLoss':result['baseline']['meanLoss'],'OOB.scoreable':result['result']['outOfBag']['eligibleRows'],'OOB.meanLoss':result['result']['outOfBag']['meanLoss']}\n  for i,p in enumerate(result['outer']['rows']):\n   add(i+1,Q(p['actual']),'Observed outcome');add(i+1,p['probabilities'][1]if a['kind']=='company'else p['prediction'],'Forest probability of class 1'if a['kind']=='company'else'Forest prediction')\n  xl='Outer-test source order, not a time path';yl='Churn label / probability'if a['kind']=='company'else'Period life expectancy, years'if a['kind']=='country'else'Nominal 1976 USD per hour';title='Fixed forest; outer labels did not fit the trees'\n def display(v):return 'undefined'if v is None else format(float(v),'.9f')\n writecsv(out/'summary.csv',['metric','value'],[[k,display(v)]for k,v in summary.items()]);writecsv(out/'plot-points.csv',['x','y','series'],points);(out/'full.json').write_text(json.dumps(serial(result),indent=2)+'\\n',encoding='utf8')\n fig,ax=plt.subplots(figsize=(5.6,4.6));fig.subplots_adjust(left=.24,right=.96,bottom=.24,top=.76);colors=['#355c72','#a55336','#507956','#78568b']\n for i,s in enumerate(dict.fromkeys(p[2]for p in points)):\n  pp=[p for p in points if p[2]==s];ax.scatter([float(p[0])for p in pp],[float(p[1])for p in pp],s=12 if len(pp)>100 else 32,alpha=.5 if len(pp)>100 else 1,color=colors[i%4],label=s)\n ax.set_xlabel(xl,labelpad=10,fontsize=11);ax.set_ylabel(yl,labelpad=10,fontsize=11);ax.xaxis.set_major_locator(MaxNLocator(3));ax.yaxis.set_major_locator(MaxNLocator(4));ax.grid(alpha=.18);ax.legend(loc='lower left',bbox_to_anchor=(0,1.01),fontsize=9,frameon=False);fig.suptitle(title,fontsize=9,y=.99);fig.savefig(out/'plot.svg',metadata={'Date':None});plt.close(fig);print(', '.join(k+'='+display(v)for k,v in summary.items()))\nif __name__=='__main__':\n import sys\n try:run_fixed(API,INPUT,sys.argv[1]if len(sys.argv)>1 else'fixed-results',sys.argv[2]if len(sys.argv)>2 else'ml09-sources')\n except ValueError as error:print('Rejected declared input: '+str(error),file=sys.stderr);sys.exit(2)\n",
        "code": "\"\"\"ML09 exact Fraction reproduction from native source fields.\n\npython ml09-public-analysis.py --source-dir ml09-sources --output-dir results\n\nThis authored educational implementation uses direct-centered leaf losses and\nexhaustive midpoint partitions. It reads no JS engine, model contract, checker,\nstored target answers or derived-result CSV. Its five tree arithmetic helpers\nwere copied from the author's own separate Fraction reference, not an independent\npeer. Parser/work budgets and display rounding of the production JS are separate.\nNumerical predictions/proper scores do not certify causal effects, calibration,\nIID OOB validity, survey representativeness or production parameter optimality.\n\"\"\"\nfrom pathlib import Path\nfrom fractions import Fraction as Q\nimport csv,json,math,itertools,argparse\n\ndef normalized(rows,task='regression'):\n return [dict(id=r.get('id',i),x=[None if x is None else Q(x)for x in r.get('x',[])],y=None if r['y']is None else str(r['y'])if task=='classification'else Q(r['y']),w=Q(r.get('weight',1)))for i,r in enumerate(rows)]\n\ndef totals(rows,task,classes):\n W=sum((r['w']for r in rows),Q());mu=sum((r['w']*r['y']for r in rows),Q())/W if task=='regression'and W else None\n probs=[sum((r['w']for r in rows if r['y']==c),Q())/W for c in classes]if task=='classification'and W else[]\n risk=sum((r['w']*(r['y']-mu)**2 for r in rows),Q())if task=='regression'and W else W*sum((p*(1-p)for p in probs),Q())\n return dict(n=len(rows),w=W,mu=mu,p=probs,risk=risk,pred=mu if task=='regression'else classes[max(range(len(probs)),key=lambda i:probs[i])]if probs else None)\n\ndef fit(rows,a,task,classes,schedule=None):\n good=[r for r in rows if r['w']>0 and r['y']is not None];root=totals(good,task,classes)['w'];depth=a.get('maxDepth',2);minimum=a.get('minLeaf',1);minmass=Q(a.get('minLeafWeight',0));mingain=Q(a.get('minGain',0));route=a.get('missingRoute','best')\n def build(rr,d,path):\n  st=totals(rr,task,classes);n=dict(rows=rr,st=st,split=None,left=None,right=None,path=path)\n  if d==depth:return n\n  best=None\n  for j in range(len(rr[0]['x'])):\n   if schedule is not None and j not in schedule[path]:continue\n   values=sorted({r['x'][j]for r in rr if r['x'][j]is not None});missing=[r for r in rr if r['x'][j]is None];observed=[r for r in rr if r['x'][j]is not None]\n   candidates=[]\n   for lo,hi in zip(values,values[1:]):\n    q=(lo+hi)/2;left=[r for r in observed if r['x'][j]<=q];right=[r for r in observed if r['x'][j]>q];directions=[route]if route!='best'else['left','right']if missing else['left'if len(left)>=len(right)else'right']\n    for direction in directions:candidates.append(('threshold',q,direction,left+missing if direction=='left'else left,right+missing if direction=='right'else right))\n   if missing and observed:candidates.append(('missing-only',None,'left',missing,observed))\n   for kind,q,direction,left,right in candidates:\n    l=totals(left,task,classes);r=totals(right,task,classes)\n    if min(l['n'],r['n'])<minimum or min(l['w'],r['w'])<minmass or min(l['w'],r['w'])<=0:continue\n    gain=(st['risk']-l['risk']-r['risk'])/root\n    if best is None or gain>best['gain']:best=dict(feature=j,kind=kind,threshold=q,missingRoute=direction,left=left,right=right,gain=gain)\n  if best and best['gain']>0 and best['gain']>mingain:\n   j=best['feature'];go=lambda r:r['x'][j]is None if best['kind']=='missing-only'else best['missingRoute']=='left'if r['x'][j]is None else r['x'][j]<=best['threshold'];n['split']=best;n['left']=build([r for r in rr if go(r)],d+1,path+'L');n['right']=build([r for r in rr if not go(r)],d+1,path+'R')\n  return n\n return build(good,0,'')\n\ndef predict(tree,x):\n n=tree\n while n['split']:\n  s=n['split'];v=x[s['feature']];left=v is None if s['kind']=='missing-only'else s['missingRoute']=='left'if v is None else v<=s['threshold'];n=n['left'if left else'right']\n return dict(prediction=n['st']['pred'],probabilities=n['st']['p'])\n\ndef combine(preds,w,task,classes,mode='probabilities'):\n mass=sum(w,Q())\n if not preds or not mass:return dict(prediction=None,probabilities=[],vote=None,prob=None)\n if task=='regression':return dict(prediction=sum((p['prediction']*v for p,v in zip(preds,w)),Q())/mass,probabilities=[],vote=None,prob=None)\n votes=[sum((v for p,v in zip(preds,w)if p['prediction']==c),Q())/mass for c in classes];ps=[sum((p['probabilities'][j]*v for p,v in zip(preds,w)),Q())/mass for j in range(len(classes))];vote=classes[max(range(len(classes)),key=lambda j:votes[j])];prob=classes[max(range(len(classes)),key=lambda j:ps[j])];return dict(prediction=vote if mode=='votes'else prob,probabilities=ps,vote=vote,prob=prob,votes=votes)\ndef number(v):\n if v is None or isinstance(v,bool):raise ValueError('explicit null/bool is not a numeric parameter')\n return Q(v)\ndef variance(a):\n B=a['B'];v=number(a['marginalVariance']);rho=number(a.get('rho',0))\n if not isinstance(B,int)or isinstance(B,bool)or B<1 or v<0:raise ValueError('positive integer B/nonnegative variance')\n if B>1 and v and not -Q(1,B-1)<=rho<=1:raise ValueError('equicorrelation PSD bound')\n return dict(B=B,marginalVariance=v,correlationApplicable=B>1 and bool(v),varianceOfMean=v if B==1 else v*(1+(B-1)*rho)/B)\ndef aggregate(a):\n task=a.get('task','regression');classes=[str(c)for c in a.get('classes',[])];members=a['members'];w=[number(v)for v in a.get('memberWeights',[1]*len(members))]\n if not members or min(w)<0 or sum(w)<=0:raise ValueError('nonnegative member weights/positive total')\n order=[p.get('id',i)for i,p in enumerate(members[0]['predictions'])];keys=lambda x:(type(x).__name__,x);lookup=[{keys(p.get('id',i)):p for i,p in enumerate(m['predictions'])}for m in members]\n if any(set(m)!={keys(v)for v in order}for m in lookup):raise ValueError('same query ID set')\n out=[]\n for pid in order:\n  predictions=[dict(prediction=number(m[keys(pid)]['value']),probabilities=[])if task=='regression'else dict(prediction=str(m[keys(pid)]['label']),probabilities=[number(v)for v in m[keys(pid)]['probabilities']])for m in lookup]\n  if task=='classification'and any(min(p['probabilities'])<0 or sum(p['probabilities'])!=1 for p in predictions):raise ValueError('probability simplex')\n  out.append(dict(id=pid,**combine(predictions,w,task,classes,a.get('aggregation','probabilities'))))\n return dict(task=task,classes=classes,predictions=out)\ndef scored(preds,rows,task,classes):\n mass=loss=absolute=errors=voteerrors=Q();out=[]\n for p,r in zip(preds,rows):\n  ok=p['prediction']is not None and r['y']is not None and r['w']>0;v=None\n  if ok:\n   mass+=r['w']\n   if task=='regression':e=r['y']-p['prediction'];v=e*e;absolute+=r['w']*abs(e)\n   else:v=sum(((q-(1 if r['y']==c else 0))**2 for c,q in zip(classes,p['probabilities'])),Q());errors+=r['w']*(p['prediction']!=r['y']);voteerrors+=r['w']*(p['vote']!=r['y'])\n   loss+=r['w']*v\n  out.append(dict(p,actual=r['y'],weight=r['w'],scoreEligible=ok,loss=v))\n return dict(rows=out,eligibleRows=sum(r['scoreEligible']for r in out),weight=mass,totalLoss=loss,meanLoss=loss/mass if mass else None,MAE=absolute/mass if mass and task=='regression'else None,errorRate=errors/mass if mass and task=='classification'else None,labelVoteErrorRate=voteerrors/mass if mass and task=='classification'else None)\ndef ensemble(a,forest=False):\n task=a.get('task','regression');classes=[str(v)for v in(a.get('classes')or[])];rr=normalized(a['rows'],task);key=lambda x:(type(x).__name__,x);lookup={key(r['id']):r for r in rr};weights=[number(v)for v in a.get('memberWeights',[1]*len(a['bootstrapDraws']))]\n if not any(r['w']>0 and r['y']is not None for r in rr)or min(weights)<0 or sum(weights)<=0:raise ValueError('positive eligible training and member weight')\n members=[]\n for i,draw in enumerate(a['bootstrapDraws']):\n  data=[lookup[key(v)]for v in draw];schedule=a['nodeFeatures'][i]if forest else None;model=fit(data,a,task,classes,schedule);inbag={key(v)for v in draw};members.append(dict(tree=model,draw=draw,inbag=inbag,weight=weights[i]))\n predictions=[]\n for q in a.get('queries',[]):predictions.append(dict(id=q['id'],**combine([predict(m['tree'],[None if v is None else number(v)for v in q['x']])for m in members],weights,task,classes,a.get('aggregation','probabilities'))))\n oob=[]\n for r in rr:\n  applicable=[i for i,m in enumerate(members)if key(r['id'])not in m['inbag']];p=combine([predict(members[i]['tree'],r['x'])for i in applicable],[weights[i]for i in applicable],task,classes,a.get('aggregation','probabilities'));oob.append(dict(id=r['id'],applicable=applicable,positiveMembers=sum(weights[i]>0 for i in applicable),**p))\n return dict(task=task,classes=classes,members=members,predictions=predictions,outOfBag=scored(oob,rr,task,classes))\ndef boost(a):\n if a.get('task','regression')!='regression':raise ValueError('regression boosting only')\n rr=normalized(a['rows']);good=[r for r in rr if r['w']and r['y']is not None];W=sum((r['w']for r in good),Q())\n if not W:raise ValueError('positive eligible training')\n eta=number(a.get('learningRate','1/2'));stages=a.get('stages',3)\n if not 0<=eta<=1 or not isinstance(stages,int)or isinstance(stages,bool)or not 0<=stages<=8:raise ValueError('supported rate/stages')\n initial=number(a['initial'])if'initial'in a else sum((r['w']*r['y']for r in good),Q())/W;training=[[initial]for r in rr];queries=[[initial]for q in a.get('queries',[])];fits=[];losses=[]\n for stage in range(stages+1):\n  sse=sum((r['w']*(r['y']-p[-1])**2 for r,p in zip(rr,training)if r['w']and r['y']is not None),Q());losses.append(dict(stage=stage,rawWeightedSSE=sse,MSE=sse/W,meanHalfSquaredLoss=sse/(2*W)))\n  if stage==stages:break\n  residuals=[dict(r,y=None if r['y']is None else r['y']-p[-1])for r,p in zip(rr,training)];tree=fit(residuals,a,'regression',[]);h=[predict(tree,r['x'])['prediction']for r in rr];qh=[predict(tree,[None if v is None else number(v)for v in q['x']])['prediction']for q in a.get('queries',[])];norm=sum((r['w']*v*v for r,v in zip(rr,h)if r['y']is not None),Q());stageRows=[]\n  for i,(r,p)in enumerate(zip(rr,training)):\n   residual=None if r['y']is None else r['y']-p[-1];stageRows.append(dict(id=r['id'],before=p[-1],residual=residual,negativeCoordinateDerivative=None if residual is None else r['w']*residual/W,fit=h[i],addition=eta*h[i],after=p[-1]+eta*h[i]));p.append(p[-1]+eta*h[i])\n  for p,v in zip(queries,qh):p.append(p[-1]+eta*v)\n  fits.append(dict(stage=stage+1,tree=tree,rows=stageRows,queryFits=qh,norm=norm,predictedSSEDecrease=eta*(2-eta)*norm))\n return dict(task='regression',initial=initial,learningRate=eta,stages=stages,training=training,queries=queries,fits=fits,losses=losses,predictions=[dict(id=q['id'],prediction=p[-1],probabilities=[],vote=None,prob=None)for q,p in zip(a.get('queries',[]),queries)])\nclass Stream:\n def __init__(self,state):self.state=state\n def choose(self,n):\n  limit=(1<<32)-((1<<32)%n)\n  while True:\n   self.state=(1664525*self.state+1013904223)&0xffffffff\n   if self.state<limit:return self.state%n\ndef fixed_schedules(ids,p,seed):\n stream=Stream(seed);draws=[];schedules=[];paths=['']+[p for d in[1,2]for p in map(''.join,itertools.product('LR',repeat=d))]\n for member in range(4):\n  draws.append([ids[stream.choose(len(ids))]for _ in range(len(ids))]);schedule={}\n  for path in paths:\n   order=list(range(p))\n   for j in range(p-1,0,-1):k=stream.choose(j+1);order[j],order[k]=order[k],order[j]\n   schedule[path]=sorted(order[:max(1,int(math.sqrt(p)))])\n  schedules.append(schedule)\n return draws,schedules\ndef csvread(file):\n with Path(file).open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))\ndef read_sources(source):\n source=Path(source);raw=csvread(source/'actual320-country-four-indicators-original-2020-2024.csv');lookup={(r['countryISO3'],int(r['date']),r['indicatorID']):r for r in raw};country=[]\n for code in sorted({r['countryISO3']for r in raw}):\n  for year in range(2020,2025):\n   cols=['NY.GDP.PCAP.KD','NY.GDP.MKTP.KD.ZG','FP.CPI.TOTL.ZG','SP.DYN.LE00.IN'];v=[lookup[code,year,k]['originalValueToken']for k in cols];x=[None if not z else Q(z)for z in v[:3]];x[0]=None if x[0]is None else x[0]/10000;y=None if not v[3]else Q(v[3]);eligible=y is not None and None not in x;country.append(dict(id=code+':'+str(year),sourceRow=code+':'+str(year),originalID=code,year=year,x=x,y=y,weight='1',role='excluded'if not eligible else'outer-test'if year==2024 else'train'))\n person=[]\n for i,r in enumerate(csvread(source/'actual3613-NLS-original52-fields-and-selection.csv'),1):\n  v=lambda k:None if r[k]=='.'else Q(r[k]);x=[v('ed76'),v('age76')];y=None if v('wage76')is None else v('wage76')/100;eligible=y is not None and None not in x;person.append(dict(id='person:'+str(i),sourceRow=str(i),originalID=r['id'],x=x,y=y,weight='1',role='excluded'if not eligible else'outer-test'if i%5==0 else'train'))\n company=[]\n for i,r in enumerate(csvread(source/'actual3150-churn-original14-fields-and-selection.csv'),1):company.append(dict(id='customer:'+str(i),sourceRow=str(i),originalID='',x=[Q(r[k])for k in['Call  Failure','Subscription  Length','Charge  Amount']],y=r['Churn'],weight='1',role='outer-test'if i%5==0 else'train'))\n models={}\n for index,(kind,rr,task,leaf)in enumerate([('country',country,'regression',4),('person',person,'regression',50),('company',company,'classification',30)]):\n  ids=[r['id']for r in rr if r['role']=='train'];draws,schedules=fixed_schedules(ids,len(rr[0]['x']),20261102+7919*index);models[kind]=dict(records=rr,task=task,classes=['0','1']if task=='classification'else[],draws=draws,schedules=schedules,minLeaf=leaf)\n return models\n_OMITTED=object()\ndef realdata(models,kind,options=_OMITTED):\n options={}if options is _OMITTED else options\n if not isinstance(options,dict):raise ValueError('options object required, not explicit null')\n m=models[kind];train=[r for r in m['records']if r['role']=='train'];test=[r for r in m['records']if r['role']=='outer-test'];method=options.get('method','forest');depth=options.get('maxDepth',2);count=options.get('memberCount',3);a=dict(rows=train,queries=[dict(id=r['id'],x=r['x'])for r in test],task=m['task'],classes=m['classes'],maxDepth=depth,minLeaf=options.get('minLeaf',m['minLeaf']),minLeafWeight='0',minGain='0',missingRoute='best',learningRate=options.get('learningRate','1/2'),stages=options.get('stages',3))\n if method not in ['bagging','forest','boost']:raise ValueError('known source method')\n if not isinstance(depth,int)or isinstance(depth,bool)or not 0<=depth<=3:raise ValueError('source depth0..3')\n if method!='boost'and(not isinstance(count,int)or isinstance(count,bool)or not 1<=count<=4):raise ValueError('source member count1..4')\n if method=='boost':result=boost(a)\n else:\n  a.update(bootstrapDraws=m['draws'][:count],nodeFeatures=[{p:v for p,v in s.items()if len(p)<depth}for s in m['schedules'][:count]]);result=ensemble(a,method=='forest')\n outer=scored(result['predictions'],normalized(test,m['task']),m['task'],m['classes']);st=totals([r for r in normalized(train,m['task'])if r['w']and r['y']is not None],m['task'],m['classes']);constant=dict(prediction=st['pred'],probabilities=st['p'],vote=st['pred'],prob=st['pred']);baseline=scored([dict(id=r['id'],**constant)for r in test],normalized(test,m['task']),m['task'],m['classes']);return dict(kind=kind,method=method,settings=a,train=train,test=test,result=result,outer=outer,baseline=baseline)\ndef serial(x):\n if isinstance(x,Q):return str(x)\n if isinstance(x,dict):return{k:serial(v)for k,v in x.items()if k not in['inbag','tree']}\n if isinstance(x,(list,tuple)):return[serial(v)for v in x]\n return x\ndef writecsv(file,heads,rows):\n with Path(file).open('w',encoding='utf8',newline='')as f:\n  w=csv.writer(f);w.writerow(heads);w.writerows([[''if v is None else str(v)for v in r]for r in rows])\nAPI='boost'\nINPUT={'rows': [{'id': '0', 'x': [0], 'y': 0}, {'id': '1', 'x': [1], 'y': 0}, {'id': '2', 'x': [2], 'y': 4}, {'id': '3', 'x': [3], 'y': 4}], 'queries': [{'id': 'q', 'x': ['3/2']}], 'maxDepth': 1, 'learningRate': '1/2', 'stages': 2}\n\ndef run_fixed(api,a,out,src):\n import matplotlib\n matplotlib.use('svg')\n import matplotlib.pyplot as plt\n from matplotlib.ticker import MaxNLocator\n plt.rcParams.update({'font.size':14,'svg.fonttype':'none','svg.hashsalt':'ml09-fixed-v1'})\n result=variance(a)if api=='variance'else aggregate(a)if api=='aggregate'else ensemble(a,api=='forest')if api in ['bagging','forest']else boost(a)if api=='boost'else realdata(read_sources(src),a['kind'])\n out=Path(out);out.mkdir(parents=True,exist_ok=True);summary={};points=[]\n def add(x,y,s):\n  if y is not None:points.append([x,y,s])\n if api=='variance':\n  summary={'B':result['B'],'varianceOfMean':result['varianceOfMean']};add(result['B'],result['varianceOfMean'],'Specified finite-B variance');xl='Number of members B';yl='Variance, stipulated units squared';title='Declared covariance model, not fitted trees'\n elif api=='aggregate':\n  p=result['predictions'][0];classification=a.get('task')=='classification';summary={'selectedPrediction':p['prediction']}\n  if classification:\n   summary.update(voteLabel=p['vote'],probabilityLabel=p['prob'],meanProbability1=p['probabilities'][1]);add(1,p['probabilities'][1],'Mean probability of class 1');add(2,p['votes'][1],'Label-vote share of class 1');xl='Aggregation (1=probability, 2=vote)';yl='Probability or vote share'\n  else:\n   for i,m in enumerate(a['members']):add(i+1,Q(m['predictions'][0]['value']),'Member prediction')\n   add(3,p['prediction'],'Weighted mean');xl='Member 1, member 2, aggregate 3';yl='Prediction, assumed units'\n  title='Votes and probabilities are distinct objects'\n elif api in ['bagging','forest']:\n  summary={'queryPrediction':result['predictions'][0]['prediction'],'OOB.scoreable':result['outOfBag']['eligibleRows'],'OOB.meanLoss':result['outOfBag']['meanLoss']}\n  for i,r in enumerate(a['rows']):add(i+1,Q(r['y']),'Observed training outcome')\n  for i,p in enumerate(result['outOfBag']['rows']):add(i+1,p['prediction'],'OOB prediction, when defined')\n  xl='Original training ID order';yl='Outcome, assumed units';title='Repeated draws and ID-level OOB membership'\n elif api=='boost':\n  summary={'initial':result['initial'],'finalMSE':result['losses'][-1]['MSE'],'stages':result['stages']}\n  for r in result['losses']:add(r['stage'],r['MSE'],'Training MSE')\n  xl='Boosting stage (0=initial)';yl='Weighted MSE, outcome units squared';title='Training descent does not certify held-out gain'\n else:\n  summary={'outer.scoreable':result['outer']['eligibleRows'],'outer.meanLoss':result['outer']['meanLoss'],'baseline.meanLoss':result['baseline']['meanLoss'],'OOB.scoreable':result['result']['outOfBag']['eligibleRows'],'OOB.meanLoss':result['result']['outOfBag']['meanLoss']}\n  for i,p in enumerate(result['outer']['rows']):\n   add(i+1,Q(p['actual']),'Observed outcome');add(i+1,p['probabilities'][1]if a['kind']=='company'else p['prediction'],'Forest probability of class 1'if a['kind']=='company'else'Forest prediction')\n  xl='Outer-test source order, not a time path';yl='Churn label / probability'if a['kind']=='company'else'Period life expectancy, years'if a['kind']=='country'else'Nominal 1976 USD per hour';title='Fixed forest; outer labels did not fit the trees'\n def display(v):return 'undefined'if v is None else format(float(v),'.9f')\n writecsv(out/'summary.csv',['metric','value'],[[k,display(v)]for k,v in summary.items()]);writecsv(out/'plot-points.csv',['x','y','series'],points);(out/'full.json').write_text(json.dumps(serial(result),indent=2)+'\\n',encoding='utf8')\n fig,ax=plt.subplots(figsize=(5.6,4.6));fig.subplots_adjust(left=.24,right=.96,bottom=.24,top=.76);colors=['#355c72','#a55336','#507956','#78568b']\n for i,s in enumerate(dict.fromkeys(p[2]for p in points)):\n  pp=[p for p in points if p[2]==s];ax.scatter([float(p[0])for p in pp],[float(p[1])for p in pp],s=12 if len(pp)>100 else 32,alpha=.5 if len(pp)>100 else 1,color=colors[i%4],label=s)\n ax.set_xlabel(xl,labelpad=10,fontsize=11);ax.set_ylabel(yl,labelpad=10,fontsize=11);ax.xaxis.set_major_locator(MaxNLocator(3));ax.yaxis.set_major_locator(MaxNLocator(4));ax.grid(alpha=.18);ax.legend(loc='lower left',bbox_to_anchor=(0,1.01),fontsize=9,frameon=False);fig.suptitle(title,fontsize=9,y=.99);fig.savefig(out/'plot.svg',metadata={'Date':None});plt.close(fig);print(', '.join(k+'='+display(v)for k,v in summary.items()))\nif __name__=='__main__':\n import sys\n try:run_fixed(API,INPUT,sys.argv[1]if len(sys.argv)>1 else'fixed-results',sys.argv[2]if len(sys.argv)>2 else'ml09-sources')\n except ValueError as error:print('Rejected declared input: '+str(error),file=sys.stderr);sys.exit(2)\n",
        "inputFiles": [],
        "input": {
          "rows": [
            {
              "id": "0",
              "x": [
                0
              ],
              "y": 0
            },
            {
              "id": "1",
              "x": [
                1
              ],
              "y": 0
            },
            {
              "id": "2",
              "x": [
                2
              ],
              "y": 4
            },
            {
              "id": "3",
              "x": [
                3
              ],
              "y": 4
            }
          ],
          "queries": [
            {
              "id": "q",
              "x": [
                "3/2"
              ]
            }
          ],
          "maxDepth": 1,
          "learningRate": "1/2",
          "stages": 2
        },
        "returnCode": 0,
        "expectedFailure": false,
        "stdout": "initial=2.000000000, finalMSE=0.250000000, stages=2.000000000\n",
        "stderr": "",
        "summary": {
          "initial": "2.000000000",
          "finalMSE": "0.250000000",
          "stages": "2.000000000"
        },
        "plotPoints": [
          {
            "x": "0",
            "y": "4",
            "series": "Training MSE"
          },
          {
            "x": "1",
            "y": "1",
            "series": "Training MSE"
          },
          {
            "x": "2",
            "y": "1/4",
            "series": "Training MSE"
          }
        ],
        "plotFile": "ml09-fixed-results/boost-two-stages-python/plot.svg",
        "plotSHA256": "d000ea66c17f0940133b57eb1065b9e6b98718ebf002f8abc007b1fe7ee7454c",
        "files": [
          {
            "file": "ml09-fixed-results/boost-two-stages-python/full.json",
            "sha256": "3544bdbf5fd51e68ece082411d6ae1f621dd6073a097d17f9345ff685694609e"
          },
          {
            "file": "ml09-fixed-results/boost-two-stages-python/plot-points.csv",
            "sha256": "b05315a5a2e6d87b5ea1d86c0944dd8346a7722c12f7bcb8bc177ca61ad35669"
          },
          {
            "file": "ml09-fixed-results/boost-two-stages-python/plot.svg",
            "sha256": "d000ea66c17f0940133b57eb1065b9e6b98718ebf002f8abc007b1fe7ee7454c"
          },
          {
            "file": "ml09-fixed-results/boost-two-stages-python/summary.csv",
            "sha256": "75bafbdd34306b7bd852e4395062c41a460a8f542426d878bcf852e3329988a5"
          }
        ],
        "scope": "Actually executed self-contained fixed example; current web controls execute separately. Python Fraction and finite-precision base R. Author gate, not independent peer."
      },
      "weighted-gradient": {
        "api": "boost",
        "variant": "weighted-gradient",
        "language": "python",
        "codeFile": "ml09-code/boost-weighted-gradient.py",
        "codeSHA256": "b752e972e8d3f0151f804d6dcc8b4a0f63178be0290fc3c81864070b998ecf06",
        "codeText": "\"\"\"ML09 exact Fraction reproduction from native source fields.\n\npython ml09-public-analysis.py --source-dir ml09-sources --output-dir results\n\nThis authored educational implementation uses direct-centered leaf losses and\nexhaustive midpoint partitions. It reads no JS engine, model contract, checker,\nstored target answers or derived-result CSV. Its five tree arithmetic helpers\nwere copied from the author's own separate Fraction reference, not an independent\npeer. Parser/work budgets and display rounding of the production JS are separate.\nNumerical predictions/proper scores do not certify causal effects, calibration,\nIID OOB validity, survey representativeness or production parameter optimality.\n\"\"\"\nfrom pathlib import Path\nfrom fractions import Fraction as Q\nimport csv,json,math,itertools,argparse\n\ndef normalized(rows,task='regression'):\n return [dict(id=r.get('id',i),x=[None if x is None else Q(x)for x in r.get('x',[])],y=None if r['y']is None else str(r['y'])if task=='classification'else Q(r['y']),w=Q(r.get('weight',1)))for i,r in enumerate(rows)]\n\ndef totals(rows,task,classes):\n W=sum((r['w']for r in rows),Q());mu=sum((r['w']*r['y']for r in rows),Q())/W if task=='regression'and W else None\n probs=[sum((r['w']for r in rows if r['y']==c),Q())/W for c in classes]if task=='classification'and W else[]\n risk=sum((r['w']*(r['y']-mu)**2 for r in rows),Q())if task=='regression'and W else W*sum((p*(1-p)for p in probs),Q())\n return dict(n=len(rows),w=W,mu=mu,p=probs,risk=risk,pred=mu if task=='regression'else classes[max(range(len(probs)),key=lambda i:probs[i])]if probs else None)\n\ndef fit(rows,a,task,classes,schedule=None):\n good=[r for r in rows if r['w']>0 and r['y']is not None];root=totals(good,task,classes)['w'];depth=a.get('maxDepth',2);minimum=a.get('minLeaf',1);minmass=Q(a.get('minLeafWeight',0));mingain=Q(a.get('minGain',0));route=a.get('missingRoute','best')\n def build(rr,d,path):\n  st=totals(rr,task,classes);n=dict(rows=rr,st=st,split=None,left=None,right=None,path=path)\n  if d==depth:return n\n  best=None\n  for j in range(len(rr[0]['x'])):\n   if schedule is not None and j not in schedule[path]:continue\n   values=sorted({r['x'][j]for r in rr if r['x'][j]is not None});missing=[r for r in rr if r['x'][j]is None];observed=[r for r in rr if r['x'][j]is not None]\n   candidates=[]\n   for lo,hi in zip(values,values[1:]):\n    q=(lo+hi)/2;left=[r for r in observed if r['x'][j]<=q];right=[r for r in observed if r['x'][j]>q];directions=[route]if route!='best'else['left','right']if missing else['left'if len(left)>=len(right)else'right']\n    for direction in directions:candidates.append(('threshold',q,direction,left+missing if direction=='left'else left,right+missing if direction=='right'else right))\n   if missing and observed:candidates.append(('missing-only',None,'left',missing,observed))\n   for kind,q,direction,left,right in candidates:\n    l=totals(left,task,classes);r=totals(right,task,classes)\n    if min(l['n'],r['n'])<minimum or min(l['w'],r['w'])<minmass or min(l['w'],r['w'])<=0:continue\n    gain=(st['risk']-l['risk']-r['risk'])/root\n    if best is None or gain>best['gain']:best=dict(feature=j,kind=kind,threshold=q,missingRoute=direction,left=left,right=right,gain=gain)\n  if best and best['gain']>0 and best['gain']>mingain:\n   j=best['feature'];go=lambda r:r['x'][j]is None if best['kind']=='missing-only'else best['missingRoute']=='left'if r['x'][j]is None else r['x'][j]<=best['threshold'];n['split']=best;n['left']=build([r for r in rr if go(r)],d+1,path+'L');n['right']=build([r for r in rr if not go(r)],d+1,path+'R')\n  return n\n return build(good,0,'')\n\ndef predict(tree,x):\n n=tree\n while n['split']:\n  s=n['split'];v=x[s['feature']];left=v is None if s['kind']=='missing-only'else s['missingRoute']=='left'if v is None else v<=s['threshold'];n=n['left'if left else'right']\n return dict(prediction=n['st']['pred'],probabilities=n['st']['p'])\n\ndef combine(preds,w,task,classes,mode='probabilities'):\n mass=sum(w,Q())\n if not preds or not mass:return dict(prediction=None,probabilities=[],vote=None,prob=None)\n if task=='regression':return dict(prediction=sum((p['prediction']*v for p,v in zip(preds,w)),Q())/mass,probabilities=[],vote=None,prob=None)\n votes=[sum((v for p,v in zip(preds,w)if p['prediction']==c),Q())/mass for c in classes];ps=[sum((p['probabilities'][j]*v for p,v in zip(preds,w)),Q())/mass for j in range(len(classes))];vote=classes[max(range(len(classes)),key=lambda j:votes[j])];prob=classes[max(range(len(classes)),key=lambda j:ps[j])];return dict(prediction=vote if mode=='votes'else prob,probabilities=ps,vote=vote,prob=prob,votes=votes)\ndef number(v):\n if v is None or isinstance(v,bool):raise ValueError('explicit null/bool is not a numeric parameter')\n return Q(v)\ndef variance(a):\n B=a['B'];v=number(a['marginalVariance']);rho=number(a.get('rho',0))\n if not isinstance(B,int)or isinstance(B,bool)or B<1 or v<0:raise ValueError('positive integer B/nonnegative variance')\n if B>1 and v and not -Q(1,B-1)<=rho<=1:raise ValueError('equicorrelation PSD bound')\n return dict(B=B,marginalVariance=v,correlationApplicable=B>1 and bool(v),varianceOfMean=v if B==1 else v*(1+(B-1)*rho)/B)\ndef aggregate(a):\n task=a.get('task','regression');classes=[str(c)for c in a.get('classes',[])];members=a['members'];w=[number(v)for v in a.get('memberWeights',[1]*len(members))]\n if not members or min(w)<0 or sum(w)<=0:raise ValueError('nonnegative member weights/positive total')\n order=[p.get('id',i)for i,p in enumerate(members[0]['predictions'])];keys=lambda x:(type(x).__name__,x);lookup=[{keys(p.get('id',i)):p for i,p in enumerate(m['predictions'])}for m in members]\n if any(set(m)!={keys(v)for v in order}for m in lookup):raise ValueError('same query ID set')\n out=[]\n for pid in order:\n  predictions=[dict(prediction=number(m[keys(pid)]['value']),probabilities=[])if task=='regression'else dict(prediction=str(m[keys(pid)]['label']),probabilities=[number(v)for v in m[keys(pid)]['probabilities']])for m in lookup]\n  if task=='classification'and any(min(p['probabilities'])<0 or sum(p['probabilities'])!=1 for p in predictions):raise ValueError('probability simplex')\n  out.append(dict(id=pid,**combine(predictions,w,task,classes,a.get('aggregation','probabilities'))))\n return dict(task=task,classes=classes,predictions=out)\ndef scored(preds,rows,task,classes):\n mass=loss=absolute=errors=voteerrors=Q();out=[]\n for p,r in zip(preds,rows):\n  ok=p['prediction']is not None and r['y']is not None and r['w']>0;v=None\n  if ok:\n   mass+=r['w']\n   if task=='regression':e=r['y']-p['prediction'];v=e*e;absolute+=r['w']*abs(e)\n   else:v=sum(((q-(1 if r['y']==c else 0))**2 for c,q in zip(classes,p['probabilities'])),Q());errors+=r['w']*(p['prediction']!=r['y']);voteerrors+=r['w']*(p['vote']!=r['y'])\n   loss+=r['w']*v\n  out.append(dict(p,actual=r['y'],weight=r['w'],scoreEligible=ok,loss=v))\n return dict(rows=out,eligibleRows=sum(r['scoreEligible']for r in out),weight=mass,totalLoss=loss,meanLoss=loss/mass if mass else None,MAE=absolute/mass if mass and task=='regression'else None,errorRate=errors/mass if mass and task=='classification'else None,labelVoteErrorRate=voteerrors/mass if mass and task=='classification'else None)\ndef ensemble(a,forest=False):\n task=a.get('task','regression');classes=[str(v)for v in(a.get('classes')or[])];rr=normalized(a['rows'],task);key=lambda x:(type(x).__name__,x);lookup={key(r['id']):r for r in rr};weights=[number(v)for v in a.get('memberWeights',[1]*len(a['bootstrapDraws']))]\n if not any(r['w']>0 and r['y']is not None for r in rr)or min(weights)<0 or sum(weights)<=0:raise ValueError('positive eligible training and member weight')\n members=[]\n for i,draw in enumerate(a['bootstrapDraws']):\n  data=[lookup[key(v)]for v in draw];schedule=a['nodeFeatures'][i]if forest else None;model=fit(data,a,task,classes,schedule);inbag={key(v)for v in draw};members.append(dict(tree=model,draw=draw,inbag=inbag,weight=weights[i]))\n predictions=[]\n for q in a.get('queries',[]):predictions.append(dict(id=q['id'],**combine([predict(m['tree'],[None if v is None else number(v)for v in q['x']])for m in members],weights,task,classes,a.get('aggregation','probabilities'))))\n oob=[]\n for r in rr:\n  applicable=[i for i,m in enumerate(members)if key(r['id'])not in m['inbag']];p=combine([predict(members[i]['tree'],r['x'])for i in applicable],[weights[i]for i in applicable],task,classes,a.get('aggregation','probabilities'));oob.append(dict(id=r['id'],applicable=applicable,positiveMembers=sum(weights[i]>0 for i in applicable),**p))\n return dict(task=task,classes=classes,members=members,predictions=predictions,outOfBag=scored(oob,rr,task,classes))\ndef boost(a):\n if a.get('task','regression')!='regression':raise ValueError('regression boosting only')\n rr=normalized(a['rows']);good=[r for r in rr if r['w']and r['y']is not None];W=sum((r['w']for r in good),Q())\n if not W:raise ValueError('positive eligible training')\n eta=number(a.get('learningRate','1/2'));stages=a.get('stages',3)\n if not 0<=eta<=1 or not isinstance(stages,int)or isinstance(stages,bool)or not 0<=stages<=8:raise ValueError('supported rate/stages')\n initial=number(a['initial'])if'initial'in a else sum((r['w']*r['y']for r in good),Q())/W;training=[[initial]for r in rr];queries=[[initial]for q in a.get('queries',[])];fits=[];losses=[]\n for stage in range(stages+1):\n  sse=sum((r['w']*(r['y']-p[-1])**2 for r,p in zip(rr,training)if r['w']and r['y']is not None),Q());losses.append(dict(stage=stage,rawWeightedSSE=sse,MSE=sse/W,meanHalfSquaredLoss=sse/(2*W)))\n  if stage==stages:break\n  residuals=[dict(r,y=None if r['y']is None else r['y']-p[-1])for r,p in zip(rr,training)];tree=fit(residuals,a,'regression',[]);h=[predict(tree,r['x'])['prediction']for r in rr];qh=[predict(tree,[None if v is None else number(v)for v in q['x']])['prediction']for q in a.get('queries',[])];norm=sum((r['w']*v*v for r,v in zip(rr,h)if r['y']is not None),Q());stageRows=[]\n  for i,(r,p)in enumerate(zip(rr,training)):\n   residual=None if r['y']is None else r['y']-p[-1];stageRows.append(dict(id=r['id'],before=p[-1],residual=residual,negativeCoordinateDerivative=None if residual is None else r['w']*residual/W,fit=h[i],addition=eta*h[i],after=p[-1]+eta*h[i]));p.append(p[-1]+eta*h[i])\n  for p,v in zip(queries,qh):p.append(p[-1]+eta*v)\n  fits.append(dict(stage=stage+1,tree=tree,rows=stageRows,queryFits=qh,norm=norm,predictedSSEDecrease=eta*(2-eta)*norm))\n return dict(task='regression',initial=initial,learningRate=eta,stages=stages,training=training,queries=queries,fits=fits,losses=losses,predictions=[dict(id=q['id'],prediction=p[-1],probabilities=[],vote=None,prob=None)for q,p in zip(a.get('queries',[]),queries)])\nclass Stream:\n def __init__(self,state):self.state=state\n def choose(self,n):\n  limit=(1<<32)-((1<<32)%n)\n  while True:\n   self.state=(1664525*self.state+1013904223)&0xffffffff\n   if self.state<limit:return self.state%n\ndef fixed_schedules(ids,p,seed):\n stream=Stream(seed);draws=[];schedules=[];paths=['']+[p for d in[1,2]for p in map(''.join,itertools.product('LR',repeat=d))]\n for member in range(4):\n  draws.append([ids[stream.choose(len(ids))]for _ in range(len(ids))]);schedule={}\n  for path in paths:\n   order=list(range(p))\n   for j in range(p-1,0,-1):k=stream.choose(j+1);order[j],order[k]=order[k],order[j]\n   schedule[path]=sorted(order[:max(1,int(math.sqrt(p)))])\n  schedules.append(schedule)\n return draws,schedules\ndef csvread(file):\n with Path(file).open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))\ndef read_sources(source):\n source=Path(source);raw=csvread(source/'actual320-country-four-indicators-original-2020-2024.csv');lookup={(r['countryISO3'],int(r['date']),r['indicatorID']):r for r in raw};country=[]\n for code in sorted({r['countryISO3']for r in raw}):\n  for year in range(2020,2025):\n   cols=['NY.GDP.PCAP.KD','NY.GDP.MKTP.KD.ZG','FP.CPI.TOTL.ZG','SP.DYN.LE00.IN'];v=[lookup[code,year,k]['originalValueToken']for k in cols];x=[None if not z else Q(z)for z in v[:3]];x[0]=None if x[0]is None else x[0]/10000;y=None if not v[3]else Q(v[3]);eligible=y is not None and None not in x;country.append(dict(id=code+':'+str(year),sourceRow=code+':'+str(year),originalID=code,year=year,x=x,y=y,weight='1',role='excluded'if not eligible else'outer-test'if year==2024 else'train'))\n person=[]\n for i,r in enumerate(csvread(source/'actual3613-NLS-original52-fields-and-selection.csv'),1):\n  v=lambda k:None if r[k]=='.'else Q(r[k]);x=[v('ed76'),v('age76')];y=None if v('wage76')is None else v('wage76')/100;eligible=y is not None and None not in x;person.append(dict(id='person:'+str(i),sourceRow=str(i),originalID=r['id'],x=x,y=y,weight='1',role='excluded'if not eligible else'outer-test'if i%5==0 else'train'))\n company=[]\n for i,r in enumerate(csvread(source/'actual3150-churn-original14-fields-and-selection.csv'),1):company.append(dict(id='customer:'+str(i),sourceRow=str(i),originalID='',x=[Q(r[k])for k in['Call  Failure','Subscription  Length','Charge  Amount']],y=r['Churn'],weight='1',role='outer-test'if i%5==0 else'train'))\n models={}\n for index,(kind,rr,task,leaf)in enumerate([('country',country,'regression',4),('person',person,'regression',50),('company',company,'classification',30)]):\n  ids=[r['id']for r in rr if r['role']=='train'];draws,schedules=fixed_schedules(ids,len(rr[0]['x']),20261102+7919*index);models[kind]=dict(records=rr,task=task,classes=['0','1']if task=='classification'else[],draws=draws,schedules=schedules,minLeaf=leaf)\n return models\n_OMITTED=object()\ndef realdata(models,kind,options=_OMITTED):\n options={}if options is _OMITTED else options\n if not isinstance(options,dict):raise ValueError('options object required, not explicit null')\n m=models[kind];train=[r for r in m['records']if r['role']=='train'];test=[r for r in m['records']if r['role']=='outer-test'];method=options.get('method','forest');depth=options.get('maxDepth',2);count=options.get('memberCount',3);a=dict(rows=train,queries=[dict(id=r['id'],x=r['x'])for r in test],task=m['task'],classes=m['classes'],maxDepth=depth,minLeaf=options.get('minLeaf',m['minLeaf']),minLeafWeight='0',minGain='0',missingRoute='best',learningRate=options.get('learningRate','1/2'),stages=options.get('stages',3))\n if method not in ['bagging','forest','boost']:raise ValueError('known source method')\n if not isinstance(depth,int)or isinstance(depth,bool)or not 0<=depth<=3:raise ValueError('source depth0..3')\n if method!='boost'and(not isinstance(count,int)or isinstance(count,bool)or not 1<=count<=4):raise ValueError('source member count1..4')\n if method=='boost':result=boost(a)\n else:\n  a.update(bootstrapDraws=m['draws'][:count],nodeFeatures=[{p:v for p,v in s.items()if len(p)<depth}for s in m['schedules'][:count]]);result=ensemble(a,method=='forest')\n outer=scored(result['predictions'],normalized(test,m['task']),m['task'],m['classes']);st=totals([r for r in normalized(train,m['task'])if r['w']and r['y']is not None],m['task'],m['classes']);constant=dict(prediction=st['pred'],probabilities=st['p'],vote=st['pred'],prob=st['pred']);baseline=scored([dict(id=r['id'],**constant)for r in test],normalized(test,m['task']),m['task'],m['classes']);return dict(kind=kind,method=method,settings=a,train=train,test=test,result=result,outer=outer,baseline=baseline)\ndef serial(x):\n if isinstance(x,Q):return str(x)\n if isinstance(x,dict):return{k:serial(v)for k,v in x.items()if k not in['inbag','tree']}\n if isinstance(x,(list,tuple)):return[serial(v)for v in x]\n return x\ndef writecsv(file,heads,rows):\n with Path(file).open('w',encoding='utf8',newline='')as f:\n  w=csv.writer(f);w.writerow(heads);w.writerows([[''if v is None else str(v)for v in r]for r in rows])\nAPI='boost'\nINPUT={'rows': [{'id': 'a', 'x': [0], 'y': 0, 'weight': 3}, {'id': 'b', 'x': [1], 'y': 4, 'weight': 1}], 'queries': [{'id': 'q', 'x': [1]}], 'maxDepth': 1, 'learningRate': '1/2', 'stages': 2}\n\ndef run_fixed(api,a,out,src):\n import matplotlib\n matplotlib.use('svg')\n import matplotlib.pyplot as plt\n from matplotlib.ticker import MaxNLocator\n plt.rcParams.update({'font.size':14,'svg.fonttype':'none','svg.hashsalt':'ml09-fixed-v1'})\n result=variance(a)if api=='variance'else aggregate(a)if api=='aggregate'else ensemble(a,api=='forest')if api in ['bagging','forest']else boost(a)if api=='boost'else realdata(read_sources(src),a['kind'])\n out=Path(out);out.mkdir(parents=True,exist_ok=True);summary={};points=[]\n def add(x,y,s):\n  if y is not None:points.append([x,y,s])\n if api=='variance':\n  summary={'B':result['B'],'varianceOfMean':result['varianceOfMean']};add(result['B'],result['varianceOfMean'],'Specified finite-B variance');xl='Number of members B';yl='Variance, stipulated units squared';title='Declared covariance model, not fitted trees'\n elif api=='aggregate':\n  p=result['predictions'][0];classification=a.get('task')=='classification';summary={'selectedPrediction':p['prediction']}\n  if classification:\n   summary.update(voteLabel=p['vote'],probabilityLabel=p['prob'],meanProbability1=p['probabilities'][1]);add(1,p['probabilities'][1],'Mean probability of class 1');add(2,p['votes'][1],'Label-vote share of class 1');xl='Aggregation (1=probability, 2=vote)';yl='Probability or vote share'\n  else:\n   for i,m in enumerate(a['members']):add(i+1,Q(m['predictions'][0]['value']),'Member prediction')\n   add(3,p['prediction'],'Weighted mean');xl='Member 1, member 2, aggregate 3';yl='Prediction, assumed units'\n  title='Votes and probabilities are distinct objects'\n elif api in ['bagging','forest']:\n  summary={'queryPrediction':result['predictions'][0]['prediction'],'OOB.scoreable':result['outOfBag']['eligibleRows'],'OOB.meanLoss':result['outOfBag']['meanLoss']}\n  for i,r in enumerate(a['rows']):add(i+1,Q(r['y']),'Observed training outcome')\n  for i,p in enumerate(result['outOfBag']['rows']):add(i+1,p['prediction'],'OOB prediction, when defined')\n  xl='Original training ID order';yl='Outcome, assumed units';title='Repeated draws and ID-level OOB membership'\n elif api=='boost':\n  summary={'initial':result['initial'],'finalMSE':result['losses'][-1]['MSE'],'stages':result['stages']}\n  for r in result['losses']:add(r['stage'],r['MSE'],'Training MSE')\n  xl='Boosting stage (0=initial)';yl='Weighted MSE, outcome units squared';title='Training descent does not certify held-out gain'\n else:\n  summary={'outer.scoreable':result['outer']['eligibleRows'],'outer.meanLoss':result['outer']['meanLoss'],'baseline.meanLoss':result['baseline']['meanLoss'],'OOB.scoreable':result['result']['outOfBag']['eligibleRows'],'OOB.meanLoss':result['result']['outOfBag']['meanLoss']}\n  for i,p in enumerate(result['outer']['rows']):\n   add(i+1,Q(p['actual']),'Observed outcome');add(i+1,p['probabilities'][1]if a['kind']=='company'else p['prediction'],'Forest probability of class 1'if a['kind']=='company'else'Forest prediction')\n  xl='Outer-test source order, not a time path';yl='Churn label / probability'if a['kind']=='company'else'Period life expectancy, years'if a['kind']=='country'else'Nominal 1976 USD per hour';title='Fixed forest; outer labels did not fit the trees'\n def display(v):return 'undefined'if v is None else format(float(v),'.9f')\n writecsv(out/'summary.csv',['metric','value'],[[k,display(v)]for k,v in summary.items()]);writecsv(out/'plot-points.csv',['x','y','series'],points);(out/'full.json').write_text(json.dumps(serial(result),indent=2)+'\\n',encoding='utf8')\n fig,ax=plt.subplots(figsize=(5.6,4.6));fig.subplots_adjust(left=.24,right=.96,bottom=.24,top=.76);colors=['#355c72','#a55336','#507956','#78568b']\n for i,s in enumerate(dict.fromkeys(p[2]for p in points)):\n  pp=[p for p in points if p[2]==s];ax.scatter([float(p[0])for p in pp],[float(p[1])for p in pp],s=12 if len(pp)>100 else 32,alpha=.5 if len(pp)>100 else 1,color=colors[i%4],label=s)\n ax.set_xlabel(xl,labelpad=10,fontsize=11);ax.set_ylabel(yl,labelpad=10,fontsize=11);ax.xaxis.set_major_locator(MaxNLocator(3));ax.yaxis.set_major_locator(MaxNLocator(4));ax.grid(alpha=.18);ax.legend(loc='lower left',bbox_to_anchor=(0,1.01),fontsize=9,frameon=False);fig.suptitle(title,fontsize=9,y=.99);fig.savefig(out/'plot.svg',metadata={'Date':None});plt.close(fig);print(', '.join(k+'='+display(v)for k,v in summary.items()))\nif __name__=='__main__':\n import sys\n try:run_fixed(API,INPUT,sys.argv[1]if len(sys.argv)>1 else'fixed-results',sys.argv[2]if len(sys.argv)>2 else'ml09-sources')\n except ValueError as error:print('Rejected declared input: '+str(error),file=sys.stderr);sys.exit(2)\n",
        "code": "\"\"\"ML09 exact Fraction reproduction from native source fields.\n\npython ml09-public-analysis.py --source-dir ml09-sources --output-dir results\n\nThis authored educational implementation uses direct-centered leaf losses and\nexhaustive midpoint partitions. It reads no JS engine, model contract, checker,\nstored target answers or derived-result CSV. Its five tree arithmetic helpers\nwere copied from the author's own separate Fraction reference, not an independent\npeer. Parser/work budgets and display rounding of the production JS are separate.\nNumerical predictions/proper scores do not certify causal effects, calibration,\nIID OOB validity, survey representativeness or production parameter optimality.\n\"\"\"\nfrom pathlib import Path\nfrom fractions import Fraction as Q\nimport csv,json,math,itertools,argparse\n\ndef normalized(rows,task='regression'):\n return [dict(id=r.get('id',i),x=[None if x is None else Q(x)for x in r.get('x',[])],y=None if r['y']is None else str(r['y'])if task=='classification'else Q(r['y']),w=Q(r.get('weight',1)))for i,r in enumerate(rows)]\n\ndef totals(rows,task,classes):\n W=sum((r['w']for r in rows),Q());mu=sum((r['w']*r['y']for r in rows),Q())/W if task=='regression'and W else None\n probs=[sum((r['w']for r in rows if r['y']==c),Q())/W for c in classes]if task=='classification'and W else[]\n risk=sum((r['w']*(r['y']-mu)**2 for r in rows),Q())if task=='regression'and W else W*sum((p*(1-p)for p in probs),Q())\n return dict(n=len(rows),w=W,mu=mu,p=probs,risk=risk,pred=mu if task=='regression'else classes[max(range(len(probs)),key=lambda i:probs[i])]if probs else None)\n\ndef fit(rows,a,task,classes,schedule=None):\n good=[r for r in rows if r['w']>0 and r['y']is not None];root=totals(good,task,classes)['w'];depth=a.get('maxDepth',2);minimum=a.get('minLeaf',1);minmass=Q(a.get('minLeafWeight',0));mingain=Q(a.get('minGain',0));route=a.get('missingRoute','best')\n def build(rr,d,path):\n  st=totals(rr,task,classes);n=dict(rows=rr,st=st,split=None,left=None,right=None,path=path)\n  if d==depth:return n\n  best=None\n  for j in range(len(rr[0]['x'])):\n   if schedule is not None and j not in schedule[path]:continue\n   values=sorted({r['x'][j]for r in rr if r['x'][j]is not None});missing=[r for r in rr if r['x'][j]is None];observed=[r for r in rr if r['x'][j]is not None]\n   candidates=[]\n   for lo,hi in zip(values,values[1:]):\n    q=(lo+hi)/2;left=[r for r in observed if r['x'][j]<=q];right=[r for r in observed if r['x'][j]>q];directions=[route]if route!='best'else['left','right']if missing else['left'if len(left)>=len(right)else'right']\n    for direction in directions:candidates.append(('threshold',q,direction,left+missing if direction=='left'else left,right+missing if direction=='right'else right))\n   if missing and observed:candidates.append(('missing-only',None,'left',missing,observed))\n   for kind,q,direction,left,right in candidates:\n    l=totals(left,task,classes);r=totals(right,task,classes)\n    if min(l['n'],r['n'])<minimum or min(l['w'],r['w'])<minmass or min(l['w'],r['w'])<=0:continue\n    gain=(st['risk']-l['risk']-r['risk'])/root\n    if best is None or gain>best['gain']:best=dict(feature=j,kind=kind,threshold=q,missingRoute=direction,left=left,right=right,gain=gain)\n  if best and best['gain']>0 and best['gain']>mingain:\n   j=best['feature'];go=lambda r:r['x'][j]is None if best['kind']=='missing-only'else best['missingRoute']=='left'if r['x'][j]is None else r['x'][j]<=best['threshold'];n['split']=best;n['left']=build([r for r in rr if go(r)],d+1,path+'L');n['right']=build([r for r in rr if not go(r)],d+1,path+'R')\n  return n\n return build(good,0,'')\n\ndef predict(tree,x):\n n=tree\n while n['split']:\n  s=n['split'];v=x[s['feature']];left=v is None if s['kind']=='missing-only'else s['missingRoute']=='left'if v is None else v<=s['threshold'];n=n['left'if left else'right']\n return dict(prediction=n['st']['pred'],probabilities=n['st']['p'])\n\ndef combine(preds,w,task,classes,mode='probabilities'):\n mass=sum(w,Q())\n if not preds or not mass:return dict(prediction=None,probabilities=[],vote=None,prob=None)\n if task=='regression':return dict(prediction=sum((p['prediction']*v for p,v in zip(preds,w)),Q())/mass,probabilities=[],vote=None,prob=None)\n votes=[sum((v for p,v in zip(preds,w)if p['prediction']==c),Q())/mass for c in classes];ps=[sum((p['probabilities'][j]*v for p,v in zip(preds,w)),Q())/mass for j in range(len(classes))];vote=classes[max(range(len(classes)),key=lambda j:votes[j])];prob=classes[max(range(len(classes)),key=lambda j:ps[j])];return dict(prediction=vote if mode=='votes'else prob,probabilities=ps,vote=vote,prob=prob,votes=votes)\ndef number(v):\n if v is None or isinstance(v,bool):raise ValueError('explicit null/bool is not a numeric parameter')\n return Q(v)\ndef variance(a):\n B=a['B'];v=number(a['marginalVariance']);rho=number(a.get('rho',0))\n if not isinstance(B,int)or isinstance(B,bool)or B<1 or v<0:raise ValueError('positive integer B/nonnegative variance')\n if B>1 and v and not -Q(1,B-1)<=rho<=1:raise ValueError('equicorrelation PSD bound')\n return dict(B=B,marginalVariance=v,correlationApplicable=B>1 and bool(v),varianceOfMean=v if B==1 else v*(1+(B-1)*rho)/B)\ndef aggregate(a):\n task=a.get('task','regression');classes=[str(c)for c in a.get('classes',[])];members=a['members'];w=[number(v)for v in a.get('memberWeights',[1]*len(members))]\n if not members or min(w)<0 or sum(w)<=0:raise ValueError('nonnegative member weights/positive total')\n order=[p.get('id',i)for i,p in enumerate(members[0]['predictions'])];keys=lambda x:(type(x).__name__,x);lookup=[{keys(p.get('id',i)):p for i,p in enumerate(m['predictions'])}for m in members]\n if any(set(m)!={keys(v)for v in order}for m in lookup):raise ValueError('same query ID set')\n out=[]\n for pid in order:\n  predictions=[dict(prediction=number(m[keys(pid)]['value']),probabilities=[])if task=='regression'else dict(prediction=str(m[keys(pid)]['label']),probabilities=[number(v)for v in m[keys(pid)]['probabilities']])for m in lookup]\n  if task=='classification'and any(min(p['probabilities'])<0 or sum(p['probabilities'])!=1 for p in predictions):raise ValueError('probability simplex')\n  out.append(dict(id=pid,**combine(predictions,w,task,classes,a.get('aggregation','probabilities'))))\n return dict(task=task,classes=classes,predictions=out)\ndef scored(preds,rows,task,classes):\n mass=loss=absolute=errors=voteerrors=Q();out=[]\n for p,r in zip(preds,rows):\n  ok=p['prediction']is not None and r['y']is not None and r['w']>0;v=None\n  if ok:\n   mass+=r['w']\n   if task=='regression':e=r['y']-p['prediction'];v=e*e;absolute+=r['w']*abs(e)\n   else:v=sum(((q-(1 if r['y']==c else 0))**2 for c,q in zip(classes,p['probabilities'])),Q());errors+=r['w']*(p['prediction']!=r['y']);voteerrors+=r['w']*(p['vote']!=r['y'])\n   loss+=r['w']*v\n  out.append(dict(p,actual=r['y'],weight=r['w'],scoreEligible=ok,loss=v))\n return dict(rows=out,eligibleRows=sum(r['scoreEligible']for r in out),weight=mass,totalLoss=loss,meanLoss=loss/mass if mass else None,MAE=absolute/mass if mass and task=='regression'else None,errorRate=errors/mass if mass and task=='classification'else None,labelVoteErrorRate=voteerrors/mass if mass and task=='classification'else None)\ndef ensemble(a,forest=False):\n task=a.get('task','regression');classes=[str(v)for v in(a.get('classes')or[])];rr=normalized(a['rows'],task);key=lambda x:(type(x).__name__,x);lookup={key(r['id']):r for r in rr};weights=[number(v)for v in a.get('memberWeights',[1]*len(a['bootstrapDraws']))]\n if not any(r['w']>0 and r['y']is not None for r in rr)or min(weights)<0 or sum(weights)<=0:raise ValueError('positive eligible training and member weight')\n members=[]\n for i,draw in enumerate(a['bootstrapDraws']):\n  data=[lookup[key(v)]for v in draw];schedule=a['nodeFeatures'][i]if forest else None;model=fit(data,a,task,classes,schedule);inbag={key(v)for v in draw};members.append(dict(tree=model,draw=draw,inbag=inbag,weight=weights[i]))\n predictions=[]\n for q in a.get('queries',[]):predictions.append(dict(id=q['id'],**combine([predict(m['tree'],[None if v is None else number(v)for v in q['x']])for m in members],weights,task,classes,a.get('aggregation','probabilities'))))\n oob=[]\n for r in rr:\n  applicable=[i for i,m in enumerate(members)if key(r['id'])not in m['inbag']];p=combine([predict(members[i]['tree'],r['x'])for i in applicable],[weights[i]for i in applicable],task,classes,a.get('aggregation','probabilities'));oob.append(dict(id=r['id'],applicable=applicable,positiveMembers=sum(weights[i]>0 for i in applicable),**p))\n return dict(task=task,classes=classes,members=members,predictions=predictions,outOfBag=scored(oob,rr,task,classes))\ndef boost(a):\n if a.get('task','regression')!='regression':raise ValueError('regression boosting only')\n rr=normalized(a['rows']);good=[r for r in rr if r['w']and r['y']is not None];W=sum((r['w']for r in good),Q())\n if not W:raise ValueError('positive eligible training')\n eta=number(a.get('learningRate','1/2'));stages=a.get('stages',3)\n if not 0<=eta<=1 or not isinstance(stages,int)or isinstance(stages,bool)or not 0<=stages<=8:raise ValueError('supported rate/stages')\n initial=number(a['initial'])if'initial'in a else sum((r['w']*r['y']for r in good),Q())/W;training=[[initial]for r in rr];queries=[[initial]for q in a.get('queries',[])];fits=[];losses=[]\n for stage in range(stages+1):\n  sse=sum((r['w']*(r['y']-p[-1])**2 for r,p in zip(rr,training)if r['w']and r['y']is not None),Q());losses.append(dict(stage=stage,rawWeightedSSE=sse,MSE=sse/W,meanHalfSquaredLoss=sse/(2*W)))\n  if stage==stages:break\n  residuals=[dict(r,y=None if r['y']is None else r['y']-p[-1])for r,p in zip(rr,training)];tree=fit(residuals,a,'regression',[]);h=[predict(tree,r['x'])['prediction']for r in rr];qh=[predict(tree,[None if v is None else number(v)for v in q['x']])['prediction']for q in a.get('queries',[])];norm=sum((r['w']*v*v for r,v in zip(rr,h)if r['y']is not None),Q());stageRows=[]\n  for i,(r,p)in enumerate(zip(rr,training)):\n   residual=None if r['y']is None else r['y']-p[-1];stageRows.append(dict(id=r['id'],before=p[-1],residual=residual,negativeCoordinateDerivative=None if residual is None else r['w']*residual/W,fit=h[i],addition=eta*h[i],after=p[-1]+eta*h[i]));p.append(p[-1]+eta*h[i])\n  for p,v in zip(queries,qh):p.append(p[-1]+eta*v)\n  fits.append(dict(stage=stage+1,tree=tree,rows=stageRows,queryFits=qh,norm=norm,predictedSSEDecrease=eta*(2-eta)*norm))\n return dict(task='regression',initial=initial,learningRate=eta,stages=stages,training=training,queries=queries,fits=fits,losses=losses,predictions=[dict(id=q['id'],prediction=p[-1],probabilities=[],vote=None,prob=None)for q,p in zip(a.get('queries',[]),queries)])\nclass Stream:\n def __init__(self,state):self.state=state\n def choose(self,n):\n  limit=(1<<32)-((1<<32)%n)\n  while True:\n   self.state=(1664525*self.state+1013904223)&0xffffffff\n   if self.state<limit:return self.state%n\ndef fixed_schedules(ids,p,seed):\n stream=Stream(seed);draws=[];schedules=[];paths=['']+[p for d in[1,2]for p in map(''.join,itertools.product('LR',repeat=d))]\n for member in range(4):\n  draws.append([ids[stream.choose(len(ids))]for _ in range(len(ids))]);schedule={}\n  for path in paths:\n   order=list(range(p))\n   for j in range(p-1,0,-1):k=stream.choose(j+1);order[j],order[k]=order[k],order[j]\n   schedule[path]=sorted(order[:max(1,int(math.sqrt(p)))])\n  schedules.append(schedule)\n return draws,schedules\ndef csvread(file):\n with Path(file).open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))\ndef read_sources(source):\n source=Path(source);raw=csvread(source/'actual320-country-four-indicators-original-2020-2024.csv');lookup={(r['countryISO3'],int(r['date']),r['indicatorID']):r for r in raw};country=[]\n for code in sorted({r['countryISO3']for r in raw}):\n  for year in range(2020,2025):\n   cols=['NY.GDP.PCAP.KD','NY.GDP.MKTP.KD.ZG','FP.CPI.TOTL.ZG','SP.DYN.LE00.IN'];v=[lookup[code,year,k]['originalValueToken']for k in cols];x=[None if not z else Q(z)for z in v[:3]];x[0]=None if x[0]is None else x[0]/10000;y=None if not v[3]else Q(v[3]);eligible=y is not None and None not in x;country.append(dict(id=code+':'+str(year),sourceRow=code+':'+str(year),originalID=code,year=year,x=x,y=y,weight='1',role='excluded'if not eligible else'outer-test'if year==2024 else'train'))\n person=[]\n for i,r in enumerate(csvread(source/'actual3613-NLS-original52-fields-and-selection.csv'),1):\n  v=lambda k:None if r[k]=='.'else Q(r[k]);x=[v('ed76'),v('age76')];y=None if v('wage76')is None else v('wage76')/100;eligible=y is not None and None not in x;person.append(dict(id='person:'+str(i),sourceRow=str(i),originalID=r['id'],x=x,y=y,weight='1',role='excluded'if not eligible else'outer-test'if i%5==0 else'train'))\n company=[]\n for i,r in enumerate(csvread(source/'actual3150-churn-original14-fields-and-selection.csv'),1):company.append(dict(id='customer:'+str(i),sourceRow=str(i),originalID='',x=[Q(r[k])for k in['Call  Failure','Subscription  Length','Charge  Amount']],y=r['Churn'],weight='1',role='outer-test'if i%5==0 else'train'))\n models={}\n for index,(kind,rr,task,leaf)in enumerate([('country',country,'regression',4),('person',person,'regression',50),('company',company,'classification',30)]):\n  ids=[r['id']for r in rr if r['role']=='train'];draws,schedules=fixed_schedules(ids,len(rr[0]['x']),20261102+7919*index);models[kind]=dict(records=rr,task=task,classes=['0','1']if task=='classification'else[],draws=draws,schedules=schedules,minLeaf=leaf)\n return models\n_OMITTED=object()\ndef realdata(models,kind,options=_OMITTED):\n options={}if options is _OMITTED else options\n if not isinstance(options,dict):raise ValueError('options object required, not explicit null')\n m=models[kind];train=[r for r in m['records']if r['role']=='train'];test=[r for r in m['records']if r['role']=='outer-test'];method=options.get('method','forest');depth=options.get('maxDepth',2);count=options.get('memberCount',3);a=dict(rows=train,queries=[dict(id=r['id'],x=r['x'])for r in test],task=m['task'],classes=m['classes'],maxDepth=depth,minLeaf=options.get('minLeaf',m['minLeaf']),minLeafWeight='0',minGain='0',missingRoute='best',learningRate=options.get('learningRate','1/2'),stages=options.get('stages',3))\n if method not in ['bagging','forest','boost']:raise ValueError('known source method')\n if not isinstance(depth,int)or isinstance(depth,bool)or not 0<=depth<=3:raise ValueError('source depth0..3')\n if method!='boost'and(not isinstance(count,int)or isinstance(count,bool)or not 1<=count<=4):raise ValueError('source member count1..4')\n if method=='boost':result=boost(a)\n else:\n  a.update(bootstrapDraws=m['draws'][:count],nodeFeatures=[{p:v for p,v in s.items()if len(p)<depth}for s in m['schedules'][:count]]);result=ensemble(a,method=='forest')\n outer=scored(result['predictions'],normalized(test,m['task']),m['task'],m['classes']);st=totals([r for r in normalized(train,m['task'])if r['w']and r['y']is not None],m['task'],m['classes']);constant=dict(prediction=st['pred'],probabilities=st['p'],vote=st['pred'],prob=st['pred']);baseline=scored([dict(id=r['id'],**constant)for r in test],normalized(test,m['task']),m['task'],m['classes']);return dict(kind=kind,method=method,settings=a,train=train,test=test,result=result,outer=outer,baseline=baseline)\ndef serial(x):\n if isinstance(x,Q):return str(x)\n if isinstance(x,dict):return{k:serial(v)for k,v in x.items()if k not in['inbag','tree']}\n if isinstance(x,(list,tuple)):return[serial(v)for v in x]\n return x\ndef writecsv(file,heads,rows):\n with Path(file).open('w',encoding='utf8',newline='')as f:\n  w=csv.writer(f);w.writerow(heads);w.writerows([[''if v is None else str(v)for v in r]for r in rows])\nAPI='boost'\nINPUT={'rows': [{'id': 'a', 'x': [0], 'y': 0, 'weight': 3}, {'id': 'b', 'x': [1], 'y': 4, 'weight': 1}], 'queries': [{'id': 'q', 'x': [1]}], 'maxDepth': 1, 'learningRate': '1/2', 'stages': 2}\n\ndef run_fixed(api,a,out,src):\n import matplotlib\n matplotlib.use('svg')\n import matplotlib.pyplot as plt\n from matplotlib.ticker import MaxNLocator\n plt.rcParams.update({'font.size':14,'svg.fonttype':'none','svg.hashsalt':'ml09-fixed-v1'})\n result=variance(a)if api=='variance'else aggregate(a)if api=='aggregate'else ensemble(a,api=='forest')if api in ['bagging','forest']else boost(a)if api=='boost'else realdata(read_sources(src),a['kind'])\n out=Path(out);out.mkdir(parents=True,exist_ok=True);summary={};points=[]\n def add(x,y,s):\n  if y is not None:points.append([x,y,s])\n if api=='variance':\n  summary={'B':result['B'],'varianceOfMean':result['varianceOfMean']};add(result['B'],result['varianceOfMean'],'Specified finite-B variance');xl='Number of members B';yl='Variance, stipulated units squared';title='Declared covariance model, not fitted trees'\n elif api=='aggregate':\n  p=result['predictions'][0];classification=a.get('task')=='classification';summary={'selectedPrediction':p['prediction']}\n  if classification:\n   summary.update(voteLabel=p['vote'],probabilityLabel=p['prob'],meanProbability1=p['probabilities'][1]);add(1,p['probabilities'][1],'Mean probability of class 1');add(2,p['votes'][1],'Label-vote share of class 1');xl='Aggregation (1=probability, 2=vote)';yl='Probability or vote share'\n  else:\n   for i,m in enumerate(a['members']):add(i+1,Q(m['predictions'][0]['value']),'Member prediction')\n   add(3,p['prediction'],'Weighted mean');xl='Member 1, member 2, aggregate 3';yl='Prediction, assumed units'\n  title='Votes and probabilities are distinct objects'\n elif api in ['bagging','forest']:\n  summary={'queryPrediction':result['predictions'][0]['prediction'],'OOB.scoreable':result['outOfBag']['eligibleRows'],'OOB.meanLoss':result['outOfBag']['meanLoss']}\n  for i,r in enumerate(a['rows']):add(i+1,Q(r['y']),'Observed training outcome')\n  for i,p in enumerate(result['outOfBag']['rows']):add(i+1,p['prediction'],'OOB prediction, when defined')\n  xl='Original training ID order';yl='Outcome, assumed units';title='Repeated draws and ID-level OOB membership'\n elif api=='boost':\n  summary={'initial':result['initial'],'finalMSE':result['losses'][-1]['MSE'],'stages':result['stages']}\n  for r in result['losses']:add(r['stage'],r['MSE'],'Training MSE')\n  xl='Boosting stage (0=initial)';yl='Weighted MSE, outcome units squared';title='Training descent does not certify held-out gain'\n else:\n  summary={'outer.scoreable':result['outer']['eligibleRows'],'outer.meanLoss':result['outer']['meanLoss'],'baseline.meanLoss':result['baseline']['meanLoss'],'OOB.scoreable':result['result']['outOfBag']['eligibleRows'],'OOB.meanLoss':result['result']['outOfBag']['meanLoss']}\n  for i,p in enumerate(result['outer']['rows']):\n   add(i+1,Q(p['actual']),'Observed outcome');add(i+1,p['probabilities'][1]if a['kind']=='company'else p['prediction'],'Forest probability of class 1'if a['kind']=='company'else'Forest prediction')\n  xl='Outer-test source order, not a time path';yl='Churn label / probability'if a['kind']=='company'else'Period life expectancy, years'if a['kind']=='country'else'Nominal 1976 USD per hour';title='Fixed forest; outer labels did not fit the trees'\n def display(v):return 'undefined'if v is None else format(float(v),'.9f')\n writecsv(out/'summary.csv',['metric','value'],[[k,display(v)]for k,v in summary.items()]);writecsv(out/'plot-points.csv',['x','y','series'],points);(out/'full.json').write_text(json.dumps(serial(result),indent=2)+'\\n',encoding='utf8')\n fig,ax=plt.subplots(figsize=(5.6,4.6));fig.subplots_adjust(left=.24,right=.96,bottom=.24,top=.76);colors=['#355c72','#a55336','#507956','#78568b']\n for i,s in enumerate(dict.fromkeys(p[2]for p in points)):\n  pp=[p for p in points if p[2]==s];ax.scatter([float(p[0])for p in pp],[float(p[1])for p in pp],s=12 if len(pp)>100 else 32,alpha=.5 if len(pp)>100 else 1,color=colors[i%4],label=s)\n ax.set_xlabel(xl,labelpad=10,fontsize=11);ax.set_ylabel(yl,labelpad=10,fontsize=11);ax.xaxis.set_major_locator(MaxNLocator(3));ax.yaxis.set_major_locator(MaxNLocator(4));ax.grid(alpha=.18);ax.legend(loc='lower left',bbox_to_anchor=(0,1.01),fontsize=9,frameon=False);fig.suptitle(title,fontsize=9,y=.99);fig.savefig(out/'plot.svg',metadata={'Date':None});plt.close(fig);print(', '.join(k+'='+display(v)for k,v in summary.items()))\nif __name__=='__main__':\n import sys\n try:run_fixed(API,INPUT,sys.argv[1]if len(sys.argv)>1 else'fixed-results',sys.argv[2]if len(sys.argv)>2 else'ml09-sources')\n except ValueError as error:print('Rejected declared input: '+str(error),file=sys.stderr);sys.exit(2)\n",
        "inputFiles": [],
        "input": {
          "rows": [
            {
              "id": "a",
              "x": [
                0
              ],
              "y": 0,
              "weight": 3
            },
            {
              "id": "b",
              "x": [
                1
              ],
              "y": 4,
              "weight": 1
            }
          ],
          "queries": [
            {
              "id": "q",
              "x": [
                1
              ]
            }
          ],
          "maxDepth": 1,
          "learningRate": "1/2",
          "stages": 2
        },
        "returnCode": 0,
        "expectedFailure": false,
        "stdout": "initial=1.000000000, finalMSE=0.187500000, stages=2.000000000\n",
        "stderr": "",
        "summary": {
          "initial": "1.000000000",
          "finalMSE": "0.187500000",
          "stages": "2.000000000"
        },
        "plotPoints": [
          {
            "x": "0",
            "y": "3",
            "series": "Training MSE"
          },
          {
            "x": "1",
            "y": "3/4",
            "series": "Training MSE"
          },
          {
            "x": "2",
            "y": "3/16",
            "series": "Training MSE"
          }
        ],
        "plotFile": "ml09-fixed-results/boost-weighted-gradient-python/plot.svg",
        "plotSHA256": "57ef607378246dc7c5363ae6e733b9a5f842f927f9c189b3a693b6b84643b3f9",
        "files": [
          {
            "file": "ml09-fixed-results/boost-weighted-gradient-python/full.json",
            "sha256": "82eb6a91e05d0cc3e8fee9e382e7b1d08fe01d86a9e7185b4de8ffafda53f23c"
          },
          {
            "file": "ml09-fixed-results/boost-weighted-gradient-python/plot-points.csv",
            "sha256": "7f6ace759a7dc44ba03d32fdf52d2097f843ae95ca3ff2fd33d32f1aec0a7697"
          },
          {
            "file": "ml09-fixed-results/boost-weighted-gradient-python/plot.svg",
            "sha256": "57ef607378246dc7c5363ae6e733b9a5f842f927f9c189b3a693b6b84643b3f9"
          },
          {
            "file": "ml09-fixed-results/boost-weighted-gradient-python/summary.csv",
            "sha256": "cffcc6f232f74140528b4a9705f683b0e14758ffa94e8c30042b36548e1d9c99"
          }
        ],
        "scope": "Actually executed self-contained fixed example; current web controls execute separately. Python Fraction and finite-precision base R. Author gate, not independent peer."
      }
    },
    "r": {
      "two-stages": {
        "api": "boost",
        "variant": "two-stages",
        "language": "r",
        "codeFile": "ml09-code/boost-two-stages.R",
        "codeSHA256": "32f2735c8f978295b29bcd188b6536126e2719e25927df79187448e893388cfc",
        "codeText": "# ML09 base-R reproduction from native original-field CSVs.\n# Rscript ml09-public-analysis.R ml09-sources results-r\n# Separately written vectorized direct-centered squared/Gini losses.\n# No Python/JS/model-contract/stored-answer/derived-result reader or package.\n# Numeric arithmetic is binary64:1e-12 relative tie tolerance stabilizes exact\n# source ties,but does not certify tiny margins/underflow like Fraction JS/Python.\n# Data-frame rows use x0,x1,...,y,weight; original IDs remain attached to draws.\noptions(stringsAsFactors=FALSE,digits=17)\nnum<-function(v){if(is.null(v)||length(v)!=1||is.na(v))stop('numeric parameter required, not explicit NULL');p<-strsplit(as.character(v),'/',fixed=TRUE)[[1]];z<-if(length(p)==2)as.numeric(p[1])/as.numeric(p[2])else as.numeric(v);if(!is.finite(z))stop('finite numeric parameter');z}\noption<-function(a,k,default){if(k%in%names(a))a[[k]]else default}\nnormrows<-function(d,task){if(!'weight'%in%names(d))d$weight<-1;if(!'id'%in%names(d))d$id<-as.character(seq_len(nrow(d))-1);d$weight<-as.numeric(d$weight);if(anyNA(d$weight)||any(d$weight<0))stop('nonnegative weights');if(task=='regression')d$y<-as.numeric(d$y)else d$y<-as.character(d$y);d}\nstat<-function(d,task,classes){W<-sum(d$weight);mu<-if(task=='regression'&&W)sum(d$weight*d$y)/W else NA_real_;p<-if(task=='classification'&&W)vapply(classes,function(c)sum(d$weight[d$y==c])/W,0)else numeric();risk<-if(task=='regression'&&W)sum(d$weight*(d$y-mu)^2)else W*sum(p*(1-p));list(n=nrow(d),w=W,mu=mu,p=unname(p),risk=risk,pred=if(task=='regression')mu else if(W)classes[which.max(p)]else NA_character_)}\nfit<-function(d,a,task,classes,schedule=NULL){d<-d[d$weight>0&!is.na(d$y),,drop=FALSE];if(!nrow(d))stop('positive observed training');W<-sum(d$weight);depth<-option(a,'maxDepth',2);minimum<-option(a,'minLeaf',1);minmass<-num(option(a,'minLeafWeight',0));mingain<-num(option(a,'minGain',0));route<-option(a,'missingRoute','best');features<-grep('^x[0-9]+$',names(d),value=TRUE)\n build<-function(rr,level,path){st<-stat(rr,task,classes);node<-list(rows=rr,st=st,split=NULL,left=NULL,right=NULL,path=path);if(level==depth)return(node);best<-NULL;allowed<-if(is.null(schedule))seq_along(features)-1L else schedule[[match(path,names(schedule))]]\n  for(j in seq_along(features)-1L){if(!j%in%allowed)next;v<-rr[[features[j+1L]]];values<-sort(unique(v[!is.na(v)]));candidates<-list()\n   if(length(values)>1)for(k in seq_len(length(values)-1L)){threshold<-(values[k]+values[k+1L])/2;missing<-is.na(v);left<-!missing&v<=threshold;right<-!missing&v>threshold;directions<-if(route!='best')route else if(any(missing))c('left','right')else if(sum(left)>=sum(right))'left'else'right';for(direction in directions)candidates[[length(candidates)+1L]]<-list(kind='threshold',threshold=threshold,missingRoute=direction,left=if(direction=='left')left|missing else left,right=if(direction=='right')right|missing else right)}\n   if(anyNA(v)&&any(!is.na(v)))candidates[[length(candidates)+1L]]<-list(kind='missing-only',threshold=NA_real_,missingRoute='left',left=is.na(v),right=!is.na(v))\n   for(candidate in candidates){l<-rr[candidate$left,,drop=FALSE];r<-rr[candidate$right,,drop=FALSE];ls<-stat(l,task,classes);rs<-stat(r,task,classes);if(min(ls$n,rs$n)<minimum||min(ls$w,rs$w)<minmass||min(ls$w,rs$w)<=0)next;gain<-(st$risk-ls$risk-rs$risk)/W;tol<-1e-12*max(1,abs(gain),if(is.null(best))0 else abs(best$gain));if(is.null(best)||gain>best$gain+tol)best<-c(candidate,list(feature=j,gain=gain,l=l,r=r))}\n  }\n  if(!is.null(best)&&best$gain>max(mingain,1e-12)){node$split<-best;node$left<-build(best$l,level+1L,paste0(path,'L'));node$right<-build(best$r,level+1L,paste0(path,'R'))};node\n };build(d,0L,'')\n}\npredict_one<-function(tree,row){n<-tree;while(!is.null(n$split)){s<-n$split;v<-as.numeric(row[[paste0('x',s$feature)]]);left<-if(s$kind=='missing-only')is.na(v)else if(is.na(v))s$missingRoute=='left'else v<=s$threshold;n<-if(left)n$left else n$right};list(prediction=n$st$pred,probabilities=n$st$p)}\ncombine<-function(pp,w,task,classes,mode='probabilities'){W<-sum(w);if(!length(pp)||!W)return(list(prediction=if(task=='regression')NA_real_ else NA_character_,probabilities=numeric(),vote=NA_character_,prob=NA_character_));if(task=='regression')return(list(prediction=sum(vapply(pp,function(p)p$prediction,0)*w)/W,probabilities=numeric(),vote=NA_character_,prob=NA_character_));votes<-vapply(classes,function(c)sum(w[vapply(pp,function(p)p$prediction==c,FALSE)])/W,0);probs<-vapply(seq_along(classes),function(j)sum(vapply(pp,function(p)p$probabilities[j],0)*w)/W,0);vote<-classes[which.max(votes)];prob<-classes[which.max(probs)];list(prediction=if(mode=='votes')vote else prob,probabilities=unname(probs),vote=vote,prob=prob,votes=unname(votes))}\nvariance<-function(a){B<-num(a$B);v<-num(a$marginalVariance);rho<-num(option(a,'rho',0));if(B<1||B!=floor(B)||v<0)stop('integer B/nonnegative variance');if(B>1&&v>0&&(rho< -1/(B-1)||rho>1))stop('PSD correlation');list(B=B,marginalVariance=v,correlationApplicable=B>1&&v>0,varianceOfMean=if(B==1)v else v*(1+(B-1)*rho)/B)}\naggregate<-function(a){task<-option(a,'task','regression');classes<-option(a,'classes',character());w<-vapply(option(a,'memberWeights',as.list(rep(1,length(a$members)))),num,0);if(any(w<0)||sum(w)<=0)stop('positive member mass');ids<-a$members[[1]]$predictions$id;pp<-lapply(ids,function(id){members<-lapply(a$members,function(m){r<-m$predictions[match(id,m$predictions$id),,drop=FALSE];if(task=='regression')list(prediction=num(r$value),probabilities=numeric())else list(prediction=as.character(r$label),probabilities=as.numeric(r[paste0('p',seq_along(classes)-1L)]))});c(list(id=id),combine(members,w,task,classes,option(a,'aggregation','probabilities')))});list(task=task,classes=classes,predictions=pp)}\nscored<-function(preds,d,task,classes){W<-loss<-absolute<-errors<-voteerrors<-0;count<-0L;out<-lapply(seq_len(nrow(d)),function(i){r<-d[i,,drop=FALSE];p<-preds[[i]];ok<-!is.na(p$prediction)&&!is.na(r$y)&&r$weight>0;value<-NA_real_;if(ok){count<<-count+1L;W<<-W+r$weight;if(task=='regression'){e<-r$y-p$prediction;value<-e*e;absolute<<-absolute+r$weight*abs(e)}else{value<-sum((p$probabilities-as.numeric(classes==r$y))^2);errors<<-errors+r$weight*(p$prediction!=r$y);voteerrors<<-voteerrors+r$weight*(p$vote!=r$y)};loss<<-loss+r$weight*value};c(p,list(actual=r$y,weight=r$weight,scoreEligible=ok,loss=value))});list(rows=out,eligibleRows=count,weight=W,totalLoss=loss,meanLoss=if(W)loss/W else NA_real_,MAE=if(W&&task=='regression')absolute/W else NA_real_,errorRate=if(W&&task=='classification')errors/W else NA_real_,labelVoteErrorRate=if(W&&task=='classification')voteerrors/W else NA_real_)}\nensemble<-function(a,forest=FALSE){task<-option(a,'task','regression');classes<-option(a,'classes',character());d<-normrows(a$rows,task);w<-vapply(option(a,'memberWeights',as.list(rep(1,length(a$bootstrapDraws)))),num,0);if(any(w<0)||sum(w)<=0)stop('positive member mass');members<-lapply(seq_along(a$bootstrapDraws),function(i){draw<-a$bootstrapDraws[[i]];indices<-match(draw,d$id);if(anyNA(indices))stop('unknown draw source');tree<-fit(d[indices,,drop=FALSE],a,task,classes,if(forest)a$nodeFeatures[[i]]else NULL);list(tree=tree,draw=draw,inbag=unique(draw),weight=w[i])});queries<-a$queries;preds<-lapply(seq_len(nrow(queries)),function(i)c(list(id=queries$id[i]),combine(lapply(members,function(m)predict_one(m$tree,queries[i,,drop=FALSE])),w,task,classes,option(a,'aggregation','probabilities'))));oob<-lapply(seq_len(nrow(d)),function(i){app<-which(!vapply(members,function(m)d$id[i]%in%m$inbag,FALSE));pp<-combine(lapply(app,function(j)predict_one(members[[j]]$tree,d[i,,drop=FALSE])),w[app],task,classes,option(a,'aggregation','probabilities'));c(list(id=d$id[i],applicable=app-1L,positiveMembers=sum(w[app]>0)),pp)});list(task=task,classes=classes,members=members,predictions=preds,outOfBag=scored(oob,d,task,classes))}\nboost<-function(a){if(option(a,'task','regression')!='regression')stop('regression boosting only');d<-normrows(a$rows,'regression');eligible<-d$weight>0&!is.na(d$y);W<-sum(d$weight[eligible]);if(!W)stop('positive eligible training');eta<-num(option(a,'learningRate','1/2'));stages<-option(a,'stages',3);if(is.null(stages)||stages!=floor(stages)||stages<0||stages>8||eta<0||eta>1)stop('supported rate/stages');initial<-if('initial'%in%names(a))num(a$initial)else sum(d$weight[eligible]*d$y[eligible])/W;train<-matrix(initial,nrow(d),stages+1L);query<-matrix(initial,nrow(a$queries),stages+1L);losses<-fits<-list();for(stage in 0:stages){sse<-sum(d$weight[eligible]*(d$y[eligible]-train[eligible,stage+1L])^2);losses[[stage+1L]]<-list(stage=stage,rawWeightedSSE=sse,MSE=sse/W,meanHalfSquaredLoss=sse/(2*W));if(stage==stages)break;residual<-d;residual$y<-d$y-train[,stage+1L];tree<-fit(residual,a,'regression',character());h<-vapply(seq_len(nrow(d)),function(i)predict_one(tree,d[i,,drop=FALSE])$prediction,0);qh<-vapply(seq_len(nrow(a$queries)),function(i)predict_one(tree,a$queries[i,,drop=FALSE])$prediction,0);stageRows<-lapply(seq_len(nrow(d)),function(i)list(id=d$id[i],before=train[i,stage+1L],residual=residual$y[i],negativeCoordinateDerivative=d$weight[i]*residual$y[i]/W,fit=h[i],addition=eta*h[i],after=train[i,stage+1L]+eta*h[i]));train[,stage+2L]<-train[,stage+1L]+eta*h;query[,stage+2L]<-query[,stage+1L]+eta*qh;norm<-sum(d$weight[eligible]*h[eligible]^2);fits[[stage+1L]]<-list(stage=stage+1L,tree=tree,rows=stageRows,queryFits=qh,norm=norm,predictedSSEDecrease=eta*(2-eta)*norm)};list(task='regression',initial=initial,learningRate=eta,stages=stages,training=train,queries=query,fits=fits,losses=losses,predictions=lapply(seq_len(nrow(a$queries)),function(i)list(id=a$queries$id[i],prediction=query[i,stages+1L],probabilities=numeric(),vote=NA_character_,prob=NA_character_)))}\nfixed_schedules<-function(ids,p,seed){state<-seed;choose<-function(n){limit<-floor(4294967296/n)*n;repeat{state<<-(1664525*state+1013904223)%%4294967296;if(state<limit)return(as.integer(state%%n))}};draws<-schedules<-list();for(member in 1:4){draws[[member]]<-vapply(seq_along(ids),function(i)ids[choose(length(ids))+1L],'');schedule<-setNames(vector('list',7),c('','L','R','LL','LR','RL','RR'));for(path in names(schedule)){order<-seq_len(p)-1L;if(p>1)for(j in seq(p-1L,1L)){k<-choose(j+1L);temp<-order[j+1L];order[j+1L]<-order[k+1L];order[k+1L]<-temp};schedule[[match(path,names(schedule))]]<-sort(order[seq_len(max(1L,floor(sqrt(p))))])};schedules[[member]]<-schedule};list(draws=draws,schedules=schedules)}\nread_sources<-function(src){read<-function(name)read.csv(file.path(src,name),check.names=FALSE,colClasses='character',na.strings=character(),fileEncoding='UTF-8-BOM');raw<-read('actual320-country-four-indicators-original-2020-2024.csv');country<-do.call(rbind,lapply(sort(unique(raw$countryISO3)),function(code)do.call(rbind,lapply(2020:2024,function(year){keys<-c('NY.GDP.PCAP.KD','NY.GDP.MKTP.KD.ZG','FP.CPI.TOTL.ZG','SP.DYN.LE00.IN');v<-vapply(keys,function(k)as.numeric(raw$originalValueToken[raw$countryISO3==code&raw$date==as.character(year)&raw$indicatorID==k]),0);data.frame(id=paste0(code,':',year),sourceRow=paste0(code,':',year),originalID=code,year=year,x0=v[1]/10000,x1=v[2],x2=v[3],y=v[4],weight=1,role=if(anyNA(v))'excluded'else if(year==2024)'outer-test'else'train')}))));raw<-read('actual3613-NLS-original52-fields-and-selection.csv');i<-seq_len(nrow(raw));x0<-suppressWarnings(as.numeric(raw$ed76));x1<-suppressWarnings(as.numeric(raw$age76));y<-suppressWarnings(as.numeric(raw$wage76))/100;person<-data.frame(id=paste0('person:',i),sourceRow=as.character(i),originalID=raw$id,x0=x0,x1=x1,y=y,weight=1,role=ifelse(is.na(x0)|is.na(x1)|is.na(y),'excluded',ifelse(i%%5==0,'outer-test','train')));raw<-read('actual3150-churn-original14-fields-and-selection.csv');i<-seq_len(nrow(raw));company<-data.frame(id=paste0('customer:',i),sourceRow=as.character(i),originalID='',x0=as.numeric(raw[['Call  Failure']]),x1=as.numeric(raw[['Subscription  Length']]),x2=as.numeric(raw[['Charge  Amount']]),y=raw$Churn,weight=1,role=ifelse(i%%5==0,'outer-test','train'));models<-list();for(index in 1:3){kind<-c('country','person','company')[index];d<-list(country,person,company)[[index]];task<-if(kind=='company')'classification'else'regression';s<-fixed_schedules(d$id[d$role=='train'],if(kind=='person')2L else 3L,20261102+7919*(index-1L));models[[kind]]<-list(records=d,task=task,classes=if(task=='classification')c('0','1')else character(),draws=s$draws,schedules=s$schedules,minLeaf=c(4L,50L,30L)[index])};models}\nrealdata<-function(models,kind,options=list()){if(is.null(options)||!is.list(options))stop('options object');m<-models[[kind]];d<-m$records;train<-d[d$role=='train',,drop=FALSE];test<-d[d$role=='outer-test',,drop=FALSE];method<-option(options,'method','forest');depth<-option(options,'maxDepth',2);count<-option(options,'memberCount',3);if(!method%in%c('bagging','forest','boost'))stop('known method');a<-list(rows=train,queries=test,task=m$task,classes=m$classes,maxDepth=depth,minLeaf=option(options,'minLeaf',m$minLeaf),minLeafWeight=0,minGain=0,missingRoute='best',learningRate=option(options,'learningRate','1/2'),stages=option(options,'stages',3));if(method=='boost')result<-boost(a)else{a$bootstrapDraws<-m$draws[seq_len(count)];a$nodeFeatures<-lapply(m$schedules[seq_len(count)],function(s)s[nchar(names(s))<depth]);result<-ensemble(a,method=='forest')};outer<-scored(result$predictions,normrows(test,m$task),m$task,m$classes);st<-stat(normrows(train,m$task),m$task,m$classes);constant<-list(prediction=st$pred,probabilities=st$p,vote=st$pred,prob=st$pred);baseline<-scored(lapply(test$id,function(id)c(list(id=id),constant)),normrows(test,m$task),m$task,m$classes);list(kind=kind,method=method,settings=a,train=train,test=test,result=result,outer=outer,baseline=baseline)}\nAPI<-\"boost\"\nINPUT<-list(rows=data.frame(id=c(\"0\",\"1\",\"2\",\"3\"),y=c(0,0,4,4),x0=c(0,1,2,3),stringsAsFactors=FALSE),queries=data.frame(id=c(\"q\"),x0=c(num(\"3/2\")),stringsAsFactors=FALSE),maxDepth=1,learningRate=\"1/2\",stages=2)\n\nrun_fixed<-function(api,a,out,src){\n r<-if(api=='variance')variance(a)else if(api=='aggregate')aggregate(a)else if(api%in%c('bagging','forest'))ensemble(a,api=='forest')else if(api=='boost')boost(a)else realdata(read_sources(src),a$kind)\n dir.create(out,recursive=TRUE,showWarnings=FALSE);summary<-list();points<-list();add<-function(x,y,s){if(!is.null(y)&&!is.na(y))points[[length(points)+1L]]<<-data.frame(x=x,y=as.numeric(y),series=s)}\n if(api=='variance'){summary<-r[c('B','varianceOfMean')];add(r$B,r$varianceOfMean,'Specified finite-B variance');xl<-'Number of members B';yl<-'Variance, stipulated units squared';title<-'Declared covariance model, not fitted trees'\n }else if(api=='aggregate'){p<-r$predictions[[1]];summary<-list(selectedPrediction=p$prediction);classification<-identical(a$task,'classification');if(classification){summary<-c(summary,list(voteLabel=p$vote,probabilityLabel=p$prob,meanProbability1=p$probabilities[2]));add(1,p$probabilities[2],'Mean probability of class 1');add(2,p$votes[2],'Label-vote share of class 1');xl<-'Aggregation (1=probability, 2=vote)';yl<-'Probability or vote share'}else{for(i in seq_along(a$members))add(i,num(a$members[[i]]$predictions$value[1]),'Member prediction');add(3,p$prediction,'Weighted mean');xl<-'Member 1, member 2, aggregate 3';yl<-'Prediction, assumed units'};title<-'Votes and probabilities are distinct objects'\n }else if(api%in%c('bagging','forest')){summary<-list(queryPrediction=r$predictions[[1]]$prediction,OOB.scoreable=r$outOfBag$eligibleRows,OOB.meanLoss=r$outOfBag$meanLoss);for(i in seq_len(nrow(a$rows)))add(i,a$rows$y[i],'Observed training outcome');for(i in seq_along(r$outOfBag$rows))add(i,r$outOfBag$rows[[i]]$prediction,'OOB prediction, when defined');xl<-'Original training ID order';yl<-'Outcome, assumed units';title<-'Repeated draws and ID-level OOB membership'\n }else if(api=='boost'){summary<-list(initial=r$initial,finalMSE=r$losses[[length(r$losses)]]$MSE,stages=r$stages);for(v in r$losses)add(v$stage,v$MSE,'Training MSE');xl<-'Boosting stage (0=initial)';yl<-'Weighted MSE, outcome units squared';title<-'Training descent does not certify held-out gain'\n }else{summary<-list(outer.scoreable=r$outer$eligibleRows,outer.meanLoss=r$outer$meanLoss,baseline.meanLoss=r$baseline$meanLoss,OOB.scoreable=r$result$outOfBag$eligibleRows,OOB.meanLoss=r$result$outOfBag$meanLoss);for(i in seq_along(r$outer$rows)){p<-r$outer$rows[[i]];add(i,as.numeric(p$actual),'Observed outcome');add(i,if(a$kind=='company')p$probabilities[2]else p$prediction,if(a$kind=='company')'Forest probability of class 1'else'Forest prediction')};xl<-'Outer-test source order, not a time path';yl<-if(a$kind=='company')'Churn label / probability'else if(a$kind=='country')'Period life expectancy, years'else'Nominal 1976 USD per hour';title<-'Fixed forest; outer labels did not fit the trees'}\n display<-function(v)if(is.null(v)||is.na(v))'undefined'else sprintf('%.9f',as.numeric(v));write.csv(data.frame(metric=names(summary),value=vapply(summary,display,'')),file.path(out,'summary.csv'),row.names=FALSE);pp<-do.call(rbind,points);write.csv(pp,file.path(out,'plot-points.csv'),row.names=FALSE);dput(r,file.path(out,'full-result.Rtext'));svg(file.path(out,'plot.svg'),width=5.6,height=4.6,pointsize=14);par(mar=c(5.8,5.8,5.3,1.2),mgp=c(3.7,1,0));xr<-range(pp$x);yr<-range(pp$y);if(diff(xr)==0)xr<-xr+c(-.5,.5);if(diff(yr)==0)yr<-yr+c(-.5,.5);plot(xr,yr,type='n',xlab=xl,ylab=yl,cex.lab=.78,axes=FALSE);axis(1,at=pretty(xr,3));axis(2,at=pretty(yr,4),las=1,cex.axis=.82);box();grid(col='#dddddd');cols<-c('#355c72','#a55336','#507956','#78568b');ss<-unique(pp$series);for(i in seq_along(ss)){v<-pp[pp$series==ss[i],];points(v$x,v$y,pch=16,cex=if(nrow(v)>100).35 else .85,col=adjustcolor(cols[i],if(nrow(v)>100).5 else 1))};legend('topleft',legend=ss,col=cols[seq_along(ss)],lty=0,pch=16,cex=.65,bty='n',inset=c(0,-.32),xpd=NA);mtext(title,side=3,line=3.9,cex=.6);dev.off();cat(paste(names(summary),vapply(summary,display,''),sep='=',collapse=', '),'\\n')\n}\nargs<-commandArgs(trailingOnly=TRUE)\ntryCatch(run_fixed(API,INPUT,if(length(args))args[1]else'fixed-results',if(length(args)>1)args[2]else'ml09-sources'),error=function(e){cat('Rejected declared input: ',conditionMessage(e),'\\n',file=stderr());quit(status=2)})\n",
        "code": "# ML09 base-R reproduction from native original-field CSVs.\n# Rscript ml09-public-analysis.R ml09-sources results-r\n# Separately written vectorized direct-centered squared/Gini losses.\n# No Python/JS/model-contract/stored-answer/derived-result reader or package.\n# Numeric arithmetic is binary64:1e-12 relative tie tolerance stabilizes exact\n# source ties,but does not certify tiny margins/underflow like Fraction JS/Python.\n# Data-frame rows use x0,x1,...,y,weight; original IDs remain attached to draws.\noptions(stringsAsFactors=FALSE,digits=17)\nnum<-function(v){if(is.null(v)||length(v)!=1||is.na(v))stop('numeric parameter required, not explicit NULL');p<-strsplit(as.character(v),'/',fixed=TRUE)[[1]];z<-if(length(p)==2)as.numeric(p[1])/as.numeric(p[2])else as.numeric(v);if(!is.finite(z))stop('finite numeric parameter');z}\noption<-function(a,k,default){if(k%in%names(a))a[[k]]else default}\nnormrows<-function(d,task){if(!'weight'%in%names(d))d$weight<-1;if(!'id'%in%names(d))d$id<-as.character(seq_len(nrow(d))-1);d$weight<-as.numeric(d$weight);if(anyNA(d$weight)||any(d$weight<0))stop('nonnegative weights');if(task=='regression')d$y<-as.numeric(d$y)else d$y<-as.character(d$y);d}\nstat<-function(d,task,classes){W<-sum(d$weight);mu<-if(task=='regression'&&W)sum(d$weight*d$y)/W else NA_real_;p<-if(task=='classification'&&W)vapply(classes,function(c)sum(d$weight[d$y==c])/W,0)else numeric();risk<-if(task=='regression'&&W)sum(d$weight*(d$y-mu)^2)else W*sum(p*(1-p));list(n=nrow(d),w=W,mu=mu,p=unname(p),risk=risk,pred=if(task=='regression')mu else if(W)classes[which.max(p)]else NA_character_)}\nfit<-function(d,a,task,classes,schedule=NULL){d<-d[d$weight>0&!is.na(d$y),,drop=FALSE];if(!nrow(d))stop('positive observed training');W<-sum(d$weight);depth<-option(a,'maxDepth',2);minimum<-option(a,'minLeaf',1);minmass<-num(option(a,'minLeafWeight',0));mingain<-num(option(a,'minGain',0));route<-option(a,'missingRoute','best');features<-grep('^x[0-9]+$',names(d),value=TRUE)\n build<-function(rr,level,path){st<-stat(rr,task,classes);node<-list(rows=rr,st=st,split=NULL,left=NULL,right=NULL,path=path);if(level==depth)return(node);best<-NULL;allowed<-if(is.null(schedule))seq_along(features)-1L else schedule[[match(path,names(schedule))]]\n  for(j in seq_along(features)-1L){if(!j%in%allowed)next;v<-rr[[features[j+1L]]];values<-sort(unique(v[!is.na(v)]));candidates<-list()\n   if(length(values)>1)for(k in seq_len(length(values)-1L)){threshold<-(values[k]+values[k+1L])/2;missing<-is.na(v);left<-!missing&v<=threshold;right<-!missing&v>threshold;directions<-if(route!='best')route else if(any(missing))c('left','right')else if(sum(left)>=sum(right))'left'else'right';for(direction in directions)candidates[[length(candidates)+1L]]<-list(kind='threshold',threshold=threshold,missingRoute=direction,left=if(direction=='left')left|missing else left,right=if(direction=='right')right|missing else right)}\n   if(anyNA(v)&&any(!is.na(v)))candidates[[length(candidates)+1L]]<-list(kind='missing-only',threshold=NA_real_,missingRoute='left',left=is.na(v),right=!is.na(v))\n   for(candidate in candidates){l<-rr[candidate$left,,drop=FALSE];r<-rr[candidate$right,,drop=FALSE];ls<-stat(l,task,classes);rs<-stat(r,task,classes);if(min(ls$n,rs$n)<minimum||min(ls$w,rs$w)<minmass||min(ls$w,rs$w)<=0)next;gain<-(st$risk-ls$risk-rs$risk)/W;tol<-1e-12*max(1,abs(gain),if(is.null(best))0 else abs(best$gain));if(is.null(best)||gain>best$gain+tol)best<-c(candidate,list(feature=j,gain=gain,l=l,r=r))}\n  }\n  if(!is.null(best)&&best$gain>max(mingain,1e-12)){node$split<-best;node$left<-build(best$l,level+1L,paste0(path,'L'));node$right<-build(best$r,level+1L,paste0(path,'R'))};node\n };build(d,0L,'')\n}\npredict_one<-function(tree,row){n<-tree;while(!is.null(n$split)){s<-n$split;v<-as.numeric(row[[paste0('x',s$feature)]]);left<-if(s$kind=='missing-only')is.na(v)else if(is.na(v))s$missingRoute=='left'else v<=s$threshold;n<-if(left)n$left else n$right};list(prediction=n$st$pred,probabilities=n$st$p)}\ncombine<-function(pp,w,task,classes,mode='probabilities'){W<-sum(w);if(!length(pp)||!W)return(list(prediction=if(task=='regression')NA_real_ else NA_character_,probabilities=numeric(),vote=NA_character_,prob=NA_character_));if(task=='regression')return(list(prediction=sum(vapply(pp,function(p)p$prediction,0)*w)/W,probabilities=numeric(),vote=NA_character_,prob=NA_character_));votes<-vapply(classes,function(c)sum(w[vapply(pp,function(p)p$prediction==c,FALSE)])/W,0);probs<-vapply(seq_along(classes),function(j)sum(vapply(pp,function(p)p$probabilities[j],0)*w)/W,0);vote<-classes[which.max(votes)];prob<-classes[which.max(probs)];list(prediction=if(mode=='votes')vote else prob,probabilities=unname(probs),vote=vote,prob=prob,votes=unname(votes))}\nvariance<-function(a){B<-num(a$B);v<-num(a$marginalVariance);rho<-num(option(a,'rho',0));if(B<1||B!=floor(B)||v<0)stop('integer B/nonnegative variance');if(B>1&&v>0&&(rho< -1/(B-1)||rho>1))stop('PSD correlation');list(B=B,marginalVariance=v,correlationApplicable=B>1&&v>0,varianceOfMean=if(B==1)v else v*(1+(B-1)*rho)/B)}\naggregate<-function(a){task<-option(a,'task','regression');classes<-option(a,'classes',character());w<-vapply(option(a,'memberWeights',as.list(rep(1,length(a$members)))),num,0);if(any(w<0)||sum(w)<=0)stop('positive member mass');ids<-a$members[[1]]$predictions$id;pp<-lapply(ids,function(id){members<-lapply(a$members,function(m){r<-m$predictions[match(id,m$predictions$id),,drop=FALSE];if(task=='regression')list(prediction=num(r$value),probabilities=numeric())else list(prediction=as.character(r$label),probabilities=as.numeric(r[paste0('p',seq_along(classes)-1L)]))});c(list(id=id),combine(members,w,task,classes,option(a,'aggregation','probabilities')))});list(task=task,classes=classes,predictions=pp)}\nscored<-function(preds,d,task,classes){W<-loss<-absolute<-errors<-voteerrors<-0;count<-0L;out<-lapply(seq_len(nrow(d)),function(i){r<-d[i,,drop=FALSE];p<-preds[[i]];ok<-!is.na(p$prediction)&&!is.na(r$y)&&r$weight>0;value<-NA_real_;if(ok){count<<-count+1L;W<<-W+r$weight;if(task=='regression'){e<-r$y-p$prediction;value<-e*e;absolute<<-absolute+r$weight*abs(e)}else{value<-sum((p$probabilities-as.numeric(classes==r$y))^2);errors<<-errors+r$weight*(p$prediction!=r$y);voteerrors<<-voteerrors+r$weight*(p$vote!=r$y)};loss<<-loss+r$weight*value};c(p,list(actual=r$y,weight=r$weight,scoreEligible=ok,loss=value))});list(rows=out,eligibleRows=count,weight=W,totalLoss=loss,meanLoss=if(W)loss/W else NA_real_,MAE=if(W&&task=='regression')absolute/W else NA_real_,errorRate=if(W&&task=='classification')errors/W else NA_real_,labelVoteErrorRate=if(W&&task=='classification')voteerrors/W else NA_real_)}\nensemble<-function(a,forest=FALSE){task<-option(a,'task','regression');classes<-option(a,'classes',character());d<-normrows(a$rows,task);w<-vapply(option(a,'memberWeights',as.list(rep(1,length(a$bootstrapDraws)))),num,0);if(any(w<0)||sum(w)<=0)stop('positive member mass');members<-lapply(seq_along(a$bootstrapDraws),function(i){draw<-a$bootstrapDraws[[i]];indices<-match(draw,d$id);if(anyNA(indices))stop('unknown draw source');tree<-fit(d[indices,,drop=FALSE],a,task,classes,if(forest)a$nodeFeatures[[i]]else NULL);list(tree=tree,draw=draw,inbag=unique(draw),weight=w[i])});queries<-a$queries;preds<-lapply(seq_len(nrow(queries)),function(i)c(list(id=queries$id[i]),combine(lapply(members,function(m)predict_one(m$tree,queries[i,,drop=FALSE])),w,task,classes,option(a,'aggregation','probabilities'))));oob<-lapply(seq_len(nrow(d)),function(i){app<-which(!vapply(members,function(m)d$id[i]%in%m$inbag,FALSE));pp<-combine(lapply(app,function(j)predict_one(members[[j]]$tree,d[i,,drop=FALSE])),w[app],task,classes,option(a,'aggregation','probabilities'));c(list(id=d$id[i],applicable=app-1L,positiveMembers=sum(w[app]>0)),pp)});list(task=task,classes=classes,members=members,predictions=preds,outOfBag=scored(oob,d,task,classes))}\nboost<-function(a){if(option(a,'task','regression')!='regression')stop('regression boosting only');d<-normrows(a$rows,'regression');eligible<-d$weight>0&!is.na(d$y);W<-sum(d$weight[eligible]);if(!W)stop('positive eligible training');eta<-num(option(a,'learningRate','1/2'));stages<-option(a,'stages',3);if(is.null(stages)||stages!=floor(stages)||stages<0||stages>8||eta<0||eta>1)stop('supported rate/stages');initial<-if('initial'%in%names(a))num(a$initial)else sum(d$weight[eligible]*d$y[eligible])/W;train<-matrix(initial,nrow(d),stages+1L);query<-matrix(initial,nrow(a$queries),stages+1L);losses<-fits<-list();for(stage in 0:stages){sse<-sum(d$weight[eligible]*(d$y[eligible]-train[eligible,stage+1L])^2);losses[[stage+1L]]<-list(stage=stage,rawWeightedSSE=sse,MSE=sse/W,meanHalfSquaredLoss=sse/(2*W));if(stage==stages)break;residual<-d;residual$y<-d$y-train[,stage+1L];tree<-fit(residual,a,'regression',character());h<-vapply(seq_len(nrow(d)),function(i)predict_one(tree,d[i,,drop=FALSE])$prediction,0);qh<-vapply(seq_len(nrow(a$queries)),function(i)predict_one(tree,a$queries[i,,drop=FALSE])$prediction,0);stageRows<-lapply(seq_len(nrow(d)),function(i)list(id=d$id[i],before=train[i,stage+1L],residual=residual$y[i],negativeCoordinateDerivative=d$weight[i]*residual$y[i]/W,fit=h[i],addition=eta*h[i],after=train[i,stage+1L]+eta*h[i]));train[,stage+2L]<-train[,stage+1L]+eta*h;query[,stage+2L]<-query[,stage+1L]+eta*qh;norm<-sum(d$weight[eligible]*h[eligible]^2);fits[[stage+1L]]<-list(stage=stage+1L,tree=tree,rows=stageRows,queryFits=qh,norm=norm,predictedSSEDecrease=eta*(2-eta)*norm)};list(task='regression',initial=initial,learningRate=eta,stages=stages,training=train,queries=query,fits=fits,losses=losses,predictions=lapply(seq_len(nrow(a$queries)),function(i)list(id=a$queries$id[i],prediction=query[i,stages+1L],probabilities=numeric(),vote=NA_character_,prob=NA_character_)))}\nfixed_schedules<-function(ids,p,seed){state<-seed;choose<-function(n){limit<-floor(4294967296/n)*n;repeat{state<<-(1664525*state+1013904223)%%4294967296;if(state<limit)return(as.integer(state%%n))}};draws<-schedules<-list();for(member in 1:4){draws[[member]]<-vapply(seq_along(ids),function(i)ids[choose(length(ids))+1L],'');schedule<-setNames(vector('list',7),c('','L','R','LL','LR','RL','RR'));for(path in names(schedule)){order<-seq_len(p)-1L;if(p>1)for(j in seq(p-1L,1L)){k<-choose(j+1L);temp<-order[j+1L];order[j+1L]<-order[k+1L];order[k+1L]<-temp};schedule[[match(path,names(schedule))]]<-sort(order[seq_len(max(1L,floor(sqrt(p))))])};schedules[[member]]<-schedule};list(draws=draws,schedules=schedules)}\nread_sources<-function(src){read<-function(name)read.csv(file.path(src,name),check.names=FALSE,colClasses='character',na.strings=character(),fileEncoding='UTF-8-BOM');raw<-read('actual320-country-four-indicators-original-2020-2024.csv');country<-do.call(rbind,lapply(sort(unique(raw$countryISO3)),function(code)do.call(rbind,lapply(2020:2024,function(year){keys<-c('NY.GDP.PCAP.KD','NY.GDP.MKTP.KD.ZG','FP.CPI.TOTL.ZG','SP.DYN.LE00.IN');v<-vapply(keys,function(k)as.numeric(raw$originalValueToken[raw$countryISO3==code&raw$date==as.character(year)&raw$indicatorID==k]),0);data.frame(id=paste0(code,':',year),sourceRow=paste0(code,':',year),originalID=code,year=year,x0=v[1]/10000,x1=v[2],x2=v[3],y=v[4],weight=1,role=if(anyNA(v))'excluded'else if(year==2024)'outer-test'else'train')}))));raw<-read('actual3613-NLS-original52-fields-and-selection.csv');i<-seq_len(nrow(raw));x0<-suppressWarnings(as.numeric(raw$ed76));x1<-suppressWarnings(as.numeric(raw$age76));y<-suppressWarnings(as.numeric(raw$wage76))/100;person<-data.frame(id=paste0('person:',i),sourceRow=as.character(i),originalID=raw$id,x0=x0,x1=x1,y=y,weight=1,role=ifelse(is.na(x0)|is.na(x1)|is.na(y),'excluded',ifelse(i%%5==0,'outer-test','train')));raw<-read('actual3150-churn-original14-fields-and-selection.csv');i<-seq_len(nrow(raw));company<-data.frame(id=paste0('customer:',i),sourceRow=as.character(i),originalID='',x0=as.numeric(raw[['Call  Failure']]),x1=as.numeric(raw[['Subscription  Length']]),x2=as.numeric(raw[['Charge  Amount']]),y=raw$Churn,weight=1,role=ifelse(i%%5==0,'outer-test','train'));models<-list();for(index in 1:3){kind<-c('country','person','company')[index];d<-list(country,person,company)[[index]];task<-if(kind=='company')'classification'else'regression';s<-fixed_schedules(d$id[d$role=='train'],if(kind=='person')2L else 3L,20261102+7919*(index-1L));models[[kind]]<-list(records=d,task=task,classes=if(task=='classification')c('0','1')else character(),draws=s$draws,schedules=s$schedules,minLeaf=c(4L,50L,30L)[index])};models}\nrealdata<-function(models,kind,options=list()){if(is.null(options)||!is.list(options))stop('options object');m<-models[[kind]];d<-m$records;train<-d[d$role=='train',,drop=FALSE];test<-d[d$role=='outer-test',,drop=FALSE];method<-option(options,'method','forest');depth<-option(options,'maxDepth',2);count<-option(options,'memberCount',3);if(!method%in%c('bagging','forest','boost'))stop('known method');a<-list(rows=train,queries=test,task=m$task,classes=m$classes,maxDepth=depth,minLeaf=option(options,'minLeaf',m$minLeaf),minLeafWeight=0,minGain=0,missingRoute='best',learningRate=option(options,'learningRate','1/2'),stages=option(options,'stages',3));if(method=='boost')result<-boost(a)else{a$bootstrapDraws<-m$draws[seq_len(count)];a$nodeFeatures<-lapply(m$schedules[seq_len(count)],function(s)s[nchar(names(s))<depth]);result<-ensemble(a,method=='forest')};outer<-scored(result$predictions,normrows(test,m$task),m$task,m$classes);st<-stat(normrows(train,m$task),m$task,m$classes);constant<-list(prediction=st$pred,probabilities=st$p,vote=st$pred,prob=st$pred);baseline<-scored(lapply(test$id,function(id)c(list(id=id),constant)),normrows(test,m$task),m$task,m$classes);list(kind=kind,method=method,settings=a,train=train,test=test,result=result,outer=outer,baseline=baseline)}\nAPI<-\"boost\"\nINPUT<-list(rows=data.frame(id=c(\"0\",\"1\",\"2\",\"3\"),y=c(0,0,4,4),x0=c(0,1,2,3),stringsAsFactors=FALSE),queries=data.frame(id=c(\"q\"),x0=c(num(\"3/2\")),stringsAsFactors=FALSE),maxDepth=1,learningRate=\"1/2\",stages=2)\n\nrun_fixed<-function(api,a,out,src){\n r<-if(api=='variance')variance(a)else if(api=='aggregate')aggregate(a)else if(api%in%c('bagging','forest'))ensemble(a,api=='forest')else if(api=='boost')boost(a)else realdata(read_sources(src),a$kind)\n dir.create(out,recursive=TRUE,showWarnings=FALSE);summary<-list();points<-list();add<-function(x,y,s){if(!is.null(y)&&!is.na(y))points[[length(points)+1L]]<<-data.frame(x=x,y=as.numeric(y),series=s)}\n if(api=='variance'){summary<-r[c('B','varianceOfMean')];add(r$B,r$varianceOfMean,'Specified finite-B variance');xl<-'Number of members B';yl<-'Variance, stipulated units squared';title<-'Declared covariance model, not fitted trees'\n }else if(api=='aggregate'){p<-r$predictions[[1]];summary<-list(selectedPrediction=p$prediction);classification<-identical(a$task,'classification');if(classification){summary<-c(summary,list(voteLabel=p$vote,probabilityLabel=p$prob,meanProbability1=p$probabilities[2]));add(1,p$probabilities[2],'Mean probability of class 1');add(2,p$votes[2],'Label-vote share of class 1');xl<-'Aggregation (1=probability, 2=vote)';yl<-'Probability or vote share'}else{for(i in seq_along(a$members))add(i,num(a$members[[i]]$predictions$value[1]),'Member prediction');add(3,p$prediction,'Weighted mean');xl<-'Member 1, member 2, aggregate 3';yl<-'Prediction, assumed units'};title<-'Votes and probabilities are distinct objects'\n }else if(api%in%c('bagging','forest')){summary<-list(queryPrediction=r$predictions[[1]]$prediction,OOB.scoreable=r$outOfBag$eligibleRows,OOB.meanLoss=r$outOfBag$meanLoss);for(i in seq_len(nrow(a$rows)))add(i,a$rows$y[i],'Observed training outcome');for(i in seq_along(r$outOfBag$rows))add(i,r$outOfBag$rows[[i]]$prediction,'OOB prediction, when defined');xl<-'Original training ID order';yl<-'Outcome, assumed units';title<-'Repeated draws and ID-level OOB membership'\n }else if(api=='boost'){summary<-list(initial=r$initial,finalMSE=r$losses[[length(r$losses)]]$MSE,stages=r$stages);for(v in r$losses)add(v$stage,v$MSE,'Training MSE');xl<-'Boosting stage (0=initial)';yl<-'Weighted MSE, outcome units squared';title<-'Training descent does not certify held-out gain'\n }else{summary<-list(outer.scoreable=r$outer$eligibleRows,outer.meanLoss=r$outer$meanLoss,baseline.meanLoss=r$baseline$meanLoss,OOB.scoreable=r$result$outOfBag$eligibleRows,OOB.meanLoss=r$result$outOfBag$meanLoss);for(i in seq_along(r$outer$rows)){p<-r$outer$rows[[i]];add(i,as.numeric(p$actual),'Observed outcome');add(i,if(a$kind=='company')p$probabilities[2]else p$prediction,if(a$kind=='company')'Forest probability of class 1'else'Forest prediction')};xl<-'Outer-test source order, not a time path';yl<-if(a$kind=='company')'Churn label / probability'else if(a$kind=='country')'Period life expectancy, years'else'Nominal 1976 USD per hour';title<-'Fixed forest; outer labels did not fit the trees'}\n display<-function(v)if(is.null(v)||is.na(v))'undefined'else sprintf('%.9f',as.numeric(v));write.csv(data.frame(metric=names(summary),value=vapply(summary,display,'')),file.path(out,'summary.csv'),row.names=FALSE);pp<-do.call(rbind,points);write.csv(pp,file.path(out,'plot-points.csv'),row.names=FALSE);dput(r,file.path(out,'full-result.Rtext'));svg(file.path(out,'plot.svg'),width=5.6,height=4.6,pointsize=14);par(mar=c(5.8,5.8,5.3,1.2),mgp=c(3.7,1,0));xr<-range(pp$x);yr<-range(pp$y);if(diff(xr)==0)xr<-xr+c(-.5,.5);if(diff(yr)==0)yr<-yr+c(-.5,.5);plot(xr,yr,type='n',xlab=xl,ylab=yl,cex.lab=.78,axes=FALSE);axis(1,at=pretty(xr,3));axis(2,at=pretty(yr,4),las=1,cex.axis=.82);box();grid(col='#dddddd');cols<-c('#355c72','#a55336','#507956','#78568b');ss<-unique(pp$series);for(i in seq_along(ss)){v<-pp[pp$series==ss[i],];points(v$x,v$y,pch=16,cex=if(nrow(v)>100).35 else .85,col=adjustcolor(cols[i],if(nrow(v)>100).5 else 1))};legend('topleft',legend=ss,col=cols[seq_along(ss)],lty=0,pch=16,cex=.65,bty='n',inset=c(0,-.32),xpd=NA);mtext(title,side=3,line=3.9,cex=.6);dev.off();cat(paste(names(summary),vapply(summary,display,''),sep='=',collapse=', '),'\\n')\n}\nargs<-commandArgs(trailingOnly=TRUE)\ntryCatch(run_fixed(API,INPUT,if(length(args))args[1]else'fixed-results',if(length(args)>1)args[2]else'ml09-sources'),error=function(e){cat('Rejected declared input: ',conditionMessage(e),'\\n',file=stderr());quit(status=2)})\n",
        "inputFiles": [],
        "input": {
          "rows": [
            {
              "id": "0",
              "x": [
                0
              ],
              "y": 0
            },
            {
              "id": "1",
              "x": [
                1
              ],
              "y": 0
            },
            {
              "id": "2",
              "x": [
                2
              ],
              "y": 4
            },
            {
              "id": "3",
              "x": [
                3
              ],
              "y": 4
            }
          ],
          "queries": [
            {
              "id": "q",
              "x": [
                "3/2"
              ]
            }
          ],
          "maxDepth": 1,
          "learningRate": "1/2",
          "stages": 2
        },
        "returnCode": 0,
        "expectedFailure": false,
        "stdout": "initial=2.000000000, finalMSE=0.250000000, stages=2.000000000 \n",
        "stderr": "During startup - Warning messages:\n1: Setting LC_COLLATE=C.UTF-8 failed \n2: Setting LC_CTYPE=C.UTF-8 failed \n3: Setting LC_MONETARY=C.UTF-8 failed \n4: Setting LC_TIME=C.UTF-8 failed \n",
        "summary": {
          "initial": "2.000000000",
          "finalMSE": "0.250000000",
          "stages": "2.000000000"
        },
        "plotPoints": [
          {
            "x": "0",
            "y": "4",
            "series": "Training MSE"
          },
          {
            "x": "1",
            "y": "1",
            "series": "Training MSE"
          },
          {
            "x": "2",
            "y": "0.25",
            "series": "Training MSE"
          }
        ],
        "plotFile": "ml09-fixed-results/boost-two-stages-r/plot.svg",
        "plotSHA256": "9895dbe1bd5a7f7da30c711f2731f2a6652f833c7d07901b4cf78495c26e5c08",
        "files": [
          {
            "file": "ml09-fixed-results/boost-two-stages-r/full-result.Rtext",
            "sha256": "c94c84b0e463276c8ea791f3f2886d6e37c7593a39b9a3e622285c5644184496"
          },
          {
            "file": "ml09-fixed-results/boost-two-stages-r/plot-points.csv",
            "sha256": "bf008257b19201e77e4bc7363ba3968903ffae3f231f742b1a06063bbb2c7355"
          },
          {
            "file": "ml09-fixed-results/boost-two-stages-r/plot.svg",
            "sha256": "9895dbe1bd5a7f7da30c711f2731f2a6652f833c7d07901b4cf78495c26e5c08"
          },
          {
            "file": "ml09-fixed-results/boost-two-stages-r/summary.csv",
            "sha256": "8b1e2be9f68f020db90b7613c0112706b3c6ee17e0d03a1111d622f788b60aaf"
          }
        ],
        "scope": "Actually executed self-contained fixed example; current web controls execute separately. Python Fraction and finite-precision base R. Author gate, not independent peer."
      },
      "weighted-gradient": {
        "api": "boost",
        "variant": "weighted-gradient",
        "language": "r",
        "codeFile": "ml09-code/boost-weighted-gradient.R",
        "codeSHA256": "d214cb5ad3d20e2f7f66ed05d9c811963f444d1e4f580cc874618875c9ab7d60",
        "codeText": "# ML09 base-R reproduction from native original-field CSVs.\n# Rscript ml09-public-analysis.R ml09-sources results-r\n# Separately written vectorized direct-centered squared/Gini losses.\n# No Python/JS/model-contract/stored-answer/derived-result reader or package.\n# Numeric arithmetic is binary64:1e-12 relative tie tolerance stabilizes exact\n# source ties,but does not certify tiny margins/underflow like Fraction JS/Python.\n# Data-frame rows use x0,x1,...,y,weight; original IDs remain attached to draws.\noptions(stringsAsFactors=FALSE,digits=17)\nnum<-function(v){if(is.null(v)||length(v)!=1||is.na(v))stop('numeric parameter required, not explicit NULL');p<-strsplit(as.character(v),'/',fixed=TRUE)[[1]];z<-if(length(p)==2)as.numeric(p[1])/as.numeric(p[2])else as.numeric(v);if(!is.finite(z))stop('finite numeric parameter');z}\noption<-function(a,k,default){if(k%in%names(a))a[[k]]else default}\nnormrows<-function(d,task){if(!'weight'%in%names(d))d$weight<-1;if(!'id'%in%names(d))d$id<-as.character(seq_len(nrow(d))-1);d$weight<-as.numeric(d$weight);if(anyNA(d$weight)||any(d$weight<0))stop('nonnegative weights');if(task=='regression')d$y<-as.numeric(d$y)else d$y<-as.character(d$y);d}\nstat<-function(d,task,classes){W<-sum(d$weight);mu<-if(task=='regression'&&W)sum(d$weight*d$y)/W else NA_real_;p<-if(task=='classification'&&W)vapply(classes,function(c)sum(d$weight[d$y==c])/W,0)else numeric();risk<-if(task=='regression'&&W)sum(d$weight*(d$y-mu)^2)else W*sum(p*(1-p));list(n=nrow(d),w=W,mu=mu,p=unname(p),risk=risk,pred=if(task=='regression')mu else if(W)classes[which.max(p)]else NA_character_)}\nfit<-function(d,a,task,classes,schedule=NULL){d<-d[d$weight>0&!is.na(d$y),,drop=FALSE];if(!nrow(d))stop('positive observed training');W<-sum(d$weight);depth<-option(a,'maxDepth',2);minimum<-option(a,'minLeaf',1);minmass<-num(option(a,'minLeafWeight',0));mingain<-num(option(a,'minGain',0));route<-option(a,'missingRoute','best');features<-grep('^x[0-9]+$',names(d),value=TRUE)\n build<-function(rr,level,path){st<-stat(rr,task,classes);node<-list(rows=rr,st=st,split=NULL,left=NULL,right=NULL,path=path);if(level==depth)return(node);best<-NULL;allowed<-if(is.null(schedule))seq_along(features)-1L else schedule[[match(path,names(schedule))]]\n  for(j in seq_along(features)-1L){if(!j%in%allowed)next;v<-rr[[features[j+1L]]];values<-sort(unique(v[!is.na(v)]));candidates<-list()\n   if(length(values)>1)for(k in seq_len(length(values)-1L)){threshold<-(values[k]+values[k+1L])/2;missing<-is.na(v);left<-!missing&v<=threshold;right<-!missing&v>threshold;directions<-if(route!='best')route else if(any(missing))c('left','right')else if(sum(left)>=sum(right))'left'else'right';for(direction in directions)candidates[[length(candidates)+1L]]<-list(kind='threshold',threshold=threshold,missingRoute=direction,left=if(direction=='left')left|missing else left,right=if(direction=='right')right|missing else right)}\n   if(anyNA(v)&&any(!is.na(v)))candidates[[length(candidates)+1L]]<-list(kind='missing-only',threshold=NA_real_,missingRoute='left',left=is.na(v),right=!is.na(v))\n   for(candidate in candidates){l<-rr[candidate$left,,drop=FALSE];r<-rr[candidate$right,,drop=FALSE];ls<-stat(l,task,classes);rs<-stat(r,task,classes);if(min(ls$n,rs$n)<minimum||min(ls$w,rs$w)<minmass||min(ls$w,rs$w)<=0)next;gain<-(st$risk-ls$risk-rs$risk)/W;tol<-1e-12*max(1,abs(gain),if(is.null(best))0 else abs(best$gain));if(is.null(best)||gain>best$gain+tol)best<-c(candidate,list(feature=j,gain=gain,l=l,r=r))}\n  }\n  if(!is.null(best)&&best$gain>max(mingain,1e-12)){node$split<-best;node$left<-build(best$l,level+1L,paste0(path,'L'));node$right<-build(best$r,level+1L,paste0(path,'R'))};node\n };build(d,0L,'')\n}\npredict_one<-function(tree,row){n<-tree;while(!is.null(n$split)){s<-n$split;v<-as.numeric(row[[paste0('x',s$feature)]]);left<-if(s$kind=='missing-only')is.na(v)else if(is.na(v))s$missingRoute=='left'else v<=s$threshold;n<-if(left)n$left else n$right};list(prediction=n$st$pred,probabilities=n$st$p)}\ncombine<-function(pp,w,task,classes,mode='probabilities'){W<-sum(w);if(!length(pp)||!W)return(list(prediction=if(task=='regression')NA_real_ else NA_character_,probabilities=numeric(),vote=NA_character_,prob=NA_character_));if(task=='regression')return(list(prediction=sum(vapply(pp,function(p)p$prediction,0)*w)/W,probabilities=numeric(),vote=NA_character_,prob=NA_character_));votes<-vapply(classes,function(c)sum(w[vapply(pp,function(p)p$prediction==c,FALSE)])/W,0);probs<-vapply(seq_along(classes),function(j)sum(vapply(pp,function(p)p$probabilities[j],0)*w)/W,0);vote<-classes[which.max(votes)];prob<-classes[which.max(probs)];list(prediction=if(mode=='votes')vote else prob,probabilities=unname(probs),vote=vote,prob=prob,votes=unname(votes))}\nvariance<-function(a){B<-num(a$B);v<-num(a$marginalVariance);rho<-num(option(a,'rho',0));if(B<1||B!=floor(B)||v<0)stop('integer B/nonnegative variance');if(B>1&&v>0&&(rho< -1/(B-1)||rho>1))stop('PSD correlation');list(B=B,marginalVariance=v,correlationApplicable=B>1&&v>0,varianceOfMean=if(B==1)v else v*(1+(B-1)*rho)/B)}\naggregate<-function(a){task<-option(a,'task','regression');classes<-option(a,'classes',character());w<-vapply(option(a,'memberWeights',as.list(rep(1,length(a$members)))),num,0);if(any(w<0)||sum(w)<=0)stop('positive member mass');ids<-a$members[[1]]$predictions$id;pp<-lapply(ids,function(id){members<-lapply(a$members,function(m){r<-m$predictions[match(id,m$predictions$id),,drop=FALSE];if(task=='regression')list(prediction=num(r$value),probabilities=numeric())else list(prediction=as.character(r$label),probabilities=as.numeric(r[paste0('p',seq_along(classes)-1L)]))});c(list(id=id),combine(members,w,task,classes,option(a,'aggregation','probabilities')))});list(task=task,classes=classes,predictions=pp)}\nscored<-function(preds,d,task,classes){W<-loss<-absolute<-errors<-voteerrors<-0;count<-0L;out<-lapply(seq_len(nrow(d)),function(i){r<-d[i,,drop=FALSE];p<-preds[[i]];ok<-!is.na(p$prediction)&&!is.na(r$y)&&r$weight>0;value<-NA_real_;if(ok){count<<-count+1L;W<<-W+r$weight;if(task=='regression'){e<-r$y-p$prediction;value<-e*e;absolute<<-absolute+r$weight*abs(e)}else{value<-sum((p$probabilities-as.numeric(classes==r$y))^2);errors<<-errors+r$weight*(p$prediction!=r$y);voteerrors<<-voteerrors+r$weight*(p$vote!=r$y)};loss<<-loss+r$weight*value};c(p,list(actual=r$y,weight=r$weight,scoreEligible=ok,loss=value))});list(rows=out,eligibleRows=count,weight=W,totalLoss=loss,meanLoss=if(W)loss/W else NA_real_,MAE=if(W&&task=='regression')absolute/W else NA_real_,errorRate=if(W&&task=='classification')errors/W else NA_real_,labelVoteErrorRate=if(W&&task=='classification')voteerrors/W else NA_real_)}\nensemble<-function(a,forest=FALSE){task<-option(a,'task','regression');classes<-option(a,'classes',character());d<-normrows(a$rows,task);w<-vapply(option(a,'memberWeights',as.list(rep(1,length(a$bootstrapDraws)))),num,0);if(any(w<0)||sum(w)<=0)stop('positive member mass');members<-lapply(seq_along(a$bootstrapDraws),function(i){draw<-a$bootstrapDraws[[i]];indices<-match(draw,d$id);if(anyNA(indices))stop('unknown draw source');tree<-fit(d[indices,,drop=FALSE],a,task,classes,if(forest)a$nodeFeatures[[i]]else NULL);list(tree=tree,draw=draw,inbag=unique(draw),weight=w[i])});queries<-a$queries;preds<-lapply(seq_len(nrow(queries)),function(i)c(list(id=queries$id[i]),combine(lapply(members,function(m)predict_one(m$tree,queries[i,,drop=FALSE])),w,task,classes,option(a,'aggregation','probabilities'))));oob<-lapply(seq_len(nrow(d)),function(i){app<-which(!vapply(members,function(m)d$id[i]%in%m$inbag,FALSE));pp<-combine(lapply(app,function(j)predict_one(members[[j]]$tree,d[i,,drop=FALSE])),w[app],task,classes,option(a,'aggregation','probabilities'));c(list(id=d$id[i],applicable=app-1L,positiveMembers=sum(w[app]>0)),pp)});list(task=task,classes=classes,members=members,predictions=preds,outOfBag=scored(oob,d,task,classes))}\nboost<-function(a){if(option(a,'task','regression')!='regression')stop('regression boosting only');d<-normrows(a$rows,'regression');eligible<-d$weight>0&!is.na(d$y);W<-sum(d$weight[eligible]);if(!W)stop('positive eligible training');eta<-num(option(a,'learningRate','1/2'));stages<-option(a,'stages',3);if(is.null(stages)||stages!=floor(stages)||stages<0||stages>8||eta<0||eta>1)stop('supported rate/stages');initial<-if('initial'%in%names(a))num(a$initial)else sum(d$weight[eligible]*d$y[eligible])/W;train<-matrix(initial,nrow(d),stages+1L);query<-matrix(initial,nrow(a$queries),stages+1L);losses<-fits<-list();for(stage in 0:stages){sse<-sum(d$weight[eligible]*(d$y[eligible]-train[eligible,stage+1L])^2);losses[[stage+1L]]<-list(stage=stage,rawWeightedSSE=sse,MSE=sse/W,meanHalfSquaredLoss=sse/(2*W));if(stage==stages)break;residual<-d;residual$y<-d$y-train[,stage+1L];tree<-fit(residual,a,'regression',character());h<-vapply(seq_len(nrow(d)),function(i)predict_one(tree,d[i,,drop=FALSE])$prediction,0);qh<-vapply(seq_len(nrow(a$queries)),function(i)predict_one(tree,a$queries[i,,drop=FALSE])$prediction,0);stageRows<-lapply(seq_len(nrow(d)),function(i)list(id=d$id[i],before=train[i,stage+1L],residual=residual$y[i],negativeCoordinateDerivative=d$weight[i]*residual$y[i]/W,fit=h[i],addition=eta*h[i],after=train[i,stage+1L]+eta*h[i]));train[,stage+2L]<-train[,stage+1L]+eta*h;query[,stage+2L]<-query[,stage+1L]+eta*qh;norm<-sum(d$weight[eligible]*h[eligible]^2);fits[[stage+1L]]<-list(stage=stage+1L,tree=tree,rows=stageRows,queryFits=qh,norm=norm,predictedSSEDecrease=eta*(2-eta)*norm)};list(task='regression',initial=initial,learningRate=eta,stages=stages,training=train,queries=query,fits=fits,losses=losses,predictions=lapply(seq_len(nrow(a$queries)),function(i)list(id=a$queries$id[i],prediction=query[i,stages+1L],probabilities=numeric(),vote=NA_character_,prob=NA_character_)))}\nfixed_schedules<-function(ids,p,seed){state<-seed;choose<-function(n){limit<-floor(4294967296/n)*n;repeat{state<<-(1664525*state+1013904223)%%4294967296;if(state<limit)return(as.integer(state%%n))}};draws<-schedules<-list();for(member in 1:4){draws[[member]]<-vapply(seq_along(ids),function(i)ids[choose(length(ids))+1L],'');schedule<-setNames(vector('list',7),c('','L','R','LL','LR','RL','RR'));for(path in names(schedule)){order<-seq_len(p)-1L;if(p>1)for(j in seq(p-1L,1L)){k<-choose(j+1L);temp<-order[j+1L];order[j+1L]<-order[k+1L];order[k+1L]<-temp};schedule[[match(path,names(schedule))]]<-sort(order[seq_len(max(1L,floor(sqrt(p))))])};schedules[[member]]<-schedule};list(draws=draws,schedules=schedules)}\nread_sources<-function(src){read<-function(name)read.csv(file.path(src,name),check.names=FALSE,colClasses='character',na.strings=character(),fileEncoding='UTF-8-BOM');raw<-read('actual320-country-four-indicators-original-2020-2024.csv');country<-do.call(rbind,lapply(sort(unique(raw$countryISO3)),function(code)do.call(rbind,lapply(2020:2024,function(year){keys<-c('NY.GDP.PCAP.KD','NY.GDP.MKTP.KD.ZG','FP.CPI.TOTL.ZG','SP.DYN.LE00.IN');v<-vapply(keys,function(k)as.numeric(raw$originalValueToken[raw$countryISO3==code&raw$date==as.character(year)&raw$indicatorID==k]),0);data.frame(id=paste0(code,':',year),sourceRow=paste0(code,':',year),originalID=code,year=year,x0=v[1]/10000,x1=v[2],x2=v[3],y=v[4],weight=1,role=if(anyNA(v))'excluded'else if(year==2024)'outer-test'else'train')}))));raw<-read('actual3613-NLS-original52-fields-and-selection.csv');i<-seq_len(nrow(raw));x0<-suppressWarnings(as.numeric(raw$ed76));x1<-suppressWarnings(as.numeric(raw$age76));y<-suppressWarnings(as.numeric(raw$wage76))/100;person<-data.frame(id=paste0('person:',i),sourceRow=as.character(i),originalID=raw$id,x0=x0,x1=x1,y=y,weight=1,role=ifelse(is.na(x0)|is.na(x1)|is.na(y),'excluded',ifelse(i%%5==0,'outer-test','train')));raw<-read('actual3150-churn-original14-fields-and-selection.csv');i<-seq_len(nrow(raw));company<-data.frame(id=paste0('customer:',i),sourceRow=as.character(i),originalID='',x0=as.numeric(raw[['Call  Failure']]),x1=as.numeric(raw[['Subscription  Length']]),x2=as.numeric(raw[['Charge  Amount']]),y=raw$Churn,weight=1,role=ifelse(i%%5==0,'outer-test','train'));models<-list();for(index in 1:3){kind<-c('country','person','company')[index];d<-list(country,person,company)[[index]];task<-if(kind=='company')'classification'else'regression';s<-fixed_schedules(d$id[d$role=='train'],if(kind=='person')2L else 3L,20261102+7919*(index-1L));models[[kind]]<-list(records=d,task=task,classes=if(task=='classification')c('0','1')else character(),draws=s$draws,schedules=s$schedules,minLeaf=c(4L,50L,30L)[index])};models}\nrealdata<-function(models,kind,options=list()){if(is.null(options)||!is.list(options))stop('options object');m<-models[[kind]];d<-m$records;train<-d[d$role=='train',,drop=FALSE];test<-d[d$role=='outer-test',,drop=FALSE];method<-option(options,'method','forest');depth<-option(options,'maxDepth',2);count<-option(options,'memberCount',3);if(!method%in%c('bagging','forest','boost'))stop('known method');a<-list(rows=train,queries=test,task=m$task,classes=m$classes,maxDepth=depth,minLeaf=option(options,'minLeaf',m$minLeaf),minLeafWeight=0,minGain=0,missingRoute='best',learningRate=option(options,'learningRate','1/2'),stages=option(options,'stages',3));if(method=='boost')result<-boost(a)else{a$bootstrapDraws<-m$draws[seq_len(count)];a$nodeFeatures<-lapply(m$schedules[seq_len(count)],function(s)s[nchar(names(s))<depth]);result<-ensemble(a,method=='forest')};outer<-scored(result$predictions,normrows(test,m$task),m$task,m$classes);st<-stat(normrows(train,m$task),m$task,m$classes);constant<-list(prediction=st$pred,probabilities=st$p,vote=st$pred,prob=st$pred);baseline<-scored(lapply(test$id,function(id)c(list(id=id),constant)),normrows(test,m$task),m$task,m$classes);list(kind=kind,method=method,settings=a,train=train,test=test,result=result,outer=outer,baseline=baseline)}\nAPI<-\"boost\"\nINPUT<-list(rows=data.frame(id=c(\"a\",\"b\"),y=c(0,4),weight=c(3,1),x0=c(0,1),stringsAsFactors=FALSE),queries=data.frame(id=c(\"q\"),x0=c(1),stringsAsFactors=FALSE),maxDepth=1,learningRate=\"1/2\",stages=2)\n\nrun_fixed<-function(api,a,out,src){\n r<-if(api=='variance')variance(a)else if(api=='aggregate')aggregate(a)else if(api%in%c('bagging','forest'))ensemble(a,api=='forest')else if(api=='boost')boost(a)else realdata(read_sources(src),a$kind)\n dir.create(out,recursive=TRUE,showWarnings=FALSE);summary<-list();points<-list();add<-function(x,y,s){if(!is.null(y)&&!is.na(y))points[[length(points)+1L]]<<-data.frame(x=x,y=as.numeric(y),series=s)}\n if(api=='variance'){summary<-r[c('B','varianceOfMean')];add(r$B,r$varianceOfMean,'Specified finite-B variance');xl<-'Number of members B';yl<-'Variance, stipulated units squared';title<-'Declared covariance model, not fitted trees'\n }else if(api=='aggregate'){p<-r$predictions[[1]];summary<-list(selectedPrediction=p$prediction);classification<-identical(a$task,'classification');if(classification){summary<-c(summary,list(voteLabel=p$vote,probabilityLabel=p$prob,meanProbability1=p$probabilities[2]));add(1,p$probabilities[2],'Mean probability of class 1');add(2,p$votes[2],'Label-vote share of class 1');xl<-'Aggregation (1=probability, 2=vote)';yl<-'Probability or vote share'}else{for(i in seq_along(a$members))add(i,num(a$members[[i]]$predictions$value[1]),'Member prediction');add(3,p$prediction,'Weighted mean');xl<-'Member 1, member 2, aggregate 3';yl<-'Prediction, assumed units'};title<-'Votes and probabilities are distinct objects'\n }else if(api%in%c('bagging','forest')){summary<-list(queryPrediction=r$predictions[[1]]$prediction,OOB.scoreable=r$outOfBag$eligibleRows,OOB.meanLoss=r$outOfBag$meanLoss);for(i in seq_len(nrow(a$rows)))add(i,a$rows$y[i],'Observed training outcome');for(i in seq_along(r$outOfBag$rows))add(i,r$outOfBag$rows[[i]]$prediction,'OOB prediction, when defined');xl<-'Original training ID order';yl<-'Outcome, assumed units';title<-'Repeated draws and ID-level OOB membership'\n }else if(api=='boost'){summary<-list(initial=r$initial,finalMSE=r$losses[[length(r$losses)]]$MSE,stages=r$stages);for(v in r$losses)add(v$stage,v$MSE,'Training MSE');xl<-'Boosting stage (0=initial)';yl<-'Weighted MSE, outcome units squared';title<-'Training descent does not certify held-out gain'\n }else{summary<-list(outer.scoreable=r$outer$eligibleRows,outer.meanLoss=r$outer$meanLoss,baseline.meanLoss=r$baseline$meanLoss,OOB.scoreable=r$result$outOfBag$eligibleRows,OOB.meanLoss=r$result$outOfBag$meanLoss);for(i in seq_along(r$outer$rows)){p<-r$outer$rows[[i]];add(i,as.numeric(p$actual),'Observed outcome');add(i,if(a$kind=='company')p$probabilities[2]else p$prediction,if(a$kind=='company')'Forest probability of class 1'else'Forest prediction')};xl<-'Outer-test source order, not a time path';yl<-if(a$kind=='company')'Churn label / probability'else if(a$kind=='country')'Period life expectancy, years'else'Nominal 1976 USD per hour';title<-'Fixed forest; outer labels did not fit the trees'}\n display<-function(v)if(is.null(v)||is.na(v))'undefined'else sprintf('%.9f',as.numeric(v));write.csv(data.frame(metric=names(summary),value=vapply(summary,display,'')),file.path(out,'summary.csv'),row.names=FALSE);pp<-do.call(rbind,points);write.csv(pp,file.path(out,'plot-points.csv'),row.names=FALSE);dput(r,file.path(out,'full-result.Rtext'));svg(file.path(out,'plot.svg'),width=5.6,height=4.6,pointsize=14);par(mar=c(5.8,5.8,5.3,1.2),mgp=c(3.7,1,0));xr<-range(pp$x);yr<-range(pp$y);if(diff(xr)==0)xr<-xr+c(-.5,.5);if(diff(yr)==0)yr<-yr+c(-.5,.5);plot(xr,yr,type='n',xlab=xl,ylab=yl,cex.lab=.78,axes=FALSE);axis(1,at=pretty(xr,3));axis(2,at=pretty(yr,4),las=1,cex.axis=.82);box();grid(col='#dddddd');cols<-c('#355c72','#a55336','#507956','#78568b');ss<-unique(pp$series);for(i in seq_along(ss)){v<-pp[pp$series==ss[i],];points(v$x,v$y,pch=16,cex=if(nrow(v)>100).35 else .85,col=adjustcolor(cols[i],if(nrow(v)>100).5 else 1))};legend('topleft',legend=ss,col=cols[seq_along(ss)],lty=0,pch=16,cex=.65,bty='n',inset=c(0,-.32),xpd=NA);mtext(title,side=3,line=3.9,cex=.6);dev.off();cat(paste(names(summary),vapply(summary,display,''),sep='=',collapse=', '),'\\n')\n}\nargs<-commandArgs(trailingOnly=TRUE)\ntryCatch(run_fixed(API,INPUT,if(length(args))args[1]else'fixed-results',if(length(args)>1)args[2]else'ml09-sources'),error=function(e){cat('Rejected declared input: ',conditionMessage(e),'\\n',file=stderr());quit(status=2)})\n",
        "code": "# ML09 base-R reproduction from native original-field CSVs.\n# Rscript ml09-public-analysis.R ml09-sources results-r\n# Separately written vectorized direct-centered squared/Gini losses.\n# No Python/JS/model-contract/stored-answer/derived-result reader or package.\n# Numeric arithmetic is binary64:1e-12 relative tie tolerance stabilizes exact\n# source ties,but does not certify tiny margins/underflow like Fraction JS/Python.\n# Data-frame rows use x0,x1,...,y,weight; original IDs remain attached to draws.\noptions(stringsAsFactors=FALSE,digits=17)\nnum<-function(v){if(is.null(v)||length(v)!=1||is.na(v))stop('numeric parameter required, not explicit NULL');p<-strsplit(as.character(v),'/',fixed=TRUE)[[1]];z<-if(length(p)==2)as.numeric(p[1])/as.numeric(p[2])else as.numeric(v);if(!is.finite(z))stop('finite numeric parameter');z}\noption<-function(a,k,default){if(k%in%names(a))a[[k]]else default}\nnormrows<-function(d,task){if(!'weight'%in%names(d))d$weight<-1;if(!'id'%in%names(d))d$id<-as.character(seq_len(nrow(d))-1);d$weight<-as.numeric(d$weight);if(anyNA(d$weight)||any(d$weight<0))stop('nonnegative weights');if(task=='regression')d$y<-as.numeric(d$y)else d$y<-as.character(d$y);d}\nstat<-function(d,task,classes){W<-sum(d$weight);mu<-if(task=='regression'&&W)sum(d$weight*d$y)/W else NA_real_;p<-if(task=='classification'&&W)vapply(classes,function(c)sum(d$weight[d$y==c])/W,0)else numeric();risk<-if(task=='regression'&&W)sum(d$weight*(d$y-mu)^2)else W*sum(p*(1-p));list(n=nrow(d),w=W,mu=mu,p=unname(p),risk=risk,pred=if(task=='regression')mu else if(W)classes[which.max(p)]else NA_character_)}\nfit<-function(d,a,task,classes,schedule=NULL){d<-d[d$weight>0&!is.na(d$y),,drop=FALSE];if(!nrow(d))stop('positive observed training');W<-sum(d$weight);depth<-option(a,'maxDepth',2);minimum<-option(a,'minLeaf',1);minmass<-num(option(a,'minLeafWeight',0));mingain<-num(option(a,'minGain',0));route<-option(a,'missingRoute','best');features<-grep('^x[0-9]+$',names(d),value=TRUE)\n build<-function(rr,level,path){st<-stat(rr,task,classes);node<-list(rows=rr,st=st,split=NULL,left=NULL,right=NULL,path=path);if(level==depth)return(node);best<-NULL;allowed<-if(is.null(schedule))seq_along(features)-1L else schedule[[match(path,names(schedule))]]\n  for(j in seq_along(features)-1L){if(!j%in%allowed)next;v<-rr[[features[j+1L]]];values<-sort(unique(v[!is.na(v)]));candidates<-list()\n   if(length(values)>1)for(k in seq_len(length(values)-1L)){threshold<-(values[k]+values[k+1L])/2;missing<-is.na(v);left<-!missing&v<=threshold;right<-!missing&v>threshold;directions<-if(route!='best')route else if(any(missing))c('left','right')else if(sum(left)>=sum(right))'left'else'right';for(direction in directions)candidates[[length(candidates)+1L]]<-list(kind='threshold',threshold=threshold,missingRoute=direction,left=if(direction=='left')left|missing else left,right=if(direction=='right')right|missing else right)}\n   if(anyNA(v)&&any(!is.na(v)))candidates[[length(candidates)+1L]]<-list(kind='missing-only',threshold=NA_real_,missingRoute='left',left=is.na(v),right=!is.na(v))\n   for(candidate in candidates){l<-rr[candidate$left,,drop=FALSE];r<-rr[candidate$right,,drop=FALSE];ls<-stat(l,task,classes);rs<-stat(r,task,classes);if(min(ls$n,rs$n)<minimum||min(ls$w,rs$w)<minmass||min(ls$w,rs$w)<=0)next;gain<-(st$risk-ls$risk-rs$risk)/W;tol<-1e-12*max(1,abs(gain),if(is.null(best))0 else abs(best$gain));if(is.null(best)||gain>best$gain+tol)best<-c(candidate,list(feature=j,gain=gain,l=l,r=r))}\n  }\n  if(!is.null(best)&&best$gain>max(mingain,1e-12)){node$split<-best;node$left<-build(best$l,level+1L,paste0(path,'L'));node$right<-build(best$r,level+1L,paste0(path,'R'))};node\n };build(d,0L,'')\n}\npredict_one<-function(tree,row){n<-tree;while(!is.null(n$split)){s<-n$split;v<-as.numeric(row[[paste0('x',s$feature)]]);left<-if(s$kind=='missing-only')is.na(v)else if(is.na(v))s$missingRoute=='left'else v<=s$threshold;n<-if(left)n$left else n$right};list(prediction=n$st$pred,probabilities=n$st$p)}\ncombine<-function(pp,w,task,classes,mode='probabilities'){W<-sum(w);if(!length(pp)||!W)return(list(prediction=if(task=='regression')NA_real_ else NA_character_,probabilities=numeric(),vote=NA_character_,prob=NA_character_));if(task=='regression')return(list(prediction=sum(vapply(pp,function(p)p$prediction,0)*w)/W,probabilities=numeric(),vote=NA_character_,prob=NA_character_));votes<-vapply(classes,function(c)sum(w[vapply(pp,function(p)p$prediction==c,FALSE)])/W,0);probs<-vapply(seq_along(classes),function(j)sum(vapply(pp,function(p)p$probabilities[j],0)*w)/W,0);vote<-classes[which.max(votes)];prob<-classes[which.max(probs)];list(prediction=if(mode=='votes')vote else prob,probabilities=unname(probs),vote=vote,prob=prob,votes=unname(votes))}\nvariance<-function(a){B<-num(a$B);v<-num(a$marginalVariance);rho<-num(option(a,'rho',0));if(B<1||B!=floor(B)||v<0)stop('integer B/nonnegative variance');if(B>1&&v>0&&(rho< -1/(B-1)||rho>1))stop('PSD correlation');list(B=B,marginalVariance=v,correlationApplicable=B>1&&v>0,varianceOfMean=if(B==1)v else v*(1+(B-1)*rho)/B)}\naggregate<-function(a){task<-option(a,'task','regression');classes<-option(a,'classes',character());w<-vapply(option(a,'memberWeights',as.list(rep(1,length(a$members)))),num,0);if(any(w<0)||sum(w)<=0)stop('positive member mass');ids<-a$members[[1]]$predictions$id;pp<-lapply(ids,function(id){members<-lapply(a$members,function(m){r<-m$predictions[match(id,m$predictions$id),,drop=FALSE];if(task=='regression')list(prediction=num(r$value),probabilities=numeric())else list(prediction=as.character(r$label),probabilities=as.numeric(r[paste0('p',seq_along(classes)-1L)]))});c(list(id=id),combine(members,w,task,classes,option(a,'aggregation','probabilities')))});list(task=task,classes=classes,predictions=pp)}\nscored<-function(preds,d,task,classes){W<-loss<-absolute<-errors<-voteerrors<-0;count<-0L;out<-lapply(seq_len(nrow(d)),function(i){r<-d[i,,drop=FALSE];p<-preds[[i]];ok<-!is.na(p$prediction)&&!is.na(r$y)&&r$weight>0;value<-NA_real_;if(ok){count<<-count+1L;W<<-W+r$weight;if(task=='regression'){e<-r$y-p$prediction;value<-e*e;absolute<<-absolute+r$weight*abs(e)}else{value<-sum((p$probabilities-as.numeric(classes==r$y))^2);errors<<-errors+r$weight*(p$prediction!=r$y);voteerrors<<-voteerrors+r$weight*(p$vote!=r$y)};loss<<-loss+r$weight*value};c(p,list(actual=r$y,weight=r$weight,scoreEligible=ok,loss=value))});list(rows=out,eligibleRows=count,weight=W,totalLoss=loss,meanLoss=if(W)loss/W else NA_real_,MAE=if(W&&task=='regression')absolute/W else NA_real_,errorRate=if(W&&task=='classification')errors/W else NA_real_,labelVoteErrorRate=if(W&&task=='classification')voteerrors/W else NA_real_)}\nensemble<-function(a,forest=FALSE){task<-option(a,'task','regression');classes<-option(a,'classes',character());d<-normrows(a$rows,task);w<-vapply(option(a,'memberWeights',as.list(rep(1,length(a$bootstrapDraws)))),num,0);if(any(w<0)||sum(w)<=0)stop('positive member mass');members<-lapply(seq_along(a$bootstrapDraws),function(i){draw<-a$bootstrapDraws[[i]];indices<-match(draw,d$id);if(anyNA(indices))stop('unknown draw source');tree<-fit(d[indices,,drop=FALSE],a,task,classes,if(forest)a$nodeFeatures[[i]]else NULL);list(tree=tree,draw=draw,inbag=unique(draw),weight=w[i])});queries<-a$queries;preds<-lapply(seq_len(nrow(queries)),function(i)c(list(id=queries$id[i]),combine(lapply(members,function(m)predict_one(m$tree,queries[i,,drop=FALSE])),w,task,classes,option(a,'aggregation','probabilities'))));oob<-lapply(seq_len(nrow(d)),function(i){app<-which(!vapply(members,function(m)d$id[i]%in%m$inbag,FALSE));pp<-combine(lapply(app,function(j)predict_one(members[[j]]$tree,d[i,,drop=FALSE])),w[app],task,classes,option(a,'aggregation','probabilities'));c(list(id=d$id[i],applicable=app-1L,positiveMembers=sum(w[app]>0)),pp)});list(task=task,classes=classes,members=members,predictions=preds,outOfBag=scored(oob,d,task,classes))}\nboost<-function(a){if(option(a,'task','regression')!='regression')stop('regression boosting only');d<-normrows(a$rows,'regression');eligible<-d$weight>0&!is.na(d$y);W<-sum(d$weight[eligible]);if(!W)stop('positive eligible training');eta<-num(option(a,'learningRate','1/2'));stages<-option(a,'stages',3);if(is.null(stages)||stages!=floor(stages)||stages<0||stages>8||eta<0||eta>1)stop('supported rate/stages');initial<-if('initial'%in%names(a))num(a$initial)else sum(d$weight[eligible]*d$y[eligible])/W;train<-matrix(initial,nrow(d),stages+1L);query<-matrix(initial,nrow(a$queries),stages+1L);losses<-fits<-list();for(stage in 0:stages){sse<-sum(d$weight[eligible]*(d$y[eligible]-train[eligible,stage+1L])^2);losses[[stage+1L]]<-list(stage=stage,rawWeightedSSE=sse,MSE=sse/W,meanHalfSquaredLoss=sse/(2*W));if(stage==stages)break;residual<-d;residual$y<-d$y-train[,stage+1L];tree<-fit(residual,a,'regression',character());h<-vapply(seq_len(nrow(d)),function(i)predict_one(tree,d[i,,drop=FALSE])$prediction,0);qh<-vapply(seq_len(nrow(a$queries)),function(i)predict_one(tree,a$queries[i,,drop=FALSE])$prediction,0);stageRows<-lapply(seq_len(nrow(d)),function(i)list(id=d$id[i],before=train[i,stage+1L],residual=residual$y[i],negativeCoordinateDerivative=d$weight[i]*residual$y[i]/W,fit=h[i],addition=eta*h[i],after=train[i,stage+1L]+eta*h[i]));train[,stage+2L]<-train[,stage+1L]+eta*h;query[,stage+2L]<-query[,stage+1L]+eta*qh;norm<-sum(d$weight[eligible]*h[eligible]^2);fits[[stage+1L]]<-list(stage=stage+1L,tree=tree,rows=stageRows,queryFits=qh,norm=norm,predictedSSEDecrease=eta*(2-eta)*norm)};list(task='regression',initial=initial,learningRate=eta,stages=stages,training=train,queries=query,fits=fits,losses=losses,predictions=lapply(seq_len(nrow(a$queries)),function(i)list(id=a$queries$id[i],prediction=query[i,stages+1L],probabilities=numeric(),vote=NA_character_,prob=NA_character_)))}\nfixed_schedules<-function(ids,p,seed){state<-seed;choose<-function(n){limit<-floor(4294967296/n)*n;repeat{state<<-(1664525*state+1013904223)%%4294967296;if(state<limit)return(as.integer(state%%n))}};draws<-schedules<-list();for(member in 1:4){draws[[member]]<-vapply(seq_along(ids),function(i)ids[choose(length(ids))+1L],'');schedule<-setNames(vector('list',7),c('','L','R','LL','LR','RL','RR'));for(path in names(schedule)){order<-seq_len(p)-1L;if(p>1)for(j in seq(p-1L,1L)){k<-choose(j+1L);temp<-order[j+1L];order[j+1L]<-order[k+1L];order[k+1L]<-temp};schedule[[match(path,names(schedule))]]<-sort(order[seq_len(max(1L,floor(sqrt(p))))])};schedules[[member]]<-schedule};list(draws=draws,schedules=schedules)}\nread_sources<-function(src){read<-function(name)read.csv(file.path(src,name),check.names=FALSE,colClasses='character',na.strings=character(),fileEncoding='UTF-8-BOM');raw<-read('actual320-country-four-indicators-original-2020-2024.csv');country<-do.call(rbind,lapply(sort(unique(raw$countryISO3)),function(code)do.call(rbind,lapply(2020:2024,function(year){keys<-c('NY.GDP.PCAP.KD','NY.GDP.MKTP.KD.ZG','FP.CPI.TOTL.ZG','SP.DYN.LE00.IN');v<-vapply(keys,function(k)as.numeric(raw$originalValueToken[raw$countryISO3==code&raw$date==as.character(year)&raw$indicatorID==k]),0);data.frame(id=paste0(code,':',year),sourceRow=paste0(code,':',year),originalID=code,year=year,x0=v[1]/10000,x1=v[2],x2=v[3],y=v[4],weight=1,role=if(anyNA(v))'excluded'else if(year==2024)'outer-test'else'train')}))));raw<-read('actual3613-NLS-original52-fields-and-selection.csv');i<-seq_len(nrow(raw));x0<-suppressWarnings(as.numeric(raw$ed76));x1<-suppressWarnings(as.numeric(raw$age76));y<-suppressWarnings(as.numeric(raw$wage76))/100;person<-data.frame(id=paste0('person:',i),sourceRow=as.character(i),originalID=raw$id,x0=x0,x1=x1,y=y,weight=1,role=ifelse(is.na(x0)|is.na(x1)|is.na(y),'excluded',ifelse(i%%5==0,'outer-test','train')));raw<-read('actual3150-churn-original14-fields-and-selection.csv');i<-seq_len(nrow(raw));company<-data.frame(id=paste0('customer:',i),sourceRow=as.character(i),originalID='',x0=as.numeric(raw[['Call  Failure']]),x1=as.numeric(raw[['Subscription  Length']]),x2=as.numeric(raw[['Charge  Amount']]),y=raw$Churn,weight=1,role=ifelse(i%%5==0,'outer-test','train'));models<-list();for(index in 1:3){kind<-c('country','person','company')[index];d<-list(country,person,company)[[index]];task<-if(kind=='company')'classification'else'regression';s<-fixed_schedules(d$id[d$role=='train'],if(kind=='person')2L else 3L,20261102+7919*(index-1L));models[[kind]]<-list(records=d,task=task,classes=if(task=='classification')c('0','1')else character(),draws=s$draws,schedules=s$schedules,minLeaf=c(4L,50L,30L)[index])};models}\nrealdata<-function(models,kind,options=list()){if(is.null(options)||!is.list(options))stop('options object');m<-models[[kind]];d<-m$records;train<-d[d$role=='train',,drop=FALSE];test<-d[d$role=='outer-test',,drop=FALSE];method<-option(options,'method','forest');depth<-option(options,'maxDepth',2);count<-option(options,'memberCount',3);if(!method%in%c('bagging','forest','boost'))stop('known method');a<-list(rows=train,queries=test,task=m$task,classes=m$classes,maxDepth=depth,minLeaf=option(options,'minLeaf',m$minLeaf),minLeafWeight=0,minGain=0,missingRoute='best',learningRate=option(options,'learningRate','1/2'),stages=option(options,'stages',3));if(method=='boost')result<-boost(a)else{a$bootstrapDraws<-m$draws[seq_len(count)];a$nodeFeatures<-lapply(m$schedules[seq_len(count)],function(s)s[nchar(names(s))<depth]);result<-ensemble(a,method=='forest')};outer<-scored(result$predictions,normrows(test,m$task),m$task,m$classes);st<-stat(normrows(train,m$task),m$task,m$classes);constant<-list(prediction=st$pred,probabilities=st$p,vote=st$pred,prob=st$pred);baseline<-scored(lapply(test$id,function(id)c(list(id=id),constant)),normrows(test,m$task),m$task,m$classes);list(kind=kind,method=method,settings=a,train=train,test=test,result=result,outer=outer,baseline=baseline)}\nAPI<-\"boost\"\nINPUT<-list(rows=data.frame(id=c(\"a\",\"b\"),y=c(0,4),weight=c(3,1),x0=c(0,1),stringsAsFactors=FALSE),queries=data.frame(id=c(\"q\"),x0=c(1),stringsAsFactors=FALSE),maxDepth=1,learningRate=\"1/2\",stages=2)\n\nrun_fixed<-function(api,a,out,src){\n r<-if(api=='variance')variance(a)else if(api=='aggregate')aggregate(a)else if(api%in%c('bagging','forest'))ensemble(a,api=='forest')else if(api=='boost')boost(a)else realdata(read_sources(src),a$kind)\n dir.create(out,recursive=TRUE,showWarnings=FALSE);summary<-list();points<-list();add<-function(x,y,s){if(!is.null(y)&&!is.na(y))points[[length(points)+1L]]<<-data.frame(x=x,y=as.numeric(y),series=s)}\n if(api=='variance'){summary<-r[c('B','varianceOfMean')];add(r$B,r$varianceOfMean,'Specified finite-B variance');xl<-'Number of members B';yl<-'Variance, stipulated units squared';title<-'Declared covariance model, not fitted trees'\n }else if(api=='aggregate'){p<-r$predictions[[1]];summary<-list(selectedPrediction=p$prediction);classification<-identical(a$task,'classification');if(classification){summary<-c(summary,list(voteLabel=p$vote,probabilityLabel=p$prob,meanProbability1=p$probabilities[2]));add(1,p$probabilities[2],'Mean probability of class 1');add(2,p$votes[2],'Label-vote share of class 1');xl<-'Aggregation (1=probability, 2=vote)';yl<-'Probability or vote share'}else{for(i in seq_along(a$members))add(i,num(a$members[[i]]$predictions$value[1]),'Member prediction');add(3,p$prediction,'Weighted mean');xl<-'Member 1, member 2, aggregate 3';yl<-'Prediction, assumed units'};title<-'Votes and probabilities are distinct objects'\n }else if(api%in%c('bagging','forest')){summary<-list(queryPrediction=r$predictions[[1]]$prediction,OOB.scoreable=r$outOfBag$eligibleRows,OOB.meanLoss=r$outOfBag$meanLoss);for(i in seq_len(nrow(a$rows)))add(i,a$rows$y[i],'Observed training outcome');for(i in seq_along(r$outOfBag$rows))add(i,r$outOfBag$rows[[i]]$prediction,'OOB prediction, when defined');xl<-'Original training ID order';yl<-'Outcome, assumed units';title<-'Repeated draws and ID-level OOB membership'\n }else if(api=='boost'){summary<-list(initial=r$initial,finalMSE=r$losses[[length(r$losses)]]$MSE,stages=r$stages);for(v in r$losses)add(v$stage,v$MSE,'Training MSE');xl<-'Boosting stage (0=initial)';yl<-'Weighted MSE, outcome units squared';title<-'Training descent does not certify held-out gain'\n }else{summary<-list(outer.scoreable=r$outer$eligibleRows,outer.meanLoss=r$outer$meanLoss,baseline.meanLoss=r$baseline$meanLoss,OOB.scoreable=r$result$outOfBag$eligibleRows,OOB.meanLoss=r$result$outOfBag$meanLoss);for(i in seq_along(r$outer$rows)){p<-r$outer$rows[[i]];add(i,as.numeric(p$actual),'Observed outcome');add(i,if(a$kind=='company')p$probabilities[2]else p$prediction,if(a$kind=='company')'Forest probability of class 1'else'Forest prediction')};xl<-'Outer-test source order, not a time path';yl<-if(a$kind=='company')'Churn label / probability'else if(a$kind=='country')'Period life expectancy, years'else'Nominal 1976 USD per hour';title<-'Fixed forest; outer labels did not fit the trees'}\n display<-function(v)if(is.null(v)||is.na(v))'undefined'else sprintf('%.9f',as.numeric(v));write.csv(data.frame(metric=names(summary),value=vapply(summary,display,'')),file.path(out,'summary.csv'),row.names=FALSE);pp<-do.call(rbind,points);write.csv(pp,file.path(out,'plot-points.csv'),row.names=FALSE);dput(r,file.path(out,'full-result.Rtext'));svg(file.path(out,'plot.svg'),width=5.6,height=4.6,pointsize=14);par(mar=c(5.8,5.8,5.3,1.2),mgp=c(3.7,1,0));xr<-range(pp$x);yr<-range(pp$y);if(diff(xr)==0)xr<-xr+c(-.5,.5);if(diff(yr)==0)yr<-yr+c(-.5,.5);plot(xr,yr,type='n',xlab=xl,ylab=yl,cex.lab=.78,axes=FALSE);axis(1,at=pretty(xr,3));axis(2,at=pretty(yr,4),las=1,cex.axis=.82);box();grid(col='#dddddd');cols<-c('#355c72','#a55336','#507956','#78568b');ss<-unique(pp$series);for(i in seq_along(ss)){v<-pp[pp$series==ss[i],];points(v$x,v$y,pch=16,cex=if(nrow(v)>100).35 else .85,col=adjustcolor(cols[i],if(nrow(v)>100).5 else 1))};legend('topleft',legend=ss,col=cols[seq_along(ss)],lty=0,pch=16,cex=.65,bty='n',inset=c(0,-.32),xpd=NA);mtext(title,side=3,line=3.9,cex=.6);dev.off();cat(paste(names(summary),vapply(summary,display,''),sep='=',collapse=', '),'\\n')\n}\nargs<-commandArgs(trailingOnly=TRUE)\ntryCatch(run_fixed(API,INPUT,if(length(args))args[1]else'fixed-results',if(length(args)>1)args[2]else'ml09-sources'),error=function(e){cat('Rejected declared input: ',conditionMessage(e),'\\n',file=stderr());quit(status=2)})\n",
        "inputFiles": [],
        "input": {
          "rows": [
            {
              "id": "a",
              "x": [
                0
              ],
              "y": 0,
              "weight": 3
            },
            {
              "id": "b",
              "x": [
                1
              ],
              "y": 4,
              "weight": 1
            }
          ],
          "queries": [
            {
              "id": "q",
              "x": [
                1
              ]
            }
          ],
          "maxDepth": 1,
          "learningRate": "1/2",
          "stages": 2
        },
        "returnCode": 0,
        "expectedFailure": false,
        "stdout": "initial=1.000000000, finalMSE=0.187500000, stages=2.000000000 \n",
        "stderr": "During startup - Warning messages:\n1: Setting LC_COLLATE=C.UTF-8 failed \n2: Setting LC_CTYPE=C.UTF-8 failed \n3: Setting LC_MONETARY=C.UTF-8 failed \n4: Setting LC_TIME=C.UTF-8 failed \n",
        "summary": {
          "initial": "1.000000000",
          "finalMSE": "0.187500000",
          "stages": "2.000000000"
        },
        "plotPoints": [
          {
            "x": "0",
            "y": "3",
            "series": "Training MSE"
          },
          {
            "x": "1",
            "y": "0.75",
            "series": "Training MSE"
          },
          {
            "x": "2",
            "y": "0.1875",
            "series": "Training MSE"
          }
        ],
        "plotFile": "ml09-fixed-results/boost-weighted-gradient-r/plot.svg",
        "plotSHA256": "360136ed06d2d8eaf57dfb5fe271671e3694c4d9a1e7ddec9a927cf6a71062c2",
        "files": [
          {
            "file": "ml09-fixed-results/boost-weighted-gradient-r/full-result.Rtext",
            "sha256": "979e9e50c903103622d9f4d25cda6e440b5754e57768900d39bc5f679bdb4c81"
          },
          {
            "file": "ml09-fixed-results/boost-weighted-gradient-r/plot-points.csv",
            "sha256": "17835d516e93e293dc3f8de7070c39b4fcf30b516f04daef950394c156ec8740"
          },
          {
            "file": "ml09-fixed-results/boost-weighted-gradient-r/plot.svg",
            "sha256": "360136ed06d2d8eaf57dfb5fe271671e3694c4d9a1e7ddec9a927cf6a71062c2"
          },
          {
            "file": "ml09-fixed-results/boost-weighted-gradient-r/summary.csv",
            "sha256": "751116548541836ce8fc065e96b0c7ed1dc489d459b69df4d6c0ecf9a42af2e1"
          }
        ],
        "scope": "Actually executed self-contained fixed example; current web controls execute separately. Python Fraction and finite-precision base R. Author gate, not independent peer."
      }
    }
  },
  "realdata": {
    "python": {
      "country": {
        "api": "realdata",
        "variant": "country",
        "language": "python",
        "codeFile": "ml09-code/realdata-country.py",
        "codeSHA256": "35ab0b719782bc3c659b0fbeb991a720e28fee50a16d2eed90dddc0f33a31755",
        "codeText": "\"\"\"ML09 exact Fraction reproduction from native source fields.\n\npython ml09-public-analysis.py --source-dir ml09-sources --output-dir results\n\nThis authored educational implementation uses direct-centered leaf losses and\nexhaustive midpoint partitions. It reads no JS engine, model contract, checker,\nstored target answers or derived-result CSV. Its five tree arithmetic helpers\nwere copied from the author's own separate Fraction reference, not an independent\npeer. Parser/work budgets and display rounding of the production JS are separate.\nNumerical predictions/proper scores do not certify causal effects, calibration,\nIID OOB validity, survey representativeness or production parameter optimality.\n\"\"\"\nfrom pathlib import Path\nfrom fractions import Fraction as Q\nimport csv,json,math,itertools,argparse\n\ndef normalized(rows,task='regression'):\n return [dict(id=r.get('id',i),x=[None if x is None else Q(x)for x in r.get('x',[])],y=None if r['y']is None else str(r['y'])if task=='classification'else Q(r['y']),w=Q(r.get('weight',1)))for i,r in enumerate(rows)]\n\ndef totals(rows,task,classes):\n W=sum((r['w']for r in rows),Q());mu=sum((r['w']*r['y']for r in rows),Q())/W if task=='regression'and W else None\n probs=[sum((r['w']for r in rows if r['y']==c),Q())/W for c in classes]if task=='classification'and W else[]\n risk=sum((r['w']*(r['y']-mu)**2 for r in rows),Q())if task=='regression'and W else W*sum((p*(1-p)for p in probs),Q())\n return dict(n=len(rows),w=W,mu=mu,p=probs,risk=risk,pred=mu if task=='regression'else classes[max(range(len(probs)),key=lambda i:probs[i])]if probs else None)\n\ndef fit(rows,a,task,classes,schedule=None):\n good=[r for r in rows if r['w']>0 and r['y']is not None];root=totals(good,task,classes)['w'];depth=a.get('maxDepth',2);minimum=a.get('minLeaf',1);minmass=Q(a.get('minLeafWeight',0));mingain=Q(a.get('minGain',0));route=a.get('missingRoute','best')\n def build(rr,d,path):\n  st=totals(rr,task,classes);n=dict(rows=rr,st=st,split=None,left=None,right=None,path=path)\n  if d==depth:return n\n  best=None\n  for j in range(len(rr[0]['x'])):\n   if schedule is not None and j not in schedule[path]:continue\n   values=sorted({r['x'][j]for r in rr if r['x'][j]is not None});missing=[r for r in rr if r['x'][j]is None];observed=[r for r in rr if r['x'][j]is not None]\n   candidates=[]\n   for lo,hi in zip(values,values[1:]):\n    q=(lo+hi)/2;left=[r for r in observed if r['x'][j]<=q];right=[r for r in observed if r['x'][j]>q];directions=[route]if route!='best'else['left','right']if missing else['left'if len(left)>=len(right)else'right']\n    for direction in directions:candidates.append(('threshold',q,direction,left+missing if direction=='left'else left,right+missing if direction=='right'else right))\n   if missing and observed:candidates.append(('missing-only',None,'left',missing,observed))\n   for kind,q,direction,left,right in candidates:\n    l=totals(left,task,classes);r=totals(right,task,classes)\n    if min(l['n'],r['n'])<minimum or min(l['w'],r['w'])<minmass or min(l['w'],r['w'])<=0:continue\n    gain=(st['risk']-l['risk']-r['risk'])/root\n    if best is None or gain>best['gain']:best=dict(feature=j,kind=kind,threshold=q,missingRoute=direction,left=left,right=right,gain=gain)\n  if best and best['gain']>0 and best['gain']>mingain:\n   j=best['feature'];go=lambda r:r['x'][j]is None if best['kind']=='missing-only'else best['missingRoute']=='left'if r['x'][j]is None else r['x'][j]<=best['threshold'];n['split']=best;n['left']=build([r for r in rr if go(r)],d+1,path+'L');n['right']=build([r for r in rr if not go(r)],d+1,path+'R')\n  return n\n return build(good,0,'')\n\ndef predict(tree,x):\n n=tree\n while n['split']:\n  s=n['split'];v=x[s['feature']];left=v is None if s['kind']=='missing-only'else s['missingRoute']=='left'if v is None else v<=s['threshold'];n=n['left'if left else'right']\n return dict(prediction=n['st']['pred'],probabilities=n['st']['p'])\n\ndef combine(preds,w,task,classes,mode='probabilities'):\n mass=sum(w,Q())\n if not preds or not mass:return dict(prediction=None,probabilities=[],vote=None,prob=None)\n if task=='regression':return dict(prediction=sum((p['prediction']*v for p,v in zip(preds,w)),Q())/mass,probabilities=[],vote=None,prob=None)\n votes=[sum((v for p,v in zip(preds,w)if p['prediction']==c),Q())/mass for c in classes];ps=[sum((p['probabilities'][j]*v for p,v in zip(preds,w)),Q())/mass for j in range(len(classes))];vote=classes[max(range(len(classes)),key=lambda j:votes[j])];prob=classes[max(range(len(classes)),key=lambda j:ps[j])];return dict(prediction=vote if mode=='votes'else prob,probabilities=ps,vote=vote,prob=prob,votes=votes)\ndef number(v):\n if v is None or isinstance(v,bool):raise ValueError('explicit null/bool is not a numeric parameter')\n return Q(v)\ndef variance(a):\n B=a['B'];v=number(a['marginalVariance']);rho=number(a.get('rho',0))\n if not isinstance(B,int)or isinstance(B,bool)or B<1 or v<0:raise ValueError('positive integer B/nonnegative variance')\n if B>1 and v and not -Q(1,B-1)<=rho<=1:raise ValueError('equicorrelation PSD bound')\n return dict(B=B,marginalVariance=v,correlationApplicable=B>1 and bool(v),varianceOfMean=v if B==1 else v*(1+(B-1)*rho)/B)\ndef aggregate(a):\n task=a.get('task','regression');classes=[str(c)for c in a.get('classes',[])];members=a['members'];w=[number(v)for v in a.get('memberWeights',[1]*len(members))]\n if not members or min(w)<0 or sum(w)<=0:raise ValueError('nonnegative member weights/positive total')\n order=[p.get('id',i)for i,p in enumerate(members[0]['predictions'])];keys=lambda x:(type(x).__name__,x);lookup=[{keys(p.get('id',i)):p for i,p in enumerate(m['predictions'])}for m in members]\n if any(set(m)!={keys(v)for v in order}for m in lookup):raise ValueError('same query ID set')\n out=[]\n for pid in order:\n  predictions=[dict(prediction=number(m[keys(pid)]['value']),probabilities=[])if task=='regression'else dict(prediction=str(m[keys(pid)]['label']),probabilities=[number(v)for v in m[keys(pid)]['probabilities']])for m in lookup]\n  if task=='classification'and any(min(p['probabilities'])<0 or sum(p['probabilities'])!=1 for p in predictions):raise ValueError('probability simplex')\n  out.append(dict(id=pid,**combine(predictions,w,task,classes,a.get('aggregation','probabilities'))))\n return dict(task=task,classes=classes,predictions=out)\ndef scored(preds,rows,task,classes):\n mass=loss=absolute=errors=voteerrors=Q();out=[]\n for p,r in zip(preds,rows):\n  ok=p['prediction']is not None and r['y']is not None and r['w']>0;v=None\n  if ok:\n   mass+=r['w']\n   if task=='regression':e=r['y']-p['prediction'];v=e*e;absolute+=r['w']*abs(e)\n   else:v=sum(((q-(1 if r['y']==c else 0))**2 for c,q in zip(classes,p['probabilities'])),Q());errors+=r['w']*(p['prediction']!=r['y']);voteerrors+=r['w']*(p['vote']!=r['y'])\n   loss+=r['w']*v\n  out.append(dict(p,actual=r['y'],weight=r['w'],scoreEligible=ok,loss=v))\n return dict(rows=out,eligibleRows=sum(r['scoreEligible']for r in out),weight=mass,totalLoss=loss,meanLoss=loss/mass if mass else None,MAE=absolute/mass if mass and task=='regression'else None,errorRate=errors/mass if mass and task=='classification'else None,labelVoteErrorRate=voteerrors/mass if mass and task=='classification'else None)\ndef ensemble(a,forest=False):\n task=a.get('task','regression');classes=[str(v)for v in(a.get('classes')or[])];rr=normalized(a['rows'],task);key=lambda x:(type(x).__name__,x);lookup={key(r['id']):r for r in rr};weights=[number(v)for v in a.get('memberWeights',[1]*len(a['bootstrapDraws']))]\n if not any(r['w']>0 and r['y']is not None for r in rr)or min(weights)<0 or sum(weights)<=0:raise ValueError('positive eligible training and member weight')\n members=[]\n for i,draw in enumerate(a['bootstrapDraws']):\n  data=[lookup[key(v)]for v in draw];schedule=a['nodeFeatures'][i]if forest else None;model=fit(data,a,task,classes,schedule);inbag={key(v)for v in draw};members.append(dict(tree=model,draw=draw,inbag=inbag,weight=weights[i]))\n predictions=[]\n for q in a.get('queries',[]):predictions.append(dict(id=q['id'],**combine([predict(m['tree'],[None if v is None else number(v)for v in q['x']])for m in members],weights,task,classes,a.get('aggregation','probabilities'))))\n oob=[]\n for r in rr:\n  applicable=[i for i,m in enumerate(members)if key(r['id'])not in m['inbag']];p=combine([predict(members[i]['tree'],r['x'])for i in applicable],[weights[i]for i in applicable],task,classes,a.get('aggregation','probabilities'));oob.append(dict(id=r['id'],applicable=applicable,positiveMembers=sum(weights[i]>0 for i in applicable),**p))\n return dict(task=task,classes=classes,members=members,predictions=predictions,outOfBag=scored(oob,rr,task,classes))\ndef boost(a):\n if a.get('task','regression')!='regression':raise ValueError('regression boosting only')\n rr=normalized(a['rows']);good=[r for r in rr if r['w']and r['y']is not None];W=sum((r['w']for r in good),Q())\n if not W:raise ValueError('positive eligible training')\n eta=number(a.get('learningRate','1/2'));stages=a.get('stages',3)\n if not 0<=eta<=1 or not isinstance(stages,int)or isinstance(stages,bool)or not 0<=stages<=8:raise ValueError('supported rate/stages')\n initial=number(a['initial'])if'initial'in a else sum((r['w']*r['y']for r in good),Q())/W;training=[[initial]for r in rr];queries=[[initial]for q in a.get('queries',[])];fits=[];losses=[]\n for stage in range(stages+1):\n  sse=sum((r['w']*(r['y']-p[-1])**2 for r,p in zip(rr,training)if r['w']and r['y']is not None),Q());losses.append(dict(stage=stage,rawWeightedSSE=sse,MSE=sse/W,meanHalfSquaredLoss=sse/(2*W)))\n  if stage==stages:break\n  residuals=[dict(r,y=None if r['y']is None else r['y']-p[-1])for r,p in zip(rr,training)];tree=fit(residuals,a,'regression',[]);h=[predict(tree,r['x'])['prediction']for r in rr];qh=[predict(tree,[None if v is None else number(v)for v in q['x']])['prediction']for q in a.get('queries',[])];norm=sum((r['w']*v*v for r,v in zip(rr,h)if r['y']is not None),Q());stageRows=[]\n  for i,(r,p)in enumerate(zip(rr,training)):\n   residual=None if r['y']is None else r['y']-p[-1];stageRows.append(dict(id=r['id'],before=p[-1],residual=residual,negativeCoordinateDerivative=None if residual is None else r['w']*residual/W,fit=h[i],addition=eta*h[i],after=p[-1]+eta*h[i]));p.append(p[-1]+eta*h[i])\n  for p,v in zip(queries,qh):p.append(p[-1]+eta*v)\n  fits.append(dict(stage=stage+1,tree=tree,rows=stageRows,queryFits=qh,norm=norm,predictedSSEDecrease=eta*(2-eta)*norm))\n return dict(task='regression',initial=initial,learningRate=eta,stages=stages,training=training,queries=queries,fits=fits,losses=losses,predictions=[dict(id=q['id'],prediction=p[-1],probabilities=[],vote=None,prob=None)for q,p in zip(a.get('queries',[]),queries)])\nclass Stream:\n def __init__(self,state):self.state=state\n def choose(self,n):\n  limit=(1<<32)-((1<<32)%n)\n  while True:\n   self.state=(1664525*self.state+1013904223)&0xffffffff\n   if self.state<limit:return self.state%n\ndef fixed_schedules(ids,p,seed):\n stream=Stream(seed);draws=[];schedules=[];paths=['']+[p for d in[1,2]for p in map(''.join,itertools.product('LR',repeat=d))]\n for member in range(4):\n  draws.append([ids[stream.choose(len(ids))]for _ in range(len(ids))]);schedule={}\n  for path in paths:\n   order=list(range(p))\n   for j in range(p-1,0,-1):k=stream.choose(j+1);order[j],order[k]=order[k],order[j]\n   schedule[path]=sorted(order[:max(1,int(math.sqrt(p)))])\n  schedules.append(schedule)\n return draws,schedules\ndef csvread(file):\n with Path(file).open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))\ndef read_sources(source):\n source=Path(source);raw=csvread(source/'actual320-country-four-indicators-original-2020-2024.csv');lookup={(r['countryISO3'],int(r['date']),r['indicatorID']):r for r in raw};country=[]\n for code in sorted({r['countryISO3']for r in raw}):\n  for year in range(2020,2025):\n   cols=['NY.GDP.PCAP.KD','NY.GDP.MKTP.KD.ZG','FP.CPI.TOTL.ZG','SP.DYN.LE00.IN'];v=[lookup[code,year,k]['originalValueToken']for k in cols];x=[None if not z else Q(z)for z in v[:3]];x[0]=None if x[0]is None else x[0]/10000;y=None if not v[3]else Q(v[3]);eligible=y is not None and None not in x;country.append(dict(id=code+':'+str(year),sourceRow=code+':'+str(year),originalID=code,year=year,x=x,y=y,weight='1',role='excluded'if not eligible else'outer-test'if year==2024 else'train'))\n person=[]\n for i,r in enumerate(csvread(source/'actual3613-NLS-original52-fields-and-selection.csv'),1):\n  v=lambda k:None if r[k]=='.'else Q(r[k]);x=[v('ed76'),v('age76')];y=None if v('wage76')is None else v('wage76')/100;eligible=y is not None and None not in x;person.append(dict(id='person:'+str(i),sourceRow=str(i),originalID=r['id'],x=x,y=y,weight='1',role='excluded'if not eligible else'outer-test'if i%5==0 else'train'))\n company=[]\n for i,r in enumerate(csvread(source/'actual3150-churn-original14-fields-and-selection.csv'),1):company.append(dict(id='customer:'+str(i),sourceRow=str(i),originalID='',x=[Q(r[k])for k in['Call  Failure','Subscription  Length','Charge  Amount']],y=r['Churn'],weight='1',role='outer-test'if i%5==0 else'train'))\n models={}\n for index,(kind,rr,task,leaf)in enumerate([('country',country,'regression',4),('person',person,'regression',50),('company',company,'classification',30)]):\n  ids=[r['id']for r in rr if r['role']=='train'];draws,schedules=fixed_schedules(ids,len(rr[0]['x']),20261102+7919*index);models[kind]=dict(records=rr,task=task,classes=['0','1']if task=='classification'else[],draws=draws,schedules=schedules,minLeaf=leaf)\n return models\n_OMITTED=object()\ndef realdata(models,kind,options=_OMITTED):\n options={}if options is _OMITTED else options\n if not isinstance(options,dict):raise ValueError('options object required, not explicit null')\n m=models[kind];train=[r for r in m['records']if r['role']=='train'];test=[r for r in m['records']if r['role']=='outer-test'];method=options.get('method','forest');depth=options.get('maxDepth',2);count=options.get('memberCount',3);a=dict(rows=train,queries=[dict(id=r['id'],x=r['x'])for r in test],task=m['task'],classes=m['classes'],maxDepth=depth,minLeaf=options.get('minLeaf',m['minLeaf']),minLeafWeight='0',minGain='0',missingRoute='best',learningRate=options.get('learningRate','1/2'),stages=options.get('stages',3))\n if method not in ['bagging','forest','boost']:raise ValueError('known source method')\n if not isinstance(depth,int)or isinstance(depth,bool)or not 0<=depth<=3:raise ValueError('source depth0..3')\n if method!='boost'and(not isinstance(count,int)or isinstance(count,bool)or not 1<=count<=4):raise ValueError('source member count1..4')\n if method=='boost':result=boost(a)\n else:\n  a.update(bootstrapDraws=m['draws'][:count],nodeFeatures=[{p:v for p,v in s.items()if len(p)<depth}for s in m['schedules'][:count]]);result=ensemble(a,method=='forest')\n outer=scored(result['predictions'],normalized(test,m['task']),m['task'],m['classes']);st=totals([r for r in normalized(train,m['task'])if r['w']and r['y']is not None],m['task'],m['classes']);constant=dict(prediction=st['pred'],probabilities=st['p'],vote=st['pred'],prob=st['pred']);baseline=scored([dict(id=r['id'],**constant)for r in test],normalized(test,m['task']),m['task'],m['classes']);return dict(kind=kind,method=method,settings=a,train=train,test=test,result=result,outer=outer,baseline=baseline)\ndef serial(x):\n if isinstance(x,Q):return str(x)\n if isinstance(x,dict):return{k:serial(v)for k,v in x.items()if k not in['inbag','tree']}\n if isinstance(x,(list,tuple)):return[serial(v)for v in x]\n return x\ndef writecsv(file,heads,rows):\n with Path(file).open('w',encoding='utf8',newline='')as f:\n  w=csv.writer(f);w.writerow(heads);w.writerows([[''if v is None else str(v)for v in r]for r in rows])\nAPI='realdata'\nINPUT={'kind': 'country'}\n\ndef run_fixed(api,a,out,src):\n import matplotlib\n matplotlib.use('svg')\n import matplotlib.pyplot as plt\n from matplotlib.ticker import MaxNLocator\n plt.rcParams.update({'font.size':14,'svg.fonttype':'none','svg.hashsalt':'ml09-fixed-v1'})\n result=variance(a)if api=='variance'else aggregate(a)if api=='aggregate'else ensemble(a,api=='forest')if api in ['bagging','forest']else boost(a)if api=='boost'else realdata(read_sources(src),a['kind'])\n out=Path(out);out.mkdir(parents=True,exist_ok=True);summary={};points=[]\n def add(x,y,s):\n  if y is not None:points.append([x,y,s])\n if api=='variance':\n  summary={'B':result['B'],'varianceOfMean':result['varianceOfMean']};add(result['B'],result['varianceOfMean'],'Specified finite-B variance');xl='Number of members B';yl='Variance, stipulated units squared';title='Declared covariance model, not fitted trees'\n elif api=='aggregate':\n  p=result['predictions'][0];classification=a.get('task')=='classification';summary={'selectedPrediction':p['prediction']}\n  if classification:\n   summary.update(voteLabel=p['vote'],probabilityLabel=p['prob'],meanProbability1=p['probabilities'][1]);add(1,p['probabilities'][1],'Mean probability of class 1');add(2,p['votes'][1],'Label-vote share of class 1');xl='Aggregation (1=probability, 2=vote)';yl='Probability or vote share'\n  else:\n   for i,m in enumerate(a['members']):add(i+1,Q(m['predictions'][0]['value']),'Member prediction')\n   add(3,p['prediction'],'Weighted mean');xl='Member 1, member 2, aggregate 3';yl='Prediction, assumed units'\n  title='Votes and probabilities are distinct objects'\n elif api in ['bagging','forest']:\n  summary={'queryPrediction':result['predictions'][0]['prediction'],'OOB.scoreable':result['outOfBag']['eligibleRows'],'OOB.meanLoss':result['outOfBag']['meanLoss']}\n  for i,r in enumerate(a['rows']):add(i+1,Q(r['y']),'Observed training outcome')\n  for i,p in enumerate(result['outOfBag']['rows']):add(i+1,p['prediction'],'OOB prediction, when defined')\n  xl='Original training ID order';yl='Outcome, assumed units';title='Repeated draws and ID-level OOB membership'\n elif api=='boost':\n  summary={'initial':result['initial'],'finalMSE':result['losses'][-1]['MSE'],'stages':result['stages']}\n  for r in result['losses']:add(r['stage'],r['MSE'],'Training MSE')\n  xl='Boosting stage (0=initial)';yl='Weighted MSE, outcome units squared';title='Training descent does not certify held-out gain'\n else:\n  summary={'outer.scoreable':result['outer']['eligibleRows'],'outer.meanLoss':result['outer']['meanLoss'],'baseline.meanLoss':result['baseline']['meanLoss'],'OOB.scoreable':result['result']['outOfBag']['eligibleRows'],'OOB.meanLoss':result['result']['outOfBag']['meanLoss']}\n  for i,p in enumerate(result['outer']['rows']):\n   add(i+1,Q(p['actual']),'Observed outcome');add(i+1,p['probabilities'][1]if a['kind']=='company'else p['prediction'],'Forest probability of class 1'if a['kind']=='company'else'Forest prediction')\n  xl='Outer-test source order, not a time path';yl='Churn label / probability'if a['kind']=='company'else'Period life expectancy, years'if a['kind']=='country'else'Nominal 1976 USD per hour';title='Fixed forest; outer labels did not fit the trees'\n def display(v):return 'undefined'if v is None else format(float(v),'.9f')\n writecsv(out/'summary.csv',['metric','value'],[[k,display(v)]for k,v in summary.items()]);writecsv(out/'plot-points.csv',['x','y','series'],points);(out/'full.json').write_text(json.dumps(serial(result),indent=2)+'\\n',encoding='utf8')\n fig,ax=plt.subplots(figsize=(5.6,4.6));fig.subplots_adjust(left=.24,right=.96,bottom=.24,top=.76);colors=['#355c72','#a55336','#507956','#78568b']\n for i,s in enumerate(dict.fromkeys(p[2]for p in points)):\n  pp=[p for p in points if p[2]==s];ax.scatter([float(p[0])for p in pp],[float(p[1])for p in pp],s=12 if len(pp)>100 else 32,alpha=.5 if len(pp)>100 else 1,color=colors[i%4],label=s)\n ax.set_xlabel(xl,labelpad=10,fontsize=11);ax.set_ylabel(yl,labelpad=10,fontsize=11);ax.xaxis.set_major_locator(MaxNLocator(3));ax.yaxis.set_major_locator(MaxNLocator(4));ax.grid(alpha=.18);ax.legend(loc='lower left',bbox_to_anchor=(0,1.01),fontsize=9,frameon=False);fig.suptitle(title,fontsize=9,y=.99);fig.savefig(out/'plot.svg',metadata={'Date':None});plt.close(fig);print(', '.join(k+'='+display(v)for k,v in summary.items()))\nif __name__=='__main__':\n import sys\n try:run_fixed(API,INPUT,sys.argv[1]if len(sys.argv)>1 else'fixed-results',sys.argv[2]if len(sys.argv)>2 else'ml09-sources')\n except ValueError as error:print('Rejected declared input: '+str(error),file=sys.stderr);sys.exit(2)\n",
        "code": "\"\"\"ML09 exact Fraction reproduction from native source fields.\n\npython ml09-public-analysis.py --source-dir ml09-sources --output-dir results\n\nThis authored educational implementation uses direct-centered leaf losses and\nexhaustive midpoint partitions. It reads no JS engine, model contract, checker,\nstored target answers or derived-result CSV. Its five tree arithmetic helpers\nwere copied from the author's own separate Fraction reference, not an independent\npeer. Parser/work budgets and display rounding of the production JS are separate.\nNumerical predictions/proper scores do not certify causal effects, calibration,\nIID OOB validity, survey representativeness or production parameter optimality.\n\"\"\"\nfrom pathlib import Path\nfrom fractions import Fraction as Q\nimport csv,json,math,itertools,argparse\n\ndef normalized(rows,task='regression'):\n return [dict(id=r.get('id',i),x=[None if x is None else Q(x)for x in r.get('x',[])],y=None if r['y']is None else str(r['y'])if task=='classification'else Q(r['y']),w=Q(r.get('weight',1)))for i,r in enumerate(rows)]\n\ndef totals(rows,task,classes):\n W=sum((r['w']for r in rows),Q());mu=sum((r['w']*r['y']for r in rows),Q())/W if task=='regression'and W else None\n probs=[sum((r['w']for r in rows if r['y']==c),Q())/W for c in classes]if task=='classification'and W else[]\n risk=sum((r['w']*(r['y']-mu)**2 for r in rows),Q())if task=='regression'and W else W*sum((p*(1-p)for p in probs),Q())\n return dict(n=len(rows),w=W,mu=mu,p=probs,risk=risk,pred=mu if task=='regression'else classes[max(range(len(probs)),key=lambda i:probs[i])]if probs else None)\n\ndef fit(rows,a,task,classes,schedule=None):\n good=[r for r in rows if r['w']>0 and r['y']is not None];root=totals(good,task,classes)['w'];depth=a.get('maxDepth',2);minimum=a.get('minLeaf',1);minmass=Q(a.get('minLeafWeight',0));mingain=Q(a.get('minGain',0));route=a.get('missingRoute','best')\n def build(rr,d,path):\n  st=totals(rr,task,classes);n=dict(rows=rr,st=st,split=None,left=None,right=None,path=path)\n  if d==depth:return n\n  best=None\n  for j in range(len(rr[0]['x'])):\n   if schedule is not None and j not in schedule[path]:continue\n   values=sorted({r['x'][j]for r in rr if r['x'][j]is not None});missing=[r for r in rr if r['x'][j]is None];observed=[r for r in rr if r['x'][j]is not None]\n   candidates=[]\n   for lo,hi in zip(values,values[1:]):\n    q=(lo+hi)/2;left=[r for r in observed if r['x'][j]<=q];right=[r for r in observed if r['x'][j]>q];directions=[route]if route!='best'else['left','right']if missing else['left'if len(left)>=len(right)else'right']\n    for direction in directions:candidates.append(('threshold',q,direction,left+missing if direction=='left'else left,right+missing if direction=='right'else right))\n   if missing and observed:candidates.append(('missing-only',None,'left',missing,observed))\n   for kind,q,direction,left,right in candidates:\n    l=totals(left,task,classes);r=totals(right,task,classes)\n    if min(l['n'],r['n'])<minimum or min(l['w'],r['w'])<minmass or min(l['w'],r['w'])<=0:continue\n    gain=(st['risk']-l['risk']-r['risk'])/root\n    if best is None or gain>best['gain']:best=dict(feature=j,kind=kind,threshold=q,missingRoute=direction,left=left,right=right,gain=gain)\n  if best and best['gain']>0 and best['gain']>mingain:\n   j=best['feature'];go=lambda r:r['x'][j]is None if best['kind']=='missing-only'else best['missingRoute']=='left'if r['x'][j]is None else r['x'][j]<=best['threshold'];n['split']=best;n['left']=build([r for r in rr if go(r)],d+1,path+'L');n['right']=build([r for r in rr if not go(r)],d+1,path+'R')\n  return n\n return build(good,0,'')\n\ndef predict(tree,x):\n n=tree\n while n['split']:\n  s=n['split'];v=x[s['feature']];left=v is None if s['kind']=='missing-only'else s['missingRoute']=='left'if v is None else v<=s['threshold'];n=n['left'if left else'right']\n return dict(prediction=n['st']['pred'],probabilities=n['st']['p'])\n\ndef combine(preds,w,task,classes,mode='probabilities'):\n mass=sum(w,Q())\n if not preds or not mass:return dict(prediction=None,probabilities=[],vote=None,prob=None)\n if task=='regression':return dict(prediction=sum((p['prediction']*v for p,v in zip(preds,w)),Q())/mass,probabilities=[],vote=None,prob=None)\n votes=[sum((v for p,v in zip(preds,w)if p['prediction']==c),Q())/mass for c in classes];ps=[sum((p['probabilities'][j]*v for p,v in zip(preds,w)),Q())/mass for j in range(len(classes))];vote=classes[max(range(len(classes)),key=lambda j:votes[j])];prob=classes[max(range(len(classes)),key=lambda j:ps[j])];return dict(prediction=vote if mode=='votes'else prob,probabilities=ps,vote=vote,prob=prob,votes=votes)\ndef number(v):\n if v is None or isinstance(v,bool):raise ValueError('explicit null/bool is not a numeric parameter')\n return Q(v)\ndef variance(a):\n B=a['B'];v=number(a['marginalVariance']);rho=number(a.get('rho',0))\n if not isinstance(B,int)or isinstance(B,bool)or B<1 or v<0:raise ValueError('positive integer B/nonnegative variance')\n if B>1 and v and not -Q(1,B-1)<=rho<=1:raise ValueError('equicorrelation PSD bound')\n return dict(B=B,marginalVariance=v,correlationApplicable=B>1 and bool(v),varianceOfMean=v if B==1 else v*(1+(B-1)*rho)/B)\ndef aggregate(a):\n task=a.get('task','regression');classes=[str(c)for c in a.get('classes',[])];members=a['members'];w=[number(v)for v in a.get('memberWeights',[1]*len(members))]\n if not members or min(w)<0 or sum(w)<=0:raise ValueError('nonnegative member weights/positive total')\n order=[p.get('id',i)for i,p in enumerate(members[0]['predictions'])];keys=lambda x:(type(x).__name__,x);lookup=[{keys(p.get('id',i)):p for i,p in enumerate(m['predictions'])}for m in members]\n if any(set(m)!={keys(v)for v in order}for m in lookup):raise ValueError('same query ID set')\n out=[]\n for pid in order:\n  predictions=[dict(prediction=number(m[keys(pid)]['value']),probabilities=[])if task=='regression'else dict(prediction=str(m[keys(pid)]['label']),probabilities=[number(v)for v in m[keys(pid)]['probabilities']])for m in lookup]\n  if task=='classification'and any(min(p['probabilities'])<0 or sum(p['probabilities'])!=1 for p in predictions):raise ValueError('probability simplex')\n  out.append(dict(id=pid,**combine(predictions,w,task,classes,a.get('aggregation','probabilities'))))\n return dict(task=task,classes=classes,predictions=out)\ndef scored(preds,rows,task,classes):\n mass=loss=absolute=errors=voteerrors=Q();out=[]\n for p,r in zip(preds,rows):\n  ok=p['prediction']is not None and r['y']is not None and r['w']>0;v=None\n  if ok:\n   mass+=r['w']\n   if task=='regression':e=r['y']-p['prediction'];v=e*e;absolute+=r['w']*abs(e)\n   else:v=sum(((q-(1 if r['y']==c else 0))**2 for c,q in zip(classes,p['probabilities'])),Q());errors+=r['w']*(p['prediction']!=r['y']);voteerrors+=r['w']*(p['vote']!=r['y'])\n   loss+=r['w']*v\n  out.append(dict(p,actual=r['y'],weight=r['w'],scoreEligible=ok,loss=v))\n return dict(rows=out,eligibleRows=sum(r['scoreEligible']for r in out),weight=mass,totalLoss=loss,meanLoss=loss/mass if mass else None,MAE=absolute/mass if mass and task=='regression'else None,errorRate=errors/mass if mass and task=='classification'else None,labelVoteErrorRate=voteerrors/mass if mass and task=='classification'else None)\ndef ensemble(a,forest=False):\n task=a.get('task','regression');classes=[str(v)for v in(a.get('classes')or[])];rr=normalized(a['rows'],task);key=lambda x:(type(x).__name__,x);lookup={key(r['id']):r for r in rr};weights=[number(v)for v in a.get('memberWeights',[1]*len(a['bootstrapDraws']))]\n if not any(r['w']>0 and r['y']is not None for r in rr)or min(weights)<0 or sum(weights)<=0:raise ValueError('positive eligible training and member weight')\n members=[]\n for i,draw in enumerate(a['bootstrapDraws']):\n  data=[lookup[key(v)]for v in draw];schedule=a['nodeFeatures'][i]if forest else None;model=fit(data,a,task,classes,schedule);inbag={key(v)for v in draw};members.append(dict(tree=model,draw=draw,inbag=inbag,weight=weights[i]))\n predictions=[]\n for q in a.get('queries',[]):predictions.append(dict(id=q['id'],**combine([predict(m['tree'],[None if v is None else number(v)for v in q['x']])for m in members],weights,task,classes,a.get('aggregation','probabilities'))))\n oob=[]\n for r in rr:\n  applicable=[i for i,m in enumerate(members)if key(r['id'])not in m['inbag']];p=combine([predict(members[i]['tree'],r['x'])for i in applicable],[weights[i]for i in applicable],task,classes,a.get('aggregation','probabilities'));oob.append(dict(id=r['id'],applicable=applicable,positiveMembers=sum(weights[i]>0 for i in applicable),**p))\n return dict(task=task,classes=classes,members=members,predictions=predictions,outOfBag=scored(oob,rr,task,classes))\ndef boost(a):\n if a.get('task','regression')!='regression':raise ValueError('regression boosting only')\n rr=normalized(a['rows']);good=[r for r in rr if r['w']and r['y']is not None];W=sum((r['w']for r in good),Q())\n if not W:raise ValueError('positive eligible training')\n eta=number(a.get('learningRate','1/2'));stages=a.get('stages',3)\n if not 0<=eta<=1 or not isinstance(stages,int)or isinstance(stages,bool)or not 0<=stages<=8:raise ValueError('supported rate/stages')\n initial=number(a['initial'])if'initial'in a else sum((r['w']*r['y']for r in good),Q())/W;training=[[initial]for r in rr];queries=[[initial]for q in a.get('queries',[])];fits=[];losses=[]\n for stage in range(stages+1):\n  sse=sum((r['w']*(r['y']-p[-1])**2 for r,p in zip(rr,training)if r['w']and r['y']is not None),Q());losses.append(dict(stage=stage,rawWeightedSSE=sse,MSE=sse/W,meanHalfSquaredLoss=sse/(2*W)))\n  if stage==stages:break\n  residuals=[dict(r,y=None if r['y']is None else r['y']-p[-1])for r,p in zip(rr,training)];tree=fit(residuals,a,'regression',[]);h=[predict(tree,r['x'])['prediction']for r in rr];qh=[predict(tree,[None if v is None else number(v)for v in q['x']])['prediction']for q in a.get('queries',[])];norm=sum((r['w']*v*v for r,v in zip(rr,h)if r['y']is not None),Q());stageRows=[]\n  for i,(r,p)in enumerate(zip(rr,training)):\n   residual=None if r['y']is None else r['y']-p[-1];stageRows.append(dict(id=r['id'],before=p[-1],residual=residual,negativeCoordinateDerivative=None if residual is None else r['w']*residual/W,fit=h[i],addition=eta*h[i],after=p[-1]+eta*h[i]));p.append(p[-1]+eta*h[i])\n  for p,v in zip(queries,qh):p.append(p[-1]+eta*v)\n  fits.append(dict(stage=stage+1,tree=tree,rows=stageRows,queryFits=qh,norm=norm,predictedSSEDecrease=eta*(2-eta)*norm))\n return dict(task='regression',initial=initial,learningRate=eta,stages=stages,training=training,queries=queries,fits=fits,losses=losses,predictions=[dict(id=q['id'],prediction=p[-1],probabilities=[],vote=None,prob=None)for q,p in zip(a.get('queries',[]),queries)])\nclass Stream:\n def __init__(self,state):self.state=state\n def choose(self,n):\n  limit=(1<<32)-((1<<32)%n)\n  while True:\n   self.state=(1664525*self.state+1013904223)&0xffffffff\n   if self.state<limit:return self.state%n\ndef fixed_schedules(ids,p,seed):\n stream=Stream(seed);draws=[];schedules=[];paths=['']+[p for d in[1,2]for p in map(''.join,itertools.product('LR',repeat=d))]\n for member in range(4):\n  draws.append([ids[stream.choose(len(ids))]for _ in range(len(ids))]);schedule={}\n  for path in paths:\n   order=list(range(p))\n   for j in range(p-1,0,-1):k=stream.choose(j+1);order[j],order[k]=order[k],order[j]\n   schedule[path]=sorted(order[:max(1,int(math.sqrt(p)))])\n  schedules.append(schedule)\n return draws,schedules\ndef csvread(file):\n with Path(file).open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))\ndef read_sources(source):\n source=Path(source);raw=csvread(source/'actual320-country-four-indicators-original-2020-2024.csv');lookup={(r['countryISO3'],int(r['date']),r['indicatorID']):r for r in raw};country=[]\n for code in sorted({r['countryISO3']for r in raw}):\n  for year in range(2020,2025):\n   cols=['NY.GDP.PCAP.KD','NY.GDP.MKTP.KD.ZG','FP.CPI.TOTL.ZG','SP.DYN.LE00.IN'];v=[lookup[code,year,k]['originalValueToken']for k in cols];x=[None if not z else Q(z)for z in v[:3]];x[0]=None if x[0]is None else x[0]/10000;y=None if not v[3]else Q(v[3]);eligible=y is not None and None not in x;country.append(dict(id=code+':'+str(year),sourceRow=code+':'+str(year),originalID=code,year=year,x=x,y=y,weight='1',role='excluded'if not eligible else'outer-test'if year==2024 else'train'))\n person=[]\n for i,r in enumerate(csvread(source/'actual3613-NLS-original52-fields-and-selection.csv'),1):\n  v=lambda k:None if r[k]=='.'else Q(r[k]);x=[v('ed76'),v('age76')];y=None if v('wage76')is None else v('wage76')/100;eligible=y is not None and None not in x;person.append(dict(id='person:'+str(i),sourceRow=str(i),originalID=r['id'],x=x,y=y,weight='1',role='excluded'if not eligible else'outer-test'if i%5==0 else'train'))\n company=[]\n for i,r in enumerate(csvread(source/'actual3150-churn-original14-fields-and-selection.csv'),1):company.append(dict(id='customer:'+str(i),sourceRow=str(i),originalID='',x=[Q(r[k])for k in['Call  Failure','Subscription  Length','Charge  Amount']],y=r['Churn'],weight='1',role='outer-test'if i%5==0 else'train'))\n models={}\n for index,(kind,rr,task,leaf)in enumerate([('country',country,'regression',4),('person',person,'regression',50),('company',company,'classification',30)]):\n  ids=[r['id']for r in rr if r['role']=='train'];draws,schedules=fixed_schedules(ids,len(rr[0]['x']),20261102+7919*index);models[kind]=dict(records=rr,task=task,classes=['0','1']if task=='classification'else[],draws=draws,schedules=schedules,minLeaf=leaf)\n return models\n_OMITTED=object()\ndef realdata(models,kind,options=_OMITTED):\n options={}if options is _OMITTED else options\n if not isinstance(options,dict):raise ValueError('options object required, not explicit null')\n m=models[kind];train=[r for r in m['records']if r['role']=='train'];test=[r for r in m['records']if r['role']=='outer-test'];method=options.get('method','forest');depth=options.get('maxDepth',2);count=options.get('memberCount',3);a=dict(rows=train,queries=[dict(id=r['id'],x=r['x'])for r in test],task=m['task'],classes=m['classes'],maxDepth=depth,minLeaf=options.get('minLeaf',m['minLeaf']),minLeafWeight='0',minGain='0',missingRoute='best',learningRate=options.get('learningRate','1/2'),stages=options.get('stages',3))\n if method not in ['bagging','forest','boost']:raise ValueError('known source method')\n if not isinstance(depth,int)or isinstance(depth,bool)or not 0<=depth<=3:raise ValueError('source depth0..3')\n if method!='boost'and(not isinstance(count,int)or isinstance(count,bool)or not 1<=count<=4):raise ValueError('source member count1..4')\n if method=='boost':result=boost(a)\n else:\n  a.update(bootstrapDraws=m['draws'][:count],nodeFeatures=[{p:v for p,v in s.items()if len(p)<depth}for s in m['schedules'][:count]]);result=ensemble(a,method=='forest')\n outer=scored(result['predictions'],normalized(test,m['task']),m['task'],m['classes']);st=totals([r for r in normalized(train,m['task'])if r['w']and r['y']is not None],m['task'],m['classes']);constant=dict(prediction=st['pred'],probabilities=st['p'],vote=st['pred'],prob=st['pred']);baseline=scored([dict(id=r['id'],**constant)for r in test],normalized(test,m['task']),m['task'],m['classes']);return dict(kind=kind,method=method,settings=a,train=train,test=test,result=result,outer=outer,baseline=baseline)\ndef serial(x):\n if isinstance(x,Q):return str(x)\n if isinstance(x,dict):return{k:serial(v)for k,v in x.items()if k not in['inbag','tree']}\n if isinstance(x,(list,tuple)):return[serial(v)for v in x]\n return x\ndef writecsv(file,heads,rows):\n with Path(file).open('w',encoding='utf8',newline='')as f:\n  w=csv.writer(f);w.writerow(heads);w.writerows([[''if v is None else str(v)for v in r]for r in rows])\nAPI='realdata'\nINPUT={'kind': 'country'}\n\ndef run_fixed(api,a,out,src):\n import matplotlib\n matplotlib.use('svg')\n import matplotlib.pyplot as plt\n from matplotlib.ticker import MaxNLocator\n plt.rcParams.update({'font.size':14,'svg.fonttype':'none','svg.hashsalt':'ml09-fixed-v1'})\n result=variance(a)if api=='variance'else aggregate(a)if api=='aggregate'else ensemble(a,api=='forest')if api in ['bagging','forest']else boost(a)if api=='boost'else realdata(read_sources(src),a['kind'])\n out=Path(out);out.mkdir(parents=True,exist_ok=True);summary={};points=[]\n def add(x,y,s):\n  if y is not None:points.append([x,y,s])\n if api=='variance':\n  summary={'B':result['B'],'varianceOfMean':result['varianceOfMean']};add(result['B'],result['varianceOfMean'],'Specified finite-B variance');xl='Number of members B';yl='Variance, stipulated units squared';title='Declared covariance model, not fitted trees'\n elif api=='aggregate':\n  p=result['predictions'][0];classification=a.get('task')=='classification';summary={'selectedPrediction':p['prediction']}\n  if classification:\n   summary.update(voteLabel=p['vote'],probabilityLabel=p['prob'],meanProbability1=p['probabilities'][1]);add(1,p['probabilities'][1],'Mean probability of class 1');add(2,p['votes'][1],'Label-vote share of class 1');xl='Aggregation (1=probability, 2=vote)';yl='Probability or vote share'\n  else:\n   for i,m in enumerate(a['members']):add(i+1,Q(m['predictions'][0]['value']),'Member prediction')\n   add(3,p['prediction'],'Weighted mean');xl='Member 1, member 2, aggregate 3';yl='Prediction, assumed units'\n  title='Votes and probabilities are distinct objects'\n elif api in ['bagging','forest']:\n  summary={'queryPrediction':result['predictions'][0]['prediction'],'OOB.scoreable':result['outOfBag']['eligibleRows'],'OOB.meanLoss':result['outOfBag']['meanLoss']}\n  for i,r in enumerate(a['rows']):add(i+1,Q(r['y']),'Observed training outcome')\n  for i,p in enumerate(result['outOfBag']['rows']):add(i+1,p['prediction'],'OOB prediction, when defined')\n  xl='Original training ID order';yl='Outcome, assumed units';title='Repeated draws and ID-level OOB membership'\n elif api=='boost':\n  summary={'initial':result['initial'],'finalMSE':result['losses'][-1]['MSE'],'stages':result['stages']}\n  for r in result['losses']:add(r['stage'],r['MSE'],'Training MSE')\n  xl='Boosting stage (0=initial)';yl='Weighted MSE, outcome units squared';title='Training descent does not certify held-out gain'\n else:\n  summary={'outer.scoreable':result['outer']['eligibleRows'],'outer.meanLoss':result['outer']['meanLoss'],'baseline.meanLoss':result['baseline']['meanLoss'],'OOB.scoreable':result['result']['outOfBag']['eligibleRows'],'OOB.meanLoss':result['result']['outOfBag']['meanLoss']}\n  for i,p in enumerate(result['outer']['rows']):\n   add(i+1,Q(p['actual']),'Observed outcome');add(i+1,p['probabilities'][1]if a['kind']=='company'else p['prediction'],'Forest probability of class 1'if a['kind']=='company'else'Forest prediction')\n  xl='Outer-test source order, not a time path';yl='Churn label / probability'if a['kind']=='company'else'Period life expectancy, years'if a['kind']=='country'else'Nominal 1976 USD per hour';title='Fixed forest; outer labels did not fit the trees'\n def display(v):return 'undefined'if v is None else format(float(v),'.9f')\n writecsv(out/'summary.csv',['metric','value'],[[k,display(v)]for k,v in summary.items()]);writecsv(out/'plot-points.csv',['x','y','series'],points);(out/'full.json').write_text(json.dumps(serial(result),indent=2)+'\\n',encoding='utf8')\n fig,ax=plt.subplots(figsize=(5.6,4.6));fig.subplots_adjust(left=.24,right=.96,bottom=.24,top=.76);colors=['#355c72','#a55336','#507956','#78568b']\n for i,s in enumerate(dict.fromkeys(p[2]for p in points)):\n  pp=[p for p in points if p[2]==s];ax.scatter([float(p[0])for p in pp],[float(p[1])for p in pp],s=12 if len(pp)>100 else 32,alpha=.5 if len(pp)>100 else 1,color=colors[i%4],label=s)\n ax.set_xlabel(xl,labelpad=10,fontsize=11);ax.set_ylabel(yl,labelpad=10,fontsize=11);ax.xaxis.set_major_locator(MaxNLocator(3));ax.yaxis.set_major_locator(MaxNLocator(4));ax.grid(alpha=.18);ax.legend(loc='lower left',bbox_to_anchor=(0,1.01),fontsize=9,frameon=False);fig.suptitle(title,fontsize=9,y=.99);fig.savefig(out/'plot.svg',metadata={'Date':None});plt.close(fig);print(', '.join(k+'='+display(v)for k,v in summary.items()))\nif __name__=='__main__':\n import sys\n try:run_fixed(API,INPUT,sys.argv[1]if len(sys.argv)>1 else'fixed-results',sys.argv[2]if len(sys.argv)>2 else'ml09-sources')\n except ValueError as error:print('Rejected declared input: '+str(error),file=sys.stderr);sys.exit(2)\n",
        "inputFiles": [
          {
            "file": "ml09-sources/actual3150-churn-original14-fields-and-selection.csv",
            "sha256": "6f5b9e98ce1896582629646dd4cfe7b1aca78c491f7e412a93840534e8b49f48"
          },
          {
            "file": "ml09-sources/actual320-country-four-indicators-original-2020-2024.csv",
            "sha256": "cedc2f748ce14601c76b254c35aea7ef0ee5f06f2928506c225efcbfb1f69390"
          },
          {
            "file": "ml09-sources/actual3613-NLS-original52-fields-and-selection.csv",
            "sha256": "7ae23478bdfee0922157264655e1a2081999f11686773478835bce315068e0df"
          }
        ],
        "input": {
          "kind": "country"
        },
        "returnCode": 0,
        "expectedFailure": false,
        "stdout": "outer.scoreable=16.000000000, outer.meanLoss=24.041092299, baseline.meanLoss=26.854082008, OOB.scoreable=0.000000000, OOB.meanLoss=undefined\n",
        "stderr": "",
        "summary": {
          "outer.scoreable": "16.000000000",
          "outer.meanLoss": "24.041092299",
          "baseline.meanLoss": "26.854082008",
          "OOB.scoreable": "0.000000000",
          "OOB.meanLoss": "undefined"
        },
        "plotPoints": [
          {
            "x": "1",
            "y": "830512195121951/10000000000000",
            "series": "Observed outcome"
          },
          {
            "x": "1",
            "y": "34104577427463414697/436896000000000000",
            "series": "Forest prediction"
          },
          {
            "x": "2",
            "y": "76023/1000",
            "series": "Observed outcome"
          },
          {
            "x": "2",
            "y": "34104577427463414697/436896000000000000",
            "series": "Forest prediction"
          },
          {
            "x": "3",
            "y": "410540243902439/5000000000000",
            "series": "Observed outcome"
          },
          {
            "x": "3",
            "y": "34104577427463414697/436896000000000000",
            "series": "Forest prediction"
          },
          {
            "x": "4",
            "y": "78017/1000",
            "series": "Observed outcome"
          },
          {
            "x": "4",
            "y": "9617012926829269/120000000000000",
            "series": "Forest prediction"
          },
          {
            "x": "5",
            "y": "807926829268293/10000000000000",
            "series": "Observed outcome"
          },
          {
            "x": "5",
            "y": "34104577427463414697/436896000000000000",
            "series": "Forest prediction"
          },
          {
            "x": "6",
            "y": "829804878048781/10000000000000",
            "series": "Observed outcome"
          },
          {
            "x": "6",
            "y": "34104577427463414697/436896000000000000",
            "series": "Forest prediction"
          },
          {
            "x": "7",
            "y": "406934268292683/5000000000000",
            "series": "Observed outcome"
          },
          {
            "x": "7",
            "y": "34104577427463414697/436896000000000000",
            "series": "Forest prediction"
          },
          {
            "x": "8",
            "y": "8911/125",
            "series": "Observed outcome"
          },
          {
            "x": "8",
            "y": "113069791951219513/1440000000000000",
            "series": "Forest prediction"
          },
          {
            "x": "9",
            "y": "14447/200",
            "series": "Observed outcome"
          },
          {
            "x": "9",
            "y": "105807168341463409/1440000000000000",
            "series": "Forest prediction"
          },
          {
            "x": "10",
            "y": "420181707317073/5000000000000",
            "series": "Observed outcome"
          },
          {
            "x": "10",
            "y": "34104577427463414697/436896000000000000",
            "series": "Forest prediction"
          },
          {
            "x": "11",
            "y": "836292682926829/10000000000000",
            "series": "Observed outcome"
          },
          {
            "x": "11",
            "y": "34104577427463414697/436896000000000000",
            "series": "Forest prediction"
          },
          {
            "x": "12",
            "y": "9408/125",
            "series": "Observed outcome"
          },
          {
            "x": "12",
            "y": "34104577427463414697/436896000000000000",
            "series": "Forest prediction"
          },
          {
            "x": "13",
            "y": "416731707317073/5000000000000",
            "series": "Observed outcome"
          },
          {
            "x": "13",
            "y": "113069791951219513/1440000000000000",
            "series": "Forest prediction"
          },
          {
            "x": "14",
            "y": "78890243902439/1000000000000",
            "series": "Observed outcome"
          },
          {
            "x": "14",
            "y": "34104577427463414697/436896000000000000",
            "series": "Forest prediction"
          },
          {
            "x": "15",
            "y": "9342/125",
            "series": "Observed outcome"
          },
          {
            "x": "15",
            "y": "105807168341463409/1440000000000000",
            "series": "Forest prediction"
          },
          {
            "x": "16",
            "y": "8289/125",
            "series": "Observed outcome"
          },
          {
            "x": "16",
            "y": "34104577427463414697/436896000000000000",
            "series": "Forest prediction"
          }
        ],
        "plotFile": "ml09-fixed-results/realdata-country-python/plot.svg",
        "plotSHA256": "4f923add8012b01e33dc99be546758a14caaf4a49ef2517672fff90339a2734c",
        "files": [
          {
            "file": "ml09-fixed-results/realdata-country-python/full.json",
            "sha256": "3dc2468cfba794454bf6a422c873c4aada66f324a45cce6b73b5a9f06147f918"
          },
          {
            "file": "ml09-fixed-results/realdata-country-python/plot-points.csv",
            "sha256": "ab44138e8a2ecace8051f982e7e9b0c3c07f897bd10fb95a5d5481669938f065"
          },
          {
            "file": "ml09-fixed-results/realdata-country-python/plot.svg",
            "sha256": "4f923add8012b01e33dc99be546758a14caaf4a49ef2517672fff90339a2734c"
          },
          {
            "file": "ml09-fixed-results/realdata-country-python/summary.csv",
            "sha256": "26ffc5a227ad831ecce8b92975bab5febcf8273bf504e1e81f7601cc0771abea"
          }
        ],
        "scope": "Actually executed self-contained fixed example; current web controls execute separately. Python Fraction and finite-precision base R. Author gate, not independent peer."
      },
      "person": {
        "api": "realdata",
        "variant": "person",
        "language": "python",
        "codeFile": "ml09-code/realdata-person.py",
        "codeSHA256": "5db94f574e9d84991f0051b223d386ac7b5b2034055a5d63a4f099741b6540cb",
        "codeText": "\"\"\"ML09 exact Fraction reproduction from native source fields.\n\npython ml09-public-analysis.py --source-dir ml09-sources --output-dir results\n\nThis authored educational implementation uses direct-centered leaf losses and\nexhaustive midpoint partitions. It reads no JS engine, model contract, checker,\nstored target answers or derived-result CSV. Its five tree arithmetic helpers\nwere copied from the author's own separate Fraction reference, not an independent\npeer. Parser/work budgets and display rounding of the production JS are separate.\nNumerical predictions/proper scores do not certify causal effects, calibration,\nIID OOB validity, survey representativeness or production parameter optimality.\n\"\"\"\nfrom pathlib import Path\nfrom fractions import Fraction as Q\nimport csv,json,math,itertools,argparse\n\ndef normalized(rows,task='regression'):\n return [dict(id=r.get('id',i),x=[None if x is None else Q(x)for x in r.get('x',[])],y=None if r['y']is None else str(r['y'])if task=='classification'else Q(r['y']),w=Q(r.get('weight',1)))for i,r in enumerate(rows)]\n\ndef totals(rows,task,classes):\n W=sum((r['w']for r in rows),Q());mu=sum((r['w']*r['y']for r in rows),Q())/W if task=='regression'and W else None\n probs=[sum((r['w']for r in rows if r['y']==c),Q())/W for c in classes]if task=='classification'and W else[]\n risk=sum((r['w']*(r['y']-mu)**2 for r in rows),Q())if task=='regression'and W else W*sum((p*(1-p)for p in probs),Q())\n return dict(n=len(rows),w=W,mu=mu,p=probs,risk=risk,pred=mu if task=='regression'else classes[max(range(len(probs)),key=lambda i:probs[i])]if probs else None)\n\ndef fit(rows,a,task,classes,schedule=None):\n good=[r for r in rows if r['w']>0 and r['y']is not None];root=totals(good,task,classes)['w'];depth=a.get('maxDepth',2);minimum=a.get('minLeaf',1);minmass=Q(a.get('minLeafWeight',0));mingain=Q(a.get('minGain',0));route=a.get('missingRoute','best')\n def build(rr,d,path):\n  st=totals(rr,task,classes);n=dict(rows=rr,st=st,split=None,left=None,right=None,path=path)\n  if d==depth:return n\n  best=None\n  for j in range(len(rr[0]['x'])):\n   if schedule is not None and j not in schedule[path]:continue\n   values=sorted({r['x'][j]for r in rr if r['x'][j]is not None});missing=[r for r in rr if r['x'][j]is None];observed=[r for r in rr if r['x'][j]is not None]\n   candidates=[]\n   for lo,hi in zip(values,values[1:]):\n    q=(lo+hi)/2;left=[r for r in observed if r['x'][j]<=q];right=[r for r in observed if r['x'][j]>q];directions=[route]if route!='best'else['left','right']if missing else['left'if len(left)>=len(right)else'right']\n    for direction in directions:candidates.append(('threshold',q,direction,left+missing if direction=='left'else left,right+missing if direction=='right'else right))\n   if missing and observed:candidates.append(('missing-only',None,'left',missing,observed))\n   for kind,q,direction,left,right in candidates:\n    l=totals(left,task,classes);r=totals(right,task,classes)\n    if min(l['n'],r['n'])<minimum or min(l['w'],r['w'])<minmass or min(l['w'],r['w'])<=0:continue\n    gain=(st['risk']-l['risk']-r['risk'])/root\n    if best is None or gain>best['gain']:best=dict(feature=j,kind=kind,threshold=q,missingRoute=direction,left=left,right=right,gain=gain)\n  if best and best['gain']>0 and best['gain']>mingain:\n   j=best['feature'];go=lambda r:r['x'][j]is None if best['kind']=='missing-only'else best['missingRoute']=='left'if r['x'][j]is None else r['x'][j]<=best['threshold'];n['split']=best;n['left']=build([r for r in rr if go(r)],d+1,path+'L');n['right']=build([r for r in rr if not go(r)],d+1,path+'R')\n  return n\n return build(good,0,'')\n\ndef predict(tree,x):\n n=tree\n while n['split']:\n  s=n['split'];v=x[s['feature']];left=v is None if s['kind']=='missing-only'else s['missingRoute']=='left'if v is None else v<=s['threshold'];n=n['left'if left else'right']\n return dict(prediction=n['st']['pred'],probabilities=n['st']['p'])\n\ndef combine(preds,w,task,classes,mode='probabilities'):\n mass=sum(w,Q())\n if not preds or not mass:return dict(prediction=None,probabilities=[],vote=None,prob=None)\n if task=='regression':return dict(prediction=sum((p['prediction']*v for p,v in zip(preds,w)),Q())/mass,probabilities=[],vote=None,prob=None)\n votes=[sum((v for p,v in zip(preds,w)if p['prediction']==c),Q())/mass for c in classes];ps=[sum((p['probabilities'][j]*v for p,v in zip(preds,w)),Q())/mass for j in range(len(classes))];vote=classes[max(range(len(classes)),key=lambda j:votes[j])];prob=classes[max(range(len(classes)),key=lambda j:ps[j])];return dict(prediction=vote if mode=='votes'else prob,probabilities=ps,vote=vote,prob=prob,votes=votes)\ndef number(v):\n if v is None or isinstance(v,bool):raise ValueError('explicit null/bool is not a numeric parameter')\n return Q(v)\ndef variance(a):\n B=a['B'];v=number(a['marginalVariance']);rho=number(a.get('rho',0))\n if not isinstance(B,int)or isinstance(B,bool)or B<1 or v<0:raise ValueError('positive integer B/nonnegative variance')\n if B>1 and v and not -Q(1,B-1)<=rho<=1:raise ValueError('equicorrelation PSD bound')\n return dict(B=B,marginalVariance=v,correlationApplicable=B>1 and bool(v),varianceOfMean=v if B==1 else v*(1+(B-1)*rho)/B)\ndef aggregate(a):\n task=a.get('task','regression');classes=[str(c)for c in a.get('classes',[])];members=a['members'];w=[number(v)for v in a.get('memberWeights',[1]*len(members))]\n if not members or min(w)<0 or sum(w)<=0:raise ValueError('nonnegative member weights/positive total')\n order=[p.get('id',i)for i,p in enumerate(members[0]['predictions'])];keys=lambda x:(type(x).__name__,x);lookup=[{keys(p.get('id',i)):p for i,p in enumerate(m['predictions'])}for m in members]\n if any(set(m)!={keys(v)for v in order}for m in lookup):raise ValueError('same query ID set')\n out=[]\n for pid in order:\n  predictions=[dict(prediction=number(m[keys(pid)]['value']),probabilities=[])if task=='regression'else dict(prediction=str(m[keys(pid)]['label']),probabilities=[number(v)for v in m[keys(pid)]['probabilities']])for m in lookup]\n  if task=='classification'and any(min(p['probabilities'])<0 or sum(p['probabilities'])!=1 for p in predictions):raise ValueError('probability simplex')\n  out.append(dict(id=pid,**combine(predictions,w,task,classes,a.get('aggregation','probabilities'))))\n return dict(task=task,classes=classes,predictions=out)\ndef scored(preds,rows,task,classes):\n mass=loss=absolute=errors=voteerrors=Q();out=[]\n for p,r in zip(preds,rows):\n  ok=p['prediction']is not None and r['y']is not None and r['w']>0;v=None\n  if ok:\n   mass+=r['w']\n   if task=='regression':e=r['y']-p['prediction'];v=e*e;absolute+=r['w']*abs(e)\n   else:v=sum(((q-(1 if r['y']==c else 0))**2 for c,q in zip(classes,p['probabilities'])),Q());errors+=r['w']*(p['prediction']!=r['y']);voteerrors+=r['w']*(p['vote']!=r['y'])\n   loss+=r['w']*v\n  out.append(dict(p,actual=r['y'],weight=r['w'],scoreEligible=ok,loss=v))\n return dict(rows=out,eligibleRows=sum(r['scoreEligible']for r in out),weight=mass,totalLoss=loss,meanLoss=loss/mass if mass else None,MAE=absolute/mass if mass and task=='regression'else None,errorRate=errors/mass if mass and task=='classification'else None,labelVoteErrorRate=voteerrors/mass if mass and task=='classification'else None)\ndef ensemble(a,forest=False):\n task=a.get('task','regression');classes=[str(v)for v in(a.get('classes')or[])];rr=normalized(a['rows'],task);key=lambda x:(type(x).__name__,x);lookup={key(r['id']):r for r in rr};weights=[number(v)for v in a.get('memberWeights',[1]*len(a['bootstrapDraws']))]\n if not any(r['w']>0 and r['y']is not None for r in rr)or min(weights)<0 or sum(weights)<=0:raise ValueError('positive eligible training and member weight')\n members=[]\n for i,draw in enumerate(a['bootstrapDraws']):\n  data=[lookup[key(v)]for v in draw];schedule=a['nodeFeatures'][i]if forest else None;model=fit(data,a,task,classes,schedule);inbag={key(v)for v in draw};members.append(dict(tree=model,draw=draw,inbag=inbag,weight=weights[i]))\n predictions=[]\n for q in a.get('queries',[]):predictions.append(dict(id=q['id'],**combine([predict(m['tree'],[None if v is None else number(v)for v in q['x']])for m in members],weights,task,classes,a.get('aggregation','probabilities'))))\n oob=[]\n for r in rr:\n  applicable=[i for i,m in enumerate(members)if key(r['id'])not in m['inbag']];p=combine([predict(members[i]['tree'],r['x'])for i in applicable],[weights[i]for i in applicable],task,classes,a.get('aggregation','probabilities'));oob.append(dict(id=r['id'],applicable=applicable,positiveMembers=sum(weights[i]>0 for i in applicable),**p))\n return dict(task=task,classes=classes,members=members,predictions=predictions,outOfBag=scored(oob,rr,task,classes))\ndef boost(a):\n if a.get('task','regression')!='regression':raise ValueError('regression boosting only')\n rr=normalized(a['rows']);good=[r for r in rr if r['w']and r['y']is not None];W=sum((r['w']for r in good),Q())\n if not W:raise ValueError('positive eligible training')\n eta=number(a.get('learningRate','1/2'));stages=a.get('stages',3)\n if not 0<=eta<=1 or not isinstance(stages,int)or isinstance(stages,bool)or not 0<=stages<=8:raise ValueError('supported rate/stages')\n initial=number(a['initial'])if'initial'in a else sum((r['w']*r['y']for r in good),Q())/W;training=[[initial]for r in rr];queries=[[initial]for q in a.get('queries',[])];fits=[];losses=[]\n for stage in range(stages+1):\n  sse=sum((r['w']*(r['y']-p[-1])**2 for r,p in zip(rr,training)if r['w']and r['y']is not None),Q());losses.append(dict(stage=stage,rawWeightedSSE=sse,MSE=sse/W,meanHalfSquaredLoss=sse/(2*W)))\n  if stage==stages:break\n  residuals=[dict(r,y=None if r['y']is None else r['y']-p[-1])for r,p in zip(rr,training)];tree=fit(residuals,a,'regression',[]);h=[predict(tree,r['x'])['prediction']for r in rr];qh=[predict(tree,[None if v is None else number(v)for v in q['x']])['prediction']for q in a.get('queries',[])];norm=sum((r['w']*v*v for r,v in zip(rr,h)if r['y']is not None),Q());stageRows=[]\n  for i,(r,p)in enumerate(zip(rr,training)):\n   residual=None if r['y']is None else r['y']-p[-1];stageRows.append(dict(id=r['id'],before=p[-1],residual=residual,negativeCoordinateDerivative=None if residual is None else r['w']*residual/W,fit=h[i],addition=eta*h[i],after=p[-1]+eta*h[i]));p.append(p[-1]+eta*h[i])\n  for p,v in zip(queries,qh):p.append(p[-1]+eta*v)\n  fits.append(dict(stage=stage+1,tree=tree,rows=stageRows,queryFits=qh,norm=norm,predictedSSEDecrease=eta*(2-eta)*norm))\n return dict(task='regression',initial=initial,learningRate=eta,stages=stages,training=training,queries=queries,fits=fits,losses=losses,predictions=[dict(id=q['id'],prediction=p[-1],probabilities=[],vote=None,prob=None)for q,p in zip(a.get('queries',[]),queries)])\nclass Stream:\n def __init__(self,state):self.state=state\n def choose(self,n):\n  limit=(1<<32)-((1<<32)%n)\n  while True:\n   self.state=(1664525*self.state+1013904223)&0xffffffff\n   if self.state<limit:return self.state%n\ndef fixed_schedules(ids,p,seed):\n stream=Stream(seed);draws=[];schedules=[];paths=['']+[p for d in[1,2]for p in map(''.join,itertools.product('LR',repeat=d))]\n for member in range(4):\n  draws.append([ids[stream.choose(len(ids))]for _ in range(len(ids))]);schedule={}\n  for path in paths:\n   order=list(range(p))\n   for j in range(p-1,0,-1):k=stream.choose(j+1);order[j],order[k]=order[k],order[j]\n   schedule[path]=sorted(order[:max(1,int(math.sqrt(p)))])\n  schedules.append(schedule)\n return draws,schedules\ndef csvread(file):\n with Path(file).open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))\ndef read_sources(source):\n source=Path(source);raw=csvread(source/'actual320-country-four-indicators-original-2020-2024.csv');lookup={(r['countryISO3'],int(r['date']),r['indicatorID']):r for r in raw};country=[]\n for code in sorted({r['countryISO3']for r in raw}):\n  for year in range(2020,2025):\n   cols=['NY.GDP.PCAP.KD','NY.GDP.MKTP.KD.ZG','FP.CPI.TOTL.ZG','SP.DYN.LE00.IN'];v=[lookup[code,year,k]['originalValueToken']for k in cols];x=[None if not z else Q(z)for z in v[:3]];x[0]=None if x[0]is None else x[0]/10000;y=None if not v[3]else Q(v[3]);eligible=y is not None and None not in x;country.append(dict(id=code+':'+str(year),sourceRow=code+':'+str(year),originalID=code,year=year,x=x,y=y,weight='1',role='excluded'if not eligible else'outer-test'if year==2024 else'train'))\n person=[]\n for i,r in enumerate(csvread(source/'actual3613-NLS-original52-fields-and-selection.csv'),1):\n  v=lambda k:None if r[k]=='.'else Q(r[k]);x=[v('ed76'),v('age76')];y=None if v('wage76')is None else v('wage76')/100;eligible=y is not None and None not in x;person.append(dict(id='person:'+str(i),sourceRow=str(i),originalID=r['id'],x=x,y=y,weight='1',role='excluded'if not eligible else'outer-test'if i%5==0 else'train'))\n company=[]\n for i,r in enumerate(csvread(source/'actual3150-churn-original14-fields-and-selection.csv'),1):company.append(dict(id='customer:'+str(i),sourceRow=str(i),originalID='',x=[Q(r[k])for k in['Call  Failure','Subscription  Length','Charge  Amount']],y=r['Churn'],weight='1',role='outer-test'if i%5==0 else'train'))\n models={}\n for index,(kind,rr,task,leaf)in enumerate([('country',country,'regression',4),('person',person,'regression',50),('company',company,'classification',30)]):\n  ids=[r['id']for r in rr if r['role']=='train'];draws,schedules=fixed_schedules(ids,len(rr[0]['x']),20261102+7919*index);models[kind]=dict(records=rr,task=task,classes=['0','1']if task=='classification'else[],draws=draws,schedules=schedules,minLeaf=leaf)\n return models\n_OMITTED=object()\ndef realdata(models,kind,options=_OMITTED):\n options={}if options is _OMITTED else options\n if not isinstance(options,dict):raise ValueError('options object required, not explicit null')\n m=models[kind];train=[r for r in m['records']if r['role']=='train'];test=[r for r in m['records']if r['role']=='outer-test'];method=options.get('method','forest');depth=options.get('maxDepth',2);count=options.get('memberCount',3);a=dict(rows=train,queries=[dict(id=r['id'],x=r['x'])for r in test],task=m['task'],classes=m['classes'],maxDepth=depth,minLeaf=options.get('minLeaf',m['minLeaf']),minLeafWeight='0',minGain='0',missingRoute='best',learningRate=options.get('learningRate','1/2'),stages=options.get('stages',3))\n if method not in ['bagging','forest','boost']:raise ValueError('known source method')\n if not isinstance(depth,int)or isinstance(depth,bool)or not 0<=depth<=3:raise ValueError('source depth0..3')\n if method!='boost'and(not isinstance(count,int)or isinstance(count,bool)or not 1<=count<=4):raise ValueError('source member count1..4')\n if method=='boost':result=boost(a)\n else:\n  a.update(bootstrapDraws=m['draws'][:count],nodeFeatures=[{p:v for p,v in s.items()if len(p)<depth}for s in m['schedules'][:count]]);result=ensemble(a,method=='forest')\n outer=scored(result['predictions'],normalized(test,m['task']),m['task'],m['classes']);st=totals([r for r in normalized(train,m['task'])if r['w']and r['y']is not None],m['task'],m['classes']);constant=dict(prediction=st['pred'],probabilities=st['p'],vote=st['pred'],prob=st['pred']);baseline=scored([dict(id=r['id'],**constant)for r in test],normalized(test,m['task']),m['task'],m['classes']);return dict(kind=kind,method=method,settings=a,train=train,test=test,result=result,outer=outer,baseline=baseline)\ndef serial(x):\n if isinstance(x,Q):return str(x)\n if isinstance(x,dict):return{k:serial(v)for k,v in x.items()if k not in['inbag','tree']}\n if isinstance(x,(list,tuple)):return[serial(v)for v in x]\n return x\ndef writecsv(file,heads,rows):\n with Path(file).open('w',encoding='utf8',newline='')as f:\n  w=csv.writer(f);w.writerow(heads);w.writerows([[''if v is None else str(v)for v in r]for r in rows])\nAPI='realdata'\nINPUT={'kind': 'person'}\n\ndef run_fixed(api,a,out,src):\n import matplotlib\n matplotlib.use('svg')\n import matplotlib.pyplot as plt\n from matplotlib.ticker import MaxNLocator\n plt.rcParams.update({'font.size':14,'svg.fonttype':'none','svg.hashsalt':'ml09-fixed-v1'})\n result=variance(a)if api=='variance'else aggregate(a)if api=='aggregate'else ensemble(a,api=='forest')if api in ['bagging','forest']else boost(a)if api=='boost'else realdata(read_sources(src),a['kind'])\n out=Path(out);out.mkdir(parents=True,exist_ok=True);summary={};points=[]\n def add(x,y,s):\n  if y is not None:points.append([x,y,s])\n if api=='variance':\n  summary={'B':result['B'],'varianceOfMean':result['varianceOfMean']};add(result['B'],result['varianceOfMean'],'Specified finite-B variance');xl='Number of members B';yl='Variance, stipulated units squared';title='Declared covariance model, not fitted trees'\n elif api=='aggregate':\n  p=result['predictions'][0];classification=a.get('task')=='classification';summary={'selectedPrediction':p['prediction']}\n  if classification:\n   summary.update(voteLabel=p['vote'],probabilityLabel=p['prob'],meanProbability1=p['probabilities'][1]);add(1,p['probabilities'][1],'Mean probability of class 1');add(2,p['votes'][1],'Label-vote share of class 1');xl='Aggregation (1=probability, 2=vote)';yl='Probability or vote share'\n  else:\n   for i,m in enumerate(a['members']):add(i+1,Q(m['predictions'][0]['value']),'Member prediction')\n   add(3,p['prediction'],'Weighted mean');xl='Member 1, member 2, aggregate 3';yl='Prediction, assumed units'\n  title='Votes and probabilities are distinct objects'\n elif api in ['bagging','forest']:\n  summary={'queryPrediction':result['predictions'][0]['prediction'],'OOB.scoreable':result['outOfBag']['eligibleRows'],'OOB.meanLoss':result['outOfBag']['meanLoss']}\n  for i,r in enumerate(a['rows']):add(i+1,Q(r['y']),'Observed training outcome')\n  for i,p in enumerate(result['outOfBag']['rows']):add(i+1,p['prediction'],'OOB prediction, when defined')\n  xl='Original training ID order';yl='Outcome, assumed units';title='Repeated draws and ID-level OOB membership'\n elif api=='boost':\n  summary={'initial':result['initial'],'finalMSE':result['losses'][-1]['MSE'],'stages':result['stages']}\n  for r in result['losses']:add(r['stage'],r['MSE'],'Training MSE')\n  xl='Boosting stage (0=initial)';yl='Weighted MSE, outcome units squared';title='Training descent does not certify held-out gain'\n else:\n  summary={'outer.scoreable':result['outer']['eligibleRows'],'outer.meanLoss':result['outer']['meanLoss'],'baseline.meanLoss':result['baseline']['meanLoss'],'OOB.scoreable':result['result']['outOfBag']['eligibleRows'],'OOB.meanLoss':result['result']['outOfBag']['meanLoss']}\n  for i,p in enumerate(result['outer']['rows']):\n   add(i+1,Q(p['actual']),'Observed outcome');add(i+1,p['probabilities'][1]if a['kind']=='company'else p['prediction'],'Forest probability of class 1'if a['kind']=='company'else'Forest prediction')\n  xl='Outer-test source order, not a time path';yl='Churn label / probability'if a['kind']=='company'else'Period life expectancy, years'if a['kind']=='country'else'Nominal 1976 USD per hour';title='Fixed forest; outer labels did not fit the trees'\n def display(v):return 'undefined'if v is None else format(float(v),'.9f')\n writecsv(out/'summary.csv',['metric','value'],[[k,display(v)]for k,v in summary.items()]);writecsv(out/'plot-points.csv',['x','y','series'],points);(out/'full.json').write_text(json.dumps(serial(result),indent=2)+'\\n',encoding='utf8')\n fig,ax=plt.subplots(figsize=(5.6,4.6));fig.subplots_adjust(left=.24,right=.96,bottom=.24,top=.76);colors=['#355c72','#a55336','#507956','#78568b']\n for i,s in enumerate(dict.fromkeys(p[2]for p in points)):\n  pp=[p for p in points if p[2]==s];ax.scatter([float(p[0])for p in pp],[float(p[1])for p in pp],s=12 if len(pp)>100 else 32,alpha=.5 if len(pp)>100 else 1,color=colors[i%4],label=s)\n ax.set_xlabel(xl,labelpad=10,fontsize=11);ax.set_ylabel(yl,labelpad=10,fontsize=11);ax.xaxis.set_major_locator(MaxNLocator(3));ax.yaxis.set_major_locator(MaxNLocator(4));ax.grid(alpha=.18);ax.legend(loc='lower left',bbox_to_anchor=(0,1.01),fontsize=9,frameon=False);fig.suptitle(title,fontsize=9,y=.99);fig.savefig(out/'plot.svg',metadata={'Date':None});plt.close(fig);print(', '.join(k+'='+display(v)for k,v in summary.items()))\nif __name__=='__main__':\n import sys\n try:run_fixed(API,INPUT,sys.argv[1]if len(sys.argv)>1 else'fixed-results',sys.argv[2]if len(sys.argv)>2 else'ml09-sources')\n except ValueError as error:print('Rejected declared input: '+str(error),file=sys.stderr);sys.exit(2)\n",
        "code": "\"\"\"ML09 exact Fraction reproduction from native source fields.\n\npython ml09-public-analysis.py --source-dir ml09-sources --output-dir results\n\nThis authored educational implementation uses direct-centered leaf losses and\nexhaustive midpoint partitions. It reads no JS engine, model contract, checker,\nstored target answers or derived-result CSV. Its five tree arithmetic helpers\nwere copied from the author's own separate Fraction reference, not an independent\npeer. Parser/work budgets and display rounding of the production JS are separate.\nNumerical predictions/proper scores do not certify causal effects, calibration,\nIID OOB validity, survey representativeness or production parameter optimality.\n\"\"\"\nfrom pathlib import Path\nfrom fractions import Fraction as Q\nimport csv,json,math,itertools,argparse\n\ndef normalized(rows,task='regression'):\n return [dict(id=r.get('id',i),x=[None if x is None else Q(x)for x in r.get('x',[])],y=None if r['y']is None else str(r['y'])if task=='classification'else Q(r['y']),w=Q(r.get('weight',1)))for i,r in enumerate(rows)]\n\ndef totals(rows,task,classes):\n W=sum((r['w']for r in rows),Q());mu=sum((r['w']*r['y']for r in rows),Q())/W if task=='regression'and W else None\n probs=[sum((r['w']for r in rows if r['y']==c),Q())/W for c in classes]if task=='classification'and W else[]\n risk=sum((r['w']*(r['y']-mu)**2 for r in rows),Q())if task=='regression'and W else W*sum((p*(1-p)for p in probs),Q())\n return dict(n=len(rows),w=W,mu=mu,p=probs,risk=risk,pred=mu if task=='regression'else classes[max(range(len(probs)),key=lambda i:probs[i])]if probs else None)\n\ndef fit(rows,a,task,classes,schedule=None):\n good=[r for r in rows if r['w']>0 and r['y']is not None];root=totals(good,task,classes)['w'];depth=a.get('maxDepth',2);minimum=a.get('minLeaf',1);minmass=Q(a.get('minLeafWeight',0));mingain=Q(a.get('minGain',0));route=a.get('missingRoute','best')\n def build(rr,d,path):\n  st=totals(rr,task,classes);n=dict(rows=rr,st=st,split=None,left=None,right=None,path=path)\n  if d==depth:return n\n  best=None\n  for j in range(len(rr[0]['x'])):\n   if schedule is not None and j not in schedule[path]:continue\n   values=sorted({r['x'][j]for r in rr if r['x'][j]is not None});missing=[r for r in rr if r['x'][j]is None];observed=[r for r in rr if r['x'][j]is not None]\n   candidates=[]\n   for lo,hi in zip(values,values[1:]):\n    q=(lo+hi)/2;left=[r for r in observed if r['x'][j]<=q];right=[r for r in observed if r['x'][j]>q];directions=[route]if route!='best'else['left','right']if missing else['left'if len(left)>=len(right)else'right']\n    for direction in directions:candidates.append(('threshold',q,direction,left+missing if direction=='left'else left,right+missing if direction=='right'else right))\n   if missing and observed:candidates.append(('missing-only',None,'left',missing,observed))\n   for kind,q,direction,left,right in candidates:\n    l=totals(left,task,classes);r=totals(right,task,classes)\n    if min(l['n'],r['n'])<minimum or min(l['w'],r['w'])<minmass or min(l['w'],r['w'])<=0:continue\n    gain=(st['risk']-l['risk']-r['risk'])/root\n    if best is None or gain>best['gain']:best=dict(feature=j,kind=kind,threshold=q,missingRoute=direction,left=left,right=right,gain=gain)\n  if best and best['gain']>0 and best['gain']>mingain:\n   j=best['feature'];go=lambda r:r['x'][j]is None if best['kind']=='missing-only'else best['missingRoute']=='left'if r['x'][j]is None else r['x'][j]<=best['threshold'];n['split']=best;n['left']=build([r for r in rr if go(r)],d+1,path+'L');n['right']=build([r for r in rr if not go(r)],d+1,path+'R')\n  return n\n return build(good,0,'')\n\ndef predict(tree,x):\n n=tree\n while n['split']:\n  s=n['split'];v=x[s['feature']];left=v is None if s['kind']=='missing-only'else s['missingRoute']=='left'if v is None else v<=s['threshold'];n=n['left'if left else'right']\n return dict(prediction=n['st']['pred'],probabilities=n['st']['p'])\n\ndef combine(preds,w,task,classes,mode='probabilities'):\n mass=sum(w,Q())\n if not preds or not mass:return dict(prediction=None,probabilities=[],vote=None,prob=None)\n if task=='regression':return dict(prediction=sum((p['prediction']*v for p,v in zip(preds,w)),Q())/mass,probabilities=[],vote=None,prob=None)\n votes=[sum((v for p,v in zip(preds,w)if p['prediction']==c),Q())/mass for c in classes];ps=[sum((p['probabilities'][j]*v for p,v in zip(preds,w)),Q())/mass for j in range(len(classes))];vote=classes[max(range(len(classes)),key=lambda j:votes[j])];prob=classes[max(range(len(classes)),key=lambda j:ps[j])];return dict(prediction=vote if mode=='votes'else prob,probabilities=ps,vote=vote,prob=prob,votes=votes)\ndef number(v):\n if v is None or isinstance(v,bool):raise ValueError('explicit null/bool is not a numeric parameter')\n return Q(v)\ndef variance(a):\n B=a['B'];v=number(a['marginalVariance']);rho=number(a.get('rho',0))\n if not isinstance(B,int)or isinstance(B,bool)or B<1 or v<0:raise ValueError('positive integer B/nonnegative variance')\n if B>1 and v and not -Q(1,B-1)<=rho<=1:raise ValueError('equicorrelation PSD bound')\n return dict(B=B,marginalVariance=v,correlationApplicable=B>1 and bool(v),varianceOfMean=v if B==1 else v*(1+(B-1)*rho)/B)\ndef aggregate(a):\n task=a.get('task','regression');classes=[str(c)for c in a.get('classes',[])];members=a['members'];w=[number(v)for v in a.get('memberWeights',[1]*len(members))]\n if not members or min(w)<0 or sum(w)<=0:raise ValueError('nonnegative member weights/positive total')\n order=[p.get('id',i)for i,p in enumerate(members[0]['predictions'])];keys=lambda x:(type(x).__name__,x);lookup=[{keys(p.get('id',i)):p for i,p in enumerate(m['predictions'])}for m in members]\n if any(set(m)!={keys(v)for v in order}for m in lookup):raise ValueError('same query ID set')\n out=[]\n for pid in order:\n  predictions=[dict(prediction=number(m[keys(pid)]['value']),probabilities=[])if task=='regression'else dict(prediction=str(m[keys(pid)]['label']),probabilities=[number(v)for v in m[keys(pid)]['probabilities']])for m in lookup]\n  if task=='classification'and any(min(p['probabilities'])<0 or sum(p['probabilities'])!=1 for p in predictions):raise ValueError('probability simplex')\n  out.append(dict(id=pid,**combine(predictions,w,task,classes,a.get('aggregation','probabilities'))))\n return dict(task=task,classes=classes,predictions=out)\ndef scored(preds,rows,task,classes):\n mass=loss=absolute=errors=voteerrors=Q();out=[]\n for p,r in zip(preds,rows):\n  ok=p['prediction']is not None and r['y']is not None and r['w']>0;v=None\n  if ok:\n   mass+=r['w']\n   if task=='regression':e=r['y']-p['prediction'];v=e*e;absolute+=r['w']*abs(e)\n   else:v=sum(((q-(1 if r['y']==c else 0))**2 for c,q in zip(classes,p['probabilities'])),Q());errors+=r['w']*(p['prediction']!=r['y']);voteerrors+=r['w']*(p['vote']!=r['y'])\n   loss+=r['w']*v\n  out.append(dict(p,actual=r['y'],weight=r['w'],scoreEligible=ok,loss=v))\n return dict(rows=out,eligibleRows=sum(r['scoreEligible']for r in out),weight=mass,totalLoss=loss,meanLoss=loss/mass if mass else None,MAE=absolute/mass if mass and task=='regression'else None,errorRate=errors/mass if mass and task=='classification'else None,labelVoteErrorRate=voteerrors/mass if mass and task=='classification'else None)\ndef ensemble(a,forest=False):\n task=a.get('task','regression');classes=[str(v)for v in(a.get('classes')or[])];rr=normalized(a['rows'],task);key=lambda x:(type(x).__name__,x);lookup={key(r['id']):r for r in rr};weights=[number(v)for v in a.get('memberWeights',[1]*len(a['bootstrapDraws']))]\n if not any(r['w']>0 and r['y']is not None for r in rr)or min(weights)<0 or sum(weights)<=0:raise ValueError('positive eligible training and member weight')\n members=[]\n for i,draw in enumerate(a['bootstrapDraws']):\n  data=[lookup[key(v)]for v in draw];schedule=a['nodeFeatures'][i]if forest else None;model=fit(data,a,task,classes,schedule);inbag={key(v)for v in draw};members.append(dict(tree=model,draw=draw,inbag=inbag,weight=weights[i]))\n predictions=[]\n for q in a.get('queries',[]):predictions.append(dict(id=q['id'],**combine([predict(m['tree'],[None if v is None else number(v)for v in q['x']])for m in members],weights,task,classes,a.get('aggregation','probabilities'))))\n oob=[]\n for r in rr:\n  applicable=[i for i,m in enumerate(members)if key(r['id'])not in m['inbag']];p=combine([predict(members[i]['tree'],r['x'])for i in applicable],[weights[i]for i in applicable],task,classes,a.get('aggregation','probabilities'));oob.append(dict(id=r['id'],applicable=applicable,positiveMembers=sum(weights[i]>0 for i in applicable),**p))\n return dict(task=task,classes=classes,members=members,predictions=predictions,outOfBag=scored(oob,rr,task,classes))\ndef boost(a):\n if a.get('task','regression')!='regression':raise ValueError('regression boosting only')\n rr=normalized(a['rows']);good=[r for r in rr if r['w']and r['y']is not None];W=sum((r['w']for r in good),Q())\n if not W:raise ValueError('positive eligible training')\n eta=number(a.get('learningRate','1/2'));stages=a.get('stages',3)\n if not 0<=eta<=1 or not isinstance(stages,int)or isinstance(stages,bool)or not 0<=stages<=8:raise ValueError('supported rate/stages')\n initial=number(a['initial'])if'initial'in a else sum((r['w']*r['y']for r in good),Q())/W;training=[[initial]for r in rr];queries=[[initial]for q in a.get('queries',[])];fits=[];losses=[]\n for stage in range(stages+1):\n  sse=sum((r['w']*(r['y']-p[-1])**2 for r,p in zip(rr,training)if r['w']and r['y']is not None),Q());losses.append(dict(stage=stage,rawWeightedSSE=sse,MSE=sse/W,meanHalfSquaredLoss=sse/(2*W)))\n  if stage==stages:break\n  residuals=[dict(r,y=None if r['y']is None else r['y']-p[-1])for r,p in zip(rr,training)];tree=fit(residuals,a,'regression',[]);h=[predict(tree,r['x'])['prediction']for r in rr];qh=[predict(tree,[None if v is None else number(v)for v in q['x']])['prediction']for q in a.get('queries',[])];norm=sum((r['w']*v*v for r,v in zip(rr,h)if r['y']is not None),Q());stageRows=[]\n  for i,(r,p)in enumerate(zip(rr,training)):\n   residual=None if r['y']is None else r['y']-p[-1];stageRows.append(dict(id=r['id'],before=p[-1],residual=residual,negativeCoordinateDerivative=None if residual is None else r['w']*residual/W,fit=h[i],addition=eta*h[i],after=p[-1]+eta*h[i]));p.append(p[-1]+eta*h[i])\n  for p,v in zip(queries,qh):p.append(p[-1]+eta*v)\n  fits.append(dict(stage=stage+1,tree=tree,rows=stageRows,queryFits=qh,norm=norm,predictedSSEDecrease=eta*(2-eta)*norm))\n return dict(task='regression',initial=initial,learningRate=eta,stages=stages,training=training,queries=queries,fits=fits,losses=losses,predictions=[dict(id=q['id'],prediction=p[-1],probabilities=[],vote=None,prob=None)for q,p in zip(a.get('queries',[]),queries)])\nclass Stream:\n def __init__(self,state):self.state=state\n def choose(self,n):\n  limit=(1<<32)-((1<<32)%n)\n  while True:\n   self.state=(1664525*self.state+1013904223)&0xffffffff\n   if self.state<limit:return self.state%n\ndef fixed_schedules(ids,p,seed):\n stream=Stream(seed);draws=[];schedules=[];paths=['']+[p for d in[1,2]for p in map(''.join,itertools.product('LR',repeat=d))]\n for member in range(4):\n  draws.append([ids[stream.choose(len(ids))]for _ in range(len(ids))]);schedule={}\n  for path in paths:\n   order=list(range(p))\n   for j in range(p-1,0,-1):k=stream.choose(j+1);order[j],order[k]=order[k],order[j]\n   schedule[path]=sorted(order[:max(1,int(math.sqrt(p)))])\n  schedules.append(schedule)\n return draws,schedules\ndef csvread(file):\n with Path(file).open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))\ndef read_sources(source):\n source=Path(source);raw=csvread(source/'actual320-country-four-indicators-original-2020-2024.csv');lookup={(r['countryISO3'],int(r['date']),r['indicatorID']):r for r in raw};country=[]\n for code in sorted({r['countryISO3']for r in raw}):\n  for year in range(2020,2025):\n   cols=['NY.GDP.PCAP.KD','NY.GDP.MKTP.KD.ZG','FP.CPI.TOTL.ZG','SP.DYN.LE00.IN'];v=[lookup[code,year,k]['originalValueToken']for k in cols];x=[None if not z else Q(z)for z in v[:3]];x[0]=None if x[0]is None else x[0]/10000;y=None if not v[3]else Q(v[3]);eligible=y is not None and None not in x;country.append(dict(id=code+':'+str(year),sourceRow=code+':'+str(year),originalID=code,year=year,x=x,y=y,weight='1',role='excluded'if not eligible else'outer-test'if year==2024 else'train'))\n person=[]\n for i,r in enumerate(csvread(source/'actual3613-NLS-original52-fields-and-selection.csv'),1):\n  v=lambda k:None if r[k]=='.'else Q(r[k]);x=[v('ed76'),v('age76')];y=None if v('wage76')is None else v('wage76')/100;eligible=y is not None and None not in x;person.append(dict(id='person:'+str(i),sourceRow=str(i),originalID=r['id'],x=x,y=y,weight='1',role='excluded'if not eligible else'outer-test'if i%5==0 else'train'))\n company=[]\n for i,r in enumerate(csvread(source/'actual3150-churn-original14-fields-and-selection.csv'),1):company.append(dict(id='customer:'+str(i),sourceRow=str(i),originalID='',x=[Q(r[k])for k in['Call  Failure','Subscription  Length','Charge  Amount']],y=r['Churn'],weight='1',role='outer-test'if i%5==0 else'train'))\n models={}\n for index,(kind,rr,task,leaf)in enumerate([('country',country,'regression',4),('person',person,'regression',50),('company',company,'classification',30)]):\n  ids=[r['id']for r in rr if r['role']=='train'];draws,schedules=fixed_schedules(ids,len(rr[0]['x']),20261102+7919*index);models[kind]=dict(records=rr,task=task,classes=['0','1']if task=='classification'else[],draws=draws,schedules=schedules,minLeaf=leaf)\n return models\n_OMITTED=object()\ndef realdata(models,kind,options=_OMITTED):\n options={}if options is _OMITTED else options\n if not isinstance(options,dict):raise ValueError('options object required, not explicit null')\n m=models[kind];train=[r for r in m['records']if r['role']=='train'];test=[r for r in m['records']if r['role']=='outer-test'];method=options.get('method','forest');depth=options.get('maxDepth',2);count=options.get('memberCount',3);a=dict(rows=train,queries=[dict(id=r['id'],x=r['x'])for r in test],task=m['task'],classes=m['classes'],maxDepth=depth,minLeaf=options.get('minLeaf',m['minLeaf']),minLeafWeight='0',minGain='0',missingRoute='best',learningRate=options.get('learningRate','1/2'),stages=options.get('stages',3))\n if method not in ['bagging','forest','boost']:raise ValueError('known source method')\n if not isinstance(depth,int)or isinstance(depth,bool)or not 0<=depth<=3:raise ValueError('source depth0..3')\n if method!='boost'and(not isinstance(count,int)or isinstance(count,bool)or not 1<=count<=4):raise ValueError('source member count1..4')\n if method=='boost':result=boost(a)\n else:\n  a.update(bootstrapDraws=m['draws'][:count],nodeFeatures=[{p:v for p,v in s.items()if len(p)<depth}for s in m['schedules'][:count]]);result=ensemble(a,method=='forest')\n outer=scored(result['predictions'],normalized(test,m['task']),m['task'],m['classes']);st=totals([r for r in normalized(train,m['task'])if r['w']and r['y']is not None],m['task'],m['classes']);constant=dict(prediction=st['pred'],probabilities=st['p'],vote=st['pred'],prob=st['pred']);baseline=scored([dict(id=r['id'],**constant)for r in test],normalized(test,m['task']),m['task'],m['classes']);return dict(kind=kind,method=method,settings=a,train=train,test=test,result=result,outer=outer,baseline=baseline)\ndef serial(x):\n if isinstance(x,Q):return str(x)\n if isinstance(x,dict):return{k:serial(v)for k,v in x.items()if k not in['inbag','tree']}\n if isinstance(x,(list,tuple)):return[serial(v)for v in x]\n return x\ndef writecsv(file,heads,rows):\n with Path(file).open('w',encoding='utf8',newline='')as f:\n  w=csv.writer(f);w.writerow(heads);w.writerows([[''if v is None else str(v)for v in r]for r in rows])\nAPI='realdata'\nINPUT={'kind': 'person'}\n\ndef run_fixed(api,a,out,src):\n import matplotlib\n matplotlib.use('svg')\n import matplotlib.pyplot as plt\n from matplotlib.ticker import MaxNLocator\n plt.rcParams.update({'font.size':14,'svg.fonttype':'none','svg.hashsalt':'ml09-fixed-v1'})\n result=variance(a)if api=='variance'else aggregate(a)if api=='aggregate'else ensemble(a,api=='forest')if api in ['bagging','forest']else boost(a)if api=='boost'else realdata(read_sources(src),a['kind'])\n out=Path(out);out.mkdir(parents=True,exist_ok=True);summary={};points=[]\n def add(x,y,s):\n  if y is not None:points.append([x,y,s])\n if api=='variance':\n  summary={'B':result['B'],'varianceOfMean':result['varianceOfMean']};add(result['B'],result['varianceOfMean'],'Specified finite-B variance');xl='Number of members B';yl='Variance, stipulated units squared';title='Declared covariance model, not fitted trees'\n elif api=='aggregate':\n  p=result['predictions'][0];classification=a.get('task')=='classification';summary={'selectedPrediction':p['prediction']}\n  if classification:\n   summary.update(voteLabel=p['vote'],probabilityLabel=p['prob'],meanProbability1=p['probabilities'][1]);add(1,p['probabilities'][1],'Mean probability of class 1');add(2,p['votes'][1],'Label-vote share of class 1');xl='Aggregation (1=probability, 2=vote)';yl='Probability or vote share'\n  else:\n   for i,m in enumerate(a['members']):add(i+1,Q(m['predictions'][0]['value']),'Member prediction')\n   add(3,p['prediction'],'Weighted mean');xl='Member 1, member 2, aggregate 3';yl='Prediction, assumed units'\n  title='Votes and probabilities are distinct objects'\n elif api in ['bagging','forest']:\n  summary={'queryPrediction':result['predictions'][0]['prediction'],'OOB.scoreable':result['outOfBag']['eligibleRows'],'OOB.meanLoss':result['outOfBag']['meanLoss']}\n  for i,r in enumerate(a['rows']):add(i+1,Q(r['y']),'Observed training outcome')\n  for i,p in enumerate(result['outOfBag']['rows']):add(i+1,p['prediction'],'OOB prediction, when defined')\n  xl='Original training ID order';yl='Outcome, assumed units';title='Repeated draws and ID-level OOB membership'\n elif api=='boost':\n  summary={'initial':result['initial'],'finalMSE':result['losses'][-1]['MSE'],'stages':result['stages']}\n  for r in result['losses']:add(r['stage'],r['MSE'],'Training MSE')\n  xl='Boosting stage (0=initial)';yl='Weighted MSE, outcome units squared';title='Training descent does not certify held-out gain'\n else:\n  summary={'outer.scoreable':result['outer']['eligibleRows'],'outer.meanLoss':result['outer']['meanLoss'],'baseline.meanLoss':result['baseline']['meanLoss'],'OOB.scoreable':result['result']['outOfBag']['eligibleRows'],'OOB.meanLoss':result['result']['outOfBag']['meanLoss']}\n  for i,p in enumerate(result['outer']['rows']):\n   add(i+1,Q(p['actual']),'Observed outcome');add(i+1,p['probabilities'][1]if a['kind']=='company'else p['prediction'],'Forest probability of class 1'if a['kind']=='company'else'Forest prediction')\n  xl='Outer-test source order, not a time path';yl='Churn label / probability'if a['kind']=='company'else'Period life expectancy, years'if a['kind']=='country'else'Nominal 1976 USD per hour';title='Fixed forest; outer labels did not fit the trees'\n def display(v):return 'undefined'if v is None else format(float(v),'.9f')\n writecsv(out/'summary.csv',['metric','value'],[[k,display(v)]for k,v in summary.items()]);writecsv(out/'plot-points.csv',['x','y','series'],points);(out/'full.json').write_text(json.dumps(serial(result),indent=2)+'\\n',encoding='utf8')\n fig,ax=plt.subplots(figsize=(5.6,4.6));fig.subplots_adjust(left=.24,right=.96,bottom=.24,top=.76);colors=['#355c72','#a55336','#507956','#78568b']\n for i,s in enumerate(dict.fromkeys(p[2]for p in points)):\n  pp=[p for p in points if p[2]==s];ax.scatter([float(p[0])for p in pp],[float(p[1])for p in pp],s=12 if len(pp)>100 else 32,alpha=.5 if len(pp)>100 else 1,color=colors[i%4],label=s)\n ax.set_xlabel(xl,labelpad=10,fontsize=11);ax.set_ylabel(yl,labelpad=10,fontsize=11);ax.xaxis.set_major_locator(MaxNLocator(3));ax.yaxis.set_major_locator(MaxNLocator(4));ax.grid(alpha=.18);ax.legend(loc='lower left',bbox_to_anchor=(0,1.01),fontsize=9,frameon=False);fig.suptitle(title,fontsize=9,y=.99);fig.savefig(out/'plot.svg',metadata={'Date':None});plt.close(fig);print(', '.join(k+'='+display(v)for k,v in summary.items()))\nif __name__=='__main__':\n import sys\n try:run_fixed(API,INPUT,sys.argv[1]if len(sys.argv)>1 else'fixed-results',sys.argv[2]if len(sys.argv)>2 else'ml09-sources')\n except ValueError as error:print('Rejected declared input: '+str(error),file=sys.stderr);sys.exit(2)\n",
        "inputFiles": [
          {
            "file": "ml09-sources/actual3150-churn-original14-fields-and-selection.csv",
            "sha256": "6f5b9e98ce1896582629646dd4cfe7b1aca78c491f7e412a93840534e8b49f48"
          },
          {
            "file": "ml09-sources/actual320-country-four-indicators-original-2020-2024.csv",
            "sha256": "cedc2f748ce14601c76b254c35aea7ef0ee5f06f2928506c225efcbfb1f69390"
          },
          {
            "file": "ml09-sources/actual3613-NLS-original52-fields-and-selection.csv",
            "sha256": "7ae23478bdfee0922157264655e1a2081999f11686773478835bce315068e0df"
          }
        ],
        "input": {
          "kind": "person"
        },
        "returnCode": 0,
        "expectedFailure": false,
        "stdout": "outer.scoreable=604.000000000, outer.meanLoss=5.748800284, baseline.meanLoss=6.409952708, OOB.scoreable=1791.000000000, OOB.meanLoss=6.446577514\n",
        "stderr": "",
        "summary": {
          "outer.scoreable": "604.000000000",
          "outer.meanLoss": "5.748800284",
          "baseline.meanLoss": "6.409952708",
          "OOB.scoreable": "1791.000000000",
          "OOB.meanLoss": "6.446577514"
        },
        "plotPoints": [
          {
            "x": "1",
            "y": "729/100",
            "series": "Observed outcome"
          },
          {
            "x": "1",
            "y": "25986452309/4270665000",
            "series": "Forest prediction"
          },
          {
            "x": "2",
            "y": "103/20",
            "series": "Observed outcome"
          },
          {
            "x": "2",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "3",
            "y": "447/50",
            "series": "Observed outcome"
          },
          {
            "x": "3",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "4",
            "y": "23/4",
            "series": "Observed outcome"
          },
          {
            "x": "4",
            "y": "180424181471/38768805000",
            "series": "Forest prediction"
          },
          {
            "x": "5",
            "y": "363/50",
            "series": "Observed outcome"
          },
          {
            "x": "5",
            "y": "25986452309/4270665000",
            "series": "Forest prediction"
          },
          {
            "x": "6",
            "y": "3",
            "series": "Observed outcome"
          },
          {
            "x": "6",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "7",
            "y": "52/25",
            "series": "Observed outcome"
          },
          {
            "x": "7",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "8",
            "y": "481/50",
            "series": "Observed outcome"
          },
          {
            "x": "8",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "9",
            "y": "81/25",
            "series": "Observed outcome"
          },
          {
            "x": "9",
            "y": "79585086737/16369051000",
            "series": "Forest prediction"
          },
          {
            "x": "10",
            "y": "13/2",
            "series": "Observed outcome"
          },
          {
            "x": "10",
            "y": "1997866201/355110000",
            "series": "Forest prediction"
          },
          {
            "x": "11",
            "y": "621/100",
            "series": "Observed outcome"
          },
          {
            "x": "11",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "12",
            "y": "269/50",
            "series": "Observed outcome"
          },
          {
            "x": "12",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "13",
            "y": "148/25",
            "series": "Observed outcome"
          },
          {
            "x": "13",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "14",
            "y": "269/50",
            "series": "Observed outcome"
          },
          {
            "x": "14",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "15",
            "y": "7",
            "series": "Observed outcome"
          },
          {
            "x": "15",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "16",
            "y": "283/100",
            "series": "Observed outcome"
          },
          {
            "x": "16",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "17",
            "y": "11/2",
            "series": "Observed outcome"
          },
          {
            "x": "17",
            "y": "7286242967/1398495000",
            "series": "Forest prediction"
          },
          {
            "x": "18",
            "y": "25/4",
            "series": "Observed outcome"
          },
          {
            "x": "18",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "19",
            "y": "173/20",
            "series": "Observed outcome"
          },
          {
            "x": "19",
            "y": "381373988437/67274970000",
            "series": "Forest prediction"
          },
          {
            "x": "20",
            "y": "25/4",
            "series": "Observed outcome"
          },
          {
            "x": "20",
            "y": "2312753/298125",
            "series": "Forest prediction"
          },
          {
            "x": "21",
            "y": "769/100",
            "series": "Observed outcome"
          },
          {
            "x": "21",
            "y": "2312753/298125",
            "series": "Forest prediction"
          },
          {
            "x": "22",
            "y": "577/50",
            "series": "Observed outcome"
          },
          {
            "x": "22",
            "y": "25986452309/4270665000",
            "series": "Forest prediction"
          },
          {
            "x": "23",
            "y": "341/50",
            "series": "Observed outcome"
          },
          {
            "x": "23",
            "y": "2312753/298125",
            "series": "Forest prediction"
          },
          {
            "x": "24",
            "y": "201/20",
            "series": "Observed outcome"
          },
          {
            "x": "24",
            "y": "2312753/298125",
            "series": "Forest prediction"
          },
          {
            "x": "25",
            "y": "529/100",
            "series": "Observed outcome"
          },
          {
            "x": "25",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "26",
            "y": "25/4",
            "series": "Observed outcome"
          },
          {
            "x": "26",
            "y": "25986452309/4270665000",
            "series": "Forest prediction"
          },
          {
            "x": "27",
            "y": "481/50",
            "series": "Observed outcome"
          },
          {
            "x": "27",
            "y": "2312753/298125",
            "series": "Forest prediction"
          },
          {
            "x": "28",
            "y": "2",
            "series": "Observed outcome"
          },
          {
            "x": "28",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "29",
            "y": "793/100",
            "series": "Observed outcome"
          },
          {
            "x": "29",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "30",
            "y": "347/50",
            "series": "Observed outcome"
          },
          {
            "x": "30",
            "y": "381373988437/67274970000",
            "series": "Forest prediction"
          },
          {
            "x": "31",
            "y": "14",
            "series": "Observed outcome"
          },
          {
            "x": "31",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "32",
            "y": "77/20",
            "series": "Observed outcome"
          },
          {
            "x": "32",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "33",
            "y": "57/20",
            "series": "Observed outcome"
          },
          {
            "x": "33",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "34",
            "y": "159/20",
            "series": "Observed outcome"
          },
          {
            "x": "34",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "35",
            "y": "673/100",
            "series": "Observed outcome"
          },
          {
            "x": "35",
            "y": "25986452309/4270665000",
            "series": "Forest prediction"
          },
          {
            "x": "36",
            "y": "144/25",
            "series": "Observed outcome"
          },
          {
            "x": "36",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "37",
            "y": "257/50",
            "series": "Observed outcome"
          },
          {
            "x": "37",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "38",
            "y": "289/100",
            "series": "Observed outcome"
          },
          {
            "x": "38",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "39",
            "y": "199/20",
            "series": "Observed outcome"
          },
          {
            "x": "39",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "40",
            "y": "343/50",
            "series": "Observed outcome"
          },
          {
            "x": "40",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "41",
            "y": "769/100",
            "series": "Observed outcome"
          },
          {
            "x": "41",
            "y": "381373988437/67274970000",
            "series": "Forest prediction"
          },
          {
            "x": "42",
            "y": "101/20",
            "series": "Observed outcome"
          },
          {
            "x": "42",
            "y": "25986452309/4270665000",
            "series": "Forest prediction"
          },
          {
            "x": "43",
            "y": "577/50",
            "series": "Observed outcome"
          },
          {
            "x": "43",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "44",
            "y": "2",
            "series": "Observed outcome"
          },
          {
            "x": "44",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "45",
            "y": "147/25",
            "series": "Observed outcome"
          },
          {
            "x": "45",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "46",
            "y": "929/100",
            "series": "Observed outcome"
          },
          {
            "x": "46",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "47",
            "y": "389/100",
            "series": "Observed outcome"
          },
          {
            "x": "47",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "48",
            "y": "101/50",
            "series": "Observed outcome"
          },
          {
            "x": "48",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "49",
            "y": "481/100",
            "series": "Observed outcome"
          },
          {
            "x": "49",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "50",
            "y": "119/25",
            "series": "Observed outcome"
          },
          {
            "x": "50",
            "y": "79585086737/16369051000",
            "series": "Forest prediction"
          },
          {
            "x": "51",
            "y": "7",
            "series": "Observed outcome"
          },
          {
            "x": "51",
            "y": "7286242967/1398495000",
            "series": "Forest prediction"
          },
          {
            "x": "52",
            "y": "38/5",
            "series": "Observed outcome"
          },
          {
            "x": "52",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "53",
            "y": "4",
            "series": "Observed outcome"
          },
          {
            "x": "53",
            "y": "1997866201/355110000",
            "series": "Forest prediction"
          },
          {
            "x": "54",
            "y": "577/100",
            "series": "Observed outcome"
          },
          {
            "x": "54",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "55",
            "y": "77/10",
            "series": "Observed outcome"
          },
          {
            "x": "55",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "56",
            "y": "123/20",
            "series": "Observed outcome"
          },
          {
            "x": "56",
            "y": "25986452309/4270665000",
            "series": "Forest prediction"
          },
          {
            "x": "57",
            "y": "15/2",
            "series": "Observed outcome"
          },
          {
            "x": "57",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "58",
            "y": "313/100",
            "series": "Observed outcome"
          },
          {
            "x": "58",
            "y": "180424181471/38768805000",
            "series": "Forest prediction"
          },
          {
            "x": "59",
            "y": "15/2",
            "series": "Observed outcome"
          },
          {
            "x": "59",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "60",
            "y": "591/100",
            "series": "Observed outcome"
          },
          {
            "x": "60",
            "y": "381373988437/67274970000",
            "series": "Forest prediction"
          },
          {
            "x": "61",
            "y": "122/25",
            "series": "Observed outcome"
          },
          {
            "x": "61",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "62",
            "y": "493/50",
            "series": "Observed outcome"
          },
          {
            "x": "62",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "63",
            "y": "123/20",
            "series": "Observed outcome"
          },
          {
            "x": "63",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "64",
            "y": "231/50",
            "series": "Observed outcome"
          },
          {
            "x": "64",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "65",
            "y": "32/5",
            "series": "Observed outcome"
          },
          {
            "x": "65",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "66",
            "y": "101/10",
            "series": "Observed outcome"
          },
          {
            "x": "66",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "67",
            "y": "1387/100",
            "series": "Observed outcome"
          },
          {
            "x": "67",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "68",
            "y": "481/100",
            "series": "Observed outcome"
          },
          {
            "x": "68",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "69",
            "y": "579/100",
            "series": "Observed outcome"
          },
          {
            "x": "69",
            "y": "25986452309/4270665000",
            "series": "Forest prediction"
          },
          {
            "x": "70",
            "y": "481/50",
            "series": "Observed outcome"
          },
          {
            "x": "70",
            "y": "25986452309/4270665000",
            "series": "Forest prediction"
          },
          {
            "x": "71",
            "y": "24/5",
            "series": "Observed outcome"
          },
          {
            "x": "71",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "72",
            "y": "417/100",
            "series": "Observed outcome"
          },
          {
            "x": "72",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "73",
            "y": "721/100",
            "series": "Observed outcome"
          },
          {
            "x": "73",
            "y": "25986452309/4270665000",
            "series": "Forest prediction"
          },
          {
            "x": "74",
            "y": "529/50",
            "series": "Observed outcome"
          },
          {
            "x": "74",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "75",
            "y": "481/50",
            "series": "Observed outcome"
          },
          {
            "x": "75",
            "y": "2312753/298125",
            "series": "Forest prediction"
          },
          {
            "x": "76",
            "y": "101/10",
            "series": "Observed outcome"
          },
          {
            "x": "76",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "77",
            "y": "5",
            "series": "Observed outcome"
          },
          {
            "x": "77",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "78",
            "y": "721/50",
            "series": "Observed outcome"
          },
          {
            "x": "78",
            "y": "381373988437/67274970000",
            "series": "Forest prediction"
          },
          {
            "x": "79",
            "y": "269/50",
            "series": "Observed outcome"
          },
          {
            "x": "79",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "80",
            "y": "561/100",
            "series": "Observed outcome"
          },
          {
            "x": "80",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "81",
            "y": "437/100",
            "series": "Observed outcome"
          },
          {
            "x": "81",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "82",
            "y": "15/2",
            "series": "Observed outcome"
          },
          {
            "x": "82",
            "y": "25986452309/4270665000",
            "series": "Forest prediction"
          },
          {
            "x": "83",
            "y": "111/20",
            "series": "Observed outcome"
          },
          {
            "x": "83",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "84",
            "y": "149/20",
            "series": "Observed outcome"
          },
          {
            "x": "84",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "85",
            "y": "173/20",
            "series": "Observed outcome"
          },
          {
            "x": "85",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "86",
            "y": "529/100",
            "series": "Observed outcome"
          },
          {
            "x": "86",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "87",
            "y": "889/100",
            "series": "Observed outcome"
          },
          {
            "x": "87",
            "y": "2312753/298125",
            "series": "Forest prediction"
          },
          {
            "x": "88",
            "y": "31/4",
            "series": "Observed outcome"
          },
          {
            "x": "88",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "89",
            "y": "333/100",
            "series": "Observed outcome"
          },
          {
            "x": "89",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "90",
            "y": "577/50",
            "series": "Observed outcome"
          },
          {
            "x": "90",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "91",
            "y": "989/100",
            "series": "Observed outcome"
          },
          {
            "x": "91",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "92",
            "y": "571/100",
            "series": "Observed outcome"
          },
          {
            "x": "92",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "93",
            "y": "97/25",
            "series": "Observed outcome"
          },
          {
            "x": "93",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "94",
            "y": "261/25",
            "series": "Observed outcome"
          },
          {
            "x": "94",
            "y": "25986452309/4270665000",
            "series": "Forest prediction"
          },
          {
            "x": "95",
            "y": "577/100",
            "series": "Observed outcome"
          },
          {
            "x": "95",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "96",
            "y": "25/4",
            "series": "Observed outcome"
          },
          {
            "x": "96",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "97",
            "y": "131/25",
            "series": "Observed outcome"
          },
          {
            "x": "97",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "98",
            "y": "213/50",
            "series": "Observed outcome"
          },
          {
            "x": "98",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "99",
            "y": "13/4",
            "series": "Observed outcome"
          },
          {
            "x": "99",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "100",
            "y": "122/25",
            "series": "Observed outcome"
          },
          {
            "x": "100",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "101",
            "y": "15/4",
            "series": "Observed outcome"
          },
          {
            "x": "101",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "102",
            "y": "319/50",
            "series": "Observed outcome"
          },
          {
            "x": "102",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "103",
            "y": "629/100",
            "series": "Observed outcome"
          },
          {
            "x": "103",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "104",
            "y": "639/100",
            "series": "Observed outcome"
          },
          {
            "x": "104",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "105",
            "y": "10",
            "series": "Observed outcome"
          },
          {
            "x": "105",
            "y": "1997866201/355110000",
            "series": "Forest prediction"
          },
          {
            "x": "106",
            "y": "159/100",
            "series": "Observed outcome"
          },
          {
            "x": "106",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "107",
            "y": "553/100",
            "series": "Observed outcome"
          },
          {
            "x": "107",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "108",
            "y": "721/50",
            "series": "Observed outcome"
          },
          {
            "x": "108",
            "y": "25986452309/4270665000",
            "series": "Forest prediction"
          },
          {
            "x": "109",
            "y": "889/100",
            "series": "Observed outcome"
          },
          {
            "x": "109",
            "y": "25986452309/4270665000",
            "series": "Forest prediction"
          },
          {
            "x": "110",
            "y": "173/25",
            "series": "Observed outcome"
          },
          {
            "x": "110",
            "y": "2312753/298125",
            "series": "Forest prediction"
          },
          {
            "x": "111",
            "y": "28/5",
            "series": "Observed outcome"
          },
          {
            "x": "111",
            "y": "381373988437/67274970000",
            "series": "Forest prediction"
          },
          {
            "x": "112",
            "y": "299/50",
            "series": "Observed outcome"
          },
          {
            "x": "112",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "113",
            "y": "253/50",
            "series": "Observed outcome"
          },
          {
            "x": "113",
            "y": "381373988437/67274970000",
            "series": "Forest prediction"
          },
          {
            "x": "114",
            "y": "557/100",
            "series": "Observed outcome"
          },
          {
            "x": "114",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "115",
            "y": "146/25",
            "series": "Observed outcome"
          },
          {
            "x": "115",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "116",
            "y": "69/10",
            "series": "Observed outcome"
          },
          {
            "x": "116",
            "y": "25986452309/4270665000",
            "series": "Forest prediction"
          },
          {
            "x": "117",
            "y": "89/25",
            "series": "Observed outcome"
          },
          {
            "x": "117",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "118",
            "y": "37/5",
            "series": "Observed outcome"
          },
          {
            "x": "118",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "119",
            "y": "239/100",
            "series": "Observed outcome"
          },
          {
            "x": "119",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "120",
            "y": "173/25",
            "series": "Observed outcome"
          },
          {
            "x": "120",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "121",
            "y": "517/100",
            "series": "Observed outcome"
          },
          {
            "x": "121",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "122",
            "y": "149/25",
            "series": "Observed outcome"
          },
          {
            "x": "122",
            "y": "381373988437/67274970000",
            "series": "Forest prediction"
          },
          {
            "x": "123",
            "y": "481/100",
            "series": "Observed outcome"
          },
          {
            "x": "123",
            "y": "2312753/298125",
            "series": "Forest prediction"
          },
          {
            "x": "124",
            "y": "769/100",
            "series": "Observed outcome"
          },
          {
            "x": "124",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "125",
            "y": "377/100",
            "series": "Observed outcome"
          },
          {
            "x": "125",
            "y": "25986452309/4270665000",
            "series": "Forest prediction"
          },
          {
            "x": "126",
            "y": "179/25",
            "series": "Observed outcome"
          },
          {
            "x": "126",
            "y": "25986452309/4270665000",
            "series": "Forest prediction"
          },
          {
            "x": "127",
            "y": "25/4",
            "series": "Observed outcome"
          },
          {
            "x": "127",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "128",
            "y": "231/50",
            "series": "Observed outcome"
          },
          {
            "x": "128",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "129",
            "y": "129/20",
            "series": "Observed outcome"
          },
          {
            "x": "129",
            "y": "381373988437/67274970000",
            "series": "Forest prediction"
          },
          {
            "x": "130",
            "y": "21/4",
            "series": "Observed outcome"
          },
          {
            "x": "130",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "131",
            "y": "142/25",
            "series": "Observed outcome"
          },
          {
            "x": "131",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "132",
            "y": "581/100",
            "series": "Observed outcome"
          },
          {
            "x": "132",
            "y": "25986452309/4270665000",
            "series": "Forest prediction"
          },
          {
            "x": "133",
            "y": "5",
            "series": "Observed outcome"
          },
          {
            "x": "133",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "134",
            "y": "6",
            "series": "Observed outcome"
          },
          {
            "x": "134",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "135",
            "y": "243/100",
            "series": "Observed outcome"
          },
          {
            "x": "135",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "136",
            "y": "4",
            "series": "Observed outcome"
          },
          {
            "x": "136",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "137",
            "y": "1043/100",
            "series": "Observed outcome"
          },
          {
            "x": "137",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "138",
            "y": "23/4",
            "series": "Observed outcome"
          },
          {
            "x": "138",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "139",
            "y": "331/50",
            "series": "Observed outcome"
          },
          {
            "x": "139",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "140",
            "y": "947/100",
            "series": "Observed outcome"
          },
          {
            "x": "140",
            "y": "1997866201/355110000",
            "series": "Forest prediction"
          },
          {
            "x": "141",
            "y": "12/5",
            "series": "Observed outcome"
          },
          {
            "x": "141",
            "y": "180424181471/38768805000",
            "series": "Forest prediction"
          },
          {
            "x": "142",
            "y": "727/100",
            "series": "Observed outcome"
          },
          {
            "x": "142",
            "y": "180424181471/38768805000",
            "series": "Forest prediction"
          },
          {
            "x": "143",
            "y": "15/2",
            "series": "Observed outcome"
          },
          {
            "x": "143",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "144",
            "y": "641/100",
            "series": "Observed outcome"
          },
          {
            "x": "144",
            "y": "381373988437/67274970000",
            "series": "Forest prediction"
          },
          {
            "x": "145",
            "y": "77/25",
            "series": "Observed outcome"
          },
          {
            "x": "145",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "146",
            "y": "409/100",
            "series": "Observed outcome"
          },
          {
            "x": "146",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "147",
            "y": "541/50",
            "series": "Observed outcome"
          },
          {
            "x": "147",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "148",
            "y": "673/100",
            "series": "Observed outcome"
          },
          {
            "x": "148",
            "y": "2312753/298125",
            "series": "Forest prediction"
          },
          {
            "x": "149",
            "y": "481/100",
            "series": "Observed outcome"
          },
          {
            "x": "149",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "150",
            "y": "577/100",
            "series": "Observed outcome"
          },
          {
            "x": "150",
            "y": "2312753/298125",
            "series": "Forest prediction"
          },
          {
            "x": "151",
            "y": "211/20",
            "series": "Observed outcome"
          },
          {
            "x": "151",
            "y": "25986452309/4270665000",
            "series": "Forest prediction"
          },
          {
            "x": "152",
            "y": "673/100",
            "series": "Observed outcome"
          },
          {
            "x": "152",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "153",
            "y": "247/50",
            "series": "Observed outcome"
          },
          {
            "x": "153",
            "y": "2312753/298125",
            "series": "Forest prediction"
          },
          {
            "x": "154",
            "y": "601/100",
            "series": "Observed outcome"
          },
          {
            "x": "154",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "155",
            "y": "643/100",
            "series": "Observed outcome"
          },
          {
            "x": "155",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "156",
            "y": "667/100",
            "series": "Observed outcome"
          },
          {
            "x": "156",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "157",
            "y": "311/100",
            "series": "Observed outcome"
          },
          {
            "x": "157",
            "y": "2312753/298125",
            "series": "Forest prediction"
          },
          {
            "x": "158",
            "y": "577/100",
            "series": "Observed outcome"
          },
          {
            "x": "158",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "159",
            "y": "601/50",
            "series": "Observed outcome"
          },
          {
            "x": "159",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "160",
            "y": "161/20",
            "series": "Observed outcome"
          },
          {
            "x": "160",
            "y": "381373988437/67274970000",
            "series": "Forest prediction"
          },
          {
            "x": "161",
            "y": "171/20",
            "series": "Observed outcome"
          },
          {
            "x": "161",
            "y": "25986452309/4270665000",
            "series": "Forest prediction"
          },
          {
            "x": "162",
            "y": "561/100",
            "series": "Observed outcome"
          },
          {
            "x": "162",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "163",
            "y": "673/100",
            "series": "Observed outcome"
          },
          {
            "x": "163",
            "y": "2312753/298125",
            "series": "Forest prediction"
          },
          {
            "x": "164",
            "y": "5",
            "series": "Observed outcome"
          },
          {
            "x": "164",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "165",
            "y": "151/20",
            "series": "Observed outcome"
          },
          {
            "x": "165",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "166",
            "y": "6",
            "series": "Observed outcome"
          },
          {
            "x": "166",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "167",
            "y": "6",
            "series": "Observed outcome"
          },
          {
            "x": "167",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "168",
            "y": "10",
            "series": "Observed outcome"
          },
          {
            "x": "168",
            "y": "180424181471/38768805000",
            "series": "Forest prediction"
          },
          {
            "x": "169",
            "y": "707/100",
            "series": "Observed outcome"
          },
          {
            "x": "169",
            "y": "381373988437/67274970000",
            "series": "Forest prediction"
          },
          {
            "x": "170",
            "y": "661/50",
            "series": "Observed outcome"
          },
          {
            "x": "170",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "171",
            "y": "6",
            "series": "Observed outcome"
          },
          {
            "x": "171",
            "y": "1997866201/355110000",
            "series": "Forest prediction"
          },
          {
            "x": "172",
            "y": "4",
            "series": "Observed outcome"
          },
          {
            "x": "172",
            "y": "2312753/298125",
            "series": "Forest prediction"
          },
          {
            "x": "173",
            "y": "109/20",
            "series": "Observed outcome"
          },
          {
            "x": "173",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "174",
            "y": "549/100",
            "series": "Observed outcome"
          },
          {
            "x": "174",
            "y": "25986452309/4270665000",
            "series": "Forest prediction"
          },
          {
            "x": "175",
            "y": "9",
            "series": "Observed outcome"
          },
          {
            "x": "175",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "176",
            "y": "5",
            "series": "Observed outcome"
          },
          {
            "x": "176",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "177",
            "y": "316/25",
            "series": "Observed outcome"
          },
          {
            "x": "177",
            "y": "2312753/298125",
            "series": "Forest prediction"
          },
          {
            "x": "178",
            "y": "983/100",
            "series": "Observed outcome"
          },
          {
            "x": "178",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "179",
            "y": "111/25",
            "series": "Observed outcome"
          },
          {
            "x": "179",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "180",
            "y": "5",
            "series": "Observed outcome"
          },
          {
            "x": "180",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "181",
            "y": "363/50",
            "series": "Observed outcome"
          },
          {
            "x": "181",
            "y": "25986452309/4270665000",
            "series": "Forest prediction"
          },
          {
            "x": "182",
            "y": "547/50",
            "series": "Observed outcome"
          },
          {
            "x": "182",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "183",
            "y": "164/25",
            "series": "Observed outcome"
          },
          {
            "x": "183",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "184",
            "y": "351/50",
            "series": "Observed outcome"
          },
          {
            "x": "184",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "185",
            "y": "649/100",
            "series": "Observed outcome"
          },
          {
            "x": "185",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "186",
            "y": "139/25",
            "series": "Observed outcome"
          },
          {
            "x": "186",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "187",
            "y": "781/100",
            "series": "Observed outcome"
          },
          {
            "x": "187",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "188",
            "y": "481/50",
            "series": "Observed outcome"
          },
          {
            "x": "188",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "189",
            "y": "469/50",
            "series": "Observed outcome"
          },
          {
            "x": "189",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "190",
            "y": "409/50",
            "series": "Observed outcome"
          },
          {
            "x": "190",
            "y": "2312753/298125",
            "series": "Forest prediction"
          },
          {
            "x": "191",
            "y": "123/20",
            "series": "Observed outcome"
          },
          {
            "x": "191",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "192",
            "y": "48/25",
            "series": "Observed outcome"
          },
          {
            "x": "192",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "193",
            "y": "219/50",
            "series": "Observed outcome"
          },
          {
            "x": "193",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "194",
            "y": "447/100",
            "series": "Observed outcome"
          },
          {
            "x": "194",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "195",
            "y": "57/10",
            "series": "Observed outcome"
          },
          {
            "x": "195",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "196",
            "y": "529/100",
            "series": "Observed outcome"
          },
          {
            "x": "196",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "197",
            "y": "173/20",
            "series": "Observed outcome"
          },
          {
            "x": "197",
            "y": "25986452309/4270665000",
            "series": "Forest prediction"
          },
          {
            "x": "198",
            "y": "797/100",
            "series": "Observed outcome"
          },
          {
            "x": "198",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "199",
            "y": "393/100",
            "series": "Observed outcome"
          },
          {
            "x": "199",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "200",
            "y": "481/100",
            "series": "Observed outcome"
          },
          {
            "x": "200",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "201",
            "y": "24/25",
            "series": "Observed outcome"
          },
          {
            "x": "201",
            "y": "1997866201/355110000",
            "series": "Forest prediction"
          },
          {
            "x": "202",
            "y": "113/50",
            "series": "Observed outcome"
          },
          {
            "x": "202",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "203",
            "y": "23/5",
            "series": "Observed outcome"
          },
          {
            "x": "203",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "204",
            "y": "189/50",
            "series": "Observed outcome"
          },
          {
            "x": "204",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "205",
            "y": "491/100",
            "series": "Observed outcome"
          },
          {
            "x": "205",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "206",
            "y": "253/50",
            "series": "Observed outcome"
          },
          {
            "x": "206",
            "y": "2312753/298125",
            "series": "Forest prediction"
          },
          {
            "x": "207",
            "y": "147/25",
            "series": "Observed outcome"
          },
          {
            "x": "207",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "208",
            "y": "831/100",
            "series": "Observed outcome"
          },
          {
            "x": "208",
            "y": "2312753/298125",
            "series": "Forest prediction"
          },
          {
            "x": "209",
            "y": "241/25",
            "series": "Observed outcome"
          },
          {
            "x": "209",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "210",
            "y": "609/100",
            "series": "Observed outcome"
          },
          {
            "x": "210",
            "y": "381373988437/67274970000",
            "series": "Forest prediction"
          },
          {
            "x": "211",
            "y": "5",
            "series": "Observed outcome"
          },
          {
            "x": "211",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "212",
            "y": "33/10",
            "series": "Observed outcome"
          },
          {
            "x": "212",
            "y": "25986452309/4270665000",
            "series": "Forest prediction"
          },
          {
            "x": "213",
            "y": "359/100",
            "series": "Observed outcome"
          },
          {
            "x": "213",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "214",
            "y": "653/100",
            "series": "Observed outcome"
          },
          {
            "x": "214",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "215",
            "y": "311/50",
            "series": "Observed outcome"
          },
          {
            "x": "215",
            "y": "2312753/298125",
            "series": "Forest prediction"
          },
          {
            "x": "216",
            "y": "23/4",
            "series": "Observed outcome"
          },
          {
            "x": "216",
            "y": "25986452309/4270665000",
            "series": "Forest prediction"
          },
          {
            "x": "217",
            "y": "3",
            "series": "Observed outcome"
          },
          {
            "x": "217",
            "y": "2312753/298125",
            "series": "Forest prediction"
          },
          {
            "x": "218",
            "y": "817/100",
            "series": "Observed outcome"
          },
          {
            "x": "218",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "219",
            "y": "5",
            "series": "Observed outcome"
          },
          {
            "x": "219",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "220",
            "y": "21/4",
            "series": "Observed outcome"
          },
          {
            "x": "220",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "221",
            "y": "151/25",
            "series": "Observed outcome"
          },
          {
            "x": "221",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "222",
            "y": "357/50",
            "series": "Observed outcome"
          },
          {
            "x": "222",
            "y": "381373988437/67274970000",
            "series": "Forest prediction"
          },
          {
            "x": "223",
            "y": "164/25",
            "series": "Observed outcome"
          },
          {
            "x": "223",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "224",
            "y": "673/100",
            "series": "Observed outcome"
          },
          {
            "x": "224",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "225",
            "y": "38/5",
            "series": "Observed outcome"
          },
          {
            "x": "225",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "226",
            "y": "19/4",
            "series": "Observed outcome"
          },
          {
            "x": "226",
            "y": "381373988437/67274970000",
            "series": "Forest prediction"
          },
          {
            "x": "227",
            "y": "9/4",
            "series": "Observed outcome"
          },
          {
            "x": "227",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "228",
            "y": "817/100",
            "series": "Observed outcome"
          },
          {
            "x": "228",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "229",
            "y": "897/100",
            "series": "Observed outcome"
          },
          {
            "x": "229",
            "y": "79585086737/16369051000",
            "series": "Forest prediction"
          },
          {
            "x": "230",
            "y": "929/100",
            "series": "Observed outcome"
          },
          {
            "x": "230",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "231",
            "y": "133/50",
            "series": "Observed outcome"
          },
          {
            "x": "231",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "232",
            "y": "801/100",
            "series": "Observed outcome"
          },
          {
            "x": "232",
            "y": "79585086737/16369051000",
            "series": "Forest prediction"
          },
          {
            "x": "233",
            "y": "6",
            "series": "Observed outcome"
          },
          {
            "x": "233",
            "y": "2312753/298125",
            "series": "Forest prediction"
          },
          {
            "x": "234",
            "y": "329/50",
            "series": "Observed outcome"
          },
          {
            "x": "234",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "235",
            "y": "149/25",
            "series": "Observed outcome"
          },
          {
            "x": "235",
            "y": "180424181471/38768805000",
            "series": "Forest prediction"
          },
          {
            "x": "236",
            "y": "721/100",
            "series": "Observed outcome"
          },
          {
            "x": "236",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "237",
            "y": "563/100",
            "series": "Observed outcome"
          },
          {
            "x": "237",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "238",
            "y": "47/10",
            "series": "Observed outcome"
          },
          {
            "x": "238",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "239",
            "y": "389/100",
            "series": "Observed outcome"
          },
          {
            "x": "239",
            "y": "79585086737/16369051000",
            "series": "Forest prediction"
          },
          {
            "x": "240",
            "y": "13/2",
            "series": "Observed outcome"
          },
          {
            "x": "240",
            "y": "1997866201/355110000",
            "series": "Forest prediction"
          },
          {
            "x": "241",
            "y": "759/100",
            "series": "Observed outcome"
          },
          {
            "x": "241",
            "y": "2312753/298125",
            "series": "Forest prediction"
          },
          {
            "x": "242",
            "y": "183/20",
            "series": "Observed outcome"
          },
          {
            "x": "242",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "243",
            "y": "267/100",
            "series": "Observed outcome"
          },
          {
            "x": "243",
            "y": "79585086737/16369051000",
            "series": "Forest prediction"
          },
          {
            "x": "244",
            "y": "721/100",
            "series": "Observed outcome"
          },
          {
            "x": "244",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "245",
            "y": "423/100",
            "series": "Observed outcome"
          },
          {
            "x": "245",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "246",
            "y": "41/10",
            "series": "Observed outcome"
          },
          {
            "x": "246",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "247",
            "y": "9/2",
            "series": "Observed outcome"
          },
          {
            "x": "247",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "248",
            "y": "817/100",
            "series": "Observed outcome"
          },
          {
            "x": "248",
            "y": "381373988437/67274970000",
            "series": "Forest prediction"
          },
          {
            "x": "249",
            "y": "913/100",
            "series": "Observed outcome"
          },
          {
            "x": "249",
            "y": "25986452309/4270665000",
            "series": "Forest prediction"
          },
          {
            "x": "250",
            "y": "99/25",
            "series": "Observed outcome"
          },
          {
            "x": "250",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "251",
            "y": "231/50",
            "series": "Observed outcome"
          },
          {
            "x": "251",
            "y": "2312753/298125",
            "series": "Forest prediction"
          },
          {
            "x": "252",
            "y": "549/100",
            "series": "Observed outcome"
          },
          {
            "x": "252",
            "y": "381373988437/67274970000",
            "series": "Forest prediction"
          },
          {
            "x": "253",
            "y": "77/20",
            "series": "Observed outcome"
          },
          {
            "x": "253",
            "y": "180424181471/38768805000",
            "series": "Forest prediction"
          },
          {
            "x": "254",
            "y": "154/25",
            "series": "Observed outcome"
          },
          {
            "x": "254",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "255",
            "y": "43/10",
            "series": "Observed outcome"
          },
          {
            "x": "255",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "256",
            "y": "11",
            "series": "Observed outcome"
          },
          {
            "x": "256",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "257",
            "y": "921/100",
            "series": "Observed outcome"
          },
          {
            "x": "257",
            "y": "25986452309/4270665000",
            "series": "Forest prediction"
          },
          {
            "x": "258",
            "y": "411/100",
            "series": "Observed outcome"
          },
          {
            "x": "258",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "259",
            "y": "423/100",
            "series": "Observed outcome"
          },
          {
            "x": "259",
            "y": "7286242967/1398495000",
            "series": "Forest prediction"
          },
          {
            "x": "260",
            "y": "6",
            "series": "Observed outcome"
          },
          {
            "x": "260",
            "y": "381373988437/67274970000",
            "series": "Forest prediction"
          },
          {
            "x": "261",
            "y": "449/100",
            "series": "Observed outcome"
          },
          {
            "x": "261",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "262",
            "y": "571/100",
            "series": "Observed outcome"
          },
          {
            "x": "262",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "263",
            "y": "721/100",
            "series": "Observed outcome"
          },
          {
            "x": "263",
            "y": "2312753/298125",
            "series": "Forest prediction"
          },
          {
            "x": "264",
            "y": "713/100",
            "series": "Observed outcome"
          },
          {
            "x": "264",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "265",
            "y": "13/5",
            "series": "Observed outcome"
          },
          {
            "x": "265",
            "y": "25986452309/4270665000",
            "series": "Forest prediction"
          },
          {
            "x": "266",
            "y": "31/5",
            "series": "Observed outcome"
          },
          {
            "x": "266",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "267",
            "y": "202/25",
            "series": "Observed outcome"
          },
          {
            "x": "267",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "268",
            "y": "693/100",
            "series": "Observed outcome"
          },
          {
            "x": "268",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "269",
            "y": "4",
            "series": "Observed outcome"
          },
          {
            "x": "269",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "270",
            "y": "7",
            "series": "Observed outcome"
          },
          {
            "x": "270",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "271",
            "y": "211/20",
            "series": "Observed outcome"
          },
          {
            "x": "271",
            "y": "25986452309/4270665000",
            "series": "Forest prediction"
          },
          {
            "x": "272",
            "y": "162/25",
            "series": "Observed outcome"
          },
          {
            "x": "272",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "273",
            "y": "17/4",
            "series": "Observed outcome"
          },
          {
            "x": "273",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "274",
            "y": "11",
            "series": "Observed outcome"
          },
          {
            "x": "274",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "275",
            "y": "7",
            "series": "Observed outcome"
          },
          {
            "x": "275",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "276",
            "y": "67/20",
            "series": "Observed outcome"
          },
          {
            "x": "276",
            "y": "79585086737/16369051000",
            "series": "Forest prediction"
          },
          {
            "x": "277",
            "y": "25/4",
            "series": "Observed outcome"
          },
          {
            "x": "277",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "278",
            "y": "11/2",
            "series": "Observed outcome"
          },
          {
            "x": "278",
            "y": "381373988437/67274970000",
            "series": "Forest prediction"
          },
          {
            "x": "279",
            "y": "713/100",
            "series": "Observed outcome"
          },
          {
            "x": "279",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "280",
            "y": "633/100",
            "series": "Observed outcome"
          },
          {
            "x": "280",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "281",
            "y": "208/25",
            "series": "Observed outcome"
          },
          {
            "x": "281",
            "y": "2312753/298125",
            "series": "Forest prediction"
          },
          {
            "x": "282",
            "y": "361/50",
            "series": "Observed outcome"
          },
          {
            "x": "282",
            "y": "381373988437/67274970000",
            "series": "Forest prediction"
          },
          {
            "x": "283",
            "y": "393/100",
            "series": "Observed outcome"
          },
          {
            "x": "283",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "284",
            "y": "26/5",
            "series": "Observed outcome"
          },
          {
            "x": "284",
            "y": "79585086737/16369051000",
            "series": "Forest prediction"
          },
          {
            "x": "285",
            "y": "19/4",
            "series": "Observed outcome"
          },
          {
            "x": "285",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "286",
            "y": "577/100",
            "series": "Observed outcome"
          },
          {
            "x": "286",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "287",
            "y": "9/2",
            "series": "Observed outcome"
          },
          {
            "x": "287",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "288",
            "y": "623/100",
            "series": "Observed outcome"
          },
          {
            "x": "288",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "289",
            "y": "721/100",
            "series": "Observed outcome"
          },
          {
            "x": "289",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "290",
            "y": "363/100",
            "series": "Observed outcome"
          },
          {
            "x": "290",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "291",
            "y": "879/100",
            "series": "Observed outcome"
          },
          {
            "x": "291",
            "y": "25986452309/4270665000",
            "series": "Forest prediction"
          },
          {
            "x": "292",
            "y": "13/4",
            "series": "Observed outcome"
          },
          {
            "x": "292",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "293",
            "y": "66/25",
            "series": "Observed outcome"
          },
          {
            "x": "293",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "294",
            "y": "49/5",
            "series": "Observed outcome"
          },
          {
            "x": "294",
            "y": "25986452309/4270665000",
            "series": "Forest prediction"
          },
          {
            "x": "295",
            "y": "463/100",
            "series": "Observed outcome"
          },
          {
            "x": "295",
            "y": "79585086737/16369051000",
            "series": "Forest prediction"
          },
          {
            "x": "296",
            "y": "101/25",
            "series": "Observed outcome"
          },
          {
            "x": "296",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "297",
            "y": "913/100",
            "series": "Observed outcome"
          },
          {
            "x": "297",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "298",
            "y": "123/20",
            "series": "Observed outcome"
          },
          {
            "x": "298",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "299",
            "y": "119/50",
            "series": "Observed outcome"
          },
          {
            "x": "299",
            "y": "180424181471/38768805000",
            "series": "Forest prediction"
          },
          {
            "x": "300",
            "y": "73/20",
            "series": "Observed outcome"
          },
          {
            "x": "300",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "301",
            "y": "231/50",
            "series": "Observed outcome"
          },
          {
            "x": "301",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "302",
            "y": "15/2",
            "series": "Observed outcome"
          },
          {
            "x": "302",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "303",
            "y": "231/50",
            "series": "Observed outcome"
          },
          {
            "x": "303",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "304",
            "y": "28/5",
            "series": "Observed outcome"
          },
          {
            "x": "304",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "305",
            "y": "411/100",
            "series": "Observed outcome"
          },
          {
            "x": "305",
            "y": "381373988437/67274970000",
            "series": "Forest prediction"
          },
          {
            "x": "306",
            "y": "31/4",
            "series": "Observed outcome"
          },
          {
            "x": "306",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "307",
            "y": "35/4",
            "series": "Observed outcome"
          },
          {
            "x": "307",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "308",
            "y": "17/5",
            "series": "Observed outcome"
          },
          {
            "x": "308",
            "y": "25986452309/4270665000",
            "series": "Forest prediction"
          },
          {
            "x": "309",
            "y": "751/50",
            "series": "Observed outcome"
          },
          {
            "x": "309",
            "y": "2312753/298125",
            "series": "Forest prediction"
          },
          {
            "x": "310",
            "y": "331/100",
            "series": "Observed outcome"
          },
          {
            "x": "310",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "311",
            "y": "759/100",
            "series": "Observed outcome"
          },
          {
            "x": "311",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "312",
            "y": "142/25",
            "series": "Observed outcome"
          },
          {
            "x": "312",
            "y": "25986452309/4270665000",
            "series": "Forest prediction"
          },
          {
            "x": "313",
            "y": "25/4",
            "series": "Observed outcome"
          },
          {
            "x": "313",
            "y": "381373988437/67274970000",
            "series": "Forest prediction"
          },
          {
            "x": "314",
            "y": "156/25",
            "series": "Observed outcome"
          },
          {
            "x": "314",
            "y": "1997866201/355110000",
            "series": "Forest prediction"
          },
          {
            "x": "315",
            "y": "337/50",
            "series": "Observed outcome"
          },
          {
            "x": "315",
            "y": "2312753/298125",
            "series": "Forest prediction"
          },
          {
            "x": "316",
            "y": "327/100",
            "series": "Observed outcome"
          },
          {
            "x": "316",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "317",
            "y": "77/20",
            "series": "Observed outcome"
          },
          {
            "x": "317",
            "y": "7286242967/1398495000",
            "series": "Forest prediction"
          },
          {
            "x": "318",
            "y": "149/20",
            "series": "Observed outcome"
          },
          {
            "x": "318",
            "y": "25986452309/4270665000",
            "series": "Forest prediction"
          },
          {
            "x": "319",
            "y": "149/20",
            "series": "Observed outcome"
          },
          {
            "x": "319",
            "y": "2312753/298125",
            "series": "Forest prediction"
          },
          {
            "x": "320",
            "y": "109/20",
            "series": "Observed outcome"
          },
          {
            "x": "320",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "321",
            "y": "577/100",
            "series": "Observed outcome"
          },
          {
            "x": "321",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "322",
            "y": "173/20",
            "series": "Observed outcome"
          },
          {
            "x": "322",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "323",
            "y": "5",
            "series": "Observed outcome"
          },
          {
            "x": "323",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "324",
            "y": "15/2",
            "series": "Observed outcome"
          },
          {
            "x": "324",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "325",
            "y": "137/20",
            "series": "Observed outcome"
          },
          {
            "x": "325",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "326",
            "y": "397/100",
            "series": "Observed outcome"
          },
          {
            "x": "326",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "327",
            "y": "481/50",
            "series": "Observed outcome"
          },
          {
            "x": "327",
            "y": "381373988437/67274970000",
            "series": "Forest prediction"
          },
          {
            "x": "328",
            "y": "27/5",
            "series": "Observed outcome"
          },
          {
            "x": "328",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "329",
            "y": "18/5",
            "series": "Observed outcome"
          },
          {
            "x": "329",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "330",
            "y": "363/50",
            "series": "Observed outcome"
          },
          {
            "x": "330",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "331",
            "y": "15/4",
            "series": "Observed outcome"
          },
          {
            "x": "331",
            "y": "1997866201/355110000",
            "series": "Forest prediction"
          },
          {
            "x": "332",
            "y": "649/100",
            "series": "Observed outcome"
          },
          {
            "x": "332",
            "y": "381373988437/67274970000",
            "series": "Forest prediction"
          },
          {
            "x": "333",
            "y": "63/20",
            "series": "Observed outcome"
          },
          {
            "x": "333",
            "y": "1997866201/355110000",
            "series": "Forest prediction"
          },
          {
            "x": "334",
            "y": "693/100",
            "series": "Observed outcome"
          },
          {
            "x": "334",
            "y": "7286242967/1398495000",
            "series": "Forest prediction"
          },
          {
            "x": "335",
            "y": "4",
            "series": "Observed outcome"
          },
          {
            "x": "335",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "336",
            "y": "481/50",
            "series": "Observed outcome"
          },
          {
            "x": "336",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "337",
            "y": "457/100",
            "series": "Observed outcome"
          },
          {
            "x": "337",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "338",
            "y": "363/100",
            "series": "Observed outcome"
          },
          {
            "x": "338",
            "y": "180424181471/38768805000",
            "series": "Forest prediction"
          },
          {
            "x": "339",
            "y": "427/100",
            "series": "Observed outcome"
          },
          {
            "x": "339",
            "y": "381373988437/67274970000",
            "series": "Forest prediction"
          },
          {
            "x": "340",
            "y": "15/4",
            "series": "Observed outcome"
          },
          {
            "x": "340",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "341",
            "y": "71/20",
            "series": "Observed outcome"
          },
          {
            "x": "341",
            "y": "79585086737/16369051000",
            "series": "Forest prediction"
          },
          {
            "x": "342",
            "y": "443/100",
            "series": "Observed outcome"
          },
          {
            "x": "342",
            "y": "2312753/298125",
            "series": "Forest prediction"
          },
          {
            "x": "343",
            "y": "481/100",
            "series": "Observed outcome"
          },
          {
            "x": "343",
            "y": "7286242967/1398495000",
            "series": "Forest prediction"
          },
          {
            "x": "344",
            "y": "5/2",
            "series": "Observed outcome"
          },
          {
            "x": "344",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "345",
            "y": "687/50",
            "series": "Observed outcome"
          },
          {
            "x": "345",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "346",
            "y": "111/25",
            "series": "Observed outcome"
          },
          {
            "x": "346",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "347",
            "y": "31/10",
            "series": "Observed outcome"
          },
          {
            "x": "347",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "348",
            "y": "673/100",
            "series": "Observed outcome"
          },
          {
            "x": "348",
            "y": "25986452309/4270665000",
            "series": "Forest prediction"
          },
          {
            "x": "349",
            "y": "77/25",
            "series": "Observed outcome"
          },
          {
            "x": "349",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "350",
            "y": "769/100",
            "series": "Observed outcome"
          },
          {
            "x": "350",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "351",
            "y": "184/25",
            "series": "Observed outcome"
          },
          {
            "x": "351",
            "y": "2312753/298125",
            "series": "Forest prediction"
          },
          {
            "x": "352",
            "y": "721/100",
            "series": "Observed outcome"
          },
          {
            "x": "352",
            "y": "25986452309/4270665000",
            "series": "Forest prediction"
          },
          {
            "x": "353",
            "y": "287/100",
            "series": "Observed outcome"
          },
          {
            "x": "353",
            "y": "25986452309/4270665000",
            "series": "Forest prediction"
          },
          {
            "x": "354",
            "y": "137/25",
            "series": "Observed outcome"
          },
          {
            "x": "354",
            "y": "381373988437/67274970000",
            "series": "Forest prediction"
          },
          {
            "x": "355",
            "y": "15/4",
            "series": "Observed outcome"
          },
          {
            "x": "355",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "356",
            "y": "231/20",
            "series": "Observed outcome"
          },
          {
            "x": "356",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "357",
            "y": "104/25",
            "series": "Observed outcome"
          },
          {
            "x": "357",
            "y": "381373988437/67274970000",
            "series": "Forest prediction"
          },
          {
            "x": "358",
            "y": "15/4",
            "series": "Observed outcome"
          },
          {
            "x": "358",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "359",
            "y": "9/2",
            "series": "Observed outcome"
          },
          {
            "x": "359",
            "y": "1997866201/355110000",
            "series": "Forest prediction"
          },
          {
            "x": "360",
            "y": "99/50",
            "series": "Observed outcome"
          },
          {
            "x": "360",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "361",
            "y": "167/100",
            "series": "Observed outcome"
          },
          {
            "x": "361",
            "y": "180424181471/38768805000",
            "series": "Forest prediction"
          },
          {
            "x": "362",
            "y": "199/50",
            "series": "Observed outcome"
          },
          {
            "x": "362",
            "y": "2312753/298125",
            "series": "Forest prediction"
          },
          {
            "x": "363",
            "y": "3",
            "series": "Observed outcome"
          },
          {
            "x": "363",
            "y": "7286242967/1398495000",
            "series": "Forest prediction"
          },
          {
            "x": "364",
            "y": "3",
            "series": "Observed outcome"
          },
          {
            "x": "364",
            "y": "180424181471/38768805000",
            "series": "Forest prediction"
          },
          {
            "x": "365",
            "y": "61/25",
            "series": "Observed outcome"
          },
          {
            "x": "365",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "366",
            "y": "99/20",
            "series": "Observed outcome"
          },
          {
            "x": "366",
            "y": "25986452309/4270665000",
            "series": "Forest prediction"
          },
          {
            "x": "367",
            "y": "3",
            "series": "Observed outcome"
          },
          {
            "x": "367",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "368",
            "y": "13/5",
            "series": "Observed outcome"
          },
          {
            "x": "368",
            "y": "180424181471/38768805000",
            "series": "Forest prediction"
          },
          {
            "x": "369",
            "y": "5",
            "series": "Observed outcome"
          },
          {
            "x": "369",
            "y": "1997866201/355110000",
            "series": "Forest prediction"
          },
          {
            "x": "370",
            "y": "77/20",
            "series": "Observed outcome"
          },
          {
            "x": "370",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "371",
            "y": "267/100",
            "series": "Observed outcome"
          },
          {
            "x": "371",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "372",
            "y": "25/4",
            "series": "Observed outcome"
          },
          {
            "x": "372",
            "y": "7286242967/1398495000",
            "series": "Forest prediction"
          },
          {
            "x": "373",
            "y": "6",
            "series": "Observed outcome"
          },
          {
            "x": "373",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "374",
            "y": "11/2",
            "series": "Observed outcome"
          },
          {
            "x": "374",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "375",
            "y": "10",
            "series": "Observed outcome"
          },
          {
            "x": "375",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "376",
            "y": "571/50",
            "series": "Observed outcome"
          },
          {
            "x": "376",
            "y": "2312753/298125",
            "series": "Forest prediction"
          },
          {
            "x": "377",
            "y": "5/2",
            "series": "Observed outcome"
          },
          {
            "x": "377",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "378",
            "y": "3",
            "series": "Observed outcome"
          },
          {
            "x": "378",
            "y": "180424181471/38768805000",
            "series": "Forest prediction"
          },
          {
            "x": "379",
            "y": "279/50",
            "series": "Observed outcome"
          },
          {
            "x": "379",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "380",
            "y": "12/5",
            "series": "Observed outcome"
          },
          {
            "x": "380",
            "y": "180424181471/38768805000",
            "series": "Forest prediction"
          },
          {
            "x": "381",
            "y": "413/100",
            "series": "Observed outcome"
          },
          {
            "x": "381",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "382",
            "y": "1097/100",
            "series": "Observed outcome"
          },
          {
            "x": "382",
            "y": "381373988437/67274970000",
            "series": "Forest prediction"
          },
          {
            "x": "383",
            "y": "577/100",
            "series": "Observed outcome"
          },
          {
            "x": "383",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "384",
            "y": "49/25",
            "series": "Observed outcome"
          },
          {
            "x": "384",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "385",
            "y": "189/20",
            "series": "Observed outcome"
          },
          {
            "x": "385",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "386",
            "y": "21/5",
            "series": "Observed outcome"
          },
          {
            "x": "386",
            "y": "25986452309/4270665000",
            "series": "Forest prediction"
          },
          {
            "x": "387",
            "y": "11/2",
            "series": "Observed outcome"
          },
          {
            "x": "387",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "388",
            "y": "15/2",
            "series": "Observed outcome"
          },
          {
            "x": "388",
            "y": "180424181471/38768805000",
            "series": "Forest prediction"
          },
          {
            "x": "389",
            "y": "19/4",
            "series": "Observed outcome"
          },
          {
            "x": "389",
            "y": "25986452309/4270665000",
            "series": "Forest prediction"
          },
          {
            "x": "390",
            "y": "263/100",
            "series": "Observed outcome"
          },
          {
            "x": "390",
            "y": "25986452309/4270665000",
            "series": "Forest prediction"
          },
          {
            "x": "391",
            "y": "173/50",
            "series": "Observed outcome"
          },
          {
            "x": "391",
            "y": "79585086737/16369051000",
            "series": "Forest prediction"
          },
          {
            "x": "392",
            "y": "319/100",
            "series": "Observed outcome"
          },
          {
            "x": "392",
            "y": "1997866201/355110000",
            "series": "Forest prediction"
          },
          {
            "x": "393",
            "y": "23/10",
            "series": "Observed outcome"
          },
          {
            "x": "393",
            "y": "180424181471/38768805000",
            "series": "Forest prediction"
          },
          {
            "x": "394",
            "y": "519/100",
            "series": "Observed outcome"
          },
          {
            "x": "394",
            "y": "25986452309/4270665000",
            "series": "Forest prediction"
          },
          {
            "x": "395",
            "y": "79/25",
            "series": "Observed outcome"
          },
          {
            "x": "395",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "396",
            "y": "451/100",
            "series": "Observed outcome"
          },
          {
            "x": "396",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "397",
            "y": "171/20",
            "series": "Observed outcome"
          },
          {
            "x": "397",
            "y": "25986452309/4270665000",
            "series": "Forest prediction"
          },
          {
            "x": "398",
            "y": "81/20",
            "series": "Observed outcome"
          },
          {
            "x": "398",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "399",
            "y": "113/25",
            "series": "Observed outcome"
          },
          {
            "x": "399",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "400",
            "y": "15/4",
            "series": "Observed outcome"
          },
          {
            "x": "400",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "401",
            "y": "25/4",
            "series": "Observed outcome"
          },
          {
            "x": "401",
            "y": "25986452309/4270665000",
            "series": "Forest prediction"
          },
          {
            "x": "402",
            "y": "5",
            "series": "Observed outcome"
          },
          {
            "x": "402",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "403",
            "y": "49/10",
            "series": "Observed outcome"
          },
          {
            "x": "403",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "404",
            "y": "4",
            "series": "Observed outcome"
          },
          {
            "x": "404",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "405",
            "y": "13/4",
            "series": "Observed outcome"
          },
          {
            "x": "405",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "406",
            "y": "619/100",
            "series": "Observed outcome"
          },
          {
            "x": "406",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "407",
            "y": "13/4",
            "series": "Observed outcome"
          },
          {
            "x": "407",
            "y": "381373988437/67274970000",
            "series": "Forest prediction"
          },
          {
            "x": "408",
            "y": "343/50",
            "series": "Observed outcome"
          },
          {
            "x": "408",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "409",
            "y": "231/50",
            "series": "Observed outcome"
          },
          {
            "x": "409",
            "y": "79585086737/16369051000",
            "series": "Forest prediction"
          },
          {
            "x": "410",
            "y": "4",
            "series": "Observed outcome"
          },
          {
            "x": "410",
            "y": "1997866201/355110000",
            "series": "Forest prediction"
          },
          {
            "x": "411",
            "y": "141/50",
            "series": "Observed outcome"
          },
          {
            "x": "411",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "412",
            "y": "959/100",
            "series": "Observed outcome"
          },
          {
            "x": "412",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "413",
            "y": "19/4",
            "series": "Observed outcome"
          },
          {
            "x": "413",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "414",
            "y": "673/100",
            "series": "Observed outcome"
          },
          {
            "x": "414",
            "y": "25986452309/4270665000",
            "series": "Forest prediction"
          },
          {
            "x": "415",
            "y": "15/4",
            "series": "Observed outcome"
          },
          {
            "x": "415",
            "y": "1997866201/355110000",
            "series": "Forest prediction"
          },
          {
            "x": "416",
            "y": "1763/100",
            "series": "Observed outcome"
          },
          {
            "x": "416",
            "y": "2312753/298125",
            "series": "Forest prediction"
          },
          {
            "x": "417",
            "y": "11/4",
            "series": "Observed outcome"
          },
          {
            "x": "417",
            "y": "7286242967/1398495000",
            "series": "Forest prediction"
          },
          {
            "x": "418",
            "y": "507/100",
            "series": "Observed outcome"
          },
          {
            "x": "418",
            "y": "180424181471/38768805000",
            "series": "Forest prediction"
          },
          {
            "x": "419",
            "y": "267/25",
            "series": "Observed outcome"
          },
          {
            "x": "419",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "420",
            "y": "15/2",
            "series": "Observed outcome"
          },
          {
            "x": "420",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "421",
            "y": "231/50",
            "series": "Observed outcome"
          },
          {
            "x": "421",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "422",
            "y": "447/50",
            "series": "Observed outcome"
          },
          {
            "x": "422",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "423",
            "y": "241/100",
            "series": "Observed outcome"
          },
          {
            "x": "423",
            "y": "7286242967/1398495000",
            "series": "Forest prediction"
          },
          {
            "x": "424",
            "y": "113/20",
            "series": "Observed outcome"
          },
          {
            "x": "424",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "425",
            "y": "413/100",
            "series": "Observed outcome"
          },
          {
            "x": "425",
            "y": "180424181471/38768805000",
            "series": "Forest prediction"
          },
          {
            "x": "426",
            "y": "389/50",
            "series": "Observed outcome"
          },
          {
            "x": "426",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "427",
            "y": "7/2",
            "series": "Observed outcome"
          },
          {
            "x": "427",
            "y": "180424181471/38768805000",
            "series": "Forest prediction"
          },
          {
            "x": "428",
            "y": "433/50",
            "series": "Observed outcome"
          },
          {
            "x": "428",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "429",
            "y": "37/25",
            "series": "Observed outcome"
          },
          {
            "x": "429",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "430",
            "y": "173/25",
            "series": "Observed outcome"
          },
          {
            "x": "430",
            "y": "2312753/298125",
            "series": "Forest prediction"
          },
          {
            "x": "431",
            "y": "173/20",
            "series": "Observed outcome"
          },
          {
            "x": "431",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "432",
            "y": "178/25",
            "series": "Observed outcome"
          },
          {
            "x": "432",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "433",
            "y": "369/50",
            "series": "Observed outcome"
          },
          {
            "x": "433",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "434",
            "y": "869/100",
            "series": "Observed outcome"
          },
          {
            "x": "434",
            "y": "25986452309/4270665000",
            "series": "Forest prediction"
          },
          {
            "x": "435",
            "y": "231/50",
            "series": "Observed outcome"
          },
          {
            "x": "435",
            "y": "2312753/298125",
            "series": "Forest prediction"
          },
          {
            "x": "436",
            "y": "77/10",
            "series": "Observed outcome"
          },
          {
            "x": "436",
            "y": "25986452309/4270665000",
            "series": "Forest prediction"
          },
          {
            "x": "437",
            "y": "713/100",
            "series": "Observed outcome"
          },
          {
            "x": "437",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "438",
            "y": "721/100",
            "series": "Observed outcome"
          },
          {
            "x": "438",
            "y": "381373988437/67274970000",
            "series": "Forest prediction"
          },
          {
            "x": "439",
            "y": "4",
            "series": "Observed outcome"
          },
          {
            "x": "439",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "440",
            "y": "553/100",
            "series": "Observed outcome"
          },
          {
            "x": "440",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "441",
            "y": "3",
            "series": "Observed outcome"
          },
          {
            "x": "441",
            "y": "180424181471/38768805000",
            "series": "Forest prediction"
          },
          {
            "x": "442",
            "y": "751/100",
            "series": "Observed outcome"
          },
          {
            "x": "442",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "443",
            "y": "529/50",
            "series": "Observed outcome"
          },
          {
            "x": "443",
            "y": "2312753/298125",
            "series": "Forest prediction"
          },
          {
            "x": "444",
            "y": "269/50",
            "series": "Observed outcome"
          },
          {
            "x": "444",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "445",
            "y": "13/2",
            "series": "Observed outcome"
          },
          {
            "x": "445",
            "y": "1997866201/355110000",
            "series": "Forest prediction"
          },
          {
            "x": "446",
            "y": "143/50",
            "series": "Observed outcome"
          },
          {
            "x": "446",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "447",
            "y": "277/100",
            "series": "Observed outcome"
          },
          {
            "x": "447",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "448",
            "y": "673/100",
            "series": "Observed outcome"
          },
          {
            "x": "448",
            "y": "381373988437/67274970000",
            "series": "Forest prediction"
          },
          {
            "x": "449",
            "y": "1443/100",
            "series": "Observed outcome"
          },
          {
            "x": "449",
            "y": "25986452309/4270665000",
            "series": "Forest prediction"
          },
          {
            "x": "450",
            "y": "479/100",
            "series": "Observed outcome"
          },
          {
            "x": "450",
            "y": "180424181471/38768805000",
            "series": "Forest prediction"
          },
          {
            "x": "451",
            "y": "25/4",
            "series": "Observed outcome"
          },
          {
            "x": "451",
            "y": "25986452309/4270665000",
            "series": "Forest prediction"
          },
          {
            "x": "452",
            "y": "123/20",
            "series": "Observed outcome"
          },
          {
            "x": "452",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "453",
            "y": "843/100",
            "series": "Observed outcome"
          },
          {
            "x": "453",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "454",
            "y": "507/50",
            "series": "Observed outcome"
          },
          {
            "x": "454",
            "y": "2312753/298125",
            "series": "Forest prediction"
          },
          {
            "x": "455",
            "y": "149/20",
            "series": "Observed outcome"
          },
          {
            "x": "455",
            "y": "25986452309/4270665000",
            "series": "Forest prediction"
          },
          {
            "x": "456",
            "y": "5",
            "series": "Observed outcome"
          },
          {
            "x": "456",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "457",
            "y": "481/50",
            "series": "Observed outcome"
          },
          {
            "x": "457",
            "y": "25986452309/4270665000",
            "series": "Forest prediction"
          },
          {
            "x": "458",
            "y": "27/4",
            "series": "Observed outcome"
          },
          {
            "x": "458",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "459",
            "y": "47/4",
            "series": "Observed outcome"
          },
          {
            "x": "459",
            "y": "2312753/298125",
            "series": "Forest prediction"
          },
          {
            "x": "460",
            "y": "1029/100",
            "series": "Observed outcome"
          },
          {
            "x": "460",
            "y": "25986452309/4270665000",
            "series": "Forest prediction"
          },
          {
            "x": "461",
            "y": "7/2",
            "series": "Observed outcome"
          },
          {
            "x": "461",
            "y": "7286242967/1398495000",
            "series": "Forest prediction"
          },
          {
            "x": "462",
            "y": "182/25",
            "series": "Observed outcome"
          },
          {
            "x": "462",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "463",
            "y": "983/100",
            "series": "Observed outcome"
          },
          {
            "x": "463",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "464",
            "y": "313/100",
            "series": "Observed outcome"
          },
          {
            "x": "464",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "465",
            "y": "4",
            "series": "Observed outcome"
          },
          {
            "x": "465",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "466",
            "y": "51/20",
            "series": "Observed outcome"
          },
          {
            "x": "466",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "467",
            "y": "769/100",
            "series": "Observed outcome"
          },
          {
            "x": "467",
            "y": "25986452309/4270665000",
            "series": "Forest prediction"
          },
          {
            "x": "468",
            "y": "453/50",
            "series": "Observed outcome"
          },
          {
            "x": "468",
            "y": "25986452309/4270665000",
            "series": "Forest prediction"
          },
          {
            "x": "469",
            "y": "148/25",
            "series": "Observed outcome"
          },
          {
            "x": "469",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "470",
            "y": "221/50",
            "series": "Observed outcome"
          },
          {
            "x": "470",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "471",
            "y": "181/25",
            "series": "Observed outcome"
          },
          {
            "x": "471",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "472",
            "y": "577/100",
            "series": "Observed outcome"
          },
          {
            "x": "472",
            "y": "381373988437/67274970000",
            "series": "Forest prediction"
          },
          {
            "x": "473",
            "y": "577/100",
            "series": "Observed outcome"
          },
          {
            "x": "473",
            "y": "381373988437/67274970000",
            "series": "Forest prediction"
          },
          {
            "x": "474",
            "y": "25/4",
            "series": "Observed outcome"
          },
          {
            "x": "474",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "475",
            "y": "73/10",
            "series": "Observed outcome"
          },
          {
            "x": "475",
            "y": "381373988437/67274970000",
            "series": "Forest prediction"
          },
          {
            "x": "476",
            "y": "411/100",
            "series": "Observed outcome"
          },
          {
            "x": "476",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "477",
            "y": "721/100",
            "series": "Observed outcome"
          },
          {
            "x": "477",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "478",
            "y": "13/4",
            "series": "Observed outcome"
          },
          {
            "x": "478",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "479",
            "y": "213/25",
            "series": "Observed outcome"
          },
          {
            "x": "479",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "480",
            "y": "267/25",
            "series": "Observed outcome"
          },
          {
            "x": "480",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "481",
            "y": "801/100",
            "series": "Observed outcome"
          },
          {
            "x": "481",
            "y": "381373988437/67274970000",
            "series": "Forest prediction"
          },
          {
            "x": "482",
            "y": "79/10",
            "series": "Observed outcome"
          },
          {
            "x": "482",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "483",
            "y": "531/100",
            "series": "Observed outcome"
          },
          {
            "x": "483",
            "y": "25986452309/4270665000",
            "series": "Forest prediction"
          },
          {
            "x": "484",
            "y": "243/50",
            "series": "Observed outcome"
          },
          {
            "x": "484",
            "y": "25986452309/4270665000",
            "series": "Forest prediction"
          },
          {
            "x": "485",
            "y": "25/4",
            "series": "Observed outcome"
          },
          {
            "x": "485",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "486",
            "y": "7",
            "series": "Observed outcome"
          },
          {
            "x": "486",
            "y": "25986452309/4270665000",
            "series": "Forest prediction"
          },
          {
            "x": "487",
            "y": "24/5",
            "series": "Observed outcome"
          },
          {
            "x": "487",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "488",
            "y": "723/100",
            "series": "Observed outcome"
          },
          {
            "x": "488",
            "y": "25986452309/4270665000",
            "series": "Forest prediction"
          },
          {
            "x": "489",
            "y": "601/50",
            "series": "Observed outcome"
          },
          {
            "x": "489",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "490",
            "y": "481/100",
            "series": "Observed outcome"
          },
          {
            "x": "490",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "491",
            "y": "9/2",
            "series": "Observed outcome"
          },
          {
            "x": "491",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "492",
            "y": "11/4",
            "series": "Observed outcome"
          },
          {
            "x": "492",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "493",
            "y": "7/2",
            "series": "Observed outcome"
          },
          {
            "x": "493",
            "y": "2312753/298125",
            "series": "Forest prediction"
          },
          {
            "x": "494",
            "y": "5/2",
            "series": "Observed outcome"
          },
          {
            "x": "494",
            "y": "180424181471/38768805000",
            "series": "Forest prediction"
          },
          {
            "x": "495",
            "y": "289/50",
            "series": "Observed outcome"
          },
          {
            "x": "495",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "496",
            "y": "241/50",
            "series": "Observed outcome"
          },
          {
            "x": "496",
            "y": "381373988437/67274970000",
            "series": "Forest prediction"
          },
          {
            "x": "497",
            "y": "29/20",
            "series": "Observed outcome"
          },
          {
            "x": "497",
            "y": "180424181471/38768805000",
            "series": "Forest prediction"
          },
          {
            "x": "498",
            "y": "481/50",
            "series": "Observed outcome"
          },
          {
            "x": "498",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "499",
            "y": "23/10",
            "series": "Observed outcome"
          },
          {
            "x": "499",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "500",
            "y": "9/2",
            "series": "Observed outcome"
          },
          {
            "x": "500",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "501",
            "y": "15/2",
            "series": "Observed outcome"
          },
          {
            "x": "501",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "502",
            "y": "97/25",
            "series": "Observed outcome"
          },
          {
            "x": "502",
            "y": "79585086737/16369051000",
            "series": "Forest prediction"
          },
          {
            "x": "503",
            "y": "47/20",
            "series": "Observed outcome"
          },
          {
            "x": "503",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "504",
            "y": "4",
            "series": "Observed outcome"
          },
          {
            "x": "504",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "505",
            "y": "19/5",
            "series": "Observed outcome"
          },
          {
            "x": "505",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "506",
            "y": "149/25",
            "series": "Observed outcome"
          },
          {
            "x": "506",
            "y": "25986452309/4270665000",
            "series": "Forest prediction"
          },
          {
            "x": "507",
            "y": "43/5",
            "series": "Observed outcome"
          },
          {
            "x": "507",
            "y": "25986452309/4270665000",
            "series": "Forest prediction"
          },
          {
            "x": "508",
            "y": "16/5",
            "series": "Observed outcome"
          },
          {
            "x": "508",
            "y": "180424181471/38768805000",
            "series": "Forest prediction"
          },
          {
            "x": "509",
            "y": "19/10",
            "series": "Observed outcome"
          },
          {
            "x": "509",
            "y": "180424181471/38768805000",
            "series": "Forest prediction"
          },
          {
            "x": "510",
            "y": "269/50",
            "series": "Observed outcome"
          },
          {
            "x": "510",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "511",
            "y": "513/50",
            "series": "Observed outcome"
          },
          {
            "x": "511",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "512",
            "y": "7/2",
            "series": "Observed outcome"
          },
          {
            "x": "512",
            "y": "7286242967/1398495000",
            "series": "Forest prediction"
          },
          {
            "x": "513",
            "y": "31/10",
            "series": "Observed outcome"
          },
          {
            "x": "513",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "514",
            "y": "479/100",
            "series": "Observed outcome"
          },
          {
            "x": "514",
            "y": "25986452309/4270665000",
            "series": "Forest prediction"
          },
          {
            "x": "515",
            "y": "423/100",
            "series": "Observed outcome"
          },
          {
            "x": "515",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "516",
            "y": "529/100",
            "series": "Observed outcome"
          },
          {
            "x": "516",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "517",
            "y": "381/100",
            "series": "Observed outcome"
          },
          {
            "x": "517",
            "y": "1997866201/355110000",
            "series": "Forest prediction"
          },
          {
            "x": "518",
            "y": "13/5",
            "series": "Observed outcome"
          },
          {
            "x": "518",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "519",
            "y": "5/2",
            "series": "Observed outcome"
          },
          {
            "x": "519",
            "y": "79585086737/16369051000",
            "series": "Forest prediction"
          },
          {
            "x": "520",
            "y": "3",
            "series": "Observed outcome"
          },
          {
            "x": "520",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "521",
            "y": "15/4",
            "series": "Observed outcome"
          },
          {
            "x": "521",
            "y": "7286242967/1398495000",
            "series": "Forest prediction"
          },
          {
            "x": "522",
            "y": "457/100",
            "series": "Observed outcome"
          },
          {
            "x": "522",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "523",
            "y": "13/2",
            "series": "Observed outcome"
          },
          {
            "x": "523",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "524",
            "y": "4",
            "series": "Observed outcome"
          },
          {
            "x": "524",
            "y": "180424181471/38768805000",
            "series": "Forest prediction"
          },
          {
            "x": "525",
            "y": "367/50",
            "series": "Observed outcome"
          },
          {
            "x": "525",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "526",
            "y": "577/100",
            "series": "Observed outcome"
          },
          {
            "x": "526",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "527",
            "y": "91/25",
            "series": "Observed outcome"
          },
          {
            "x": "527",
            "y": "25986452309/4270665000",
            "series": "Forest prediction"
          },
          {
            "x": "528",
            "y": "19/5",
            "series": "Observed outcome"
          },
          {
            "x": "528",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "529",
            "y": "257/100",
            "series": "Observed outcome"
          },
          {
            "x": "529",
            "y": "25986452309/4270665000",
            "series": "Forest prediction"
          },
          {
            "x": "530",
            "y": "433/100",
            "series": "Observed outcome"
          },
          {
            "x": "530",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "531",
            "y": "433/100",
            "series": "Observed outcome"
          },
          {
            "x": "531",
            "y": "7286242967/1398495000",
            "series": "Forest prediction"
          },
          {
            "x": "532",
            "y": "15/4",
            "series": "Observed outcome"
          },
          {
            "x": "532",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "533",
            "y": "212/25",
            "series": "Observed outcome"
          },
          {
            "x": "533",
            "y": "25986452309/4270665000",
            "series": "Forest prediction"
          },
          {
            "x": "534",
            "y": "649/100",
            "series": "Observed outcome"
          },
          {
            "x": "534",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "535",
            "y": "148/25",
            "series": "Observed outcome"
          },
          {
            "x": "535",
            "y": "2312753/298125",
            "series": "Forest prediction"
          },
          {
            "x": "536",
            "y": "481/50",
            "series": "Observed outcome"
          },
          {
            "x": "536",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "537",
            "y": "359/100",
            "series": "Observed outcome"
          },
          {
            "x": "537",
            "y": "25986452309/4270665000",
            "series": "Forest prediction"
          },
          {
            "x": "538",
            "y": "231/50",
            "series": "Observed outcome"
          },
          {
            "x": "538",
            "y": "25986452309/4270665000",
            "series": "Forest prediction"
          },
          {
            "x": "539",
            "y": "3",
            "series": "Observed outcome"
          },
          {
            "x": "539",
            "y": "7286242967/1398495000",
            "series": "Forest prediction"
          },
          {
            "x": "540",
            "y": "7/2",
            "series": "Observed outcome"
          },
          {
            "x": "540",
            "y": "7286242967/1398495000",
            "series": "Forest prediction"
          },
          {
            "x": "541",
            "y": "11/4",
            "series": "Observed outcome"
          },
          {
            "x": "541",
            "y": "1997866201/355110000",
            "series": "Forest prediction"
          },
          {
            "x": "542",
            "y": "163/100",
            "series": "Observed outcome"
          },
          {
            "x": "542",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "543",
            "y": "113/20",
            "series": "Observed outcome"
          },
          {
            "x": "543",
            "y": "180424181471/38768805000",
            "series": "Forest prediction"
          },
          {
            "x": "544",
            "y": "321/50",
            "series": "Observed outcome"
          },
          {
            "x": "544",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "545",
            "y": "4",
            "series": "Observed outcome"
          },
          {
            "x": "545",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "546",
            "y": "89/20",
            "series": "Observed outcome"
          },
          {
            "x": "546",
            "y": "180424181471/38768805000",
            "series": "Forest prediction"
          },
          {
            "x": "547",
            "y": "419/100",
            "series": "Observed outcome"
          },
          {
            "x": "547",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "548",
            "y": "19/5",
            "series": "Observed outcome"
          },
          {
            "x": "548",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "549",
            "y": "769/100",
            "series": "Observed outcome"
          },
          {
            "x": "549",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "550",
            "y": "19/4",
            "series": "Observed outcome"
          },
          {
            "x": "550",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "551",
            "y": "13/5",
            "series": "Observed outcome"
          },
          {
            "x": "551",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "552",
            "y": "803/100",
            "series": "Observed outcome"
          },
          {
            "x": "552",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "553",
            "y": "417/100",
            "series": "Observed outcome"
          },
          {
            "x": "553",
            "y": "180424181471/38768805000",
            "series": "Forest prediction"
          },
          {
            "x": "554",
            "y": "53/20",
            "series": "Observed outcome"
          },
          {
            "x": "554",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "555",
            "y": "28/5",
            "series": "Observed outcome"
          },
          {
            "x": "555",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "556",
            "y": "9/4",
            "series": "Observed outcome"
          },
          {
            "x": "556",
            "y": "79585086737/16369051000",
            "series": "Forest prediction"
          },
          {
            "x": "557",
            "y": "577/100",
            "series": "Observed outcome"
          },
          {
            "x": "557",
            "y": "381373988437/67274970000",
            "series": "Forest prediction"
          },
          {
            "x": "558",
            "y": "203/50",
            "series": "Observed outcome"
          },
          {
            "x": "558",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "559",
            "y": "577/100",
            "series": "Observed outcome"
          },
          {
            "x": "559",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "560",
            "y": "727/100",
            "series": "Observed outcome"
          },
          {
            "x": "560",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "561",
            "y": "77/20",
            "series": "Observed outcome"
          },
          {
            "x": "561",
            "y": "2312753/298125",
            "series": "Forest prediction"
          },
          {
            "x": "562",
            "y": "5/2",
            "series": "Observed outcome"
          },
          {
            "x": "562",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "563",
            "y": "108/25",
            "series": "Observed outcome"
          },
          {
            "x": "563",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "564",
            "y": "331/100",
            "series": "Observed outcome"
          },
          {
            "x": "564",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "565",
            "y": "77/20",
            "series": "Observed outcome"
          },
          {
            "x": "565",
            "y": "381373988437/67274970000",
            "series": "Forest prediction"
          },
          {
            "x": "566",
            "y": "801/100",
            "series": "Observed outcome"
          },
          {
            "x": "566",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "567",
            "y": "361/100",
            "series": "Observed outcome"
          },
          {
            "x": "567",
            "y": "79585086737/16369051000",
            "series": "Forest prediction"
          },
          {
            "x": "568",
            "y": "243/50",
            "series": "Observed outcome"
          },
          {
            "x": "568",
            "y": "25986452309/4270665000",
            "series": "Forest prediction"
          },
          {
            "x": "569",
            "y": "112/25",
            "series": "Observed outcome"
          },
          {
            "x": "569",
            "y": "25986452309/4270665000",
            "series": "Forest prediction"
          },
          {
            "x": "570",
            "y": "13/5",
            "series": "Observed outcome"
          },
          {
            "x": "570",
            "y": "7286242967/1398495000",
            "series": "Forest prediction"
          },
          {
            "x": "571",
            "y": "5/2",
            "series": "Observed outcome"
          },
          {
            "x": "571",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "572",
            "y": "48/25",
            "series": "Observed outcome"
          },
          {
            "x": "572",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "573",
            "y": "353/100",
            "series": "Observed outcome"
          },
          {
            "x": "573",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "574",
            "y": "973/100",
            "series": "Observed outcome"
          },
          {
            "x": "574",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "575",
            "y": "4",
            "series": "Observed outcome"
          },
          {
            "x": "575",
            "y": "79585086737/16369051000",
            "series": "Forest prediction"
          },
          {
            "x": "576",
            "y": "219/50",
            "series": "Observed outcome"
          },
          {
            "x": "576",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "577",
            "y": "49/20",
            "series": "Observed outcome"
          },
          {
            "x": "577",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "578",
            "y": "289/100",
            "series": "Observed outcome"
          },
          {
            "x": "578",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "579",
            "y": "25/4",
            "series": "Observed outcome"
          },
          {
            "x": "579",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "580",
            "y": "87/20",
            "series": "Observed outcome"
          },
          {
            "x": "580",
            "y": "180424181471/38768805000",
            "series": "Forest prediction"
          },
          {
            "x": "581",
            "y": "72/25",
            "series": "Observed outcome"
          },
          {
            "x": "581",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "582",
            "y": "49/20",
            "series": "Observed outcome"
          },
          {
            "x": "582",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "583",
            "y": "553/100",
            "series": "Observed outcome"
          },
          {
            "x": "583",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "584",
            "y": "5/2",
            "series": "Observed outcome"
          },
          {
            "x": "584",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "585",
            "y": "513/100",
            "series": "Observed outcome"
          },
          {
            "x": "585",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "586",
            "y": "271/50",
            "series": "Observed outcome"
          },
          {
            "x": "586",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "587",
            "y": "15/4",
            "series": "Observed outcome"
          },
          {
            "x": "587",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "588",
            "y": "5",
            "series": "Observed outcome"
          },
          {
            "x": "588",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "589",
            "y": "857/100",
            "series": "Observed outcome"
          },
          {
            "x": "589",
            "y": "180424181471/38768805000",
            "series": "Forest prediction"
          },
          {
            "x": "590",
            "y": "202/25",
            "series": "Observed outcome"
          },
          {
            "x": "590",
            "y": "25986452309/4270665000",
            "series": "Forest prediction"
          },
          {
            "x": "591",
            "y": "481/50",
            "series": "Observed outcome"
          },
          {
            "x": "591",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "592",
            "y": "123/100",
            "series": "Observed outcome"
          },
          {
            "x": "592",
            "y": "180424181471/38768805000",
            "series": "Forest prediction"
          },
          {
            "x": "593",
            "y": "9/4",
            "series": "Observed outcome"
          },
          {
            "x": "593",
            "y": "79585086737/16369051000",
            "series": "Forest prediction"
          },
          {
            "x": "594",
            "y": "539/100",
            "series": "Observed outcome"
          },
          {
            "x": "594",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "595",
            "y": "5/2",
            "series": "Observed outcome"
          },
          {
            "x": "595",
            "y": "79585086737/16369051000",
            "series": "Forest prediction"
          },
          {
            "x": "596",
            "y": "183/50",
            "series": "Observed outcome"
          },
          {
            "x": "596",
            "y": "25986452309/4270665000",
            "series": "Forest prediction"
          },
          {
            "x": "597",
            "y": "463/100",
            "series": "Observed outcome"
          },
          {
            "x": "597",
            "y": "79585086737/16369051000",
            "series": "Forest prediction"
          },
          {
            "x": "598",
            "y": "25/4",
            "series": "Observed outcome"
          },
          {
            "x": "598",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "599",
            "y": "3",
            "series": "Observed outcome"
          },
          {
            "x": "599",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "600",
            "y": "3",
            "series": "Observed outcome"
          },
          {
            "x": "600",
            "y": "180424181471/38768805000",
            "series": "Forest prediction"
          },
          {
            "x": "601",
            "y": "263/100",
            "series": "Observed outcome"
          },
          {
            "x": "601",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "602",
            "y": "77/20",
            "series": "Observed outcome"
          },
          {
            "x": "602",
            "y": "276268671/44237600",
            "series": "Forest prediction"
          },
          {
            "x": "603",
            "y": "47/10",
            "series": "Observed outcome"
          },
          {
            "x": "603",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          },
          {
            "x": "604",
            "y": "5",
            "series": "Observed outcome"
          },
          {
            "x": "604",
            "y": "167590262373/31497500240",
            "series": "Forest prediction"
          }
        ],
        "plotFile": "ml09-fixed-results/realdata-person-python/plot.svg",
        "plotSHA256": "2478de194cb230ad55e4506c908504434c31efbc186182ad8a33399857550a5e",
        "files": [
          {
            "file": "ml09-fixed-results/realdata-person-python/full.json",
            "sha256": "e60cdd7546ff56d34bb614d6ee292fe81c1c64814871b19b21b62fc7d0f35e70"
          },
          {
            "file": "ml09-fixed-results/realdata-person-python/plot-points.csv",
            "sha256": "49f293404573b6e555d52ab0ebda179ce002d0f39f6bc0c464973aa87e9c073b"
          },
          {
            "file": "ml09-fixed-results/realdata-person-python/plot.svg",
            "sha256": "2478de194cb230ad55e4506c908504434c31efbc186182ad8a33399857550a5e"
          },
          {
            "file": "ml09-fixed-results/realdata-person-python/summary.csv",
            "sha256": "ab1727ee56b1602ec159d6e430bd67e3d5d9f504e5e8c12bf7648c68b4e93bf1"
          }
        ],
        "scope": "Actually executed self-contained fixed example; current web controls execute separately. Python Fraction and finite-precision base R. Author gate, not independent peer."
      },
      "company": {
        "api": "realdata",
        "variant": "company",
        "language": "python",
        "codeFile": "ml09-code/realdata-company.py",
        "codeSHA256": "5bf3dd4741a24070c190a6b4eb64d87e689f9b4db2d5319d7be499a5cdf788cb",
        "codeText": "\"\"\"ML09 exact Fraction reproduction from native source fields.\n\npython ml09-public-analysis.py --source-dir ml09-sources --output-dir results\n\nThis authored educational implementation uses direct-centered leaf losses and\nexhaustive midpoint partitions. It reads no JS engine, model contract, checker,\nstored target answers or derived-result CSV. Its five tree arithmetic helpers\nwere copied from the author's own separate Fraction reference, not an independent\npeer. Parser/work budgets and display rounding of the production JS are separate.\nNumerical predictions/proper scores do not certify causal effects, calibration,\nIID OOB validity, survey representativeness or production parameter optimality.\n\"\"\"\nfrom pathlib import Path\nfrom fractions import Fraction as Q\nimport csv,json,math,itertools,argparse\n\ndef normalized(rows,task='regression'):\n return [dict(id=r.get('id',i),x=[None if x is None else Q(x)for x in r.get('x',[])],y=None if r['y']is None else str(r['y'])if task=='classification'else Q(r['y']),w=Q(r.get('weight',1)))for i,r in enumerate(rows)]\n\ndef totals(rows,task,classes):\n W=sum((r['w']for r in rows),Q());mu=sum((r['w']*r['y']for r in rows),Q())/W if task=='regression'and W else None\n probs=[sum((r['w']for r in rows if r['y']==c),Q())/W for c in classes]if task=='classification'and W else[]\n risk=sum((r['w']*(r['y']-mu)**2 for r in rows),Q())if task=='regression'and W else W*sum((p*(1-p)for p in probs),Q())\n return dict(n=len(rows),w=W,mu=mu,p=probs,risk=risk,pred=mu if task=='regression'else classes[max(range(len(probs)),key=lambda i:probs[i])]if probs else None)\n\ndef fit(rows,a,task,classes,schedule=None):\n good=[r for r in rows if r['w']>0 and r['y']is not None];root=totals(good,task,classes)['w'];depth=a.get('maxDepth',2);minimum=a.get('minLeaf',1);minmass=Q(a.get('minLeafWeight',0));mingain=Q(a.get('minGain',0));route=a.get('missingRoute','best')\n def build(rr,d,path):\n  st=totals(rr,task,classes);n=dict(rows=rr,st=st,split=None,left=None,right=None,path=path)\n  if d==depth:return n\n  best=None\n  for j in range(len(rr[0]['x'])):\n   if schedule is not None and j not in schedule[path]:continue\n   values=sorted({r['x'][j]for r in rr if r['x'][j]is not None});missing=[r for r in rr if r['x'][j]is None];observed=[r for r in rr if r['x'][j]is not None]\n   candidates=[]\n   for lo,hi in zip(values,values[1:]):\n    q=(lo+hi)/2;left=[r for r in observed if r['x'][j]<=q];right=[r for r in observed if r['x'][j]>q];directions=[route]if route!='best'else['left','right']if missing else['left'if len(left)>=len(right)else'right']\n    for direction in directions:candidates.append(('threshold',q,direction,left+missing if direction=='left'else left,right+missing if direction=='right'else right))\n   if missing and observed:candidates.append(('missing-only',None,'left',missing,observed))\n   for kind,q,direction,left,right in candidates:\n    l=totals(left,task,classes);r=totals(right,task,classes)\n    if min(l['n'],r['n'])<minimum or min(l['w'],r['w'])<minmass or min(l['w'],r['w'])<=0:continue\n    gain=(st['risk']-l['risk']-r['risk'])/root\n    if best is None or gain>best['gain']:best=dict(feature=j,kind=kind,threshold=q,missingRoute=direction,left=left,right=right,gain=gain)\n  if best and best['gain']>0 and best['gain']>mingain:\n   j=best['feature'];go=lambda r:r['x'][j]is None if best['kind']=='missing-only'else best['missingRoute']=='left'if r['x'][j]is None else r['x'][j]<=best['threshold'];n['split']=best;n['left']=build([r for r in rr if go(r)],d+1,path+'L');n['right']=build([r for r in rr if not go(r)],d+1,path+'R')\n  return n\n return build(good,0,'')\n\ndef predict(tree,x):\n n=tree\n while n['split']:\n  s=n['split'];v=x[s['feature']];left=v is None if s['kind']=='missing-only'else s['missingRoute']=='left'if v is None else v<=s['threshold'];n=n['left'if left else'right']\n return dict(prediction=n['st']['pred'],probabilities=n['st']['p'])\n\ndef combine(preds,w,task,classes,mode='probabilities'):\n mass=sum(w,Q())\n if not preds or not mass:return dict(prediction=None,probabilities=[],vote=None,prob=None)\n if task=='regression':return dict(prediction=sum((p['prediction']*v for p,v in zip(preds,w)),Q())/mass,probabilities=[],vote=None,prob=None)\n votes=[sum((v for p,v in zip(preds,w)if p['prediction']==c),Q())/mass for c in classes];ps=[sum((p['probabilities'][j]*v for p,v in zip(preds,w)),Q())/mass for j in range(len(classes))];vote=classes[max(range(len(classes)),key=lambda j:votes[j])];prob=classes[max(range(len(classes)),key=lambda j:ps[j])];return dict(prediction=vote if mode=='votes'else prob,probabilities=ps,vote=vote,prob=prob,votes=votes)\ndef number(v):\n if v is None or isinstance(v,bool):raise ValueError('explicit null/bool is not a numeric parameter')\n return Q(v)\ndef variance(a):\n B=a['B'];v=number(a['marginalVariance']);rho=number(a.get('rho',0))\n if not isinstance(B,int)or isinstance(B,bool)or B<1 or v<0:raise ValueError('positive integer B/nonnegative variance')\n if B>1 and v and not -Q(1,B-1)<=rho<=1:raise ValueError('equicorrelation PSD bound')\n return dict(B=B,marginalVariance=v,correlationApplicable=B>1 and bool(v),varianceOfMean=v if B==1 else v*(1+(B-1)*rho)/B)\ndef aggregate(a):\n task=a.get('task','regression');classes=[str(c)for c in a.get('classes',[])];members=a['members'];w=[number(v)for v in a.get('memberWeights',[1]*len(members))]\n if not members or min(w)<0 or sum(w)<=0:raise ValueError('nonnegative member weights/positive total')\n order=[p.get('id',i)for i,p in enumerate(members[0]['predictions'])];keys=lambda x:(type(x).__name__,x);lookup=[{keys(p.get('id',i)):p for i,p in enumerate(m['predictions'])}for m in members]\n if any(set(m)!={keys(v)for v in order}for m in lookup):raise ValueError('same query ID set')\n out=[]\n for pid in order:\n  predictions=[dict(prediction=number(m[keys(pid)]['value']),probabilities=[])if task=='regression'else dict(prediction=str(m[keys(pid)]['label']),probabilities=[number(v)for v in m[keys(pid)]['probabilities']])for m in lookup]\n  if task=='classification'and any(min(p['probabilities'])<0 or sum(p['probabilities'])!=1 for p in predictions):raise ValueError('probability simplex')\n  out.append(dict(id=pid,**combine(predictions,w,task,classes,a.get('aggregation','probabilities'))))\n return dict(task=task,classes=classes,predictions=out)\ndef scored(preds,rows,task,classes):\n mass=loss=absolute=errors=voteerrors=Q();out=[]\n for p,r in zip(preds,rows):\n  ok=p['prediction']is not None and r['y']is not None and r['w']>0;v=None\n  if ok:\n   mass+=r['w']\n   if task=='regression':e=r['y']-p['prediction'];v=e*e;absolute+=r['w']*abs(e)\n   else:v=sum(((q-(1 if r['y']==c else 0))**2 for c,q in zip(classes,p['probabilities'])),Q());errors+=r['w']*(p['prediction']!=r['y']);voteerrors+=r['w']*(p['vote']!=r['y'])\n   loss+=r['w']*v\n  out.append(dict(p,actual=r['y'],weight=r['w'],scoreEligible=ok,loss=v))\n return dict(rows=out,eligibleRows=sum(r['scoreEligible']for r in out),weight=mass,totalLoss=loss,meanLoss=loss/mass if mass else None,MAE=absolute/mass if mass and task=='regression'else None,errorRate=errors/mass if mass and task=='classification'else None,labelVoteErrorRate=voteerrors/mass if mass and task=='classification'else None)\ndef ensemble(a,forest=False):\n task=a.get('task','regression');classes=[str(v)for v in(a.get('classes')or[])];rr=normalized(a['rows'],task);key=lambda x:(type(x).__name__,x);lookup={key(r['id']):r for r in rr};weights=[number(v)for v in a.get('memberWeights',[1]*len(a['bootstrapDraws']))]\n if not any(r['w']>0 and r['y']is not None for r in rr)or min(weights)<0 or sum(weights)<=0:raise ValueError('positive eligible training and member weight')\n members=[]\n for i,draw in enumerate(a['bootstrapDraws']):\n  data=[lookup[key(v)]for v in draw];schedule=a['nodeFeatures'][i]if forest else None;model=fit(data,a,task,classes,schedule);inbag={key(v)for v in draw};members.append(dict(tree=model,draw=draw,inbag=inbag,weight=weights[i]))\n predictions=[]\n for q in a.get('queries',[]):predictions.append(dict(id=q['id'],**combine([predict(m['tree'],[None if v is None else number(v)for v in q['x']])for m in members],weights,task,classes,a.get('aggregation','probabilities'))))\n oob=[]\n for r in rr:\n  applicable=[i for i,m in enumerate(members)if key(r['id'])not in m['inbag']];p=combine([predict(members[i]['tree'],r['x'])for i in applicable],[weights[i]for i in applicable],task,classes,a.get('aggregation','probabilities'));oob.append(dict(id=r['id'],applicable=applicable,positiveMembers=sum(weights[i]>0 for i in applicable),**p))\n return dict(task=task,classes=classes,members=members,predictions=predictions,outOfBag=scored(oob,rr,task,classes))\ndef boost(a):\n if a.get('task','regression')!='regression':raise ValueError('regression boosting only')\n rr=normalized(a['rows']);good=[r for r in rr if r['w']and r['y']is not None];W=sum((r['w']for r in good),Q())\n if not W:raise ValueError('positive eligible training')\n eta=number(a.get('learningRate','1/2'));stages=a.get('stages',3)\n if not 0<=eta<=1 or not isinstance(stages,int)or isinstance(stages,bool)or not 0<=stages<=8:raise ValueError('supported rate/stages')\n initial=number(a['initial'])if'initial'in a else sum((r['w']*r['y']for r in good),Q())/W;training=[[initial]for r in rr];queries=[[initial]for q in a.get('queries',[])];fits=[];losses=[]\n for stage in range(stages+1):\n  sse=sum((r['w']*(r['y']-p[-1])**2 for r,p in zip(rr,training)if r['w']and r['y']is not None),Q());losses.append(dict(stage=stage,rawWeightedSSE=sse,MSE=sse/W,meanHalfSquaredLoss=sse/(2*W)))\n  if stage==stages:break\n  residuals=[dict(r,y=None if r['y']is None else r['y']-p[-1])for r,p in zip(rr,training)];tree=fit(residuals,a,'regression',[]);h=[predict(tree,r['x'])['prediction']for r in rr];qh=[predict(tree,[None if v is None else number(v)for v in q['x']])['prediction']for q in a.get('queries',[])];norm=sum((r['w']*v*v for r,v in zip(rr,h)if r['y']is not None),Q());stageRows=[]\n  for i,(r,p)in enumerate(zip(rr,training)):\n   residual=None if r['y']is None else r['y']-p[-1];stageRows.append(dict(id=r['id'],before=p[-1],residual=residual,negativeCoordinateDerivative=None if residual is None else r['w']*residual/W,fit=h[i],addition=eta*h[i],after=p[-1]+eta*h[i]));p.append(p[-1]+eta*h[i])\n  for p,v in zip(queries,qh):p.append(p[-1]+eta*v)\n  fits.append(dict(stage=stage+1,tree=tree,rows=stageRows,queryFits=qh,norm=norm,predictedSSEDecrease=eta*(2-eta)*norm))\n return dict(task='regression',initial=initial,learningRate=eta,stages=stages,training=training,queries=queries,fits=fits,losses=losses,predictions=[dict(id=q['id'],prediction=p[-1],probabilities=[],vote=None,prob=None)for q,p in zip(a.get('queries',[]),queries)])\nclass Stream:\n def __init__(self,state):self.state=state\n def choose(self,n):\n  limit=(1<<32)-((1<<32)%n)\n  while True:\n   self.state=(1664525*self.state+1013904223)&0xffffffff\n   if self.state<limit:return self.state%n\ndef fixed_schedules(ids,p,seed):\n stream=Stream(seed);draws=[];schedules=[];paths=['']+[p for d in[1,2]for p in map(''.join,itertools.product('LR',repeat=d))]\n for member in range(4):\n  draws.append([ids[stream.choose(len(ids))]for _ in range(len(ids))]);schedule={}\n  for path in paths:\n   order=list(range(p))\n   for j in range(p-1,0,-1):k=stream.choose(j+1);order[j],order[k]=order[k],order[j]\n   schedule[path]=sorted(order[:max(1,int(math.sqrt(p)))])\n  schedules.append(schedule)\n return draws,schedules\ndef csvread(file):\n with Path(file).open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))\ndef read_sources(source):\n source=Path(source);raw=csvread(source/'actual320-country-four-indicators-original-2020-2024.csv');lookup={(r['countryISO3'],int(r['date']),r['indicatorID']):r for r in raw};country=[]\n for code in sorted({r['countryISO3']for r in raw}):\n  for year in range(2020,2025):\n   cols=['NY.GDP.PCAP.KD','NY.GDP.MKTP.KD.ZG','FP.CPI.TOTL.ZG','SP.DYN.LE00.IN'];v=[lookup[code,year,k]['originalValueToken']for k in cols];x=[None if not z else Q(z)for z in v[:3]];x[0]=None if x[0]is None else x[0]/10000;y=None if not v[3]else Q(v[3]);eligible=y is not None and None not in x;country.append(dict(id=code+':'+str(year),sourceRow=code+':'+str(year),originalID=code,year=year,x=x,y=y,weight='1',role='excluded'if not eligible else'outer-test'if year==2024 else'train'))\n person=[]\n for i,r in enumerate(csvread(source/'actual3613-NLS-original52-fields-and-selection.csv'),1):\n  v=lambda k:None if r[k]=='.'else Q(r[k]);x=[v('ed76'),v('age76')];y=None if v('wage76')is None else v('wage76')/100;eligible=y is not None and None not in x;person.append(dict(id='person:'+str(i),sourceRow=str(i),originalID=r['id'],x=x,y=y,weight='1',role='excluded'if not eligible else'outer-test'if i%5==0 else'train'))\n company=[]\n for i,r in enumerate(csvread(source/'actual3150-churn-original14-fields-and-selection.csv'),1):company.append(dict(id='customer:'+str(i),sourceRow=str(i),originalID='',x=[Q(r[k])for k in['Call  Failure','Subscription  Length','Charge  Amount']],y=r['Churn'],weight='1',role='outer-test'if i%5==0 else'train'))\n models={}\n for index,(kind,rr,task,leaf)in enumerate([('country',country,'regression',4),('person',person,'regression',50),('company',company,'classification',30)]):\n  ids=[r['id']for r in rr if r['role']=='train'];draws,schedules=fixed_schedules(ids,len(rr[0]['x']),20261102+7919*index);models[kind]=dict(records=rr,task=task,classes=['0','1']if task=='classification'else[],draws=draws,schedules=schedules,minLeaf=leaf)\n return models\n_OMITTED=object()\ndef realdata(models,kind,options=_OMITTED):\n options={}if options is _OMITTED else options\n if not isinstance(options,dict):raise ValueError('options object required, not explicit null')\n m=models[kind];train=[r for r in m['records']if r['role']=='train'];test=[r for r in m['records']if r['role']=='outer-test'];method=options.get('method','forest');depth=options.get('maxDepth',2);count=options.get('memberCount',3);a=dict(rows=train,queries=[dict(id=r['id'],x=r['x'])for r in test],task=m['task'],classes=m['classes'],maxDepth=depth,minLeaf=options.get('minLeaf',m['minLeaf']),minLeafWeight='0',minGain='0',missingRoute='best',learningRate=options.get('learningRate','1/2'),stages=options.get('stages',3))\n if method not in ['bagging','forest','boost']:raise ValueError('known source method')\n if not isinstance(depth,int)or isinstance(depth,bool)or not 0<=depth<=3:raise ValueError('source depth0..3')\n if method!='boost'and(not isinstance(count,int)or isinstance(count,bool)or not 1<=count<=4):raise ValueError('source member count1..4')\n if method=='boost':result=boost(a)\n else:\n  a.update(bootstrapDraws=m['draws'][:count],nodeFeatures=[{p:v for p,v in s.items()if len(p)<depth}for s in m['schedules'][:count]]);result=ensemble(a,method=='forest')\n outer=scored(result['predictions'],normalized(test,m['task']),m['task'],m['classes']);st=totals([r for r in normalized(train,m['task'])if r['w']and r['y']is not None],m['task'],m['classes']);constant=dict(prediction=st['pred'],probabilities=st['p'],vote=st['pred'],prob=st['pred']);baseline=scored([dict(id=r['id'],**constant)for r in test],normalized(test,m['task']),m['task'],m['classes']);return dict(kind=kind,method=method,settings=a,train=train,test=test,result=result,outer=outer,baseline=baseline)\ndef serial(x):\n if isinstance(x,Q):return str(x)\n if isinstance(x,dict):return{k:serial(v)for k,v in x.items()if k not in['inbag','tree']}\n if isinstance(x,(list,tuple)):return[serial(v)for v in x]\n return x\ndef writecsv(file,heads,rows):\n with Path(file).open('w',encoding='utf8',newline='')as f:\n  w=csv.writer(f);w.writerow(heads);w.writerows([[''if v is None else str(v)for v in r]for r in rows])\nAPI='realdata'\nINPUT={'kind': 'company'}\n\ndef run_fixed(api,a,out,src):\n import matplotlib\n matplotlib.use('svg')\n import matplotlib.pyplot as plt\n from matplotlib.ticker import MaxNLocator\n plt.rcParams.update({'font.size':14,'svg.fonttype':'none','svg.hashsalt':'ml09-fixed-v1'})\n result=variance(a)if api=='variance'else aggregate(a)if api=='aggregate'else ensemble(a,api=='forest')if api in ['bagging','forest']else boost(a)if api=='boost'else realdata(read_sources(src),a['kind'])\n out=Path(out);out.mkdir(parents=True,exist_ok=True);summary={};points=[]\n def add(x,y,s):\n  if y is not None:points.append([x,y,s])\n if api=='variance':\n  summary={'B':result['B'],'varianceOfMean':result['varianceOfMean']};add(result['B'],result['varianceOfMean'],'Specified finite-B variance');xl='Number of members B';yl='Variance, stipulated units squared';title='Declared covariance model, not fitted trees'\n elif api=='aggregate':\n  p=result['predictions'][0];classification=a.get('task')=='classification';summary={'selectedPrediction':p['prediction']}\n  if classification:\n   summary.update(voteLabel=p['vote'],probabilityLabel=p['prob'],meanProbability1=p['probabilities'][1]);add(1,p['probabilities'][1],'Mean probability of class 1');add(2,p['votes'][1],'Label-vote share of class 1');xl='Aggregation (1=probability, 2=vote)';yl='Probability or vote share'\n  else:\n   for i,m in enumerate(a['members']):add(i+1,Q(m['predictions'][0]['value']),'Member prediction')\n   add(3,p['prediction'],'Weighted mean');xl='Member 1, member 2, aggregate 3';yl='Prediction, assumed units'\n  title='Votes and probabilities are distinct objects'\n elif api in ['bagging','forest']:\n  summary={'queryPrediction':result['predictions'][0]['prediction'],'OOB.scoreable':result['outOfBag']['eligibleRows'],'OOB.meanLoss':result['outOfBag']['meanLoss']}\n  for i,r in enumerate(a['rows']):add(i+1,Q(r['y']),'Observed training outcome')\n  for i,p in enumerate(result['outOfBag']['rows']):add(i+1,p['prediction'],'OOB prediction, when defined')\n  xl='Original training ID order';yl='Outcome, assumed units';title='Repeated draws and ID-level OOB membership'\n elif api=='boost':\n  summary={'initial':result['initial'],'finalMSE':result['losses'][-1]['MSE'],'stages':result['stages']}\n  for r in result['losses']:add(r['stage'],r['MSE'],'Training MSE')\n  xl='Boosting stage (0=initial)';yl='Weighted MSE, outcome units squared';title='Training descent does not certify held-out gain'\n else:\n  summary={'outer.scoreable':result['outer']['eligibleRows'],'outer.meanLoss':result['outer']['meanLoss'],'baseline.meanLoss':result['baseline']['meanLoss'],'OOB.scoreable':result['result']['outOfBag']['eligibleRows'],'OOB.meanLoss':result['result']['outOfBag']['meanLoss']}\n  for i,p in enumerate(result['outer']['rows']):\n   add(i+1,Q(p['actual']),'Observed outcome');add(i+1,p['probabilities'][1]if a['kind']=='company'else p['prediction'],'Forest probability of class 1'if a['kind']=='company'else'Forest prediction')\n  xl='Outer-test source order, not a time path';yl='Churn label / probability'if a['kind']=='company'else'Period life expectancy, years'if a['kind']=='country'else'Nominal 1976 USD per hour';title='Fixed forest; outer labels did not fit the trees'\n def display(v):return 'undefined'if v is None else format(float(v),'.9f')\n writecsv(out/'summary.csv',['metric','value'],[[k,display(v)]for k,v in summary.items()]);writecsv(out/'plot-points.csv',['x','y','series'],points);(out/'full.json').write_text(json.dumps(serial(result),indent=2)+'\\n',encoding='utf8')\n fig,ax=plt.subplots(figsize=(5.6,4.6));fig.subplots_adjust(left=.24,right=.96,bottom=.24,top=.76);colors=['#355c72','#a55336','#507956','#78568b']\n for i,s in enumerate(dict.fromkeys(p[2]for p in points)):\n  pp=[p for p in points if p[2]==s];ax.scatter([float(p[0])for p in pp],[float(p[1])for p in pp],s=12 if len(pp)>100 else 32,alpha=.5 if len(pp)>100 else 1,color=colors[i%4],label=s)\n ax.set_xlabel(xl,labelpad=10,fontsize=11);ax.set_ylabel(yl,labelpad=10,fontsize=11);ax.xaxis.set_major_locator(MaxNLocator(3));ax.yaxis.set_major_locator(MaxNLocator(4));ax.grid(alpha=.18);ax.legend(loc='lower left',bbox_to_anchor=(0,1.01),fontsize=9,frameon=False);fig.suptitle(title,fontsize=9,y=.99);fig.savefig(out/'plot.svg',metadata={'Date':None});plt.close(fig);print(', '.join(k+'='+display(v)for k,v in summary.items()))\nif __name__=='__main__':\n import sys\n try:run_fixed(API,INPUT,sys.argv[1]if len(sys.argv)>1 else'fixed-results',sys.argv[2]if len(sys.argv)>2 else'ml09-sources')\n except ValueError as error:print('Rejected declared input: '+str(error),file=sys.stderr);sys.exit(2)\n",
        "code": "\"\"\"ML09 exact Fraction reproduction from native source fields.\n\npython ml09-public-analysis.py --source-dir ml09-sources --output-dir results\n\nThis authored educational implementation uses direct-centered leaf losses and\nexhaustive midpoint partitions. It reads no JS engine, model contract, checker,\nstored target answers or derived-result CSV. Its five tree arithmetic helpers\nwere copied from the author's own separate Fraction reference, not an independent\npeer. Parser/work budgets and display rounding of the production JS are separate.\nNumerical predictions/proper scores do not certify causal effects, calibration,\nIID OOB validity, survey representativeness or production parameter optimality.\n\"\"\"\nfrom pathlib import Path\nfrom fractions import Fraction as Q\nimport csv,json,math,itertools,argparse\n\ndef normalized(rows,task='regression'):\n return [dict(id=r.get('id',i),x=[None if x is None else Q(x)for x in r.get('x',[])],y=None if r['y']is None else str(r['y'])if task=='classification'else Q(r['y']),w=Q(r.get('weight',1)))for i,r in enumerate(rows)]\n\ndef totals(rows,task,classes):\n W=sum((r['w']for r in rows),Q());mu=sum((r['w']*r['y']for r in rows),Q())/W if task=='regression'and W else None\n probs=[sum((r['w']for r in rows if r['y']==c),Q())/W for c in classes]if task=='classification'and W else[]\n risk=sum((r['w']*(r['y']-mu)**2 for r in rows),Q())if task=='regression'and W else W*sum((p*(1-p)for p in probs),Q())\n return dict(n=len(rows),w=W,mu=mu,p=probs,risk=risk,pred=mu if task=='regression'else classes[max(range(len(probs)),key=lambda i:probs[i])]if probs else None)\n\ndef fit(rows,a,task,classes,schedule=None):\n good=[r for r in rows if r['w']>0 and r['y']is not None];root=totals(good,task,classes)['w'];depth=a.get('maxDepth',2);minimum=a.get('minLeaf',1);minmass=Q(a.get('minLeafWeight',0));mingain=Q(a.get('minGain',0));route=a.get('missingRoute','best')\n def build(rr,d,path):\n  st=totals(rr,task,classes);n=dict(rows=rr,st=st,split=None,left=None,right=None,path=path)\n  if d==depth:return n\n  best=None\n  for j in range(len(rr[0]['x'])):\n   if schedule is not None and j not in schedule[path]:continue\n   values=sorted({r['x'][j]for r in rr if r['x'][j]is not None});missing=[r for r in rr if r['x'][j]is None];observed=[r for r in rr if r['x'][j]is not None]\n   candidates=[]\n   for lo,hi in zip(values,values[1:]):\n    q=(lo+hi)/2;left=[r for r in observed if r['x'][j]<=q];right=[r for r in observed if r['x'][j]>q];directions=[route]if route!='best'else['left','right']if missing else['left'if len(left)>=len(right)else'right']\n    for direction in directions:candidates.append(('threshold',q,direction,left+missing if direction=='left'else left,right+missing if direction=='right'else right))\n   if missing and observed:candidates.append(('missing-only',None,'left',missing,observed))\n   for kind,q,direction,left,right in candidates:\n    l=totals(left,task,classes);r=totals(right,task,classes)\n    if min(l['n'],r['n'])<minimum or min(l['w'],r['w'])<minmass or min(l['w'],r['w'])<=0:continue\n    gain=(st['risk']-l['risk']-r['risk'])/root\n    if best is None or gain>best['gain']:best=dict(feature=j,kind=kind,threshold=q,missingRoute=direction,left=left,right=right,gain=gain)\n  if best and best['gain']>0 and best['gain']>mingain:\n   j=best['feature'];go=lambda r:r['x'][j]is None if best['kind']=='missing-only'else best['missingRoute']=='left'if r['x'][j]is None else r['x'][j]<=best['threshold'];n['split']=best;n['left']=build([r for r in rr if go(r)],d+1,path+'L');n['right']=build([r for r in rr if not go(r)],d+1,path+'R')\n  return n\n return build(good,0,'')\n\ndef predict(tree,x):\n n=tree\n while n['split']:\n  s=n['split'];v=x[s['feature']];left=v is None if s['kind']=='missing-only'else s['missingRoute']=='left'if v is None else v<=s['threshold'];n=n['left'if left else'right']\n return dict(prediction=n['st']['pred'],probabilities=n['st']['p'])\n\ndef combine(preds,w,task,classes,mode='probabilities'):\n mass=sum(w,Q())\n if not preds or not mass:return dict(prediction=None,probabilities=[],vote=None,prob=None)\n if task=='regression':return dict(prediction=sum((p['prediction']*v for p,v in zip(preds,w)),Q())/mass,probabilities=[],vote=None,prob=None)\n votes=[sum((v for p,v in zip(preds,w)if p['prediction']==c),Q())/mass for c in classes];ps=[sum((p['probabilities'][j]*v for p,v in zip(preds,w)),Q())/mass for j in range(len(classes))];vote=classes[max(range(len(classes)),key=lambda j:votes[j])];prob=classes[max(range(len(classes)),key=lambda j:ps[j])];return dict(prediction=vote if mode=='votes'else prob,probabilities=ps,vote=vote,prob=prob,votes=votes)\ndef number(v):\n if v is None or isinstance(v,bool):raise ValueError('explicit null/bool is not a numeric parameter')\n return Q(v)\ndef variance(a):\n B=a['B'];v=number(a['marginalVariance']);rho=number(a.get('rho',0))\n if not isinstance(B,int)or isinstance(B,bool)or B<1 or v<0:raise ValueError('positive integer B/nonnegative variance')\n if B>1 and v and not -Q(1,B-1)<=rho<=1:raise ValueError('equicorrelation PSD bound')\n return dict(B=B,marginalVariance=v,correlationApplicable=B>1 and bool(v),varianceOfMean=v if B==1 else v*(1+(B-1)*rho)/B)\ndef aggregate(a):\n task=a.get('task','regression');classes=[str(c)for c in a.get('classes',[])];members=a['members'];w=[number(v)for v in a.get('memberWeights',[1]*len(members))]\n if not members or min(w)<0 or sum(w)<=0:raise ValueError('nonnegative member weights/positive total')\n order=[p.get('id',i)for i,p in enumerate(members[0]['predictions'])];keys=lambda x:(type(x).__name__,x);lookup=[{keys(p.get('id',i)):p for i,p in enumerate(m['predictions'])}for m in members]\n if any(set(m)!={keys(v)for v in order}for m in lookup):raise ValueError('same query ID set')\n out=[]\n for pid in order:\n  predictions=[dict(prediction=number(m[keys(pid)]['value']),probabilities=[])if task=='regression'else dict(prediction=str(m[keys(pid)]['label']),probabilities=[number(v)for v in m[keys(pid)]['probabilities']])for m in lookup]\n  if task=='classification'and any(min(p['probabilities'])<0 or sum(p['probabilities'])!=1 for p in predictions):raise ValueError('probability simplex')\n  out.append(dict(id=pid,**combine(predictions,w,task,classes,a.get('aggregation','probabilities'))))\n return dict(task=task,classes=classes,predictions=out)\ndef scored(preds,rows,task,classes):\n mass=loss=absolute=errors=voteerrors=Q();out=[]\n for p,r in zip(preds,rows):\n  ok=p['prediction']is not None and r['y']is not None and r['w']>0;v=None\n  if ok:\n   mass+=r['w']\n   if task=='regression':e=r['y']-p['prediction'];v=e*e;absolute+=r['w']*abs(e)\n   else:v=sum(((q-(1 if r['y']==c else 0))**2 for c,q in zip(classes,p['probabilities'])),Q());errors+=r['w']*(p['prediction']!=r['y']);voteerrors+=r['w']*(p['vote']!=r['y'])\n   loss+=r['w']*v\n  out.append(dict(p,actual=r['y'],weight=r['w'],scoreEligible=ok,loss=v))\n return dict(rows=out,eligibleRows=sum(r['scoreEligible']for r in out),weight=mass,totalLoss=loss,meanLoss=loss/mass if mass else None,MAE=absolute/mass if mass and task=='regression'else None,errorRate=errors/mass if mass and task=='classification'else None,labelVoteErrorRate=voteerrors/mass if mass and task=='classification'else None)\ndef ensemble(a,forest=False):\n task=a.get('task','regression');classes=[str(v)for v in(a.get('classes')or[])];rr=normalized(a['rows'],task);key=lambda x:(type(x).__name__,x);lookup={key(r['id']):r for r in rr};weights=[number(v)for v in a.get('memberWeights',[1]*len(a['bootstrapDraws']))]\n if not any(r['w']>0 and r['y']is not None for r in rr)or min(weights)<0 or sum(weights)<=0:raise ValueError('positive eligible training and member weight')\n members=[]\n for i,draw in enumerate(a['bootstrapDraws']):\n  data=[lookup[key(v)]for v in draw];schedule=a['nodeFeatures'][i]if forest else None;model=fit(data,a,task,classes,schedule);inbag={key(v)for v in draw};members.append(dict(tree=model,draw=draw,inbag=inbag,weight=weights[i]))\n predictions=[]\n for q in a.get('queries',[]):predictions.append(dict(id=q['id'],**combine([predict(m['tree'],[None if v is None else number(v)for v in q['x']])for m in members],weights,task,classes,a.get('aggregation','probabilities'))))\n oob=[]\n for r in rr:\n  applicable=[i for i,m in enumerate(members)if key(r['id'])not in m['inbag']];p=combine([predict(members[i]['tree'],r['x'])for i in applicable],[weights[i]for i in applicable],task,classes,a.get('aggregation','probabilities'));oob.append(dict(id=r['id'],applicable=applicable,positiveMembers=sum(weights[i]>0 for i in applicable),**p))\n return dict(task=task,classes=classes,members=members,predictions=predictions,outOfBag=scored(oob,rr,task,classes))\ndef boost(a):\n if a.get('task','regression')!='regression':raise ValueError('regression boosting only')\n rr=normalized(a['rows']);good=[r for r in rr if r['w']and r['y']is not None];W=sum((r['w']for r in good),Q())\n if not W:raise ValueError('positive eligible training')\n eta=number(a.get('learningRate','1/2'));stages=a.get('stages',3)\n if not 0<=eta<=1 or not isinstance(stages,int)or isinstance(stages,bool)or not 0<=stages<=8:raise ValueError('supported rate/stages')\n initial=number(a['initial'])if'initial'in a else sum((r['w']*r['y']for r in good),Q())/W;training=[[initial]for r in rr];queries=[[initial]for q in a.get('queries',[])];fits=[];losses=[]\n for stage in range(stages+1):\n  sse=sum((r['w']*(r['y']-p[-1])**2 for r,p in zip(rr,training)if r['w']and r['y']is not None),Q());losses.append(dict(stage=stage,rawWeightedSSE=sse,MSE=sse/W,meanHalfSquaredLoss=sse/(2*W)))\n  if stage==stages:break\n  residuals=[dict(r,y=None if r['y']is None else r['y']-p[-1])for r,p in zip(rr,training)];tree=fit(residuals,a,'regression',[]);h=[predict(tree,r['x'])['prediction']for r in rr];qh=[predict(tree,[None if v is None else number(v)for v in q['x']])['prediction']for q in a.get('queries',[])];norm=sum((r['w']*v*v for r,v in zip(rr,h)if r['y']is not None),Q());stageRows=[]\n  for i,(r,p)in enumerate(zip(rr,training)):\n   residual=None if r['y']is None else r['y']-p[-1];stageRows.append(dict(id=r['id'],before=p[-1],residual=residual,negativeCoordinateDerivative=None if residual is None else r['w']*residual/W,fit=h[i],addition=eta*h[i],after=p[-1]+eta*h[i]));p.append(p[-1]+eta*h[i])\n  for p,v in zip(queries,qh):p.append(p[-1]+eta*v)\n  fits.append(dict(stage=stage+1,tree=tree,rows=stageRows,queryFits=qh,norm=norm,predictedSSEDecrease=eta*(2-eta)*norm))\n return dict(task='regression',initial=initial,learningRate=eta,stages=stages,training=training,queries=queries,fits=fits,losses=losses,predictions=[dict(id=q['id'],prediction=p[-1],probabilities=[],vote=None,prob=None)for q,p in zip(a.get('queries',[]),queries)])\nclass Stream:\n def __init__(self,state):self.state=state\n def choose(self,n):\n  limit=(1<<32)-((1<<32)%n)\n  while True:\n   self.state=(1664525*self.state+1013904223)&0xffffffff\n   if self.state<limit:return self.state%n\ndef fixed_schedules(ids,p,seed):\n stream=Stream(seed);draws=[];schedules=[];paths=['']+[p for d in[1,2]for p in map(''.join,itertools.product('LR',repeat=d))]\n for member in range(4):\n  draws.append([ids[stream.choose(len(ids))]for _ in range(len(ids))]);schedule={}\n  for path in paths:\n   order=list(range(p))\n   for j in range(p-1,0,-1):k=stream.choose(j+1);order[j],order[k]=order[k],order[j]\n   schedule[path]=sorted(order[:max(1,int(math.sqrt(p)))])\n  schedules.append(schedule)\n return draws,schedules\ndef csvread(file):\n with Path(file).open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))\ndef read_sources(source):\n source=Path(source);raw=csvread(source/'actual320-country-four-indicators-original-2020-2024.csv');lookup={(r['countryISO3'],int(r['date']),r['indicatorID']):r for r in raw};country=[]\n for code in sorted({r['countryISO3']for r in raw}):\n  for year in range(2020,2025):\n   cols=['NY.GDP.PCAP.KD','NY.GDP.MKTP.KD.ZG','FP.CPI.TOTL.ZG','SP.DYN.LE00.IN'];v=[lookup[code,year,k]['originalValueToken']for k in cols];x=[None if not z else Q(z)for z in v[:3]];x[0]=None if x[0]is None else x[0]/10000;y=None if not v[3]else Q(v[3]);eligible=y is not None and None not in x;country.append(dict(id=code+':'+str(year),sourceRow=code+':'+str(year),originalID=code,year=year,x=x,y=y,weight='1',role='excluded'if not eligible else'outer-test'if year==2024 else'train'))\n person=[]\n for i,r in enumerate(csvread(source/'actual3613-NLS-original52-fields-and-selection.csv'),1):\n  v=lambda k:None if r[k]=='.'else Q(r[k]);x=[v('ed76'),v('age76')];y=None if v('wage76')is None else v('wage76')/100;eligible=y is not None and None not in x;person.append(dict(id='person:'+str(i),sourceRow=str(i),originalID=r['id'],x=x,y=y,weight='1',role='excluded'if not eligible else'outer-test'if i%5==0 else'train'))\n company=[]\n for i,r in enumerate(csvread(source/'actual3150-churn-original14-fields-and-selection.csv'),1):company.append(dict(id='customer:'+str(i),sourceRow=str(i),originalID='',x=[Q(r[k])for k in['Call  Failure','Subscription  Length','Charge  Amount']],y=r['Churn'],weight='1',role='outer-test'if i%5==0 else'train'))\n models={}\n for index,(kind,rr,task,leaf)in enumerate([('country',country,'regression',4),('person',person,'regression',50),('company',company,'classification',30)]):\n  ids=[r['id']for r in rr if r['role']=='train'];draws,schedules=fixed_schedules(ids,len(rr[0]['x']),20261102+7919*index);models[kind]=dict(records=rr,task=task,classes=['0','1']if task=='classification'else[],draws=draws,schedules=schedules,minLeaf=leaf)\n return models\n_OMITTED=object()\ndef realdata(models,kind,options=_OMITTED):\n options={}if options is _OMITTED else options\n if not isinstance(options,dict):raise ValueError('options object required, not explicit null')\n m=models[kind];train=[r for r in m['records']if r['role']=='train'];test=[r for r in m['records']if r['role']=='outer-test'];method=options.get('method','forest');depth=options.get('maxDepth',2);count=options.get('memberCount',3);a=dict(rows=train,queries=[dict(id=r['id'],x=r['x'])for r in test],task=m['task'],classes=m['classes'],maxDepth=depth,minLeaf=options.get('minLeaf',m['minLeaf']),minLeafWeight='0',minGain='0',missingRoute='best',learningRate=options.get('learningRate','1/2'),stages=options.get('stages',3))\n if method not in ['bagging','forest','boost']:raise ValueError('known source method')\n if not isinstance(depth,int)or isinstance(depth,bool)or not 0<=depth<=3:raise ValueError('source depth0..3')\n if method!='boost'and(not isinstance(count,int)or isinstance(count,bool)or not 1<=count<=4):raise ValueError('source member count1..4')\n if method=='boost':result=boost(a)\n else:\n  a.update(bootstrapDraws=m['draws'][:count],nodeFeatures=[{p:v for p,v in s.items()if len(p)<depth}for s in m['schedules'][:count]]);result=ensemble(a,method=='forest')\n outer=scored(result['predictions'],normalized(test,m['task']),m['task'],m['classes']);st=totals([r for r in normalized(train,m['task'])if r['w']and r['y']is not None],m['task'],m['classes']);constant=dict(prediction=st['pred'],probabilities=st['p'],vote=st['pred'],prob=st['pred']);baseline=scored([dict(id=r['id'],**constant)for r in test],normalized(test,m['task']),m['task'],m['classes']);return dict(kind=kind,method=method,settings=a,train=train,test=test,result=result,outer=outer,baseline=baseline)\ndef serial(x):\n if isinstance(x,Q):return str(x)\n if isinstance(x,dict):return{k:serial(v)for k,v in x.items()if k not in['inbag','tree']}\n if isinstance(x,(list,tuple)):return[serial(v)for v in x]\n return x\ndef writecsv(file,heads,rows):\n with Path(file).open('w',encoding='utf8',newline='')as f:\n  w=csv.writer(f);w.writerow(heads);w.writerows([[''if v is None else str(v)for v in r]for r in rows])\nAPI='realdata'\nINPUT={'kind': 'company'}\n\ndef run_fixed(api,a,out,src):\n import matplotlib\n matplotlib.use('svg')\n import matplotlib.pyplot as plt\n from matplotlib.ticker import MaxNLocator\n plt.rcParams.update({'font.size':14,'svg.fonttype':'none','svg.hashsalt':'ml09-fixed-v1'})\n result=variance(a)if api=='variance'else aggregate(a)if api=='aggregate'else ensemble(a,api=='forest')if api in ['bagging','forest']else boost(a)if api=='boost'else realdata(read_sources(src),a['kind'])\n out=Path(out);out.mkdir(parents=True,exist_ok=True);summary={};points=[]\n def add(x,y,s):\n  if y is not None:points.append([x,y,s])\n if api=='variance':\n  summary={'B':result['B'],'varianceOfMean':result['varianceOfMean']};add(result['B'],result['varianceOfMean'],'Specified finite-B variance');xl='Number of members B';yl='Variance, stipulated units squared';title='Declared covariance model, not fitted trees'\n elif api=='aggregate':\n  p=result['predictions'][0];classification=a.get('task')=='classification';summary={'selectedPrediction':p['prediction']}\n  if classification:\n   summary.update(voteLabel=p['vote'],probabilityLabel=p['prob'],meanProbability1=p['probabilities'][1]);add(1,p['probabilities'][1],'Mean probability of class 1');add(2,p['votes'][1],'Label-vote share of class 1');xl='Aggregation (1=probability, 2=vote)';yl='Probability or vote share'\n  else:\n   for i,m in enumerate(a['members']):add(i+1,Q(m['predictions'][0]['value']),'Member prediction')\n   add(3,p['prediction'],'Weighted mean');xl='Member 1, member 2, aggregate 3';yl='Prediction, assumed units'\n  title='Votes and probabilities are distinct objects'\n elif api in ['bagging','forest']:\n  summary={'queryPrediction':result['predictions'][0]['prediction'],'OOB.scoreable':result['outOfBag']['eligibleRows'],'OOB.meanLoss':result['outOfBag']['meanLoss']}\n  for i,r in enumerate(a['rows']):add(i+1,Q(r['y']),'Observed training outcome')\n  for i,p in enumerate(result['outOfBag']['rows']):add(i+1,p['prediction'],'OOB prediction, when defined')\n  xl='Original training ID order';yl='Outcome, assumed units';title='Repeated draws and ID-level OOB membership'\n elif api=='boost':\n  summary={'initial':result['initial'],'finalMSE':result['losses'][-1]['MSE'],'stages':result['stages']}\n  for r in result['losses']:add(r['stage'],r['MSE'],'Training MSE')\n  xl='Boosting stage (0=initial)';yl='Weighted MSE, outcome units squared';title='Training descent does not certify held-out gain'\n else:\n  summary={'outer.scoreable':result['outer']['eligibleRows'],'outer.meanLoss':result['outer']['meanLoss'],'baseline.meanLoss':result['baseline']['meanLoss'],'OOB.scoreable':result['result']['outOfBag']['eligibleRows'],'OOB.meanLoss':result['result']['outOfBag']['meanLoss']}\n  for i,p in enumerate(result['outer']['rows']):\n   add(i+1,Q(p['actual']),'Observed outcome');add(i+1,p['probabilities'][1]if a['kind']=='company'else p['prediction'],'Forest probability of class 1'if a['kind']=='company'else'Forest prediction')\n  xl='Outer-test source order, not a time path';yl='Churn label / probability'if a['kind']=='company'else'Period life expectancy, years'if a['kind']=='country'else'Nominal 1976 USD per hour';title='Fixed forest; outer labels did not fit the trees'\n def display(v):return 'undefined'if v is None else format(float(v),'.9f')\n writecsv(out/'summary.csv',['metric','value'],[[k,display(v)]for k,v in summary.items()]);writecsv(out/'plot-points.csv',['x','y','series'],points);(out/'full.json').write_text(json.dumps(serial(result),indent=2)+'\\n',encoding='utf8')\n fig,ax=plt.subplots(figsize=(5.6,4.6));fig.subplots_adjust(left=.24,right=.96,bottom=.24,top=.76);colors=['#355c72','#a55336','#507956','#78568b']\n for i,s in enumerate(dict.fromkeys(p[2]for p in points)):\n  pp=[p for p in points if p[2]==s];ax.scatter([float(p[0])for p in pp],[float(p[1])for p in pp],s=12 if len(pp)>100 else 32,alpha=.5 if len(pp)>100 else 1,color=colors[i%4],label=s)\n ax.set_xlabel(xl,labelpad=10,fontsize=11);ax.set_ylabel(yl,labelpad=10,fontsize=11);ax.xaxis.set_major_locator(MaxNLocator(3));ax.yaxis.set_major_locator(MaxNLocator(4));ax.grid(alpha=.18);ax.legend(loc='lower left',bbox_to_anchor=(0,1.01),fontsize=9,frameon=False);fig.suptitle(title,fontsize=9,y=.99);fig.savefig(out/'plot.svg',metadata={'Date':None});plt.close(fig);print(', '.join(k+'='+display(v)for k,v in summary.items()))\nif __name__=='__main__':\n import sys\n try:run_fixed(API,INPUT,sys.argv[1]if len(sys.argv)>1 else'fixed-results',sys.argv[2]if len(sys.argv)>2 else'ml09-sources')\n except ValueError as error:print('Rejected declared input: '+str(error),file=sys.stderr);sys.exit(2)\n",
        "inputFiles": [
          {
            "file": "ml09-sources/actual3150-churn-original14-fields-and-selection.csv",
            "sha256": "6f5b9e98ce1896582629646dd4cfe7b1aca78c491f7e412a93840534e8b49f48"
          },
          {
            "file": "ml09-sources/actual320-country-four-indicators-original-2020-2024.csv",
            "sha256": "cedc2f748ce14601c76b254c35aea7ef0ee5f06f2928506c225efcbfb1f69390"
          },
          {
            "file": "ml09-sources/actual3613-NLS-original52-fields-and-selection.csv",
            "sha256": "7ae23478bdfee0922157264655e1a2081999f11686773478835bce315068e0df"
          }
        ],
        "input": {
          "kind": "company"
        },
        "returnCode": 0,
        "expectedFailure": false,
        "stdout": "outer.scoreable=630.000000000, outer.meanLoss=0.318897321, baseline.meanLoss=0.269263039, OOB.scoreable=1865.000000000, OOB.meanLoss=0.239656197\n",
        "stderr": "",
        "summary": {
          "outer.scoreable": "630.000000000",
          "outer.meanLoss": "0.318897321",
          "baseline.meanLoss": "0.269263039",
          "OOB.scoreable": "1865.000000000",
          "OOB.meanLoss": "0.239656197"
        },
        "plotPoints": [
          {
            "x": "1",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "1",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "2",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "2",
            "y": "13525031/87435522",
            "series": "Forest probability of class 1"
          },
          {
            "x": "3",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "3",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "4",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "4",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "5",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "5",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "6",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "6",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "7",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "7",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "8",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "8",
            "y": "1118839/28101630",
            "series": "Forest probability of class 1"
          },
          {
            "x": "9",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "9",
            "y": "1067/67390",
            "series": "Forest probability of class 1"
          },
          {
            "x": "10",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "10",
            "y": "5/1539",
            "series": "Forest probability of class 1"
          },
          {
            "x": "11",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "11",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "12",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "12",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "13",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "13",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "14",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "14",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "15",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "15",
            "y": "13525031/87435522",
            "series": "Forest probability of class 1"
          },
          {
            "x": "16",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "16",
            "y": "13525031/87435522",
            "series": "Forest probability of class 1"
          },
          {
            "x": "17",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "17",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "18",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "18",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "19",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "19",
            "y": "5/1539",
            "series": "Forest probability of class 1"
          },
          {
            "x": "20",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "20",
            "y": "5/1539",
            "series": "Forest probability of class 1"
          },
          {
            "x": "21",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "21",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "22",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "22",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "23",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "23",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "24",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "24",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "25",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "25",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "26",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "26",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "27",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "27",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "28",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "28",
            "y": "1067/67390",
            "series": "Forest probability of class 1"
          },
          {
            "x": "29",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "29",
            "y": "1067/67390",
            "series": "Forest probability of class 1"
          },
          {
            "x": "30",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "30",
            "y": "1067/67390",
            "series": "Forest probability of class 1"
          },
          {
            "x": "31",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "31",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "32",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "32",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "33",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "33",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "34",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "34",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "35",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "35",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "36",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "36",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "37",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "37",
            "y": "13525031/87435522",
            "series": "Forest probability of class 1"
          },
          {
            "x": "38",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "38",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "39",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "39",
            "y": "5/1539",
            "series": "Forest probability of class 1"
          },
          {
            "x": "40",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "40",
            "y": "5/1539",
            "series": "Forest probability of class 1"
          },
          {
            "x": "41",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "41",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "42",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "42",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "43",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "43",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "44",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "44",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "45",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "45",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "46",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "46",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "47",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "47",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "48",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "48",
            "y": "1067/67390",
            "series": "Forest probability of class 1"
          },
          {
            "x": "49",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "49",
            "y": "1067/67390",
            "series": "Forest probability of class 1"
          },
          {
            "x": "50",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "50",
            "y": "1067/67390",
            "series": "Forest probability of class 1"
          },
          {
            "x": "51",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "51",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "52",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "52",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "53",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "53",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "54",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "54",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "55",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "55",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "56",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "56",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "57",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "57",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "58",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "58",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "59",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "59",
            "y": "5/1539",
            "series": "Forest probability of class 1"
          },
          {
            "x": "60",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "60",
            "y": "5/1539",
            "series": "Forest probability of class 1"
          },
          {
            "x": "61",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "61",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "62",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "62",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "63",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "63",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "64",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "64",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "65",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "65",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "66",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "66",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "67",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "67",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "68",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "68",
            "y": "1067/67390",
            "series": "Forest probability of class 1"
          },
          {
            "x": "69",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "69",
            "y": "1067/67390",
            "series": "Forest probability of class 1"
          },
          {
            "x": "70",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "70",
            "y": "1067/67390",
            "series": "Forest probability of class 1"
          },
          {
            "x": "71",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "71",
            "y": "80075069/445184343",
            "series": "Forest probability of class 1"
          },
          {
            "x": "72",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "72",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "73",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "73",
            "y": "80075069/445184343",
            "series": "Forest probability of class 1"
          },
          {
            "x": "74",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "74",
            "y": "80075069/445184343",
            "series": "Forest probability of class 1"
          },
          {
            "x": "75",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "75",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "76",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "76",
            "y": "80075069/445184343",
            "series": "Forest probability of class 1"
          },
          {
            "x": "77",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "77",
            "y": "13525031/87435522",
            "series": "Forest probability of class 1"
          },
          {
            "x": "78",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "78",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "79",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "79",
            "y": "1067/67390",
            "series": "Forest probability of class 1"
          },
          {
            "x": "80",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "80",
            "y": "5/1539",
            "series": "Forest probability of class 1"
          },
          {
            "x": "81",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "81",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "82",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "82",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "83",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "83",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "84",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "84",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "85",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "85",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "86",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "86",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "87",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "87",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "88",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "88",
            "y": "1067/67390",
            "series": "Forest probability of class 1"
          },
          {
            "x": "89",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "89",
            "y": "1067/67390",
            "series": "Forest probability of class 1"
          },
          {
            "x": "90",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "90",
            "y": "5/1539",
            "series": "Forest probability of class 1"
          },
          {
            "x": "91",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "91",
            "y": "13525031/87435522",
            "series": "Forest probability of class 1"
          },
          {
            "x": "92",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "92",
            "y": "13525031/87435522",
            "series": "Forest probability of class 1"
          },
          {
            "x": "93",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "93",
            "y": "13525031/87435522",
            "series": "Forest probability of class 1"
          },
          {
            "x": "94",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "94",
            "y": "13525031/87435522",
            "series": "Forest probability of class 1"
          },
          {
            "x": "95",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "95",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "96",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "96",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "97",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "97",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "98",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "98",
            "y": "5825/213921",
            "series": "Forest probability of class 1"
          },
          {
            "x": "99",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "99",
            "y": "5/1539",
            "series": "Forest probability of class 1"
          },
          {
            "x": "100",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "100",
            "y": "5/1539",
            "series": "Forest probability of class 1"
          },
          {
            "x": "101",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "101",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "102",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "102",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "103",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "103",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "104",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "104",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "105",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "105",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "106",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "106",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "107",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "107",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "108",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "108",
            "y": "1118839/28101630",
            "series": "Forest probability of class 1"
          },
          {
            "x": "109",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "109",
            "y": "1067/67390",
            "series": "Forest probability of class 1"
          },
          {
            "x": "110",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "110",
            "y": "1067/67390",
            "series": "Forest probability of class 1"
          },
          {
            "x": "111",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "111",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "112",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "112",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "113",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "113",
            "y": "13525031/87435522",
            "series": "Forest probability of class 1"
          },
          {
            "x": "114",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "114",
            "y": "13525031/87435522",
            "series": "Forest probability of class 1"
          },
          {
            "x": "115",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "115",
            "y": "13525031/87435522",
            "series": "Forest probability of class 1"
          },
          {
            "x": "116",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "116",
            "y": "13525031/87435522",
            "series": "Forest probability of class 1"
          },
          {
            "x": "117",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "117",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "118",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "118",
            "y": "10287653/105463053",
            "series": "Forest probability of class 1"
          },
          {
            "x": "119",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "119",
            "y": "5/1539",
            "series": "Forest probability of class 1"
          },
          {
            "x": "120",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "120",
            "y": "5/1539",
            "series": "Forest probability of class 1"
          },
          {
            "x": "121",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "121",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "122",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "122",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "123",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "123",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "124",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "124",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "125",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "125",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "126",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "126",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "127",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "127",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "128",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "128",
            "y": "1118839/28101630",
            "series": "Forest probability of class 1"
          },
          {
            "x": "129",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "129",
            "y": "1067/67390",
            "series": "Forest probability of class 1"
          },
          {
            "x": "130",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "130",
            "y": "1067/67390",
            "series": "Forest probability of class 1"
          },
          {
            "x": "131",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "131",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "132",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "132",
            "y": "13525031/87435522",
            "series": "Forest probability of class 1"
          },
          {
            "x": "133",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "133",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "134",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "134",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "135",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "135",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "136",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "136",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "137",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "137",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "138",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "138",
            "y": "1118839/28101630",
            "series": "Forest probability of class 1"
          },
          {
            "x": "139",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "139",
            "y": "1067/67390",
            "series": "Forest probability of class 1"
          },
          {
            "x": "140",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "140",
            "y": "5/1539",
            "series": "Forest probability of class 1"
          },
          {
            "x": "141",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "141",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "142",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "142",
            "y": "13525031/87435522",
            "series": "Forest probability of class 1"
          },
          {
            "x": "143",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "143",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "144",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "144",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "145",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "145",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "146",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "146",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "147",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "147",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "148",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "148",
            "y": "1118839/28101630",
            "series": "Forest probability of class 1"
          },
          {
            "x": "149",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "149",
            "y": "1067/67390",
            "series": "Forest probability of class 1"
          },
          {
            "x": "150",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "150",
            "y": "5/1539",
            "series": "Forest probability of class 1"
          },
          {
            "x": "151",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "151",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "152",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "152",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "153",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "153",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "154",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "154",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "155",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "155",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "156",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "156",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "157",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "157",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "158",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "158",
            "y": "1067/67390",
            "series": "Forest probability of class 1"
          },
          {
            "x": "159",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "159",
            "y": "1067/67390",
            "series": "Forest probability of class 1"
          },
          {
            "x": "160",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "160",
            "y": "1067/67390",
            "series": "Forest probability of class 1"
          },
          {
            "x": "161",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "161",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "162",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "162",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "163",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "163",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "164",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "164",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "165",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "165",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "166",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "166",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "167",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "167",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "168",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "168",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "169",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "169",
            "y": "5/1539",
            "series": "Forest probability of class 1"
          },
          {
            "x": "170",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "170",
            "y": "5/1539",
            "series": "Forest probability of class 1"
          },
          {
            "x": "171",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "171",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "172",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "172",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "173",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "173",
            "y": "13525031/87435522",
            "series": "Forest probability of class 1"
          },
          {
            "x": "174",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "174",
            "y": "13525031/87435522",
            "series": "Forest probability of class 1"
          },
          {
            "x": "175",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "175",
            "y": "13525031/87435522",
            "series": "Forest probability of class 1"
          },
          {
            "x": "176",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "176",
            "y": "13525031/87435522",
            "series": "Forest probability of class 1"
          },
          {
            "x": "177",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "177",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "178",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "178",
            "y": "10287653/105463053",
            "series": "Forest probability of class 1"
          },
          {
            "x": "179",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "179",
            "y": "5/1539",
            "series": "Forest probability of class 1"
          },
          {
            "x": "180",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "180",
            "y": "5/1539",
            "series": "Forest probability of class 1"
          },
          {
            "x": "181",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "181",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "182",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "182",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "183",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "183",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "184",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "184",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "185",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "185",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "186",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "186",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "187",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "187",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "188",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "188",
            "y": "1118839/28101630",
            "series": "Forest probability of class 1"
          },
          {
            "x": "189",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "189",
            "y": "1067/67390",
            "series": "Forest probability of class 1"
          },
          {
            "x": "190",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "190",
            "y": "1067/67390",
            "series": "Forest probability of class 1"
          },
          {
            "x": "191",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "191",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "192",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "192",
            "y": "13525031/87435522",
            "series": "Forest probability of class 1"
          },
          {
            "x": "193",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "193",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "194",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "194",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "195",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "195",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "196",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "196",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "197",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "197",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "198",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "198",
            "y": "1118839/28101630",
            "series": "Forest probability of class 1"
          },
          {
            "x": "199",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "199",
            "y": "1067/67390",
            "series": "Forest probability of class 1"
          },
          {
            "x": "200",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "200",
            "y": "5/1539",
            "series": "Forest probability of class 1"
          },
          {
            "x": "201",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "201",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "202",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "202",
            "y": "13525031/87435522",
            "series": "Forest probability of class 1"
          },
          {
            "x": "203",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "203",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "204",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "204",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "205",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "205",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "206",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "206",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "207",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "207",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "208",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "208",
            "y": "1118839/28101630",
            "series": "Forest probability of class 1"
          },
          {
            "x": "209",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "209",
            "y": "1067/67390",
            "series": "Forest probability of class 1"
          },
          {
            "x": "210",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "210",
            "y": "5/1539",
            "series": "Forest probability of class 1"
          },
          {
            "x": "211",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "211",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "212",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "212",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "213",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "213",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "214",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "214",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "215",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "215",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "216",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "216",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "217",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "217",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "218",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "218",
            "y": "1067/67390",
            "series": "Forest probability of class 1"
          },
          {
            "x": "219",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "219",
            "y": "1067/67390",
            "series": "Forest probability of class 1"
          },
          {
            "x": "220",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "220",
            "y": "1067/67390",
            "series": "Forest probability of class 1"
          },
          {
            "x": "221",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "221",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "222",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "222",
            "y": "13525031/87435522",
            "series": "Forest probability of class 1"
          },
          {
            "x": "223",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "223",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "224",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "224",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "225",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "225",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "226",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "226",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "227",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "227",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "228",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "228",
            "y": "1118839/28101630",
            "series": "Forest probability of class 1"
          },
          {
            "x": "229",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "229",
            "y": "1067/67390",
            "series": "Forest probability of class 1"
          },
          {
            "x": "230",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "230",
            "y": "5/1539",
            "series": "Forest probability of class 1"
          },
          {
            "x": "231",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "231",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "232",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "232",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "233",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "233",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "234",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "234",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "235",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "235",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "236",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "236",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "237",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "237",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "238",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "238",
            "y": "1067/67390",
            "series": "Forest probability of class 1"
          },
          {
            "x": "239",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "239",
            "y": "1067/67390",
            "series": "Forest probability of class 1"
          },
          {
            "x": "240",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "240",
            "y": "1067/67390",
            "series": "Forest probability of class 1"
          },
          {
            "x": "241",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "241",
            "y": "80075069/445184343",
            "series": "Forest probability of class 1"
          },
          {
            "x": "242",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "242",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "243",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "243",
            "y": "80075069/445184343",
            "series": "Forest probability of class 1"
          },
          {
            "x": "244",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "244",
            "y": "80075069/445184343",
            "series": "Forest probability of class 1"
          },
          {
            "x": "245",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "245",
            "y": "13525031/87435522",
            "series": "Forest probability of class 1"
          },
          {
            "x": "246",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "246",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "247",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "247",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "248",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "248",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "249",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "249",
            "y": "1067/67390",
            "series": "Forest probability of class 1"
          },
          {
            "x": "250",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "250",
            "y": "5/1539",
            "series": "Forest probability of class 1"
          },
          {
            "x": "251",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "251",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "252",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "252",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "253",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "253",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "254",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "254",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "255",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "255",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "256",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "256",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "257",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "257",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "258",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "258",
            "y": "1067/67390",
            "series": "Forest probability of class 1"
          },
          {
            "x": "259",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "259",
            "y": "1067/67390",
            "series": "Forest probability of class 1"
          },
          {
            "x": "260",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "260",
            "y": "1067/67390",
            "series": "Forest probability of class 1"
          },
          {
            "x": "261",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "261",
            "y": "80075069/445184343",
            "series": "Forest probability of class 1"
          },
          {
            "x": "262",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "262",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "263",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "263",
            "y": "80075069/445184343",
            "series": "Forest probability of class 1"
          },
          {
            "x": "264",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "264",
            "y": "80075069/445184343",
            "series": "Forest probability of class 1"
          },
          {
            "x": "265",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "265",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "266",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "266",
            "y": "80075069/445184343",
            "series": "Forest probability of class 1"
          },
          {
            "x": "267",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "267",
            "y": "13525031/87435522",
            "series": "Forest probability of class 1"
          },
          {
            "x": "268",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "268",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "269",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "269",
            "y": "1067/67390",
            "series": "Forest probability of class 1"
          },
          {
            "x": "270",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "270",
            "y": "5/1539",
            "series": "Forest probability of class 1"
          },
          {
            "x": "271",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "271",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "272",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "272",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "273",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "273",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "274",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "274",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "275",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "275",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "276",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "276",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "277",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "277",
            "y": "5825/213921",
            "series": "Forest probability of class 1"
          },
          {
            "x": "278",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "278",
            "y": "1067/67390",
            "series": "Forest probability of class 1"
          },
          {
            "x": "279",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "279",
            "y": "1067/67390",
            "series": "Forest probability of class 1"
          },
          {
            "x": "280",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "280",
            "y": "1067/67390",
            "series": "Forest probability of class 1"
          },
          {
            "x": "281",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "281",
            "y": "80075069/445184343",
            "series": "Forest probability of class 1"
          },
          {
            "x": "282",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "282",
            "y": "80075069/445184343",
            "series": "Forest probability of class 1"
          },
          {
            "x": "283",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "283",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "284",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "284",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "285",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "285",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "286",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "286",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "287",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "287",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "288",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "288",
            "y": "6022733/60235233",
            "series": "Forest probability of class 1"
          },
          {
            "x": "289",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "289",
            "y": "1067/67390",
            "series": "Forest probability of class 1"
          },
          {
            "x": "290",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "290",
            "y": "1067/67390",
            "series": "Forest probability of class 1"
          },
          {
            "x": "291",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "291",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "292",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "292",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "293",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "293",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "294",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "294",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "295",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "295",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "296",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "296",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "297",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "297",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "298",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "298",
            "y": "1067/67390",
            "series": "Forest probability of class 1"
          },
          {
            "x": "299",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "299",
            "y": "1067/67390",
            "series": "Forest probability of class 1"
          },
          {
            "x": "300",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "300",
            "y": "1067/67390",
            "series": "Forest probability of class 1"
          },
          {
            "x": "301",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "301",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "302",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "302",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "303",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "303",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "304",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "304",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "305",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "305",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "306",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "306",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "307",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "307",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "308",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "308",
            "y": "5/1539",
            "series": "Forest probability of class 1"
          },
          {
            "x": "309",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "309",
            "y": "5/1539",
            "series": "Forest probability of class 1"
          },
          {
            "x": "310",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "310",
            "y": "5/1539",
            "series": "Forest probability of class 1"
          },
          {
            "x": "311",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "311",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "312",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "312",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "313",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "313",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "314",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "314",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "315",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "315",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "316",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "316",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "317",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "317",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "318",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "318",
            "y": "1067/67390",
            "series": "Forest probability of class 1"
          },
          {
            "x": "319",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "319",
            "y": "1067/67390",
            "series": "Forest probability of class 1"
          },
          {
            "x": "320",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "320",
            "y": "1067/67390",
            "series": "Forest probability of class 1"
          },
          {
            "x": "321",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "321",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "322",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "322",
            "y": "13525031/87435522",
            "series": "Forest probability of class 1"
          },
          {
            "x": "323",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "323",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "324",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "324",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "325",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "325",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "326",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "326",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "327",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "327",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "328",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "328",
            "y": "1118839/28101630",
            "series": "Forest probability of class 1"
          },
          {
            "x": "329",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "329",
            "y": "1067/67390",
            "series": "Forest probability of class 1"
          },
          {
            "x": "330",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "330",
            "y": "5/1539",
            "series": "Forest probability of class 1"
          },
          {
            "x": "331",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "331",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "332",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "332",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "333",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "333",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "334",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "334",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "335",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "335",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "336",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "336",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "337",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "337",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "338",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "338",
            "y": "1067/67390",
            "series": "Forest probability of class 1"
          },
          {
            "x": "339",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "339",
            "y": "1067/67390",
            "series": "Forest probability of class 1"
          },
          {
            "x": "340",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "340",
            "y": "1067/67390",
            "series": "Forest probability of class 1"
          },
          {
            "x": "341",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "341",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "342",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "342",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "343",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "343",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "344",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "344",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "345",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "345",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "346",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "346",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "347",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "347",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "348",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "348",
            "y": "1067/67390",
            "series": "Forest probability of class 1"
          },
          {
            "x": "349",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "349",
            "y": "1067/67390",
            "series": "Forest probability of class 1"
          },
          {
            "x": "350",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "350",
            "y": "1067/67390",
            "series": "Forest probability of class 1"
          },
          {
            "x": "351",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "351",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "352",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "352",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "353",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "353",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "354",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "354",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "355",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "355",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "356",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "356",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "357",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "357",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "358",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "358",
            "y": "1067/67390",
            "series": "Forest probability of class 1"
          },
          {
            "x": "359",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "359",
            "y": "1067/67390",
            "series": "Forest probability of class 1"
          },
          {
            "x": "360",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "360",
            "y": "1067/67390",
            "series": "Forest probability of class 1"
          },
          {
            "x": "361",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "361",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "362",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "362",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "363",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "363",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "364",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "364",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "365",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "365",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "366",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "366",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "367",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "367",
            "y": "10287653/105463053",
            "series": "Forest probability of class 1"
          },
          {
            "x": "368",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "368",
            "y": "1067/67390",
            "series": "Forest probability of class 1"
          },
          {
            "x": "369",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "369",
            "y": "1067/67390",
            "series": "Forest probability of class 1"
          },
          {
            "x": "370",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "370",
            "y": "1067/67390",
            "series": "Forest probability of class 1"
          },
          {
            "x": "371",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "371",
            "y": "80075069/445184343",
            "series": "Forest probability of class 1"
          },
          {
            "x": "372",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "372",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "373",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "373",
            "y": "80075069/445184343",
            "series": "Forest probability of class 1"
          },
          {
            "x": "374",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "374",
            "y": "80075069/445184343",
            "series": "Forest probability of class 1"
          },
          {
            "x": "375",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "375",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "376",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "376",
            "y": "80075069/445184343",
            "series": "Forest probability of class 1"
          },
          {
            "x": "377",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "377",
            "y": "13525031/87435522",
            "series": "Forest probability of class 1"
          },
          {
            "x": "378",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "378",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "379",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "379",
            "y": "1067/67390",
            "series": "Forest probability of class 1"
          },
          {
            "x": "380",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "380",
            "y": "5/1539",
            "series": "Forest probability of class 1"
          },
          {
            "x": "381",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "381",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "382",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "382",
            "y": "13525031/87435522",
            "series": "Forest probability of class 1"
          },
          {
            "x": "383",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "383",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "384",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "384",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "385",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "385",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "386",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "386",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "387",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "387",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "388",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "388",
            "y": "1118839/28101630",
            "series": "Forest probability of class 1"
          },
          {
            "x": "389",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "389",
            "y": "1067/67390",
            "series": "Forest probability of class 1"
          },
          {
            "x": "390",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "390",
            "y": "5/1539",
            "series": "Forest probability of class 1"
          },
          {
            "x": "391",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "391",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "392",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "392",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "393",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "393",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "394",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "394",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "395",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "395",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "396",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "396",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "397",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "397",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "398",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "398",
            "y": "1067/67390",
            "series": "Forest probability of class 1"
          },
          {
            "x": "399",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "399",
            "y": "1067/67390",
            "series": "Forest probability of class 1"
          },
          {
            "x": "400",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "400",
            "y": "1067/67390",
            "series": "Forest probability of class 1"
          },
          {
            "x": "401",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "401",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "402",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "402",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "403",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "403",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "404",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "404",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "405",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "405",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "406",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "406",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "407",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "407",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "408",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "408",
            "y": "1067/67390",
            "series": "Forest probability of class 1"
          },
          {
            "x": "409",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "409",
            "y": "1067/67390",
            "series": "Forest probability of class 1"
          },
          {
            "x": "410",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "410",
            "y": "1067/67390",
            "series": "Forest probability of class 1"
          },
          {
            "x": "411",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "411",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "412",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "412",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "413",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "413",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "414",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "414",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "415",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "415",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "416",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "416",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "417",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "417",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "418",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "418",
            "y": "1067/67390",
            "series": "Forest probability of class 1"
          },
          {
            "x": "419",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "419",
            "y": "1067/67390",
            "series": "Forest probability of class 1"
          },
          {
            "x": "420",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "420",
            "y": "1067/67390",
            "series": "Forest probability of class 1"
          },
          {
            "x": "421",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "421",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "422",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "422",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "423",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "423",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "424",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "424",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "425",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "425",
            "y": "13525031/87435522",
            "series": "Forest probability of class 1"
          },
          {
            "x": "426",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "426",
            "y": "13525031/87435522",
            "series": "Forest probability of class 1"
          },
          {
            "x": "427",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "427",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "428",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "428",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "429",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "429",
            "y": "5/1539",
            "series": "Forest probability of class 1"
          },
          {
            "x": "430",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "430",
            "y": "5/1539",
            "series": "Forest probability of class 1"
          },
          {
            "x": "431",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "431",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "432",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "432",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "433",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "433",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "434",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "434",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "435",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "435",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "436",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "436",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "437",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "437",
            "y": "13525031/87435522",
            "series": "Forest probability of class 1"
          },
          {
            "x": "438",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "438",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "439",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "439",
            "y": "5/1539",
            "series": "Forest probability of class 1"
          },
          {
            "x": "440",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "440",
            "y": "5/1539",
            "series": "Forest probability of class 1"
          },
          {
            "x": "441",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "441",
            "y": "13525031/87435522",
            "series": "Forest probability of class 1"
          },
          {
            "x": "442",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "442",
            "y": "13525031/87435522",
            "series": "Forest probability of class 1"
          },
          {
            "x": "443",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "443",
            "y": "13525031/87435522",
            "series": "Forest probability of class 1"
          },
          {
            "x": "444",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "444",
            "y": "13525031/87435522",
            "series": "Forest probability of class 1"
          },
          {
            "x": "445",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "445",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "446",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "446",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "447",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "447",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "448",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "448",
            "y": "5825/213921",
            "series": "Forest probability of class 1"
          },
          {
            "x": "449",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "449",
            "y": "5/1539",
            "series": "Forest probability of class 1"
          },
          {
            "x": "450",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "450",
            "y": "5/1539",
            "series": "Forest probability of class 1"
          },
          {
            "x": "451",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "451",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "452",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "452",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "453",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "453",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "454",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "454",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "455",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "455",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "456",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "456",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "457",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "457",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "458",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "458",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "459",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "459",
            "y": "5/1539",
            "series": "Forest probability of class 1"
          },
          {
            "x": "460",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "460",
            "y": "5/1539",
            "series": "Forest probability of class 1"
          },
          {
            "x": "461",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "461",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "462",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "462",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "463",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "463",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "464",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "464",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "465",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "465",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "466",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "466",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "467",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "467",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "468",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "468",
            "y": "5/1539",
            "series": "Forest probability of class 1"
          },
          {
            "x": "469",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "469",
            "y": "5/1539",
            "series": "Forest probability of class 1"
          },
          {
            "x": "470",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "470",
            "y": "5/1539",
            "series": "Forest probability of class 1"
          },
          {
            "x": "471",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "471",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "472",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "472",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "473",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "473",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "474",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "474",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "475",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "475",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "476",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "476",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "477",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "477",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "478",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "478",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "479",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "479",
            "y": "5825/213921",
            "series": "Forest probability of class 1"
          },
          {
            "x": "480",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "480",
            "y": "5/1539",
            "series": "Forest probability of class 1"
          },
          {
            "x": "481",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "481",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "482",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "482",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "483",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "483",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "484",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "484",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "485",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "485",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "486",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "486",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "487",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "487",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "488",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "488",
            "y": "5/1539",
            "series": "Forest probability of class 1"
          },
          {
            "x": "489",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "489",
            "y": "5/1539",
            "series": "Forest probability of class 1"
          },
          {
            "x": "490",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "490",
            "y": "1067/67390",
            "series": "Forest probability of class 1"
          },
          {
            "x": "491",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "491",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "492",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "492",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "493",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "493",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "494",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "494",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "495",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "495",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "496",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "496",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "497",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "497",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "498",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "498",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "499",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "499",
            "y": "5/1539",
            "series": "Forest probability of class 1"
          },
          {
            "x": "500",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "500",
            "y": "5/1539",
            "series": "Forest probability of class 1"
          },
          {
            "x": "501",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "501",
            "y": "13525031/87435522",
            "series": "Forest probability of class 1"
          },
          {
            "x": "502",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "502",
            "y": "13525031/87435522",
            "series": "Forest probability of class 1"
          },
          {
            "x": "503",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "503",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "504",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "504",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "505",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "505",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "506",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "506",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "507",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "507",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "508",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "508",
            "y": "5825/213921",
            "series": "Forest probability of class 1"
          },
          {
            "x": "509",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "509",
            "y": "5/1539",
            "series": "Forest probability of class 1"
          },
          {
            "x": "510",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "510",
            "y": "5/1539",
            "series": "Forest probability of class 1"
          },
          {
            "x": "511",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "511",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "512",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "512",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "513",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "513",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "514",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "514",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "515",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "515",
            "y": "13525031/87435522",
            "series": "Forest probability of class 1"
          },
          {
            "x": "516",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "516",
            "y": "13525031/87435522",
            "series": "Forest probability of class 1"
          },
          {
            "x": "517",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "517",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "518",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "518",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "519",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "519",
            "y": "5/1539",
            "series": "Forest probability of class 1"
          },
          {
            "x": "520",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "520",
            "y": "5/1539",
            "series": "Forest probability of class 1"
          },
          {
            "x": "521",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "521",
            "y": "80075069/445184343",
            "series": "Forest probability of class 1"
          },
          {
            "x": "522",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "522",
            "y": "80075069/445184343",
            "series": "Forest probability of class 1"
          },
          {
            "x": "523",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "523",
            "y": "80075069/445184343",
            "series": "Forest probability of class 1"
          },
          {
            "x": "524",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "524",
            "y": "80075069/445184343",
            "series": "Forest probability of class 1"
          },
          {
            "x": "525",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "525",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "526",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "526",
            "y": "13525031/87435522",
            "series": "Forest probability of class 1"
          },
          {
            "x": "527",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "527",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "528",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "528",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "529",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "529",
            "y": "5/1539",
            "series": "Forest probability of class 1"
          },
          {
            "x": "530",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "530",
            "y": "5/1539",
            "series": "Forest probability of class 1"
          },
          {
            "x": "531",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "531",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "532",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "532",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "533",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "533",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "534",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "534",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "535",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "535",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "536",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "536",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "537",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "537",
            "y": "13525031/87435522",
            "series": "Forest probability of class 1"
          },
          {
            "x": "538",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "538",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "539",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "539",
            "y": "5/1539",
            "series": "Forest probability of class 1"
          },
          {
            "x": "540",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "540",
            "y": "5/1539",
            "series": "Forest probability of class 1"
          },
          {
            "x": "541",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "541",
            "y": "80075069/445184343",
            "series": "Forest probability of class 1"
          },
          {
            "x": "542",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "542",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "543",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "543",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "544",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "544",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "545",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "545",
            "y": "13525031/87435522",
            "series": "Forest probability of class 1"
          },
          {
            "x": "546",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "546",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "547",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "547",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "548",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "548",
            "y": "6022733/60235233",
            "series": "Forest probability of class 1"
          },
          {
            "x": "549",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "549",
            "y": "1067/67390",
            "series": "Forest probability of class 1"
          },
          {
            "x": "550",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "550",
            "y": "5/1539",
            "series": "Forest probability of class 1"
          },
          {
            "x": "551",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "551",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "552",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "552",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "553",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "553",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "554",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "554",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "555",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "555",
            "y": "13525031/87435522",
            "series": "Forest probability of class 1"
          },
          {
            "x": "556",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "556",
            "y": "13525031/87435522",
            "series": "Forest probability of class 1"
          },
          {
            "x": "557",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "557",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "558",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "558",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "559",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "559",
            "y": "5/1539",
            "series": "Forest probability of class 1"
          },
          {
            "x": "560",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "560",
            "y": "5/1539",
            "series": "Forest probability of class 1"
          },
          {
            "x": "561",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "561",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "562",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "562",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "563",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "563",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "564",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "564",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "565",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "565",
            "y": "13525031/87435522",
            "series": "Forest probability of class 1"
          },
          {
            "x": "566",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "566",
            "y": "13525031/87435522",
            "series": "Forest probability of class 1"
          },
          {
            "x": "567",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "567",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "568",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "568",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "569",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "569",
            "y": "5/1539",
            "series": "Forest probability of class 1"
          },
          {
            "x": "570",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "570",
            "y": "5/1539",
            "series": "Forest probability of class 1"
          },
          {
            "x": "571",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "571",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "572",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "572",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "573",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "573",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "574",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "574",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "575",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "575",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "576",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "576",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "577",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "577",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "578",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "578",
            "y": "1067/67390",
            "series": "Forest probability of class 1"
          },
          {
            "x": "579",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "579",
            "y": "1067/67390",
            "series": "Forest probability of class 1"
          },
          {
            "x": "580",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "580",
            "y": "5/1539",
            "series": "Forest probability of class 1"
          },
          {
            "x": "581",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "581",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "582",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "582",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "583",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "583",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "584",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "584",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "585",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "585",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "586",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "586",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "587",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "587",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "588",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "588",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "589",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "589",
            "y": "5825/213921",
            "series": "Forest probability of class 1"
          },
          {
            "x": "590",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "590",
            "y": "5/1539",
            "series": "Forest probability of class 1"
          },
          {
            "x": "591",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "591",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "592",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "592",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "593",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "593",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "594",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "594",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "595",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "595",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "596",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "596",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "597",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "597",
            "y": "13525031/87435522",
            "series": "Forest probability of class 1"
          },
          {
            "x": "598",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "598",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "599",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "599",
            "y": "5/1539",
            "series": "Forest probability of class 1"
          },
          {
            "x": "600",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "600",
            "y": "5/1539",
            "series": "Forest probability of class 1"
          },
          {
            "x": "601",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "601",
            "y": "80075069/445184343",
            "series": "Forest probability of class 1"
          },
          {
            "x": "602",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "602",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "603",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "603",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "604",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "604",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "605",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "605",
            "y": "13525031/87435522",
            "series": "Forest probability of class 1"
          },
          {
            "x": "606",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "606",
            "y": "153157741/635085558",
            "series": "Forest probability of class 1"
          },
          {
            "x": "607",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "607",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "608",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "608",
            "y": "6022733/60235233",
            "series": "Forest probability of class 1"
          },
          {
            "x": "609",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "609",
            "y": "1067/67390",
            "series": "Forest probability of class 1"
          },
          {
            "x": "610",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "610",
            "y": "5/1539",
            "series": "Forest probability of class 1"
          },
          {
            "x": "611",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "611",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "612",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "612",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "613",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "613",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "614",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "614",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "615",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "615",
            "y": "13525031/87435522",
            "series": "Forest probability of class 1"
          },
          {
            "x": "616",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "616",
            "y": "13525031/87435522",
            "series": "Forest probability of class 1"
          },
          {
            "x": "617",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "617",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "618",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "618",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "619",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "619",
            "y": "5/1539",
            "series": "Forest probability of class 1"
          },
          {
            "x": "620",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "620",
            "y": "5/1539",
            "series": "Forest probability of class 1"
          },
          {
            "x": "621",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "621",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "622",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "622",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "623",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "623",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "624",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "624",
            "y": "5724223/61290837",
            "series": "Forest probability of class 1"
          },
          {
            "x": "625",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "625",
            "y": "13525031/87435522",
            "series": "Forest probability of class 1"
          },
          {
            "x": "626",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "626",
            "y": "13525031/87435522",
            "series": "Forest probability of class 1"
          },
          {
            "x": "627",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "627",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "628",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "628",
            "y": "13246343/89529786",
            "series": "Forest probability of class 1"
          },
          {
            "x": "629",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "629",
            "y": "5/1539",
            "series": "Forest probability of class 1"
          },
          {
            "x": "630",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "630",
            "y": "5/1539",
            "series": "Forest probability of class 1"
          }
        ],
        "plotFile": "ml09-fixed-results/realdata-company-python/plot.svg",
        "plotSHA256": "93922fb565b17b4da0ea582f3b35954c7101b63cd8ca74518d26c74870750c6b",
        "files": [
          {
            "file": "ml09-fixed-results/realdata-company-python/full.json",
            "sha256": "bfe5bc3248ee66ea47a5bae26961e3baa093deb32789cc36003754a7be0207bc"
          },
          {
            "file": "ml09-fixed-results/realdata-company-python/plot-points.csv",
            "sha256": "5965cd1efbf3bcc0d0f47b07552e03b7a2fd45991012e5aedf4f4611b7265930"
          },
          {
            "file": "ml09-fixed-results/realdata-company-python/plot.svg",
            "sha256": "93922fb565b17b4da0ea582f3b35954c7101b63cd8ca74518d26c74870750c6b"
          },
          {
            "file": "ml09-fixed-results/realdata-company-python/summary.csv",
            "sha256": "1cac88ff86a8e427fef533f51b3d128753713c9935be477ca0a0a65dbaa48870"
          }
        ],
        "scope": "Actually executed self-contained fixed example; current web controls execute separately. Python Fraction and finite-precision base R. Author gate, not independent peer."
      }
    },
    "r": {
      "country": {
        "api": "realdata",
        "variant": "country",
        "language": "r",
        "codeFile": "ml09-code/realdata-country.R",
        "codeSHA256": "fe639adf07c6ff5d732473dca6fe31923242c02aab773c832acd84587edee6f2",
        "codeText": "# ML09 base-R reproduction from native original-field CSVs.\n# Rscript ml09-public-analysis.R ml09-sources results-r\n# Separately written vectorized direct-centered squared/Gini losses.\n# No Python/JS/model-contract/stored-answer/derived-result reader or package.\n# Numeric arithmetic is binary64:1e-12 relative tie tolerance stabilizes exact\n# source ties,but does not certify tiny margins/underflow like Fraction JS/Python.\n# Data-frame rows use x0,x1,...,y,weight; original IDs remain attached to draws.\noptions(stringsAsFactors=FALSE,digits=17)\nnum<-function(v){if(is.null(v)||length(v)!=1||is.na(v))stop('numeric parameter required, not explicit NULL');p<-strsplit(as.character(v),'/',fixed=TRUE)[[1]];z<-if(length(p)==2)as.numeric(p[1])/as.numeric(p[2])else as.numeric(v);if(!is.finite(z))stop('finite numeric parameter');z}\noption<-function(a,k,default){if(k%in%names(a))a[[k]]else default}\nnormrows<-function(d,task){if(!'weight'%in%names(d))d$weight<-1;if(!'id'%in%names(d))d$id<-as.character(seq_len(nrow(d))-1);d$weight<-as.numeric(d$weight);if(anyNA(d$weight)||any(d$weight<0))stop('nonnegative weights');if(task=='regression')d$y<-as.numeric(d$y)else d$y<-as.character(d$y);d}\nstat<-function(d,task,classes){W<-sum(d$weight);mu<-if(task=='regression'&&W)sum(d$weight*d$y)/W else NA_real_;p<-if(task=='classification'&&W)vapply(classes,function(c)sum(d$weight[d$y==c])/W,0)else numeric();risk<-if(task=='regression'&&W)sum(d$weight*(d$y-mu)^2)else W*sum(p*(1-p));list(n=nrow(d),w=W,mu=mu,p=unname(p),risk=risk,pred=if(task=='regression')mu else if(W)classes[which.max(p)]else NA_character_)}\nfit<-function(d,a,task,classes,schedule=NULL){d<-d[d$weight>0&!is.na(d$y),,drop=FALSE];if(!nrow(d))stop('positive observed training');W<-sum(d$weight);depth<-option(a,'maxDepth',2);minimum<-option(a,'minLeaf',1);minmass<-num(option(a,'minLeafWeight',0));mingain<-num(option(a,'minGain',0));route<-option(a,'missingRoute','best');features<-grep('^x[0-9]+$',names(d),value=TRUE)\n build<-function(rr,level,path){st<-stat(rr,task,classes);node<-list(rows=rr,st=st,split=NULL,left=NULL,right=NULL,path=path);if(level==depth)return(node);best<-NULL;allowed<-if(is.null(schedule))seq_along(features)-1L else schedule[[match(path,names(schedule))]]\n  for(j in seq_along(features)-1L){if(!j%in%allowed)next;v<-rr[[features[j+1L]]];values<-sort(unique(v[!is.na(v)]));candidates<-list()\n   if(length(values)>1)for(k in seq_len(length(values)-1L)){threshold<-(values[k]+values[k+1L])/2;missing<-is.na(v);left<-!missing&v<=threshold;right<-!missing&v>threshold;directions<-if(route!='best')route else if(any(missing))c('left','right')else if(sum(left)>=sum(right))'left'else'right';for(direction in directions)candidates[[length(candidates)+1L]]<-list(kind='threshold',threshold=threshold,missingRoute=direction,left=if(direction=='left')left|missing else left,right=if(direction=='right')right|missing else right)}\n   if(anyNA(v)&&any(!is.na(v)))candidates[[length(candidates)+1L]]<-list(kind='missing-only',threshold=NA_real_,missingRoute='left',left=is.na(v),right=!is.na(v))\n   for(candidate in candidates){l<-rr[candidate$left,,drop=FALSE];r<-rr[candidate$right,,drop=FALSE];ls<-stat(l,task,classes);rs<-stat(r,task,classes);if(min(ls$n,rs$n)<minimum||min(ls$w,rs$w)<minmass||min(ls$w,rs$w)<=0)next;gain<-(st$risk-ls$risk-rs$risk)/W;tol<-1e-12*max(1,abs(gain),if(is.null(best))0 else abs(best$gain));if(is.null(best)||gain>best$gain+tol)best<-c(candidate,list(feature=j,gain=gain,l=l,r=r))}\n  }\n  if(!is.null(best)&&best$gain>max(mingain,1e-12)){node$split<-best;node$left<-build(best$l,level+1L,paste0(path,'L'));node$right<-build(best$r,level+1L,paste0(path,'R'))};node\n };build(d,0L,'')\n}\npredict_one<-function(tree,row){n<-tree;while(!is.null(n$split)){s<-n$split;v<-as.numeric(row[[paste0('x',s$feature)]]);left<-if(s$kind=='missing-only')is.na(v)else if(is.na(v))s$missingRoute=='left'else v<=s$threshold;n<-if(left)n$left else n$right};list(prediction=n$st$pred,probabilities=n$st$p)}\ncombine<-function(pp,w,task,classes,mode='probabilities'){W<-sum(w);if(!length(pp)||!W)return(list(prediction=if(task=='regression')NA_real_ else NA_character_,probabilities=numeric(),vote=NA_character_,prob=NA_character_));if(task=='regression')return(list(prediction=sum(vapply(pp,function(p)p$prediction,0)*w)/W,probabilities=numeric(),vote=NA_character_,prob=NA_character_));votes<-vapply(classes,function(c)sum(w[vapply(pp,function(p)p$prediction==c,FALSE)])/W,0);probs<-vapply(seq_along(classes),function(j)sum(vapply(pp,function(p)p$probabilities[j],0)*w)/W,0);vote<-classes[which.max(votes)];prob<-classes[which.max(probs)];list(prediction=if(mode=='votes')vote else prob,probabilities=unname(probs),vote=vote,prob=prob,votes=unname(votes))}\nvariance<-function(a){B<-num(a$B);v<-num(a$marginalVariance);rho<-num(option(a,'rho',0));if(B<1||B!=floor(B)||v<0)stop('integer B/nonnegative variance');if(B>1&&v>0&&(rho< -1/(B-1)||rho>1))stop('PSD correlation');list(B=B,marginalVariance=v,correlationApplicable=B>1&&v>0,varianceOfMean=if(B==1)v else v*(1+(B-1)*rho)/B)}\naggregate<-function(a){task<-option(a,'task','regression');classes<-option(a,'classes',character());w<-vapply(option(a,'memberWeights',as.list(rep(1,length(a$members)))),num,0);if(any(w<0)||sum(w)<=0)stop('positive member mass');ids<-a$members[[1]]$predictions$id;pp<-lapply(ids,function(id){members<-lapply(a$members,function(m){r<-m$predictions[match(id,m$predictions$id),,drop=FALSE];if(task=='regression')list(prediction=num(r$value),probabilities=numeric())else list(prediction=as.character(r$label),probabilities=as.numeric(r[paste0('p',seq_along(classes)-1L)]))});c(list(id=id),combine(members,w,task,classes,option(a,'aggregation','probabilities')))});list(task=task,classes=classes,predictions=pp)}\nscored<-function(preds,d,task,classes){W<-loss<-absolute<-errors<-voteerrors<-0;count<-0L;out<-lapply(seq_len(nrow(d)),function(i){r<-d[i,,drop=FALSE];p<-preds[[i]];ok<-!is.na(p$prediction)&&!is.na(r$y)&&r$weight>0;value<-NA_real_;if(ok){count<<-count+1L;W<<-W+r$weight;if(task=='regression'){e<-r$y-p$prediction;value<-e*e;absolute<<-absolute+r$weight*abs(e)}else{value<-sum((p$probabilities-as.numeric(classes==r$y))^2);errors<<-errors+r$weight*(p$prediction!=r$y);voteerrors<<-voteerrors+r$weight*(p$vote!=r$y)};loss<<-loss+r$weight*value};c(p,list(actual=r$y,weight=r$weight,scoreEligible=ok,loss=value))});list(rows=out,eligibleRows=count,weight=W,totalLoss=loss,meanLoss=if(W)loss/W else NA_real_,MAE=if(W&&task=='regression')absolute/W else NA_real_,errorRate=if(W&&task=='classification')errors/W else NA_real_,labelVoteErrorRate=if(W&&task=='classification')voteerrors/W else NA_real_)}\nensemble<-function(a,forest=FALSE){task<-option(a,'task','regression');classes<-option(a,'classes',character());d<-normrows(a$rows,task);w<-vapply(option(a,'memberWeights',as.list(rep(1,length(a$bootstrapDraws)))),num,0);if(any(w<0)||sum(w)<=0)stop('positive member mass');members<-lapply(seq_along(a$bootstrapDraws),function(i){draw<-a$bootstrapDraws[[i]];indices<-match(draw,d$id);if(anyNA(indices))stop('unknown draw source');tree<-fit(d[indices,,drop=FALSE],a,task,classes,if(forest)a$nodeFeatures[[i]]else NULL);list(tree=tree,draw=draw,inbag=unique(draw),weight=w[i])});queries<-a$queries;preds<-lapply(seq_len(nrow(queries)),function(i)c(list(id=queries$id[i]),combine(lapply(members,function(m)predict_one(m$tree,queries[i,,drop=FALSE])),w,task,classes,option(a,'aggregation','probabilities'))));oob<-lapply(seq_len(nrow(d)),function(i){app<-which(!vapply(members,function(m)d$id[i]%in%m$inbag,FALSE));pp<-combine(lapply(app,function(j)predict_one(members[[j]]$tree,d[i,,drop=FALSE])),w[app],task,classes,option(a,'aggregation','probabilities'));c(list(id=d$id[i],applicable=app-1L,positiveMembers=sum(w[app]>0)),pp)});list(task=task,classes=classes,members=members,predictions=preds,outOfBag=scored(oob,d,task,classes))}\nboost<-function(a){if(option(a,'task','regression')!='regression')stop('regression boosting only');d<-normrows(a$rows,'regression');eligible<-d$weight>0&!is.na(d$y);W<-sum(d$weight[eligible]);if(!W)stop('positive eligible training');eta<-num(option(a,'learningRate','1/2'));stages<-option(a,'stages',3);if(is.null(stages)||stages!=floor(stages)||stages<0||stages>8||eta<0||eta>1)stop('supported rate/stages');initial<-if('initial'%in%names(a))num(a$initial)else sum(d$weight[eligible]*d$y[eligible])/W;train<-matrix(initial,nrow(d),stages+1L);query<-matrix(initial,nrow(a$queries),stages+1L);losses<-fits<-list();for(stage in 0:stages){sse<-sum(d$weight[eligible]*(d$y[eligible]-train[eligible,stage+1L])^2);losses[[stage+1L]]<-list(stage=stage,rawWeightedSSE=sse,MSE=sse/W,meanHalfSquaredLoss=sse/(2*W));if(stage==stages)break;residual<-d;residual$y<-d$y-train[,stage+1L];tree<-fit(residual,a,'regression',character());h<-vapply(seq_len(nrow(d)),function(i)predict_one(tree,d[i,,drop=FALSE])$prediction,0);qh<-vapply(seq_len(nrow(a$queries)),function(i)predict_one(tree,a$queries[i,,drop=FALSE])$prediction,0);stageRows<-lapply(seq_len(nrow(d)),function(i)list(id=d$id[i],before=train[i,stage+1L],residual=residual$y[i],negativeCoordinateDerivative=d$weight[i]*residual$y[i]/W,fit=h[i],addition=eta*h[i],after=train[i,stage+1L]+eta*h[i]));train[,stage+2L]<-train[,stage+1L]+eta*h;query[,stage+2L]<-query[,stage+1L]+eta*qh;norm<-sum(d$weight[eligible]*h[eligible]^2);fits[[stage+1L]]<-list(stage=stage+1L,tree=tree,rows=stageRows,queryFits=qh,norm=norm,predictedSSEDecrease=eta*(2-eta)*norm)};list(task='regression',initial=initial,learningRate=eta,stages=stages,training=train,queries=query,fits=fits,losses=losses,predictions=lapply(seq_len(nrow(a$queries)),function(i)list(id=a$queries$id[i],prediction=query[i,stages+1L],probabilities=numeric(),vote=NA_character_,prob=NA_character_)))}\nfixed_schedules<-function(ids,p,seed){state<-seed;choose<-function(n){limit<-floor(4294967296/n)*n;repeat{state<<-(1664525*state+1013904223)%%4294967296;if(state<limit)return(as.integer(state%%n))}};draws<-schedules<-list();for(member in 1:4){draws[[member]]<-vapply(seq_along(ids),function(i)ids[choose(length(ids))+1L],'');schedule<-setNames(vector('list',7),c('','L','R','LL','LR','RL','RR'));for(path in names(schedule)){order<-seq_len(p)-1L;if(p>1)for(j in seq(p-1L,1L)){k<-choose(j+1L);temp<-order[j+1L];order[j+1L]<-order[k+1L];order[k+1L]<-temp};schedule[[match(path,names(schedule))]]<-sort(order[seq_len(max(1L,floor(sqrt(p))))])};schedules[[member]]<-schedule};list(draws=draws,schedules=schedules)}\nread_sources<-function(src){read<-function(name)read.csv(file.path(src,name),check.names=FALSE,colClasses='character',na.strings=character(),fileEncoding='UTF-8-BOM');raw<-read('actual320-country-four-indicators-original-2020-2024.csv');country<-do.call(rbind,lapply(sort(unique(raw$countryISO3)),function(code)do.call(rbind,lapply(2020:2024,function(year){keys<-c('NY.GDP.PCAP.KD','NY.GDP.MKTP.KD.ZG','FP.CPI.TOTL.ZG','SP.DYN.LE00.IN');v<-vapply(keys,function(k)as.numeric(raw$originalValueToken[raw$countryISO3==code&raw$date==as.character(year)&raw$indicatorID==k]),0);data.frame(id=paste0(code,':',year),sourceRow=paste0(code,':',year),originalID=code,year=year,x0=v[1]/10000,x1=v[2],x2=v[3],y=v[4],weight=1,role=if(anyNA(v))'excluded'else if(year==2024)'outer-test'else'train')}))));raw<-read('actual3613-NLS-original52-fields-and-selection.csv');i<-seq_len(nrow(raw));x0<-suppressWarnings(as.numeric(raw$ed76));x1<-suppressWarnings(as.numeric(raw$age76));y<-suppressWarnings(as.numeric(raw$wage76))/100;person<-data.frame(id=paste0('person:',i),sourceRow=as.character(i),originalID=raw$id,x0=x0,x1=x1,y=y,weight=1,role=ifelse(is.na(x0)|is.na(x1)|is.na(y),'excluded',ifelse(i%%5==0,'outer-test','train')));raw<-read('actual3150-churn-original14-fields-and-selection.csv');i<-seq_len(nrow(raw));company<-data.frame(id=paste0('customer:',i),sourceRow=as.character(i),originalID='',x0=as.numeric(raw[['Call  Failure']]),x1=as.numeric(raw[['Subscription  Length']]),x2=as.numeric(raw[['Charge  Amount']]),y=raw$Churn,weight=1,role=ifelse(i%%5==0,'outer-test','train'));models<-list();for(index in 1:3){kind<-c('country','person','company')[index];d<-list(country,person,company)[[index]];task<-if(kind=='company')'classification'else'regression';s<-fixed_schedules(d$id[d$role=='train'],if(kind=='person')2L else 3L,20261102+7919*(index-1L));models[[kind]]<-list(records=d,task=task,classes=if(task=='classification')c('0','1')else character(),draws=s$draws,schedules=s$schedules,minLeaf=c(4L,50L,30L)[index])};models}\nrealdata<-function(models,kind,options=list()){if(is.null(options)||!is.list(options))stop('options object');m<-models[[kind]];d<-m$records;train<-d[d$role=='train',,drop=FALSE];test<-d[d$role=='outer-test',,drop=FALSE];method<-option(options,'method','forest');depth<-option(options,'maxDepth',2);count<-option(options,'memberCount',3);if(!method%in%c('bagging','forest','boost'))stop('known method');a<-list(rows=train,queries=test,task=m$task,classes=m$classes,maxDepth=depth,minLeaf=option(options,'minLeaf',m$minLeaf),minLeafWeight=0,minGain=0,missingRoute='best',learningRate=option(options,'learningRate','1/2'),stages=option(options,'stages',3));if(method=='boost')result<-boost(a)else{a$bootstrapDraws<-m$draws[seq_len(count)];a$nodeFeatures<-lapply(m$schedules[seq_len(count)],function(s)s[nchar(names(s))<depth]);result<-ensemble(a,method=='forest')};outer<-scored(result$predictions,normrows(test,m$task),m$task,m$classes);st<-stat(normrows(train,m$task),m$task,m$classes);constant<-list(prediction=st$pred,probabilities=st$p,vote=st$pred,prob=st$pred);baseline<-scored(lapply(test$id,function(id)c(list(id=id),constant)),normrows(test,m$task),m$task,m$classes);list(kind=kind,method=method,settings=a,train=train,test=test,result=result,outer=outer,baseline=baseline)}\nAPI<-\"realdata\"\nINPUT<-list(kind=\"country\")\n\nrun_fixed<-function(api,a,out,src){\n r<-if(api=='variance')variance(a)else if(api=='aggregate')aggregate(a)else if(api%in%c('bagging','forest'))ensemble(a,api=='forest')else if(api=='boost')boost(a)else realdata(read_sources(src),a$kind)\n dir.create(out,recursive=TRUE,showWarnings=FALSE);summary<-list();points<-list();add<-function(x,y,s){if(!is.null(y)&&!is.na(y))points[[length(points)+1L]]<<-data.frame(x=x,y=as.numeric(y),series=s)}\n if(api=='variance'){summary<-r[c('B','varianceOfMean')];add(r$B,r$varianceOfMean,'Specified finite-B variance');xl<-'Number of members B';yl<-'Variance, stipulated units squared';title<-'Declared covariance model, not fitted trees'\n }else if(api=='aggregate'){p<-r$predictions[[1]];summary<-list(selectedPrediction=p$prediction);classification<-identical(a$task,'classification');if(classification){summary<-c(summary,list(voteLabel=p$vote,probabilityLabel=p$prob,meanProbability1=p$probabilities[2]));add(1,p$probabilities[2],'Mean probability of class 1');add(2,p$votes[2],'Label-vote share of class 1');xl<-'Aggregation (1=probability, 2=vote)';yl<-'Probability or vote share'}else{for(i in seq_along(a$members))add(i,num(a$members[[i]]$predictions$value[1]),'Member prediction');add(3,p$prediction,'Weighted mean');xl<-'Member 1, member 2, aggregate 3';yl<-'Prediction, assumed units'};title<-'Votes and probabilities are distinct objects'\n }else if(api%in%c('bagging','forest')){summary<-list(queryPrediction=r$predictions[[1]]$prediction,OOB.scoreable=r$outOfBag$eligibleRows,OOB.meanLoss=r$outOfBag$meanLoss);for(i in seq_len(nrow(a$rows)))add(i,a$rows$y[i],'Observed training outcome');for(i in seq_along(r$outOfBag$rows))add(i,r$outOfBag$rows[[i]]$prediction,'OOB prediction, when defined');xl<-'Original training ID order';yl<-'Outcome, assumed units';title<-'Repeated draws and ID-level OOB membership'\n }else if(api=='boost'){summary<-list(initial=r$initial,finalMSE=r$losses[[length(r$losses)]]$MSE,stages=r$stages);for(v in r$losses)add(v$stage,v$MSE,'Training MSE');xl<-'Boosting stage (0=initial)';yl<-'Weighted MSE, outcome units squared';title<-'Training descent does not certify held-out gain'\n }else{summary<-list(outer.scoreable=r$outer$eligibleRows,outer.meanLoss=r$outer$meanLoss,baseline.meanLoss=r$baseline$meanLoss,OOB.scoreable=r$result$outOfBag$eligibleRows,OOB.meanLoss=r$result$outOfBag$meanLoss);for(i in seq_along(r$outer$rows)){p<-r$outer$rows[[i]];add(i,as.numeric(p$actual),'Observed outcome');add(i,if(a$kind=='company')p$probabilities[2]else p$prediction,if(a$kind=='company')'Forest probability of class 1'else'Forest prediction')};xl<-'Outer-test source order, not a time path';yl<-if(a$kind=='company')'Churn label / probability'else if(a$kind=='country')'Period life expectancy, years'else'Nominal 1976 USD per hour';title<-'Fixed forest; outer labels did not fit the trees'}\n display<-function(v)if(is.null(v)||is.na(v))'undefined'else sprintf('%.9f',as.numeric(v));write.csv(data.frame(metric=names(summary),value=vapply(summary,display,'')),file.path(out,'summary.csv'),row.names=FALSE);pp<-do.call(rbind,points);write.csv(pp,file.path(out,'plot-points.csv'),row.names=FALSE);dput(r,file.path(out,'full-result.Rtext'));svg(file.path(out,'plot.svg'),width=5.6,height=4.6,pointsize=14);par(mar=c(5.8,5.8,5.3,1.2),mgp=c(3.7,1,0));xr<-range(pp$x);yr<-range(pp$y);if(diff(xr)==0)xr<-xr+c(-.5,.5);if(diff(yr)==0)yr<-yr+c(-.5,.5);plot(xr,yr,type='n',xlab=xl,ylab=yl,cex.lab=.78,axes=FALSE);axis(1,at=pretty(xr,3));axis(2,at=pretty(yr,4),las=1,cex.axis=.82);box();grid(col='#dddddd');cols<-c('#355c72','#a55336','#507956','#78568b');ss<-unique(pp$series);for(i in seq_along(ss)){v<-pp[pp$series==ss[i],];points(v$x,v$y,pch=16,cex=if(nrow(v)>100).35 else .85,col=adjustcolor(cols[i],if(nrow(v)>100).5 else 1))};legend('topleft',legend=ss,col=cols[seq_along(ss)],lty=0,pch=16,cex=.65,bty='n',inset=c(0,-.32),xpd=NA);mtext(title,side=3,line=3.9,cex=.6);dev.off();cat(paste(names(summary),vapply(summary,display,''),sep='=',collapse=', '),'\\n')\n}\nargs<-commandArgs(trailingOnly=TRUE)\ntryCatch(run_fixed(API,INPUT,if(length(args))args[1]else'fixed-results',if(length(args)>1)args[2]else'ml09-sources'),error=function(e){cat('Rejected declared input: ',conditionMessage(e),'\\n',file=stderr());quit(status=2)})\n",
        "code": "# ML09 base-R reproduction from native original-field CSVs.\n# Rscript ml09-public-analysis.R ml09-sources results-r\n# Separately written vectorized direct-centered squared/Gini losses.\n# No Python/JS/model-contract/stored-answer/derived-result reader or package.\n# Numeric arithmetic is binary64:1e-12 relative tie tolerance stabilizes exact\n# source ties,but does not certify tiny margins/underflow like Fraction JS/Python.\n# Data-frame rows use x0,x1,...,y,weight; original IDs remain attached to draws.\noptions(stringsAsFactors=FALSE,digits=17)\nnum<-function(v){if(is.null(v)||length(v)!=1||is.na(v))stop('numeric parameter required, not explicit NULL');p<-strsplit(as.character(v),'/',fixed=TRUE)[[1]];z<-if(length(p)==2)as.numeric(p[1])/as.numeric(p[2])else as.numeric(v);if(!is.finite(z))stop('finite numeric parameter');z}\noption<-function(a,k,default){if(k%in%names(a))a[[k]]else default}\nnormrows<-function(d,task){if(!'weight'%in%names(d))d$weight<-1;if(!'id'%in%names(d))d$id<-as.character(seq_len(nrow(d))-1);d$weight<-as.numeric(d$weight);if(anyNA(d$weight)||any(d$weight<0))stop('nonnegative weights');if(task=='regression')d$y<-as.numeric(d$y)else d$y<-as.character(d$y);d}\nstat<-function(d,task,classes){W<-sum(d$weight);mu<-if(task=='regression'&&W)sum(d$weight*d$y)/W else NA_real_;p<-if(task=='classification'&&W)vapply(classes,function(c)sum(d$weight[d$y==c])/W,0)else numeric();risk<-if(task=='regression'&&W)sum(d$weight*(d$y-mu)^2)else W*sum(p*(1-p));list(n=nrow(d),w=W,mu=mu,p=unname(p),risk=risk,pred=if(task=='regression')mu else if(W)classes[which.max(p)]else NA_character_)}\nfit<-function(d,a,task,classes,schedule=NULL){d<-d[d$weight>0&!is.na(d$y),,drop=FALSE];if(!nrow(d))stop('positive observed training');W<-sum(d$weight);depth<-option(a,'maxDepth',2);minimum<-option(a,'minLeaf',1);minmass<-num(option(a,'minLeafWeight',0));mingain<-num(option(a,'minGain',0));route<-option(a,'missingRoute','best');features<-grep('^x[0-9]+$',names(d),value=TRUE)\n build<-function(rr,level,path){st<-stat(rr,task,classes);node<-list(rows=rr,st=st,split=NULL,left=NULL,right=NULL,path=path);if(level==depth)return(node);best<-NULL;allowed<-if(is.null(schedule))seq_along(features)-1L else schedule[[match(path,names(schedule))]]\n  for(j in seq_along(features)-1L){if(!j%in%allowed)next;v<-rr[[features[j+1L]]];values<-sort(unique(v[!is.na(v)]));candidates<-list()\n   if(length(values)>1)for(k in seq_len(length(values)-1L)){threshold<-(values[k]+values[k+1L])/2;missing<-is.na(v);left<-!missing&v<=threshold;right<-!missing&v>threshold;directions<-if(route!='best')route else if(any(missing))c('left','right')else if(sum(left)>=sum(right))'left'else'right';for(direction in directions)candidates[[length(candidates)+1L]]<-list(kind='threshold',threshold=threshold,missingRoute=direction,left=if(direction=='left')left|missing else left,right=if(direction=='right')right|missing else right)}\n   if(anyNA(v)&&any(!is.na(v)))candidates[[length(candidates)+1L]]<-list(kind='missing-only',threshold=NA_real_,missingRoute='left',left=is.na(v),right=!is.na(v))\n   for(candidate in candidates){l<-rr[candidate$left,,drop=FALSE];r<-rr[candidate$right,,drop=FALSE];ls<-stat(l,task,classes);rs<-stat(r,task,classes);if(min(ls$n,rs$n)<minimum||min(ls$w,rs$w)<minmass||min(ls$w,rs$w)<=0)next;gain<-(st$risk-ls$risk-rs$risk)/W;tol<-1e-12*max(1,abs(gain),if(is.null(best))0 else abs(best$gain));if(is.null(best)||gain>best$gain+tol)best<-c(candidate,list(feature=j,gain=gain,l=l,r=r))}\n  }\n  if(!is.null(best)&&best$gain>max(mingain,1e-12)){node$split<-best;node$left<-build(best$l,level+1L,paste0(path,'L'));node$right<-build(best$r,level+1L,paste0(path,'R'))};node\n };build(d,0L,'')\n}\npredict_one<-function(tree,row){n<-tree;while(!is.null(n$split)){s<-n$split;v<-as.numeric(row[[paste0('x',s$feature)]]);left<-if(s$kind=='missing-only')is.na(v)else if(is.na(v))s$missingRoute=='left'else v<=s$threshold;n<-if(left)n$left else n$right};list(prediction=n$st$pred,probabilities=n$st$p)}\ncombine<-function(pp,w,task,classes,mode='probabilities'){W<-sum(w);if(!length(pp)||!W)return(list(prediction=if(task=='regression')NA_real_ else NA_character_,probabilities=numeric(),vote=NA_character_,prob=NA_character_));if(task=='regression')return(list(prediction=sum(vapply(pp,function(p)p$prediction,0)*w)/W,probabilities=numeric(),vote=NA_character_,prob=NA_character_));votes<-vapply(classes,function(c)sum(w[vapply(pp,function(p)p$prediction==c,FALSE)])/W,0);probs<-vapply(seq_along(classes),function(j)sum(vapply(pp,function(p)p$probabilities[j],0)*w)/W,0);vote<-classes[which.max(votes)];prob<-classes[which.max(probs)];list(prediction=if(mode=='votes')vote else prob,probabilities=unname(probs),vote=vote,prob=prob,votes=unname(votes))}\nvariance<-function(a){B<-num(a$B);v<-num(a$marginalVariance);rho<-num(option(a,'rho',0));if(B<1||B!=floor(B)||v<0)stop('integer B/nonnegative variance');if(B>1&&v>0&&(rho< -1/(B-1)||rho>1))stop('PSD correlation');list(B=B,marginalVariance=v,correlationApplicable=B>1&&v>0,varianceOfMean=if(B==1)v else v*(1+(B-1)*rho)/B)}\naggregate<-function(a){task<-option(a,'task','regression');classes<-option(a,'classes',character());w<-vapply(option(a,'memberWeights',as.list(rep(1,length(a$members)))),num,0);if(any(w<0)||sum(w)<=0)stop('positive member mass');ids<-a$members[[1]]$predictions$id;pp<-lapply(ids,function(id){members<-lapply(a$members,function(m){r<-m$predictions[match(id,m$predictions$id),,drop=FALSE];if(task=='regression')list(prediction=num(r$value),probabilities=numeric())else list(prediction=as.character(r$label),probabilities=as.numeric(r[paste0('p',seq_along(classes)-1L)]))});c(list(id=id),combine(members,w,task,classes,option(a,'aggregation','probabilities')))});list(task=task,classes=classes,predictions=pp)}\nscored<-function(preds,d,task,classes){W<-loss<-absolute<-errors<-voteerrors<-0;count<-0L;out<-lapply(seq_len(nrow(d)),function(i){r<-d[i,,drop=FALSE];p<-preds[[i]];ok<-!is.na(p$prediction)&&!is.na(r$y)&&r$weight>0;value<-NA_real_;if(ok){count<<-count+1L;W<<-W+r$weight;if(task=='regression'){e<-r$y-p$prediction;value<-e*e;absolute<<-absolute+r$weight*abs(e)}else{value<-sum((p$probabilities-as.numeric(classes==r$y))^2);errors<<-errors+r$weight*(p$prediction!=r$y);voteerrors<<-voteerrors+r$weight*(p$vote!=r$y)};loss<<-loss+r$weight*value};c(p,list(actual=r$y,weight=r$weight,scoreEligible=ok,loss=value))});list(rows=out,eligibleRows=count,weight=W,totalLoss=loss,meanLoss=if(W)loss/W else NA_real_,MAE=if(W&&task=='regression')absolute/W else NA_real_,errorRate=if(W&&task=='classification')errors/W else NA_real_,labelVoteErrorRate=if(W&&task=='classification')voteerrors/W else NA_real_)}\nensemble<-function(a,forest=FALSE){task<-option(a,'task','regression');classes<-option(a,'classes',character());d<-normrows(a$rows,task);w<-vapply(option(a,'memberWeights',as.list(rep(1,length(a$bootstrapDraws)))),num,0);if(any(w<0)||sum(w)<=0)stop('positive member mass');members<-lapply(seq_along(a$bootstrapDraws),function(i){draw<-a$bootstrapDraws[[i]];indices<-match(draw,d$id);if(anyNA(indices))stop('unknown draw source');tree<-fit(d[indices,,drop=FALSE],a,task,classes,if(forest)a$nodeFeatures[[i]]else NULL);list(tree=tree,draw=draw,inbag=unique(draw),weight=w[i])});queries<-a$queries;preds<-lapply(seq_len(nrow(queries)),function(i)c(list(id=queries$id[i]),combine(lapply(members,function(m)predict_one(m$tree,queries[i,,drop=FALSE])),w,task,classes,option(a,'aggregation','probabilities'))));oob<-lapply(seq_len(nrow(d)),function(i){app<-which(!vapply(members,function(m)d$id[i]%in%m$inbag,FALSE));pp<-combine(lapply(app,function(j)predict_one(members[[j]]$tree,d[i,,drop=FALSE])),w[app],task,classes,option(a,'aggregation','probabilities'));c(list(id=d$id[i],applicable=app-1L,positiveMembers=sum(w[app]>0)),pp)});list(task=task,classes=classes,members=members,predictions=preds,outOfBag=scored(oob,d,task,classes))}\nboost<-function(a){if(option(a,'task','regression')!='regression')stop('regression boosting only');d<-normrows(a$rows,'regression');eligible<-d$weight>0&!is.na(d$y);W<-sum(d$weight[eligible]);if(!W)stop('positive eligible training');eta<-num(option(a,'learningRate','1/2'));stages<-option(a,'stages',3);if(is.null(stages)||stages!=floor(stages)||stages<0||stages>8||eta<0||eta>1)stop('supported rate/stages');initial<-if('initial'%in%names(a))num(a$initial)else sum(d$weight[eligible]*d$y[eligible])/W;train<-matrix(initial,nrow(d),stages+1L);query<-matrix(initial,nrow(a$queries),stages+1L);losses<-fits<-list();for(stage in 0:stages){sse<-sum(d$weight[eligible]*(d$y[eligible]-train[eligible,stage+1L])^2);losses[[stage+1L]]<-list(stage=stage,rawWeightedSSE=sse,MSE=sse/W,meanHalfSquaredLoss=sse/(2*W));if(stage==stages)break;residual<-d;residual$y<-d$y-train[,stage+1L];tree<-fit(residual,a,'regression',character());h<-vapply(seq_len(nrow(d)),function(i)predict_one(tree,d[i,,drop=FALSE])$prediction,0);qh<-vapply(seq_len(nrow(a$queries)),function(i)predict_one(tree,a$queries[i,,drop=FALSE])$prediction,0);stageRows<-lapply(seq_len(nrow(d)),function(i)list(id=d$id[i],before=train[i,stage+1L],residual=residual$y[i],negativeCoordinateDerivative=d$weight[i]*residual$y[i]/W,fit=h[i],addition=eta*h[i],after=train[i,stage+1L]+eta*h[i]));train[,stage+2L]<-train[,stage+1L]+eta*h;query[,stage+2L]<-query[,stage+1L]+eta*qh;norm<-sum(d$weight[eligible]*h[eligible]^2);fits[[stage+1L]]<-list(stage=stage+1L,tree=tree,rows=stageRows,queryFits=qh,norm=norm,predictedSSEDecrease=eta*(2-eta)*norm)};list(task='regression',initial=initial,learningRate=eta,stages=stages,training=train,queries=query,fits=fits,losses=losses,predictions=lapply(seq_len(nrow(a$queries)),function(i)list(id=a$queries$id[i],prediction=query[i,stages+1L],probabilities=numeric(),vote=NA_character_,prob=NA_character_)))}\nfixed_schedules<-function(ids,p,seed){state<-seed;choose<-function(n){limit<-floor(4294967296/n)*n;repeat{state<<-(1664525*state+1013904223)%%4294967296;if(state<limit)return(as.integer(state%%n))}};draws<-schedules<-list();for(member in 1:4){draws[[member]]<-vapply(seq_along(ids),function(i)ids[choose(length(ids))+1L],'');schedule<-setNames(vector('list',7),c('','L','R','LL','LR','RL','RR'));for(path in names(schedule)){order<-seq_len(p)-1L;if(p>1)for(j in seq(p-1L,1L)){k<-choose(j+1L);temp<-order[j+1L];order[j+1L]<-order[k+1L];order[k+1L]<-temp};schedule[[match(path,names(schedule))]]<-sort(order[seq_len(max(1L,floor(sqrt(p))))])};schedules[[member]]<-schedule};list(draws=draws,schedules=schedules)}\nread_sources<-function(src){read<-function(name)read.csv(file.path(src,name),check.names=FALSE,colClasses='character',na.strings=character(),fileEncoding='UTF-8-BOM');raw<-read('actual320-country-four-indicators-original-2020-2024.csv');country<-do.call(rbind,lapply(sort(unique(raw$countryISO3)),function(code)do.call(rbind,lapply(2020:2024,function(year){keys<-c('NY.GDP.PCAP.KD','NY.GDP.MKTP.KD.ZG','FP.CPI.TOTL.ZG','SP.DYN.LE00.IN');v<-vapply(keys,function(k)as.numeric(raw$originalValueToken[raw$countryISO3==code&raw$date==as.character(year)&raw$indicatorID==k]),0);data.frame(id=paste0(code,':',year),sourceRow=paste0(code,':',year),originalID=code,year=year,x0=v[1]/10000,x1=v[2],x2=v[3],y=v[4],weight=1,role=if(anyNA(v))'excluded'else if(year==2024)'outer-test'else'train')}))));raw<-read('actual3613-NLS-original52-fields-and-selection.csv');i<-seq_len(nrow(raw));x0<-suppressWarnings(as.numeric(raw$ed76));x1<-suppressWarnings(as.numeric(raw$age76));y<-suppressWarnings(as.numeric(raw$wage76))/100;person<-data.frame(id=paste0('person:',i),sourceRow=as.character(i),originalID=raw$id,x0=x0,x1=x1,y=y,weight=1,role=ifelse(is.na(x0)|is.na(x1)|is.na(y),'excluded',ifelse(i%%5==0,'outer-test','train')));raw<-read('actual3150-churn-original14-fields-and-selection.csv');i<-seq_len(nrow(raw));company<-data.frame(id=paste0('customer:',i),sourceRow=as.character(i),originalID='',x0=as.numeric(raw[['Call  Failure']]),x1=as.numeric(raw[['Subscription  Length']]),x2=as.numeric(raw[['Charge  Amount']]),y=raw$Churn,weight=1,role=ifelse(i%%5==0,'outer-test','train'));models<-list();for(index in 1:3){kind<-c('country','person','company')[index];d<-list(country,person,company)[[index]];task<-if(kind=='company')'classification'else'regression';s<-fixed_schedules(d$id[d$role=='train'],if(kind=='person')2L else 3L,20261102+7919*(index-1L));models[[kind]]<-list(records=d,task=task,classes=if(task=='classification')c('0','1')else character(),draws=s$draws,schedules=s$schedules,minLeaf=c(4L,50L,30L)[index])};models}\nrealdata<-function(models,kind,options=list()){if(is.null(options)||!is.list(options))stop('options object');m<-models[[kind]];d<-m$records;train<-d[d$role=='train',,drop=FALSE];test<-d[d$role=='outer-test',,drop=FALSE];method<-option(options,'method','forest');depth<-option(options,'maxDepth',2);count<-option(options,'memberCount',3);if(!method%in%c('bagging','forest','boost'))stop('known method');a<-list(rows=train,queries=test,task=m$task,classes=m$classes,maxDepth=depth,minLeaf=option(options,'minLeaf',m$minLeaf),minLeafWeight=0,minGain=0,missingRoute='best',learningRate=option(options,'learningRate','1/2'),stages=option(options,'stages',3));if(method=='boost')result<-boost(a)else{a$bootstrapDraws<-m$draws[seq_len(count)];a$nodeFeatures<-lapply(m$schedules[seq_len(count)],function(s)s[nchar(names(s))<depth]);result<-ensemble(a,method=='forest')};outer<-scored(result$predictions,normrows(test,m$task),m$task,m$classes);st<-stat(normrows(train,m$task),m$task,m$classes);constant<-list(prediction=st$pred,probabilities=st$p,vote=st$pred,prob=st$pred);baseline<-scored(lapply(test$id,function(id)c(list(id=id),constant)),normrows(test,m$task),m$task,m$classes);list(kind=kind,method=method,settings=a,train=train,test=test,result=result,outer=outer,baseline=baseline)}\nAPI<-\"realdata\"\nINPUT<-list(kind=\"country\")\n\nrun_fixed<-function(api,a,out,src){\n r<-if(api=='variance')variance(a)else if(api=='aggregate')aggregate(a)else if(api%in%c('bagging','forest'))ensemble(a,api=='forest')else if(api=='boost')boost(a)else realdata(read_sources(src),a$kind)\n dir.create(out,recursive=TRUE,showWarnings=FALSE);summary<-list();points<-list();add<-function(x,y,s){if(!is.null(y)&&!is.na(y))points[[length(points)+1L]]<<-data.frame(x=x,y=as.numeric(y),series=s)}\n if(api=='variance'){summary<-r[c('B','varianceOfMean')];add(r$B,r$varianceOfMean,'Specified finite-B variance');xl<-'Number of members B';yl<-'Variance, stipulated units squared';title<-'Declared covariance model, not fitted trees'\n }else if(api=='aggregate'){p<-r$predictions[[1]];summary<-list(selectedPrediction=p$prediction);classification<-identical(a$task,'classification');if(classification){summary<-c(summary,list(voteLabel=p$vote,probabilityLabel=p$prob,meanProbability1=p$probabilities[2]));add(1,p$probabilities[2],'Mean probability of class 1');add(2,p$votes[2],'Label-vote share of class 1');xl<-'Aggregation (1=probability, 2=vote)';yl<-'Probability or vote share'}else{for(i in seq_along(a$members))add(i,num(a$members[[i]]$predictions$value[1]),'Member prediction');add(3,p$prediction,'Weighted mean');xl<-'Member 1, member 2, aggregate 3';yl<-'Prediction, assumed units'};title<-'Votes and probabilities are distinct objects'\n }else if(api%in%c('bagging','forest')){summary<-list(queryPrediction=r$predictions[[1]]$prediction,OOB.scoreable=r$outOfBag$eligibleRows,OOB.meanLoss=r$outOfBag$meanLoss);for(i in seq_len(nrow(a$rows)))add(i,a$rows$y[i],'Observed training outcome');for(i in seq_along(r$outOfBag$rows))add(i,r$outOfBag$rows[[i]]$prediction,'OOB prediction, when defined');xl<-'Original training ID order';yl<-'Outcome, assumed units';title<-'Repeated draws and ID-level OOB membership'\n }else if(api=='boost'){summary<-list(initial=r$initial,finalMSE=r$losses[[length(r$losses)]]$MSE,stages=r$stages);for(v in r$losses)add(v$stage,v$MSE,'Training MSE');xl<-'Boosting stage (0=initial)';yl<-'Weighted MSE, outcome units squared';title<-'Training descent does not certify held-out gain'\n }else{summary<-list(outer.scoreable=r$outer$eligibleRows,outer.meanLoss=r$outer$meanLoss,baseline.meanLoss=r$baseline$meanLoss,OOB.scoreable=r$result$outOfBag$eligibleRows,OOB.meanLoss=r$result$outOfBag$meanLoss);for(i in seq_along(r$outer$rows)){p<-r$outer$rows[[i]];add(i,as.numeric(p$actual),'Observed outcome');add(i,if(a$kind=='company')p$probabilities[2]else p$prediction,if(a$kind=='company')'Forest probability of class 1'else'Forest prediction')};xl<-'Outer-test source order, not a time path';yl<-if(a$kind=='company')'Churn label / probability'else if(a$kind=='country')'Period life expectancy, years'else'Nominal 1976 USD per hour';title<-'Fixed forest; outer labels did not fit the trees'}\n display<-function(v)if(is.null(v)||is.na(v))'undefined'else sprintf('%.9f',as.numeric(v));write.csv(data.frame(metric=names(summary),value=vapply(summary,display,'')),file.path(out,'summary.csv'),row.names=FALSE);pp<-do.call(rbind,points);write.csv(pp,file.path(out,'plot-points.csv'),row.names=FALSE);dput(r,file.path(out,'full-result.Rtext'));svg(file.path(out,'plot.svg'),width=5.6,height=4.6,pointsize=14);par(mar=c(5.8,5.8,5.3,1.2),mgp=c(3.7,1,0));xr<-range(pp$x);yr<-range(pp$y);if(diff(xr)==0)xr<-xr+c(-.5,.5);if(diff(yr)==0)yr<-yr+c(-.5,.5);plot(xr,yr,type='n',xlab=xl,ylab=yl,cex.lab=.78,axes=FALSE);axis(1,at=pretty(xr,3));axis(2,at=pretty(yr,4),las=1,cex.axis=.82);box();grid(col='#dddddd');cols<-c('#355c72','#a55336','#507956','#78568b');ss<-unique(pp$series);for(i in seq_along(ss)){v<-pp[pp$series==ss[i],];points(v$x,v$y,pch=16,cex=if(nrow(v)>100).35 else .85,col=adjustcolor(cols[i],if(nrow(v)>100).5 else 1))};legend('topleft',legend=ss,col=cols[seq_along(ss)],lty=0,pch=16,cex=.65,bty='n',inset=c(0,-.32),xpd=NA);mtext(title,side=3,line=3.9,cex=.6);dev.off();cat(paste(names(summary),vapply(summary,display,''),sep='=',collapse=', '),'\\n')\n}\nargs<-commandArgs(trailingOnly=TRUE)\ntryCatch(run_fixed(API,INPUT,if(length(args))args[1]else'fixed-results',if(length(args)>1)args[2]else'ml09-sources'),error=function(e){cat('Rejected declared input: ',conditionMessage(e),'\\n',file=stderr());quit(status=2)})\n",
        "inputFiles": [
          {
            "file": "ml09-sources/actual3150-churn-original14-fields-and-selection.csv",
            "sha256": "6f5b9e98ce1896582629646dd4cfe7b1aca78c491f7e412a93840534e8b49f48"
          },
          {
            "file": "ml09-sources/actual320-country-four-indicators-original-2020-2024.csv",
            "sha256": "cedc2f748ce14601c76b254c35aea7ef0ee5f06f2928506c225efcbfb1f69390"
          },
          {
            "file": "ml09-sources/actual3613-NLS-original52-fields-and-selection.csv",
            "sha256": "7ae23478bdfee0922157264655e1a2081999f11686773478835bce315068e0df"
          }
        ],
        "input": {
          "kind": "country"
        },
        "returnCode": 0,
        "expectedFailure": false,
        "stdout": "outer.scoreable=16.000000000, outer.meanLoss=24.041092299, baseline.meanLoss=26.854082008, OOB.scoreable=0.000000000, OOB.meanLoss=undefined \n",
        "stderr": "During startup - Warning messages:\n1: Setting LC_COLLATE=C.UTF-8 failed \n2: Setting LC_CTYPE=C.UTF-8 failed \n3: Setting LC_MONETARY=C.UTF-8 failed \n4: Setting LC_TIME=C.UTF-8 failed \n",
        "summary": {
          "outer.scoreable": "16.000000000",
          "outer.meanLoss": "24.041092299",
          "baseline.meanLoss": "26.854082008",
          "OOB.scoreable": "0.000000000",
          "OOB.meanLoss": "undefined"
        },
        "plotPoints": [
          {
            "x": "1",
            "y": "83.0512195121951",
            "series": "Observed outcome"
          },
          {
            "x": "1",
            "y": "78.0610887430039",
            "series": "Forest prediction"
          },
          {
            "x": "2",
            "y": "76.023",
            "series": "Observed outcome"
          },
          {
            "x": "2",
            "y": "78.0610887430039",
            "series": "Forest prediction"
          },
          {
            "x": "3",
            "y": "82.1080487804878",
            "series": "Observed outcome"
          },
          {
            "x": "3",
            "y": "78.0610887430039",
            "series": "Forest prediction"
          },
          {
            "x": "4",
            "y": "78.017",
            "series": "Observed outcome"
          },
          {
            "x": "4",
            "y": "80.1417743902439",
            "series": "Forest prediction"
          },
          {
            "x": "5",
            "y": "80.7926829268293",
            "series": "Observed outcome"
          },
          {
            "x": "5",
            "y": "78.0610887430039",
            "series": "Forest prediction"
          },
          {
            "x": "6",
            "y": "82.9804878048781",
            "series": "Observed outcome"
          },
          {
            "x": "6",
            "y": "78.0610887430039",
            "series": "Forest prediction"
          },
          {
            "x": "7",
            "y": "81.3868536585366",
            "series": "Observed outcome"
          },
          {
            "x": "7",
            "y": "78.0610887430039",
            "series": "Forest prediction"
          },
          {
            "x": "8",
            "y": "71.288",
            "series": "Observed outcome"
          },
          {
            "x": "8",
            "y": "78.5206888550135",
            "series": "Forest prediction"
          },
          {
            "x": "9",
            "y": "72.235",
            "series": "Observed outcome"
          },
          {
            "x": "9",
            "y": "73.4772002371274",
            "series": "Forest prediction"
          },
          {
            "x": "10",
            "y": "84.0363414634146",
            "series": "Observed outcome"
          },
          {
            "x": "10",
            "y": "78.0610887430039",
            "series": "Forest prediction"
          },
          {
            "x": "11",
            "y": "83.6292682926829",
            "series": "Observed outcome"
          },
          {
            "x": "11",
            "y": "78.0610887430039",
            "series": "Forest prediction"
          },
          {
            "x": "12",
            "y": "75.264",
            "series": "Observed outcome"
          },
          {
            "x": "12",
            "y": "78.0610887430039",
            "series": "Forest prediction"
          },
          {
            "x": "13",
            "y": "83.3463414634146",
            "series": "Observed outcome"
          },
          {
            "x": "13",
            "y": "78.5206888550135",
            "series": "Forest prediction"
          },
          {
            "x": "14",
            "y": "78.890243902439",
            "series": "Observed outcome"
          },
          {
            "x": "14",
            "y": "78.0610887430039",
            "series": "Forest prediction"
          },
          {
            "x": "15",
            "y": "74.736",
            "series": "Observed outcome"
          },
          {
            "x": "15",
            "y": "73.4772002371274",
            "series": "Forest prediction"
          },
          {
            "x": "16",
            "y": "66.312",
            "series": "Observed outcome"
          },
          {
            "x": "16",
            "y": "78.0610887430039",
            "series": "Forest prediction"
          }
        ],
        "plotFile": "ml09-fixed-results/realdata-country-r/plot.svg",
        "plotSHA256": "842c82d17e8b762bfad9db1a387a6ec345c17e05fb91b09c03876bfaf079a398",
        "files": [
          {
            "file": "ml09-fixed-results/realdata-country-r/full-result.Rtext",
            "sha256": "1075575a47fd145d6212c7785e13c9516c3945a10c63b32e6591e1ead4fd4ad5"
          },
          {
            "file": "ml09-fixed-results/realdata-country-r/plot-points.csv",
            "sha256": "e5f0b1fab79bc3826844def2b1096f61b893840caacbf5f68492b41cfdab08c2"
          },
          {
            "file": "ml09-fixed-results/realdata-country-r/plot.svg",
            "sha256": "842c82d17e8b762bfad9db1a387a6ec345c17e05fb91b09c03876bfaf079a398"
          },
          {
            "file": "ml09-fixed-results/realdata-country-r/summary.csv",
            "sha256": "63e70939474d147e0629aaf0f053698b1f05dae055e4f033926c37b6e48defbb"
          }
        ],
        "scope": "Actually executed self-contained fixed example; current web controls execute separately. Python Fraction and finite-precision base R. Author gate, not independent peer."
      },
      "person": {
        "api": "realdata",
        "variant": "person",
        "language": "r",
        "codeFile": "ml09-code/realdata-person.R",
        "codeSHA256": "ee9c240c39311f273c4aebb5375a27b0185dc1ba973226eed15e752144a288a0",
        "codeText": "# ML09 base-R reproduction from native original-field CSVs.\n# Rscript ml09-public-analysis.R ml09-sources results-r\n# Separately written vectorized direct-centered squared/Gini losses.\n# No Python/JS/model-contract/stored-answer/derived-result reader or package.\n# Numeric arithmetic is binary64:1e-12 relative tie tolerance stabilizes exact\n# source ties,but does not certify tiny margins/underflow like Fraction JS/Python.\n# Data-frame rows use x0,x1,...,y,weight; original IDs remain attached to draws.\noptions(stringsAsFactors=FALSE,digits=17)\nnum<-function(v){if(is.null(v)||length(v)!=1||is.na(v))stop('numeric parameter required, not explicit NULL');p<-strsplit(as.character(v),'/',fixed=TRUE)[[1]];z<-if(length(p)==2)as.numeric(p[1])/as.numeric(p[2])else as.numeric(v);if(!is.finite(z))stop('finite numeric parameter');z}\noption<-function(a,k,default){if(k%in%names(a))a[[k]]else default}\nnormrows<-function(d,task){if(!'weight'%in%names(d))d$weight<-1;if(!'id'%in%names(d))d$id<-as.character(seq_len(nrow(d))-1);d$weight<-as.numeric(d$weight);if(anyNA(d$weight)||any(d$weight<0))stop('nonnegative weights');if(task=='regression')d$y<-as.numeric(d$y)else d$y<-as.character(d$y);d}\nstat<-function(d,task,classes){W<-sum(d$weight);mu<-if(task=='regression'&&W)sum(d$weight*d$y)/W else NA_real_;p<-if(task=='classification'&&W)vapply(classes,function(c)sum(d$weight[d$y==c])/W,0)else numeric();risk<-if(task=='regression'&&W)sum(d$weight*(d$y-mu)^2)else W*sum(p*(1-p));list(n=nrow(d),w=W,mu=mu,p=unname(p),risk=risk,pred=if(task=='regression')mu else if(W)classes[which.max(p)]else NA_character_)}\nfit<-function(d,a,task,classes,schedule=NULL){d<-d[d$weight>0&!is.na(d$y),,drop=FALSE];if(!nrow(d))stop('positive observed training');W<-sum(d$weight);depth<-option(a,'maxDepth',2);minimum<-option(a,'minLeaf',1);minmass<-num(option(a,'minLeafWeight',0));mingain<-num(option(a,'minGain',0));route<-option(a,'missingRoute','best');features<-grep('^x[0-9]+$',names(d),value=TRUE)\n build<-function(rr,level,path){st<-stat(rr,task,classes);node<-list(rows=rr,st=st,split=NULL,left=NULL,right=NULL,path=path);if(level==depth)return(node);best<-NULL;allowed<-if(is.null(schedule))seq_along(features)-1L else schedule[[match(path,names(schedule))]]\n  for(j in seq_along(features)-1L){if(!j%in%allowed)next;v<-rr[[features[j+1L]]];values<-sort(unique(v[!is.na(v)]));candidates<-list()\n   if(length(values)>1)for(k in seq_len(length(values)-1L)){threshold<-(values[k]+values[k+1L])/2;missing<-is.na(v);left<-!missing&v<=threshold;right<-!missing&v>threshold;directions<-if(route!='best')route else if(any(missing))c('left','right')else if(sum(left)>=sum(right))'left'else'right';for(direction in directions)candidates[[length(candidates)+1L]]<-list(kind='threshold',threshold=threshold,missingRoute=direction,left=if(direction=='left')left|missing else left,right=if(direction=='right')right|missing else right)}\n   if(anyNA(v)&&any(!is.na(v)))candidates[[length(candidates)+1L]]<-list(kind='missing-only',threshold=NA_real_,missingRoute='left',left=is.na(v),right=!is.na(v))\n   for(candidate in candidates){l<-rr[candidate$left,,drop=FALSE];r<-rr[candidate$right,,drop=FALSE];ls<-stat(l,task,classes);rs<-stat(r,task,classes);if(min(ls$n,rs$n)<minimum||min(ls$w,rs$w)<minmass||min(ls$w,rs$w)<=0)next;gain<-(st$risk-ls$risk-rs$risk)/W;tol<-1e-12*max(1,abs(gain),if(is.null(best))0 else abs(best$gain));if(is.null(best)||gain>best$gain+tol)best<-c(candidate,list(feature=j,gain=gain,l=l,r=r))}\n  }\n  if(!is.null(best)&&best$gain>max(mingain,1e-12)){node$split<-best;node$left<-build(best$l,level+1L,paste0(path,'L'));node$right<-build(best$r,level+1L,paste0(path,'R'))};node\n };build(d,0L,'')\n}\npredict_one<-function(tree,row){n<-tree;while(!is.null(n$split)){s<-n$split;v<-as.numeric(row[[paste0('x',s$feature)]]);left<-if(s$kind=='missing-only')is.na(v)else if(is.na(v))s$missingRoute=='left'else v<=s$threshold;n<-if(left)n$left else n$right};list(prediction=n$st$pred,probabilities=n$st$p)}\ncombine<-function(pp,w,task,classes,mode='probabilities'){W<-sum(w);if(!length(pp)||!W)return(list(prediction=if(task=='regression')NA_real_ else NA_character_,probabilities=numeric(),vote=NA_character_,prob=NA_character_));if(task=='regression')return(list(prediction=sum(vapply(pp,function(p)p$prediction,0)*w)/W,probabilities=numeric(),vote=NA_character_,prob=NA_character_));votes<-vapply(classes,function(c)sum(w[vapply(pp,function(p)p$prediction==c,FALSE)])/W,0);probs<-vapply(seq_along(classes),function(j)sum(vapply(pp,function(p)p$probabilities[j],0)*w)/W,0);vote<-classes[which.max(votes)];prob<-classes[which.max(probs)];list(prediction=if(mode=='votes')vote else prob,probabilities=unname(probs),vote=vote,prob=prob,votes=unname(votes))}\nvariance<-function(a){B<-num(a$B);v<-num(a$marginalVariance);rho<-num(option(a,'rho',0));if(B<1||B!=floor(B)||v<0)stop('integer B/nonnegative variance');if(B>1&&v>0&&(rho< -1/(B-1)||rho>1))stop('PSD correlation');list(B=B,marginalVariance=v,correlationApplicable=B>1&&v>0,varianceOfMean=if(B==1)v else v*(1+(B-1)*rho)/B)}\naggregate<-function(a){task<-option(a,'task','regression');classes<-option(a,'classes',character());w<-vapply(option(a,'memberWeights',as.list(rep(1,length(a$members)))),num,0);if(any(w<0)||sum(w)<=0)stop('positive member mass');ids<-a$members[[1]]$predictions$id;pp<-lapply(ids,function(id){members<-lapply(a$members,function(m){r<-m$predictions[match(id,m$predictions$id),,drop=FALSE];if(task=='regression')list(prediction=num(r$value),probabilities=numeric())else list(prediction=as.character(r$label),probabilities=as.numeric(r[paste0('p',seq_along(classes)-1L)]))});c(list(id=id),combine(members,w,task,classes,option(a,'aggregation','probabilities')))});list(task=task,classes=classes,predictions=pp)}\nscored<-function(preds,d,task,classes){W<-loss<-absolute<-errors<-voteerrors<-0;count<-0L;out<-lapply(seq_len(nrow(d)),function(i){r<-d[i,,drop=FALSE];p<-preds[[i]];ok<-!is.na(p$prediction)&&!is.na(r$y)&&r$weight>0;value<-NA_real_;if(ok){count<<-count+1L;W<<-W+r$weight;if(task=='regression'){e<-r$y-p$prediction;value<-e*e;absolute<<-absolute+r$weight*abs(e)}else{value<-sum((p$probabilities-as.numeric(classes==r$y))^2);errors<<-errors+r$weight*(p$prediction!=r$y);voteerrors<<-voteerrors+r$weight*(p$vote!=r$y)};loss<<-loss+r$weight*value};c(p,list(actual=r$y,weight=r$weight,scoreEligible=ok,loss=value))});list(rows=out,eligibleRows=count,weight=W,totalLoss=loss,meanLoss=if(W)loss/W else NA_real_,MAE=if(W&&task=='regression')absolute/W else NA_real_,errorRate=if(W&&task=='classification')errors/W else NA_real_,labelVoteErrorRate=if(W&&task=='classification')voteerrors/W else NA_real_)}\nensemble<-function(a,forest=FALSE){task<-option(a,'task','regression');classes<-option(a,'classes',character());d<-normrows(a$rows,task);w<-vapply(option(a,'memberWeights',as.list(rep(1,length(a$bootstrapDraws)))),num,0);if(any(w<0)||sum(w)<=0)stop('positive member mass');members<-lapply(seq_along(a$bootstrapDraws),function(i){draw<-a$bootstrapDraws[[i]];indices<-match(draw,d$id);if(anyNA(indices))stop('unknown draw source');tree<-fit(d[indices,,drop=FALSE],a,task,classes,if(forest)a$nodeFeatures[[i]]else NULL);list(tree=tree,draw=draw,inbag=unique(draw),weight=w[i])});queries<-a$queries;preds<-lapply(seq_len(nrow(queries)),function(i)c(list(id=queries$id[i]),combine(lapply(members,function(m)predict_one(m$tree,queries[i,,drop=FALSE])),w,task,classes,option(a,'aggregation','probabilities'))));oob<-lapply(seq_len(nrow(d)),function(i){app<-which(!vapply(members,function(m)d$id[i]%in%m$inbag,FALSE));pp<-combine(lapply(app,function(j)predict_one(members[[j]]$tree,d[i,,drop=FALSE])),w[app],task,classes,option(a,'aggregation','probabilities'));c(list(id=d$id[i],applicable=app-1L,positiveMembers=sum(w[app]>0)),pp)});list(task=task,classes=classes,members=members,predictions=preds,outOfBag=scored(oob,d,task,classes))}\nboost<-function(a){if(option(a,'task','regression')!='regression')stop('regression boosting only');d<-normrows(a$rows,'regression');eligible<-d$weight>0&!is.na(d$y);W<-sum(d$weight[eligible]);if(!W)stop('positive eligible training');eta<-num(option(a,'learningRate','1/2'));stages<-option(a,'stages',3);if(is.null(stages)||stages!=floor(stages)||stages<0||stages>8||eta<0||eta>1)stop('supported rate/stages');initial<-if('initial'%in%names(a))num(a$initial)else sum(d$weight[eligible]*d$y[eligible])/W;train<-matrix(initial,nrow(d),stages+1L);query<-matrix(initial,nrow(a$queries),stages+1L);losses<-fits<-list();for(stage in 0:stages){sse<-sum(d$weight[eligible]*(d$y[eligible]-train[eligible,stage+1L])^2);losses[[stage+1L]]<-list(stage=stage,rawWeightedSSE=sse,MSE=sse/W,meanHalfSquaredLoss=sse/(2*W));if(stage==stages)break;residual<-d;residual$y<-d$y-train[,stage+1L];tree<-fit(residual,a,'regression',character());h<-vapply(seq_len(nrow(d)),function(i)predict_one(tree,d[i,,drop=FALSE])$prediction,0);qh<-vapply(seq_len(nrow(a$queries)),function(i)predict_one(tree,a$queries[i,,drop=FALSE])$prediction,0);stageRows<-lapply(seq_len(nrow(d)),function(i)list(id=d$id[i],before=train[i,stage+1L],residual=residual$y[i],negativeCoordinateDerivative=d$weight[i]*residual$y[i]/W,fit=h[i],addition=eta*h[i],after=train[i,stage+1L]+eta*h[i]));train[,stage+2L]<-train[,stage+1L]+eta*h;query[,stage+2L]<-query[,stage+1L]+eta*qh;norm<-sum(d$weight[eligible]*h[eligible]^2);fits[[stage+1L]]<-list(stage=stage+1L,tree=tree,rows=stageRows,queryFits=qh,norm=norm,predictedSSEDecrease=eta*(2-eta)*norm)};list(task='regression',initial=initial,learningRate=eta,stages=stages,training=train,queries=query,fits=fits,losses=losses,predictions=lapply(seq_len(nrow(a$queries)),function(i)list(id=a$queries$id[i],prediction=query[i,stages+1L],probabilities=numeric(),vote=NA_character_,prob=NA_character_)))}\nfixed_schedules<-function(ids,p,seed){state<-seed;choose<-function(n){limit<-floor(4294967296/n)*n;repeat{state<<-(1664525*state+1013904223)%%4294967296;if(state<limit)return(as.integer(state%%n))}};draws<-schedules<-list();for(member in 1:4){draws[[member]]<-vapply(seq_along(ids),function(i)ids[choose(length(ids))+1L],'');schedule<-setNames(vector('list',7),c('','L','R','LL','LR','RL','RR'));for(path in names(schedule)){order<-seq_len(p)-1L;if(p>1)for(j in seq(p-1L,1L)){k<-choose(j+1L);temp<-order[j+1L];order[j+1L]<-order[k+1L];order[k+1L]<-temp};schedule[[match(path,names(schedule))]]<-sort(order[seq_len(max(1L,floor(sqrt(p))))])};schedules[[member]]<-schedule};list(draws=draws,schedules=schedules)}\nread_sources<-function(src){read<-function(name)read.csv(file.path(src,name),check.names=FALSE,colClasses='character',na.strings=character(),fileEncoding='UTF-8-BOM');raw<-read('actual320-country-four-indicators-original-2020-2024.csv');country<-do.call(rbind,lapply(sort(unique(raw$countryISO3)),function(code)do.call(rbind,lapply(2020:2024,function(year){keys<-c('NY.GDP.PCAP.KD','NY.GDP.MKTP.KD.ZG','FP.CPI.TOTL.ZG','SP.DYN.LE00.IN');v<-vapply(keys,function(k)as.numeric(raw$originalValueToken[raw$countryISO3==code&raw$date==as.character(year)&raw$indicatorID==k]),0);data.frame(id=paste0(code,':',year),sourceRow=paste0(code,':',year),originalID=code,year=year,x0=v[1]/10000,x1=v[2],x2=v[3],y=v[4],weight=1,role=if(anyNA(v))'excluded'else if(year==2024)'outer-test'else'train')}))));raw<-read('actual3613-NLS-original52-fields-and-selection.csv');i<-seq_len(nrow(raw));x0<-suppressWarnings(as.numeric(raw$ed76));x1<-suppressWarnings(as.numeric(raw$age76));y<-suppressWarnings(as.numeric(raw$wage76))/100;person<-data.frame(id=paste0('person:',i),sourceRow=as.character(i),originalID=raw$id,x0=x0,x1=x1,y=y,weight=1,role=ifelse(is.na(x0)|is.na(x1)|is.na(y),'excluded',ifelse(i%%5==0,'outer-test','train')));raw<-read('actual3150-churn-original14-fields-and-selection.csv');i<-seq_len(nrow(raw));company<-data.frame(id=paste0('customer:',i),sourceRow=as.character(i),originalID='',x0=as.numeric(raw[['Call  Failure']]),x1=as.numeric(raw[['Subscription  Length']]),x2=as.numeric(raw[['Charge  Amount']]),y=raw$Churn,weight=1,role=ifelse(i%%5==0,'outer-test','train'));models<-list();for(index in 1:3){kind<-c('country','person','company')[index];d<-list(country,person,company)[[index]];task<-if(kind=='company')'classification'else'regression';s<-fixed_schedules(d$id[d$role=='train'],if(kind=='person')2L else 3L,20261102+7919*(index-1L));models[[kind]]<-list(records=d,task=task,classes=if(task=='classification')c('0','1')else character(),draws=s$draws,schedules=s$schedules,minLeaf=c(4L,50L,30L)[index])};models}\nrealdata<-function(models,kind,options=list()){if(is.null(options)||!is.list(options))stop('options object');m<-models[[kind]];d<-m$records;train<-d[d$role=='train',,drop=FALSE];test<-d[d$role=='outer-test',,drop=FALSE];method<-option(options,'method','forest');depth<-option(options,'maxDepth',2);count<-option(options,'memberCount',3);if(!method%in%c('bagging','forest','boost'))stop('known method');a<-list(rows=train,queries=test,task=m$task,classes=m$classes,maxDepth=depth,minLeaf=option(options,'minLeaf',m$minLeaf),minLeafWeight=0,minGain=0,missingRoute='best',learningRate=option(options,'learningRate','1/2'),stages=option(options,'stages',3));if(method=='boost')result<-boost(a)else{a$bootstrapDraws<-m$draws[seq_len(count)];a$nodeFeatures<-lapply(m$schedules[seq_len(count)],function(s)s[nchar(names(s))<depth]);result<-ensemble(a,method=='forest')};outer<-scored(result$predictions,normrows(test,m$task),m$task,m$classes);st<-stat(normrows(train,m$task),m$task,m$classes);constant<-list(prediction=st$pred,probabilities=st$p,vote=st$pred,prob=st$pred);baseline<-scored(lapply(test$id,function(id)c(list(id=id),constant)),normrows(test,m$task),m$task,m$classes);list(kind=kind,method=method,settings=a,train=train,test=test,result=result,outer=outer,baseline=baseline)}\nAPI<-\"realdata\"\nINPUT<-list(kind=\"person\")\n\nrun_fixed<-function(api,a,out,src){\n r<-if(api=='variance')variance(a)else if(api=='aggregate')aggregate(a)else if(api%in%c('bagging','forest'))ensemble(a,api=='forest')else if(api=='boost')boost(a)else realdata(read_sources(src),a$kind)\n dir.create(out,recursive=TRUE,showWarnings=FALSE);summary<-list();points<-list();add<-function(x,y,s){if(!is.null(y)&&!is.na(y))points[[length(points)+1L]]<<-data.frame(x=x,y=as.numeric(y),series=s)}\n if(api=='variance'){summary<-r[c('B','varianceOfMean')];add(r$B,r$varianceOfMean,'Specified finite-B variance');xl<-'Number of members B';yl<-'Variance, stipulated units squared';title<-'Declared covariance model, not fitted trees'\n }else if(api=='aggregate'){p<-r$predictions[[1]];summary<-list(selectedPrediction=p$prediction);classification<-identical(a$task,'classification');if(classification){summary<-c(summary,list(voteLabel=p$vote,probabilityLabel=p$prob,meanProbability1=p$probabilities[2]));add(1,p$probabilities[2],'Mean probability of class 1');add(2,p$votes[2],'Label-vote share of class 1');xl<-'Aggregation (1=probability, 2=vote)';yl<-'Probability or vote share'}else{for(i in seq_along(a$members))add(i,num(a$members[[i]]$predictions$value[1]),'Member prediction');add(3,p$prediction,'Weighted mean');xl<-'Member 1, member 2, aggregate 3';yl<-'Prediction, assumed units'};title<-'Votes and probabilities are distinct objects'\n }else if(api%in%c('bagging','forest')){summary<-list(queryPrediction=r$predictions[[1]]$prediction,OOB.scoreable=r$outOfBag$eligibleRows,OOB.meanLoss=r$outOfBag$meanLoss);for(i in seq_len(nrow(a$rows)))add(i,a$rows$y[i],'Observed training outcome');for(i in seq_along(r$outOfBag$rows))add(i,r$outOfBag$rows[[i]]$prediction,'OOB prediction, when defined');xl<-'Original training ID order';yl<-'Outcome, assumed units';title<-'Repeated draws and ID-level OOB membership'\n }else if(api=='boost'){summary<-list(initial=r$initial,finalMSE=r$losses[[length(r$losses)]]$MSE,stages=r$stages);for(v in r$losses)add(v$stage,v$MSE,'Training MSE');xl<-'Boosting stage (0=initial)';yl<-'Weighted MSE, outcome units squared';title<-'Training descent does not certify held-out gain'\n }else{summary<-list(outer.scoreable=r$outer$eligibleRows,outer.meanLoss=r$outer$meanLoss,baseline.meanLoss=r$baseline$meanLoss,OOB.scoreable=r$result$outOfBag$eligibleRows,OOB.meanLoss=r$result$outOfBag$meanLoss);for(i in seq_along(r$outer$rows)){p<-r$outer$rows[[i]];add(i,as.numeric(p$actual),'Observed outcome');add(i,if(a$kind=='company')p$probabilities[2]else p$prediction,if(a$kind=='company')'Forest probability of class 1'else'Forest prediction')};xl<-'Outer-test source order, not a time path';yl<-if(a$kind=='company')'Churn label / probability'else if(a$kind=='country')'Period life expectancy, years'else'Nominal 1976 USD per hour';title<-'Fixed forest; outer labels did not fit the trees'}\n display<-function(v)if(is.null(v)||is.na(v))'undefined'else sprintf('%.9f',as.numeric(v));write.csv(data.frame(metric=names(summary),value=vapply(summary,display,'')),file.path(out,'summary.csv'),row.names=FALSE);pp<-do.call(rbind,points);write.csv(pp,file.path(out,'plot-points.csv'),row.names=FALSE);dput(r,file.path(out,'full-result.Rtext'));svg(file.path(out,'plot.svg'),width=5.6,height=4.6,pointsize=14);par(mar=c(5.8,5.8,5.3,1.2),mgp=c(3.7,1,0));xr<-range(pp$x);yr<-range(pp$y);if(diff(xr)==0)xr<-xr+c(-.5,.5);if(diff(yr)==0)yr<-yr+c(-.5,.5);plot(xr,yr,type='n',xlab=xl,ylab=yl,cex.lab=.78,axes=FALSE);axis(1,at=pretty(xr,3));axis(2,at=pretty(yr,4),las=1,cex.axis=.82);box();grid(col='#dddddd');cols<-c('#355c72','#a55336','#507956','#78568b');ss<-unique(pp$series);for(i in seq_along(ss)){v<-pp[pp$series==ss[i],];points(v$x,v$y,pch=16,cex=if(nrow(v)>100).35 else .85,col=adjustcolor(cols[i],if(nrow(v)>100).5 else 1))};legend('topleft',legend=ss,col=cols[seq_along(ss)],lty=0,pch=16,cex=.65,bty='n',inset=c(0,-.32),xpd=NA);mtext(title,side=3,line=3.9,cex=.6);dev.off();cat(paste(names(summary),vapply(summary,display,''),sep='=',collapse=', '),'\\n')\n}\nargs<-commandArgs(trailingOnly=TRUE)\ntryCatch(run_fixed(API,INPUT,if(length(args))args[1]else'fixed-results',if(length(args)>1)args[2]else'ml09-sources'),error=function(e){cat('Rejected declared input: ',conditionMessage(e),'\\n',file=stderr());quit(status=2)})\n",
        "code": "# ML09 base-R reproduction from native original-field CSVs.\n# Rscript ml09-public-analysis.R ml09-sources results-r\n# Separately written vectorized direct-centered squared/Gini losses.\n# No Python/JS/model-contract/stored-answer/derived-result reader or package.\n# Numeric arithmetic is binary64:1e-12 relative tie tolerance stabilizes exact\n# source ties,but does not certify tiny margins/underflow like Fraction JS/Python.\n# Data-frame rows use x0,x1,...,y,weight; original IDs remain attached to draws.\noptions(stringsAsFactors=FALSE,digits=17)\nnum<-function(v){if(is.null(v)||length(v)!=1||is.na(v))stop('numeric parameter required, not explicit NULL');p<-strsplit(as.character(v),'/',fixed=TRUE)[[1]];z<-if(length(p)==2)as.numeric(p[1])/as.numeric(p[2])else as.numeric(v);if(!is.finite(z))stop('finite numeric parameter');z}\noption<-function(a,k,default){if(k%in%names(a))a[[k]]else default}\nnormrows<-function(d,task){if(!'weight'%in%names(d))d$weight<-1;if(!'id'%in%names(d))d$id<-as.character(seq_len(nrow(d))-1);d$weight<-as.numeric(d$weight);if(anyNA(d$weight)||any(d$weight<0))stop('nonnegative weights');if(task=='regression')d$y<-as.numeric(d$y)else d$y<-as.character(d$y);d}\nstat<-function(d,task,classes){W<-sum(d$weight);mu<-if(task=='regression'&&W)sum(d$weight*d$y)/W else NA_real_;p<-if(task=='classification'&&W)vapply(classes,function(c)sum(d$weight[d$y==c])/W,0)else numeric();risk<-if(task=='regression'&&W)sum(d$weight*(d$y-mu)^2)else W*sum(p*(1-p));list(n=nrow(d),w=W,mu=mu,p=unname(p),risk=risk,pred=if(task=='regression')mu else if(W)classes[which.max(p)]else NA_character_)}\nfit<-function(d,a,task,classes,schedule=NULL){d<-d[d$weight>0&!is.na(d$y),,drop=FALSE];if(!nrow(d))stop('positive observed training');W<-sum(d$weight);depth<-option(a,'maxDepth',2);minimum<-option(a,'minLeaf',1);minmass<-num(option(a,'minLeafWeight',0));mingain<-num(option(a,'minGain',0));route<-option(a,'missingRoute','best');features<-grep('^x[0-9]+$',names(d),value=TRUE)\n build<-function(rr,level,path){st<-stat(rr,task,classes);node<-list(rows=rr,st=st,split=NULL,left=NULL,right=NULL,path=path);if(level==depth)return(node);best<-NULL;allowed<-if(is.null(schedule))seq_along(features)-1L else schedule[[match(path,names(schedule))]]\n  for(j in seq_along(features)-1L){if(!j%in%allowed)next;v<-rr[[features[j+1L]]];values<-sort(unique(v[!is.na(v)]));candidates<-list()\n   if(length(values)>1)for(k in seq_len(length(values)-1L)){threshold<-(values[k]+values[k+1L])/2;missing<-is.na(v);left<-!missing&v<=threshold;right<-!missing&v>threshold;directions<-if(route!='best')route else if(any(missing))c('left','right')else if(sum(left)>=sum(right))'left'else'right';for(direction in directions)candidates[[length(candidates)+1L]]<-list(kind='threshold',threshold=threshold,missingRoute=direction,left=if(direction=='left')left|missing else left,right=if(direction=='right')right|missing else right)}\n   if(anyNA(v)&&any(!is.na(v)))candidates[[length(candidates)+1L]]<-list(kind='missing-only',threshold=NA_real_,missingRoute='left',left=is.na(v),right=!is.na(v))\n   for(candidate in candidates){l<-rr[candidate$left,,drop=FALSE];r<-rr[candidate$right,,drop=FALSE];ls<-stat(l,task,classes);rs<-stat(r,task,classes);if(min(ls$n,rs$n)<minimum||min(ls$w,rs$w)<minmass||min(ls$w,rs$w)<=0)next;gain<-(st$risk-ls$risk-rs$risk)/W;tol<-1e-12*max(1,abs(gain),if(is.null(best))0 else abs(best$gain));if(is.null(best)||gain>best$gain+tol)best<-c(candidate,list(feature=j,gain=gain,l=l,r=r))}\n  }\n  if(!is.null(best)&&best$gain>max(mingain,1e-12)){node$split<-best;node$left<-build(best$l,level+1L,paste0(path,'L'));node$right<-build(best$r,level+1L,paste0(path,'R'))};node\n };build(d,0L,'')\n}\npredict_one<-function(tree,row){n<-tree;while(!is.null(n$split)){s<-n$split;v<-as.numeric(row[[paste0('x',s$feature)]]);left<-if(s$kind=='missing-only')is.na(v)else if(is.na(v))s$missingRoute=='left'else v<=s$threshold;n<-if(left)n$left else n$right};list(prediction=n$st$pred,probabilities=n$st$p)}\ncombine<-function(pp,w,task,classes,mode='probabilities'){W<-sum(w);if(!length(pp)||!W)return(list(prediction=if(task=='regression')NA_real_ else NA_character_,probabilities=numeric(),vote=NA_character_,prob=NA_character_));if(task=='regression')return(list(prediction=sum(vapply(pp,function(p)p$prediction,0)*w)/W,probabilities=numeric(),vote=NA_character_,prob=NA_character_));votes<-vapply(classes,function(c)sum(w[vapply(pp,function(p)p$prediction==c,FALSE)])/W,0);probs<-vapply(seq_along(classes),function(j)sum(vapply(pp,function(p)p$probabilities[j],0)*w)/W,0);vote<-classes[which.max(votes)];prob<-classes[which.max(probs)];list(prediction=if(mode=='votes')vote else prob,probabilities=unname(probs),vote=vote,prob=prob,votes=unname(votes))}\nvariance<-function(a){B<-num(a$B);v<-num(a$marginalVariance);rho<-num(option(a,'rho',0));if(B<1||B!=floor(B)||v<0)stop('integer B/nonnegative variance');if(B>1&&v>0&&(rho< -1/(B-1)||rho>1))stop('PSD correlation');list(B=B,marginalVariance=v,correlationApplicable=B>1&&v>0,varianceOfMean=if(B==1)v else v*(1+(B-1)*rho)/B)}\naggregate<-function(a){task<-option(a,'task','regression');classes<-option(a,'classes',character());w<-vapply(option(a,'memberWeights',as.list(rep(1,length(a$members)))),num,0);if(any(w<0)||sum(w)<=0)stop('positive member mass');ids<-a$members[[1]]$predictions$id;pp<-lapply(ids,function(id){members<-lapply(a$members,function(m){r<-m$predictions[match(id,m$predictions$id),,drop=FALSE];if(task=='regression')list(prediction=num(r$value),probabilities=numeric())else list(prediction=as.character(r$label),probabilities=as.numeric(r[paste0('p',seq_along(classes)-1L)]))});c(list(id=id),combine(members,w,task,classes,option(a,'aggregation','probabilities')))});list(task=task,classes=classes,predictions=pp)}\nscored<-function(preds,d,task,classes){W<-loss<-absolute<-errors<-voteerrors<-0;count<-0L;out<-lapply(seq_len(nrow(d)),function(i){r<-d[i,,drop=FALSE];p<-preds[[i]];ok<-!is.na(p$prediction)&&!is.na(r$y)&&r$weight>0;value<-NA_real_;if(ok){count<<-count+1L;W<<-W+r$weight;if(task=='regression'){e<-r$y-p$prediction;value<-e*e;absolute<<-absolute+r$weight*abs(e)}else{value<-sum((p$probabilities-as.numeric(classes==r$y))^2);errors<<-errors+r$weight*(p$prediction!=r$y);voteerrors<<-voteerrors+r$weight*(p$vote!=r$y)};loss<<-loss+r$weight*value};c(p,list(actual=r$y,weight=r$weight,scoreEligible=ok,loss=value))});list(rows=out,eligibleRows=count,weight=W,totalLoss=loss,meanLoss=if(W)loss/W else NA_real_,MAE=if(W&&task=='regression')absolute/W else NA_real_,errorRate=if(W&&task=='classification')errors/W else NA_real_,labelVoteErrorRate=if(W&&task=='classification')voteerrors/W else NA_real_)}\nensemble<-function(a,forest=FALSE){task<-option(a,'task','regression');classes<-option(a,'classes',character());d<-normrows(a$rows,task);w<-vapply(option(a,'memberWeights',as.list(rep(1,length(a$bootstrapDraws)))),num,0);if(any(w<0)||sum(w)<=0)stop('positive member mass');members<-lapply(seq_along(a$bootstrapDraws),function(i){draw<-a$bootstrapDraws[[i]];indices<-match(draw,d$id);if(anyNA(indices))stop('unknown draw source');tree<-fit(d[indices,,drop=FALSE],a,task,classes,if(forest)a$nodeFeatures[[i]]else NULL);list(tree=tree,draw=draw,inbag=unique(draw),weight=w[i])});queries<-a$queries;preds<-lapply(seq_len(nrow(queries)),function(i)c(list(id=queries$id[i]),combine(lapply(members,function(m)predict_one(m$tree,queries[i,,drop=FALSE])),w,task,classes,option(a,'aggregation','probabilities'))));oob<-lapply(seq_len(nrow(d)),function(i){app<-which(!vapply(members,function(m)d$id[i]%in%m$inbag,FALSE));pp<-combine(lapply(app,function(j)predict_one(members[[j]]$tree,d[i,,drop=FALSE])),w[app],task,classes,option(a,'aggregation','probabilities'));c(list(id=d$id[i],applicable=app-1L,positiveMembers=sum(w[app]>0)),pp)});list(task=task,classes=classes,members=members,predictions=preds,outOfBag=scored(oob,d,task,classes))}\nboost<-function(a){if(option(a,'task','regression')!='regression')stop('regression boosting only');d<-normrows(a$rows,'regression');eligible<-d$weight>0&!is.na(d$y);W<-sum(d$weight[eligible]);if(!W)stop('positive eligible training');eta<-num(option(a,'learningRate','1/2'));stages<-option(a,'stages',3);if(is.null(stages)||stages!=floor(stages)||stages<0||stages>8||eta<0||eta>1)stop('supported rate/stages');initial<-if('initial'%in%names(a))num(a$initial)else sum(d$weight[eligible]*d$y[eligible])/W;train<-matrix(initial,nrow(d),stages+1L);query<-matrix(initial,nrow(a$queries),stages+1L);losses<-fits<-list();for(stage in 0:stages){sse<-sum(d$weight[eligible]*(d$y[eligible]-train[eligible,stage+1L])^2);losses[[stage+1L]]<-list(stage=stage,rawWeightedSSE=sse,MSE=sse/W,meanHalfSquaredLoss=sse/(2*W));if(stage==stages)break;residual<-d;residual$y<-d$y-train[,stage+1L];tree<-fit(residual,a,'regression',character());h<-vapply(seq_len(nrow(d)),function(i)predict_one(tree,d[i,,drop=FALSE])$prediction,0);qh<-vapply(seq_len(nrow(a$queries)),function(i)predict_one(tree,a$queries[i,,drop=FALSE])$prediction,0);stageRows<-lapply(seq_len(nrow(d)),function(i)list(id=d$id[i],before=train[i,stage+1L],residual=residual$y[i],negativeCoordinateDerivative=d$weight[i]*residual$y[i]/W,fit=h[i],addition=eta*h[i],after=train[i,stage+1L]+eta*h[i]));train[,stage+2L]<-train[,stage+1L]+eta*h;query[,stage+2L]<-query[,stage+1L]+eta*qh;norm<-sum(d$weight[eligible]*h[eligible]^2);fits[[stage+1L]]<-list(stage=stage+1L,tree=tree,rows=stageRows,queryFits=qh,norm=norm,predictedSSEDecrease=eta*(2-eta)*norm)};list(task='regression',initial=initial,learningRate=eta,stages=stages,training=train,queries=query,fits=fits,losses=losses,predictions=lapply(seq_len(nrow(a$queries)),function(i)list(id=a$queries$id[i],prediction=query[i,stages+1L],probabilities=numeric(),vote=NA_character_,prob=NA_character_)))}\nfixed_schedules<-function(ids,p,seed){state<-seed;choose<-function(n){limit<-floor(4294967296/n)*n;repeat{state<<-(1664525*state+1013904223)%%4294967296;if(state<limit)return(as.integer(state%%n))}};draws<-schedules<-list();for(member in 1:4){draws[[member]]<-vapply(seq_along(ids),function(i)ids[choose(length(ids))+1L],'');schedule<-setNames(vector('list',7),c('','L','R','LL','LR','RL','RR'));for(path in names(schedule)){order<-seq_len(p)-1L;if(p>1)for(j in seq(p-1L,1L)){k<-choose(j+1L);temp<-order[j+1L];order[j+1L]<-order[k+1L];order[k+1L]<-temp};schedule[[match(path,names(schedule))]]<-sort(order[seq_len(max(1L,floor(sqrt(p))))])};schedules[[member]]<-schedule};list(draws=draws,schedules=schedules)}\nread_sources<-function(src){read<-function(name)read.csv(file.path(src,name),check.names=FALSE,colClasses='character',na.strings=character(),fileEncoding='UTF-8-BOM');raw<-read('actual320-country-four-indicators-original-2020-2024.csv');country<-do.call(rbind,lapply(sort(unique(raw$countryISO3)),function(code)do.call(rbind,lapply(2020:2024,function(year){keys<-c('NY.GDP.PCAP.KD','NY.GDP.MKTP.KD.ZG','FP.CPI.TOTL.ZG','SP.DYN.LE00.IN');v<-vapply(keys,function(k)as.numeric(raw$originalValueToken[raw$countryISO3==code&raw$date==as.character(year)&raw$indicatorID==k]),0);data.frame(id=paste0(code,':',year),sourceRow=paste0(code,':',year),originalID=code,year=year,x0=v[1]/10000,x1=v[2],x2=v[3],y=v[4],weight=1,role=if(anyNA(v))'excluded'else if(year==2024)'outer-test'else'train')}))));raw<-read('actual3613-NLS-original52-fields-and-selection.csv');i<-seq_len(nrow(raw));x0<-suppressWarnings(as.numeric(raw$ed76));x1<-suppressWarnings(as.numeric(raw$age76));y<-suppressWarnings(as.numeric(raw$wage76))/100;person<-data.frame(id=paste0('person:',i),sourceRow=as.character(i),originalID=raw$id,x0=x0,x1=x1,y=y,weight=1,role=ifelse(is.na(x0)|is.na(x1)|is.na(y),'excluded',ifelse(i%%5==0,'outer-test','train')));raw<-read('actual3150-churn-original14-fields-and-selection.csv');i<-seq_len(nrow(raw));company<-data.frame(id=paste0('customer:',i),sourceRow=as.character(i),originalID='',x0=as.numeric(raw[['Call  Failure']]),x1=as.numeric(raw[['Subscription  Length']]),x2=as.numeric(raw[['Charge  Amount']]),y=raw$Churn,weight=1,role=ifelse(i%%5==0,'outer-test','train'));models<-list();for(index in 1:3){kind<-c('country','person','company')[index];d<-list(country,person,company)[[index]];task<-if(kind=='company')'classification'else'regression';s<-fixed_schedules(d$id[d$role=='train'],if(kind=='person')2L else 3L,20261102+7919*(index-1L));models[[kind]]<-list(records=d,task=task,classes=if(task=='classification')c('0','1')else character(),draws=s$draws,schedules=s$schedules,minLeaf=c(4L,50L,30L)[index])};models}\nrealdata<-function(models,kind,options=list()){if(is.null(options)||!is.list(options))stop('options object');m<-models[[kind]];d<-m$records;train<-d[d$role=='train',,drop=FALSE];test<-d[d$role=='outer-test',,drop=FALSE];method<-option(options,'method','forest');depth<-option(options,'maxDepth',2);count<-option(options,'memberCount',3);if(!method%in%c('bagging','forest','boost'))stop('known method');a<-list(rows=train,queries=test,task=m$task,classes=m$classes,maxDepth=depth,minLeaf=option(options,'minLeaf',m$minLeaf),minLeafWeight=0,minGain=0,missingRoute='best',learningRate=option(options,'learningRate','1/2'),stages=option(options,'stages',3));if(method=='boost')result<-boost(a)else{a$bootstrapDraws<-m$draws[seq_len(count)];a$nodeFeatures<-lapply(m$schedules[seq_len(count)],function(s)s[nchar(names(s))<depth]);result<-ensemble(a,method=='forest')};outer<-scored(result$predictions,normrows(test,m$task),m$task,m$classes);st<-stat(normrows(train,m$task),m$task,m$classes);constant<-list(prediction=st$pred,probabilities=st$p,vote=st$pred,prob=st$pred);baseline<-scored(lapply(test$id,function(id)c(list(id=id),constant)),normrows(test,m$task),m$task,m$classes);list(kind=kind,method=method,settings=a,train=train,test=test,result=result,outer=outer,baseline=baseline)}\nAPI<-\"realdata\"\nINPUT<-list(kind=\"person\")\n\nrun_fixed<-function(api,a,out,src){\n r<-if(api=='variance')variance(a)else if(api=='aggregate')aggregate(a)else if(api%in%c('bagging','forest'))ensemble(a,api=='forest')else if(api=='boost')boost(a)else realdata(read_sources(src),a$kind)\n dir.create(out,recursive=TRUE,showWarnings=FALSE);summary<-list();points<-list();add<-function(x,y,s){if(!is.null(y)&&!is.na(y))points[[length(points)+1L]]<<-data.frame(x=x,y=as.numeric(y),series=s)}\n if(api=='variance'){summary<-r[c('B','varianceOfMean')];add(r$B,r$varianceOfMean,'Specified finite-B variance');xl<-'Number of members B';yl<-'Variance, stipulated units squared';title<-'Declared covariance model, not fitted trees'\n }else if(api=='aggregate'){p<-r$predictions[[1]];summary<-list(selectedPrediction=p$prediction);classification<-identical(a$task,'classification');if(classification){summary<-c(summary,list(voteLabel=p$vote,probabilityLabel=p$prob,meanProbability1=p$probabilities[2]));add(1,p$probabilities[2],'Mean probability of class 1');add(2,p$votes[2],'Label-vote share of class 1');xl<-'Aggregation (1=probability, 2=vote)';yl<-'Probability or vote share'}else{for(i in seq_along(a$members))add(i,num(a$members[[i]]$predictions$value[1]),'Member prediction');add(3,p$prediction,'Weighted mean');xl<-'Member 1, member 2, aggregate 3';yl<-'Prediction, assumed units'};title<-'Votes and probabilities are distinct objects'\n }else if(api%in%c('bagging','forest')){summary<-list(queryPrediction=r$predictions[[1]]$prediction,OOB.scoreable=r$outOfBag$eligibleRows,OOB.meanLoss=r$outOfBag$meanLoss);for(i in seq_len(nrow(a$rows)))add(i,a$rows$y[i],'Observed training outcome');for(i in seq_along(r$outOfBag$rows))add(i,r$outOfBag$rows[[i]]$prediction,'OOB prediction, when defined');xl<-'Original training ID order';yl<-'Outcome, assumed units';title<-'Repeated draws and ID-level OOB membership'\n }else if(api=='boost'){summary<-list(initial=r$initial,finalMSE=r$losses[[length(r$losses)]]$MSE,stages=r$stages);for(v in r$losses)add(v$stage,v$MSE,'Training MSE');xl<-'Boosting stage (0=initial)';yl<-'Weighted MSE, outcome units squared';title<-'Training descent does not certify held-out gain'\n }else{summary<-list(outer.scoreable=r$outer$eligibleRows,outer.meanLoss=r$outer$meanLoss,baseline.meanLoss=r$baseline$meanLoss,OOB.scoreable=r$result$outOfBag$eligibleRows,OOB.meanLoss=r$result$outOfBag$meanLoss);for(i in seq_along(r$outer$rows)){p<-r$outer$rows[[i]];add(i,as.numeric(p$actual),'Observed outcome');add(i,if(a$kind=='company')p$probabilities[2]else p$prediction,if(a$kind=='company')'Forest probability of class 1'else'Forest prediction')};xl<-'Outer-test source order, not a time path';yl<-if(a$kind=='company')'Churn label / probability'else if(a$kind=='country')'Period life expectancy, years'else'Nominal 1976 USD per hour';title<-'Fixed forest; outer labels did not fit the trees'}\n display<-function(v)if(is.null(v)||is.na(v))'undefined'else sprintf('%.9f',as.numeric(v));write.csv(data.frame(metric=names(summary),value=vapply(summary,display,'')),file.path(out,'summary.csv'),row.names=FALSE);pp<-do.call(rbind,points);write.csv(pp,file.path(out,'plot-points.csv'),row.names=FALSE);dput(r,file.path(out,'full-result.Rtext'));svg(file.path(out,'plot.svg'),width=5.6,height=4.6,pointsize=14);par(mar=c(5.8,5.8,5.3,1.2),mgp=c(3.7,1,0));xr<-range(pp$x);yr<-range(pp$y);if(diff(xr)==0)xr<-xr+c(-.5,.5);if(diff(yr)==0)yr<-yr+c(-.5,.5);plot(xr,yr,type='n',xlab=xl,ylab=yl,cex.lab=.78,axes=FALSE);axis(1,at=pretty(xr,3));axis(2,at=pretty(yr,4),las=1,cex.axis=.82);box();grid(col='#dddddd');cols<-c('#355c72','#a55336','#507956','#78568b');ss<-unique(pp$series);for(i in seq_along(ss)){v<-pp[pp$series==ss[i],];points(v$x,v$y,pch=16,cex=if(nrow(v)>100).35 else .85,col=adjustcolor(cols[i],if(nrow(v)>100).5 else 1))};legend('topleft',legend=ss,col=cols[seq_along(ss)],lty=0,pch=16,cex=.65,bty='n',inset=c(0,-.32),xpd=NA);mtext(title,side=3,line=3.9,cex=.6);dev.off();cat(paste(names(summary),vapply(summary,display,''),sep='=',collapse=', '),'\\n')\n}\nargs<-commandArgs(trailingOnly=TRUE)\ntryCatch(run_fixed(API,INPUT,if(length(args))args[1]else'fixed-results',if(length(args)>1)args[2]else'ml09-sources'),error=function(e){cat('Rejected declared input: ',conditionMessage(e),'\\n',file=stderr());quit(status=2)})\n",
        "inputFiles": [
          {
            "file": "ml09-sources/actual3150-churn-original14-fields-and-selection.csv",
            "sha256": "6f5b9e98ce1896582629646dd4cfe7b1aca78c491f7e412a93840534e8b49f48"
          },
          {
            "file": "ml09-sources/actual320-country-four-indicators-original-2020-2024.csv",
            "sha256": "cedc2f748ce14601c76b254c35aea7ef0ee5f06f2928506c225efcbfb1f69390"
          },
          {
            "file": "ml09-sources/actual3613-NLS-original52-fields-and-selection.csv",
            "sha256": "7ae23478bdfee0922157264655e1a2081999f11686773478835bce315068e0df"
          }
        ],
        "input": {
          "kind": "person"
        },
        "returnCode": 0,
        "expectedFailure": false,
        "stdout": "outer.scoreable=604.000000000, outer.meanLoss=5.748800284, baseline.meanLoss=6.409952708, OOB.scoreable=1791.000000000, OOB.meanLoss=6.446577514 \n",
        "stderr": "During startup - Warning messages:\n1: Setting LC_COLLATE=C.UTF-8 failed \n2: Setting LC_CTYPE=C.UTF-8 failed \n3: Setting LC_MONETARY=C.UTF-8 failed \n4: Setting LC_TIME=C.UTF-8 failed \n",
        "summary": {
          "outer.scoreable": "604.000000000",
          "outer.meanLoss": "5.748800284",
          "baseline.meanLoss": "6.409952708",
          "OOB.scoreable": "1791.000000000",
          "OOB.meanLoss": "6.446577514"
        },
        "plotPoints": [
          {
            "x": "1",
            "y": "7.29",
            "series": "Observed outcome"
          },
          {
            "x": "1",
            "y": "6.08487256879198",
            "series": "Forest prediction"
          },
          {
            "x": "2",
            "y": "5.15",
            "series": "Observed outcome"
          },
          {
            "x": "2",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "3",
            "y": "8.94",
            "series": "Observed outcome"
          },
          {
            "x": "3",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "4",
            "y": "5.75",
            "series": "Observed outcome"
          },
          {
            "x": "4",
            "y": "4.65384944083265",
            "series": "Forest prediction"
          },
          {
            "x": "5",
            "y": "7.26",
            "series": "Observed outcome"
          },
          {
            "x": "5",
            "y": "6.08487256879198",
            "series": "Forest prediction"
          },
          {
            "x": "6",
            "y": "3",
            "series": "Observed outcome"
          },
          {
            "x": "6",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "7",
            "y": "2.08",
            "series": "Observed outcome"
          },
          {
            "x": "7",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "8",
            "y": "9.62",
            "series": "Observed outcome"
          },
          {
            "x": "8",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "9",
            "y": "3.24",
            "series": "Observed outcome"
          },
          {
            "x": "9",
            "y": "4.86192429463382",
            "series": "Forest prediction"
          },
          {
            "x": "10",
            "y": "6.5",
            "series": "Observed outcome"
          },
          {
            "x": "10",
            "y": "5.62604883275605",
            "series": "Forest prediction"
          },
          {
            "x": "11",
            "y": "6.21",
            "series": "Observed outcome"
          },
          {
            "x": "11",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "12",
            "y": "5.38",
            "series": "Observed outcome"
          },
          {
            "x": "12",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "13",
            "y": "5.92",
            "series": "Observed outcome"
          },
          {
            "x": "13",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "14",
            "y": "5.38",
            "series": "Observed outcome"
          },
          {
            "x": "14",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "15",
            "y": "7",
            "series": "Observed outcome"
          },
          {
            "x": "15",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "16",
            "y": "2.83",
            "series": "Observed outcome"
          },
          {
            "x": "16",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "17",
            "y": "5.5",
            "series": "Observed outcome"
          },
          {
            "x": "17",
            "y": "5.21006007672534",
            "series": "Forest prediction"
          },
          {
            "x": "18",
            "y": "6.25",
            "series": "Observed outcome"
          },
          {
            "x": "18",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "19",
            "y": "8.65",
            "series": "Observed outcome"
          },
          {
            "x": "19",
            "y": "5.66888381276127",
            "series": "Forest prediction"
          },
          {
            "x": "20",
            "y": "6.25",
            "series": "Observed outcome"
          },
          {
            "x": "20",
            "y": "7.75766205450734",
            "series": "Forest prediction"
          },
          {
            "x": "21",
            "y": "7.69",
            "series": "Observed outcome"
          },
          {
            "x": "21",
            "y": "7.75766205450734",
            "series": "Forest prediction"
          },
          {
            "x": "22",
            "y": "11.54",
            "series": "Observed outcome"
          },
          {
            "x": "22",
            "y": "6.08487256879198",
            "series": "Forest prediction"
          },
          {
            "x": "23",
            "y": "6.82",
            "series": "Observed outcome"
          },
          {
            "x": "23",
            "y": "7.75766205450734",
            "series": "Forest prediction"
          },
          {
            "x": "24",
            "y": "10.05",
            "series": "Observed outcome"
          },
          {
            "x": "24",
            "y": "7.75766205450734",
            "series": "Forest prediction"
          },
          {
            "x": "25",
            "y": "5.29",
            "series": "Observed outcome"
          },
          {
            "x": "25",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "26",
            "y": "6.25",
            "series": "Observed outcome"
          },
          {
            "x": "26",
            "y": "6.08487256879198",
            "series": "Forest prediction"
          },
          {
            "x": "27",
            "y": "9.62",
            "series": "Observed outcome"
          },
          {
            "x": "27",
            "y": "7.75766205450734",
            "series": "Forest prediction"
          },
          {
            "x": "28",
            "y": "2",
            "series": "Observed outcome"
          },
          {
            "x": "28",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "29",
            "y": "7.93",
            "series": "Observed outcome"
          },
          {
            "x": "29",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "30",
            "y": "6.94",
            "series": "Observed outcome"
          },
          {
            "x": "30",
            "y": "5.66888381276127",
            "series": "Forest prediction"
          },
          {
            "x": "31",
            "y": "14",
            "series": "Observed outcome"
          },
          {
            "x": "31",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "32",
            "y": "3.85",
            "series": "Observed outcome"
          },
          {
            "x": "32",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "33",
            "y": "2.85",
            "series": "Observed outcome"
          },
          {
            "x": "33",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "34",
            "y": "7.95",
            "series": "Observed outcome"
          },
          {
            "x": "34",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "35",
            "y": "6.73",
            "series": "Observed outcome"
          },
          {
            "x": "35",
            "y": "6.08487256879198",
            "series": "Forest prediction"
          },
          {
            "x": "36",
            "y": "5.76",
            "series": "Observed outcome"
          },
          {
            "x": "36",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "37",
            "y": "5.14",
            "series": "Observed outcome"
          },
          {
            "x": "37",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "38",
            "y": "2.89",
            "series": "Observed outcome"
          },
          {
            "x": "38",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "39",
            "y": "9.95",
            "series": "Observed outcome"
          },
          {
            "x": "39",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "40",
            "y": "6.86",
            "series": "Observed outcome"
          },
          {
            "x": "40",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "41",
            "y": "7.69",
            "series": "Observed outcome"
          },
          {
            "x": "41",
            "y": "5.66888381276127",
            "series": "Forest prediction"
          },
          {
            "x": "42",
            "y": "5.05",
            "series": "Observed outcome"
          },
          {
            "x": "42",
            "y": "6.08487256879198",
            "series": "Forest prediction"
          },
          {
            "x": "43",
            "y": "11.54",
            "series": "Observed outcome"
          },
          {
            "x": "43",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "44",
            "y": "2",
            "series": "Observed outcome"
          },
          {
            "x": "44",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "45",
            "y": "5.88",
            "series": "Observed outcome"
          },
          {
            "x": "45",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "46",
            "y": "9.29",
            "series": "Observed outcome"
          },
          {
            "x": "46",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "47",
            "y": "3.89",
            "series": "Observed outcome"
          },
          {
            "x": "47",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "48",
            "y": "2.02",
            "series": "Observed outcome"
          },
          {
            "x": "48",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "49",
            "y": "4.81",
            "series": "Observed outcome"
          },
          {
            "x": "49",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "50",
            "y": "4.76",
            "series": "Observed outcome"
          },
          {
            "x": "50",
            "y": "4.86192429463382",
            "series": "Forest prediction"
          },
          {
            "x": "51",
            "y": "7",
            "series": "Observed outcome"
          },
          {
            "x": "51",
            "y": "5.21006007672534",
            "series": "Forest prediction"
          },
          {
            "x": "52",
            "y": "7.6",
            "series": "Observed outcome"
          },
          {
            "x": "52",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "53",
            "y": "4",
            "series": "Observed outcome"
          },
          {
            "x": "53",
            "y": "5.62604883275605",
            "series": "Forest prediction"
          },
          {
            "x": "54",
            "y": "5.77",
            "series": "Observed outcome"
          },
          {
            "x": "54",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "55",
            "y": "7.7",
            "series": "Observed outcome"
          },
          {
            "x": "55",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "56",
            "y": "6.15",
            "series": "Observed outcome"
          },
          {
            "x": "56",
            "y": "6.08487256879198",
            "series": "Forest prediction"
          },
          {
            "x": "57",
            "y": "7.5",
            "series": "Observed outcome"
          },
          {
            "x": "57",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "58",
            "y": "3.13",
            "series": "Observed outcome"
          },
          {
            "x": "58",
            "y": "4.65384944083265",
            "series": "Forest prediction"
          },
          {
            "x": "59",
            "y": "7.5",
            "series": "Observed outcome"
          },
          {
            "x": "59",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "60",
            "y": "5.91",
            "series": "Observed outcome"
          },
          {
            "x": "60",
            "y": "5.66888381276127",
            "series": "Forest prediction"
          },
          {
            "x": "61",
            "y": "4.88",
            "series": "Observed outcome"
          },
          {
            "x": "61",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "62",
            "y": "9.86",
            "series": "Observed outcome"
          },
          {
            "x": "62",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "63",
            "y": "6.15",
            "series": "Observed outcome"
          },
          {
            "x": "63",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "64",
            "y": "4.62",
            "series": "Observed outcome"
          },
          {
            "x": "64",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "65",
            "y": "6.4",
            "series": "Observed outcome"
          },
          {
            "x": "65",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "66",
            "y": "10.1",
            "series": "Observed outcome"
          },
          {
            "x": "66",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "67",
            "y": "13.87",
            "series": "Observed outcome"
          },
          {
            "x": "67",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "68",
            "y": "4.81",
            "series": "Observed outcome"
          },
          {
            "x": "68",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "69",
            "y": "5.79",
            "series": "Observed outcome"
          },
          {
            "x": "69",
            "y": "6.08487256879198",
            "series": "Forest prediction"
          },
          {
            "x": "70",
            "y": "9.62",
            "series": "Observed outcome"
          },
          {
            "x": "70",
            "y": "6.08487256879198",
            "series": "Forest prediction"
          },
          {
            "x": "71",
            "y": "4.8",
            "series": "Observed outcome"
          },
          {
            "x": "71",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "72",
            "y": "4.17",
            "series": "Observed outcome"
          },
          {
            "x": "72",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "73",
            "y": "7.21",
            "series": "Observed outcome"
          },
          {
            "x": "73",
            "y": "6.08487256879198",
            "series": "Forest prediction"
          },
          {
            "x": "74",
            "y": "10.58",
            "series": "Observed outcome"
          },
          {
            "x": "74",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "75",
            "y": "9.62",
            "series": "Observed outcome"
          },
          {
            "x": "75",
            "y": "7.75766205450734",
            "series": "Forest prediction"
          },
          {
            "x": "76",
            "y": "10.1",
            "series": "Observed outcome"
          },
          {
            "x": "76",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "77",
            "y": "5",
            "series": "Observed outcome"
          },
          {
            "x": "77",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "78",
            "y": "14.42",
            "series": "Observed outcome"
          },
          {
            "x": "78",
            "y": "5.66888381276127",
            "series": "Forest prediction"
          },
          {
            "x": "79",
            "y": "5.38",
            "series": "Observed outcome"
          },
          {
            "x": "79",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "80",
            "y": "5.61",
            "series": "Observed outcome"
          },
          {
            "x": "80",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "81",
            "y": "4.37",
            "series": "Observed outcome"
          },
          {
            "x": "81",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "82",
            "y": "7.5",
            "series": "Observed outcome"
          },
          {
            "x": "82",
            "y": "6.08487256879198",
            "series": "Forest prediction"
          },
          {
            "x": "83",
            "y": "5.55",
            "series": "Observed outcome"
          },
          {
            "x": "83",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "84",
            "y": "7.45",
            "series": "Observed outcome"
          },
          {
            "x": "84",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "85",
            "y": "8.65",
            "series": "Observed outcome"
          },
          {
            "x": "85",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "86",
            "y": "5.29",
            "series": "Observed outcome"
          },
          {
            "x": "86",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "87",
            "y": "8.89",
            "series": "Observed outcome"
          },
          {
            "x": "87",
            "y": "7.75766205450734",
            "series": "Forest prediction"
          },
          {
            "x": "88",
            "y": "7.75",
            "series": "Observed outcome"
          },
          {
            "x": "88",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "89",
            "y": "3.33",
            "series": "Observed outcome"
          },
          {
            "x": "89",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "90",
            "y": "11.54",
            "series": "Observed outcome"
          },
          {
            "x": "90",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "91",
            "y": "9.89",
            "series": "Observed outcome"
          },
          {
            "x": "91",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "92",
            "y": "5.71",
            "series": "Observed outcome"
          },
          {
            "x": "92",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "93",
            "y": "3.88",
            "series": "Observed outcome"
          },
          {
            "x": "93",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "94",
            "y": "10.44",
            "series": "Observed outcome"
          },
          {
            "x": "94",
            "y": "6.08487256879198",
            "series": "Forest prediction"
          },
          {
            "x": "95",
            "y": "5.77",
            "series": "Observed outcome"
          },
          {
            "x": "95",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "96",
            "y": "6.25",
            "series": "Observed outcome"
          },
          {
            "x": "96",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "97",
            "y": "5.24",
            "series": "Observed outcome"
          },
          {
            "x": "97",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "98",
            "y": "4.26",
            "series": "Observed outcome"
          },
          {
            "x": "98",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "99",
            "y": "3.25",
            "series": "Observed outcome"
          },
          {
            "x": "99",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "100",
            "y": "4.88",
            "series": "Observed outcome"
          },
          {
            "x": "100",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "101",
            "y": "3.75",
            "series": "Observed outcome"
          },
          {
            "x": "101",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "102",
            "y": "6.38",
            "series": "Observed outcome"
          },
          {
            "x": "102",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "103",
            "y": "6.29",
            "series": "Observed outcome"
          },
          {
            "x": "103",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "104",
            "y": "6.39",
            "series": "Observed outcome"
          },
          {
            "x": "104",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "105",
            "y": "10",
            "series": "Observed outcome"
          },
          {
            "x": "105",
            "y": "5.62604883275605",
            "series": "Forest prediction"
          },
          {
            "x": "106",
            "y": "1.59",
            "series": "Observed outcome"
          },
          {
            "x": "106",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "107",
            "y": "5.53",
            "series": "Observed outcome"
          },
          {
            "x": "107",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "108",
            "y": "14.42",
            "series": "Observed outcome"
          },
          {
            "x": "108",
            "y": "6.08487256879198",
            "series": "Forest prediction"
          },
          {
            "x": "109",
            "y": "8.89",
            "series": "Observed outcome"
          },
          {
            "x": "109",
            "y": "6.08487256879198",
            "series": "Forest prediction"
          },
          {
            "x": "110",
            "y": "6.92",
            "series": "Observed outcome"
          },
          {
            "x": "110",
            "y": "7.75766205450734",
            "series": "Forest prediction"
          },
          {
            "x": "111",
            "y": "5.6",
            "series": "Observed outcome"
          },
          {
            "x": "111",
            "y": "5.66888381276127",
            "series": "Forest prediction"
          },
          {
            "x": "112",
            "y": "5.98",
            "series": "Observed outcome"
          },
          {
            "x": "112",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "113",
            "y": "5.06",
            "series": "Observed outcome"
          },
          {
            "x": "113",
            "y": "5.66888381276127",
            "series": "Forest prediction"
          },
          {
            "x": "114",
            "y": "5.57",
            "series": "Observed outcome"
          },
          {
            "x": "114",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "115",
            "y": "5.84",
            "series": "Observed outcome"
          },
          {
            "x": "115",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "116",
            "y": "6.9",
            "series": "Observed outcome"
          },
          {
            "x": "116",
            "y": "6.08487256879198",
            "series": "Forest prediction"
          },
          {
            "x": "117",
            "y": "3.56",
            "series": "Observed outcome"
          },
          {
            "x": "117",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "118",
            "y": "7.4",
            "series": "Observed outcome"
          },
          {
            "x": "118",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "119",
            "y": "2.39",
            "series": "Observed outcome"
          },
          {
            "x": "119",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "120",
            "y": "6.92",
            "series": "Observed outcome"
          },
          {
            "x": "120",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "121",
            "y": "5.17",
            "series": "Observed outcome"
          },
          {
            "x": "121",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "122",
            "y": "5.96",
            "series": "Observed outcome"
          },
          {
            "x": "122",
            "y": "5.66888381276127",
            "series": "Forest prediction"
          },
          {
            "x": "123",
            "y": "4.81",
            "series": "Observed outcome"
          },
          {
            "x": "123",
            "y": "7.75766205450734",
            "series": "Forest prediction"
          },
          {
            "x": "124",
            "y": "7.69",
            "series": "Observed outcome"
          },
          {
            "x": "124",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "125",
            "y": "3.77",
            "series": "Observed outcome"
          },
          {
            "x": "125",
            "y": "6.08487256879198",
            "series": "Forest prediction"
          },
          {
            "x": "126",
            "y": "7.16",
            "series": "Observed outcome"
          },
          {
            "x": "126",
            "y": "6.08487256879198",
            "series": "Forest prediction"
          },
          {
            "x": "127",
            "y": "6.25",
            "series": "Observed outcome"
          },
          {
            "x": "127",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "128",
            "y": "4.62",
            "series": "Observed outcome"
          },
          {
            "x": "128",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "129",
            "y": "6.45",
            "series": "Observed outcome"
          },
          {
            "x": "129",
            "y": "5.66888381276127",
            "series": "Forest prediction"
          },
          {
            "x": "130",
            "y": "5.25",
            "series": "Observed outcome"
          },
          {
            "x": "130",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "131",
            "y": "5.68",
            "series": "Observed outcome"
          },
          {
            "x": "131",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "132",
            "y": "5.81",
            "series": "Observed outcome"
          },
          {
            "x": "132",
            "y": "6.08487256879198",
            "series": "Forest prediction"
          },
          {
            "x": "133",
            "y": "5",
            "series": "Observed outcome"
          },
          {
            "x": "133",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "134",
            "y": "6",
            "series": "Observed outcome"
          },
          {
            "x": "134",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "135",
            "y": "2.43",
            "series": "Observed outcome"
          },
          {
            "x": "135",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "136",
            "y": "4",
            "series": "Observed outcome"
          },
          {
            "x": "136",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "137",
            "y": "10.43",
            "series": "Observed outcome"
          },
          {
            "x": "137",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "138",
            "y": "5.75",
            "series": "Observed outcome"
          },
          {
            "x": "138",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "139",
            "y": "6.62",
            "series": "Observed outcome"
          },
          {
            "x": "139",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "140",
            "y": "9.47",
            "series": "Observed outcome"
          },
          {
            "x": "140",
            "y": "5.62604883275605",
            "series": "Forest prediction"
          },
          {
            "x": "141",
            "y": "2.4",
            "series": "Observed outcome"
          },
          {
            "x": "141",
            "y": "4.65384944083265",
            "series": "Forest prediction"
          },
          {
            "x": "142",
            "y": "7.27",
            "series": "Observed outcome"
          },
          {
            "x": "142",
            "y": "4.65384944083265",
            "series": "Forest prediction"
          },
          {
            "x": "143",
            "y": "7.5",
            "series": "Observed outcome"
          },
          {
            "x": "143",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "144",
            "y": "6.41",
            "series": "Observed outcome"
          },
          {
            "x": "144",
            "y": "5.66888381276127",
            "series": "Forest prediction"
          },
          {
            "x": "145",
            "y": "3.08",
            "series": "Observed outcome"
          },
          {
            "x": "145",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "146",
            "y": "4.09",
            "series": "Observed outcome"
          },
          {
            "x": "146",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "147",
            "y": "10.82",
            "series": "Observed outcome"
          },
          {
            "x": "147",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "148",
            "y": "6.73",
            "series": "Observed outcome"
          },
          {
            "x": "148",
            "y": "7.75766205450734",
            "series": "Forest prediction"
          },
          {
            "x": "149",
            "y": "4.81",
            "series": "Observed outcome"
          },
          {
            "x": "149",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "150",
            "y": "5.77",
            "series": "Observed outcome"
          },
          {
            "x": "150",
            "y": "7.75766205450734",
            "series": "Forest prediction"
          },
          {
            "x": "151",
            "y": "10.55",
            "series": "Observed outcome"
          },
          {
            "x": "151",
            "y": "6.08487256879198",
            "series": "Forest prediction"
          },
          {
            "x": "152",
            "y": "6.73",
            "series": "Observed outcome"
          },
          {
            "x": "152",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "153",
            "y": "4.94",
            "series": "Observed outcome"
          },
          {
            "x": "153",
            "y": "7.75766205450734",
            "series": "Forest prediction"
          },
          {
            "x": "154",
            "y": "6.01",
            "series": "Observed outcome"
          },
          {
            "x": "154",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "155",
            "y": "6.43",
            "series": "Observed outcome"
          },
          {
            "x": "155",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "156",
            "y": "6.67",
            "series": "Observed outcome"
          },
          {
            "x": "156",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "157",
            "y": "3.11",
            "series": "Observed outcome"
          },
          {
            "x": "157",
            "y": "7.75766205450734",
            "series": "Forest prediction"
          },
          {
            "x": "158",
            "y": "5.77",
            "series": "Observed outcome"
          },
          {
            "x": "158",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "159",
            "y": "12.02",
            "series": "Observed outcome"
          },
          {
            "x": "159",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "160",
            "y": "8.05",
            "series": "Observed outcome"
          },
          {
            "x": "160",
            "y": "5.66888381276127",
            "series": "Forest prediction"
          },
          {
            "x": "161",
            "y": "8.55",
            "series": "Observed outcome"
          },
          {
            "x": "161",
            "y": "6.08487256879198",
            "series": "Forest prediction"
          },
          {
            "x": "162",
            "y": "5.61",
            "series": "Observed outcome"
          },
          {
            "x": "162",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "163",
            "y": "6.73",
            "series": "Observed outcome"
          },
          {
            "x": "163",
            "y": "7.75766205450734",
            "series": "Forest prediction"
          },
          {
            "x": "164",
            "y": "5",
            "series": "Observed outcome"
          },
          {
            "x": "164",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "165",
            "y": "7.55",
            "series": "Observed outcome"
          },
          {
            "x": "165",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "166",
            "y": "6",
            "series": "Observed outcome"
          },
          {
            "x": "166",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "167",
            "y": "6",
            "series": "Observed outcome"
          },
          {
            "x": "167",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "168",
            "y": "10",
            "series": "Observed outcome"
          },
          {
            "x": "168",
            "y": "4.65384944083265",
            "series": "Forest prediction"
          },
          {
            "x": "169",
            "y": "7.07",
            "series": "Observed outcome"
          },
          {
            "x": "169",
            "y": "5.66888381276127",
            "series": "Forest prediction"
          },
          {
            "x": "170",
            "y": "13.22",
            "series": "Observed outcome"
          },
          {
            "x": "170",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "171",
            "y": "6",
            "series": "Observed outcome"
          },
          {
            "x": "171",
            "y": "5.62604883275605",
            "series": "Forest prediction"
          },
          {
            "x": "172",
            "y": "4",
            "series": "Observed outcome"
          },
          {
            "x": "172",
            "y": "7.75766205450734",
            "series": "Forest prediction"
          },
          {
            "x": "173",
            "y": "5.45",
            "series": "Observed outcome"
          },
          {
            "x": "173",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "174",
            "y": "5.49",
            "series": "Observed outcome"
          },
          {
            "x": "174",
            "y": "6.08487256879198",
            "series": "Forest prediction"
          },
          {
            "x": "175",
            "y": "9",
            "series": "Observed outcome"
          },
          {
            "x": "175",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "176",
            "y": "5",
            "series": "Observed outcome"
          },
          {
            "x": "176",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "177",
            "y": "12.64",
            "series": "Observed outcome"
          },
          {
            "x": "177",
            "y": "7.75766205450734",
            "series": "Forest prediction"
          },
          {
            "x": "178",
            "y": "9.83",
            "series": "Observed outcome"
          },
          {
            "x": "178",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "179",
            "y": "4.44",
            "series": "Observed outcome"
          },
          {
            "x": "179",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "180",
            "y": "5",
            "series": "Observed outcome"
          },
          {
            "x": "180",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "181",
            "y": "7.26",
            "series": "Observed outcome"
          },
          {
            "x": "181",
            "y": "6.08487256879198",
            "series": "Forest prediction"
          },
          {
            "x": "182",
            "y": "10.94",
            "series": "Observed outcome"
          },
          {
            "x": "182",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "183",
            "y": "6.56",
            "series": "Observed outcome"
          },
          {
            "x": "183",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "184",
            "y": "7.02",
            "series": "Observed outcome"
          },
          {
            "x": "184",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "185",
            "y": "6.49",
            "series": "Observed outcome"
          },
          {
            "x": "185",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "186",
            "y": "5.56",
            "series": "Observed outcome"
          },
          {
            "x": "186",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "187",
            "y": "7.81",
            "series": "Observed outcome"
          },
          {
            "x": "187",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "188",
            "y": "9.62",
            "series": "Observed outcome"
          },
          {
            "x": "188",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "189",
            "y": "9.38",
            "series": "Observed outcome"
          },
          {
            "x": "189",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "190",
            "y": "8.18",
            "series": "Observed outcome"
          },
          {
            "x": "190",
            "y": "7.75766205450734",
            "series": "Forest prediction"
          },
          {
            "x": "191",
            "y": "6.15",
            "series": "Observed outcome"
          },
          {
            "x": "191",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "192",
            "y": "1.92",
            "series": "Observed outcome"
          },
          {
            "x": "192",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "193",
            "y": "4.38",
            "series": "Observed outcome"
          },
          {
            "x": "193",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "194",
            "y": "4.47",
            "series": "Observed outcome"
          },
          {
            "x": "194",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "195",
            "y": "5.7",
            "series": "Observed outcome"
          },
          {
            "x": "195",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "196",
            "y": "5.29",
            "series": "Observed outcome"
          },
          {
            "x": "196",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "197",
            "y": "8.65",
            "series": "Observed outcome"
          },
          {
            "x": "197",
            "y": "6.08487256879198",
            "series": "Forest prediction"
          },
          {
            "x": "198",
            "y": "7.97",
            "series": "Observed outcome"
          },
          {
            "x": "198",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "199",
            "y": "3.93",
            "series": "Observed outcome"
          },
          {
            "x": "199",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "200",
            "y": "4.81",
            "series": "Observed outcome"
          },
          {
            "x": "200",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "201",
            "y": "0.96",
            "series": "Observed outcome"
          },
          {
            "x": "201",
            "y": "5.62604883275605",
            "series": "Forest prediction"
          },
          {
            "x": "202",
            "y": "2.26",
            "series": "Observed outcome"
          },
          {
            "x": "202",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "203",
            "y": "4.6",
            "series": "Observed outcome"
          },
          {
            "x": "203",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "204",
            "y": "3.78",
            "series": "Observed outcome"
          },
          {
            "x": "204",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "205",
            "y": "4.91",
            "series": "Observed outcome"
          },
          {
            "x": "205",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "206",
            "y": "5.06",
            "series": "Observed outcome"
          },
          {
            "x": "206",
            "y": "7.75766205450734",
            "series": "Forest prediction"
          },
          {
            "x": "207",
            "y": "5.88",
            "series": "Observed outcome"
          },
          {
            "x": "207",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "208",
            "y": "8.31",
            "series": "Observed outcome"
          },
          {
            "x": "208",
            "y": "7.75766205450734",
            "series": "Forest prediction"
          },
          {
            "x": "209",
            "y": "9.64",
            "series": "Observed outcome"
          },
          {
            "x": "209",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "210",
            "y": "6.09",
            "series": "Observed outcome"
          },
          {
            "x": "210",
            "y": "5.66888381276127",
            "series": "Forest prediction"
          },
          {
            "x": "211",
            "y": "5",
            "series": "Observed outcome"
          },
          {
            "x": "211",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "212",
            "y": "3.3",
            "series": "Observed outcome"
          },
          {
            "x": "212",
            "y": "6.08487256879198",
            "series": "Forest prediction"
          },
          {
            "x": "213",
            "y": "3.59",
            "series": "Observed outcome"
          },
          {
            "x": "213",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "214",
            "y": "6.53",
            "series": "Observed outcome"
          },
          {
            "x": "214",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "215",
            "y": "6.22",
            "series": "Observed outcome"
          },
          {
            "x": "215",
            "y": "7.75766205450734",
            "series": "Forest prediction"
          },
          {
            "x": "216",
            "y": "5.75",
            "series": "Observed outcome"
          },
          {
            "x": "216",
            "y": "6.08487256879198",
            "series": "Forest prediction"
          },
          {
            "x": "217",
            "y": "3",
            "series": "Observed outcome"
          },
          {
            "x": "217",
            "y": "7.75766205450734",
            "series": "Forest prediction"
          },
          {
            "x": "218",
            "y": "8.17",
            "series": "Observed outcome"
          },
          {
            "x": "218",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "219",
            "y": "5",
            "series": "Observed outcome"
          },
          {
            "x": "219",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "220",
            "y": "5.25",
            "series": "Observed outcome"
          },
          {
            "x": "220",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "221",
            "y": "6.04",
            "series": "Observed outcome"
          },
          {
            "x": "221",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "222",
            "y": "7.14",
            "series": "Observed outcome"
          },
          {
            "x": "222",
            "y": "5.66888381276127",
            "series": "Forest prediction"
          },
          {
            "x": "223",
            "y": "6.56",
            "series": "Observed outcome"
          },
          {
            "x": "223",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "224",
            "y": "6.73",
            "series": "Observed outcome"
          },
          {
            "x": "224",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "225",
            "y": "7.6",
            "series": "Observed outcome"
          },
          {
            "x": "225",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "226",
            "y": "4.75",
            "series": "Observed outcome"
          },
          {
            "x": "226",
            "y": "5.66888381276127",
            "series": "Forest prediction"
          },
          {
            "x": "227",
            "y": "2.25",
            "series": "Observed outcome"
          },
          {
            "x": "227",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "228",
            "y": "8.17",
            "series": "Observed outcome"
          },
          {
            "x": "228",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "229",
            "y": "8.97",
            "series": "Observed outcome"
          },
          {
            "x": "229",
            "y": "4.86192429463382",
            "series": "Forest prediction"
          },
          {
            "x": "230",
            "y": "9.29",
            "series": "Observed outcome"
          },
          {
            "x": "230",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "231",
            "y": "2.66",
            "series": "Observed outcome"
          },
          {
            "x": "231",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "232",
            "y": "8.01",
            "series": "Observed outcome"
          },
          {
            "x": "232",
            "y": "4.86192429463382",
            "series": "Forest prediction"
          },
          {
            "x": "233",
            "y": "6",
            "series": "Observed outcome"
          },
          {
            "x": "233",
            "y": "7.75766205450734",
            "series": "Forest prediction"
          },
          {
            "x": "234",
            "y": "6.58",
            "series": "Observed outcome"
          },
          {
            "x": "234",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "235",
            "y": "5.96",
            "series": "Observed outcome"
          },
          {
            "x": "235",
            "y": "4.65384944083265",
            "series": "Forest prediction"
          },
          {
            "x": "236",
            "y": "7.21",
            "series": "Observed outcome"
          },
          {
            "x": "236",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "237",
            "y": "5.63",
            "series": "Observed outcome"
          },
          {
            "x": "237",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "238",
            "y": "4.7",
            "series": "Observed outcome"
          },
          {
            "x": "238",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "239",
            "y": "3.89",
            "series": "Observed outcome"
          },
          {
            "x": "239",
            "y": "4.86192429463382",
            "series": "Forest prediction"
          },
          {
            "x": "240",
            "y": "6.5",
            "series": "Observed outcome"
          },
          {
            "x": "240",
            "y": "5.62604883275605",
            "series": "Forest prediction"
          },
          {
            "x": "241",
            "y": "7.59",
            "series": "Observed outcome"
          },
          {
            "x": "241",
            "y": "7.75766205450734",
            "series": "Forest prediction"
          },
          {
            "x": "242",
            "y": "9.15",
            "series": "Observed outcome"
          },
          {
            "x": "242",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "243",
            "y": "2.67",
            "series": "Observed outcome"
          },
          {
            "x": "243",
            "y": "4.86192429463382",
            "series": "Forest prediction"
          },
          {
            "x": "244",
            "y": "7.21",
            "series": "Observed outcome"
          },
          {
            "x": "244",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "245",
            "y": "4.23",
            "series": "Observed outcome"
          },
          {
            "x": "245",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "246",
            "y": "4.1",
            "series": "Observed outcome"
          },
          {
            "x": "246",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "247",
            "y": "4.5",
            "series": "Observed outcome"
          },
          {
            "x": "247",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "248",
            "y": "8.17",
            "series": "Observed outcome"
          },
          {
            "x": "248",
            "y": "5.66888381276127",
            "series": "Forest prediction"
          },
          {
            "x": "249",
            "y": "9.13",
            "series": "Observed outcome"
          },
          {
            "x": "249",
            "y": "6.08487256879198",
            "series": "Forest prediction"
          },
          {
            "x": "250",
            "y": "3.96",
            "series": "Observed outcome"
          },
          {
            "x": "250",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "251",
            "y": "4.62",
            "series": "Observed outcome"
          },
          {
            "x": "251",
            "y": "7.75766205450734",
            "series": "Forest prediction"
          },
          {
            "x": "252",
            "y": "5.49",
            "series": "Observed outcome"
          },
          {
            "x": "252",
            "y": "5.66888381276127",
            "series": "Forest prediction"
          },
          {
            "x": "253",
            "y": "3.85",
            "series": "Observed outcome"
          },
          {
            "x": "253",
            "y": "4.65384944083265",
            "series": "Forest prediction"
          },
          {
            "x": "254",
            "y": "6.16",
            "series": "Observed outcome"
          },
          {
            "x": "254",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "255",
            "y": "4.3",
            "series": "Observed outcome"
          },
          {
            "x": "255",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "256",
            "y": "11",
            "series": "Observed outcome"
          },
          {
            "x": "256",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "257",
            "y": "9.21",
            "series": "Observed outcome"
          },
          {
            "x": "257",
            "y": "6.08487256879198",
            "series": "Forest prediction"
          },
          {
            "x": "258",
            "y": "4.11",
            "series": "Observed outcome"
          },
          {
            "x": "258",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "259",
            "y": "4.23",
            "series": "Observed outcome"
          },
          {
            "x": "259",
            "y": "5.21006007672534",
            "series": "Forest prediction"
          },
          {
            "x": "260",
            "y": "6",
            "series": "Observed outcome"
          },
          {
            "x": "260",
            "y": "5.66888381276127",
            "series": "Forest prediction"
          },
          {
            "x": "261",
            "y": "4.49",
            "series": "Observed outcome"
          },
          {
            "x": "261",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "262",
            "y": "5.71",
            "series": "Observed outcome"
          },
          {
            "x": "262",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "263",
            "y": "7.21",
            "series": "Observed outcome"
          },
          {
            "x": "263",
            "y": "7.75766205450734",
            "series": "Forest prediction"
          },
          {
            "x": "264",
            "y": "7.13",
            "series": "Observed outcome"
          },
          {
            "x": "264",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "265",
            "y": "2.6",
            "series": "Observed outcome"
          },
          {
            "x": "265",
            "y": "6.08487256879198",
            "series": "Forest prediction"
          },
          {
            "x": "266",
            "y": "6.2",
            "series": "Observed outcome"
          },
          {
            "x": "266",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "267",
            "y": "8.08",
            "series": "Observed outcome"
          },
          {
            "x": "267",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "268",
            "y": "6.93",
            "series": "Observed outcome"
          },
          {
            "x": "268",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "269",
            "y": "4",
            "series": "Observed outcome"
          },
          {
            "x": "269",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "270",
            "y": "7",
            "series": "Observed outcome"
          },
          {
            "x": "270",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "271",
            "y": "10.55",
            "series": "Observed outcome"
          },
          {
            "x": "271",
            "y": "6.08487256879198",
            "series": "Forest prediction"
          },
          {
            "x": "272",
            "y": "6.48",
            "series": "Observed outcome"
          },
          {
            "x": "272",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "273",
            "y": "4.25",
            "series": "Observed outcome"
          },
          {
            "x": "273",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "274",
            "y": "11",
            "series": "Observed outcome"
          },
          {
            "x": "274",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "275",
            "y": "7",
            "series": "Observed outcome"
          },
          {
            "x": "275",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "276",
            "y": "3.35",
            "series": "Observed outcome"
          },
          {
            "x": "276",
            "y": "4.86192429463382",
            "series": "Forest prediction"
          },
          {
            "x": "277",
            "y": "6.25",
            "series": "Observed outcome"
          },
          {
            "x": "277",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "278",
            "y": "5.5",
            "series": "Observed outcome"
          },
          {
            "x": "278",
            "y": "5.66888381276127",
            "series": "Forest prediction"
          },
          {
            "x": "279",
            "y": "7.13",
            "series": "Observed outcome"
          },
          {
            "x": "279",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "280",
            "y": "6.33",
            "series": "Observed outcome"
          },
          {
            "x": "280",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "281",
            "y": "8.32",
            "series": "Observed outcome"
          },
          {
            "x": "281",
            "y": "7.75766205450734",
            "series": "Forest prediction"
          },
          {
            "x": "282",
            "y": "7.22",
            "series": "Observed outcome"
          },
          {
            "x": "282",
            "y": "5.66888381276127",
            "series": "Forest prediction"
          },
          {
            "x": "283",
            "y": "3.93",
            "series": "Observed outcome"
          },
          {
            "x": "283",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "284",
            "y": "5.2",
            "series": "Observed outcome"
          },
          {
            "x": "284",
            "y": "4.86192429463382",
            "series": "Forest prediction"
          },
          {
            "x": "285",
            "y": "4.75",
            "series": "Observed outcome"
          },
          {
            "x": "285",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "286",
            "y": "5.77",
            "series": "Observed outcome"
          },
          {
            "x": "286",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "287",
            "y": "4.5",
            "series": "Observed outcome"
          },
          {
            "x": "287",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "288",
            "y": "6.23",
            "series": "Observed outcome"
          },
          {
            "x": "288",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "289",
            "y": "7.21",
            "series": "Observed outcome"
          },
          {
            "x": "289",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "290",
            "y": "3.63",
            "series": "Observed outcome"
          },
          {
            "x": "290",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "291",
            "y": "8.79",
            "series": "Observed outcome"
          },
          {
            "x": "291",
            "y": "6.08487256879198",
            "series": "Forest prediction"
          },
          {
            "x": "292",
            "y": "3.25",
            "series": "Observed outcome"
          },
          {
            "x": "292",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "293",
            "y": "2.64",
            "series": "Observed outcome"
          },
          {
            "x": "293",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "294",
            "y": "9.8",
            "series": "Observed outcome"
          },
          {
            "x": "294",
            "y": "6.08487256879198",
            "series": "Forest prediction"
          },
          {
            "x": "295",
            "y": "4.63",
            "series": "Observed outcome"
          },
          {
            "x": "295",
            "y": "4.86192429463382",
            "series": "Forest prediction"
          },
          {
            "x": "296",
            "y": "4.04",
            "series": "Observed outcome"
          },
          {
            "x": "296",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "297",
            "y": "9.13",
            "series": "Observed outcome"
          },
          {
            "x": "297",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "298",
            "y": "6.15",
            "series": "Observed outcome"
          },
          {
            "x": "298",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "299",
            "y": "2.38",
            "series": "Observed outcome"
          },
          {
            "x": "299",
            "y": "4.65384944083265",
            "series": "Forest prediction"
          },
          {
            "x": "300",
            "y": "3.65",
            "series": "Observed outcome"
          },
          {
            "x": "300",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "301",
            "y": "4.62",
            "series": "Observed outcome"
          },
          {
            "x": "301",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "302",
            "y": "7.5",
            "series": "Observed outcome"
          },
          {
            "x": "302",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "303",
            "y": "4.62",
            "series": "Observed outcome"
          },
          {
            "x": "303",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "304",
            "y": "5.6",
            "series": "Observed outcome"
          },
          {
            "x": "304",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "305",
            "y": "4.11",
            "series": "Observed outcome"
          },
          {
            "x": "305",
            "y": "5.66888381276127",
            "series": "Forest prediction"
          },
          {
            "x": "306",
            "y": "7.75",
            "series": "Observed outcome"
          },
          {
            "x": "306",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "307",
            "y": "8.75",
            "series": "Observed outcome"
          },
          {
            "x": "307",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "308",
            "y": "3.4",
            "series": "Observed outcome"
          },
          {
            "x": "308",
            "y": "6.08487256879198",
            "series": "Forest prediction"
          },
          {
            "x": "309",
            "y": "15.02",
            "series": "Observed outcome"
          },
          {
            "x": "309",
            "y": "7.75766205450734",
            "series": "Forest prediction"
          },
          {
            "x": "310",
            "y": "3.31",
            "series": "Observed outcome"
          },
          {
            "x": "310",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "311",
            "y": "7.59",
            "series": "Observed outcome"
          },
          {
            "x": "311",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "312",
            "y": "5.68",
            "series": "Observed outcome"
          },
          {
            "x": "312",
            "y": "6.08487256879198",
            "series": "Forest prediction"
          },
          {
            "x": "313",
            "y": "6.25",
            "series": "Observed outcome"
          },
          {
            "x": "313",
            "y": "5.66888381276127",
            "series": "Forest prediction"
          },
          {
            "x": "314",
            "y": "6.24",
            "series": "Observed outcome"
          },
          {
            "x": "314",
            "y": "5.62604883275605",
            "series": "Forest prediction"
          },
          {
            "x": "315",
            "y": "6.74",
            "series": "Observed outcome"
          },
          {
            "x": "315",
            "y": "7.75766205450734",
            "series": "Forest prediction"
          },
          {
            "x": "316",
            "y": "3.27",
            "series": "Observed outcome"
          },
          {
            "x": "316",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "317",
            "y": "3.85",
            "series": "Observed outcome"
          },
          {
            "x": "317",
            "y": "5.21006007672534",
            "series": "Forest prediction"
          },
          {
            "x": "318",
            "y": "7.45",
            "series": "Observed outcome"
          },
          {
            "x": "318",
            "y": "6.08487256879198",
            "series": "Forest prediction"
          },
          {
            "x": "319",
            "y": "7.45",
            "series": "Observed outcome"
          },
          {
            "x": "319",
            "y": "7.75766205450734",
            "series": "Forest prediction"
          },
          {
            "x": "320",
            "y": "5.45",
            "series": "Observed outcome"
          },
          {
            "x": "320",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "321",
            "y": "5.77",
            "series": "Observed outcome"
          },
          {
            "x": "321",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "322",
            "y": "8.65",
            "series": "Observed outcome"
          },
          {
            "x": "322",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "323",
            "y": "5",
            "series": "Observed outcome"
          },
          {
            "x": "323",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "324",
            "y": "7.5",
            "series": "Observed outcome"
          },
          {
            "x": "324",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "325",
            "y": "6.85",
            "series": "Observed outcome"
          },
          {
            "x": "325",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "326",
            "y": "3.97",
            "series": "Observed outcome"
          },
          {
            "x": "326",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "327",
            "y": "9.62",
            "series": "Observed outcome"
          },
          {
            "x": "327",
            "y": "5.66888381276127",
            "series": "Forest prediction"
          },
          {
            "x": "328",
            "y": "5.4",
            "series": "Observed outcome"
          },
          {
            "x": "328",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "329",
            "y": "3.6",
            "series": "Observed outcome"
          },
          {
            "x": "329",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "330",
            "y": "7.26",
            "series": "Observed outcome"
          },
          {
            "x": "330",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "331",
            "y": "3.75",
            "series": "Observed outcome"
          },
          {
            "x": "331",
            "y": "5.62604883275605",
            "series": "Forest prediction"
          },
          {
            "x": "332",
            "y": "6.49",
            "series": "Observed outcome"
          },
          {
            "x": "332",
            "y": "5.66888381276127",
            "series": "Forest prediction"
          },
          {
            "x": "333",
            "y": "3.15",
            "series": "Observed outcome"
          },
          {
            "x": "333",
            "y": "5.62604883275605",
            "series": "Forest prediction"
          },
          {
            "x": "334",
            "y": "6.93",
            "series": "Observed outcome"
          },
          {
            "x": "334",
            "y": "5.21006007672534",
            "series": "Forest prediction"
          },
          {
            "x": "335",
            "y": "4",
            "series": "Observed outcome"
          },
          {
            "x": "335",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "336",
            "y": "9.62",
            "series": "Observed outcome"
          },
          {
            "x": "336",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "337",
            "y": "4.57",
            "series": "Observed outcome"
          },
          {
            "x": "337",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "338",
            "y": "3.63",
            "series": "Observed outcome"
          },
          {
            "x": "338",
            "y": "4.65384944083265",
            "series": "Forest prediction"
          },
          {
            "x": "339",
            "y": "4.27",
            "series": "Observed outcome"
          },
          {
            "x": "339",
            "y": "5.66888381276127",
            "series": "Forest prediction"
          },
          {
            "x": "340",
            "y": "3.75",
            "series": "Observed outcome"
          },
          {
            "x": "340",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "341",
            "y": "3.55",
            "series": "Observed outcome"
          },
          {
            "x": "341",
            "y": "4.86192429463382",
            "series": "Forest prediction"
          },
          {
            "x": "342",
            "y": "4.43",
            "series": "Observed outcome"
          },
          {
            "x": "342",
            "y": "7.75766205450734",
            "series": "Forest prediction"
          },
          {
            "x": "343",
            "y": "4.81",
            "series": "Observed outcome"
          },
          {
            "x": "343",
            "y": "5.21006007672534",
            "series": "Forest prediction"
          },
          {
            "x": "344",
            "y": "2.5",
            "series": "Observed outcome"
          },
          {
            "x": "344",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "345",
            "y": "13.74",
            "series": "Observed outcome"
          },
          {
            "x": "345",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "346",
            "y": "4.44",
            "series": "Observed outcome"
          },
          {
            "x": "346",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "347",
            "y": "3.1",
            "series": "Observed outcome"
          },
          {
            "x": "347",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "348",
            "y": "6.73",
            "series": "Observed outcome"
          },
          {
            "x": "348",
            "y": "6.08487256879198",
            "series": "Forest prediction"
          },
          {
            "x": "349",
            "y": "3.08",
            "series": "Observed outcome"
          },
          {
            "x": "349",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "350",
            "y": "7.69",
            "series": "Observed outcome"
          },
          {
            "x": "350",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "351",
            "y": "7.36",
            "series": "Observed outcome"
          },
          {
            "x": "351",
            "y": "7.75766205450734",
            "series": "Forest prediction"
          },
          {
            "x": "352",
            "y": "7.21",
            "series": "Observed outcome"
          },
          {
            "x": "352",
            "y": "6.08487256879198",
            "series": "Forest prediction"
          },
          {
            "x": "353",
            "y": "2.87",
            "series": "Observed outcome"
          },
          {
            "x": "353",
            "y": "6.08487256879198",
            "series": "Forest prediction"
          },
          {
            "x": "354",
            "y": "5.48",
            "series": "Observed outcome"
          },
          {
            "x": "354",
            "y": "5.66888381276127",
            "series": "Forest prediction"
          },
          {
            "x": "355",
            "y": "3.75",
            "series": "Observed outcome"
          },
          {
            "x": "355",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "356",
            "y": "11.55",
            "series": "Observed outcome"
          },
          {
            "x": "356",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "357",
            "y": "4.16",
            "series": "Observed outcome"
          },
          {
            "x": "357",
            "y": "5.66888381276127",
            "series": "Forest prediction"
          },
          {
            "x": "358",
            "y": "3.75",
            "series": "Observed outcome"
          },
          {
            "x": "358",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "359",
            "y": "4.5",
            "series": "Observed outcome"
          },
          {
            "x": "359",
            "y": "5.62604883275605",
            "series": "Forest prediction"
          },
          {
            "x": "360",
            "y": "1.98",
            "series": "Observed outcome"
          },
          {
            "x": "360",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "361",
            "y": "1.67",
            "series": "Observed outcome"
          },
          {
            "x": "361",
            "y": "4.65384944083265",
            "series": "Forest prediction"
          },
          {
            "x": "362",
            "y": "3.98",
            "series": "Observed outcome"
          },
          {
            "x": "362",
            "y": "7.75766205450734",
            "series": "Forest prediction"
          },
          {
            "x": "363",
            "y": "3",
            "series": "Observed outcome"
          },
          {
            "x": "363",
            "y": "5.21006007672534",
            "series": "Forest prediction"
          },
          {
            "x": "364",
            "y": "3",
            "series": "Observed outcome"
          },
          {
            "x": "364",
            "y": "4.65384944083265",
            "series": "Forest prediction"
          },
          {
            "x": "365",
            "y": "2.44",
            "series": "Observed outcome"
          },
          {
            "x": "365",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "366",
            "y": "4.95",
            "series": "Observed outcome"
          },
          {
            "x": "366",
            "y": "6.08487256879198",
            "series": "Forest prediction"
          },
          {
            "x": "367",
            "y": "3",
            "series": "Observed outcome"
          },
          {
            "x": "367",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "368",
            "y": "2.6",
            "series": "Observed outcome"
          },
          {
            "x": "368",
            "y": "4.65384944083265",
            "series": "Forest prediction"
          },
          {
            "x": "369",
            "y": "5",
            "series": "Observed outcome"
          },
          {
            "x": "369",
            "y": "5.62604883275605",
            "series": "Forest prediction"
          },
          {
            "x": "370",
            "y": "3.85",
            "series": "Observed outcome"
          },
          {
            "x": "370",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "371",
            "y": "2.67",
            "series": "Observed outcome"
          },
          {
            "x": "371",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "372",
            "y": "6.25",
            "series": "Observed outcome"
          },
          {
            "x": "372",
            "y": "5.21006007672534",
            "series": "Forest prediction"
          },
          {
            "x": "373",
            "y": "6",
            "series": "Observed outcome"
          },
          {
            "x": "373",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "374",
            "y": "5.5",
            "series": "Observed outcome"
          },
          {
            "x": "374",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "375",
            "y": "10",
            "series": "Observed outcome"
          },
          {
            "x": "375",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "376",
            "y": "11.42",
            "series": "Observed outcome"
          },
          {
            "x": "376",
            "y": "7.75766205450734",
            "series": "Forest prediction"
          },
          {
            "x": "377",
            "y": "2.5",
            "series": "Observed outcome"
          },
          {
            "x": "377",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "378",
            "y": "3",
            "series": "Observed outcome"
          },
          {
            "x": "378",
            "y": "4.65384944083265",
            "series": "Forest prediction"
          },
          {
            "x": "379",
            "y": "5.58",
            "series": "Observed outcome"
          },
          {
            "x": "379",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "380",
            "y": "2.4",
            "series": "Observed outcome"
          },
          {
            "x": "380",
            "y": "4.65384944083265",
            "series": "Forest prediction"
          },
          {
            "x": "381",
            "y": "4.13",
            "series": "Observed outcome"
          },
          {
            "x": "381",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "382",
            "y": "10.97",
            "series": "Observed outcome"
          },
          {
            "x": "382",
            "y": "5.66888381276127",
            "series": "Forest prediction"
          },
          {
            "x": "383",
            "y": "5.77",
            "series": "Observed outcome"
          },
          {
            "x": "383",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "384",
            "y": "1.96",
            "series": "Observed outcome"
          },
          {
            "x": "384",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "385",
            "y": "9.45",
            "series": "Observed outcome"
          },
          {
            "x": "385",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "386",
            "y": "4.2",
            "series": "Observed outcome"
          },
          {
            "x": "386",
            "y": "6.08487256879198",
            "series": "Forest prediction"
          },
          {
            "x": "387",
            "y": "5.5",
            "series": "Observed outcome"
          },
          {
            "x": "387",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "388",
            "y": "7.5",
            "series": "Observed outcome"
          },
          {
            "x": "388",
            "y": "4.65384944083265",
            "series": "Forest prediction"
          },
          {
            "x": "389",
            "y": "4.75",
            "series": "Observed outcome"
          },
          {
            "x": "389",
            "y": "6.08487256879198",
            "series": "Forest prediction"
          },
          {
            "x": "390",
            "y": "2.63",
            "series": "Observed outcome"
          },
          {
            "x": "390",
            "y": "6.08487256879198",
            "series": "Forest prediction"
          },
          {
            "x": "391",
            "y": "3.46",
            "series": "Observed outcome"
          },
          {
            "x": "391",
            "y": "4.86192429463382",
            "series": "Forest prediction"
          },
          {
            "x": "392",
            "y": "3.19",
            "series": "Observed outcome"
          },
          {
            "x": "392",
            "y": "5.62604883275605",
            "series": "Forest prediction"
          },
          {
            "x": "393",
            "y": "2.3",
            "series": "Observed outcome"
          },
          {
            "x": "393",
            "y": "4.65384944083265",
            "series": "Forest prediction"
          },
          {
            "x": "394",
            "y": "5.19",
            "series": "Observed outcome"
          },
          {
            "x": "394",
            "y": "6.08487256879198",
            "series": "Forest prediction"
          },
          {
            "x": "395",
            "y": "3.16",
            "series": "Observed outcome"
          },
          {
            "x": "395",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "396",
            "y": "4.51",
            "series": "Observed outcome"
          },
          {
            "x": "396",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "397",
            "y": "8.55",
            "series": "Observed outcome"
          },
          {
            "x": "397",
            "y": "6.08487256879198",
            "series": "Forest prediction"
          },
          {
            "x": "398",
            "y": "4.05",
            "series": "Observed outcome"
          },
          {
            "x": "398",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "399",
            "y": "4.52",
            "series": "Observed outcome"
          },
          {
            "x": "399",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "400",
            "y": "3.75",
            "series": "Observed outcome"
          },
          {
            "x": "400",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "401",
            "y": "6.25",
            "series": "Observed outcome"
          },
          {
            "x": "401",
            "y": "6.08487256879198",
            "series": "Forest prediction"
          },
          {
            "x": "402",
            "y": "5",
            "series": "Observed outcome"
          },
          {
            "x": "402",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "403",
            "y": "4.9",
            "series": "Observed outcome"
          },
          {
            "x": "403",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "404",
            "y": "4",
            "series": "Observed outcome"
          },
          {
            "x": "404",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "405",
            "y": "3.25",
            "series": "Observed outcome"
          },
          {
            "x": "405",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "406",
            "y": "6.19",
            "series": "Observed outcome"
          },
          {
            "x": "406",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "407",
            "y": "3.25",
            "series": "Observed outcome"
          },
          {
            "x": "407",
            "y": "5.66888381276127",
            "series": "Forest prediction"
          },
          {
            "x": "408",
            "y": "6.86",
            "series": "Observed outcome"
          },
          {
            "x": "408",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "409",
            "y": "4.62",
            "series": "Observed outcome"
          },
          {
            "x": "409",
            "y": "4.86192429463382",
            "series": "Forest prediction"
          },
          {
            "x": "410",
            "y": "4",
            "series": "Observed outcome"
          },
          {
            "x": "410",
            "y": "5.62604883275605",
            "series": "Forest prediction"
          },
          {
            "x": "411",
            "y": "2.82",
            "series": "Observed outcome"
          },
          {
            "x": "411",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "412",
            "y": "9.59",
            "series": "Observed outcome"
          },
          {
            "x": "412",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "413",
            "y": "4.75",
            "series": "Observed outcome"
          },
          {
            "x": "413",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "414",
            "y": "6.73",
            "series": "Observed outcome"
          },
          {
            "x": "414",
            "y": "6.08487256879198",
            "series": "Forest prediction"
          },
          {
            "x": "415",
            "y": "3.75",
            "series": "Observed outcome"
          },
          {
            "x": "415",
            "y": "5.62604883275605",
            "series": "Forest prediction"
          },
          {
            "x": "416",
            "y": "17.63",
            "series": "Observed outcome"
          },
          {
            "x": "416",
            "y": "7.75766205450734",
            "series": "Forest prediction"
          },
          {
            "x": "417",
            "y": "2.75",
            "series": "Observed outcome"
          },
          {
            "x": "417",
            "y": "5.21006007672534",
            "series": "Forest prediction"
          },
          {
            "x": "418",
            "y": "5.07",
            "series": "Observed outcome"
          },
          {
            "x": "418",
            "y": "4.65384944083265",
            "series": "Forest prediction"
          },
          {
            "x": "419",
            "y": "10.68",
            "series": "Observed outcome"
          },
          {
            "x": "419",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "420",
            "y": "7.5",
            "series": "Observed outcome"
          },
          {
            "x": "420",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "421",
            "y": "4.62",
            "series": "Observed outcome"
          },
          {
            "x": "421",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "422",
            "y": "8.94",
            "series": "Observed outcome"
          },
          {
            "x": "422",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "423",
            "y": "2.41",
            "series": "Observed outcome"
          },
          {
            "x": "423",
            "y": "5.21006007672534",
            "series": "Forest prediction"
          },
          {
            "x": "424",
            "y": "5.65",
            "series": "Observed outcome"
          },
          {
            "x": "424",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "425",
            "y": "4.13",
            "series": "Observed outcome"
          },
          {
            "x": "425",
            "y": "4.65384944083265",
            "series": "Forest prediction"
          },
          {
            "x": "426",
            "y": "7.78",
            "series": "Observed outcome"
          },
          {
            "x": "426",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "427",
            "y": "3.5",
            "series": "Observed outcome"
          },
          {
            "x": "427",
            "y": "4.65384944083265",
            "series": "Forest prediction"
          },
          {
            "x": "428",
            "y": "8.66",
            "series": "Observed outcome"
          },
          {
            "x": "428",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "429",
            "y": "1.48",
            "series": "Observed outcome"
          },
          {
            "x": "429",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "430",
            "y": "6.92",
            "series": "Observed outcome"
          },
          {
            "x": "430",
            "y": "7.75766205450734",
            "series": "Forest prediction"
          },
          {
            "x": "431",
            "y": "8.65",
            "series": "Observed outcome"
          },
          {
            "x": "431",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "432",
            "y": "7.12",
            "series": "Observed outcome"
          },
          {
            "x": "432",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "433",
            "y": "7.38",
            "series": "Observed outcome"
          },
          {
            "x": "433",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "434",
            "y": "8.69",
            "series": "Observed outcome"
          },
          {
            "x": "434",
            "y": "6.08487256879198",
            "series": "Forest prediction"
          },
          {
            "x": "435",
            "y": "4.62",
            "series": "Observed outcome"
          },
          {
            "x": "435",
            "y": "7.75766205450734",
            "series": "Forest prediction"
          },
          {
            "x": "436",
            "y": "7.7",
            "series": "Observed outcome"
          },
          {
            "x": "436",
            "y": "6.08487256879198",
            "series": "Forest prediction"
          },
          {
            "x": "437",
            "y": "7.13",
            "series": "Observed outcome"
          },
          {
            "x": "437",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "438",
            "y": "7.21",
            "series": "Observed outcome"
          },
          {
            "x": "438",
            "y": "5.66888381276127",
            "series": "Forest prediction"
          },
          {
            "x": "439",
            "y": "4",
            "series": "Observed outcome"
          },
          {
            "x": "439",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "440",
            "y": "5.53",
            "series": "Observed outcome"
          },
          {
            "x": "440",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "441",
            "y": "3",
            "series": "Observed outcome"
          },
          {
            "x": "441",
            "y": "4.65384944083265",
            "series": "Forest prediction"
          },
          {
            "x": "442",
            "y": "7.51",
            "series": "Observed outcome"
          },
          {
            "x": "442",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "443",
            "y": "10.58",
            "series": "Observed outcome"
          },
          {
            "x": "443",
            "y": "7.75766205450734",
            "series": "Forest prediction"
          },
          {
            "x": "444",
            "y": "5.38",
            "series": "Observed outcome"
          },
          {
            "x": "444",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "445",
            "y": "6.5",
            "series": "Observed outcome"
          },
          {
            "x": "445",
            "y": "5.62604883275605",
            "series": "Forest prediction"
          },
          {
            "x": "446",
            "y": "2.86",
            "series": "Observed outcome"
          },
          {
            "x": "446",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "447",
            "y": "2.77",
            "series": "Observed outcome"
          },
          {
            "x": "447",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "448",
            "y": "6.73",
            "series": "Observed outcome"
          },
          {
            "x": "448",
            "y": "5.66888381276127",
            "series": "Forest prediction"
          },
          {
            "x": "449",
            "y": "14.43",
            "series": "Observed outcome"
          },
          {
            "x": "449",
            "y": "6.08487256879198",
            "series": "Forest prediction"
          },
          {
            "x": "450",
            "y": "4.79",
            "series": "Observed outcome"
          },
          {
            "x": "450",
            "y": "4.65384944083265",
            "series": "Forest prediction"
          },
          {
            "x": "451",
            "y": "6.25",
            "series": "Observed outcome"
          },
          {
            "x": "451",
            "y": "6.08487256879198",
            "series": "Forest prediction"
          },
          {
            "x": "452",
            "y": "6.15",
            "series": "Observed outcome"
          },
          {
            "x": "452",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "453",
            "y": "8.43",
            "series": "Observed outcome"
          },
          {
            "x": "453",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "454",
            "y": "10.14",
            "series": "Observed outcome"
          },
          {
            "x": "454",
            "y": "7.75766205450734",
            "series": "Forest prediction"
          },
          {
            "x": "455",
            "y": "7.45",
            "series": "Observed outcome"
          },
          {
            "x": "455",
            "y": "6.08487256879198",
            "series": "Forest prediction"
          },
          {
            "x": "456",
            "y": "5",
            "series": "Observed outcome"
          },
          {
            "x": "456",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "457",
            "y": "9.62",
            "series": "Observed outcome"
          },
          {
            "x": "457",
            "y": "6.08487256879198",
            "series": "Forest prediction"
          },
          {
            "x": "458",
            "y": "6.75",
            "series": "Observed outcome"
          },
          {
            "x": "458",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "459",
            "y": "11.75",
            "series": "Observed outcome"
          },
          {
            "x": "459",
            "y": "7.75766205450734",
            "series": "Forest prediction"
          },
          {
            "x": "460",
            "y": "10.29",
            "series": "Observed outcome"
          },
          {
            "x": "460",
            "y": "6.08487256879198",
            "series": "Forest prediction"
          },
          {
            "x": "461",
            "y": "3.5",
            "series": "Observed outcome"
          },
          {
            "x": "461",
            "y": "5.21006007672534",
            "series": "Forest prediction"
          },
          {
            "x": "462",
            "y": "7.28",
            "series": "Observed outcome"
          },
          {
            "x": "462",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "463",
            "y": "9.83",
            "series": "Observed outcome"
          },
          {
            "x": "463",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "464",
            "y": "3.13",
            "series": "Observed outcome"
          },
          {
            "x": "464",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "465",
            "y": "4",
            "series": "Observed outcome"
          },
          {
            "x": "465",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "466",
            "y": "2.55",
            "series": "Observed outcome"
          },
          {
            "x": "466",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "467",
            "y": "7.69",
            "series": "Observed outcome"
          },
          {
            "x": "467",
            "y": "6.08487256879198",
            "series": "Forest prediction"
          },
          {
            "x": "468",
            "y": "9.06",
            "series": "Observed outcome"
          },
          {
            "x": "468",
            "y": "6.08487256879198",
            "series": "Forest prediction"
          },
          {
            "x": "469",
            "y": "5.92",
            "series": "Observed outcome"
          },
          {
            "x": "469",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "470",
            "y": "4.42",
            "series": "Observed outcome"
          },
          {
            "x": "470",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "471",
            "y": "7.24",
            "series": "Observed outcome"
          },
          {
            "x": "471",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "472",
            "y": "5.77",
            "series": "Observed outcome"
          },
          {
            "x": "472",
            "y": "5.66888381276127",
            "series": "Forest prediction"
          },
          {
            "x": "473",
            "y": "5.77",
            "series": "Observed outcome"
          },
          {
            "x": "473",
            "y": "5.66888381276127",
            "series": "Forest prediction"
          },
          {
            "x": "474",
            "y": "6.25",
            "series": "Observed outcome"
          },
          {
            "x": "474",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "475",
            "y": "7.3",
            "series": "Observed outcome"
          },
          {
            "x": "475",
            "y": "5.66888381276127",
            "series": "Forest prediction"
          },
          {
            "x": "476",
            "y": "4.11",
            "series": "Observed outcome"
          },
          {
            "x": "476",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "477",
            "y": "7.21",
            "series": "Observed outcome"
          },
          {
            "x": "477",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "478",
            "y": "3.25",
            "series": "Observed outcome"
          },
          {
            "x": "478",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "479",
            "y": "8.52",
            "series": "Observed outcome"
          },
          {
            "x": "479",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "480",
            "y": "10.68",
            "series": "Observed outcome"
          },
          {
            "x": "480",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "481",
            "y": "8.01",
            "series": "Observed outcome"
          },
          {
            "x": "481",
            "y": "5.66888381276127",
            "series": "Forest prediction"
          },
          {
            "x": "482",
            "y": "7.9",
            "series": "Observed outcome"
          },
          {
            "x": "482",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "483",
            "y": "5.31",
            "series": "Observed outcome"
          },
          {
            "x": "483",
            "y": "6.08487256879198",
            "series": "Forest prediction"
          },
          {
            "x": "484",
            "y": "4.86",
            "series": "Observed outcome"
          },
          {
            "x": "484",
            "y": "6.08487256879198",
            "series": "Forest prediction"
          },
          {
            "x": "485",
            "y": "6.25",
            "series": "Observed outcome"
          },
          {
            "x": "485",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "486",
            "y": "7",
            "series": "Observed outcome"
          },
          {
            "x": "486",
            "y": "6.08487256879198",
            "series": "Forest prediction"
          },
          {
            "x": "487",
            "y": "4.8",
            "series": "Observed outcome"
          },
          {
            "x": "487",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "488",
            "y": "7.23",
            "series": "Observed outcome"
          },
          {
            "x": "488",
            "y": "6.08487256879198",
            "series": "Forest prediction"
          },
          {
            "x": "489",
            "y": "12.02",
            "series": "Observed outcome"
          },
          {
            "x": "489",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "490",
            "y": "4.81",
            "series": "Observed outcome"
          },
          {
            "x": "490",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "491",
            "y": "4.5",
            "series": "Observed outcome"
          },
          {
            "x": "491",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "492",
            "y": "2.75",
            "series": "Observed outcome"
          },
          {
            "x": "492",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "493",
            "y": "3.5",
            "series": "Observed outcome"
          },
          {
            "x": "493",
            "y": "7.75766205450734",
            "series": "Forest prediction"
          },
          {
            "x": "494",
            "y": "2.5",
            "series": "Observed outcome"
          },
          {
            "x": "494",
            "y": "4.65384944083265",
            "series": "Forest prediction"
          },
          {
            "x": "495",
            "y": "5.78",
            "series": "Observed outcome"
          },
          {
            "x": "495",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "496",
            "y": "4.82",
            "series": "Observed outcome"
          },
          {
            "x": "496",
            "y": "5.66888381276127",
            "series": "Forest prediction"
          },
          {
            "x": "497",
            "y": "1.45",
            "series": "Observed outcome"
          },
          {
            "x": "497",
            "y": "4.65384944083265",
            "series": "Forest prediction"
          },
          {
            "x": "498",
            "y": "9.62",
            "series": "Observed outcome"
          },
          {
            "x": "498",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "499",
            "y": "2.3",
            "series": "Observed outcome"
          },
          {
            "x": "499",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "500",
            "y": "4.5",
            "series": "Observed outcome"
          },
          {
            "x": "500",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "501",
            "y": "7.5",
            "series": "Observed outcome"
          },
          {
            "x": "501",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "502",
            "y": "3.88",
            "series": "Observed outcome"
          },
          {
            "x": "502",
            "y": "4.86192429463382",
            "series": "Forest prediction"
          },
          {
            "x": "503",
            "y": "2.35",
            "series": "Observed outcome"
          },
          {
            "x": "503",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "504",
            "y": "4",
            "series": "Observed outcome"
          },
          {
            "x": "504",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "505",
            "y": "3.8",
            "series": "Observed outcome"
          },
          {
            "x": "505",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "506",
            "y": "5.96",
            "series": "Observed outcome"
          },
          {
            "x": "506",
            "y": "6.08487256879198",
            "series": "Forest prediction"
          },
          {
            "x": "507",
            "y": "8.6",
            "series": "Observed outcome"
          },
          {
            "x": "507",
            "y": "6.08487256879198",
            "series": "Forest prediction"
          },
          {
            "x": "508",
            "y": "3.2",
            "series": "Observed outcome"
          },
          {
            "x": "508",
            "y": "4.65384944083265",
            "series": "Forest prediction"
          },
          {
            "x": "509",
            "y": "1.9",
            "series": "Observed outcome"
          },
          {
            "x": "509",
            "y": "4.65384944083265",
            "series": "Forest prediction"
          },
          {
            "x": "510",
            "y": "5.38",
            "series": "Observed outcome"
          },
          {
            "x": "510",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "511",
            "y": "10.26",
            "series": "Observed outcome"
          },
          {
            "x": "511",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "512",
            "y": "3.5",
            "series": "Observed outcome"
          },
          {
            "x": "512",
            "y": "5.21006007672534",
            "series": "Forest prediction"
          },
          {
            "x": "513",
            "y": "3.1",
            "series": "Observed outcome"
          },
          {
            "x": "513",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "514",
            "y": "4.79",
            "series": "Observed outcome"
          },
          {
            "x": "514",
            "y": "6.08487256879198",
            "series": "Forest prediction"
          },
          {
            "x": "515",
            "y": "4.23",
            "series": "Observed outcome"
          },
          {
            "x": "515",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "516",
            "y": "5.29",
            "series": "Observed outcome"
          },
          {
            "x": "516",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "517",
            "y": "3.81",
            "series": "Observed outcome"
          },
          {
            "x": "517",
            "y": "5.62604883275605",
            "series": "Forest prediction"
          },
          {
            "x": "518",
            "y": "2.6",
            "series": "Observed outcome"
          },
          {
            "x": "518",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "519",
            "y": "2.5",
            "series": "Observed outcome"
          },
          {
            "x": "519",
            "y": "4.86192429463382",
            "series": "Forest prediction"
          },
          {
            "x": "520",
            "y": "3",
            "series": "Observed outcome"
          },
          {
            "x": "520",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "521",
            "y": "3.75",
            "series": "Observed outcome"
          },
          {
            "x": "521",
            "y": "5.21006007672534",
            "series": "Forest prediction"
          },
          {
            "x": "522",
            "y": "4.57",
            "series": "Observed outcome"
          },
          {
            "x": "522",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "523",
            "y": "6.5",
            "series": "Observed outcome"
          },
          {
            "x": "523",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "524",
            "y": "4",
            "series": "Observed outcome"
          },
          {
            "x": "524",
            "y": "4.65384944083265",
            "series": "Forest prediction"
          },
          {
            "x": "525",
            "y": "7.34",
            "series": "Observed outcome"
          },
          {
            "x": "525",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "526",
            "y": "5.77",
            "series": "Observed outcome"
          },
          {
            "x": "526",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "527",
            "y": "3.64",
            "series": "Observed outcome"
          },
          {
            "x": "527",
            "y": "6.08487256879198",
            "series": "Forest prediction"
          },
          {
            "x": "528",
            "y": "3.8",
            "series": "Observed outcome"
          },
          {
            "x": "528",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "529",
            "y": "2.57",
            "series": "Observed outcome"
          },
          {
            "x": "529",
            "y": "6.08487256879198",
            "series": "Forest prediction"
          },
          {
            "x": "530",
            "y": "4.33",
            "series": "Observed outcome"
          },
          {
            "x": "530",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "531",
            "y": "4.33",
            "series": "Observed outcome"
          },
          {
            "x": "531",
            "y": "5.21006007672534",
            "series": "Forest prediction"
          },
          {
            "x": "532",
            "y": "3.75",
            "series": "Observed outcome"
          },
          {
            "x": "532",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "533",
            "y": "8.48",
            "series": "Observed outcome"
          },
          {
            "x": "533",
            "y": "6.08487256879198",
            "series": "Forest prediction"
          },
          {
            "x": "534",
            "y": "6.49",
            "series": "Observed outcome"
          },
          {
            "x": "534",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "535",
            "y": "5.92",
            "series": "Observed outcome"
          },
          {
            "x": "535",
            "y": "7.75766205450734",
            "series": "Forest prediction"
          },
          {
            "x": "536",
            "y": "9.62",
            "series": "Observed outcome"
          },
          {
            "x": "536",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "537",
            "y": "3.59",
            "series": "Observed outcome"
          },
          {
            "x": "537",
            "y": "6.08487256879198",
            "series": "Forest prediction"
          },
          {
            "x": "538",
            "y": "4.62",
            "series": "Observed outcome"
          },
          {
            "x": "538",
            "y": "6.08487256879198",
            "series": "Forest prediction"
          },
          {
            "x": "539",
            "y": "3",
            "series": "Observed outcome"
          },
          {
            "x": "539",
            "y": "5.21006007672534",
            "series": "Forest prediction"
          },
          {
            "x": "540",
            "y": "3.5",
            "series": "Observed outcome"
          },
          {
            "x": "540",
            "y": "5.21006007672534",
            "series": "Forest prediction"
          },
          {
            "x": "541",
            "y": "2.75",
            "series": "Observed outcome"
          },
          {
            "x": "541",
            "y": "5.62604883275605",
            "series": "Forest prediction"
          },
          {
            "x": "542",
            "y": "1.63",
            "series": "Observed outcome"
          },
          {
            "x": "542",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "543",
            "y": "5.65",
            "series": "Observed outcome"
          },
          {
            "x": "543",
            "y": "4.65384944083265",
            "series": "Forest prediction"
          },
          {
            "x": "544",
            "y": "6.42",
            "series": "Observed outcome"
          },
          {
            "x": "544",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "545",
            "y": "4",
            "series": "Observed outcome"
          },
          {
            "x": "545",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "546",
            "y": "4.45",
            "series": "Observed outcome"
          },
          {
            "x": "546",
            "y": "4.65384944083265",
            "series": "Forest prediction"
          },
          {
            "x": "547",
            "y": "4.19",
            "series": "Observed outcome"
          },
          {
            "x": "547",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "548",
            "y": "3.8",
            "series": "Observed outcome"
          },
          {
            "x": "548",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "549",
            "y": "7.69",
            "series": "Observed outcome"
          },
          {
            "x": "549",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "550",
            "y": "4.75",
            "series": "Observed outcome"
          },
          {
            "x": "550",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "551",
            "y": "2.6",
            "series": "Observed outcome"
          },
          {
            "x": "551",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "552",
            "y": "8.03",
            "series": "Observed outcome"
          },
          {
            "x": "552",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "553",
            "y": "4.17",
            "series": "Observed outcome"
          },
          {
            "x": "553",
            "y": "4.65384944083265",
            "series": "Forest prediction"
          },
          {
            "x": "554",
            "y": "2.65",
            "series": "Observed outcome"
          },
          {
            "x": "554",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "555",
            "y": "5.6",
            "series": "Observed outcome"
          },
          {
            "x": "555",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "556",
            "y": "2.25",
            "series": "Observed outcome"
          },
          {
            "x": "556",
            "y": "4.86192429463382",
            "series": "Forest prediction"
          },
          {
            "x": "557",
            "y": "5.77",
            "series": "Observed outcome"
          },
          {
            "x": "557",
            "y": "5.66888381276127",
            "series": "Forest prediction"
          },
          {
            "x": "558",
            "y": "4.06",
            "series": "Observed outcome"
          },
          {
            "x": "558",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "559",
            "y": "5.77",
            "series": "Observed outcome"
          },
          {
            "x": "559",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "560",
            "y": "7.27",
            "series": "Observed outcome"
          },
          {
            "x": "560",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "561",
            "y": "3.85",
            "series": "Observed outcome"
          },
          {
            "x": "561",
            "y": "7.75766205450734",
            "series": "Forest prediction"
          },
          {
            "x": "562",
            "y": "2.5",
            "series": "Observed outcome"
          },
          {
            "x": "562",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "563",
            "y": "4.32",
            "series": "Observed outcome"
          },
          {
            "x": "563",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "564",
            "y": "3.31",
            "series": "Observed outcome"
          },
          {
            "x": "564",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "565",
            "y": "3.85",
            "series": "Observed outcome"
          },
          {
            "x": "565",
            "y": "5.66888381276127",
            "series": "Forest prediction"
          },
          {
            "x": "566",
            "y": "8.01",
            "series": "Observed outcome"
          },
          {
            "x": "566",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "567",
            "y": "3.61",
            "series": "Observed outcome"
          },
          {
            "x": "567",
            "y": "4.86192429463382",
            "series": "Forest prediction"
          },
          {
            "x": "568",
            "y": "4.86",
            "series": "Observed outcome"
          },
          {
            "x": "568",
            "y": "6.08487256879198",
            "series": "Forest prediction"
          },
          {
            "x": "569",
            "y": "4.48",
            "series": "Observed outcome"
          },
          {
            "x": "569",
            "y": "6.08487256879198",
            "series": "Forest prediction"
          },
          {
            "x": "570",
            "y": "2.6",
            "series": "Observed outcome"
          },
          {
            "x": "570",
            "y": "5.21006007672534",
            "series": "Forest prediction"
          },
          {
            "x": "571",
            "y": "2.5",
            "series": "Observed outcome"
          },
          {
            "x": "571",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "572",
            "y": "1.92",
            "series": "Observed outcome"
          },
          {
            "x": "572",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "573",
            "y": "3.53",
            "series": "Observed outcome"
          },
          {
            "x": "573",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "574",
            "y": "9.73",
            "series": "Observed outcome"
          },
          {
            "x": "574",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "575",
            "y": "4",
            "series": "Observed outcome"
          },
          {
            "x": "575",
            "y": "4.86192429463382",
            "series": "Forest prediction"
          },
          {
            "x": "576",
            "y": "4.38",
            "series": "Observed outcome"
          },
          {
            "x": "576",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "577",
            "y": "2.45",
            "series": "Observed outcome"
          },
          {
            "x": "577",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "578",
            "y": "2.89",
            "series": "Observed outcome"
          },
          {
            "x": "578",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "579",
            "y": "6.25",
            "series": "Observed outcome"
          },
          {
            "x": "579",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "580",
            "y": "4.35",
            "series": "Observed outcome"
          },
          {
            "x": "580",
            "y": "4.65384944083265",
            "series": "Forest prediction"
          },
          {
            "x": "581",
            "y": "2.88",
            "series": "Observed outcome"
          },
          {
            "x": "581",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "582",
            "y": "2.45",
            "series": "Observed outcome"
          },
          {
            "x": "582",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "583",
            "y": "5.53",
            "series": "Observed outcome"
          },
          {
            "x": "583",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "584",
            "y": "2.5",
            "series": "Observed outcome"
          },
          {
            "x": "584",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "585",
            "y": "5.13",
            "series": "Observed outcome"
          },
          {
            "x": "585",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "586",
            "y": "5.42",
            "series": "Observed outcome"
          },
          {
            "x": "586",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "587",
            "y": "3.75",
            "series": "Observed outcome"
          },
          {
            "x": "587",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "588",
            "y": "5",
            "series": "Observed outcome"
          },
          {
            "x": "588",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "589",
            "y": "8.57",
            "series": "Observed outcome"
          },
          {
            "x": "589",
            "y": "4.65384944083265",
            "series": "Forest prediction"
          },
          {
            "x": "590",
            "y": "8.08",
            "series": "Observed outcome"
          },
          {
            "x": "590",
            "y": "6.08487256879198",
            "series": "Forest prediction"
          },
          {
            "x": "591",
            "y": "9.62",
            "series": "Observed outcome"
          },
          {
            "x": "591",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "592",
            "y": "1.23",
            "series": "Observed outcome"
          },
          {
            "x": "592",
            "y": "4.65384944083265",
            "series": "Forest prediction"
          },
          {
            "x": "593",
            "y": "2.25",
            "series": "Observed outcome"
          },
          {
            "x": "593",
            "y": "4.86192429463382",
            "series": "Forest prediction"
          },
          {
            "x": "594",
            "y": "5.39",
            "series": "Observed outcome"
          },
          {
            "x": "594",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "595",
            "y": "2.5",
            "series": "Observed outcome"
          },
          {
            "x": "595",
            "y": "4.86192429463382",
            "series": "Forest prediction"
          },
          {
            "x": "596",
            "y": "3.66",
            "series": "Observed outcome"
          },
          {
            "x": "596",
            "y": "6.08487256879198",
            "series": "Forest prediction"
          },
          {
            "x": "597",
            "y": "4.63",
            "series": "Observed outcome"
          },
          {
            "x": "597",
            "y": "4.86192429463382",
            "series": "Forest prediction"
          },
          {
            "x": "598",
            "y": "6.25",
            "series": "Observed outcome"
          },
          {
            "x": "598",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "599",
            "y": "3",
            "series": "Observed outcome"
          },
          {
            "x": "599",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "600",
            "y": "3",
            "series": "Observed outcome"
          },
          {
            "x": "600",
            "y": "4.65384944083265",
            "series": "Forest prediction"
          },
          {
            "x": "601",
            "y": "2.63",
            "series": "Observed outcome"
          },
          {
            "x": "601",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "602",
            "y": "3.85",
            "series": "Observed outcome"
          },
          {
            "x": "602",
            "y": "6.24510983868926",
            "series": "Forest prediction"
          },
          {
            "x": "603",
            "y": "4.7",
            "series": "Observed outcome"
          },
          {
            "x": "603",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          },
          {
            "x": "604",
            "y": "5",
            "series": "Observed outcome"
          },
          {
            "x": "604",
            "y": "5.32074803066975",
            "series": "Forest prediction"
          }
        ],
        "plotFile": "ml09-fixed-results/realdata-person-r/plot.svg",
        "plotSHA256": "2260872198fb170d1fbb4a4099ed5e7ddaa4f1de9970fd63221a122d6b968fa2",
        "files": [
          {
            "file": "ml09-fixed-results/realdata-person-r/full-result.Rtext",
            "sha256": "2653ee79d5b0a94d1d07080f98686fce4e1bf705e245c4c707d69653cb2722f9"
          },
          {
            "file": "ml09-fixed-results/realdata-person-r/plot-points.csv",
            "sha256": "beaa5bec1209378e8355d02d4e2d291ce41c8e362b6d561d5bb5ced8d03380aa"
          },
          {
            "file": "ml09-fixed-results/realdata-person-r/plot.svg",
            "sha256": "2260872198fb170d1fbb4a4099ed5e7ddaa4f1de9970fd63221a122d6b968fa2"
          },
          {
            "file": "ml09-fixed-results/realdata-person-r/summary.csv",
            "sha256": "d6a050272b4116f834da92317b50064ada76a076770ad2e859ebd3bc05047958"
          }
        ],
        "scope": "Actually executed self-contained fixed example; current web controls execute separately. Python Fraction and finite-precision base R. Author gate, not independent peer."
      },
      "company": {
        "api": "realdata",
        "variant": "company",
        "language": "r",
        "codeFile": "ml09-code/realdata-company.R",
        "codeSHA256": "6fc2a5a42b067c11c6645318241fb8713e1d27764574449ad369311645eeb1bc",
        "codeText": "# ML09 base-R reproduction from native original-field CSVs.\n# Rscript ml09-public-analysis.R ml09-sources results-r\n# Separately written vectorized direct-centered squared/Gini losses.\n# No Python/JS/model-contract/stored-answer/derived-result reader or package.\n# Numeric arithmetic is binary64:1e-12 relative tie tolerance stabilizes exact\n# source ties,but does not certify tiny margins/underflow like Fraction JS/Python.\n# Data-frame rows use x0,x1,...,y,weight; original IDs remain attached to draws.\noptions(stringsAsFactors=FALSE,digits=17)\nnum<-function(v){if(is.null(v)||length(v)!=1||is.na(v))stop('numeric parameter required, not explicit NULL');p<-strsplit(as.character(v),'/',fixed=TRUE)[[1]];z<-if(length(p)==2)as.numeric(p[1])/as.numeric(p[2])else as.numeric(v);if(!is.finite(z))stop('finite numeric parameter');z}\noption<-function(a,k,default){if(k%in%names(a))a[[k]]else default}\nnormrows<-function(d,task){if(!'weight'%in%names(d))d$weight<-1;if(!'id'%in%names(d))d$id<-as.character(seq_len(nrow(d))-1);d$weight<-as.numeric(d$weight);if(anyNA(d$weight)||any(d$weight<0))stop('nonnegative weights');if(task=='regression')d$y<-as.numeric(d$y)else d$y<-as.character(d$y);d}\nstat<-function(d,task,classes){W<-sum(d$weight);mu<-if(task=='regression'&&W)sum(d$weight*d$y)/W else NA_real_;p<-if(task=='classification'&&W)vapply(classes,function(c)sum(d$weight[d$y==c])/W,0)else numeric();risk<-if(task=='regression'&&W)sum(d$weight*(d$y-mu)^2)else W*sum(p*(1-p));list(n=nrow(d),w=W,mu=mu,p=unname(p),risk=risk,pred=if(task=='regression')mu else if(W)classes[which.max(p)]else NA_character_)}\nfit<-function(d,a,task,classes,schedule=NULL){d<-d[d$weight>0&!is.na(d$y),,drop=FALSE];if(!nrow(d))stop('positive observed training');W<-sum(d$weight);depth<-option(a,'maxDepth',2);minimum<-option(a,'minLeaf',1);minmass<-num(option(a,'minLeafWeight',0));mingain<-num(option(a,'minGain',0));route<-option(a,'missingRoute','best');features<-grep('^x[0-9]+$',names(d),value=TRUE)\n build<-function(rr,level,path){st<-stat(rr,task,classes);node<-list(rows=rr,st=st,split=NULL,left=NULL,right=NULL,path=path);if(level==depth)return(node);best<-NULL;allowed<-if(is.null(schedule))seq_along(features)-1L else schedule[[match(path,names(schedule))]]\n  for(j in seq_along(features)-1L){if(!j%in%allowed)next;v<-rr[[features[j+1L]]];values<-sort(unique(v[!is.na(v)]));candidates<-list()\n   if(length(values)>1)for(k in seq_len(length(values)-1L)){threshold<-(values[k]+values[k+1L])/2;missing<-is.na(v);left<-!missing&v<=threshold;right<-!missing&v>threshold;directions<-if(route!='best')route else if(any(missing))c('left','right')else if(sum(left)>=sum(right))'left'else'right';for(direction in directions)candidates[[length(candidates)+1L]]<-list(kind='threshold',threshold=threshold,missingRoute=direction,left=if(direction=='left')left|missing else left,right=if(direction=='right')right|missing else right)}\n   if(anyNA(v)&&any(!is.na(v)))candidates[[length(candidates)+1L]]<-list(kind='missing-only',threshold=NA_real_,missingRoute='left',left=is.na(v),right=!is.na(v))\n   for(candidate in candidates){l<-rr[candidate$left,,drop=FALSE];r<-rr[candidate$right,,drop=FALSE];ls<-stat(l,task,classes);rs<-stat(r,task,classes);if(min(ls$n,rs$n)<minimum||min(ls$w,rs$w)<minmass||min(ls$w,rs$w)<=0)next;gain<-(st$risk-ls$risk-rs$risk)/W;tol<-1e-12*max(1,abs(gain),if(is.null(best))0 else abs(best$gain));if(is.null(best)||gain>best$gain+tol)best<-c(candidate,list(feature=j,gain=gain,l=l,r=r))}\n  }\n  if(!is.null(best)&&best$gain>max(mingain,1e-12)){node$split<-best;node$left<-build(best$l,level+1L,paste0(path,'L'));node$right<-build(best$r,level+1L,paste0(path,'R'))};node\n };build(d,0L,'')\n}\npredict_one<-function(tree,row){n<-tree;while(!is.null(n$split)){s<-n$split;v<-as.numeric(row[[paste0('x',s$feature)]]);left<-if(s$kind=='missing-only')is.na(v)else if(is.na(v))s$missingRoute=='left'else v<=s$threshold;n<-if(left)n$left else n$right};list(prediction=n$st$pred,probabilities=n$st$p)}\ncombine<-function(pp,w,task,classes,mode='probabilities'){W<-sum(w);if(!length(pp)||!W)return(list(prediction=if(task=='regression')NA_real_ else NA_character_,probabilities=numeric(),vote=NA_character_,prob=NA_character_));if(task=='regression')return(list(prediction=sum(vapply(pp,function(p)p$prediction,0)*w)/W,probabilities=numeric(),vote=NA_character_,prob=NA_character_));votes<-vapply(classes,function(c)sum(w[vapply(pp,function(p)p$prediction==c,FALSE)])/W,0);probs<-vapply(seq_along(classes),function(j)sum(vapply(pp,function(p)p$probabilities[j],0)*w)/W,0);vote<-classes[which.max(votes)];prob<-classes[which.max(probs)];list(prediction=if(mode=='votes')vote else prob,probabilities=unname(probs),vote=vote,prob=prob,votes=unname(votes))}\nvariance<-function(a){B<-num(a$B);v<-num(a$marginalVariance);rho<-num(option(a,'rho',0));if(B<1||B!=floor(B)||v<0)stop('integer B/nonnegative variance');if(B>1&&v>0&&(rho< -1/(B-1)||rho>1))stop('PSD correlation');list(B=B,marginalVariance=v,correlationApplicable=B>1&&v>0,varianceOfMean=if(B==1)v else v*(1+(B-1)*rho)/B)}\naggregate<-function(a){task<-option(a,'task','regression');classes<-option(a,'classes',character());w<-vapply(option(a,'memberWeights',as.list(rep(1,length(a$members)))),num,0);if(any(w<0)||sum(w)<=0)stop('positive member mass');ids<-a$members[[1]]$predictions$id;pp<-lapply(ids,function(id){members<-lapply(a$members,function(m){r<-m$predictions[match(id,m$predictions$id),,drop=FALSE];if(task=='regression')list(prediction=num(r$value),probabilities=numeric())else list(prediction=as.character(r$label),probabilities=as.numeric(r[paste0('p',seq_along(classes)-1L)]))});c(list(id=id),combine(members,w,task,classes,option(a,'aggregation','probabilities')))});list(task=task,classes=classes,predictions=pp)}\nscored<-function(preds,d,task,classes){W<-loss<-absolute<-errors<-voteerrors<-0;count<-0L;out<-lapply(seq_len(nrow(d)),function(i){r<-d[i,,drop=FALSE];p<-preds[[i]];ok<-!is.na(p$prediction)&&!is.na(r$y)&&r$weight>0;value<-NA_real_;if(ok){count<<-count+1L;W<<-W+r$weight;if(task=='regression'){e<-r$y-p$prediction;value<-e*e;absolute<<-absolute+r$weight*abs(e)}else{value<-sum((p$probabilities-as.numeric(classes==r$y))^2);errors<<-errors+r$weight*(p$prediction!=r$y);voteerrors<<-voteerrors+r$weight*(p$vote!=r$y)};loss<<-loss+r$weight*value};c(p,list(actual=r$y,weight=r$weight,scoreEligible=ok,loss=value))});list(rows=out,eligibleRows=count,weight=W,totalLoss=loss,meanLoss=if(W)loss/W else NA_real_,MAE=if(W&&task=='regression')absolute/W else NA_real_,errorRate=if(W&&task=='classification')errors/W else NA_real_,labelVoteErrorRate=if(W&&task=='classification')voteerrors/W else NA_real_)}\nensemble<-function(a,forest=FALSE){task<-option(a,'task','regression');classes<-option(a,'classes',character());d<-normrows(a$rows,task);w<-vapply(option(a,'memberWeights',as.list(rep(1,length(a$bootstrapDraws)))),num,0);if(any(w<0)||sum(w)<=0)stop('positive member mass');members<-lapply(seq_along(a$bootstrapDraws),function(i){draw<-a$bootstrapDraws[[i]];indices<-match(draw,d$id);if(anyNA(indices))stop('unknown draw source');tree<-fit(d[indices,,drop=FALSE],a,task,classes,if(forest)a$nodeFeatures[[i]]else NULL);list(tree=tree,draw=draw,inbag=unique(draw),weight=w[i])});queries<-a$queries;preds<-lapply(seq_len(nrow(queries)),function(i)c(list(id=queries$id[i]),combine(lapply(members,function(m)predict_one(m$tree,queries[i,,drop=FALSE])),w,task,classes,option(a,'aggregation','probabilities'))));oob<-lapply(seq_len(nrow(d)),function(i){app<-which(!vapply(members,function(m)d$id[i]%in%m$inbag,FALSE));pp<-combine(lapply(app,function(j)predict_one(members[[j]]$tree,d[i,,drop=FALSE])),w[app],task,classes,option(a,'aggregation','probabilities'));c(list(id=d$id[i],applicable=app-1L,positiveMembers=sum(w[app]>0)),pp)});list(task=task,classes=classes,members=members,predictions=preds,outOfBag=scored(oob,d,task,classes))}\nboost<-function(a){if(option(a,'task','regression')!='regression')stop('regression boosting only');d<-normrows(a$rows,'regression');eligible<-d$weight>0&!is.na(d$y);W<-sum(d$weight[eligible]);if(!W)stop('positive eligible training');eta<-num(option(a,'learningRate','1/2'));stages<-option(a,'stages',3);if(is.null(stages)||stages!=floor(stages)||stages<0||stages>8||eta<0||eta>1)stop('supported rate/stages');initial<-if('initial'%in%names(a))num(a$initial)else sum(d$weight[eligible]*d$y[eligible])/W;train<-matrix(initial,nrow(d),stages+1L);query<-matrix(initial,nrow(a$queries),stages+1L);losses<-fits<-list();for(stage in 0:stages){sse<-sum(d$weight[eligible]*(d$y[eligible]-train[eligible,stage+1L])^2);losses[[stage+1L]]<-list(stage=stage,rawWeightedSSE=sse,MSE=sse/W,meanHalfSquaredLoss=sse/(2*W));if(stage==stages)break;residual<-d;residual$y<-d$y-train[,stage+1L];tree<-fit(residual,a,'regression',character());h<-vapply(seq_len(nrow(d)),function(i)predict_one(tree,d[i,,drop=FALSE])$prediction,0);qh<-vapply(seq_len(nrow(a$queries)),function(i)predict_one(tree,a$queries[i,,drop=FALSE])$prediction,0);stageRows<-lapply(seq_len(nrow(d)),function(i)list(id=d$id[i],before=train[i,stage+1L],residual=residual$y[i],negativeCoordinateDerivative=d$weight[i]*residual$y[i]/W,fit=h[i],addition=eta*h[i],after=train[i,stage+1L]+eta*h[i]));train[,stage+2L]<-train[,stage+1L]+eta*h;query[,stage+2L]<-query[,stage+1L]+eta*qh;norm<-sum(d$weight[eligible]*h[eligible]^2);fits[[stage+1L]]<-list(stage=stage+1L,tree=tree,rows=stageRows,queryFits=qh,norm=norm,predictedSSEDecrease=eta*(2-eta)*norm)};list(task='regression',initial=initial,learningRate=eta,stages=stages,training=train,queries=query,fits=fits,losses=losses,predictions=lapply(seq_len(nrow(a$queries)),function(i)list(id=a$queries$id[i],prediction=query[i,stages+1L],probabilities=numeric(),vote=NA_character_,prob=NA_character_)))}\nfixed_schedules<-function(ids,p,seed){state<-seed;choose<-function(n){limit<-floor(4294967296/n)*n;repeat{state<<-(1664525*state+1013904223)%%4294967296;if(state<limit)return(as.integer(state%%n))}};draws<-schedules<-list();for(member in 1:4){draws[[member]]<-vapply(seq_along(ids),function(i)ids[choose(length(ids))+1L],'');schedule<-setNames(vector('list',7),c('','L','R','LL','LR','RL','RR'));for(path in names(schedule)){order<-seq_len(p)-1L;if(p>1)for(j in seq(p-1L,1L)){k<-choose(j+1L);temp<-order[j+1L];order[j+1L]<-order[k+1L];order[k+1L]<-temp};schedule[[match(path,names(schedule))]]<-sort(order[seq_len(max(1L,floor(sqrt(p))))])};schedules[[member]]<-schedule};list(draws=draws,schedules=schedules)}\nread_sources<-function(src){read<-function(name)read.csv(file.path(src,name),check.names=FALSE,colClasses='character',na.strings=character(),fileEncoding='UTF-8-BOM');raw<-read('actual320-country-four-indicators-original-2020-2024.csv');country<-do.call(rbind,lapply(sort(unique(raw$countryISO3)),function(code)do.call(rbind,lapply(2020:2024,function(year){keys<-c('NY.GDP.PCAP.KD','NY.GDP.MKTP.KD.ZG','FP.CPI.TOTL.ZG','SP.DYN.LE00.IN');v<-vapply(keys,function(k)as.numeric(raw$originalValueToken[raw$countryISO3==code&raw$date==as.character(year)&raw$indicatorID==k]),0);data.frame(id=paste0(code,':',year),sourceRow=paste0(code,':',year),originalID=code,year=year,x0=v[1]/10000,x1=v[2],x2=v[3],y=v[4],weight=1,role=if(anyNA(v))'excluded'else if(year==2024)'outer-test'else'train')}))));raw<-read('actual3613-NLS-original52-fields-and-selection.csv');i<-seq_len(nrow(raw));x0<-suppressWarnings(as.numeric(raw$ed76));x1<-suppressWarnings(as.numeric(raw$age76));y<-suppressWarnings(as.numeric(raw$wage76))/100;person<-data.frame(id=paste0('person:',i),sourceRow=as.character(i),originalID=raw$id,x0=x0,x1=x1,y=y,weight=1,role=ifelse(is.na(x0)|is.na(x1)|is.na(y),'excluded',ifelse(i%%5==0,'outer-test','train')));raw<-read('actual3150-churn-original14-fields-and-selection.csv');i<-seq_len(nrow(raw));company<-data.frame(id=paste0('customer:',i),sourceRow=as.character(i),originalID='',x0=as.numeric(raw[['Call  Failure']]),x1=as.numeric(raw[['Subscription  Length']]),x2=as.numeric(raw[['Charge  Amount']]),y=raw$Churn,weight=1,role=ifelse(i%%5==0,'outer-test','train'));models<-list();for(index in 1:3){kind<-c('country','person','company')[index];d<-list(country,person,company)[[index]];task<-if(kind=='company')'classification'else'regression';s<-fixed_schedules(d$id[d$role=='train'],if(kind=='person')2L else 3L,20261102+7919*(index-1L));models[[kind]]<-list(records=d,task=task,classes=if(task=='classification')c('0','1')else character(),draws=s$draws,schedules=s$schedules,minLeaf=c(4L,50L,30L)[index])};models}\nrealdata<-function(models,kind,options=list()){if(is.null(options)||!is.list(options))stop('options object');m<-models[[kind]];d<-m$records;train<-d[d$role=='train',,drop=FALSE];test<-d[d$role=='outer-test',,drop=FALSE];method<-option(options,'method','forest');depth<-option(options,'maxDepth',2);count<-option(options,'memberCount',3);if(!method%in%c('bagging','forest','boost'))stop('known method');a<-list(rows=train,queries=test,task=m$task,classes=m$classes,maxDepth=depth,minLeaf=option(options,'minLeaf',m$minLeaf),minLeafWeight=0,minGain=0,missingRoute='best',learningRate=option(options,'learningRate','1/2'),stages=option(options,'stages',3));if(method=='boost')result<-boost(a)else{a$bootstrapDraws<-m$draws[seq_len(count)];a$nodeFeatures<-lapply(m$schedules[seq_len(count)],function(s)s[nchar(names(s))<depth]);result<-ensemble(a,method=='forest')};outer<-scored(result$predictions,normrows(test,m$task),m$task,m$classes);st<-stat(normrows(train,m$task),m$task,m$classes);constant<-list(prediction=st$pred,probabilities=st$p,vote=st$pred,prob=st$pred);baseline<-scored(lapply(test$id,function(id)c(list(id=id),constant)),normrows(test,m$task),m$task,m$classes);list(kind=kind,method=method,settings=a,train=train,test=test,result=result,outer=outer,baseline=baseline)}\nAPI<-\"realdata\"\nINPUT<-list(kind=\"company\")\n\nrun_fixed<-function(api,a,out,src){\n r<-if(api=='variance')variance(a)else if(api=='aggregate')aggregate(a)else if(api%in%c('bagging','forest'))ensemble(a,api=='forest')else if(api=='boost')boost(a)else realdata(read_sources(src),a$kind)\n dir.create(out,recursive=TRUE,showWarnings=FALSE);summary<-list();points<-list();add<-function(x,y,s){if(!is.null(y)&&!is.na(y))points[[length(points)+1L]]<<-data.frame(x=x,y=as.numeric(y),series=s)}\n if(api=='variance'){summary<-r[c('B','varianceOfMean')];add(r$B,r$varianceOfMean,'Specified finite-B variance');xl<-'Number of members B';yl<-'Variance, stipulated units squared';title<-'Declared covariance model, not fitted trees'\n }else if(api=='aggregate'){p<-r$predictions[[1]];summary<-list(selectedPrediction=p$prediction);classification<-identical(a$task,'classification');if(classification){summary<-c(summary,list(voteLabel=p$vote,probabilityLabel=p$prob,meanProbability1=p$probabilities[2]));add(1,p$probabilities[2],'Mean probability of class 1');add(2,p$votes[2],'Label-vote share of class 1');xl<-'Aggregation (1=probability, 2=vote)';yl<-'Probability or vote share'}else{for(i in seq_along(a$members))add(i,num(a$members[[i]]$predictions$value[1]),'Member prediction');add(3,p$prediction,'Weighted mean');xl<-'Member 1, member 2, aggregate 3';yl<-'Prediction, assumed units'};title<-'Votes and probabilities are distinct objects'\n }else if(api%in%c('bagging','forest')){summary<-list(queryPrediction=r$predictions[[1]]$prediction,OOB.scoreable=r$outOfBag$eligibleRows,OOB.meanLoss=r$outOfBag$meanLoss);for(i in seq_len(nrow(a$rows)))add(i,a$rows$y[i],'Observed training outcome');for(i in seq_along(r$outOfBag$rows))add(i,r$outOfBag$rows[[i]]$prediction,'OOB prediction, when defined');xl<-'Original training ID order';yl<-'Outcome, assumed units';title<-'Repeated draws and ID-level OOB membership'\n }else if(api=='boost'){summary<-list(initial=r$initial,finalMSE=r$losses[[length(r$losses)]]$MSE,stages=r$stages);for(v in r$losses)add(v$stage,v$MSE,'Training MSE');xl<-'Boosting stage (0=initial)';yl<-'Weighted MSE, outcome units squared';title<-'Training descent does not certify held-out gain'\n }else{summary<-list(outer.scoreable=r$outer$eligibleRows,outer.meanLoss=r$outer$meanLoss,baseline.meanLoss=r$baseline$meanLoss,OOB.scoreable=r$result$outOfBag$eligibleRows,OOB.meanLoss=r$result$outOfBag$meanLoss);for(i in seq_along(r$outer$rows)){p<-r$outer$rows[[i]];add(i,as.numeric(p$actual),'Observed outcome');add(i,if(a$kind=='company')p$probabilities[2]else p$prediction,if(a$kind=='company')'Forest probability of class 1'else'Forest prediction')};xl<-'Outer-test source order, not a time path';yl<-if(a$kind=='company')'Churn label / probability'else if(a$kind=='country')'Period life expectancy, years'else'Nominal 1976 USD per hour';title<-'Fixed forest; outer labels did not fit the trees'}\n display<-function(v)if(is.null(v)||is.na(v))'undefined'else sprintf('%.9f',as.numeric(v));write.csv(data.frame(metric=names(summary),value=vapply(summary,display,'')),file.path(out,'summary.csv'),row.names=FALSE);pp<-do.call(rbind,points);write.csv(pp,file.path(out,'plot-points.csv'),row.names=FALSE);dput(r,file.path(out,'full-result.Rtext'));svg(file.path(out,'plot.svg'),width=5.6,height=4.6,pointsize=14);par(mar=c(5.8,5.8,5.3,1.2),mgp=c(3.7,1,0));xr<-range(pp$x);yr<-range(pp$y);if(diff(xr)==0)xr<-xr+c(-.5,.5);if(diff(yr)==0)yr<-yr+c(-.5,.5);plot(xr,yr,type='n',xlab=xl,ylab=yl,cex.lab=.78,axes=FALSE);axis(1,at=pretty(xr,3));axis(2,at=pretty(yr,4),las=1,cex.axis=.82);box();grid(col='#dddddd');cols<-c('#355c72','#a55336','#507956','#78568b');ss<-unique(pp$series);for(i in seq_along(ss)){v<-pp[pp$series==ss[i],];points(v$x,v$y,pch=16,cex=if(nrow(v)>100).35 else .85,col=adjustcolor(cols[i],if(nrow(v)>100).5 else 1))};legend('topleft',legend=ss,col=cols[seq_along(ss)],lty=0,pch=16,cex=.65,bty='n',inset=c(0,-.32),xpd=NA);mtext(title,side=3,line=3.9,cex=.6);dev.off();cat(paste(names(summary),vapply(summary,display,''),sep='=',collapse=', '),'\\n')\n}\nargs<-commandArgs(trailingOnly=TRUE)\ntryCatch(run_fixed(API,INPUT,if(length(args))args[1]else'fixed-results',if(length(args)>1)args[2]else'ml09-sources'),error=function(e){cat('Rejected declared input: ',conditionMessage(e),'\\n',file=stderr());quit(status=2)})\n",
        "code": "# ML09 base-R reproduction from native original-field CSVs.\n# Rscript ml09-public-analysis.R ml09-sources results-r\n# Separately written vectorized direct-centered squared/Gini losses.\n# No Python/JS/model-contract/stored-answer/derived-result reader or package.\n# Numeric arithmetic is binary64:1e-12 relative tie tolerance stabilizes exact\n# source ties,but does not certify tiny margins/underflow like Fraction JS/Python.\n# Data-frame rows use x0,x1,...,y,weight; original IDs remain attached to draws.\noptions(stringsAsFactors=FALSE,digits=17)\nnum<-function(v){if(is.null(v)||length(v)!=1||is.na(v))stop('numeric parameter required, not explicit NULL');p<-strsplit(as.character(v),'/',fixed=TRUE)[[1]];z<-if(length(p)==2)as.numeric(p[1])/as.numeric(p[2])else as.numeric(v);if(!is.finite(z))stop('finite numeric parameter');z}\noption<-function(a,k,default){if(k%in%names(a))a[[k]]else default}\nnormrows<-function(d,task){if(!'weight'%in%names(d))d$weight<-1;if(!'id'%in%names(d))d$id<-as.character(seq_len(nrow(d))-1);d$weight<-as.numeric(d$weight);if(anyNA(d$weight)||any(d$weight<0))stop('nonnegative weights');if(task=='regression')d$y<-as.numeric(d$y)else d$y<-as.character(d$y);d}\nstat<-function(d,task,classes){W<-sum(d$weight);mu<-if(task=='regression'&&W)sum(d$weight*d$y)/W else NA_real_;p<-if(task=='classification'&&W)vapply(classes,function(c)sum(d$weight[d$y==c])/W,0)else numeric();risk<-if(task=='regression'&&W)sum(d$weight*(d$y-mu)^2)else W*sum(p*(1-p));list(n=nrow(d),w=W,mu=mu,p=unname(p),risk=risk,pred=if(task=='regression')mu else if(W)classes[which.max(p)]else NA_character_)}\nfit<-function(d,a,task,classes,schedule=NULL){d<-d[d$weight>0&!is.na(d$y),,drop=FALSE];if(!nrow(d))stop('positive observed training');W<-sum(d$weight);depth<-option(a,'maxDepth',2);minimum<-option(a,'minLeaf',1);minmass<-num(option(a,'minLeafWeight',0));mingain<-num(option(a,'minGain',0));route<-option(a,'missingRoute','best');features<-grep('^x[0-9]+$',names(d),value=TRUE)\n build<-function(rr,level,path){st<-stat(rr,task,classes);node<-list(rows=rr,st=st,split=NULL,left=NULL,right=NULL,path=path);if(level==depth)return(node);best<-NULL;allowed<-if(is.null(schedule))seq_along(features)-1L else schedule[[match(path,names(schedule))]]\n  for(j in seq_along(features)-1L){if(!j%in%allowed)next;v<-rr[[features[j+1L]]];values<-sort(unique(v[!is.na(v)]));candidates<-list()\n   if(length(values)>1)for(k in seq_len(length(values)-1L)){threshold<-(values[k]+values[k+1L])/2;missing<-is.na(v);left<-!missing&v<=threshold;right<-!missing&v>threshold;directions<-if(route!='best')route else if(any(missing))c('left','right')else if(sum(left)>=sum(right))'left'else'right';for(direction in directions)candidates[[length(candidates)+1L]]<-list(kind='threshold',threshold=threshold,missingRoute=direction,left=if(direction=='left')left|missing else left,right=if(direction=='right')right|missing else right)}\n   if(anyNA(v)&&any(!is.na(v)))candidates[[length(candidates)+1L]]<-list(kind='missing-only',threshold=NA_real_,missingRoute='left',left=is.na(v),right=!is.na(v))\n   for(candidate in candidates){l<-rr[candidate$left,,drop=FALSE];r<-rr[candidate$right,,drop=FALSE];ls<-stat(l,task,classes);rs<-stat(r,task,classes);if(min(ls$n,rs$n)<minimum||min(ls$w,rs$w)<minmass||min(ls$w,rs$w)<=0)next;gain<-(st$risk-ls$risk-rs$risk)/W;tol<-1e-12*max(1,abs(gain),if(is.null(best))0 else abs(best$gain));if(is.null(best)||gain>best$gain+tol)best<-c(candidate,list(feature=j,gain=gain,l=l,r=r))}\n  }\n  if(!is.null(best)&&best$gain>max(mingain,1e-12)){node$split<-best;node$left<-build(best$l,level+1L,paste0(path,'L'));node$right<-build(best$r,level+1L,paste0(path,'R'))};node\n };build(d,0L,'')\n}\npredict_one<-function(tree,row){n<-tree;while(!is.null(n$split)){s<-n$split;v<-as.numeric(row[[paste0('x',s$feature)]]);left<-if(s$kind=='missing-only')is.na(v)else if(is.na(v))s$missingRoute=='left'else v<=s$threshold;n<-if(left)n$left else n$right};list(prediction=n$st$pred,probabilities=n$st$p)}\ncombine<-function(pp,w,task,classes,mode='probabilities'){W<-sum(w);if(!length(pp)||!W)return(list(prediction=if(task=='regression')NA_real_ else NA_character_,probabilities=numeric(),vote=NA_character_,prob=NA_character_));if(task=='regression')return(list(prediction=sum(vapply(pp,function(p)p$prediction,0)*w)/W,probabilities=numeric(),vote=NA_character_,prob=NA_character_));votes<-vapply(classes,function(c)sum(w[vapply(pp,function(p)p$prediction==c,FALSE)])/W,0);probs<-vapply(seq_along(classes),function(j)sum(vapply(pp,function(p)p$probabilities[j],0)*w)/W,0);vote<-classes[which.max(votes)];prob<-classes[which.max(probs)];list(prediction=if(mode=='votes')vote else prob,probabilities=unname(probs),vote=vote,prob=prob,votes=unname(votes))}\nvariance<-function(a){B<-num(a$B);v<-num(a$marginalVariance);rho<-num(option(a,'rho',0));if(B<1||B!=floor(B)||v<0)stop('integer B/nonnegative variance');if(B>1&&v>0&&(rho< -1/(B-1)||rho>1))stop('PSD correlation');list(B=B,marginalVariance=v,correlationApplicable=B>1&&v>0,varianceOfMean=if(B==1)v else v*(1+(B-1)*rho)/B)}\naggregate<-function(a){task<-option(a,'task','regression');classes<-option(a,'classes',character());w<-vapply(option(a,'memberWeights',as.list(rep(1,length(a$members)))),num,0);if(any(w<0)||sum(w)<=0)stop('positive member mass');ids<-a$members[[1]]$predictions$id;pp<-lapply(ids,function(id){members<-lapply(a$members,function(m){r<-m$predictions[match(id,m$predictions$id),,drop=FALSE];if(task=='regression')list(prediction=num(r$value),probabilities=numeric())else list(prediction=as.character(r$label),probabilities=as.numeric(r[paste0('p',seq_along(classes)-1L)]))});c(list(id=id),combine(members,w,task,classes,option(a,'aggregation','probabilities')))});list(task=task,classes=classes,predictions=pp)}\nscored<-function(preds,d,task,classes){W<-loss<-absolute<-errors<-voteerrors<-0;count<-0L;out<-lapply(seq_len(nrow(d)),function(i){r<-d[i,,drop=FALSE];p<-preds[[i]];ok<-!is.na(p$prediction)&&!is.na(r$y)&&r$weight>0;value<-NA_real_;if(ok){count<<-count+1L;W<<-W+r$weight;if(task=='regression'){e<-r$y-p$prediction;value<-e*e;absolute<<-absolute+r$weight*abs(e)}else{value<-sum((p$probabilities-as.numeric(classes==r$y))^2);errors<<-errors+r$weight*(p$prediction!=r$y);voteerrors<<-voteerrors+r$weight*(p$vote!=r$y)};loss<<-loss+r$weight*value};c(p,list(actual=r$y,weight=r$weight,scoreEligible=ok,loss=value))});list(rows=out,eligibleRows=count,weight=W,totalLoss=loss,meanLoss=if(W)loss/W else NA_real_,MAE=if(W&&task=='regression')absolute/W else NA_real_,errorRate=if(W&&task=='classification')errors/W else NA_real_,labelVoteErrorRate=if(W&&task=='classification')voteerrors/W else NA_real_)}\nensemble<-function(a,forest=FALSE){task<-option(a,'task','regression');classes<-option(a,'classes',character());d<-normrows(a$rows,task);w<-vapply(option(a,'memberWeights',as.list(rep(1,length(a$bootstrapDraws)))),num,0);if(any(w<0)||sum(w)<=0)stop('positive member mass');members<-lapply(seq_along(a$bootstrapDraws),function(i){draw<-a$bootstrapDraws[[i]];indices<-match(draw,d$id);if(anyNA(indices))stop('unknown draw source');tree<-fit(d[indices,,drop=FALSE],a,task,classes,if(forest)a$nodeFeatures[[i]]else NULL);list(tree=tree,draw=draw,inbag=unique(draw),weight=w[i])});queries<-a$queries;preds<-lapply(seq_len(nrow(queries)),function(i)c(list(id=queries$id[i]),combine(lapply(members,function(m)predict_one(m$tree,queries[i,,drop=FALSE])),w,task,classes,option(a,'aggregation','probabilities'))));oob<-lapply(seq_len(nrow(d)),function(i){app<-which(!vapply(members,function(m)d$id[i]%in%m$inbag,FALSE));pp<-combine(lapply(app,function(j)predict_one(members[[j]]$tree,d[i,,drop=FALSE])),w[app],task,classes,option(a,'aggregation','probabilities'));c(list(id=d$id[i],applicable=app-1L,positiveMembers=sum(w[app]>0)),pp)});list(task=task,classes=classes,members=members,predictions=preds,outOfBag=scored(oob,d,task,classes))}\nboost<-function(a){if(option(a,'task','regression')!='regression')stop('regression boosting only');d<-normrows(a$rows,'regression');eligible<-d$weight>0&!is.na(d$y);W<-sum(d$weight[eligible]);if(!W)stop('positive eligible training');eta<-num(option(a,'learningRate','1/2'));stages<-option(a,'stages',3);if(is.null(stages)||stages!=floor(stages)||stages<0||stages>8||eta<0||eta>1)stop('supported rate/stages');initial<-if('initial'%in%names(a))num(a$initial)else sum(d$weight[eligible]*d$y[eligible])/W;train<-matrix(initial,nrow(d),stages+1L);query<-matrix(initial,nrow(a$queries),stages+1L);losses<-fits<-list();for(stage in 0:stages){sse<-sum(d$weight[eligible]*(d$y[eligible]-train[eligible,stage+1L])^2);losses[[stage+1L]]<-list(stage=stage,rawWeightedSSE=sse,MSE=sse/W,meanHalfSquaredLoss=sse/(2*W));if(stage==stages)break;residual<-d;residual$y<-d$y-train[,stage+1L];tree<-fit(residual,a,'regression',character());h<-vapply(seq_len(nrow(d)),function(i)predict_one(tree,d[i,,drop=FALSE])$prediction,0);qh<-vapply(seq_len(nrow(a$queries)),function(i)predict_one(tree,a$queries[i,,drop=FALSE])$prediction,0);stageRows<-lapply(seq_len(nrow(d)),function(i)list(id=d$id[i],before=train[i,stage+1L],residual=residual$y[i],negativeCoordinateDerivative=d$weight[i]*residual$y[i]/W,fit=h[i],addition=eta*h[i],after=train[i,stage+1L]+eta*h[i]));train[,stage+2L]<-train[,stage+1L]+eta*h;query[,stage+2L]<-query[,stage+1L]+eta*qh;norm<-sum(d$weight[eligible]*h[eligible]^2);fits[[stage+1L]]<-list(stage=stage+1L,tree=tree,rows=stageRows,queryFits=qh,norm=norm,predictedSSEDecrease=eta*(2-eta)*norm)};list(task='regression',initial=initial,learningRate=eta,stages=stages,training=train,queries=query,fits=fits,losses=losses,predictions=lapply(seq_len(nrow(a$queries)),function(i)list(id=a$queries$id[i],prediction=query[i,stages+1L],probabilities=numeric(),vote=NA_character_,prob=NA_character_)))}\nfixed_schedules<-function(ids,p,seed){state<-seed;choose<-function(n){limit<-floor(4294967296/n)*n;repeat{state<<-(1664525*state+1013904223)%%4294967296;if(state<limit)return(as.integer(state%%n))}};draws<-schedules<-list();for(member in 1:4){draws[[member]]<-vapply(seq_along(ids),function(i)ids[choose(length(ids))+1L],'');schedule<-setNames(vector('list',7),c('','L','R','LL','LR','RL','RR'));for(path in names(schedule)){order<-seq_len(p)-1L;if(p>1)for(j in seq(p-1L,1L)){k<-choose(j+1L);temp<-order[j+1L];order[j+1L]<-order[k+1L];order[k+1L]<-temp};schedule[[match(path,names(schedule))]]<-sort(order[seq_len(max(1L,floor(sqrt(p))))])};schedules[[member]]<-schedule};list(draws=draws,schedules=schedules)}\nread_sources<-function(src){read<-function(name)read.csv(file.path(src,name),check.names=FALSE,colClasses='character',na.strings=character(),fileEncoding='UTF-8-BOM');raw<-read('actual320-country-four-indicators-original-2020-2024.csv');country<-do.call(rbind,lapply(sort(unique(raw$countryISO3)),function(code)do.call(rbind,lapply(2020:2024,function(year){keys<-c('NY.GDP.PCAP.KD','NY.GDP.MKTP.KD.ZG','FP.CPI.TOTL.ZG','SP.DYN.LE00.IN');v<-vapply(keys,function(k)as.numeric(raw$originalValueToken[raw$countryISO3==code&raw$date==as.character(year)&raw$indicatorID==k]),0);data.frame(id=paste0(code,':',year),sourceRow=paste0(code,':',year),originalID=code,year=year,x0=v[1]/10000,x1=v[2],x2=v[3],y=v[4],weight=1,role=if(anyNA(v))'excluded'else if(year==2024)'outer-test'else'train')}))));raw<-read('actual3613-NLS-original52-fields-and-selection.csv');i<-seq_len(nrow(raw));x0<-suppressWarnings(as.numeric(raw$ed76));x1<-suppressWarnings(as.numeric(raw$age76));y<-suppressWarnings(as.numeric(raw$wage76))/100;person<-data.frame(id=paste0('person:',i),sourceRow=as.character(i),originalID=raw$id,x0=x0,x1=x1,y=y,weight=1,role=ifelse(is.na(x0)|is.na(x1)|is.na(y),'excluded',ifelse(i%%5==0,'outer-test','train')));raw<-read('actual3150-churn-original14-fields-and-selection.csv');i<-seq_len(nrow(raw));company<-data.frame(id=paste0('customer:',i),sourceRow=as.character(i),originalID='',x0=as.numeric(raw[['Call  Failure']]),x1=as.numeric(raw[['Subscription  Length']]),x2=as.numeric(raw[['Charge  Amount']]),y=raw$Churn,weight=1,role=ifelse(i%%5==0,'outer-test','train'));models<-list();for(index in 1:3){kind<-c('country','person','company')[index];d<-list(country,person,company)[[index]];task<-if(kind=='company')'classification'else'regression';s<-fixed_schedules(d$id[d$role=='train'],if(kind=='person')2L else 3L,20261102+7919*(index-1L));models[[kind]]<-list(records=d,task=task,classes=if(task=='classification')c('0','1')else character(),draws=s$draws,schedules=s$schedules,minLeaf=c(4L,50L,30L)[index])};models}\nrealdata<-function(models,kind,options=list()){if(is.null(options)||!is.list(options))stop('options object');m<-models[[kind]];d<-m$records;train<-d[d$role=='train',,drop=FALSE];test<-d[d$role=='outer-test',,drop=FALSE];method<-option(options,'method','forest');depth<-option(options,'maxDepth',2);count<-option(options,'memberCount',3);if(!method%in%c('bagging','forest','boost'))stop('known method');a<-list(rows=train,queries=test,task=m$task,classes=m$classes,maxDepth=depth,minLeaf=option(options,'minLeaf',m$minLeaf),minLeafWeight=0,minGain=0,missingRoute='best',learningRate=option(options,'learningRate','1/2'),stages=option(options,'stages',3));if(method=='boost')result<-boost(a)else{a$bootstrapDraws<-m$draws[seq_len(count)];a$nodeFeatures<-lapply(m$schedules[seq_len(count)],function(s)s[nchar(names(s))<depth]);result<-ensemble(a,method=='forest')};outer<-scored(result$predictions,normrows(test,m$task),m$task,m$classes);st<-stat(normrows(train,m$task),m$task,m$classes);constant<-list(prediction=st$pred,probabilities=st$p,vote=st$pred,prob=st$pred);baseline<-scored(lapply(test$id,function(id)c(list(id=id),constant)),normrows(test,m$task),m$task,m$classes);list(kind=kind,method=method,settings=a,train=train,test=test,result=result,outer=outer,baseline=baseline)}\nAPI<-\"realdata\"\nINPUT<-list(kind=\"company\")\n\nrun_fixed<-function(api,a,out,src){\n r<-if(api=='variance')variance(a)else if(api=='aggregate')aggregate(a)else if(api%in%c('bagging','forest'))ensemble(a,api=='forest')else if(api=='boost')boost(a)else realdata(read_sources(src),a$kind)\n dir.create(out,recursive=TRUE,showWarnings=FALSE);summary<-list();points<-list();add<-function(x,y,s){if(!is.null(y)&&!is.na(y))points[[length(points)+1L]]<<-data.frame(x=x,y=as.numeric(y),series=s)}\n if(api=='variance'){summary<-r[c('B','varianceOfMean')];add(r$B,r$varianceOfMean,'Specified finite-B variance');xl<-'Number of members B';yl<-'Variance, stipulated units squared';title<-'Declared covariance model, not fitted trees'\n }else if(api=='aggregate'){p<-r$predictions[[1]];summary<-list(selectedPrediction=p$prediction);classification<-identical(a$task,'classification');if(classification){summary<-c(summary,list(voteLabel=p$vote,probabilityLabel=p$prob,meanProbability1=p$probabilities[2]));add(1,p$probabilities[2],'Mean probability of class 1');add(2,p$votes[2],'Label-vote share of class 1');xl<-'Aggregation (1=probability, 2=vote)';yl<-'Probability or vote share'}else{for(i in seq_along(a$members))add(i,num(a$members[[i]]$predictions$value[1]),'Member prediction');add(3,p$prediction,'Weighted mean');xl<-'Member 1, member 2, aggregate 3';yl<-'Prediction, assumed units'};title<-'Votes and probabilities are distinct objects'\n }else if(api%in%c('bagging','forest')){summary<-list(queryPrediction=r$predictions[[1]]$prediction,OOB.scoreable=r$outOfBag$eligibleRows,OOB.meanLoss=r$outOfBag$meanLoss);for(i in seq_len(nrow(a$rows)))add(i,a$rows$y[i],'Observed training outcome');for(i in seq_along(r$outOfBag$rows))add(i,r$outOfBag$rows[[i]]$prediction,'OOB prediction, when defined');xl<-'Original training ID order';yl<-'Outcome, assumed units';title<-'Repeated draws and ID-level OOB membership'\n }else if(api=='boost'){summary<-list(initial=r$initial,finalMSE=r$losses[[length(r$losses)]]$MSE,stages=r$stages);for(v in r$losses)add(v$stage,v$MSE,'Training MSE');xl<-'Boosting stage (0=initial)';yl<-'Weighted MSE, outcome units squared';title<-'Training descent does not certify held-out gain'\n }else{summary<-list(outer.scoreable=r$outer$eligibleRows,outer.meanLoss=r$outer$meanLoss,baseline.meanLoss=r$baseline$meanLoss,OOB.scoreable=r$result$outOfBag$eligibleRows,OOB.meanLoss=r$result$outOfBag$meanLoss);for(i in seq_along(r$outer$rows)){p<-r$outer$rows[[i]];add(i,as.numeric(p$actual),'Observed outcome');add(i,if(a$kind=='company')p$probabilities[2]else p$prediction,if(a$kind=='company')'Forest probability of class 1'else'Forest prediction')};xl<-'Outer-test source order, not a time path';yl<-if(a$kind=='company')'Churn label / probability'else if(a$kind=='country')'Period life expectancy, years'else'Nominal 1976 USD per hour';title<-'Fixed forest; outer labels did not fit the trees'}\n display<-function(v)if(is.null(v)||is.na(v))'undefined'else sprintf('%.9f',as.numeric(v));write.csv(data.frame(metric=names(summary),value=vapply(summary,display,'')),file.path(out,'summary.csv'),row.names=FALSE);pp<-do.call(rbind,points);write.csv(pp,file.path(out,'plot-points.csv'),row.names=FALSE);dput(r,file.path(out,'full-result.Rtext'));svg(file.path(out,'plot.svg'),width=5.6,height=4.6,pointsize=14);par(mar=c(5.8,5.8,5.3,1.2),mgp=c(3.7,1,0));xr<-range(pp$x);yr<-range(pp$y);if(diff(xr)==0)xr<-xr+c(-.5,.5);if(diff(yr)==0)yr<-yr+c(-.5,.5);plot(xr,yr,type='n',xlab=xl,ylab=yl,cex.lab=.78,axes=FALSE);axis(1,at=pretty(xr,3));axis(2,at=pretty(yr,4),las=1,cex.axis=.82);box();grid(col='#dddddd');cols<-c('#355c72','#a55336','#507956','#78568b');ss<-unique(pp$series);for(i in seq_along(ss)){v<-pp[pp$series==ss[i],];points(v$x,v$y,pch=16,cex=if(nrow(v)>100).35 else .85,col=adjustcolor(cols[i],if(nrow(v)>100).5 else 1))};legend('topleft',legend=ss,col=cols[seq_along(ss)],lty=0,pch=16,cex=.65,bty='n',inset=c(0,-.32),xpd=NA);mtext(title,side=3,line=3.9,cex=.6);dev.off();cat(paste(names(summary),vapply(summary,display,''),sep='=',collapse=', '),'\\n')\n}\nargs<-commandArgs(trailingOnly=TRUE)\ntryCatch(run_fixed(API,INPUT,if(length(args))args[1]else'fixed-results',if(length(args)>1)args[2]else'ml09-sources'),error=function(e){cat('Rejected declared input: ',conditionMessage(e),'\\n',file=stderr());quit(status=2)})\n",
        "inputFiles": [
          {
            "file": "ml09-sources/actual3150-churn-original14-fields-and-selection.csv",
            "sha256": "6f5b9e98ce1896582629646dd4cfe7b1aca78c491f7e412a93840534e8b49f48"
          },
          {
            "file": "ml09-sources/actual320-country-four-indicators-original-2020-2024.csv",
            "sha256": "cedc2f748ce14601c76b254c35aea7ef0ee5f06f2928506c225efcbfb1f69390"
          },
          {
            "file": "ml09-sources/actual3613-NLS-original52-fields-and-selection.csv",
            "sha256": "7ae23478bdfee0922157264655e1a2081999f11686773478835bce315068e0df"
          }
        ],
        "input": {
          "kind": "company"
        },
        "returnCode": 0,
        "expectedFailure": false,
        "stdout": "outer.scoreable=630.000000000, outer.meanLoss=0.318897321, baseline.meanLoss=0.269263039, OOB.scoreable=1865.000000000, OOB.meanLoss=0.239656197 \n",
        "stderr": "During startup - Warning messages:\n1: Setting LC_COLLATE=C.UTF-8 failed \n2: Setting LC_CTYPE=C.UTF-8 failed \n3: Setting LC_MONETARY=C.UTF-8 failed \n4: Setting LC_TIME=C.UTF-8 failed \n",
        "summary": {
          "outer.scoreable": "630.000000000",
          "outer.meanLoss": "0.318897321",
          "baseline.meanLoss": "0.269263039",
          "OOB.scoreable": "1865.000000000",
          "OOB.meanLoss": "0.239656197"
        },
        "plotPoints": [
          {
            "x": "1",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "1",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "2",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "2",
            "y": "0.154685769474791",
            "series": "Forest probability of class 1"
          },
          {
            "x": "3",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "3",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "4",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "4",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "5",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "5",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "6",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "6",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "7",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "7",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "8",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "8",
            "y": "0.0398140250227478",
            "series": "Forest probability of class 1"
          },
          {
            "x": "9",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "9",
            "y": "0.015833209675026",
            "series": "Forest probability of class 1"
          },
          {
            "x": "10",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "10",
            "y": "0.0032488628979857",
            "series": "Forest probability of class 1"
          },
          {
            "x": "11",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "11",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "12",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "12",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "13",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "13",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "14",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "14",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "15",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "15",
            "y": "0.154685769474791",
            "series": "Forest probability of class 1"
          },
          {
            "x": "16",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "16",
            "y": "0.154685769474791",
            "series": "Forest probability of class 1"
          },
          {
            "x": "17",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "17",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "18",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "18",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "19",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "19",
            "y": "0.0032488628979857",
            "series": "Forest probability of class 1"
          },
          {
            "x": "20",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "20",
            "y": "0.0032488628979857",
            "series": "Forest probability of class 1"
          },
          {
            "x": "21",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "21",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "22",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "22",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "23",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "23",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "24",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "24",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "25",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "25",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "26",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "26",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "27",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "27",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "28",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "28",
            "y": "0.015833209675026",
            "series": "Forest probability of class 1"
          },
          {
            "x": "29",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "29",
            "y": "0.015833209675026",
            "series": "Forest probability of class 1"
          },
          {
            "x": "30",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "30",
            "y": "0.015833209675026",
            "series": "Forest probability of class 1"
          },
          {
            "x": "31",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "31",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "32",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "32",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "33",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "33",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "34",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "34",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "35",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "35",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "36",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "36",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "37",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "37",
            "y": "0.154685769474791",
            "series": "Forest probability of class 1"
          },
          {
            "x": "38",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "38",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "39",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "39",
            "y": "0.0032488628979857",
            "series": "Forest probability of class 1"
          },
          {
            "x": "40",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "40",
            "y": "0.0032488628979857",
            "series": "Forest probability of class 1"
          },
          {
            "x": "41",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "41",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "42",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "42",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "43",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "43",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "44",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "44",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "45",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "45",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "46",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "46",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "47",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "47",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "48",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "48",
            "y": "0.015833209675026",
            "series": "Forest probability of class 1"
          },
          {
            "x": "49",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "49",
            "y": "0.015833209675026",
            "series": "Forest probability of class 1"
          },
          {
            "x": "50",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "50",
            "y": "0.015833209675026",
            "series": "Forest probability of class 1"
          },
          {
            "x": "51",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "51",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "52",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "52",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "53",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "53",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "54",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "54",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "55",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "55",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "56",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "56",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "57",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "57",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "58",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "58",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "59",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "59",
            "y": "0.0032488628979857",
            "series": "Forest probability of class 1"
          },
          {
            "x": "60",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "60",
            "y": "0.0032488628979857",
            "series": "Forest probability of class 1"
          },
          {
            "x": "61",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "61",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "62",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "62",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "63",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "63",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "64",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "64",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "65",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "65",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "66",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "66",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "67",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "67",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "68",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "68",
            "y": "0.015833209675026",
            "series": "Forest probability of class 1"
          },
          {
            "x": "69",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "69",
            "y": "0.015833209675026",
            "series": "Forest probability of class 1"
          },
          {
            "x": "70",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "70",
            "y": "0.015833209675026",
            "series": "Forest probability of class 1"
          },
          {
            "x": "71",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "71",
            "y": "0.179869463648231",
            "series": "Forest probability of class 1"
          },
          {
            "x": "72",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "72",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "73",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "73",
            "y": "0.179869463648231",
            "series": "Forest probability of class 1"
          },
          {
            "x": "74",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "74",
            "y": "0.179869463648231",
            "series": "Forest probability of class 1"
          },
          {
            "x": "75",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "75",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "76",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "76",
            "y": "0.179869463648231",
            "series": "Forest probability of class 1"
          },
          {
            "x": "77",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "77",
            "y": "0.154685769474791",
            "series": "Forest probability of class 1"
          },
          {
            "x": "78",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "78",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "79",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "79",
            "y": "0.015833209675026",
            "series": "Forest probability of class 1"
          },
          {
            "x": "80",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "80",
            "y": "0.0032488628979857",
            "series": "Forest probability of class 1"
          },
          {
            "x": "81",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "81",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "82",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "82",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "83",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "83",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "84",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "84",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "85",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "85",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "86",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "86",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "87",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "87",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "88",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "88",
            "y": "0.015833209675026",
            "series": "Forest probability of class 1"
          },
          {
            "x": "89",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "89",
            "y": "0.015833209675026",
            "series": "Forest probability of class 1"
          },
          {
            "x": "90",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "90",
            "y": "0.0032488628979857",
            "series": "Forest probability of class 1"
          },
          {
            "x": "91",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "91",
            "y": "0.154685769474791",
            "series": "Forest probability of class 1"
          },
          {
            "x": "92",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "92",
            "y": "0.154685769474791",
            "series": "Forest probability of class 1"
          },
          {
            "x": "93",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "93",
            "y": "0.154685769474791",
            "series": "Forest probability of class 1"
          },
          {
            "x": "94",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "94",
            "y": "0.154685769474791",
            "series": "Forest probability of class 1"
          },
          {
            "x": "95",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "95",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "96",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "96",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "97",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "97",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "98",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "98",
            "y": "0.0272296782457075",
            "series": "Forest probability of class 1"
          },
          {
            "x": "99",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "99",
            "y": "0.0032488628979857",
            "series": "Forest probability of class 1"
          },
          {
            "x": "100",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "100",
            "y": "0.0032488628979857",
            "series": "Forest probability of class 1"
          },
          {
            "x": "101",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "101",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "102",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "102",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "103",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "103",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "104",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "104",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "105",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "105",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "106",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "106",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "107",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "107",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "108",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "108",
            "y": "0.0398140250227478",
            "series": "Forest probability of class 1"
          },
          {
            "x": "109",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "109",
            "y": "0.015833209675026",
            "series": "Forest probability of class 1"
          },
          {
            "x": "110",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "110",
            "y": "0.015833209675026",
            "series": "Forest probability of class 1"
          },
          {
            "x": "111",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "111",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "112",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "112",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "113",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "113",
            "y": "0.154685769474791",
            "series": "Forest probability of class 1"
          },
          {
            "x": "114",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "114",
            "y": "0.154685769474791",
            "series": "Forest probability of class 1"
          },
          {
            "x": "115",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "115",
            "y": "0.154685769474791",
            "series": "Forest probability of class 1"
          },
          {
            "x": "116",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "116",
            "y": "0.154685769474791",
            "series": "Forest probability of class 1"
          },
          {
            "x": "117",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "117",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "118",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "118",
            "y": "0.0975474605310355",
            "series": "Forest probability of class 1"
          },
          {
            "x": "119",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "119",
            "y": "0.0032488628979857",
            "series": "Forest probability of class 1"
          },
          {
            "x": "120",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "120",
            "y": "0.0032488628979857",
            "series": "Forest probability of class 1"
          },
          {
            "x": "121",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "121",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "122",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "122",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "123",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "123",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "124",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "124",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "125",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "125",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "126",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "126",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "127",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "127",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "128",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "128",
            "y": "0.0398140250227478",
            "series": "Forest probability of class 1"
          },
          {
            "x": "129",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "129",
            "y": "0.015833209675026",
            "series": "Forest probability of class 1"
          },
          {
            "x": "130",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "130",
            "y": "0.015833209675026",
            "series": "Forest probability of class 1"
          },
          {
            "x": "131",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "131",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "132",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "132",
            "y": "0.154685769474791",
            "series": "Forest probability of class 1"
          },
          {
            "x": "133",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "133",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "134",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "134",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "135",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "135",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "136",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "136",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "137",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "137",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "138",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "138",
            "y": "0.0398140250227478",
            "series": "Forest probability of class 1"
          },
          {
            "x": "139",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "139",
            "y": "0.015833209675026",
            "series": "Forest probability of class 1"
          },
          {
            "x": "140",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "140",
            "y": "0.0032488628979857",
            "series": "Forest probability of class 1"
          },
          {
            "x": "141",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "141",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "142",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "142",
            "y": "0.154685769474791",
            "series": "Forest probability of class 1"
          },
          {
            "x": "143",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "143",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "144",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "144",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "145",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "145",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "146",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "146",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "147",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "147",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "148",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "148",
            "y": "0.0398140250227478",
            "series": "Forest probability of class 1"
          },
          {
            "x": "149",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "149",
            "y": "0.015833209675026",
            "series": "Forest probability of class 1"
          },
          {
            "x": "150",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "150",
            "y": "0.0032488628979857",
            "series": "Forest probability of class 1"
          },
          {
            "x": "151",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "151",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "152",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "152",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "153",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "153",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "154",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "154",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "155",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "155",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "156",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "156",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "157",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "157",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "158",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "158",
            "y": "0.015833209675026",
            "series": "Forest probability of class 1"
          },
          {
            "x": "159",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "159",
            "y": "0.015833209675026",
            "series": "Forest probability of class 1"
          },
          {
            "x": "160",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "160",
            "y": "0.015833209675026",
            "series": "Forest probability of class 1"
          },
          {
            "x": "161",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "161",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "162",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "162",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "163",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "163",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "164",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "164",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "165",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "165",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "166",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "166",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "167",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "167",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "168",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "168",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "169",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "169",
            "y": "0.0032488628979857",
            "series": "Forest probability of class 1"
          },
          {
            "x": "170",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "170",
            "y": "0.0032488628979857",
            "series": "Forest probability of class 1"
          },
          {
            "x": "171",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "171",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "172",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "172",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "173",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "173",
            "y": "0.154685769474791",
            "series": "Forest probability of class 1"
          },
          {
            "x": "174",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "174",
            "y": "0.154685769474791",
            "series": "Forest probability of class 1"
          },
          {
            "x": "175",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "175",
            "y": "0.154685769474791",
            "series": "Forest probability of class 1"
          },
          {
            "x": "176",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "176",
            "y": "0.154685769474791",
            "series": "Forest probability of class 1"
          },
          {
            "x": "177",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "177",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "178",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "178",
            "y": "0.0975474605310355",
            "series": "Forest probability of class 1"
          },
          {
            "x": "179",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "179",
            "y": "0.0032488628979857",
            "series": "Forest probability of class 1"
          },
          {
            "x": "180",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "180",
            "y": "0.0032488628979857",
            "series": "Forest probability of class 1"
          },
          {
            "x": "181",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "181",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "182",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "182",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "183",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "183",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "184",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "184",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "185",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "185",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "186",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "186",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "187",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "187",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "188",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "188",
            "y": "0.0398140250227478",
            "series": "Forest probability of class 1"
          },
          {
            "x": "189",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "189",
            "y": "0.015833209675026",
            "series": "Forest probability of class 1"
          },
          {
            "x": "190",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "190",
            "y": "0.015833209675026",
            "series": "Forest probability of class 1"
          },
          {
            "x": "191",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "191",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "192",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "192",
            "y": "0.154685769474791",
            "series": "Forest probability of class 1"
          },
          {
            "x": "193",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "193",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "194",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "194",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "195",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "195",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "196",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "196",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "197",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "197",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "198",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "198",
            "y": "0.0398140250227478",
            "series": "Forest probability of class 1"
          },
          {
            "x": "199",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "199",
            "y": "0.015833209675026",
            "series": "Forest probability of class 1"
          },
          {
            "x": "200",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "200",
            "y": "0.0032488628979857",
            "series": "Forest probability of class 1"
          },
          {
            "x": "201",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "201",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "202",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "202",
            "y": "0.154685769474791",
            "series": "Forest probability of class 1"
          },
          {
            "x": "203",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "203",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "204",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "204",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "205",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "205",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "206",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "206",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "207",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "207",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "208",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "208",
            "y": "0.0398140250227478",
            "series": "Forest probability of class 1"
          },
          {
            "x": "209",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "209",
            "y": "0.015833209675026",
            "series": "Forest probability of class 1"
          },
          {
            "x": "210",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "210",
            "y": "0.0032488628979857",
            "series": "Forest probability of class 1"
          },
          {
            "x": "211",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "211",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "212",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "212",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "213",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "213",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "214",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "214",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "215",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "215",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "216",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "216",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "217",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "217",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "218",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "218",
            "y": "0.015833209675026",
            "series": "Forest probability of class 1"
          },
          {
            "x": "219",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "219",
            "y": "0.015833209675026",
            "series": "Forest probability of class 1"
          },
          {
            "x": "220",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "220",
            "y": "0.015833209675026",
            "series": "Forest probability of class 1"
          },
          {
            "x": "221",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "221",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "222",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "222",
            "y": "0.154685769474791",
            "series": "Forest probability of class 1"
          },
          {
            "x": "223",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "223",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "224",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "224",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "225",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "225",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "226",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "226",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "227",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "227",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "228",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "228",
            "y": "0.0398140250227478",
            "series": "Forest probability of class 1"
          },
          {
            "x": "229",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "229",
            "y": "0.015833209675026",
            "series": "Forest probability of class 1"
          },
          {
            "x": "230",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "230",
            "y": "0.0032488628979857",
            "series": "Forest probability of class 1"
          },
          {
            "x": "231",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "231",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "232",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "232",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "233",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "233",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "234",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "234",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "235",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "235",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "236",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "236",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "237",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "237",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "238",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "238",
            "y": "0.015833209675026",
            "series": "Forest probability of class 1"
          },
          {
            "x": "239",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "239",
            "y": "0.015833209675026",
            "series": "Forest probability of class 1"
          },
          {
            "x": "240",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "240",
            "y": "0.015833209675026",
            "series": "Forest probability of class 1"
          },
          {
            "x": "241",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "241",
            "y": "0.179869463648231",
            "series": "Forest probability of class 1"
          },
          {
            "x": "242",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "242",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "243",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "243",
            "y": "0.179869463648231",
            "series": "Forest probability of class 1"
          },
          {
            "x": "244",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "244",
            "y": "0.179869463648231",
            "series": "Forest probability of class 1"
          },
          {
            "x": "245",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "245",
            "y": "0.154685769474791",
            "series": "Forest probability of class 1"
          },
          {
            "x": "246",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "246",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "247",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "247",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "248",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "248",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "249",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "249",
            "y": "0.015833209675026",
            "series": "Forest probability of class 1"
          },
          {
            "x": "250",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "250",
            "y": "0.0032488628979857",
            "series": "Forest probability of class 1"
          },
          {
            "x": "251",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "251",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "252",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "252",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "253",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "253",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "254",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "254",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "255",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "255",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "256",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "256",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "257",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "257",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "258",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "258",
            "y": "0.015833209675026",
            "series": "Forest probability of class 1"
          },
          {
            "x": "259",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "259",
            "y": "0.015833209675026",
            "series": "Forest probability of class 1"
          },
          {
            "x": "260",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "260",
            "y": "0.015833209675026",
            "series": "Forest probability of class 1"
          },
          {
            "x": "261",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "261",
            "y": "0.179869463648231",
            "series": "Forest probability of class 1"
          },
          {
            "x": "262",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "262",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "263",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "263",
            "y": "0.179869463648231",
            "series": "Forest probability of class 1"
          },
          {
            "x": "264",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "264",
            "y": "0.179869463648231",
            "series": "Forest probability of class 1"
          },
          {
            "x": "265",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "265",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "266",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "266",
            "y": "0.179869463648231",
            "series": "Forest probability of class 1"
          },
          {
            "x": "267",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "267",
            "y": "0.154685769474791",
            "series": "Forest probability of class 1"
          },
          {
            "x": "268",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "268",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "269",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "269",
            "y": "0.015833209675026",
            "series": "Forest probability of class 1"
          },
          {
            "x": "270",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "270",
            "y": "0.0032488628979857",
            "series": "Forest probability of class 1"
          },
          {
            "x": "271",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "271",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "272",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "272",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "273",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "273",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "274",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "274",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "275",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "275",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "276",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "276",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "277",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "277",
            "y": "0.0272296782457075",
            "series": "Forest probability of class 1"
          },
          {
            "x": "278",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "278",
            "y": "0.015833209675026",
            "series": "Forest probability of class 1"
          },
          {
            "x": "279",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "279",
            "y": "0.015833209675026",
            "series": "Forest probability of class 1"
          },
          {
            "x": "280",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "280",
            "y": "0.015833209675026",
            "series": "Forest probability of class 1"
          },
          {
            "x": "281",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "281",
            "y": "0.179869463648231",
            "series": "Forest probability of class 1"
          },
          {
            "x": "282",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "282",
            "y": "0.179869463648231",
            "series": "Forest probability of class 1"
          },
          {
            "x": "283",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "283",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "284",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "284",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "285",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "285",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "286",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "286",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "287",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "287",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "288",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "288",
            "y": "0.0999868797718438",
            "series": "Forest probability of class 1"
          },
          {
            "x": "289",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "289",
            "y": "0.015833209675026",
            "series": "Forest probability of class 1"
          },
          {
            "x": "290",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "290",
            "y": "0.015833209675026",
            "series": "Forest probability of class 1"
          },
          {
            "x": "291",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "291",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "292",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "292",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "293",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "293",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "294",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "294",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "295",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "295",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "296",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "296",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "297",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "297",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "298",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "298",
            "y": "0.015833209675026",
            "series": "Forest probability of class 1"
          },
          {
            "x": "299",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "299",
            "y": "0.015833209675026",
            "series": "Forest probability of class 1"
          },
          {
            "x": "300",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "300",
            "y": "0.015833209675026",
            "series": "Forest probability of class 1"
          },
          {
            "x": "301",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "301",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "302",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "302",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "303",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "303",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "304",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "304",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "305",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "305",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "306",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "306",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "307",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "307",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "308",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "308",
            "y": "0.0032488628979857",
            "series": "Forest probability of class 1"
          },
          {
            "x": "309",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "309",
            "y": "0.0032488628979857",
            "series": "Forest probability of class 1"
          },
          {
            "x": "310",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "310",
            "y": "0.0032488628979857",
            "series": "Forest probability of class 1"
          },
          {
            "x": "311",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "311",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "312",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "312",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "313",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "313",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "314",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "314",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "315",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "315",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "316",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "316",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "317",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "317",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "318",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "318",
            "y": "0.015833209675026",
            "series": "Forest probability of class 1"
          },
          {
            "x": "319",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "319",
            "y": "0.015833209675026",
            "series": "Forest probability of class 1"
          },
          {
            "x": "320",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "320",
            "y": "0.015833209675026",
            "series": "Forest probability of class 1"
          },
          {
            "x": "321",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "321",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "322",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "322",
            "y": "0.154685769474791",
            "series": "Forest probability of class 1"
          },
          {
            "x": "323",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "323",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "324",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "324",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "325",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "325",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "326",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "326",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "327",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "327",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "328",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "328",
            "y": "0.0398140250227478",
            "series": "Forest probability of class 1"
          },
          {
            "x": "329",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "329",
            "y": "0.015833209675026",
            "series": "Forest probability of class 1"
          },
          {
            "x": "330",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "330",
            "y": "0.0032488628979857",
            "series": "Forest probability of class 1"
          },
          {
            "x": "331",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "331",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "332",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "332",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "333",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "333",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "334",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "334",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "335",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "335",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "336",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "336",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "337",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "337",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "338",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "338",
            "y": "0.015833209675026",
            "series": "Forest probability of class 1"
          },
          {
            "x": "339",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "339",
            "y": "0.015833209675026",
            "series": "Forest probability of class 1"
          },
          {
            "x": "340",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "340",
            "y": "0.015833209675026",
            "series": "Forest probability of class 1"
          },
          {
            "x": "341",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "341",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "342",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "342",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "343",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "343",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "344",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "344",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "345",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "345",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "346",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "346",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "347",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "347",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "348",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "348",
            "y": "0.015833209675026",
            "series": "Forest probability of class 1"
          },
          {
            "x": "349",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "349",
            "y": "0.015833209675026",
            "series": "Forest probability of class 1"
          },
          {
            "x": "350",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "350",
            "y": "0.015833209675026",
            "series": "Forest probability of class 1"
          },
          {
            "x": "351",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "351",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "352",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "352",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "353",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "353",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "354",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "354",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "355",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "355",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "356",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "356",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "357",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "357",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "358",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "358",
            "y": "0.015833209675026",
            "series": "Forest probability of class 1"
          },
          {
            "x": "359",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "359",
            "y": "0.015833209675026",
            "series": "Forest probability of class 1"
          },
          {
            "x": "360",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "360",
            "y": "0.015833209675026",
            "series": "Forest probability of class 1"
          },
          {
            "x": "361",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "361",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "362",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "362",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "363",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "363",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "364",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "364",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "365",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "365",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "366",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "366",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "367",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "367",
            "y": "0.0975474605310355",
            "series": "Forest probability of class 1"
          },
          {
            "x": "368",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "368",
            "y": "0.015833209675026",
            "series": "Forest probability of class 1"
          },
          {
            "x": "369",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "369",
            "y": "0.015833209675026",
            "series": "Forest probability of class 1"
          },
          {
            "x": "370",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "370",
            "y": "0.015833209675026",
            "series": "Forest probability of class 1"
          },
          {
            "x": "371",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "371",
            "y": "0.179869463648231",
            "series": "Forest probability of class 1"
          },
          {
            "x": "372",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "372",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "373",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "373",
            "y": "0.179869463648231",
            "series": "Forest probability of class 1"
          },
          {
            "x": "374",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "374",
            "y": "0.179869463648231",
            "series": "Forest probability of class 1"
          },
          {
            "x": "375",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "375",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "376",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "376",
            "y": "0.179869463648231",
            "series": "Forest probability of class 1"
          },
          {
            "x": "377",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "377",
            "y": "0.154685769474791",
            "series": "Forest probability of class 1"
          },
          {
            "x": "378",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "378",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "379",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "379",
            "y": "0.015833209675026",
            "series": "Forest probability of class 1"
          },
          {
            "x": "380",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "380",
            "y": "0.0032488628979857",
            "series": "Forest probability of class 1"
          },
          {
            "x": "381",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "381",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "382",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "382",
            "y": "0.154685769474791",
            "series": "Forest probability of class 1"
          },
          {
            "x": "383",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "383",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "384",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "384",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "385",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "385",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "386",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "386",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "387",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "387",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "388",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "388",
            "y": "0.0398140250227478",
            "series": "Forest probability of class 1"
          },
          {
            "x": "389",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "389",
            "y": "0.015833209675026",
            "series": "Forest probability of class 1"
          },
          {
            "x": "390",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "390",
            "y": "0.0032488628979857",
            "series": "Forest probability of class 1"
          },
          {
            "x": "391",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "391",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "392",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "392",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "393",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "393",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "394",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "394",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "395",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "395",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "396",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "396",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "397",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "397",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "398",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "398",
            "y": "0.015833209675026",
            "series": "Forest probability of class 1"
          },
          {
            "x": "399",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "399",
            "y": "0.015833209675026",
            "series": "Forest probability of class 1"
          },
          {
            "x": "400",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "400",
            "y": "0.015833209675026",
            "series": "Forest probability of class 1"
          },
          {
            "x": "401",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "401",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "402",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "402",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "403",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "403",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "404",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "404",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "405",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "405",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "406",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "406",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "407",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "407",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "408",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "408",
            "y": "0.015833209675026",
            "series": "Forest probability of class 1"
          },
          {
            "x": "409",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "409",
            "y": "0.015833209675026",
            "series": "Forest probability of class 1"
          },
          {
            "x": "410",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "410",
            "y": "0.015833209675026",
            "series": "Forest probability of class 1"
          },
          {
            "x": "411",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "411",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "412",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "412",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "413",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "413",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "414",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "414",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "415",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "415",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "416",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "416",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "417",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "417",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "418",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "418",
            "y": "0.015833209675026",
            "series": "Forest probability of class 1"
          },
          {
            "x": "419",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "419",
            "y": "0.015833209675026",
            "series": "Forest probability of class 1"
          },
          {
            "x": "420",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "420",
            "y": "0.015833209675026",
            "series": "Forest probability of class 1"
          },
          {
            "x": "421",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "421",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "422",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "422",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "423",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "423",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "424",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "424",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "425",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "425",
            "y": "0.154685769474791",
            "series": "Forest probability of class 1"
          },
          {
            "x": "426",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "426",
            "y": "0.154685769474791",
            "series": "Forest probability of class 1"
          },
          {
            "x": "427",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "427",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "428",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "428",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "429",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "429",
            "y": "0.0032488628979857",
            "series": "Forest probability of class 1"
          },
          {
            "x": "430",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "430",
            "y": "0.0032488628979857",
            "series": "Forest probability of class 1"
          },
          {
            "x": "431",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "431",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "432",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "432",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "433",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "433",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "434",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "434",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "435",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "435",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "436",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "436",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "437",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "437",
            "y": "0.154685769474791",
            "series": "Forest probability of class 1"
          },
          {
            "x": "438",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "438",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "439",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "439",
            "y": "0.0032488628979857",
            "series": "Forest probability of class 1"
          },
          {
            "x": "440",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "440",
            "y": "0.0032488628979857",
            "series": "Forest probability of class 1"
          },
          {
            "x": "441",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "441",
            "y": "0.154685769474791",
            "series": "Forest probability of class 1"
          },
          {
            "x": "442",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "442",
            "y": "0.154685769474791",
            "series": "Forest probability of class 1"
          },
          {
            "x": "443",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "443",
            "y": "0.154685769474791",
            "series": "Forest probability of class 1"
          },
          {
            "x": "444",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "444",
            "y": "0.154685769474791",
            "series": "Forest probability of class 1"
          },
          {
            "x": "445",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "445",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "446",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "446",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "447",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "447",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "448",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "448",
            "y": "0.0272296782457075",
            "series": "Forest probability of class 1"
          },
          {
            "x": "449",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "449",
            "y": "0.0032488628979857",
            "series": "Forest probability of class 1"
          },
          {
            "x": "450",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "450",
            "y": "0.0032488628979857",
            "series": "Forest probability of class 1"
          },
          {
            "x": "451",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "451",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "452",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "452",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "453",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "453",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "454",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "454",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "455",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "455",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "456",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "456",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "457",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "457",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "458",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "458",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "459",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "459",
            "y": "0.0032488628979857",
            "series": "Forest probability of class 1"
          },
          {
            "x": "460",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "460",
            "y": "0.0032488628979857",
            "series": "Forest probability of class 1"
          },
          {
            "x": "461",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "461",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "462",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "462",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "463",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "463",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "464",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "464",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "465",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "465",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "466",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "466",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "467",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "467",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "468",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "468",
            "y": "0.0032488628979857",
            "series": "Forest probability of class 1"
          },
          {
            "x": "469",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "469",
            "y": "0.0032488628979857",
            "series": "Forest probability of class 1"
          },
          {
            "x": "470",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "470",
            "y": "0.0032488628979857",
            "series": "Forest probability of class 1"
          },
          {
            "x": "471",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "471",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "472",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "472",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "473",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "473",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "474",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "474",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "475",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "475",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "476",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "476",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "477",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "477",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "478",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "478",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "479",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "479",
            "y": "0.0272296782457075",
            "series": "Forest probability of class 1"
          },
          {
            "x": "480",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "480",
            "y": "0.0032488628979857",
            "series": "Forest probability of class 1"
          },
          {
            "x": "481",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "481",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "482",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "482",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "483",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "483",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "484",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "484",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "485",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "485",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "486",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "486",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "487",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "487",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "488",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "488",
            "y": "0.0032488628979857",
            "series": "Forest probability of class 1"
          },
          {
            "x": "489",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "489",
            "y": "0.0032488628979857",
            "series": "Forest probability of class 1"
          },
          {
            "x": "490",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "490",
            "y": "0.015833209675026",
            "series": "Forest probability of class 1"
          },
          {
            "x": "491",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "491",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "492",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "492",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "493",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "493",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "494",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "494",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "495",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "495",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "496",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "496",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "497",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "497",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "498",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "498",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "499",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "499",
            "y": "0.0032488628979857",
            "series": "Forest probability of class 1"
          },
          {
            "x": "500",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "500",
            "y": "0.0032488628979857",
            "series": "Forest probability of class 1"
          },
          {
            "x": "501",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "501",
            "y": "0.154685769474791",
            "series": "Forest probability of class 1"
          },
          {
            "x": "502",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "502",
            "y": "0.154685769474791",
            "series": "Forest probability of class 1"
          },
          {
            "x": "503",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "503",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "504",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "504",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "505",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "505",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "506",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "506",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "507",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "507",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "508",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "508",
            "y": "0.0272296782457075",
            "series": "Forest probability of class 1"
          },
          {
            "x": "509",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "509",
            "y": "0.0032488628979857",
            "series": "Forest probability of class 1"
          },
          {
            "x": "510",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "510",
            "y": "0.0032488628979857",
            "series": "Forest probability of class 1"
          },
          {
            "x": "511",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "511",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "512",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "512",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "513",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "513",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "514",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "514",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "515",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "515",
            "y": "0.154685769474791",
            "series": "Forest probability of class 1"
          },
          {
            "x": "516",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "516",
            "y": "0.154685769474791",
            "series": "Forest probability of class 1"
          },
          {
            "x": "517",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "517",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "518",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "518",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "519",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "519",
            "y": "0.0032488628979857",
            "series": "Forest probability of class 1"
          },
          {
            "x": "520",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "520",
            "y": "0.0032488628979857",
            "series": "Forest probability of class 1"
          },
          {
            "x": "521",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "521",
            "y": "0.179869463648231",
            "series": "Forest probability of class 1"
          },
          {
            "x": "522",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "522",
            "y": "0.179869463648231",
            "series": "Forest probability of class 1"
          },
          {
            "x": "523",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "523",
            "y": "0.179869463648231",
            "series": "Forest probability of class 1"
          },
          {
            "x": "524",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "524",
            "y": "0.179869463648231",
            "series": "Forest probability of class 1"
          },
          {
            "x": "525",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "525",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "526",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "526",
            "y": "0.154685769474791",
            "series": "Forest probability of class 1"
          },
          {
            "x": "527",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "527",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "528",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "528",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "529",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "529",
            "y": "0.0032488628979857",
            "series": "Forest probability of class 1"
          },
          {
            "x": "530",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "530",
            "y": "0.0032488628979857",
            "series": "Forest probability of class 1"
          },
          {
            "x": "531",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "531",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "532",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "532",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "533",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "533",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "534",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "534",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "535",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "535",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "536",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "536",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "537",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "537",
            "y": "0.154685769474791",
            "series": "Forest probability of class 1"
          },
          {
            "x": "538",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "538",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "539",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "539",
            "y": "0.0032488628979857",
            "series": "Forest probability of class 1"
          },
          {
            "x": "540",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "540",
            "y": "0.0032488628979857",
            "series": "Forest probability of class 1"
          },
          {
            "x": "541",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "541",
            "y": "0.179869463648231",
            "series": "Forest probability of class 1"
          },
          {
            "x": "542",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "542",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "543",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "543",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "544",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "544",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "545",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "545",
            "y": "0.154685769474791",
            "series": "Forest probability of class 1"
          },
          {
            "x": "546",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "546",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "547",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "547",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "548",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "548",
            "y": "0.0999868797718438",
            "series": "Forest probability of class 1"
          },
          {
            "x": "549",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "549",
            "y": "0.015833209675026",
            "series": "Forest probability of class 1"
          },
          {
            "x": "550",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "550",
            "y": "0.0032488628979857",
            "series": "Forest probability of class 1"
          },
          {
            "x": "551",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "551",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "552",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "552",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "553",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "553",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "554",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "554",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "555",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "555",
            "y": "0.154685769474791",
            "series": "Forest probability of class 1"
          },
          {
            "x": "556",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "556",
            "y": "0.154685769474791",
            "series": "Forest probability of class 1"
          },
          {
            "x": "557",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "557",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "558",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "558",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "559",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "559",
            "y": "0.0032488628979857",
            "series": "Forest probability of class 1"
          },
          {
            "x": "560",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "560",
            "y": "0.0032488628979857",
            "series": "Forest probability of class 1"
          },
          {
            "x": "561",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "561",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "562",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "562",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "563",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "563",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "564",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "564",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "565",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "565",
            "y": "0.154685769474791",
            "series": "Forest probability of class 1"
          },
          {
            "x": "566",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "566",
            "y": "0.154685769474791",
            "series": "Forest probability of class 1"
          },
          {
            "x": "567",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "567",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "568",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "568",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "569",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "569",
            "y": "0.0032488628979857",
            "series": "Forest probability of class 1"
          },
          {
            "x": "570",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "570",
            "y": "0.0032488628979857",
            "series": "Forest probability of class 1"
          },
          {
            "x": "571",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "571",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "572",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "572",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "573",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "573",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "574",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "574",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "575",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "575",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "576",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "576",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "577",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "577",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "578",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "578",
            "y": "0.015833209675026",
            "series": "Forest probability of class 1"
          },
          {
            "x": "579",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "579",
            "y": "0.015833209675026",
            "series": "Forest probability of class 1"
          },
          {
            "x": "580",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "580",
            "y": "0.0032488628979857",
            "series": "Forest probability of class 1"
          },
          {
            "x": "581",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "581",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "582",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "582",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "583",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "583",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "584",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "584",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "585",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "585",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "586",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "586",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "587",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "587",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "588",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "588",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "589",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "589",
            "y": "0.0272296782457075",
            "series": "Forest probability of class 1"
          },
          {
            "x": "590",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "590",
            "y": "0.0032488628979857",
            "series": "Forest probability of class 1"
          },
          {
            "x": "591",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "591",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "592",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "592",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "593",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "593",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "594",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "594",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "595",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "595",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "596",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "596",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "597",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "597",
            "y": "0.154685769474791",
            "series": "Forest probability of class 1"
          },
          {
            "x": "598",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "598",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "599",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "599",
            "y": "0.0032488628979857",
            "series": "Forest probability of class 1"
          },
          {
            "x": "600",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "600",
            "y": "0.0032488628979857",
            "series": "Forest probability of class 1"
          },
          {
            "x": "601",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "601",
            "y": "0.179869463648231",
            "series": "Forest probability of class 1"
          },
          {
            "x": "602",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "602",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "603",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "603",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "604",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "604",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "605",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "605",
            "y": "0.154685769474791",
            "series": "Forest probability of class 1"
          },
          {
            "x": "606",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "606",
            "y": "0.241160799628827",
            "series": "Forest probability of class 1"
          },
          {
            "x": "607",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "607",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "608",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "608",
            "y": "0.0999868797718438",
            "series": "Forest probability of class 1"
          },
          {
            "x": "609",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "609",
            "y": "0.015833209675026",
            "series": "Forest probability of class 1"
          },
          {
            "x": "610",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "610",
            "y": "0.0032488628979857",
            "series": "Forest probability of class 1"
          },
          {
            "x": "611",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "611",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "612",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "612",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "613",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "613",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "614",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "614",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "615",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "615",
            "y": "0.154685769474791",
            "series": "Forest probability of class 1"
          },
          {
            "x": "616",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "616",
            "y": "0.154685769474791",
            "series": "Forest probability of class 1"
          },
          {
            "x": "617",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "617",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "618",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "618",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "619",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "619",
            "y": "0.0032488628979857",
            "series": "Forest probability of class 1"
          },
          {
            "x": "620",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "620",
            "y": "0.0032488628979857",
            "series": "Forest probability of class 1"
          },
          {
            "x": "621",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "621",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "622",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "622",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "623",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "623",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "624",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "624",
            "y": "0.0933944334941942",
            "series": "Forest probability of class 1"
          },
          {
            "x": "625",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "625",
            "y": "0.154685769474791",
            "series": "Forest probability of class 1"
          },
          {
            "x": "626",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "626",
            "y": "0.154685769474791",
            "series": "Forest probability of class 1"
          },
          {
            "x": "627",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "627",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "628",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "628",
            "y": "0.147954592452617",
            "series": "Forest probability of class 1"
          },
          {
            "x": "629",
            "y": "0",
            "series": "Observed outcome"
          },
          {
            "x": "629",
            "y": "0.0032488628979857",
            "series": "Forest probability of class 1"
          },
          {
            "x": "630",
            "y": "1",
            "series": "Observed outcome"
          },
          {
            "x": "630",
            "y": "0.0032488628979857",
            "series": "Forest probability of class 1"
          }
        ],
        "plotFile": "ml09-fixed-results/realdata-company-r/plot.svg",
        "plotSHA256": "d699f75ad5fd694d3d67090c73c17be53561fe99bc2b3fb86c797aa7a729c89c",
        "files": [
          {
            "file": "ml09-fixed-results/realdata-company-r/full-result.Rtext",
            "sha256": "5cf4bb54bd75bd1f210d634301417c46d6780c65db899d0b5cddcec10c698d0b"
          },
          {
            "file": "ml09-fixed-results/realdata-company-r/plot-points.csv",
            "sha256": "d6e2653df52d855f02ecdbf8b91dd47e8a10a967b293b99698387e0c8fd5d9c0"
          },
          {
            "file": "ml09-fixed-results/realdata-company-r/plot.svg",
            "sha256": "d699f75ad5fd694d3d67090c73c17be53561fe99bc2b3fb86c797aa7a729c89c"
          },
          {
            "file": "ml09-fixed-results/realdata-company-r/summary.csv",
            "sha256": "87a440ce5a3e662915824bc1555af5374b3e08e2a3abdca7cfd27e5dc85100db"
          }
        ],
        "scope": "Actually executed self-contained fixed example; current web controls execute separately. Python Fraction and finite-precision base R. Author gate, not independent peer."
      }
    }
  }
}
