{
  "chapter": "METR-20",
  "status": "Author actual fixed-program archive; independent fixed/UI peer and native gates separate",
  "programProcesses": 30,
  "successful": 28,
  "expectedInvalid": 2,
  "storedSVG": 28,
  "authorTargetLaunchesIncludingHistorical": 35,
  "history": "Initial30:25normal successes,3R actual-source transport failures before native CSV access because a Korean Windows argv data path was mangled in C locale,2genuine PSD rejects. Follow-up5:3R data programs rerun from same-byte ASCII native-source staging and2Python source programs rerun for English title spacing only. Raw failures,commands/code and all old outputs remain private. Current archive30 is not the full35-target history.",
  "sourceScope": "All2500county waves,722NSW experimental people/1444waves and410NJPA raw records/820slots are retained in the respective fixed source projections. Source programs read only the three factual CSVs; no engine/model/answer CSV import.",
  "publicProjection": "Complete code and short summaries embedded; original SVG/full JSON/CSV external links. Full means the declared bounded standalone teaching projection,not a replacement for every general API diagnostic or confidence procedure. Original executable commands/cwd/raw stdout/stderr remain private.",
  "dependencies": {
    "Python": "Python3 standard Fraction library plus Matplotlib Agg",
    "R": "Base R only",
    "sourcePrograms": "Three retained native CSVs,ordinary fixed hypothetical examples require no data files"
  },
  "historicalWholeCandidateBindings": {
    "body": "5866d8e6e1545290b6d4546dc0475e1ddd5f4f08fb86213d2fdff07e4a758aab",
    "cases": "c08afeaf5086acd5e2b1410f8a64e2f1699fc27a27cef3f32a0458d3adb2db8d",
    "engine": "ab9c2354fa493e535db04e10b5d491a4f19e86bc4cd86ddb5072aec2db2fcdb4",
    "source": "1f0e337bbf72f6341c7a82337e7bacf2dd598fdad2f1900d5e7026daef446627"
  },
  "runs": [
    {
      "api": "twobytwo",
      "variant": "paired-four-changes",
      "profile": "paired-four-changes",
      "language": "Python",
      "file": "metr20-programs/paired-four-changes-python.py",
      "codeSHA256": "d669345266de0608f545d12ec5852075712cee9622f7e8b10d995db931ca9a79",
      "returnCode": 0,
      "expectedRejection": false,
      "title": {
        "ko": "같은 네 개체의 변화와 두 분산",
        "en": "Four paired changes and two variances"
      },
      "code": "\"\"\"METR20 actual sources. Python standard library, exact stored-value rationals.\r\nRead ONLY the three native-observation CSVs; no JS engine,model JSON,derived\r\nanswers,private modules or internet needed. Outcome measurement/identification\r\nand valid sampling inference remain separate from exact finite arithmetic.\r\nRun: python metr20-reproduce.py --data-dir PATH --out NEW_EMPTY_DIRECTORY\r\n\"\"\"\r\nfrom pathlib import Path\r\nfrom fractions import Fraction as Q\r\nfrom collections import defaultdict,Counter\r\nimport csv,json,math,argparse,hashlib\r\n\r\nUNIT={'country':'log teen-employment points','person':'recorded real earnings','company':'FTE employees'}\r\nCLOCK={'country':'calendar year','person':'calendar year','company':'survey-wave index'}\r\nSTEP={'country':1,'person':3,'company':1}\r\nFILES={'country':'actual2500-county-mpdta-all6-fields.csv','person':'actual38408-NSW-all15-fields.csv','company':'actual410-NJPA-all46-fields.csv'}\r\ndef avg(v):return sum(v,Q(0))/len(v)if v else None\r\ndef samplevar(v):return sum(((x-avg(v))**2 for x in v),Q(0))/(len(v)-1)if len(v)>1 else None\r\ndef binary(s):return None if s=='.'else Q.from_float(float(s))\r\ndef token(v):\r\n if v is None:return ''\r\n if isinstance(v,bool):return 'true'if v else'false'\r\n return str(v)\r\ndef safe_float(v):\r\n if v is None:return None\r\n try:r=float(v)\r\n except OverflowError:return None\r\n return r if math.isfinite(r)else None\r\ndef read(p):\r\n with p.open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))\r\ndef write(p,rows,head=None):\r\n if head is None:\r\n  assert rows;head=list(rows[0])\r\n with p.open('w',encoding='utf8',newline='')as f:\r\n  w=csv.DictWriter(f,fieldnames=head);w.writeheader();w.writerows({k:token(r.get(k))for k in head}for r in rows)\r\ndef source(data):\r\n raw={k:read(data/n)for k,n in FILES.items()};assert[len(raw[k])for k in FILES]==[2500,38408,410]\r\n models={k:[]for k in FILES}\r\n for r in raw['country']:\r\n  g0=int(r['first.treat']);g=None if g0==0 else g0;assert int(r['treat'])==int(g is not None)\r\n  models['country'].append(dict(id='mpdta:'+r['sourceRow'],entity='county:'+str(int(r['countyreal'])),time=int(r['year']),y=binary(r['lemp']),g=g,sourceRow=int(r['sourceRow']),nativeID=r['countyreal']))\r\n for r in raw['person']:\r\n  selected=int(r['experimental'])==1;assert selected==(int(r['sample'])==1);assert(r['treated']!='.')==selected\r\n  if selected:\r\n   d=int(r['treated']);assert d in[0,1]\r\n   models['person'].append(dict(id='nsw:'+r['sourceRow'],entity='nsw-id:'+str(int(r['id'])),time=int(r['year']),y=binary(r['re']),g=1978 if d else None,sourceRow=int(r['sourceRow']),nativeID=str(int(r['id']))))\r\n for r in raw['company']:\r\n  state=int(r['STATE']);assert state in[0,1]\r\n  for t,suffix in[(0,''),(1,'2')]:\r\n   a=[r[n+suffix]for n in['EMPFT','NMGRS','EMPPT']];y=None if'.'in a else Q(a[0])+Q(a[1])+Q(a[2])/2\r\n   models['company'].append(dict(id='njpa:'+r['sourceRow']+':wave'+str(t),entity='njpa-row:'+r['sourceRow'],time=t,y=y,g=1 if state else None,sourceRow=int(r['sourceRow']),nativeID=r['SHEET']))\r\n assert[len(models[k])for k in FILES]==[2500,1444,820]\r\n return models,raw\r\ndef panel(rows):\r\n groups={}\r\n for r in rows:\r\n  u=groups.setdefault(r['entity'],{'g':r['g'],'rows':{}});assert u['g']==r['g']and r['time']not in u['rows'];u['rows'][r['time']]=r\r\n return groups\r\ndef cell(groups,g,t,step,control):\r\n b=g-step;members=[];T=[];C=[]\r\n for key,u in groups.items():\r\n  role='treated'if u['g']==g else'control'if u['g']is None or(control=='notyet'and u['g']>max(t,b))else'excluded-comparison'\r\n  before=u['rows'].get(b);after=u['rows'].get(t);yb=None if before is None else before['y'];ya=None if after is None else after['y'];eligible=role!='excluded-comparison'and yb is not None and ya is not None\r\n  reason='target-or-already-exposed-cohort-not-valid-control'if role=='excluded-comparison'else'baseline-source-row-absent'if before is None else'target-time-source-row-absent'if after is None else'baseline-outcome-missing'if yb is None else'target-outcome-missing'if ya is None else''\r\n  m={'entity':key,'nativeID':next(iter(u['rows'].values()))['nativeID'],'g':u['g'],'role':role,'eligible':eligible,'baselineSourceId':None if before is None else before['id'],'targetSourceId':None if after is None else after['id'],'before':yb,'after':ya,'change':ya-yb if eligible else None,'reason':reason};members.append(m)\r\n  if eligible:(T if role=='treated'else C).append(m)\r\n d=avg([r['change']for r in T]);e=avg([r['change']for r in C]);estimate=None if d is None or e is None else d-e;defined=estimate is not None;scores={}\r\n for m in members:\r\n  s=None if not defined else Q(0)\r\n  if defined and m['eligible']:s=(m['change']-(d if m['role']=='treated'else e))/(len(T)if m['role']=='treated'else-len(C))\r\n  m['score']=s;scores[m['entity']]=s\r\n st=samplevar([r['change']for r in T]);sc=samplevar([r['change']for r in C]);v=None if st is None or sc is None else st/len(T)+sc/len(C)\r\n return {'g':g,'t':t,'baseline':b,'event':(t-g)//step,'phase':'mechanical-reference'if t==b else'post'if t>=g else'pre-placebo','defined':defined,'estimate':estimate,'T':T,'C':C,'members':members,'scores':scores,'HC0':None if not defined else sum((s*s for s in scores.values()),Q(0)),'unbiased':v,'treatedMeanBefore':avg([r['before']for r in T]),'treatedMeanAfter':avg([r['after']for r in T]),'treatedMeanChange':d,'controlMeanBefore':avg([r['before']for r in C]),'controlMeanAfter':avg([r['after']for r in C]),'controlMeanChange':e}\r\ndef covariance(cells):\r\n return[[None if not a['defined']or not b['defined']else sum((v*b['scores'][i]for i,v in a['scores'].items()),Q(0))for b in cells]for a in cells]\r\ndef aggregate(post,V,step):\r\n out=[]\r\n def push(typ,key,coeff):\r\n  estimate=None if not coeff or any(post[i]['estimate']is None for i in coeff)else sum((w*post[i]['estimate']for i,w in coeff.items()),Q(0));variance=None if estimate is None or any(V[i][j]is None for i in coeff for j in coeff)else sum((a*b*V[i][j]for i,a in coeff.items()for j,b in coeff.items()),Q(0));out.append({'type':typ,'key':key,'coeff':coeff,'estimate':estimate,'variance':variance})\r\n positive=[i for i,c in enumerate(post)if len(c['T'])>0];mass=sum(len(post[i]['T'])for i in positive)\r\n push('simple','overall',{i:Q(len(post[i]['T']),mass)for i in positive}if mass else{})\r\n for typ in['event','calendar','group']:\r\n  groups=defaultdict(list)\r\n  for i,c in enumerate(post):groups[c['event']if typ=='event'else c['t']if typ=='calendar'else c['g']].append(i)\r\n  overall={};cohortMass=sum(len(post[ii[0]]['T'])for ii in groups.values())if typ=='group'else 0\r\n  for key,ii in sorted(groups.items()):\r\n   jj=[i for i in ii if len(post[i]['T'])>0]\r\n   if typ=='group':\r\n    assert len({len(post[i]['T'])for i in ii})<=1\r\n    coeff={i:Q(1,len(jj))for i in jj}if jj else{}\r\n    if cohortMass:\r\n     for i,w in coeff.items():overall[i]=w*Q(len(post[ii[0]]['T']),cohortMass)\r\n   else:\r\n    total=sum(len(post[i]['T'])for i in jj);coeff={i:Q(len(post[i]['T']),total)for i in jj}if total else{}\r\n   push(typ,str(key),coeff)\r\n  if typ=='group':push(typ,'overall',overall)\r\n return out\r\ndef twfe(groups,times):\r\n ledger=[];good={}\r\n for key,u in groups.items():\r\n  absent=[t for t in times if t not in u['rows']];missing=[t for t in times if t in u['rows']and u['rows'][t]['y']is None];eligible=bool(times)and not absent and not missing\r\n  ledger.append({'entity':key,'g':u['g'],'nativeID':next(iter(u['rows'].values()))['nativeID'],'eligible':eligible,'absentTimes':','.join(map(str,absent)),'missingOutcomeTimes':','.join(map(str,missing)),'originalRows':len(u['rows'])})\r\n  if eligible:good[key]=u\r\n rows=[dict(**u['rows'][t],D=Q(u['g']is not None and t>=u['g']))for key,u in good.items()for t in times]\r\n em={k:{'D':avg([Q(u['g']is not None and t>=u['g'])for t in times]),'Y':avg([u['rows'][t]['y']for t in times])}for k,u in good.items()};tm={t:{'D':avg([Q(u['g']is not None and t>=u['g'])for u in good.values()]),'Y':avg([u['rows'][t]['y']for u in good.values()])}for t in times};gd=avg([r['D']for r in rows]);gy=avg([r['y']for r in rows]);num=den=Q(0)\r\n for r in rows:\r\n  r['residualD']=r['D']-em[r['entity']]['D']-tm[r['time']]['D']+gd;r['residualY']=r['y']-em[r['entity']]['Y']-tm[r['time']]['Y']+gy;num+=r['residualD']*r['residualY'];den+=r['residualD']**2\r\n beta=num/den if den else None;weights={}\r\n for r in rows:\r\n  r['projectionCoefficient']=r['residualD']/den if den else None;r['regressionResidual']=r['residualY']-beta*r['residualD']if beta is not None else None\r\n  if r['D']:\r\n   k=(r['g'],r['time']);z=weights.setdefault(k,{'rows':0,'coefficient':Q(0)if den else None});z['rows']+=1\r\n   if den:z['coefficient']+=r['projectionCoefficient']\r\n return {'ledger':ledger,'rows':rows,'num':num,'den':den,'beta':beta,'weights':weights,'balancedEntities':len(good)}\r\ndef adjacent_pre(groups,g,t,step,control):\r\n b=t-step;T=[];C=[]\r\n for u in groups.values():\r\n  if u['g']==g:target=T\r\n  elif u['g']is None or(control=='notyet'and u['g']>max(t,b)):target=C\r\n  else:continue\r\n  before=u['rows'].get(b);after=u['rows'].get(t)\r\n  if before is not None and after is not None and before['y']is not None and after['y']is not None:target.append(after['y']-before['y'])\r\n return None if not T or not C else avg(T)-avg(C)\r\n\r\n\"\"\"New bounded teaching projections. The program is self-contained after build.\r\nExact Fraction finite algebra; figures and9-digit summary are approximations.\r\nIt is not a general parser/API replacement or a causal/inference certificate.\r\n\"\"\"\r\ndef paired(treated,control):\r\n def stats(rr):\r\n  use=[r for r in rr if r['before']is not None and r['after']is not None];delta=[Q(r['after'])-Q(r['before'])for r in use]\r\n  return dict(sourcePairs=len(rr),eligiblePairs=len(use),excludedPairs=len(rr)-len(use),meanBefore=avg([Q(r['before'])for r in use]),meanAfter=avg([Q(r['after'])for r in use]),meanChange=avg(delta),sampleChangeVariance=samplevar(delta))\r\n T,C=stats(treated),stats(control);defined=T['eligiblePairs']>0 and C['eligiblePairs']>0;estimate=T['meanChange']-C['meanChange']if defined else None;records=[]\r\n for group,rr,s in [('treated',treated,T),('control',control,C)]:\r\n  for r in rr:\r\n   before=None if r['before']is None else Q(r['before']);after=None if r['after']is None else Q(r['after']);eligible=before is not None and after is not None;delta=after-before if eligible else None;score=None if not defined else Q(0)if not eligible else(delta-s['meanChange'])/(s['eligiblePairs']if group=='treated'else-s['eligiblePairs']);records.append(dict(id=r['id'],role=group,before=before,after=after,eligible=eligible,change=delta,score=score))\r\n unbiased=None if not defined or T['eligiblePairs']<2 or C['eligiblePairs']<2 else T['sampleChangeVariance']/T['eligiblePairs']+C['sampleChangeVariance']/C['eligiblePairs'];hc0=None if not defined else sum((r['score']**2 for r in records),Q(0))\r\n return dict(defined=defined,estimate=estimate,treated=T,control=C,unbiasedVariance=unbiased,HC0=hc0,rows=records)\r\ndef literal_panel(raw):\r\n return[dict(r,y=None if r['y']is None else Q(r['y']),nativeID=r['entity'],sourceRow=i+1)for i,r in enumerate(raw)]\r\ndef att_projection(rows,control='never',step=1):\r\n G=panel(rows);times=sorted({r['time']for r in rows});cohorts=sorted({r['g']for r in rows if r['g']is not None});cells=[cell(G,g,t,step,control)for g in cohorts for t in times]\r\n return dict(sourceRows=len(rows),sourceEntities=len(G),step=step,control=control,cells=cells,covariance=covariance(cells))\r\ndef psd(V):\r\n A=[r[:]for r in V];rank=0\r\n while A:\r\n  if any(A[i][i]<0 for i in range(len(A))):raise ValueError('covariance-must-be-positive-semidefinite')\r\n  p=next((i for i in range(len(A))if A[i][i]>0),None)\r\n  if p is None:\r\n   if any(v for r in A for v in r):raise ValueError('covariance-must-be-positive-semidefinite')\r\n   return rank\r\n  A[0],A[p]=A[p],A[0]\r\n  for r in A:r[0],r[p]=r[p],r[0]\r\n  d=A[0][0];A=[[A[i][j]-A[i][0]*A[0][j]/d for j in range(1,len(A))]for i in range(1,len(A))];rank+=1\r\n return rank\r\ndef linear_aggregate(a):\r\n rr=[dict(r,estimate=None if r['estimate']is None else Q(r['estimate']),weight=Q(r['weight']))for r in a['cells']];V=[[Q(v)for v in r]for r in a['covariance']]if 'covariance'in a else None\r\n if V is not None:\r\n  assert len(V)==len(rr)and all(len(z)==len(rr)for z in V);assert all(V[i][j]==V[j][i]for i in range(len(rr))for j in range(len(rr)));rank=psd(V)\r\n else:rank=None\r\n selected=[i for i,r in enumerate(rr)if r['time']>=r['cohort']and r['weight']>0];weights={}\r\n if a.get('type','simple')=='simple':\r\n  mass=sum((rr[i]['weight']for i in selected),Q(0));weights={i:rr[i]['weight']/mass for i in selected}if mass else{}\r\n else:\r\n  gg=defaultdict(list)\r\n  for i in selected:gg[rr[i]['cohort']].append(i)\r\n  assert all(len({rr[i]['weight']for i in ii})==1 for ii in gg.values());mass=sum((rr[ii[0]]['weight']for ii in gg.values()),Q(0));weights={i:rr[ii[0]]['weight']/mass/len(ii)for ii in gg.values()for i in ii}if mass else{}\r\n estimate=None if not weights or any(rr[i]['estimate']is None for i in weights)else sum((w*rr[i]['estimate']for i,w in weights.items()),Q(0));variance=None if estimate is None or V is None else sum((x*y*V[i][j]for i,x in weights.items()for j,y in weights.items()),Q(0))\r\n return dict(type=a.get('type','simple'),defined=estimate is not None,estimate=estimate,variance=variance,covarianceRank=rank,weights=[dict(sourceIndex=i,cohort=rr[i]['cohort'],time=rr[i]['time'],coefficient=w,estimate=rr[i]['estimate'],contribution=None if rr[i]['estimate']is None else w*rr[i]['estimate'])for i,w in weights.items()],cells=rr,covariance=V)\r\ndef sensitivity_fixed(a):\r\n estimate=Q(a['estimate']);M=Q(a['M']);h=a.get('horizon',1);assert M>=0 and h>=1\r\n pre=[Q(v)for v in a.get('preDifferences',[])];scale=Q(a['scale'])if 'scale'in a else max(map(abs,pre))if pre else None;budget=None if scale is None else M*scale*h\r\n return dict(defined=scale is not None,estimate=estimate,scale=scale,M=M,horizon=h,biasBudget=budget,lower=None if budget is None else estimate-budget,upper=None if budget is None else estimate+budget,preDifferences=pre,confidenceLevel=None)\r\ndef realdata_fixed(kind,data):\r\n models,raw=source(data);rows=models[kind];G=panel(rows);times=sorted({r['time']for r in rows});step=STEP[kind];aa=att_projection(rows,'never',step);post=[r for r in aa['cells']if r['phase']=='post'];aggs=aggregate(post,covariance(post),step);tf=twfe(G,times)\r\n return dict(kind=kind,unit=UNIT[kind],periodUnit=CLOCK[kind],nativeRows=len(raw[kind]),modelRows=len(rows),entities=len(G),sourceRows=rows,att=aa,aggregations=aggs,twfe=tf,scope='Complete source frame; never-treated comparison,universal baseline,no anticipation. Native/model/paired/balanced denominators differ. All sampling/causal assumptions remain separate.')\r\ndef encode(v):\r\n if isinstance(v,Q):return str(v)\r\n if isinstance(v,dict):return{str(k):encode(x)for k,x in v.items()}\r\n if isinstance(v,(list,tuple)):return[encode(x)for x in v]\r\n return v\r\ndef v9(v):\r\n if v is None:return'undefined'\r\n if isinstance(v,str):return v\r\n if isinstance(v,bool):return'1'if v else'0'\r\n return format(float(v),'.9g')\r\ndef run_fixed(spec,out,data):\r\n api=spec['api'];a=spec['input'];summary={};points=[]\r\n def emit(series,x,y):points.append(dict(series=series,x=x,y=y,numericY=safe_float(y)))\r\n if api=='twobytwo':\r\n  result=paired(a['treated'],a['control']);summary=dict(defined=result['defined'],estimate=result['estimate'],treatedPairs=result['treated']['eligiblePairs'],controlPairs=result['control']['eligiblePairs'],unbiasedVariance=result['unbiasedVariance'],HC0=result['HC0'])\r\n  for i,r in enumerate(result['rows']):emit(r['role']+':'+r['id'],i+1,r['change'])\r\n elif api=='att':\r\n  result=att_projection(literal_panel(a['rows']),a.get('control','never'));summary=dict(sourceRows=result['sourceRows'],entities=result['sourceEntities'],cells=len(result['cells']),supportedCells=sum(r['defined']for r in result['cells']),postCells=sum(r['phase']=='post'for r in result['cells']))\r\n  for i,r in enumerate(result['cells']):emit('g'+str(r['g'])+':t'+str(r['t']),i+1,r['estimate'])\r\n elif api=='aggregate':\r\n  result=linear_aggregate(a);summary=dict(defined=result['defined'],estimate=result['estimate'],variance=result['variance'],covarianceRank=result['covarianceRank'],sumWeights=sum((r['coefficient']for r in result['weights']),Q(0)))\r\n  for i,r in enumerate(result['weights']):emit('g'+str(r['cohort'])+':t'+str(r['time']),i+1,r['contribution'])\r\n elif api=='twfe':\r\n  rows=literal_panel(a['rows']);G=panel(rows);result=twfe(G,sorted({r['time']for r in rows}));summary=dict(defined=result['beta']is not None,beta=result['beta'],numerator=result['num'],denominator=result['den'],balancedEntities=result['balancedEntities'],negativeTreatedCells=sum(v['coefficient']is not None and v['coefficient']<0 for v in result['weights'].values()))\r\n  for i,((g,t),r)in enumerate(sorted(result['weights'].items())):emit('g'+str(g)+':t'+str(t),i+1,r['coefficient'])\r\n elif api=='sensitivity':\r\n  result=sensitivity_fixed(a);summary={k:result[k]for k in['defined','estimate','scale','M','horizon','biasBudget','lower','upper']}\r\n  for i,k in enumerate(['lower','estimate','upper']):emit(k,i+1,result[k]if result['defined']else None)\r\n else:\r\n  result=realdata_fixed(a['kind'],data);post=[r for r in result['att']['cells']if r['phase']=='post'];s=next(r for r in result['aggregations']if r['type']=='simple');g=next(r for r in result['aggregations']if r['type']=='group'and r['key']=='overall');summary=dict(nativeRows=result['nativeRows'],modelRows=result['modelRows'],entities=result['entities'],postCells=len(post),simple=s['estimate'],group=g['estimate'],TWFE=result['twfe']['beta'],balancedEntities=result['twfe']['balancedEntities'])\r\n  for i,r in enumerate(post):emit('g'+str(r['g'])+':t'+str(r['t']),i+1,r['estimate'])\r\n out.mkdir(parents=True,exist_ok=True)\r\n if any(out.iterdir()):raise ValueError('use-new-empty-output-directory')\r\n shown={k:v9(v)for k,v in summary.items()};write(out/'summary.csv',[dict(name=k,value=v)for k,v in shown.items()]);write(out/'points.csv',points,['series','x','y','numericY']);full=dict(chapter='METR-20',profile=spec['id'],api=api,input=spec['input'],summary=shown,points=encode(points),details=encode(result),arithmetic='Python Fraction exact finite stored values;summary/plot approximate;bounded teaching projection,not causal or sampling certification')\r\n (out/'full.json').write_text(json.dumps(full,ensure_ascii=False,indent=2,allow_nan=False)+'\\n',encoding='utf8')\r\n import matplotlib\r\n matplotlib.use('Agg')\r\n import matplotlib.pyplot as plt\r\n plt.rcParams.update({'svg.fonttype':'none','font.family':'DejaVu Sans','font.size':12,'axes.spines.top':False,'axes.spines.right':False});fig,ax=plt.subplots(figsize=(9,5.6));good=[r for r in points if r['numericY']is not None]\r\n if good:\r\n  ax.scatter([r['x']for r in good],[r['numericY']for r in good],color='#315d7c',s=32);ax.axhline(0,color='#9eabb2',lw=.8);ax.set_xlabel('Declared cell/unit/bound ordinal')\r\n else:ax.text(.5,.5,'Undefined: no supported plotted quantity',ha='center',va='center',transform=ax.transAxes);ax.set_xticks([]);ax.set_yticks([])\r\n ax.set_ylabel('Cell weight'if api=='twfe'else result.get('unit','Stated outcome/bias units'));ax.set_title(spec['title']['en'],wrap=True,pad=14);ax.grid(axis='y',alpha=.2);fig.tight_layout(pad=2);fig.savefig(out/'plot.svg');plt.close(fig);print(json.dumps(shown))\r\n\r\nSPEC={'id': 'paired-four-changes', 'api': 'twobytwo', 'title': {'ko': '같은 네 개체의 변화와 두 분산', 'en': 'Four paired changes and two variances'}, 'input': {'treated': [{'id': 'T1', 'before': '10', 'after': '15'}, {'id': 'T2', 'before': '20', 'after': '29'}], 'control': [{'id': 'C1', 'before': '5', 'after': '7'}, {'id': 'C2', 'before': '8', 'after': '12'}]}, 'expectedReject': False}\r\nif __name__=='__main__':\r\n import sys\r\n run_fixed(SPEC,Path(sys.argv[1]),Path(sys.argv[2])if len(sys.argv)>2 else Path(__file__).resolve().parent.parent/'metr20-sources')\r\n",
      "arithmetic": "Python Fraction exact stored finite values;logs/summary/plots approximate",
      "summary": {
        "defined": "1",
        "estimate": "4",
        "treatedPairs": "2",
        "controlPairs": "2",
        "unbiasedVariance": "5",
        "HC0": "2.5"
      },
      "fullResultEmbedded": false,
      "plotEmbedded": false,
      "full": {
        "summary": {
          "defined": "1",
          "estimate": "4",
          "treatedPairs": "2",
          "controlPairs": "2",
          "unbiasedVariance": "5",
          "HC0": "2.5"
        },
        "notice": "Complete source/finite projection is retained in the linked external JSON; this short projection is not the full result."
      },
      "plot": null,
      "points": [
        {
          "series": "treated:T1",
          "x": 1,
          "y": "5",
          "numericY": 5.0
        },
        {
          "series": "treated:T2",
          "x": 2,
          "y": "9",
          "numericY": 9.0
        },
        {
          "series": "control:C1",
          "x": 3,
          "y": "2",
          "numericY": 2.0
        },
        {
          "series": "control:C2",
          "x": 4,
          "y": "4",
          "numericY": 4.0
        }
      ],
      "summaryFile": "metr20-programs/paired-four-changes-python-summary.csv",
      "summarySHA256": "cbd250b6a8fb4b27ebc6810ce08739863659e65f7a72655d67a0fcb34731f150",
      "pointsFile": "metr20-programs/paired-four-changes-python-points.csv",
      "pointsSHA256": "cfbe75c87377dd1ff299c14c0734ad9985a9c5ea18e8edfa7a1d9009d39fa4c4",
      "fullResultFile": "metr20-programs/paired-four-changes-python.json",
      "fullResultSHA256": "b3705a8ca4a6ed86f9b32b25166a5f2a5079c68724a121c91cb3860362c60b4f",
      "plotFile": "metr20-programs/paired-four-changes-python.svg",
      "plotSHA256": "99cc3d7add4c1a6b071abf6a471e5a896580404d387283343466b9e8149b03c3"
    },
    {
      "api": "twobytwo",
      "variant": "paired-four-changes",
      "profile": "paired-four-changes",
      "language": "R",
      "file": "metr20-programs/paired-four-changes-r.R",
      "codeSHA256": "c5a6ada435e8c66aa6f49ee104ea00d1a384858d6d91c6ed56b1869d9fb9dcc5",
      "returnCode": 0,
      "expectedRejection": false,
      "title": {
        "ko": "같은 네 개체의 변화와 두 분산",
        "en": "Four paired changes and two variances"
      },
      "code": "# METR20 fixed example. Base R only, finite arithmetic approximate.\r\n# No JavaScript engine,model JSON,derived answer table,private module or internet.\r\noptions(stringsAsFactors=FALSE,digits=17)\r\nargv<-commandArgs(trailingOnly=TRUE);if(length(argv)<1L)stop('Supply a new empty output directory')\r\noutdir<-argv[1];script<-sub('^--file=','',commandArgs(FALSE)[grepl('^--file=',commandArgs(FALSE))][1]);here<-dirname(normalizePath(script,mustWork=TRUE));datadir<-if(length(argv)>=2L)argv[2]else file.path(here,'..','metr20-sources')\r\nunits<-c(country='log teen-employment points',person='recorded real earnings',company='FTE employees');clocks<-c(country='calendar year',person='calendar year',company='survey-wave index');steps<-c(country=1,person=3,company=1);files<-c(country='actual2500-county-mpdta-all6-fields.csv',person='actual38408-NSW-all15-fields.csv',company='actual410-NJPA-all46-fields.csv')\r\nnum<-function(s)ifelse(s=='.',NA_real_,as.numeric(s));mean0<-function(v)if(length(v))mean(v)else NA_real_;var0<-function(v)if(length(v)>1L)sum((v-mean(v))^2)/(length(v)-1L)else NA_real_\r\n\r\nSPEC<-list(id=\"paired-four-changes\",api=\"twobytwo\",title=list(ko=\"같은 네 개체의 변화와 두 분산\",en=\"Four paired changes and two variances\"),input=list(treated=list(list(id=\"T1\",before=\"10\",after=\"15\"),list(id=\"T2\",before=\"20\",after=\"29\")),control=list(list(id=\"C1\",before=\"5\",after=\"7\"),list(id=\"C2\",before=\"8\",after=\"12\"))),expectedReject=FALSE)\r\npanel<-function(rows){G<-list();for(r in rows){key<-r$entity;u<-G[[key]];if(is.null(u))u<-list(g=r$g,rows=list());stopifnot(identical(u$g,r$g),is.null(u$rows[[as.character(r$time)]]));u$rows[[as.character(r$time)]]<-r;G[[key]]<-u};G}\r\ncell<-function(G,g,t,step,control){b<-g-step;members<-list();T<-C<-list();for(key in names(G)){u<-G[[key]];target<-!is.na(u$g)&&u$g==g;comp<-is.na(u$g)||(control=='notyet'&&!is.na(u$g)&&u$g>max(t,b));role<-if(target)'treated'else if(comp)'control'else'excluded-comparison';before<-u$rows[[as.character(b)]];after<-u$rows[[as.character(t)]];yb<-if(is.null(before))NA_real_ else before$y;ya<-if(is.null(after))NA_real_ else after$y;eligible<-role!='excluded-comparison'&&!is.na(yb)&&!is.na(ya);reason<-if(role=='excluded-comparison')'target-or-already-exposed-cohort-not-valid-control'else if(is.null(before))'baseline-source-row-absent'else if(is.null(after))'target-time-source-row-absent'else if(is.na(yb))'baseline-outcome-missing'else if(is.na(ya))'target-outcome-missing'else'';m<-list(entity=key,nativeID=u$rows[[1]]$nativeID,g=u$g,role=role,eligible=eligible,baselineSourceId=if(is.null(before))NA_character_ else before$id,targetSourceId=if(is.null(after))NA_character_ else after$id,before=yb,after=ya,change=if(eligible)ya-yb else NA_real_,reason=reason);members[[key]]<-m;if(eligible){if(role=='treated')T[[length(T)+1L]]<-m else C[[length(C)+1L]]<-m}}\r\n change<-function(a)vapply(a,function(r)r$change,0);d<-mean0(change(T));e<-mean0(change(C));estimate<-if(is.na(d)||is.na(e))NA_real_ else d-e;defined<-!is.na(estimate);scores<-setNames(rep(NA_real_,length(members)),names(members));for(key in names(members)){m<-members[[key]];s<-if(!defined)NA_real_ else if(!m$eligible)0 else if(m$role=='treated')(m$change-d)/length(T)else-(m$change-e)/length(C);m$score<-s;scores[key]<-s;members[[key]]<-m};st<-var0(change(T));sc<-var0(change(C));v<-if(is.na(st)||is.na(sc))NA_real_ else st/length(T)+sc/length(C);level<-function(a,k)mean0(vapply(a,function(r)r[[k]],0))\r\n list(g=g,t=t,baseline=b,event=(t-g)/step,phase=if(t==b)'mechanical-reference'else if(t>=g)'post'else'pre-placebo',defined=defined,estimate=estimate,T=T,C=C,members=members,scores=scores,HC0=if(defined)sum(scores^2)else NA_real_,unbiased=v,treatedMeanBefore=level(T,'before'),treatedMeanAfter=level(T,'after'),treatedMeanChange=d,controlMeanBefore=level(C,'before'),controlMeanAfter=level(C,'after'),controlMeanChange=e)\r\n}\r\ncovariance<-function(cells){n<-length(cells);V<-matrix(NA_real_,n,n);for(i in seq_len(n))for(j in seq_len(n))if(cells[[i]]$defined&&cells[[j]]$defined)V[i,j]<-sum(cells[[i]]$scores*cells[[j]]$scores);V}\r\naggregate_cells<-function(post,V,step){out<-list();push<-function(typ,key,ii,w){est<-if(!length(ii)||any(vapply(post[ii],function(z)is.na(z$estimate),TRUE)))NA_real_ else sum(w*vapply(post[ii],function(z)z$estimate,0));vv<-if(is.na(est)||anyNA(V[ii,ii,drop=FALSE]))NA_real_ else as.numeric(t(w)%*%V[ii,ii,drop=FALSE]%*%w);out[[length(out)+1L]]<<-list(type=typ,key=as.character(key),ii=ii,w=w,estimate=est,variance=vv)};positive<-which(vapply(post,function(c)length(c$T)>0L,TRUE));mass<-sum(vapply(post[positive],function(c)length(c$T),0));push('simple','overall',positive,if(mass)vapply(post[positive],function(c)length(c$T)/mass,0)else numeric())\r\n for(typ in c('event','calendar','group')){keys<-vapply(post,function(c)if(typ=='event')c$event else if(typ=='calendar')c$t else c$g,0);gg<-sort(unique(keys));cohortmass<-if(typ=='group')sum(vapply(gg,function(k)length(post[[which(keys==k)[1]]]$T),0))else 0;allii<-integer();allw<-numeric();for(key in gg){ii<-which(keys==key);jj<-ii[vapply(post[ii],function(c)length(c$T)>0L,TRUE)];if(typ=='group'){stopifnot(length(unique(vapply(post[ii],function(c)length(c$T),0)))<=1L);w<-if(length(jj))rep(1/length(jj),length(jj))else numeric();if(cohortmass){allii<-c(allii,jj);allw<-c(allw,w*length(post[[ii[1]]]$T)/cohortmass)}}else{total<-sum(vapply(post[jj],function(c)length(c$T),0));w<-if(total)vapply(post[jj],function(c)length(c$T)/total,0)else numeric()};push(typ,key,jj,w)};if(typ=='group')push(typ,'overall',allii,allw)};out}\r\ntwfe<-function(G,times){ledger<-list();good<-list();for(key in names(G)){u<-G[[key]];absent<-times[!as.character(times)%in%names(u$rows)];missing<-times[vapply(times,function(t){r<-u$rows[[as.character(t)]];!is.null(r)&&is.na(r$y)},TRUE)];eligible<-length(times)>0L&&!length(absent)&&!length(missing);ledger[[length(ledger)+1L]]<-list(entity=key,g=u$g,nativeID=u$rows[[1]]$nativeID,eligible=eligible,absentTimes=paste(absent,collapse=','),missingOutcomeTimes=paste(missing,collapse=','),originalRows=length(u$rows));if(eligible)good[[key]]<-u};rows<-list();for(key in names(good))for(t in times){r<-good[[key]]$rows[[as.character(t)]];r$D<-as.integer(!is.na(r$g)&&t>=r$g);rows[[length(rows)+1L]]<-r};em<-lapply(good,function(u)list(D=mean(vapply(times,function(t)as.integer(!is.na(u$g)&&t>=u$g),0)),Y=mean(vapply(u$rows[as.character(times)],function(r)r$y,0))));tm<-lapply(times,function(t)list(D=mean(vapply(good,function(u)as.integer(!is.na(u$g)&&t>=u$g),0)),Y=mean(vapply(good,function(u)u$rows[[as.character(t)]]$y,0))));names(tm)<-as.character(times);gd<-mean0(vapply(rows,function(r)r$D,0));gy<-mean0(vapply(rows,function(r)r$y,0));num<-den<-0\r\n for(i in seq_along(rows)){r<-rows[[i]];r$residualD<-r$D-em[[r$entity]]$D-tm[[as.character(r$time)]]$D+gd;r$residualY<-r$y-em[[r$entity]]$Y-tm[[as.character(r$time)]]$Y+gy;num<-num+r$residualD*r$residualY;den<-den+r$residualD^2;rows[[i]]<-r};beta<-if(den!=0)num/den else NA_real_;weights<-list();for(i in seq_along(rows)){r<-rows[[i]];r$projectionCoefficient<-if(den!=0)r$residualD/den else NA_real_;r$regressionResidual<-if(!is.na(beta))r$residualY-beta*r$residualD else NA_real_;rows[[i]]<-r;if(r$D==1L){k<-paste(r$g,r$time,sep=':');z<-weights[[k]];if(is.null(z))z<-list(g=r$g,t=r$time,rows=0,coefficient=if(den!=0)0 else NA_real_);z$rows<-z$rows+1L;if(den!=0)z$coefficient<-z$coefficient+r$projectionCoefficient;weights[[k]]<-z}};list(ledger=ledger,rows=rows,num=num,den=den,beta=beta,weights=weights,balancedEntities=length(good))}\r\nadjacent_pre<-function(G,g,t,step,control){b<-t-step;T<-C<-numeric();for(u in G){target<-!is.na(u$g)&&u$g==g;comp<-is.na(u$g)||(control=='notyet'&&!is.na(u$g)&&u$g>max(t,b));if(!target&&!comp)next;before<-u$rows[[as.character(b)]];after<-u$rows[[as.character(t)]];if(!is.null(before)&&!is.null(after)&&!is.na(before$y)&&!is.na(after$y)){if(target)T<-c(T,after$y-before$y)else C<-c(C,after$y-before$y)}};if(!length(T)||!length(C))NA_real_ else mean(T)-mean(C)}\r\n\r\n# Newly authored bounded teaching projections; base R finite approximation.\r\n# Source helper functions are inlined in each public file, never imported.\r\nqnum<-function(v){if(is.null(v)||is.na(v))return(NA_real_);s<-strsplit(as.character(v),'/',fixed=TRUE)[[1]];if(length(s)==1L)as.numeric(s)else as.numeric(s[1])/as.numeric(s[2])}\r\npaired<-function(T,C){\r\n stats<-function(rr){use<-Filter(function(r)!is.na(qnum(r$before))&&!is.na(qnum(r$after)),rr);a<-vapply(use,function(r)qnum(r$before),0);b<-vapply(use,function(r)qnum(r$after),0);list(sourcePairs=length(rr),eligiblePairs=length(use),excludedPairs=length(rr)-length(use),meanBefore=mean0(a),meanAfter=mean0(b),meanChange=mean0(b-a),sampleChangeVariance=var0(b-a))}\r\n st<-stats(T);sc<-stats(C);defined<-st$eligiblePairs>0L&&sc$eligiblePairs>0L;estimate<-if(defined)st$meanChange-sc$meanChange else NA_real_;rr<-list()\r\n for(role in c('treated','control')){input<-if(role=='treated')T else C;s<-if(role=='treated')st else sc;for(r in input){before<-qnum(r$before);after<-qnum(r$after);eligible<-!is.na(before)&&!is.na(after);change<-if(eligible)after-before else NA_real_;score<-if(!defined)NA_real_ else if(!eligible)0 else (change-s$meanChange)/(if(role=='treated')s$eligiblePairs else -s$eligiblePairs);rr[[length(rr)+1L]]<-list(id=r$id,role=role,before=before,after=after,eligible=eligible,change=change,score=score)}}\r\n list(defined=defined,estimate=estimate,treated=st,control=sc,unbiasedVariance=if(defined&&st$eligiblePairs>=2L&&sc$eligiblePairs>=2L)st$sampleChangeVariance/st$eligiblePairs+sc$sampleChangeVariance/sc$eligiblePairs else NA_real_,HC0=if(defined)sum(vapply(rr,function(r)r$score^2,0))else NA_real_,rows=rr)\r\n}\r\nliteral_panel<-function(rr)lapply(seq_along(rr),function(i){r<-rr[[i]];r$y<-qnum(r$y);r$nativeID<-r$entity;r$sourceRow<-i;r})\r\natt_projection<-function(rows,control='never',step=1){G<-panel(rows);times<-sort(unique(vapply(rows,function(r)r$time,0)));cohorts<-sort(unique(na.omit(vapply(rows,function(r)r$g,0))));cells<-list();for(g in cohorts)for(t in times)cells[[length(cells)+1L]]<-cell(G,g,t,step,control);list(sourceRows=length(rows),sourceEntities=length(G),step=step,control=control,cells=cells,covariance=covariance(cells))}\r\nlinear_aggregate<-function(a){\r\n rr<-lapply(a$cells,function(r){r$estimate<-qnum(r$estimate);r$weight<-qnum(r$weight);r});V<-if(is.null(a$covariance))NULL else do.call(rbind,lapply(a$covariance,function(r)vapply(r,qnum,0)));rank<-NA_real_\r\n if(!is.null(V)){stopifnot(nrow(V)==length(rr),ncol(V)==length(rr),all(V==t(V)));ev<-eigen(V,symmetric=TRUE,only.values=TRUE)$values;if(any(ev< -1e-12))stop('covariance-must-be-positive-semidefinite');rank<-sum(ev>1e-12)}\r\n selected<-which(vapply(rr,function(r)r$time>=r$cohort&&r$weight>0,TRUE));w<-numeric(length(rr));type<-if(is.null(a$type))'simple'else a$type\r\n if(type=='simple'){mass<-sum(vapply(rr[selected],function(r)r$weight,0));if(mass>0)for(i in selected)w[i]<-rr[[i]]$weight/mass}else{g<-vapply(rr,function(r)r$cohort,0);gg<-sort(unique(g[selected]));mass<-sum(vapply(gg,function(gi)rr[[intersect(which(g==gi),selected)[1]]]$weight,0));for(gi in gg){ii<-intersect(which(g==gi),selected);stopifnot(length(unique(vapply(rr[ii],function(r)r$weight,0)))==1L);w[ii]<-rr[[ii[1]]]$weight/mass/length(ii)}}\r\n used<-which(w>0);estimate<-if(!length(used)||any(vapply(rr[used],function(r)is.na(r$estimate),TRUE)))NA_real_ else sum(w[used]*vapply(rr[used],function(r)r$estimate,0));variance<-if(is.na(estimate)||is.null(V))NA_real_ else as.numeric(t(w)%*%V%*%w);weights<-lapply(used,function(i)list(sourceIndex=i-1L,cohort=rr[[i]]$cohort,time=rr[[i]]$time,coefficient=w[i],estimate=rr[[i]]$estimate,contribution=w[i]*rr[[i]]$estimate))\r\n list(type=type,defined=!is.na(estimate),estimate=estimate,variance=variance,covarianceRank=rank,weights=weights,cells=rr,covariance=V)\r\n}\r\nsensitivity_fixed<-function(a){estimate<-qnum(a$estimate);M<-qnum(a$M);h<-if(is.null(a$horizon))1 else a$horizon;stopifnot(M>=0,h>=1);pre<-vapply(a$preDifferences,qnum,0);scale<-if(!is.null(a$scale))qnum(a$scale)else if(length(pre))max(abs(pre))else NA_real_;budget<-M*scale*h;list(defined=!is.na(scale),estimate=estimate,scale=scale,M=M,horizon=h,biasBudget=budget,lower=estimate-budget,upper=estimate+budget,preDifferences=as.list(pre),confidenceLevel=NULL)}\r\nrealdata_fixed<-function(kind){rows<-models[[kind]];G<-panel(rows);times<-sort(unique(vapply(rows,function(r)r$time,0)));step<-unname(steps[kind]);aa<-att_projection(rows,'never',step);post<-Filter(function(r)r$phase=='post',aa$cells);aggs<-aggregate_cells(post,covariance(post),step);tf<-twfe(G,times);list(kind=kind,unit=unname(units[kind]),periodUnit=unname(clocks[kind]),nativeRows=nrow(raw[[kind]]),modelRows=length(rows),entities=length(G),sourceRows=rows,att=aa,aggregations=aggs,twfe=tf,scope='Complete native/model/paired/balanced source frames; never control,universal base,no anticipation;not causal/sampling certification.')}\r\n# JSON encoder deliberately handles matrices and scalar/vector distinctions.\r\nencode<-function(x){\r\n if(is.null(x))return('null')\r\n quote<-function(s){s<-gsub('\\\\','\\\\\\\\',as.character(s),fixed=TRUE);s<-gsub('\"','\\\\\"',s,fixed=TRUE);s<-gsub('\\n','\\\\n',s,fixed=TRUE);s<-gsub('\\r','\\\\r',s,fixed=TRUE);s<-gsub('\\t','\\\\t',s,fixed=TRUE);paste0('\"',s,'\"')}\r\n if(is.matrix(x))return(paste0('[',paste(vapply(seq_len(nrow(x)),function(i)encode(as.list(unname(x[i,]))),''),collapse=','),']'))\r\n if(is.list(x)){if(length(x)&&!is.null(names(x)))return(paste0('{',paste(paste0(vapply(names(x),quote,''),':',vapply(x,encode,'')),collapse=','),'}'));return(paste0('[',paste(vapply(x,encode,''),collapse=','),']'))}\r\n if(length(x)!=1L)return(encode(as.list(unname(x))))\r\n if(is.na(x))return('null');if(is.logical(x))return(if(x)'true'else'false');if(is.numeric(x))return(sprintf('%.17g',unname(x)));quote(x)\r\n}\r\nv9<-function(x){if(is.null(x)||is.na(x))return('undefined');if(is.logical(x))return(if(x)'1'else'0');if(is.numeric(x))return(sprintf('%.9g',unname(x)));as.character(x)}\r\nrun_fixed<-function(spec,out){api<-spec$api;a<-spec$input;summary<-list();points<-list();emit<-function(series,x,y){points[[length(points)+1L]]<<-list(series=series,x=x,y=y,numericY=y)}\r\n if(api=='twobytwo'){result<-paired(a$treated,a$control);summary<-list(defined=result$defined,estimate=result$estimate,treatedPairs=result$treated$eligiblePairs,controlPairs=result$control$eligiblePairs,unbiasedVariance=result$unbiasedVariance,HC0=result$HC0);for(i in seq_along(result$rows)){r<-result$rows[[i]];emit(paste(r$role,r$id,sep=':'),i,r$change)}}\r\n else if(api=='att'){result<-att_projection(literal_panel(a$rows),a$control);summary<-list(sourceRows=result$sourceRows,entities=result$sourceEntities,cells=length(result$cells),supportedCells=sum(vapply(result$cells,function(r)r$defined,TRUE)),postCells=sum(vapply(result$cells,function(r)r$phase=='post',TRUE)));for(i in seq_along(result$cells)){r<-result$cells[[i]];emit(paste0('g',r$g,':t',r$t),i,r$estimate)}}\r\n else if(api=='aggregate'){result<-linear_aggregate(a);summary<-list(defined=result$defined,estimate=result$estimate,variance=result$variance,covarianceRank=result$covarianceRank,sumWeights=sum(vapply(result$weights,function(r)r$coefficient,0)));for(i in seq_along(result$weights)){r<-result$weights[[i]];emit(paste0('g',r$cohort,':t',r$time),i,r$contribution)}}\r\n else if(api=='twfe'){rows<-literal_panel(a$rows);G<-panel(rows);result<-twfe(G,sort(unique(vapply(rows,function(r)r$time,0))));summary<-list(defined=!is.na(result$beta),beta=result$beta,numerator=result$num,denominator=result$den,balancedEntities=result$balancedEntities,negativeTreatedCells=sum(vapply(result$weights,function(r)!is.na(r$coefficient)&&r$coefficient<0,TRUE)));if(length(result$weights)){ord<-order(vapply(result$weights,function(r)r$g,0),vapply(result$weights,function(r)r$t,0));for(i in seq_along(ord)){r<-result$weights[[ord[i]]];emit(paste0('g',r$g,':t',r$t),i,r$coefficient)}}}\r\n else if(api=='sensitivity'){result<-sensitivity_fixed(a);summary<-result[c('defined','estimate','scale','M','horizon','biasBudget','lower','upper')];for(i in seq_along(c('lower','estimate','upper'))){k<-c('lower','estimate','upper')[i];emit(k,i,if(result$defined)result[[k]]else NA_real_)}}\r\n else{result<-realdata_fixed(a$kind);post<-Filter(function(r)r$phase=='post',result$att$cells);simple<-Filter(function(r)r$type=='simple',result$aggregations)[[1]];group<-Filter(function(r)r$type=='group'&&r$key=='overall',result$aggregations)[[1]];summary<-list(nativeRows=result$nativeRows,modelRows=result$modelRows,entities=result$entities,postCells=length(post),simple=simple$estimate,group=group$estimate,TWFE=result$twfe$beta,balancedEntities=result$twfe$balancedEntities);for(i in seq_along(post)){r<-post[[i]];emit(paste0('g',r$g,':t',r$t),i,r$estimate)}}\r\n dir.create(out,recursive=TRUE,showWarnings=FALSE);if(length(list.files(out,all.files=TRUE,no..=TRUE)))stop('use-new-empty-output-directory');shown<-lapply(summary,v9);write.csv(data.frame(name=names(shown),value=unlist(shown,use.names=FALSE)),file.path(out,'summary.csv'),row.names=FALSE,na='');pointframe<-if(length(points))do.call(rbind,lapply(points,function(p)data.frame(series=p$series,x=p$x,y=p$y,numericY=p$numericY,stringsAsFactors=FALSE)))else data.frame(series=character(),x=numeric(),y=numeric(),numericY=numeric());write.csv(pointframe,file.path(out,'points.csv'),row.names=FALSE,na='');full<-list(chapter='METR-20',profile=spec$id,api=api,input=spec$input,summary=shown,points=points,details=result,arithmetic='Base R approximate finite values;bounded teaching projection,not exact fractions or causal/sampling certification.');writeLines(encode(full),file.path(out,'full.json'),useBytes=TRUE)\r\n svg(file.path(out,'plot.svg'),width=9,height=5.6,pointsize=12);par(mar=c(4.5,5.5,4,1));good<-pointframe[!is.na(pointframe$numericY),,drop=FALSE]\r\n if(nrow(good)){plot(good$x,good$numericY,pch=19,col='#315d7c',xlab='Declared cell/unit/bound ordinal',ylab=if(api=='twfe')'Cell weight'else if(!is.null(result$unit))result$unit else 'Stated outcome/bias units',main=spec$title$en);abline(h=0,col='#9eabb2');grid(nx=NA,ny=NULL,col='#e2e5e7');points(good$x,good$numericY,pch=19,col='#315d7c')}else{plot.new();text(.5,.5,'Undefined: no supported plotted quantity');title(main=spec$title$en)};dev.off();cat(encode(shown),'\\n')\r\n}\r\n\r\nrun_fixed(SPEC,outdir)\r\n",
      "arithmetic": "Base R approximate finite arithmetic;not an exact rational result",
      "summary": {
        "defined": "1",
        "estimate": "4",
        "treatedPairs": "2",
        "controlPairs": "2",
        "unbiasedVariance": "5",
        "HC0": "2.5"
      },
      "fullResultEmbedded": false,
      "plotEmbedded": false,
      "full": {
        "summary": {
          "defined": "1",
          "estimate": "4",
          "treatedPairs": "2",
          "controlPairs": "2",
          "unbiasedVariance": "5",
          "HC0": "2.5"
        },
        "notice": "Complete source/finite projection is retained in the linked external JSON; this short projection is not the full result."
      },
      "plot": null,
      "points": [
        {
          "series": "treated:T1",
          "x": 1,
          "y": 5,
          "numericY": 5
        },
        {
          "series": "treated:T2",
          "x": 2,
          "y": 9,
          "numericY": 9
        },
        {
          "series": "control:C1",
          "x": 3,
          "y": 2,
          "numericY": 2
        },
        {
          "series": "control:C2",
          "x": 4,
          "y": 4,
          "numericY": 4
        }
      ],
      "summaryFile": "metr20-programs/paired-four-changes-r-summary.csv",
      "summarySHA256": "aac37c8697719c33f5fc66b9b591b680f609c54266bc53adfbbf8d7de10d2bb6",
      "pointsFile": "metr20-programs/paired-four-changes-r-points.csv",
      "pointsSHA256": "e47f3e064d583728f7e1f0728d114bfaf642144b6f02172851d6302dd47a5a18",
      "fullResultFile": "metr20-programs/paired-four-changes-r.json",
      "fullResultSHA256": "ae66a9fb1e6d89f5a9580a591a1efcf7055e3e2efa1b256def9977616e2e899a",
      "plotFile": "metr20-programs/paired-four-changes-r.svg",
      "plotSHA256": "99f2746e07613d4883a5c1a9839e72372d30d864514b27fa9b4c57f1c8582c0a"
    },
    {
      "api": "twobytwo",
      "variant": "paired-single-and-missing",
      "profile": "paired-single-and-missing",
      "language": "Python",
      "file": "metr20-programs/paired-single-and-missing-python.py",
      "codeSHA256": "403125e78248cd6f12f12ea24129c488264cc8eebf328c28807561b705090463",
      "returnCode": 0,
      "expectedRejection": false,
      "title": {
        "ko": "한 쌍의 0 점수와 미정의 표본 분산",
        "en": "One pair: zero scores, undefined sample variance"
      },
      "code": "\"\"\"METR20 actual sources. Python standard library, exact stored-value rationals.\r\nRead ONLY the three native-observation CSVs; no JS engine,model JSON,derived\r\nanswers,private modules or internet needed. Outcome measurement/identification\r\nand valid sampling inference remain separate from exact finite arithmetic.\r\nRun: python metr20-reproduce.py --data-dir PATH --out NEW_EMPTY_DIRECTORY\r\n\"\"\"\r\nfrom pathlib import Path\r\nfrom fractions import Fraction as Q\r\nfrom collections import defaultdict,Counter\r\nimport csv,json,math,argparse,hashlib\r\n\r\nUNIT={'country':'log teen-employment points','person':'recorded real earnings','company':'FTE employees'}\r\nCLOCK={'country':'calendar year','person':'calendar year','company':'survey-wave index'}\r\nSTEP={'country':1,'person':3,'company':1}\r\nFILES={'country':'actual2500-county-mpdta-all6-fields.csv','person':'actual38408-NSW-all15-fields.csv','company':'actual410-NJPA-all46-fields.csv'}\r\ndef avg(v):return sum(v,Q(0))/len(v)if v else None\r\ndef samplevar(v):return sum(((x-avg(v))**2 for x in v),Q(0))/(len(v)-1)if len(v)>1 else None\r\ndef binary(s):return None if s=='.'else Q.from_float(float(s))\r\ndef token(v):\r\n if v is None:return ''\r\n if isinstance(v,bool):return 'true'if v else'false'\r\n return str(v)\r\ndef safe_float(v):\r\n if v is None:return None\r\n try:r=float(v)\r\n except OverflowError:return None\r\n return r if math.isfinite(r)else None\r\ndef read(p):\r\n with p.open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))\r\ndef write(p,rows,head=None):\r\n if head is None:\r\n  assert rows;head=list(rows[0])\r\n with p.open('w',encoding='utf8',newline='')as f:\r\n  w=csv.DictWriter(f,fieldnames=head);w.writeheader();w.writerows({k:token(r.get(k))for k in head}for r in rows)\r\ndef source(data):\r\n raw={k:read(data/n)for k,n in FILES.items()};assert[len(raw[k])for k in FILES]==[2500,38408,410]\r\n models={k:[]for k in FILES}\r\n for r in raw['country']:\r\n  g0=int(r['first.treat']);g=None if g0==0 else g0;assert int(r['treat'])==int(g is not None)\r\n  models['country'].append(dict(id='mpdta:'+r['sourceRow'],entity='county:'+str(int(r['countyreal'])),time=int(r['year']),y=binary(r['lemp']),g=g,sourceRow=int(r['sourceRow']),nativeID=r['countyreal']))\r\n for r in raw['person']:\r\n  selected=int(r['experimental'])==1;assert selected==(int(r['sample'])==1);assert(r['treated']!='.')==selected\r\n  if selected:\r\n   d=int(r['treated']);assert d in[0,1]\r\n   models['person'].append(dict(id='nsw:'+r['sourceRow'],entity='nsw-id:'+str(int(r['id'])),time=int(r['year']),y=binary(r['re']),g=1978 if d else None,sourceRow=int(r['sourceRow']),nativeID=str(int(r['id']))))\r\n for r in raw['company']:\r\n  state=int(r['STATE']);assert state in[0,1]\r\n  for t,suffix in[(0,''),(1,'2')]:\r\n   a=[r[n+suffix]for n in['EMPFT','NMGRS','EMPPT']];y=None if'.'in a else Q(a[0])+Q(a[1])+Q(a[2])/2\r\n   models['company'].append(dict(id='njpa:'+r['sourceRow']+':wave'+str(t),entity='njpa-row:'+r['sourceRow'],time=t,y=y,g=1 if state else None,sourceRow=int(r['sourceRow']),nativeID=r['SHEET']))\r\n assert[len(models[k])for k in FILES]==[2500,1444,820]\r\n return models,raw\r\ndef panel(rows):\r\n groups={}\r\n for r in rows:\r\n  u=groups.setdefault(r['entity'],{'g':r['g'],'rows':{}});assert u['g']==r['g']and r['time']not in u['rows'];u['rows'][r['time']]=r\r\n return groups\r\ndef cell(groups,g,t,step,control):\r\n b=g-step;members=[];T=[];C=[]\r\n for key,u in groups.items():\r\n  role='treated'if u['g']==g else'control'if u['g']is None or(control=='notyet'and u['g']>max(t,b))else'excluded-comparison'\r\n  before=u['rows'].get(b);after=u['rows'].get(t);yb=None if before is None else before['y'];ya=None if after is None else after['y'];eligible=role!='excluded-comparison'and yb is not None and ya is not None\r\n  reason='target-or-already-exposed-cohort-not-valid-control'if role=='excluded-comparison'else'baseline-source-row-absent'if before is None else'target-time-source-row-absent'if after is None else'baseline-outcome-missing'if yb is None else'target-outcome-missing'if ya is None else''\r\n  m={'entity':key,'nativeID':next(iter(u['rows'].values()))['nativeID'],'g':u['g'],'role':role,'eligible':eligible,'baselineSourceId':None if before is None else before['id'],'targetSourceId':None if after is None else after['id'],'before':yb,'after':ya,'change':ya-yb if eligible else None,'reason':reason};members.append(m)\r\n  if eligible:(T if role=='treated'else C).append(m)\r\n d=avg([r['change']for r in T]);e=avg([r['change']for r in C]);estimate=None if d is None or e is None else d-e;defined=estimate is not None;scores={}\r\n for m in members:\r\n  s=None if not defined else Q(0)\r\n  if defined and m['eligible']:s=(m['change']-(d if m['role']=='treated'else e))/(len(T)if m['role']=='treated'else-len(C))\r\n  m['score']=s;scores[m['entity']]=s\r\n st=samplevar([r['change']for r in T]);sc=samplevar([r['change']for r in C]);v=None if st is None or sc is None else st/len(T)+sc/len(C)\r\n return {'g':g,'t':t,'baseline':b,'event':(t-g)//step,'phase':'mechanical-reference'if t==b else'post'if t>=g else'pre-placebo','defined':defined,'estimate':estimate,'T':T,'C':C,'members':members,'scores':scores,'HC0':None if not defined else sum((s*s for s in scores.values()),Q(0)),'unbiased':v,'treatedMeanBefore':avg([r['before']for r in T]),'treatedMeanAfter':avg([r['after']for r in T]),'treatedMeanChange':d,'controlMeanBefore':avg([r['before']for r in C]),'controlMeanAfter':avg([r['after']for r in C]),'controlMeanChange':e}\r\ndef covariance(cells):\r\n return[[None if not a['defined']or not b['defined']else sum((v*b['scores'][i]for i,v in a['scores'].items()),Q(0))for b in cells]for a in cells]\r\ndef aggregate(post,V,step):\r\n out=[]\r\n def push(typ,key,coeff):\r\n  estimate=None if not coeff or any(post[i]['estimate']is None for i in coeff)else sum((w*post[i]['estimate']for i,w in coeff.items()),Q(0));variance=None if estimate is None or any(V[i][j]is None for i in coeff for j in coeff)else sum((a*b*V[i][j]for i,a in coeff.items()for j,b in coeff.items()),Q(0));out.append({'type':typ,'key':key,'coeff':coeff,'estimate':estimate,'variance':variance})\r\n positive=[i for i,c in enumerate(post)if len(c['T'])>0];mass=sum(len(post[i]['T'])for i in positive)\r\n push('simple','overall',{i:Q(len(post[i]['T']),mass)for i in positive}if mass else{})\r\n for typ in['event','calendar','group']:\r\n  groups=defaultdict(list)\r\n  for i,c in enumerate(post):groups[c['event']if typ=='event'else c['t']if typ=='calendar'else c['g']].append(i)\r\n  overall={};cohortMass=sum(len(post[ii[0]]['T'])for ii in groups.values())if typ=='group'else 0\r\n  for key,ii in sorted(groups.items()):\r\n   jj=[i for i in ii if len(post[i]['T'])>0]\r\n   if typ=='group':\r\n    assert len({len(post[i]['T'])for i in ii})<=1\r\n    coeff={i:Q(1,len(jj))for i in jj}if jj else{}\r\n    if cohortMass:\r\n     for i,w in coeff.items():overall[i]=w*Q(len(post[ii[0]]['T']),cohortMass)\r\n   else:\r\n    total=sum(len(post[i]['T'])for i in jj);coeff={i:Q(len(post[i]['T']),total)for i in jj}if total else{}\r\n   push(typ,str(key),coeff)\r\n  if typ=='group':push(typ,'overall',overall)\r\n return out\r\ndef twfe(groups,times):\r\n ledger=[];good={}\r\n for key,u in groups.items():\r\n  absent=[t for t in times if t not in u['rows']];missing=[t for t in times if t in u['rows']and u['rows'][t]['y']is None];eligible=bool(times)and not absent and not missing\r\n  ledger.append({'entity':key,'g':u['g'],'nativeID':next(iter(u['rows'].values()))['nativeID'],'eligible':eligible,'absentTimes':','.join(map(str,absent)),'missingOutcomeTimes':','.join(map(str,missing)),'originalRows':len(u['rows'])})\r\n  if eligible:good[key]=u\r\n rows=[dict(**u['rows'][t],D=Q(u['g']is not None and t>=u['g']))for key,u in good.items()for t in times]\r\n em={k:{'D':avg([Q(u['g']is not None and t>=u['g'])for t in times]),'Y':avg([u['rows'][t]['y']for t in times])}for k,u in good.items()};tm={t:{'D':avg([Q(u['g']is not None and t>=u['g'])for u in good.values()]),'Y':avg([u['rows'][t]['y']for u in good.values()])}for t in times};gd=avg([r['D']for r in rows]);gy=avg([r['y']for r in rows]);num=den=Q(0)\r\n for r in rows:\r\n  r['residualD']=r['D']-em[r['entity']]['D']-tm[r['time']]['D']+gd;r['residualY']=r['y']-em[r['entity']]['Y']-tm[r['time']]['Y']+gy;num+=r['residualD']*r['residualY'];den+=r['residualD']**2\r\n beta=num/den if den else None;weights={}\r\n for r in rows:\r\n  r['projectionCoefficient']=r['residualD']/den if den else None;r['regressionResidual']=r['residualY']-beta*r['residualD']if beta is not None else None\r\n  if r['D']:\r\n   k=(r['g'],r['time']);z=weights.setdefault(k,{'rows':0,'coefficient':Q(0)if den else None});z['rows']+=1\r\n   if den:z['coefficient']+=r['projectionCoefficient']\r\n return {'ledger':ledger,'rows':rows,'num':num,'den':den,'beta':beta,'weights':weights,'balancedEntities':len(good)}\r\ndef adjacent_pre(groups,g,t,step,control):\r\n b=t-step;T=[];C=[]\r\n for u in groups.values():\r\n  if u['g']==g:target=T\r\n  elif u['g']is None or(control=='notyet'and u['g']>max(t,b)):target=C\r\n  else:continue\r\n  before=u['rows'].get(b);after=u['rows'].get(t)\r\n  if before is not None and after is not None and before['y']is not None and after['y']is not None:target.append(after['y']-before['y'])\r\n return None if not T or not C else avg(T)-avg(C)\r\n\r\n\"\"\"New bounded teaching projections. The program is self-contained after build.\r\nExact Fraction finite algebra; figures and9-digit summary are approximations.\r\nIt is not a general parser/API replacement or a causal/inference certificate.\r\n\"\"\"\r\ndef paired(treated,control):\r\n def stats(rr):\r\n  use=[r for r in rr if r['before']is not None and r['after']is not None];delta=[Q(r['after'])-Q(r['before'])for r in use]\r\n  return dict(sourcePairs=len(rr),eligiblePairs=len(use),excludedPairs=len(rr)-len(use),meanBefore=avg([Q(r['before'])for r in use]),meanAfter=avg([Q(r['after'])for r in use]),meanChange=avg(delta),sampleChangeVariance=samplevar(delta))\r\n T,C=stats(treated),stats(control);defined=T['eligiblePairs']>0 and C['eligiblePairs']>0;estimate=T['meanChange']-C['meanChange']if defined else None;records=[]\r\n for group,rr,s in [('treated',treated,T),('control',control,C)]:\r\n  for r in rr:\r\n   before=None if r['before']is None else Q(r['before']);after=None if r['after']is None else Q(r['after']);eligible=before is not None and after is not None;delta=after-before if eligible else None;score=None if not defined else Q(0)if not eligible else(delta-s['meanChange'])/(s['eligiblePairs']if group=='treated'else-s['eligiblePairs']);records.append(dict(id=r['id'],role=group,before=before,after=after,eligible=eligible,change=delta,score=score))\r\n unbiased=None if not defined or T['eligiblePairs']<2 or C['eligiblePairs']<2 else T['sampleChangeVariance']/T['eligiblePairs']+C['sampleChangeVariance']/C['eligiblePairs'];hc0=None if not defined else sum((r['score']**2 for r in records),Q(0))\r\n return dict(defined=defined,estimate=estimate,treated=T,control=C,unbiasedVariance=unbiased,HC0=hc0,rows=records)\r\ndef literal_panel(raw):\r\n return[dict(r,y=None if r['y']is None else Q(r['y']),nativeID=r['entity'],sourceRow=i+1)for i,r in enumerate(raw)]\r\ndef att_projection(rows,control='never',step=1):\r\n G=panel(rows);times=sorted({r['time']for r in rows});cohorts=sorted({r['g']for r in rows if r['g']is not None});cells=[cell(G,g,t,step,control)for g in cohorts for t in times]\r\n return dict(sourceRows=len(rows),sourceEntities=len(G),step=step,control=control,cells=cells,covariance=covariance(cells))\r\ndef psd(V):\r\n A=[r[:]for r in V];rank=0\r\n while A:\r\n  if any(A[i][i]<0 for i in range(len(A))):raise ValueError('covariance-must-be-positive-semidefinite')\r\n  p=next((i for i in range(len(A))if A[i][i]>0),None)\r\n  if p is None:\r\n   if any(v for r in A for v in r):raise ValueError('covariance-must-be-positive-semidefinite')\r\n   return rank\r\n  A[0],A[p]=A[p],A[0]\r\n  for r in A:r[0],r[p]=r[p],r[0]\r\n  d=A[0][0];A=[[A[i][j]-A[i][0]*A[0][j]/d for j in range(1,len(A))]for i in range(1,len(A))];rank+=1\r\n return rank\r\ndef linear_aggregate(a):\r\n rr=[dict(r,estimate=None if r['estimate']is None else Q(r['estimate']),weight=Q(r['weight']))for r in a['cells']];V=[[Q(v)for v in r]for r in a['covariance']]if 'covariance'in a else None\r\n if V is not None:\r\n  assert len(V)==len(rr)and all(len(z)==len(rr)for z in V);assert all(V[i][j]==V[j][i]for i in range(len(rr))for j in range(len(rr)));rank=psd(V)\r\n else:rank=None\r\n selected=[i for i,r in enumerate(rr)if r['time']>=r['cohort']and r['weight']>0];weights={}\r\n if a.get('type','simple')=='simple':\r\n  mass=sum((rr[i]['weight']for i in selected),Q(0));weights={i:rr[i]['weight']/mass for i in selected}if mass else{}\r\n else:\r\n  gg=defaultdict(list)\r\n  for i in selected:gg[rr[i]['cohort']].append(i)\r\n  assert all(len({rr[i]['weight']for i in ii})==1 for ii in gg.values());mass=sum((rr[ii[0]]['weight']for ii in gg.values()),Q(0));weights={i:rr[ii[0]]['weight']/mass/len(ii)for ii in gg.values()for i in ii}if mass else{}\r\n estimate=None if not weights or any(rr[i]['estimate']is None for i in weights)else sum((w*rr[i]['estimate']for i,w in weights.items()),Q(0));variance=None if estimate is None or V is None else sum((x*y*V[i][j]for i,x in weights.items()for j,y in weights.items()),Q(0))\r\n return dict(type=a.get('type','simple'),defined=estimate is not None,estimate=estimate,variance=variance,covarianceRank=rank,weights=[dict(sourceIndex=i,cohort=rr[i]['cohort'],time=rr[i]['time'],coefficient=w,estimate=rr[i]['estimate'],contribution=None if rr[i]['estimate']is None else w*rr[i]['estimate'])for i,w in weights.items()],cells=rr,covariance=V)\r\ndef sensitivity_fixed(a):\r\n estimate=Q(a['estimate']);M=Q(a['M']);h=a.get('horizon',1);assert M>=0 and h>=1\r\n pre=[Q(v)for v in a.get('preDifferences',[])];scale=Q(a['scale'])if 'scale'in a else max(map(abs,pre))if pre else None;budget=None if scale is None else M*scale*h\r\n return dict(defined=scale is not None,estimate=estimate,scale=scale,M=M,horizon=h,biasBudget=budget,lower=None if budget is None else estimate-budget,upper=None if budget is None else estimate+budget,preDifferences=pre,confidenceLevel=None)\r\ndef realdata_fixed(kind,data):\r\n models,raw=source(data);rows=models[kind];G=panel(rows);times=sorted({r['time']for r in rows});step=STEP[kind];aa=att_projection(rows,'never',step);post=[r for r in aa['cells']if r['phase']=='post'];aggs=aggregate(post,covariance(post),step);tf=twfe(G,times)\r\n return dict(kind=kind,unit=UNIT[kind],periodUnit=CLOCK[kind],nativeRows=len(raw[kind]),modelRows=len(rows),entities=len(G),sourceRows=rows,att=aa,aggregations=aggs,twfe=tf,scope='Complete source frame; never-treated comparison,universal baseline,no anticipation. Native/model/paired/balanced denominators differ. All sampling/causal assumptions remain separate.')\r\ndef encode(v):\r\n if isinstance(v,Q):return str(v)\r\n if isinstance(v,dict):return{str(k):encode(x)for k,x in v.items()}\r\n if isinstance(v,(list,tuple)):return[encode(x)for x in v]\r\n return v\r\ndef v9(v):\r\n if v is None:return'undefined'\r\n if isinstance(v,str):return v\r\n if isinstance(v,bool):return'1'if v else'0'\r\n return format(float(v),'.9g')\r\ndef run_fixed(spec,out,data):\r\n api=spec['api'];a=spec['input'];summary={};points=[]\r\n def emit(series,x,y):points.append(dict(series=series,x=x,y=y,numericY=safe_float(y)))\r\n if api=='twobytwo':\r\n  result=paired(a['treated'],a['control']);summary=dict(defined=result['defined'],estimate=result['estimate'],treatedPairs=result['treated']['eligiblePairs'],controlPairs=result['control']['eligiblePairs'],unbiasedVariance=result['unbiasedVariance'],HC0=result['HC0'])\r\n  for i,r in enumerate(result['rows']):emit(r['role']+':'+r['id'],i+1,r['change'])\r\n elif api=='att':\r\n  result=att_projection(literal_panel(a['rows']),a.get('control','never'));summary=dict(sourceRows=result['sourceRows'],entities=result['sourceEntities'],cells=len(result['cells']),supportedCells=sum(r['defined']for r in result['cells']),postCells=sum(r['phase']=='post'for r in result['cells']))\r\n  for i,r in enumerate(result['cells']):emit('g'+str(r['g'])+':t'+str(r['t']),i+1,r['estimate'])\r\n elif api=='aggregate':\r\n  result=linear_aggregate(a);summary=dict(defined=result['defined'],estimate=result['estimate'],variance=result['variance'],covarianceRank=result['covarianceRank'],sumWeights=sum((r['coefficient']for r in result['weights']),Q(0)))\r\n  for i,r in enumerate(result['weights']):emit('g'+str(r['cohort'])+':t'+str(r['time']),i+1,r['contribution'])\r\n elif api=='twfe':\r\n  rows=literal_panel(a['rows']);G=panel(rows);result=twfe(G,sorted({r['time']for r in rows}));summary=dict(defined=result['beta']is not None,beta=result['beta'],numerator=result['num'],denominator=result['den'],balancedEntities=result['balancedEntities'],negativeTreatedCells=sum(v['coefficient']is not None and v['coefficient']<0 for v in result['weights'].values()))\r\n  for i,((g,t),r)in enumerate(sorted(result['weights'].items())):emit('g'+str(g)+':t'+str(t),i+1,r['coefficient'])\r\n elif api=='sensitivity':\r\n  result=sensitivity_fixed(a);summary={k:result[k]for k in['defined','estimate','scale','M','horizon','biasBudget','lower','upper']}\r\n  for i,k in enumerate(['lower','estimate','upper']):emit(k,i+1,result[k]if result['defined']else None)\r\n else:\r\n  result=realdata_fixed(a['kind'],data);post=[r for r in result['att']['cells']if r['phase']=='post'];s=next(r for r in result['aggregations']if r['type']=='simple');g=next(r for r in result['aggregations']if r['type']=='group'and r['key']=='overall');summary=dict(nativeRows=result['nativeRows'],modelRows=result['modelRows'],entities=result['entities'],postCells=len(post),simple=s['estimate'],group=g['estimate'],TWFE=result['twfe']['beta'],balancedEntities=result['twfe']['balancedEntities'])\r\n  for i,r in enumerate(post):emit('g'+str(r['g'])+':t'+str(r['t']),i+1,r['estimate'])\r\n out.mkdir(parents=True,exist_ok=True)\r\n if any(out.iterdir()):raise ValueError('use-new-empty-output-directory')\r\n shown={k:v9(v)for k,v in summary.items()};write(out/'summary.csv',[dict(name=k,value=v)for k,v in shown.items()]);write(out/'points.csv',points,['series','x','y','numericY']);full=dict(chapter='METR-20',profile=spec['id'],api=api,input=spec['input'],summary=shown,points=encode(points),details=encode(result),arithmetic='Python Fraction exact finite stored values;summary/plot approximate;bounded teaching projection,not causal or sampling certification')\r\n (out/'full.json').write_text(json.dumps(full,ensure_ascii=False,indent=2,allow_nan=False)+'\\n',encoding='utf8')\r\n import matplotlib\r\n matplotlib.use('Agg')\r\n import matplotlib.pyplot as plt\r\n plt.rcParams.update({'svg.fonttype':'none','font.family':'DejaVu Sans','font.size':12,'axes.spines.top':False,'axes.spines.right':False});fig,ax=plt.subplots(figsize=(9,5.6));good=[r for r in points if r['numericY']is not None]\r\n if good:\r\n  ax.scatter([r['x']for r in good],[r['numericY']for r in good],color='#315d7c',s=32);ax.axhline(0,color='#9eabb2',lw=.8);ax.set_xlabel('Declared cell/unit/bound ordinal')\r\n else:ax.text(.5,.5,'Undefined: no supported plotted quantity',ha='center',va='center',transform=ax.transAxes);ax.set_xticks([]);ax.set_yticks([])\r\n ax.set_ylabel('Cell weight'if api=='twfe'else result.get('unit','Stated outcome/bias units'));ax.set_title(spec['title']['en'],wrap=True,pad=14);ax.grid(axis='y',alpha=.2);fig.tight_layout(pad=2);fig.savefig(out/'plot.svg');plt.close(fig);print(json.dumps(shown))\r\n\r\nSPEC={'id': 'paired-single-and-missing', 'api': 'twobytwo', 'title': {'ko': '한 쌍의 0 점수와 미정의 표본 분산', 'en': 'One pair: zero scores, undefined sample variance'}, 'input': {'treated': [{'id': 'T1', 'before': '4', 'after': '10'}, {'id': 'Tmissing', 'before': None, 'after': '3'}], 'control': [{'id': 'C1', 'before': '2', 'after': '5'}]}, 'expectedReject': False}\r\nif __name__=='__main__':\r\n import sys\r\n run_fixed(SPEC,Path(sys.argv[1]),Path(sys.argv[2])if len(sys.argv)>2 else Path(__file__).resolve().parent.parent/'metr20-sources')\r\n",
      "arithmetic": "Python Fraction exact stored finite values;logs/summary/plots approximate",
      "summary": {
        "defined": "1",
        "estimate": "3",
        "treatedPairs": "1",
        "controlPairs": "1",
        "unbiasedVariance": "undefined",
        "HC0": "0"
      },
      "fullResultEmbedded": false,
      "plotEmbedded": false,
      "full": {
        "summary": {
          "defined": "1",
          "estimate": "3",
          "treatedPairs": "1",
          "controlPairs": "1",
          "unbiasedVariance": "undefined",
          "HC0": "0"
        },
        "notice": "Complete source/finite projection is retained in the linked external JSON; this short projection is not the full result."
      },
      "plot": null,
      "points": [
        {
          "series": "treated:T1",
          "x": 1,
          "y": "6",
          "numericY": 6.0
        },
        {
          "series": "treated:Tmissing",
          "x": 2,
          "y": null,
          "numericY": null
        },
        {
          "series": "control:C1",
          "x": 3,
          "y": "3",
          "numericY": 3.0
        }
      ],
      "summaryFile": "metr20-programs/paired-single-and-missing-python-summary.csv",
      "summarySHA256": "64b67d4250b2102f29014f3998ba95ed556367456adb14f0c7b16b40dc139c81",
      "pointsFile": "metr20-programs/paired-single-and-missing-python-points.csv",
      "pointsSHA256": "3ae5e798e450e7e981deb9c9cc3700c3d92d7963ed0ae2f5ba985114909b2dbb",
      "fullResultFile": "metr20-programs/paired-single-and-missing-python.json",
      "fullResultSHA256": "eeb4f11a4dd905bddff9a34fa51255d628a07ea7dc07429a2b1ef89894b30662",
      "plotFile": "metr20-programs/paired-single-and-missing-python.svg",
      "plotSHA256": "d55940e50a6f3f02e3694471d09a92edd03b9b12c6da5c582da1ac64f1105d11"
    },
    {
      "api": "twobytwo",
      "variant": "paired-single-and-missing",
      "profile": "paired-single-and-missing",
      "language": "R",
      "file": "metr20-programs/paired-single-and-missing-r.R",
      "codeSHA256": "b4800795f3fbce9dc5f16dc1b7ca2eadd2d9ed5236dacab0ea63789ba526902b",
      "returnCode": 0,
      "expectedRejection": false,
      "title": {
        "ko": "한 쌍의 0 점수와 미정의 표본 분산",
        "en": "One pair: zero scores, undefined sample variance"
      },
      "code": "# METR20 fixed example. Base R only, finite arithmetic approximate.\r\n# No JavaScript engine,model JSON,derived answer table,private module or internet.\r\noptions(stringsAsFactors=FALSE,digits=17)\r\nargv<-commandArgs(trailingOnly=TRUE);if(length(argv)<1L)stop('Supply a new empty output directory')\r\noutdir<-argv[1];script<-sub('^--file=','',commandArgs(FALSE)[grepl('^--file=',commandArgs(FALSE))][1]);here<-dirname(normalizePath(script,mustWork=TRUE));datadir<-if(length(argv)>=2L)argv[2]else file.path(here,'..','metr20-sources')\r\nunits<-c(country='log teen-employment points',person='recorded real earnings',company='FTE employees');clocks<-c(country='calendar year',person='calendar year',company='survey-wave index');steps<-c(country=1,person=3,company=1);files<-c(country='actual2500-county-mpdta-all6-fields.csv',person='actual38408-NSW-all15-fields.csv',company='actual410-NJPA-all46-fields.csv')\r\nnum<-function(s)ifelse(s=='.',NA_real_,as.numeric(s));mean0<-function(v)if(length(v))mean(v)else NA_real_;var0<-function(v)if(length(v)>1L)sum((v-mean(v))^2)/(length(v)-1L)else NA_real_\r\n\r\nSPEC<-list(id=\"paired-single-and-missing\",api=\"twobytwo\",title=list(ko=\"한 쌍의 0 점수와 미정의 표본 분산\",en=\"One pair: zero scores, undefined sample variance\"),input=list(treated=list(list(id=\"T1\",before=\"4\",after=\"10\"),list(id=\"Tmissing\",before=NA_real_,after=\"3\")),control=list(list(id=\"C1\",before=\"2\",after=\"5\"))),expectedReject=FALSE)\r\npanel<-function(rows){G<-list();for(r in rows){key<-r$entity;u<-G[[key]];if(is.null(u))u<-list(g=r$g,rows=list());stopifnot(identical(u$g,r$g),is.null(u$rows[[as.character(r$time)]]));u$rows[[as.character(r$time)]]<-r;G[[key]]<-u};G}\r\ncell<-function(G,g,t,step,control){b<-g-step;members<-list();T<-C<-list();for(key in names(G)){u<-G[[key]];target<-!is.na(u$g)&&u$g==g;comp<-is.na(u$g)||(control=='notyet'&&!is.na(u$g)&&u$g>max(t,b));role<-if(target)'treated'else if(comp)'control'else'excluded-comparison';before<-u$rows[[as.character(b)]];after<-u$rows[[as.character(t)]];yb<-if(is.null(before))NA_real_ else before$y;ya<-if(is.null(after))NA_real_ else after$y;eligible<-role!='excluded-comparison'&&!is.na(yb)&&!is.na(ya);reason<-if(role=='excluded-comparison')'target-or-already-exposed-cohort-not-valid-control'else if(is.null(before))'baseline-source-row-absent'else if(is.null(after))'target-time-source-row-absent'else if(is.na(yb))'baseline-outcome-missing'else if(is.na(ya))'target-outcome-missing'else'';m<-list(entity=key,nativeID=u$rows[[1]]$nativeID,g=u$g,role=role,eligible=eligible,baselineSourceId=if(is.null(before))NA_character_ else before$id,targetSourceId=if(is.null(after))NA_character_ else after$id,before=yb,after=ya,change=if(eligible)ya-yb else NA_real_,reason=reason);members[[key]]<-m;if(eligible){if(role=='treated')T[[length(T)+1L]]<-m else C[[length(C)+1L]]<-m}}\r\n change<-function(a)vapply(a,function(r)r$change,0);d<-mean0(change(T));e<-mean0(change(C));estimate<-if(is.na(d)||is.na(e))NA_real_ else d-e;defined<-!is.na(estimate);scores<-setNames(rep(NA_real_,length(members)),names(members));for(key in names(members)){m<-members[[key]];s<-if(!defined)NA_real_ else if(!m$eligible)0 else if(m$role=='treated')(m$change-d)/length(T)else-(m$change-e)/length(C);m$score<-s;scores[key]<-s;members[[key]]<-m};st<-var0(change(T));sc<-var0(change(C));v<-if(is.na(st)||is.na(sc))NA_real_ else st/length(T)+sc/length(C);level<-function(a,k)mean0(vapply(a,function(r)r[[k]],0))\r\n list(g=g,t=t,baseline=b,event=(t-g)/step,phase=if(t==b)'mechanical-reference'else if(t>=g)'post'else'pre-placebo',defined=defined,estimate=estimate,T=T,C=C,members=members,scores=scores,HC0=if(defined)sum(scores^2)else NA_real_,unbiased=v,treatedMeanBefore=level(T,'before'),treatedMeanAfter=level(T,'after'),treatedMeanChange=d,controlMeanBefore=level(C,'before'),controlMeanAfter=level(C,'after'),controlMeanChange=e)\r\n}\r\ncovariance<-function(cells){n<-length(cells);V<-matrix(NA_real_,n,n);for(i in seq_len(n))for(j in seq_len(n))if(cells[[i]]$defined&&cells[[j]]$defined)V[i,j]<-sum(cells[[i]]$scores*cells[[j]]$scores);V}\r\naggregate_cells<-function(post,V,step){out<-list();push<-function(typ,key,ii,w){est<-if(!length(ii)||any(vapply(post[ii],function(z)is.na(z$estimate),TRUE)))NA_real_ else sum(w*vapply(post[ii],function(z)z$estimate,0));vv<-if(is.na(est)||anyNA(V[ii,ii,drop=FALSE]))NA_real_ else as.numeric(t(w)%*%V[ii,ii,drop=FALSE]%*%w);out[[length(out)+1L]]<<-list(type=typ,key=as.character(key),ii=ii,w=w,estimate=est,variance=vv)};positive<-which(vapply(post,function(c)length(c$T)>0L,TRUE));mass<-sum(vapply(post[positive],function(c)length(c$T),0));push('simple','overall',positive,if(mass)vapply(post[positive],function(c)length(c$T)/mass,0)else numeric())\r\n for(typ in c('event','calendar','group')){keys<-vapply(post,function(c)if(typ=='event')c$event else if(typ=='calendar')c$t else c$g,0);gg<-sort(unique(keys));cohortmass<-if(typ=='group')sum(vapply(gg,function(k)length(post[[which(keys==k)[1]]]$T),0))else 0;allii<-integer();allw<-numeric();for(key in gg){ii<-which(keys==key);jj<-ii[vapply(post[ii],function(c)length(c$T)>0L,TRUE)];if(typ=='group'){stopifnot(length(unique(vapply(post[ii],function(c)length(c$T),0)))<=1L);w<-if(length(jj))rep(1/length(jj),length(jj))else numeric();if(cohortmass){allii<-c(allii,jj);allw<-c(allw,w*length(post[[ii[1]]]$T)/cohortmass)}}else{total<-sum(vapply(post[jj],function(c)length(c$T),0));w<-if(total)vapply(post[jj],function(c)length(c$T)/total,0)else numeric()};push(typ,key,jj,w)};if(typ=='group')push(typ,'overall',allii,allw)};out}\r\ntwfe<-function(G,times){ledger<-list();good<-list();for(key in names(G)){u<-G[[key]];absent<-times[!as.character(times)%in%names(u$rows)];missing<-times[vapply(times,function(t){r<-u$rows[[as.character(t)]];!is.null(r)&&is.na(r$y)},TRUE)];eligible<-length(times)>0L&&!length(absent)&&!length(missing);ledger[[length(ledger)+1L]]<-list(entity=key,g=u$g,nativeID=u$rows[[1]]$nativeID,eligible=eligible,absentTimes=paste(absent,collapse=','),missingOutcomeTimes=paste(missing,collapse=','),originalRows=length(u$rows));if(eligible)good[[key]]<-u};rows<-list();for(key in names(good))for(t in times){r<-good[[key]]$rows[[as.character(t)]];r$D<-as.integer(!is.na(r$g)&&t>=r$g);rows[[length(rows)+1L]]<-r};em<-lapply(good,function(u)list(D=mean(vapply(times,function(t)as.integer(!is.na(u$g)&&t>=u$g),0)),Y=mean(vapply(u$rows[as.character(times)],function(r)r$y,0))));tm<-lapply(times,function(t)list(D=mean(vapply(good,function(u)as.integer(!is.na(u$g)&&t>=u$g),0)),Y=mean(vapply(good,function(u)u$rows[[as.character(t)]]$y,0))));names(tm)<-as.character(times);gd<-mean0(vapply(rows,function(r)r$D,0));gy<-mean0(vapply(rows,function(r)r$y,0));num<-den<-0\r\n for(i in seq_along(rows)){r<-rows[[i]];r$residualD<-r$D-em[[r$entity]]$D-tm[[as.character(r$time)]]$D+gd;r$residualY<-r$y-em[[r$entity]]$Y-tm[[as.character(r$time)]]$Y+gy;num<-num+r$residualD*r$residualY;den<-den+r$residualD^2;rows[[i]]<-r};beta<-if(den!=0)num/den else NA_real_;weights<-list();for(i in seq_along(rows)){r<-rows[[i]];r$projectionCoefficient<-if(den!=0)r$residualD/den else NA_real_;r$regressionResidual<-if(!is.na(beta))r$residualY-beta*r$residualD else NA_real_;rows[[i]]<-r;if(r$D==1L){k<-paste(r$g,r$time,sep=':');z<-weights[[k]];if(is.null(z))z<-list(g=r$g,t=r$time,rows=0,coefficient=if(den!=0)0 else NA_real_);z$rows<-z$rows+1L;if(den!=0)z$coefficient<-z$coefficient+r$projectionCoefficient;weights[[k]]<-z}};list(ledger=ledger,rows=rows,num=num,den=den,beta=beta,weights=weights,balancedEntities=length(good))}\r\nadjacent_pre<-function(G,g,t,step,control){b<-t-step;T<-C<-numeric();for(u in G){target<-!is.na(u$g)&&u$g==g;comp<-is.na(u$g)||(control=='notyet'&&!is.na(u$g)&&u$g>max(t,b));if(!target&&!comp)next;before<-u$rows[[as.character(b)]];after<-u$rows[[as.character(t)]];if(!is.null(before)&&!is.null(after)&&!is.na(before$y)&&!is.na(after$y)){if(target)T<-c(T,after$y-before$y)else C<-c(C,after$y-before$y)}};if(!length(T)||!length(C))NA_real_ else mean(T)-mean(C)}\r\n\r\n# Newly authored bounded teaching projections; base R finite approximation.\r\n# Source helper functions are inlined in each public file, never imported.\r\nqnum<-function(v){if(is.null(v)||is.na(v))return(NA_real_);s<-strsplit(as.character(v),'/',fixed=TRUE)[[1]];if(length(s)==1L)as.numeric(s)else as.numeric(s[1])/as.numeric(s[2])}\r\npaired<-function(T,C){\r\n stats<-function(rr){use<-Filter(function(r)!is.na(qnum(r$before))&&!is.na(qnum(r$after)),rr);a<-vapply(use,function(r)qnum(r$before),0);b<-vapply(use,function(r)qnum(r$after),0);list(sourcePairs=length(rr),eligiblePairs=length(use),excludedPairs=length(rr)-length(use),meanBefore=mean0(a),meanAfter=mean0(b),meanChange=mean0(b-a),sampleChangeVariance=var0(b-a))}\r\n st<-stats(T);sc<-stats(C);defined<-st$eligiblePairs>0L&&sc$eligiblePairs>0L;estimate<-if(defined)st$meanChange-sc$meanChange else NA_real_;rr<-list()\r\n for(role in c('treated','control')){input<-if(role=='treated')T else C;s<-if(role=='treated')st else sc;for(r in input){before<-qnum(r$before);after<-qnum(r$after);eligible<-!is.na(before)&&!is.na(after);change<-if(eligible)after-before else NA_real_;score<-if(!defined)NA_real_ else if(!eligible)0 else (change-s$meanChange)/(if(role=='treated')s$eligiblePairs else -s$eligiblePairs);rr[[length(rr)+1L]]<-list(id=r$id,role=role,before=before,after=after,eligible=eligible,change=change,score=score)}}\r\n list(defined=defined,estimate=estimate,treated=st,control=sc,unbiasedVariance=if(defined&&st$eligiblePairs>=2L&&sc$eligiblePairs>=2L)st$sampleChangeVariance/st$eligiblePairs+sc$sampleChangeVariance/sc$eligiblePairs else NA_real_,HC0=if(defined)sum(vapply(rr,function(r)r$score^2,0))else NA_real_,rows=rr)\r\n}\r\nliteral_panel<-function(rr)lapply(seq_along(rr),function(i){r<-rr[[i]];r$y<-qnum(r$y);r$nativeID<-r$entity;r$sourceRow<-i;r})\r\natt_projection<-function(rows,control='never',step=1){G<-panel(rows);times<-sort(unique(vapply(rows,function(r)r$time,0)));cohorts<-sort(unique(na.omit(vapply(rows,function(r)r$g,0))));cells<-list();for(g in cohorts)for(t in times)cells[[length(cells)+1L]]<-cell(G,g,t,step,control);list(sourceRows=length(rows),sourceEntities=length(G),step=step,control=control,cells=cells,covariance=covariance(cells))}\r\nlinear_aggregate<-function(a){\r\n rr<-lapply(a$cells,function(r){r$estimate<-qnum(r$estimate);r$weight<-qnum(r$weight);r});V<-if(is.null(a$covariance))NULL else do.call(rbind,lapply(a$covariance,function(r)vapply(r,qnum,0)));rank<-NA_real_\r\n if(!is.null(V)){stopifnot(nrow(V)==length(rr),ncol(V)==length(rr),all(V==t(V)));ev<-eigen(V,symmetric=TRUE,only.values=TRUE)$values;if(any(ev< -1e-12))stop('covariance-must-be-positive-semidefinite');rank<-sum(ev>1e-12)}\r\n selected<-which(vapply(rr,function(r)r$time>=r$cohort&&r$weight>0,TRUE));w<-numeric(length(rr));type<-if(is.null(a$type))'simple'else a$type\r\n if(type=='simple'){mass<-sum(vapply(rr[selected],function(r)r$weight,0));if(mass>0)for(i in selected)w[i]<-rr[[i]]$weight/mass}else{g<-vapply(rr,function(r)r$cohort,0);gg<-sort(unique(g[selected]));mass<-sum(vapply(gg,function(gi)rr[[intersect(which(g==gi),selected)[1]]]$weight,0));for(gi in gg){ii<-intersect(which(g==gi),selected);stopifnot(length(unique(vapply(rr[ii],function(r)r$weight,0)))==1L);w[ii]<-rr[[ii[1]]]$weight/mass/length(ii)}}\r\n used<-which(w>0);estimate<-if(!length(used)||any(vapply(rr[used],function(r)is.na(r$estimate),TRUE)))NA_real_ else sum(w[used]*vapply(rr[used],function(r)r$estimate,0));variance<-if(is.na(estimate)||is.null(V))NA_real_ else as.numeric(t(w)%*%V%*%w);weights<-lapply(used,function(i)list(sourceIndex=i-1L,cohort=rr[[i]]$cohort,time=rr[[i]]$time,coefficient=w[i],estimate=rr[[i]]$estimate,contribution=w[i]*rr[[i]]$estimate))\r\n list(type=type,defined=!is.na(estimate),estimate=estimate,variance=variance,covarianceRank=rank,weights=weights,cells=rr,covariance=V)\r\n}\r\nsensitivity_fixed<-function(a){estimate<-qnum(a$estimate);M<-qnum(a$M);h<-if(is.null(a$horizon))1 else a$horizon;stopifnot(M>=0,h>=1);pre<-vapply(a$preDifferences,qnum,0);scale<-if(!is.null(a$scale))qnum(a$scale)else if(length(pre))max(abs(pre))else NA_real_;budget<-M*scale*h;list(defined=!is.na(scale),estimate=estimate,scale=scale,M=M,horizon=h,biasBudget=budget,lower=estimate-budget,upper=estimate+budget,preDifferences=as.list(pre),confidenceLevel=NULL)}\r\nrealdata_fixed<-function(kind){rows<-models[[kind]];G<-panel(rows);times<-sort(unique(vapply(rows,function(r)r$time,0)));step<-unname(steps[kind]);aa<-att_projection(rows,'never',step);post<-Filter(function(r)r$phase=='post',aa$cells);aggs<-aggregate_cells(post,covariance(post),step);tf<-twfe(G,times);list(kind=kind,unit=unname(units[kind]),periodUnit=unname(clocks[kind]),nativeRows=nrow(raw[[kind]]),modelRows=length(rows),entities=length(G),sourceRows=rows,att=aa,aggregations=aggs,twfe=tf,scope='Complete native/model/paired/balanced source frames; never control,universal base,no anticipation;not causal/sampling certification.')}\r\n# JSON encoder deliberately handles matrices and scalar/vector distinctions.\r\nencode<-function(x){\r\n if(is.null(x))return('null')\r\n quote<-function(s){s<-gsub('\\\\','\\\\\\\\',as.character(s),fixed=TRUE);s<-gsub('\"','\\\\\"',s,fixed=TRUE);s<-gsub('\\n','\\\\n',s,fixed=TRUE);s<-gsub('\\r','\\\\r',s,fixed=TRUE);s<-gsub('\\t','\\\\t',s,fixed=TRUE);paste0('\"',s,'\"')}\r\n if(is.matrix(x))return(paste0('[',paste(vapply(seq_len(nrow(x)),function(i)encode(as.list(unname(x[i,]))),''),collapse=','),']'))\r\n if(is.list(x)){if(length(x)&&!is.null(names(x)))return(paste0('{',paste(paste0(vapply(names(x),quote,''),':',vapply(x,encode,'')),collapse=','),'}'));return(paste0('[',paste(vapply(x,encode,''),collapse=','),']'))}\r\n if(length(x)!=1L)return(encode(as.list(unname(x))))\r\n if(is.na(x))return('null');if(is.logical(x))return(if(x)'true'else'false');if(is.numeric(x))return(sprintf('%.17g',unname(x)));quote(x)\r\n}\r\nv9<-function(x){if(is.null(x)||is.na(x))return('undefined');if(is.logical(x))return(if(x)'1'else'0');if(is.numeric(x))return(sprintf('%.9g',unname(x)));as.character(x)}\r\nrun_fixed<-function(spec,out){api<-spec$api;a<-spec$input;summary<-list();points<-list();emit<-function(series,x,y){points[[length(points)+1L]]<<-list(series=series,x=x,y=y,numericY=y)}\r\n if(api=='twobytwo'){result<-paired(a$treated,a$control);summary<-list(defined=result$defined,estimate=result$estimate,treatedPairs=result$treated$eligiblePairs,controlPairs=result$control$eligiblePairs,unbiasedVariance=result$unbiasedVariance,HC0=result$HC0);for(i in seq_along(result$rows)){r<-result$rows[[i]];emit(paste(r$role,r$id,sep=':'),i,r$change)}}\r\n else if(api=='att'){result<-att_projection(literal_panel(a$rows),a$control);summary<-list(sourceRows=result$sourceRows,entities=result$sourceEntities,cells=length(result$cells),supportedCells=sum(vapply(result$cells,function(r)r$defined,TRUE)),postCells=sum(vapply(result$cells,function(r)r$phase=='post',TRUE)));for(i in seq_along(result$cells)){r<-result$cells[[i]];emit(paste0('g',r$g,':t',r$t),i,r$estimate)}}\r\n else if(api=='aggregate'){result<-linear_aggregate(a);summary<-list(defined=result$defined,estimate=result$estimate,variance=result$variance,covarianceRank=result$covarianceRank,sumWeights=sum(vapply(result$weights,function(r)r$coefficient,0)));for(i in seq_along(result$weights)){r<-result$weights[[i]];emit(paste0('g',r$cohort,':t',r$time),i,r$contribution)}}\r\n else if(api=='twfe'){rows<-literal_panel(a$rows);G<-panel(rows);result<-twfe(G,sort(unique(vapply(rows,function(r)r$time,0))));summary<-list(defined=!is.na(result$beta),beta=result$beta,numerator=result$num,denominator=result$den,balancedEntities=result$balancedEntities,negativeTreatedCells=sum(vapply(result$weights,function(r)!is.na(r$coefficient)&&r$coefficient<0,TRUE)));if(length(result$weights)){ord<-order(vapply(result$weights,function(r)r$g,0),vapply(result$weights,function(r)r$t,0));for(i in seq_along(ord)){r<-result$weights[[ord[i]]];emit(paste0('g',r$g,':t',r$t),i,r$coefficient)}}}\r\n else if(api=='sensitivity'){result<-sensitivity_fixed(a);summary<-result[c('defined','estimate','scale','M','horizon','biasBudget','lower','upper')];for(i in seq_along(c('lower','estimate','upper'))){k<-c('lower','estimate','upper')[i];emit(k,i,if(result$defined)result[[k]]else NA_real_)}}\r\n else{result<-realdata_fixed(a$kind);post<-Filter(function(r)r$phase=='post',result$att$cells);simple<-Filter(function(r)r$type=='simple',result$aggregations)[[1]];group<-Filter(function(r)r$type=='group'&&r$key=='overall',result$aggregations)[[1]];summary<-list(nativeRows=result$nativeRows,modelRows=result$modelRows,entities=result$entities,postCells=length(post),simple=simple$estimate,group=group$estimate,TWFE=result$twfe$beta,balancedEntities=result$twfe$balancedEntities);for(i in seq_along(post)){r<-post[[i]];emit(paste0('g',r$g,':t',r$t),i,r$estimate)}}\r\n dir.create(out,recursive=TRUE,showWarnings=FALSE);if(length(list.files(out,all.files=TRUE,no..=TRUE)))stop('use-new-empty-output-directory');shown<-lapply(summary,v9);write.csv(data.frame(name=names(shown),value=unlist(shown,use.names=FALSE)),file.path(out,'summary.csv'),row.names=FALSE,na='');pointframe<-if(length(points))do.call(rbind,lapply(points,function(p)data.frame(series=p$series,x=p$x,y=p$y,numericY=p$numericY,stringsAsFactors=FALSE)))else data.frame(series=character(),x=numeric(),y=numeric(),numericY=numeric());write.csv(pointframe,file.path(out,'points.csv'),row.names=FALSE,na='');full<-list(chapter='METR-20',profile=spec$id,api=api,input=spec$input,summary=shown,points=points,details=result,arithmetic='Base R approximate finite values;bounded teaching projection,not exact fractions or causal/sampling certification.');writeLines(encode(full),file.path(out,'full.json'),useBytes=TRUE)\r\n svg(file.path(out,'plot.svg'),width=9,height=5.6,pointsize=12);par(mar=c(4.5,5.5,4,1));good<-pointframe[!is.na(pointframe$numericY),,drop=FALSE]\r\n if(nrow(good)){plot(good$x,good$numericY,pch=19,col='#315d7c',xlab='Declared cell/unit/bound ordinal',ylab=if(api=='twfe')'Cell weight'else if(!is.null(result$unit))result$unit else 'Stated outcome/bias units',main=spec$title$en);abline(h=0,col='#9eabb2');grid(nx=NA,ny=NULL,col='#e2e5e7');points(good$x,good$numericY,pch=19,col='#315d7c')}else{plot.new();text(.5,.5,'Undefined: no supported plotted quantity');title(main=spec$title$en)};dev.off();cat(encode(shown),'\\n')\r\n}\r\n\r\nrun_fixed(SPEC,outdir)\r\n",
      "arithmetic": "Base R approximate finite arithmetic;not an exact rational result",
      "summary": {
        "defined": "1",
        "estimate": "3",
        "treatedPairs": "1",
        "controlPairs": "1",
        "unbiasedVariance": "undefined",
        "HC0": "0"
      },
      "fullResultEmbedded": false,
      "plotEmbedded": false,
      "full": {
        "summary": {
          "defined": "1",
          "estimate": "3",
          "treatedPairs": "1",
          "controlPairs": "1",
          "unbiasedVariance": "undefined",
          "HC0": "0"
        },
        "notice": "Complete source/finite projection is retained in the linked external JSON; this short projection is not the full result."
      },
      "plot": null,
      "points": [
        {
          "series": "treated:T1",
          "x": 1,
          "y": 6,
          "numericY": 6
        },
        {
          "series": "treated:Tmissing",
          "x": 2,
          "y": null,
          "numericY": null
        },
        {
          "series": "control:C1",
          "x": 3,
          "y": 3,
          "numericY": 3
        }
      ],
      "summaryFile": "metr20-programs/paired-single-and-missing-r-summary.csv",
      "summarySHA256": "af612a9e870b066339ab9a8a9e03f6fc876fe6632246faeaf7fd46baef72e8e7",
      "pointsFile": "metr20-programs/paired-single-and-missing-r-points.csv",
      "pointsSHA256": "c77d5e73beb28d608c276b4f949bec65527fd3e1850064ae432ae76c34e8407d",
      "fullResultFile": "metr20-programs/paired-single-and-missing-r.json",
      "fullResultSHA256": "914701d7b90a982a186ac4b38c331e741e717c59763b035db799332be863ce75",
      "plotFile": "metr20-programs/paired-single-and-missing-r.svg",
      "plotSHA256": "b8f911adf73dce5d227a4bcbb9a90197877b41de5184b1caff37cb31f67c432c"
    },
    {
      "api": "att",
      "variant": "att-never-reference",
      "profile": "att-never-reference",
      "language": "Python",
      "file": "metr20-programs/att-never-reference-python.py",
      "codeSHA256": "c94b44af81df3e962a588b6866dada52f4425ea65f77687bed375d57a6ed9c6b",
      "returnCode": 0,
      "expectedRejection": false,
      "title": {
        "ko": "고정 기준과 사후 셀의 전체 구분",
        "en": "Universal baseline, reference and post cells"
      },
      "code": "\"\"\"METR20 actual sources. Python standard library, exact stored-value rationals.\r\nRead ONLY the three native-observation CSVs; no JS engine,model JSON,derived\r\nanswers,private modules or internet needed. Outcome measurement/identification\r\nand valid sampling inference remain separate from exact finite arithmetic.\r\nRun: python metr20-reproduce.py --data-dir PATH --out NEW_EMPTY_DIRECTORY\r\n\"\"\"\r\nfrom pathlib import Path\r\nfrom fractions import Fraction as Q\r\nfrom collections import defaultdict,Counter\r\nimport csv,json,math,argparse,hashlib\r\n\r\nUNIT={'country':'log teen-employment points','person':'recorded real earnings','company':'FTE employees'}\r\nCLOCK={'country':'calendar year','person':'calendar year','company':'survey-wave index'}\r\nSTEP={'country':1,'person':3,'company':1}\r\nFILES={'country':'actual2500-county-mpdta-all6-fields.csv','person':'actual38408-NSW-all15-fields.csv','company':'actual410-NJPA-all46-fields.csv'}\r\ndef avg(v):return sum(v,Q(0))/len(v)if v else None\r\ndef samplevar(v):return sum(((x-avg(v))**2 for x in v),Q(0))/(len(v)-1)if len(v)>1 else None\r\ndef binary(s):return None if s=='.'else Q.from_float(float(s))\r\ndef token(v):\r\n if v is None:return ''\r\n if isinstance(v,bool):return 'true'if v else'false'\r\n return str(v)\r\ndef safe_float(v):\r\n if v is None:return None\r\n try:r=float(v)\r\n except OverflowError:return None\r\n return r if math.isfinite(r)else None\r\ndef read(p):\r\n with p.open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))\r\ndef write(p,rows,head=None):\r\n if head is None:\r\n  assert rows;head=list(rows[0])\r\n with p.open('w',encoding='utf8',newline='')as f:\r\n  w=csv.DictWriter(f,fieldnames=head);w.writeheader();w.writerows({k:token(r.get(k))for k in head}for r in rows)\r\ndef source(data):\r\n raw={k:read(data/n)for k,n in FILES.items()};assert[len(raw[k])for k in FILES]==[2500,38408,410]\r\n models={k:[]for k in FILES}\r\n for r in raw['country']:\r\n  g0=int(r['first.treat']);g=None if g0==0 else g0;assert int(r['treat'])==int(g is not None)\r\n  models['country'].append(dict(id='mpdta:'+r['sourceRow'],entity='county:'+str(int(r['countyreal'])),time=int(r['year']),y=binary(r['lemp']),g=g,sourceRow=int(r['sourceRow']),nativeID=r['countyreal']))\r\n for r in raw['person']:\r\n  selected=int(r['experimental'])==1;assert selected==(int(r['sample'])==1);assert(r['treated']!='.')==selected\r\n  if selected:\r\n   d=int(r['treated']);assert d in[0,1]\r\n   models['person'].append(dict(id='nsw:'+r['sourceRow'],entity='nsw-id:'+str(int(r['id'])),time=int(r['year']),y=binary(r['re']),g=1978 if d else None,sourceRow=int(r['sourceRow']),nativeID=str(int(r['id']))))\r\n for r in raw['company']:\r\n  state=int(r['STATE']);assert state in[0,1]\r\n  for t,suffix in[(0,''),(1,'2')]:\r\n   a=[r[n+suffix]for n in['EMPFT','NMGRS','EMPPT']];y=None if'.'in a else Q(a[0])+Q(a[1])+Q(a[2])/2\r\n   models['company'].append(dict(id='njpa:'+r['sourceRow']+':wave'+str(t),entity='njpa-row:'+r['sourceRow'],time=t,y=y,g=1 if state else None,sourceRow=int(r['sourceRow']),nativeID=r['SHEET']))\r\n assert[len(models[k])for k in FILES]==[2500,1444,820]\r\n return models,raw\r\ndef panel(rows):\r\n groups={}\r\n for r in rows:\r\n  u=groups.setdefault(r['entity'],{'g':r['g'],'rows':{}});assert u['g']==r['g']and r['time']not in u['rows'];u['rows'][r['time']]=r\r\n return groups\r\ndef cell(groups,g,t,step,control):\r\n b=g-step;members=[];T=[];C=[]\r\n for key,u in groups.items():\r\n  role='treated'if u['g']==g else'control'if u['g']is None or(control=='notyet'and u['g']>max(t,b))else'excluded-comparison'\r\n  before=u['rows'].get(b);after=u['rows'].get(t);yb=None if before is None else before['y'];ya=None if after is None else after['y'];eligible=role!='excluded-comparison'and yb is not None and ya is not None\r\n  reason='target-or-already-exposed-cohort-not-valid-control'if role=='excluded-comparison'else'baseline-source-row-absent'if before is None else'target-time-source-row-absent'if after is None else'baseline-outcome-missing'if yb is None else'target-outcome-missing'if ya is None else''\r\n  m={'entity':key,'nativeID':next(iter(u['rows'].values()))['nativeID'],'g':u['g'],'role':role,'eligible':eligible,'baselineSourceId':None if before is None else before['id'],'targetSourceId':None if after is None else after['id'],'before':yb,'after':ya,'change':ya-yb if eligible else None,'reason':reason};members.append(m)\r\n  if eligible:(T if role=='treated'else C).append(m)\r\n d=avg([r['change']for r in T]);e=avg([r['change']for r in C]);estimate=None if d is None or e is None else d-e;defined=estimate is not None;scores={}\r\n for m in members:\r\n  s=None if not defined else Q(0)\r\n  if defined and m['eligible']:s=(m['change']-(d if m['role']=='treated'else e))/(len(T)if m['role']=='treated'else-len(C))\r\n  m['score']=s;scores[m['entity']]=s\r\n st=samplevar([r['change']for r in T]);sc=samplevar([r['change']for r in C]);v=None if st is None or sc is None else st/len(T)+sc/len(C)\r\n return {'g':g,'t':t,'baseline':b,'event':(t-g)//step,'phase':'mechanical-reference'if t==b else'post'if t>=g else'pre-placebo','defined':defined,'estimate':estimate,'T':T,'C':C,'members':members,'scores':scores,'HC0':None if not defined else sum((s*s for s in scores.values()),Q(0)),'unbiased':v,'treatedMeanBefore':avg([r['before']for r in T]),'treatedMeanAfter':avg([r['after']for r in T]),'treatedMeanChange':d,'controlMeanBefore':avg([r['before']for r in C]),'controlMeanAfter':avg([r['after']for r in C]),'controlMeanChange':e}\r\ndef covariance(cells):\r\n return[[None if not a['defined']or not b['defined']else sum((v*b['scores'][i]for i,v in a['scores'].items()),Q(0))for b in cells]for a in cells]\r\ndef aggregate(post,V,step):\r\n out=[]\r\n def push(typ,key,coeff):\r\n  estimate=None if not coeff or any(post[i]['estimate']is None for i in coeff)else sum((w*post[i]['estimate']for i,w in coeff.items()),Q(0));variance=None if estimate is None or any(V[i][j]is None for i in coeff for j in coeff)else sum((a*b*V[i][j]for i,a in coeff.items()for j,b in coeff.items()),Q(0));out.append({'type':typ,'key':key,'coeff':coeff,'estimate':estimate,'variance':variance})\r\n positive=[i for i,c in enumerate(post)if len(c['T'])>0];mass=sum(len(post[i]['T'])for i in positive)\r\n push('simple','overall',{i:Q(len(post[i]['T']),mass)for i in positive}if mass else{})\r\n for typ in['event','calendar','group']:\r\n  groups=defaultdict(list)\r\n  for i,c in enumerate(post):groups[c['event']if typ=='event'else c['t']if typ=='calendar'else c['g']].append(i)\r\n  overall={};cohortMass=sum(len(post[ii[0]]['T'])for ii in groups.values())if typ=='group'else 0\r\n  for key,ii in sorted(groups.items()):\r\n   jj=[i for i in ii if len(post[i]['T'])>0]\r\n   if typ=='group':\r\n    assert len({len(post[i]['T'])for i in ii})<=1\r\n    coeff={i:Q(1,len(jj))for i in jj}if jj else{}\r\n    if cohortMass:\r\n     for i,w in coeff.items():overall[i]=w*Q(len(post[ii[0]]['T']),cohortMass)\r\n   else:\r\n    total=sum(len(post[i]['T'])for i in jj);coeff={i:Q(len(post[i]['T']),total)for i in jj}if total else{}\r\n   push(typ,str(key),coeff)\r\n  if typ=='group':push(typ,'overall',overall)\r\n return out\r\ndef twfe(groups,times):\r\n ledger=[];good={}\r\n for key,u in groups.items():\r\n  absent=[t for t in times if t not in u['rows']];missing=[t for t in times if t in u['rows']and u['rows'][t]['y']is None];eligible=bool(times)and not absent and not missing\r\n  ledger.append({'entity':key,'g':u['g'],'nativeID':next(iter(u['rows'].values()))['nativeID'],'eligible':eligible,'absentTimes':','.join(map(str,absent)),'missingOutcomeTimes':','.join(map(str,missing)),'originalRows':len(u['rows'])})\r\n  if eligible:good[key]=u\r\n rows=[dict(**u['rows'][t],D=Q(u['g']is not None and t>=u['g']))for key,u in good.items()for t in times]\r\n em={k:{'D':avg([Q(u['g']is not None and t>=u['g'])for t in times]),'Y':avg([u['rows'][t]['y']for t in times])}for k,u in good.items()};tm={t:{'D':avg([Q(u['g']is not None and t>=u['g'])for u in good.values()]),'Y':avg([u['rows'][t]['y']for u in good.values()])}for t in times};gd=avg([r['D']for r in rows]);gy=avg([r['y']for r in rows]);num=den=Q(0)\r\n for r in rows:\r\n  r['residualD']=r['D']-em[r['entity']]['D']-tm[r['time']]['D']+gd;r['residualY']=r['y']-em[r['entity']]['Y']-tm[r['time']]['Y']+gy;num+=r['residualD']*r['residualY'];den+=r['residualD']**2\r\n beta=num/den if den else None;weights={}\r\n for r in rows:\r\n  r['projectionCoefficient']=r['residualD']/den if den else None;r['regressionResidual']=r['residualY']-beta*r['residualD']if beta is not None else None\r\n  if r['D']:\r\n   k=(r['g'],r['time']);z=weights.setdefault(k,{'rows':0,'coefficient':Q(0)if den else None});z['rows']+=1\r\n   if den:z['coefficient']+=r['projectionCoefficient']\r\n return {'ledger':ledger,'rows':rows,'num':num,'den':den,'beta':beta,'weights':weights,'balancedEntities':len(good)}\r\ndef adjacent_pre(groups,g,t,step,control):\r\n b=t-step;T=[];C=[]\r\n for u in groups.values():\r\n  if u['g']==g:target=T\r\n  elif u['g']is None or(control=='notyet'and u['g']>max(t,b)):target=C\r\n  else:continue\r\n  before=u['rows'].get(b);after=u['rows'].get(t)\r\n  if before is not None and after is not None and before['y']is not None and after['y']is not None:target.append(after['y']-before['y'])\r\n return None if not T or not C else avg(T)-avg(C)\r\n\r\n\"\"\"New bounded teaching projections. The program is self-contained after build.\r\nExact Fraction finite algebra; figures and9-digit summary are approximations.\r\nIt is not a general parser/API replacement or a causal/inference certificate.\r\n\"\"\"\r\ndef paired(treated,control):\r\n def stats(rr):\r\n  use=[r for r in rr if r['before']is not None and r['after']is not None];delta=[Q(r['after'])-Q(r['before'])for r in use]\r\n  return dict(sourcePairs=len(rr),eligiblePairs=len(use),excludedPairs=len(rr)-len(use),meanBefore=avg([Q(r['before'])for r in use]),meanAfter=avg([Q(r['after'])for r in use]),meanChange=avg(delta),sampleChangeVariance=samplevar(delta))\r\n T,C=stats(treated),stats(control);defined=T['eligiblePairs']>0 and C['eligiblePairs']>0;estimate=T['meanChange']-C['meanChange']if defined else None;records=[]\r\n for group,rr,s in [('treated',treated,T),('control',control,C)]:\r\n  for r in rr:\r\n   before=None if r['before']is None else Q(r['before']);after=None if r['after']is None else Q(r['after']);eligible=before is not None and after is not None;delta=after-before if eligible else None;score=None if not defined else Q(0)if not eligible else(delta-s['meanChange'])/(s['eligiblePairs']if group=='treated'else-s['eligiblePairs']);records.append(dict(id=r['id'],role=group,before=before,after=after,eligible=eligible,change=delta,score=score))\r\n unbiased=None if not defined or T['eligiblePairs']<2 or C['eligiblePairs']<2 else T['sampleChangeVariance']/T['eligiblePairs']+C['sampleChangeVariance']/C['eligiblePairs'];hc0=None if not defined else sum((r['score']**2 for r in records),Q(0))\r\n return dict(defined=defined,estimate=estimate,treated=T,control=C,unbiasedVariance=unbiased,HC0=hc0,rows=records)\r\ndef literal_panel(raw):\r\n return[dict(r,y=None if r['y']is None else Q(r['y']),nativeID=r['entity'],sourceRow=i+1)for i,r in enumerate(raw)]\r\ndef att_projection(rows,control='never',step=1):\r\n G=panel(rows);times=sorted({r['time']for r in rows});cohorts=sorted({r['g']for r in rows if r['g']is not None});cells=[cell(G,g,t,step,control)for g in cohorts for t in times]\r\n return dict(sourceRows=len(rows),sourceEntities=len(G),step=step,control=control,cells=cells,covariance=covariance(cells))\r\ndef psd(V):\r\n A=[r[:]for r in V];rank=0\r\n while A:\r\n  if any(A[i][i]<0 for i in range(len(A))):raise ValueError('covariance-must-be-positive-semidefinite')\r\n  p=next((i for i in range(len(A))if A[i][i]>0),None)\r\n  if p is None:\r\n   if any(v for r in A for v in r):raise ValueError('covariance-must-be-positive-semidefinite')\r\n   return rank\r\n  A[0],A[p]=A[p],A[0]\r\n  for r in A:r[0],r[p]=r[p],r[0]\r\n  d=A[0][0];A=[[A[i][j]-A[i][0]*A[0][j]/d for j in range(1,len(A))]for i in range(1,len(A))];rank+=1\r\n return rank\r\ndef linear_aggregate(a):\r\n rr=[dict(r,estimate=None if r['estimate']is None else Q(r['estimate']),weight=Q(r['weight']))for r in a['cells']];V=[[Q(v)for v in r]for r in a['covariance']]if 'covariance'in a else None\r\n if V is not None:\r\n  assert len(V)==len(rr)and all(len(z)==len(rr)for z in V);assert all(V[i][j]==V[j][i]for i in range(len(rr))for j in range(len(rr)));rank=psd(V)\r\n else:rank=None\r\n selected=[i for i,r in enumerate(rr)if r['time']>=r['cohort']and r['weight']>0];weights={}\r\n if a.get('type','simple')=='simple':\r\n  mass=sum((rr[i]['weight']for i in selected),Q(0));weights={i:rr[i]['weight']/mass for i in selected}if mass else{}\r\n else:\r\n  gg=defaultdict(list)\r\n  for i in selected:gg[rr[i]['cohort']].append(i)\r\n  assert all(len({rr[i]['weight']for i in ii})==1 for ii in gg.values());mass=sum((rr[ii[0]]['weight']for ii in gg.values()),Q(0));weights={i:rr[ii[0]]['weight']/mass/len(ii)for ii in gg.values()for i in ii}if mass else{}\r\n estimate=None if not weights or any(rr[i]['estimate']is None for i in weights)else sum((w*rr[i]['estimate']for i,w in weights.items()),Q(0));variance=None if estimate is None or V is None else sum((x*y*V[i][j]for i,x in weights.items()for j,y in weights.items()),Q(0))\r\n return dict(type=a.get('type','simple'),defined=estimate is not None,estimate=estimate,variance=variance,covarianceRank=rank,weights=[dict(sourceIndex=i,cohort=rr[i]['cohort'],time=rr[i]['time'],coefficient=w,estimate=rr[i]['estimate'],contribution=None if rr[i]['estimate']is None else w*rr[i]['estimate'])for i,w in weights.items()],cells=rr,covariance=V)\r\ndef sensitivity_fixed(a):\r\n estimate=Q(a['estimate']);M=Q(a['M']);h=a.get('horizon',1);assert M>=0 and h>=1\r\n pre=[Q(v)for v in a.get('preDifferences',[])];scale=Q(a['scale'])if 'scale'in a else max(map(abs,pre))if pre else None;budget=None if scale is None else M*scale*h\r\n return dict(defined=scale is not None,estimate=estimate,scale=scale,M=M,horizon=h,biasBudget=budget,lower=None if budget is None else estimate-budget,upper=None if budget is None else estimate+budget,preDifferences=pre,confidenceLevel=None)\r\ndef realdata_fixed(kind,data):\r\n models,raw=source(data);rows=models[kind];G=panel(rows);times=sorted({r['time']for r in rows});step=STEP[kind];aa=att_projection(rows,'never',step);post=[r for r in aa['cells']if r['phase']=='post'];aggs=aggregate(post,covariance(post),step);tf=twfe(G,times)\r\n return dict(kind=kind,unit=UNIT[kind],periodUnit=CLOCK[kind],nativeRows=len(raw[kind]),modelRows=len(rows),entities=len(G),sourceRows=rows,att=aa,aggregations=aggs,twfe=tf,scope='Complete source frame; never-treated comparison,universal baseline,no anticipation. Native/model/paired/balanced denominators differ. All sampling/causal assumptions remain separate.')\r\ndef encode(v):\r\n if isinstance(v,Q):return str(v)\r\n if isinstance(v,dict):return{str(k):encode(x)for k,x in v.items()}\r\n if isinstance(v,(list,tuple)):return[encode(x)for x in v]\r\n return v\r\ndef v9(v):\r\n if v is None:return'undefined'\r\n if isinstance(v,str):return v\r\n if isinstance(v,bool):return'1'if v else'0'\r\n return format(float(v),'.9g')\r\ndef run_fixed(spec,out,data):\r\n api=spec['api'];a=spec['input'];summary={};points=[]\r\n def emit(series,x,y):points.append(dict(series=series,x=x,y=y,numericY=safe_float(y)))\r\n if api=='twobytwo':\r\n  result=paired(a['treated'],a['control']);summary=dict(defined=result['defined'],estimate=result['estimate'],treatedPairs=result['treated']['eligiblePairs'],controlPairs=result['control']['eligiblePairs'],unbiasedVariance=result['unbiasedVariance'],HC0=result['HC0'])\r\n  for i,r in enumerate(result['rows']):emit(r['role']+':'+r['id'],i+1,r['change'])\r\n elif api=='att':\r\n  result=att_projection(literal_panel(a['rows']),a.get('control','never'));summary=dict(sourceRows=result['sourceRows'],entities=result['sourceEntities'],cells=len(result['cells']),supportedCells=sum(r['defined']for r in result['cells']),postCells=sum(r['phase']=='post'for r in result['cells']))\r\n  for i,r in enumerate(result['cells']):emit('g'+str(r['g'])+':t'+str(r['t']),i+1,r['estimate'])\r\n elif api=='aggregate':\r\n  result=linear_aggregate(a);summary=dict(defined=result['defined'],estimate=result['estimate'],variance=result['variance'],covarianceRank=result['covarianceRank'],sumWeights=sum((r['coefficient']for r in result['weights']),Q(0)))\r\n  for i,r in enumerate(result['weights']):emit('g'+str(r['cohort'])+':t'+str(r['time']),i+1,r['contribution'])\r\n elif api=='twfe':\r\n  rows=literal_panel(a['rows']);G=panel(rows);result=twfe(G,sorted({r['time']for r in rows}));summary=dict(defined=result['beta']is not None,beta=result['beta'],numerator=result['num'],denominator=result['den'],balancedEntities=result['balancedEntities'],negativeTreatedCells=sum(v['coefficient']is not None and v['coefficient']<0 for v in result['weights'].values()))\r\n  for i,((g,t),r)in enumerate(sorted(result['weights'].items())):emit('g'+str(g)+':t'+str(t),i+1,r['coefficient'])\r\n elif api=='sensitivity':\r\n  result=sensitivity_fixed(a);summary={k:result[k]for k in['defined','estimate','scale','M','horizon','biasBudget','lower','upper']}\r\n  for i,k in enumerate(['lower','estimate','upper']):emit(k,i+1,result[k]if result['defined']else None)\r\n else:\r\n  result=realdata_fixed(a['kind'],data);post=[r for r in result['att']['cells']if r['phase']=='post'];s=next(r for r in result['aggregations']if r['type']=='simple');g=next(r for r in result['aggregations']if r['type']=='group'and r['key']=='overall');summary=dict(nativeRows=result['nativeRows'],modelRows=result['modelRows'],entities=result['entities'],postCells=len(post),simple=s['estimate'],group=g['estimate'],TWFE=result['twfe']['beta'],balancedEntities=result['twfe']['balancedEntities'])\r\n  for i,r in enumerate(post):emit('g'+str(r['g'])+':t'+str(r['t']),i+1,r['estimate'])\r\n out.mkdir(parents=True,exist_ok=True)\r\n if any(out.iterdir()):raise ValueError('use-new-empty-output-directory')\r\n shown={k:v9(v)for k,v in summary.items()};write(out/'summary.csv',[dict(name=k,value=v)for k,v in shown.items()]);write(out/'points.csv',points,['series','x','y','numericY']);full=dict(chapter='METR-20',profile=spec['id'],api=api,input=spec['input'],summary=shown,points=encode(points),details=encode(result),arithmetic='Python Fraction exact finite stored values;summary/plot approximate;bounded teaching projection,not causal or sampling certification')\r\n (out/'full.json').write_text(json.dumps(full,ensure_ascii=False,indent=2,allow_nan=False)+'\\n',encoding='utf8')\r\n import matplotlib\r\n matplotlib.use('Agg')\r\n import matplotlib.pyplot as plt\r\n plt.rcParams.update({'svg.fonttype':'none','font.family':'DejaVu Sans','font.size':12,'axes.spines.top':False,'axes.spines.right':False});fig,ax=plt.subplots(figsize=(9,5.6));good=[r for r in points if r['numericY']is not None]\r\n if good:\r\n  ax.scatter([r['x']for r in good],[r['numericY']for r in good],color='#315d7c',s=32);ax.axhline(0,color='#9eabb2',lw=.8);ax.set_xlabel('Declared cell/unit/bound ordinal')\r\n else:ax.text(.5,.5,'Undefined: no supported plotted quantity',ha='center',va='center',transform=ax.transAxes);ax.set_xticks([]);ax.set_yticks([])\r\n ax.set_ylabel('Cell weight'if api=='twfe'else result.get('unit','Stated outcome/bias units'));ax.set_title(spec['title']['en'],wrap=True,pad=14);ax.grid(axis='y',alpha=.2);fig.tight_layout(pad=2);fig.savefig(out/'plot.svg');plt.close(fig);print(json.dumps(shown))\r\n\r\nSPEC={'id': 'att-never-reference', 'api': 'att', 'title': {'ko': '고정 기준과 사후 셀의 전체 구분', 'en': 'Universal baseline, reference and post cells'}, 'input': {'rows': [{'id': 'early:0', 'entity': 'early', 'time': 0, 'y': '0', 'g': 1}, {'id': 'early:1', 'entity': 'early', 'time': 1, 'y': '1', 'g': 1}, {'id': 'early:2', 'entity': 'early', 'time': 2, 'y': '1', 'g': 1}, {'id': 'early:3', 'entity': 'early', 'time': 3, 'y': '20', 'g': 1}, {'id': 'late:0', 'entity': 'late', 'time': 0, 'y': '0', 'g': 3}, {'id': 'late:1', 'entity': 'late', 'time': 1, 'y': '0', 'g': 3}, {'id': 'late:2', 'entity': 'late', 'time': 2, 'y': '0', 'g': 3}, {'id': 'late:3', 'entity': 'late', 'time': 3, 'y': '1', 'g': 3}, {'id': 'never:0', 'entity': 'never', 'time': 0, 'y': '0', 'g': None}, {'id': 'never:1', 'entity': 'never', 'time': 1, 'y': '0', 'g': None}, {'id': 'never:2', 'entity': 'never', 'time': 2, 'y': '0', 'g': None}, {'id': 'never:3', 'entity': 'never', 'time': 3, 'y': '0', 'g': None}], 'control': 'never'}, 'expectedReject': False}\r\nif __name__=='__main__':\r\n import sys\r\n run_fixed(SPEC,Path(sys.argv[1]),Path(sys.argv[2])if len(sys.argv)>2 else Path(__file__).resolve().parent.parent/'metr20-sources')\r\n",
      "arithmetic": "Python Fraction exact stored finite values;logs/summary/plots approximate",
      "summary": {
        "sourceRows": "12",
        "entities": "3",
        "cells": "8",
        "supportedCells": "8",
        "postCells": "4"
      },
      "fullResultEmbedded": false,
      "plotEmbedded": false,
      "full": {
        "summary": {
          "sourceRows": "12",
          "entities": "3",
          "cells": "8",
          "supportedCells": "8",
          "postCells": "4"
        },
        "notice": "Complete source/finite projection is retained in the linked external JSON; this short projection is not the full result."
      },
      "plot": null,
      "points": [
        {
          "series": "g1:t0",
          "x": 1,
          "y": "0",
          "numericY": 0.0
        },
        {
          "series": "g1:t1",
          "x": 2,
          "y": "1",
          "numericY": 1.0
        },
        {
          "series": "g1:t2",
          "x": 3,
          "y": "1",
          "numericY": 1.0
        },
        {
          "series": "g1:t3",
          "x": 4,
          "y": "20",
          "numericY": 20.0
        },
        {
          "series": "g3:t0",
          "x": 5,
          "y": "0",
          "numericY": 0.0
        },
        {
          "series": "g3:t1",
          "x": 6,
          "y": "0",
          "numericY": 0.0
        },
        {
          "series": "g3:t2",
          "x": 7,
          "y": "0",
          "numericY": 0.0
        },
        {
          "series": "g3:t3",
          "x": 8,
          "y": "1",
          "numericY": 1.0
        }
      ],
      "summaryFile": "metr20-programs/att-never-reference-python-summary.csv",
      "summarySHA256": "2dd996f0887e846a29ffc0f8e0ddccb3b96d7e1a90eadb5c0365d8b2aa84cf93",
      "pointsFile": "metr20-programs/att-never-reference-python-points.csv",
      "pointsSHA256": "378f7c00511065f61fb92cd26e22805732008dae84a75826f9698041405736d2",
      "fullResultFile": "metr20-programs/att-never-reference-python.json",
      "fullResultSHA256": "7d6b313e10859802c686f28e0655d1cd2b328a541ed5f0de494dcb56a528868d",
      "plotFile": "metr20-programs/att-never-reference-python.svg",
      "plotSHA256": "ba0cf15160b1487acbd0080904d0499f41693a2e107588ac1d60d4971222c213"
    },
    {
      "api": "att",
      "variant": "att-never-reference",
      "profile": "att-never-reference",
      "language": "R",
      "file": "metr20-programs/att-never-reference-r.R",
      "codeSHA256": "601535474e5a432af8d0efbd56e5e643538428bde6364ee225fdb1beead1df47",
      "returnCode": 0,
      "expectedRejection": false,
      "title": {
        "ko": "고정 기준과 사후 셀의 전체 구분",
        "en": "Universal baseline, reference and post cells"
      },
      "code": "# METR20 fixed example. Base R only, finite arithmetic approximate.\r\n# No JavaScript engine,model JSON,derived answer table,private module or internet.\r\noptions(stringsAsFactors=FALSE,digits=17)\r\nargv<-commandArgs(trailingOnly=TRUE);if(length(argv)<1L)stop('Supply a new empty output directory')\r\noutdir<-argv[1];script<-sub('^--file=','',commandArgs(FALSE)[grepl('^--file=',commandArgs(FALSE))][1]);here<-dirname(normalizePath(script,mustWork=TRUE));datadir<-if(length(argv)>=2L)argv[2]else file.path(here,'..','metr20-sources')\r\nunits<-c(country='log teen-employment points',person='recorded real earnings',company='FTE employees');clocks<-c(country='calendar year',person='calendar year',company='survey-wave index');steps<-c(country=1,person=3,company=1);files<-c(country='actual2500-county-mpdta-all6-fields.csv',person='actual38408-NSW-all15-fields.csv',company='actual410-NJPA-all46-fields.csv')\r\nnum<-function(s)ifelse(s=='.',NA_real_,as.numeric(s));mean0<-function(v)if(length(v))mean(v)else NA_real_;var0<-function(v)if(length(v)>1L)sum((v-mean(v))^2)/(length(v)-1L)else NA_real_\r\n\r\nSPEC<-list(id=\"att-never-reference\",api=\"att\",title=list(ko=\"고정 기준과 사후 셀의 전체 구분\",en=\"Universal baseline, reference and post cells\"),input=list(rows=list(list(id=\"early:0\",entity=\"early\",time=0,y=\"0\",g=1),list(id=\"early:1\",entity=\"early\",time=1,y=\"1\",g=1),list(id=\"early:2\",entity=\"early\",time=2,y=\"1\",g=1),list(id=\"early:3\",entity=\"early\",time=3,y=\"20\",g=1),list(id=\"late:0\",entity=\"late\",time=0,y=\"0\",g=3),list(id=\"late:1\",entity=\"late\",time=1,y=\"0\",g=3),list(id=\"late:2\",entity=\"late\",time=2,y=\"0\",g=3),list(id=\"late:3\",entity=\"late\",time=3,y=\"1\",g=3),list(id=\"never:0\",entity=\"never\",time=0,y=\"0\",g=NA_real_),list(id=\"never:1\",entity=\"never\",time=1,y=\"0\",g=NA_real_),list(id=\"never:2\",entity=\"never\",time=2,y=\"0\",g=NA_real_),list(id=\"never:3\",entity=\"never\",time=3,y=\"0\",g=NA_real_)),control=\"never\"),expectedReject=FALSE)\r\npanel<-function(rows){G<-list();for(r in rows){key<-r$entity;u<-G[[key]];if(is.null(u))u<-list(g=r$g,rows=list());stopifnot(identical(u$g,r$g),is.null(u$rows[[as.character(r$time)]]));u$rows[[as.character(r$time)]]<-r;G[[key]]<-u};G}\r\ncell<-function(G,g,t,step,control){b<-g-step;members<-list();T<-C<-list();for(key in names(G)){u<-G[[key]];target<-!is.na(u$g)&&u$g==g;comp<-is.na(u$g)||(control=='notyet'&&!is.na(u$g)&&u$g>max(t,b));role<-if(target)'treated'else if(comp)'control'else'excluded-comparison';before<-u$rows[[as.character(b)]];after<-u$rows[[as.character(t)]];yb<-if(is.null(before))NA_real_ else before$y;ya<-if(is.null(after))NA_real_ else after$y;eligible<-role!='excluded-comparison'&&!is.na(yb)&&!is.na(ya);reason<-if(role=='excluded-comparison')'target-or-already-exposed-cohort-not-valid-control'else if(is.null(before))'baseline-source-row-absent'else if(is.null(after))'target-time-source-row-absent'else if(is.na(yb))'baseline-outcome-missing'else if(is.na(ya))'target-outcome-missing'else'';m<-list(entity=key,nativeID=u$rows[[1]]$nativeID,g=u$g,role=role,eligible=eligible,baselineSourceId=if(is.null(before))NA_character_ else before$id,targetSourceId=if(is.null(after))NA_character_ else after$id,before=yb,after=ya,change=if(eligible)ya-yb else NA_real_,reason=reason);members[[key]]<-m;if(eligible){if(role=='treated')T[[length(T)+1L]]<-m else C[[length(C)+1L]]<-m}}\r\n change<-function(a)vapply(a,function(r)r$change,0);d<-mean0(change(T));e<-mean0(change(C));estimate<-if(is.na(d)||is.na(e))NA_real_ else d-e;defined<-!is.na(estimate);scores<-setNames(rep(NA_real_,length(members)),names(members));for(key in names(members)){m<-members[[key]];s<-if(!defined)NA_real_ else if(!m$eligible)0 else if(m$role=='treated')(m$change-d)/length(T)else-(m$change-e)/length(C);m$score<-s;scores[key]<-s;members[[key]]<-m};st<-var0(change(T));sc<-var0(change(C));v<-if(is.na(st)||is.na(sc))NA_real_ else st/length(T)+sc/length(C);level<-function(a,k)mean0(vapply(a,function(r)r[[k]],0))\r\n list(g=g,t=t,baseline=b,event=(t-g)/step,phase=if(t==b)'mechanical-reference'else if(t>=g)'post'else'pre-placebo',defined=defined,estimate=estimate,T=T,C=C,members=members,scores=scores,HC0=if(defined)sum(scores^2)else NA_real_,unbiased=v,treatedMeanBefore=level(T,'before'),treatedMeanAfter=level(T,'after'),treatedMeanChange=d,controlMeanBefore=level(C,'before'),controlMeanAfter=level(C,'after'),controlMeanChange=e)\r\n}\r\ncovariance<-function(cells){n<-length(cells);V<-matrix(NA_real_,n,n);for(i in seq_len(n))for(j in seq_len(n))if(cells[[i]]$defined&&cells[[j]]$defined)V[i,j]<-sum(cells[[i]]$scores*cells[[j]]$scores);V}\r\naggregate_cells<-function(post,V,step){out<-list();push<-function(typ,key,ii,w){est<-if(!length(ii)||any(vapply(post[ii],function(z)is.na(z$estimate),TRUE)))NA_real_ else sum(w*vapply(post[ii],function(z)z$estimate,0));vv<-if(is.na(est)||anyNA(V[ii,ii,drop=FALSE]))NA_real_ else as.numeric(t(w)%*%V[ii,ii,drop=FALSE]%*%w);out[[length(out)+1L]]<<-list(type=typ,key=as.character(key),ii=ii,w=w,estimate=est,variance=vv)};positive<-which(vapply(post,function(c)length(c$T)>0L,TRUE));mass<-sum(vapply(post[positive],function(c)length(c$T),0));push('simple','overall',positive,if(mass)vapply(post[positive],function(c)length(c$T)/mass,0)else numeric())\r\n for(typ in c('event','calendar','group')){keys<-vapply(post,function(c)if(typ=='event')c$event else if(typ=='calendar')c$t else c$g,0);gg<-sort(unique(keys));cohortmass<-if(typ=='group')sum(vapply(gg,function(k)length(post[[which(keys==k)[1]]]$T),0))else 0;allii<-integer();allw<-numeric();for(key in gg){ii<-which(keys==key);jj<-ii[vapply(post[ii],function(c)length(c$T)>0L,TRUE)];if(typ=='group'){stopifnot(length(unique(vapply(post[ii],function(c)length(c$T),0)))<=1L);w<-if(length(jj))rep(1/length(jj),length(jj))else numeric();if(cohortmass){allii<-c(allii,jj);allw<-c(allw,w*length(post[[ii[1]]]$T)/cohortmass)}}else{total<-sum(vapply(post[jj],function(c)length(c$T),0));w<-if(total)vapply(post[jj],function(c)length(c$T)/total,0)else numeric()};push(typ,key,jj,w)};if(typ=='group')push(typ,'overall',allii,allw)};out}\r\ntwfe<-function(G,times){ledger<-list();good<-list();for(key in names(G)){u<-G[[key]];absent<-times[!as.character(times)%in%names(u$rows)];missing<-times[vapply(times,function(t){r<-u$rows[[as.character(t)]];!is.null(r)&&is.na(r$y)},TRUE)];eligible<-length(times)>0L&&!length(absent)&&!length(missing);ledger[[length(ledger)+1L]]<-list(entity=key,g=u$g,nativeID=u$rows[[1]]$nativeID,eligible=eligible,absentTimes=paste(absent,collapse=','),missingOutcomeTimes=paste(missing,collapse=','),originalRows=length(u$rows));if(eligible)good[[key]]<-u};rows<-list();for(key in names(good))for(t in times){r<-good[[key]]$rows[[as.character(t)]];r$D<-as.integer(!is.na(r$g)&&t>=r$g);rows[[length(rows)+1L]]<-r};em<-lapply(good,function(u)list(D=mean(vapply(times,function(t)as.integer(!is.na(u$g)&&t>=u$g),0)),Y=mean(vapply(u$rows[as.character(times)],function(r)r$y,0))));tm<-lapply(times,function(t)list(D=mean(vapply(good,function(u)as.integer(!is.na(u$g)&&t>=u$g),0)),Y=mean(vapply(good,function(u)u$rows[[as.character(t)]]$y,0))));names(tm)<-as.character(times);gd<-mean0(vapply(rows,function(r)r$D,0));gy<-mean0(vapply(rows,function(r)r$y,0));num<-den<-0\r\n for(i in seq_along(rows)){r<-rows[[i]];r$residualD<-r$D-em[[r$entity]]$D-tm[[as.character(r$time)]]$D+gd;r$residualY<-r$y-em[[r$entity]]$Y-tm[[as.character(r$time)]]$Y+gy;num<-num+r$residualD*r$residualY;den<-den+r$residualD^2;rows[[i]]<-r};beta<-if(den!=0)num/den else NA_real_;weights<-list();for(i in seq_along(rows)){r<-rows[[i]];r$projectionCoefficient<-if(den!=0)r$residualD/den else NA_real_;r$regressionResidual<-if(!is.na(beta))r$residualY-beta*r$residualD else NA_real_;rows[[i]]<-r;if(r$D==1L){k<-paste(r$g,r$time,sep=':');z<-weights[[k]];if(is.null(z))z<-list(g=r$g,t=r$time,rows=0,coefficient=if(den!=0)0 else NA_real_);z$rows<-z$rows+1L;if(den!=0)z$coefficient<-z$coefficient+r$projectionCoefficient;weights[[k]]<-z}};list(ledger=ledger,rows=rows,num=num,den=den,beta=beta,weights=weights,balancedEntities=length(good))}\r\nadjacent_pre<-function(G,g,t,step,control){b<-t-step;T<-C<-numeric();for(u in G){target<-!is.na(u$g)&&u$g==g;comp<-is.na(u$g)||(control=='notyet'&&!is.na(u$g)&&u$g>max(t,b));if(!target&&!comp)next;before<-u$rows[[as.character(b)]];after<-u$rows[[as.character(t)]];if(!is.null(before)&&!is.null(after)&&!is.na(before$y)&&!is.na(after$y)){if(target)T<-c(T,after$y-before$y)else C<-c(C,after$y-before$y)}};if(!length(T)||!length(C))NA_real_ else mean(T)-mean(C)}\r\n\r\n# Newly authored bounded teaching projections; base R finite approximation.\r\n# Source helper functions are inlined in each public file, never imported.\r\nqnum<-function(v){if(is.null(v)||is.na(v))return(NA_real_);s<-strsplit(as.character(v),'/',fixed=TRUE)[[1]];if(length(s)==1L)as.numeric(s)else as.numeric(s[1])/as.numeric(s[2])}\r\npaired<-function(T,C){\r\n stats<-function(rr){use<-Filter(function(r)!is.na(qnum(r$before))&&!is.na(qnum(r$after)),rr);a<-vapply(use,function(r)qnum(r$before),0);b<-vapply(use,function(r)qnum(r$after),0);list(sourcePairs=length(rr),eligiblePairs=length(use),excludedPairs=length(rr)-length(use),meanBefore=mean0(a),meanAfter=mean0(b),meanChange=mean0(b-a),sampleChangeVariance=var0(b-a))}\r\n st<-stats(T);sc<-stats(C);defined<-st$eligiblePairs>0L&&sc$eligiblePairs>0L;estimate<-if(defined)st$meanChange-sc$meanChange else NA_real_;rr<-list()\r\n for(role in c('treated','control')){input<-if(role=='treated')T else C;s<-if(role=='treated')st else sc;for(r in input){before<-qnum(r$before);after<-qnum(r$after);eligible<-!is.na(before)&&!is.na(after);change<-if(eligible)after-before else NA_real_;score<-if(!defined)NA_real_ else if(!eligible)0 else (change-s$meanChange)/(if(role=='treated')s$eligiblePairs else -s$eligiblePairs);rr[[length(rr)+1L]]<-list(id=r$id,role=role,before=before,after=after,eligible=eligible,change=change,score=score)}}\r\n list(defined=defined,estimate=estimate,treated=st,control=sc,unbiasedVariance=if(defined&&st$eligiblePairs>=2L&&sc$eligiblePairs>=2L)st$sampleChangeVariance/st$eligiblePairs+sc$sampleChangeVariance/sc$eligiblePairs else NA_real_,HC0=if(defined)sum(vapply(rr,function(r)r$score^2,0))else NA_real_,rows=rr)\r\n}\r\nliteral_panel<-function(rr)lapply(seq_along(rr),function(i){r<-rr[[i]];r$y<-qnum(r$y);r$nativeID<-r$entity;r$sourceRow<-i;r})\r\natt_projection<-function(rows,control='never',step=1){G<-panel(rows);times<-sort(unique(vapply(rows,function(r)r$time,0)));cohorts<-sort(unique(na.omit(vapply(rows,function(r)r$g,0))));cells<-list();for(g in cohorts)for(t in times)cells[[length(cells)+1L]]<-cell(G,g,t,step,control);list(sourceRows=length(rows),sourceEntities=length(G),step=step,control=control,cells=cells,covariance=covariance(cells))}\r\nlinear_aggregate<-function(a){\r\n rr<-lapply(a$cells,function(r){r$estimate<-qnum(r$estimate);r$weight<-qnum(r$weight);r});V<-if(is.null(a$covariance))NULL else do.call(rbind,lapply(a$covariance,function(r)vapply(r,qnum,0)));rank<-NA_real_\r\n if(!is.null(V)){stopifnot(nrow(V)==length(rr),ncol(V)==length(rr),all(V==t(V)));ev<-eigen(V,symmetric=TRUE,only.values=TRUE)$values;if(any(ev< -1e-12))stop('covariance-must-be-positive-semidefinite');rank<-sum(ev>1e-12)}\r\n selected<-which(vapply(rr,function(r)r$time>=r$cohort&&r$weight>0,TRUE));w<-numeric(length(rr));type<-if(is.null(a$type))'simple'else a$type\r\n if(type=='simple'){mass<-sum(vapply(rr[selected],function(r)r$weight,0));if(mass>0)for(i in selected)w[i]<-rr[[i]]$weight/mass}else{g<-vapply(rr,function(r)r$cohort,0);gg<-sort(unique(g[selected]));mass<-sum(vapply(gg,function(gi)rr[[intersect(which(g==gi),selected)[1]]]$weight,0));for(gi in gg){ii<-intersect(which(g==gi),selected);stopifnot(length(unique(vapply(rr[ii],function(r)r$weight,0)))==1L);w[ii]<-rr[[ii[1]]]$weight/mass/length(ii)}}\r\n used<-which(w>0);estimate<-if(!length(used)||any(vapply(rr[used],function(r)is.na(r$estimate),TRUE)))NA_real_ else sum(w[used]*vapply(rr[used],function(r)r$estimate,0));variance<-if(is.na(estimate)||is.null(V))NA_real_ else as.numeric(t(w)%*%V%*%w);weights<-lapply(used,function(i)list(sourceIndex=i-1L,cohort=rr[[i]]$cohort,time=rr[[i]]$time,coefficient=w[i],estimate=rr[[i]]$estimate,contribution=w[i]*rr[[i]]$estimate))\r\n list(type=type,defined=!is.na(estimate),estimate=estimate,variance=variance,covarianceRank=rank,weights=weights,cells=rr,covariance=V)\r\n}\r\nsensitivity_fixed<-function(a){estimate<-qnum(a$estimate);M<-qnum(a$M);h<-if(is.null(a$horizon))1 else a$horizon;stopifnot(M>=0,h>=1);pre<-vapply(a$preDifferences,qnum,0);scale<-if(!is.null(a$scale))qnum(a$scale)else if(length(pre))max(abs(pre))else NA_real_;budget<-M*scale*h;list(defined=!is.na(scale),estimate=estimate,scale=scale,M=M,horizon=h,biasBudget=budget,lower=estimate-budget,upper=estimate+budget,preDifferences=as.list(pre),confidenceLevel=NULL)}\r\nrealdata_fixed<-function(kind){rows<-models[[kind]];G<-panel(rows);times<-sort(unique(vapply(rows,function(r)r$time,0)));step<-unname(steps[kind]);aa<-att_projection(rows,'never',step);post<-Filter(function(r)r$phase=='post',aa$cells);aggs<-aggregate_cells(post,covariance(post),step);tf<-twfe(G,times);list(kind=kind,unit=unname(units[kind]),periodUnit=unname(clocks[kind]),nativeRows=nrow(raw[[kind]]),modelRows=length(rows),entities=length(G),sourceRows=rows,att=aa,aggregations=aggs,twfe=tf,scope='Complete native/model/paired/balanced source frames; never control,universal base,no anticipation;not causal/sampling certification.')}\r\n# JSON encoder deliberately handles matrices and scalar/vector distinctions.\r\nencode<-function(x){\r\n if(is.null(x))return('null')\r\n quote<-function(s){s<-gsub('\\\\','\\\\\\\\',as.character(s),fixed=TRUE);s<-gsub('\"','\\\\\"',s,fixed=TRUE);s<-gsub('\\n','\\\\n',s,fixed=TRUE);s<-gsub('\\r','\\\\r',s,fixed=TRUE);s<-gsub('\\t','\\\\t',s,fixed=TRUE);paste0('\"',s,'\"')}\r\n if(is.matrix(x))return(paste0('[',paste(vapply(seq_len(nrow(x)),function(i)encode(as.list(unname(x[i,]))),''),collapse=','),']'))\r\n if(is.list(x)){if(length(x)&&!is.null(names(x)))return(paste0('{',paste(paste0(vapply(names(x),quote,''),':',vapply(x,encode,'')),collapse=','),'}'));return(paste0('[',paste(vapply(x,encode,''),collapse=','),']'))}\r\n if(length(x)!=1L)return(encode(as.list(unname(x))))\r\n if(is.na(x))return('null');if(is.logical(x))return(if(x)'true'else'false');if(is.numeric(x))return(sprintf('%.17g',unname(x)));quote(x)\r\n}\r\nv9<-function(x){if(is.null(x)||is.na(x))return('undefined');if(is.logical(x))return(if(x)'1'else'0');if(is.numeric(x))return(sprintf('%.9g',unname(x)));as.character(x)}\r\nrun_fixed<-function(spec,out){api<-spec$api;a<-spec$input;summary<-list();points<-list();emit<-function(series,x,y){points[[length(points)+1L]]<<-list(series=series,x=x,y=y,numericY=y)}\r\n if(api=='twobytwo'){result<-paired(a$treated,a$control);summary<-list(defined=result$defined,estimate=result$estimate,treatedPairs=result$treated$eligiblePairs,controlPairs=result$control$eligiblePairs,unbiasedVariance=result$unbiasedVariance,HC0=result$HC0);for(i in seq_along(result$rows)){r<-result$rows[[i]];emit(paste(r$role,r$id,sep=':'),i,r$change)}}\r\n else if(api=='att'){result<-att_projection(literal_panel(a$rows),a$control);summary<-list(sourceRows=result$sourceRows,entities=result$sourceEntities,cells=length(result$cells),supportedCells=sum(vapply(result$cells,function(r)r$defined,TRUE)),postCells=sum(vapply(result$cells,function(r)r$phase=='post',TRUE)));for(i in seq_along(result$cells)){r<-result$cells[[i]];emit(paste0('g',r$g,':t',r$t),i,r$estimate)}}\r\n else if(api=='aggregate'){result<-linear_aggregate(a);summary<-list(defined=result$defined,estimate=result$estimate,variance=result$variance,covarianceRank=result$covarianceRank,sumWeights=sum(vapply(result$weights,function(r)r$coefficient,0)));for(i in seq_along(result$weights)){r<-result$weights[[i]];emit(paste0('g',r$cohort,':t',r$time),i,r$contribution)}}\r\n else if(api=='twfe'){rows<-literal_panel(a$rows);G<-panel(rows);result<-twfe(G,sort(unique(vapply(rows,function(r)r$time,0))));summary<-list(defined=!is.na(result$beta),beta=result$beta,numerator=result$num,denominator=result$den,balancedEntities=result$balancedEntities,negativeTreatedCells=sum(vapply(result$weights,function(r)!is.na(r$coefficient)&&r$coefficient<0,TRUE)));if(length(result$weights)){ord<-order(vapply(result$weights,function(r)r$g,0),vapply(result$weights,function(r)r$t,0));for(i in seq_along(ord)){r<-result$weights[[ord[i]]];emit(paste0('g',r$g,':t',r$t),i,r$coefficient)}}}\r\n else if(api=='sensitivity'){result<-sensitivity_fixed(a);summary<-result[c('defined','estimate','scale','M','horizon','biasBudget','lower','upper')];for(i in seq_along(c('lower','estimate','upper'))){k<-c('lower','estimate','upper')[i];emit(k,i,if(result$defined)result[[k]]else NA_real_)}}\r\n else{result<-realdata_fixed(a$kind);post<-Filter(function(r)r$phase=='post',result$att$cells);simple<-Filter(function(r)r$type=='simple',result$aggregations)[[1]];group<-Filter(function(r)r$type=='group'&&r$key=='overall',result$aggregations)[[1]];summary<-list(nativeRows=result$nativeRows,modelRows=result$modelRows,entities=result$entities,postCells=length(post),simple=simple$estimate,group=group$estimate,TWFE=result$twfe$beta,balancedEntities=result$twfe$balancedEntities);for(i in seq_along(post)){r<-post[[i]];emit(paste0('g',r$g,':t',r$t),i,r$estimate)}}\r\n dir.create(out,recursive=TRUE,showWarnings=FALSE);if(length(list.files(out,all.files=TRUE,no..=TRUE)))stop('use-new-empty-output-directory');shown<-lapply(summary,v9);write.csv(data.frame(name=names(shown),value=unlist(shown,use.names=FALSE)),file.path(out,'summary.csv'),row.names=FALSE,na='');pointframe<-if(length(points))do.call(rbind,lapply(points,function(p)data.frame(series=p$series,x=p$x,y=p$y,numericY=p$numericY,stringsAsFactors=FALSE)))else data.frame(series=character(),x=numeric(),y=numeric(),numericY=numeric());write.csv(pointframe,file.path(out,'points.csv'),row.names=FALSE,na='');full<-list(chapter='METR-20',profile=spec$id,api=api,input=spec$input,summary=shown,points=points,details=result,arithmetic='Base R approximate finite values;bounded teaching projection,not exact fractions or causal/sampling certification.');writeLines(encode(full),file.path(out,'full.json'),useBytes=TRUE)\r\n svg(file.path(out,'plot.svg'),width=9,height=5.6,pointsize=12);par(mar=c(4.5,5.5,4,1));good<-pointframe[!is.na(pointframe$numericY),,drop=FALSE]\r\n if(nrow(good)){plot(good$x,good$numericY,pch=19,col='#315d7c',xlab='Declared cell/unit/bound ordinal',ylab=if(api=='twfe')'Cell weight'else if(!is.null(result$unit))result$unit else 'Stated outcome/bias units',main=spec$title$en);abline(h=0,col='#9eabb2');grid(nx=NA,ny=NULL,col='#e2e5e7');points(good$x,good$numericY,pch=19,col='#315d7c')}else{plot.new();text(.5,.5,'Undefined: no supported plotted quantity');title(main=spec$title$en)};dev.off();cat(encode(shown),'\\n')\r\n}\r\n\r\nrun_fixed(SPEC,outdir)\r\n",
      "arithmetic": "Base R approximate finite arithmetic;not an exact rational result",
      "summary": {
        "sourceRows": "12",
        "entities": "3",
        "cells": "8",
        "supportedCells": "8",
        "postCells": "4"
      },
      "fullResultEmbedded": false,
      "plotEmbedded": false,
      "full": {
        "summary": {
          "sourceRows": "12",
          "entities": "3",
          "cells": "8",
          "supportedCells": "8",
          "postCells": "4"
        },
        "notice": "Complete source/finite projection is retained in the linked external JSON; this short projection is not the full result."
      },
      "plot": null,
      "points": [
        {
          "series": "g1:t0",
          "x": 1,
          "y": 0,
          "numericY": 0
        },
        {
          "series": "g1:t1",
          "x": 2,
          "y": 1,
          "numericY": 1
        },
        {
          "series": "g1:t2",
          "x": 3,
          "y": 1,
          "numericY": 1
        },
        {
          "series": "g1:t3",
          "x": 4,
          "y": 20,
          "numericY": 20
        },
        {
          "series": "g3:t0",
          "x": 5,
          "y": 0,
          "numericY": 0
        },
        {
          "series": "g3:t1",
          "x": 6,
          "y": 0,
          "numericY": 0
        },
        {
          "series": "g3:t2",
          "x": 7,
          "y": 0,
          "numericY": 0
        },
        {
          "series": "g3:t3",
          "x": 8,
          "y": 1,
          "numericY": 1
        }
      ],
      "summaryFile": "metr20-programs/att-never-reference-r-summary.csv",
      "summarySHA256": "1106bf5176bd738900d444bdfc28f9bfa24a6a8504e11652cca360cd7e5c354b",
      "pointsFile": "metr20-programs/att-never-reference-r-points.csv",
      "pointsSHA256": "2415556f88e88cff77eba641de970028557f5953e67cd80ef4a882e4329f47c8",
      "fullResultFile": "metr20-programs/att-never-reference-r.json",
      "fullResultSHA256": "0dff5093315b22f084f4b06c8690e77c63ffd547766df41a29892ed3eee07a10",
      "plotFile": "metr20-programs/att-never-reference-r.svg",
      "plotSHA256": "e2dc82b75c8ccb7077fd31486699bccb698d33664e428634e2a8665632a58fc0"
    },
    {
      "api": "att",
      "variant": "att-notyet-missing",
      "profile": "att-notyet-missing",
      "language": "Python",
      "file": "metr20-programs/att-notyet-missing-python.py",
      "codeSHA256": "cf15677153775a48b4033058240f137fa5d097d47c6a4a8cebb318ce2a2a5513",
      "returnCode": 0,
      "expectedRejection": false,
      "title": {
        "ko": "미도입 비교와 빠진 같은 개체",
        "en": "Not-yet comparisons and missing paired outcomes"
      },
      "code": "\"\"\"METR20 actual sources. Python standard library, exact stored-value rationals.\r\nRead ONLY the three native-observation CSVs; no JS engine,model JSON,derived\r\nanswers,private modules or internet needed. Outcome measurement/identification\r\nand valid sampling inference remain separate from exact finite arithmetic.\r\nRun: python metr20-reproduce.py --data-dir PATH --out NEW_EMPTY_DIRECTORY\r\n\"\"\"\r\nfrom pathlib import Path\r\nfrom fractions import Fraction as Q\r\nfrom collections import defaultdict,Counter\r\nimport csv,json,math,argparse,hashlib\r\n\r\nUNIT={'country':'log teen-employment points','person':'recorded real earnings','company':'FTE employees'}\r\nCLOCK={'country':'calendar year','person':'calendar year','company':'survey-wave index'}\r\nSTEP={'country':1,'person':3,'company':1}\r\nFILES={'country':'actual2500-county-mpdta-all6-fields.csv','person':'actual38408-NSW-all15-fields.csv','company':'actual410-NJPA-all46-fields.csv'}\r\ndef avg(v):return sum(v,Q(0))/len(v)if v else None\r\ndef samplevar(v):return sum(((x-avg(v))**2 for x in v),Q(0))/(len(v)-1)if len(v)>1 else None\r\ndef binary(s):return None if s=='.'else Q.from_float(float(s))\r\ndef token(v):\r\n if v is None:return ''\r\n if isinstance(v,bool):return 'true'if v else'false'\r\n return str(v)\r\ndef safe_float(v):\r\n if v is None:return None\r\n try:r=float(v)\r\n except OverflowError:return None\r\n return r if math.isfinite(r)else None\r\ndef read(p):\r\n with p.open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))\r\ndef write(p,rows,head=None):\r\n if head is None:\r\n  assert rows;head=list(rows[0])\r\n with p.open('w',encoding='utf8',newline='')as f:\r\n  w=csv.DictWriter(f,fieldnames=head);w.writeheader();w.writerows({k:token(r.get(k))for k in head}for r in rows)\r\ndef source(data):\r\n raw={k:read(data/n)for k,n in FILES.items()};assert[len(raw[k])for k in FILES]==[2500,38408,410]\r\n models={k:[]for k in FILES}\r\n for r in raw['country']:\r\n  g0=int(r['first.treat']);g=None if g0==0 else g0;assert int(r['treat'])==int(g is not None)\r\n  models['country'].append(dict(id='mpdta:'+r['sourceRow'],entity='county:'+str(int(r['countyreal'])),time=int(r['year']),y=binary(r['lemp']),g=g,sourceRow=int(r['sourceRow']),nativeID=r['countyreal']))\r\n for r in raw['person']:\r\n  selected=int(r['experimental'])==1;assert selected==(int(r['sample'])==1);assert(r['treated']!='.')==selected\r\n  if selected:\r\n   d=int(r['treated']);assert d in[0,1]\r\n   models['person'].append(dict(id='nsw:'+r['sourceRow'],entity='nsw-id:'+str(int(r['id'])),time=int(r['year']),y=binary(r['re']),g=1978 if d else None,sourceRow=int(r['sourceRow']),nativeID=str(int(r['id']))))\r\n for r in raw['company']:\r\n  state=int(r['STATE']);assert state in[0,1]\r\n  for t,suffix in[(0,''),(1,'2')]:\r\n   a=[r[n+suffix]for n in['EMPFT','NMGRS','EMPPT']];y=None if'.'in a else Q(a[0])+Q(a[1])+Q(a[2])/2\r\n   models['company'].append(dict(id='njpa:'+r['sourceRow']+':wave'+str(t),entity='njpa-row:'+r['sourceRow'],time=t,y=y,g=1 if state else None,sourceRow=int(r['sourceRow']),nativeID=r['SHEET']))\r\n assert[len(models[k])for k in FILES]==[2500,1444,820]\r\n return models,raw\r\ndef panel(rows):\r\n groups={}\r\n for r in rows:\r\n  u=groups.setdefault(r['entity'],{'g':r['g'],'rows':{}});assert u['g']==r['g']and r['time']not in u['rows'];u['rows'][r['time']]=r\r\n return groups\r\ndef cell(groups,g,t,step,control):\r\n b=g-step;members=[];T=[];C=[]\r\n for key,u in groups.items():\r\n  role='treated'if u['g']==g else'control'if u['g']is None or(control=='notyet'and u['g']>max(t,b))else'excluded-comparison'\r\n  before=u['rows'].get(b);after=u['rows'].get(t);yb=None if before is None else before['y'];ya=None if after is None else after['y'];eligible=role!='excluded-comparison'and yb is not None and ya is not None\r\n  reason='target-or-already-exposed-cohort-not-valid-control'if role=='excluded-comparison'else'baseline-source-row-absent'if before is None else'target-time-source-row-absent'if after is None else'baseline-outcome-missing'if yb is None else'target-outcome-missing'if ya is None else''\r\n  m={'entity':key,'nativeID':next(iter(u['rows'].values()))['nativeID'],'g':u['g'],'role':role,'eligible':eligible,'baselineSourceId':None if before is None else before['id'],'targetSourceId':None if after is None else after['id'],'before':yb,'after':ya,'change':ya-yb if eligible else None,'reason':reason};members.append(m)\r\n  if eligible:(T if role=='treated'else C).append(m)\r\n d=avg([r['change']for r in T]);e=avg([r['change']for r in C]);estimate=None if d is None or e is None else d-e;defined=estimate is not None;scores={}\r\n for m in members:\r\n  s=None if not defined else Q(0)\r\n  if defined and m['eligible']:s=(m['change']-(d if m['role']=='treated'else e))/(len(T)if m['role']=='treated'else-len(C))\r\n  m['score']=s;scores[m['entity']]=s\r\n st=samplevar([r['change']for r in T]);sc=samplevar([r['change']for r in C]);v=None if st is None or sc is None else st/len(T)+sc/len(C)\r\n return {'g':g,'t':t,'baseline':b,'event':(t-g)//step,'phase':'mechanical-reference'if t==b else'post'if t>=g else'pre-placebo','defined':defined,'estimate':estimate,'T':T,'C':C,'members':members,'scores':scores,'HC0':None if not defined else sum((s*s for s in scores.values()),Q(0)),'unbiased':v,'treatedMeanBefore':avg([r['before']for r in T]),'treatedMeanAfter':avg([r['after']for r in T]),'treatedMeanChange':d,'controlMeanBefore':avg([r['before']for r in C]),'controlMeanAfter':avg([r['after']for r in C]),'controlMeanChange':e}\r\ndef covariance(cells):\r\n return[[None if not a['defined']or not b['defined']else sum((v*b['scores'][i]for i,v in a['scores'].items()),Q(0))for b in cells]for a in cells]\r\ndef aggregate(post,V,step):\r\n out=[]\r\n def push(typ,key,coeff):\r\n  estimate=None if not coeff or any(post[i]['estimate']is None for i in coeff)else sum((w*post[i]['estimate']for i,w in coeff.items()),Q(0));variance=None if estimate is None or any(V[i][j]is None for i in coeff for j in coeff)else sum((a*b*V[i][j]for i,a in coeff.items()for j,b in coeff.items()),Q(0));out.append({'type':typ,'key':key,'coeff':coeff,'estimate':estimate,'variance':variance})\r\n positive=[i for i,c in enumerate(post)if len(c['T'])>0];mass=sum(len(post[i]['T'])for i in positive)\r\n push('simple','overall',{i:Q(len(post[i]['T']),mass)for i in positive}if mass else{})\r\n for typ in['event','calendar','group']:\r\n  groups=defaultdict(list)\r\n  for i,c in enumerate(post):groups[c['event']if typ=='event'else c['t']if typ=='calendar'else c['g']].append(i)\r\n  overall={};cohortMass=sum(len(post[ii[0]]['T'])for ii in groups.values())if typ=='group'else 0\r\n  for key,ii in sorted(groups.items()):\r\n   jj=[i for i in ii if len(post[i]['T'])>0]\r\n   if typ=='group':\r\n    assert len({len(post[i]['T'])for i in ii})<=1\r\n    coeff={i:Q(1,len(jj))for i in jj}if jj else{}\r\n    if cohortMass:\r\n     for i,w in coeff.items():overall[i]=w*Q(len(post[ii[0]]['T']),cohortMass)\r\n   else:\r\n    total=sum(len(post[i]['T'])for i in jj);coeff={i:Q(len(post[i]['T']),total)for i in jj}if total else{}\r\n   push(typ,str(key),coeff)\r\n  if typ=='group':push(typ,'overall',overall)\r\n return out\r\ndef twfe(groups,times):\r\n ledger=[];good={}\r\n for key,u in groups.items():\r\n  absent=[t for t in times if t not in u['rows']];missing=[t for t in times if t in u['rows']and u['rows'][t]['y']is None];eligible=bool(times)and not absent and not missing\r\n  ledger.append({'entity':key,'g':u['g'],'nativeID':next(iter(u['rows'].values()))['nativeID'],'eligible':eligible,'absentTimes':','.join(map(str,absent)),'missingOutcomeTimes':','.join(map(str,missing)),'originalRows':len(u['rows'])})\r\n  if eligible:good[key]=u\r\n rows=[dict(**u['rows'][t],D=Q(u['g']is not None and t>=u['g']))for key,u in good.items()for t in times]\r\n em={k:{'D':avg([Q(u['g']is not None and t>=u['g'])for t in times]),'Y':avg([u['rows'][t]['y']for t in times])}for k,u in good.items()};tm={t:{'D':avg([Q(u['g']is not None and t>=u['g'])for u in good.values()]),'Y':avg([u['rows'][t]['y']for u in good.values()])}for t in times};gd=avg([r['D']for r in rows]);gy=avg([r['y']for r in rows]);num=den=Q(0)\r\n for r in rows:\r\n  r['residualD']=r['D']-em[r['entity']]['D']-tm[r['time']]['D']+gd;r['residualY']=r['y']-em[r['entity']]['Y']-tm[r['time']]['Y']+gy;num+=r['residualD']*r['residualY'];den+=r['residualD']**2\r\n beta=num/den if den else None;weights={}\r\n for r in rows:\r\n  r['projectionCoefficient']=r['residualD']/den if den else None;r['regressionResidual']=r['residualY']-beta*r['residualD']if beta is not None else None\r\n  if r['D']:\r\n   k=(r['g'],r['time']);z=weights.setdefault(k,{'rows':0,'coefficient':Q(0)if den else None});z['rows']+=1\r\n   if den:z['coefficient']+=r['projectionCoefficient']\r\n return {'ledger':ledger,'rows':rows,'num':num,'den':den,'beta':beta,'weights':weights,'balancedEntities':len(good)}\r\ndef adjacent_pre(groups,g,t,step,control):\r\n b=t-step;T=[];C=[]\r\n for u in groups.values():\r\n  if u['g']==g:target=T\r\n  elif u['g']is None or(control=='notyet'and u['g']>max(t,b)):target=C\r\n  else:continue\r\n  before=u['rows'].get(b);after=u['rows'].get(t)\r\n  if before is not None and after is not None and before['y']is not None and after['y']is not None:target.append(after['y']-before['y'])\r\n return None if not T or not C else avg(T)-avg(C)\r\n\r\n\"\"\"New bounded teaching projections. The program is self-contained after build.\r\nExact Fraction finite algebra; figures and9-digit summary are approximations.\r\nIt is not a general parser/API replacement or a causal/inference certificate.\r\n\"\"\"\r\ndef paired(treated,control):\r\n def stats(rr):\r\n  use=[r for r in rr if r['before']is not None and r['after']is not None];delta=[Q(r['after'])-Q(r['before'])for r in use]\r\n  return dict(sourcePairs=len(rr),eligiblePairs=len(use),excludedPairs=len(rr)-len(use),meanBefore=avg([Q(r['before'])for r in use]),meanAfter=avg([Q(r['after'])for r in use]),meanChange=avg(delta),sampleChangeVariance=samplevar(delta))\r\n T,C=stats(treated),stats(control);defined=T['eligiblePairs']>0 and C['eligiblePairs']>0;estimate=T['meanChange']-C['meanChange']if defined else None;records=[]\r\n for group,rr,s in [('treated',treated,T),('control',control,C)]:\r\n  for r in rr:\r\n   before=None if r['before']is None else Q(r['before']);after=None if r['after']is None else Q(r['after']);eligible=before is not None and after is not None;delta=after-before if eligible else None;score=None if not defined else Q(0)if not eligible else(delta-s['meanChange'])/(s['eligiblePairs']if group=='treated'else-s['eligiblePairs']);records.append(dict(id=r['id'],role=group,before=before,after=after,eligible=eligible,change=delta,score=score))\r\n unbiased=None if not defined or T['eligiblePairs']<2 or C['eligiblePairs']<2 else T['sampleChangeVariance']/T['eligiblePairs']+C['sampleChangeVariance']/C['eligiblePairs'];hc0=None if not defined else sum((r['score']**2 for r in records),Q(0))\r\n return dict(defined=defined,estimate=estimate,treated=T,control=C,unbiasedVariance=unbiased,HC0=hc0,rows=records)\r\ndef literal_panel(raw):\r\n return[dict(r,y=None if r['y']is None else Q(r['y']),nativeID=r['entity'],sourceRow=i+1)for i,r in enumerate(raw)]\r\ndef att_projection(rows,control='never',step=1):\r\n G=panel(rows);times=sorted({r['time']for r in rows});cohorts=sorted({r['g']for r in rows if r['g']is not None});cells=[cell(G,g,t,step,control)for g in cohorts for t in times]\r\n return dict(sourceRows=len(rows),sourceEntities=len(G),step=step,control=control,cells=cells,covariance=covariance(cells))\r\ndef psd(V):\r\n A=[r[:]for r in V];rank=0\r\n while A:\r\n  if any(A[i][i]<0 for i in range(len(A))):raise ValueError('covariance-must-be-positive-semidefinite')\r\n  p=next((i for i in range(len(A))if A[i][i]>0),None)\r\n  if p is None:\r\n   if any(v for r in A for v in r):raise ValueError('covariance-must-be-positive-semidefinite')\r\n   return rank\r\n  A[0],A[p]=A[p],A[0]\r\n  for r in A:r[0],r[p]=r[p],r[0]\r\n  d=A[0][0];A=[[A[i][j]-A[i][0]*A[0][j]/d for j in range(1,len(A))]for i in range(1,len(A))];rank+=1\r\n return rank\r\ndef linear_aggregate(a):\r\n rr=[dict(r,estimate=None if r['estimate']is None else Q(r['estimate']),weight=Q(r['weight']))for r in a['cells']];V=[[Q(v)for v in r]for r in a['covariance']]if 'covariance'in a else None\r\n if V is not None:\r\n  assert len(V)==len(rr)and all(len(z)==len(rr)for z in V);assert all(V[i][j]==V[j][i]for i in range(len(rr))for j in range(len(rr)));rank=psd(V)\r\n else:rank=None\r\n selected=[i for i,r in enumerate(rr)if r['time']>=r['cohort']and r['weight']>0];weights={}\r\n if a.get('type','simple')=='simple':\r\n  mass=sum((rr[i]['weight']for i in selected),Q(0));weights={i:rr[i]['weight']/mass for i in selected}if mass else{}\r\n else:\r\n  gg=defaultdict(list)\r\n  for i in selected:gg[rr[i]['cohort']].append(i)\r\n  assert all(len({rr[i]['weight']for i in ii})==1 for ii in gg.values());mass=sum((rr[ii[0]]['weight']for ii in gg.values()),Q(0));weights={i:rr[ii[0]]['weight']/mass/len(ii)for ii in gg.values()for i in ii}if mass else{}\r\n estimate=None if not weights or any(rr[i]['estimate']is None for i in weights)else sum((w*rr[i]['estimate']for i,w in weights.items()),Q(0));variance=None if estimate is None or V is None else sum((x*y*V[i][j]for i,x in weights.items()for j,y in weights.items()),Q(0))\r\n return dict(type=a.get('type','simple'),defined=estimate is not None,estimate=estimate,variance=variance,covarianceRank=rank,weights=[dict(sourceIndex=i,cohort=rr[i]['cohort'],time=rr[i]['time'],coefficient=w,estimate=rr[i]['estimate'],contribution=None if rr[i]['estimate']is None else w*rr[i]['estimate'])for i,w in weights.items()],cells=rr,covariance=V)\r\ndef sensitivity_fixed(a):\r\n estimate=Q(a['estimate']);M=Q(a['M']);h=a.get('horizon',1);assert M>=0 and h>=1\r\n pre=[Q(v)for v in a.get('preDifferences',[])];scale=Q(a['scale'])if 'scale'in a else max(map(abs,pre))if pre else None;budget=None if scale is None else M*scale*h\r\n return dict(defined=scale is not None,estimate=estimate,scale=scale,M=M,horizon=h,biasBudget=budget,lower=None if budget is None else estimate-budget,upper=None if budget is None else estimate+budget,preDifferences=pre,confidenceLevel=None)\r\ndef realdata_fixed(kind,data):\r\n models,raw=source(data);rows=models[kind];G=panel(rows);times=sorted({r['time']for r in rows});step=STEP[kind];aa=att_projection(rows,'never',step);post=[r for r in aa['cells']if r['phase']=='post'];aggs=aggregate(post,covariance(post),step);tf=twfe(G,times)\r\n return dict(kind=kind,unit=UNIT[kind],periodUnit=CLOCK[kind],nativeRows=len(raw[kind]),modelRows=len(rows),entities=len(G),sourceRows=rows,att=aa,aggregations=aggs,twfe=tf,scope='Complete source frame; never-treated comparison,universal baseline,no anticipation. Native/model/paired/balanced denominators differ. All sampling/causal assumptions remain separate.')\r\ndef encode(v):\r\n if isinstance(v,Q):return str(v)\r\n if isinstance(v,dict):return{str(k):encode(x)for k,x in v.items()}\r\n if isinstance(v,(list,tuple)):return[encode(x)for x in v]\r\n return v\r\ndef v9(v):\r\n if v is None:return'undefined'\r\n if isinstance(v,str):return v\r\n if isinstance(v,bool):return'1'if v else'0'\r\n return format(float(v),'.9g')\r\ndef run_fixed(spec,out,data):\r\n api=spec['api'];a=spec['input'];summary={};points=[]\r\n def emit(series,x,y):points.append(dict(series=series,x=x,y=y,numericY=safe_float(y)))\r\n if api=='twobytwo':\r\n  result=paired(a['treated'],a['control']);summary=dict(defined=result['defined'],estimate=result['estimate'],treatedPairs=result['treated']['eligiblePairs'],controlPairs=result['control']['eligiblePairs'],unbiasedVariance=result['unbiasedVariance'],HC0=result['HC0'])\r\n  for i,r in enumerate(result['rows']):emit(r['role']+':'+r['id'],i+1,r['change'])\r\n elif api=='att':\r\n  result=att_projection(literal_panel(a['rows']),a.get('control','never'));summary=dict(sourceRows=result['sourceRows'],entities=result['sourceEntities'],cells=len(result['cells']),supportedCells=sum(r['defined']for r in result['cells']),postCells=sum(r['phase']=='post'for r in result['cells']))\r\n  for i,r in enumerate(result['cells']):emit('g'+str(r['g'])+':t'+str(r['t']),i+1,r['estimate'])\r\n elif api=='aggregate':\r\n  result=linear_aggregate(a);summary=dict(defined=result['defined'],estimate=result['estimate'],variance=result['variance'],covarianceRank=result['covarianceRank'],sumWeights=sum((r['coefficient']for r in result['weights']),Q(0)))\r\n  for i,r in enumerate(result['weights']):emit('g'+str(r['cohort'])+':t'+str(r['time']),i+1,r['contribution'])\r\n elif api=='twfe':\r\n  rows=literal_panel(a['rows']);G=panel(rows);result=twfe(G,sorted({r['time']for r in rows}));summary=dict(defined=result['beta']is not None,beta=result['beta'],numerator=result['num'],denominator=result['den'],balancedEntities=result['balancedEntities'],negativeTreatedCells=sum(v['coefficient']is not None and v['coefficient']<0 for v in result['weights'].values()))\r\n  for i,((g,t),r)in enumerate(sorted(result['weights'].items())):emit('g'+str(g)+':t'+str(t),i+1,r['coefficient'])\r\n elif api=='sensitivity':\r\n  result=sensitivity_fixed(a);summary={k:result[k]for k in['defined','estimate','scale','M','horizon','biasBudget','lower','upper']}\r\n  for i,k in enumerate(['lower','estimate','upper']):emit(k,i+1,result[k]if result['defined']else None)\r\n else:\r\n  result=realdata_fixed(a['kind'],data);post=[r for r in result['att']['cells']if r['phase']=='post'];s=next(r for r in result['aggregations']if r['type']=='simple');g=next(r for r in result['aggregations']if r['type']=='group'and r['key']=='overall');summary=dict(nativeRows=result['nativeRows'],modelRows=result['modelRows'],entities=result['entities'],postCells=len(post),simple=s['estimate'],group=g['estimate'],TWFE=result['twfe']['beta'],balancedEntities=result['twfe']['balancedEntities'])\r\n  for i,r in enumerate(post):emit('g'+str(r['g'])+':t'+str(r['t']),i+1,r['estimate'])\r\n out.mkdir(parents=True,exist_ok=True)\r\n if any(out.iterdir()):raise ValueError('use-new-empty-output-directory')\r\n shown={k:v9(v)for k,v in summary.items()};write(out/'summary.csv',[dict(name=k,value=v)for k,v in shown.items()]);write(out/'points.csv',points,['series','x','y','numericY']);full=dict(chapter='METR-20',profile=spec['id'],api=api,input=spec['input'],summary=shown,points=encode(points),details=encode(result),arithmetic='Python Fraction exact finite stored values;summary/plot approximate;bounded teaching projection,not causal or sampling certification')\r\n (out/'full.json').write_text(json.dumps(full,ensure_ascii=False,indent=2,allow_nan=False)+'\\n',encoding='utf8')\r\n import matplotlib\r\n matplotlib.use('Agg')\r\n import matplotlib.pyplot as plt\r\n plt.rcParams.update({'svg.fonttype':'none','font.family':'DejaVu Sans','font.size':12,'axes.spines.top':False,'axes.spines.right':False});fig,ax=plt.subplots(figsize=(9,5.6));good=[r for r in points if r['numericY']is not None]\r\n if good:\r\n  ax.scatter([r['x']for r in good],[r['numericY']for r in good],color='#315d7c',s=32);ax.axhline(0,color='#9eabb2',lw=.8);ax.set_xlabel('Declared cell/unit/bound ordinal')\r\n else:ax.text(.5,.5,'Undefined: no supported plotted quantity',ha='center',va='center',transform=ax.transAxes);ax.set_xticks([]);ax.set_yticks([])\r\n ax.set_ylabel('Cell weight'if api=='twfe'else result.get('unit','Stated outcome/bias units'));ax.set_title(spec['title']['en'],wrap=True,pad=14);ax.grid(axis='y',alpha=.2);fig.tight_layout(pad=2);fig.savefig(out/'plot.svg');plt.close(fig);print(json.dumps(shown))\r\n\r\nSPEC={'id': 'att-notyet-missing', 'api': 'att', 'title': {'ko': '미도입 비교와 빠진 같은 개체', 'en': 'Not-yet comparisons and missing paired outcomes'}, 'input': {'rows': [{'id': 'early:0', 'entity': 'early', 'time': 0, 'y': '0', 'g': 1}, {'id': 'early:1', 'entity': 'early', 'time': 1, 'y': '2', 'g': 1}, {'id': 'early:2', 'entity': 'early', 'time': 2, 'y': '5', 'g': 1}, {'id': 'early:3', 'entity': 'early', 'time': 3, 'y': '8', 'g': 1}, {'id': 'late:0', 'entity': 'late', 'time': 0, 'y': '0', 'g': 3}, {'id': 'late:1', 'entity': 'late', 'time': 1, 'y': None, 'g': 3}, {'id': 'late:2', 'entity': 'late', 'time': 2, 'y': '0', 'g': 3}, {'id': 'late:3', 'entity': 'late', 'time': 3, 'y': '2', 'g': 3}, {'id': 'never:0', 'entity': 'never', 'time': 0, 'y': '0', 'g': None}, {'id': 'never:1', 'entity': 'never', 'time': 1, 'y': '0', 'g': None}, {'id': 'never:2', 'entity': 'never', 'time': 2, 'y': '0', 'g': None}, {'id': 'never:3', 'entity': 'never', 'time': 3, 'y': '0', 'g': None}], 'control': 'notyet'}, 'expectedReject': False}\r\nif __name__=='__main__':\r\n import sys\r\n run_fixed(SPEC,Path(sys.argv[1]),Path(sys.argv[2])if len(sys.argv)>2 else Path(__file__).resolve().parent.parent/'metr20-sources')\r\n",
      "arithmetic": "Python Fraction exact stored finite values;logs/summary/plots approximate",
      "summary": {
        "sourceRows": "12",
        "entities": "3",
        "cells": "8",
        "supportedCells": "7",
        "postCells": "4"
      },
      "fullResultEmbedded": false,
      "plotEmbedded": false,
      "full": {
        "summary": {
          "sourceRows": "12",
          "entities": "3",
          "cells": "8",
          "supportedCells": "7",
          "postCells": "4"
        },
        "notice": "Complete source/finite projection is retained in the linked external JSON; this short projection is not the full result."
      },
      "plot": null,
      "points": [
        {
          "series": "g1:t0",
          "x": 1,
          "y": "0",
          "numericY": 0.0
        },
        {
          "series": "g1:t1",
          "x": 2,
          "y": "2",
          "numericY": 2.0
        },
        {
          "series": "g1:t2",
          "x": 3,
          "y": "5",
          "numericY": 5.0
        },
        {
          "series": "g1:t3",
          "x": 4,
          "y": "8",
          "numericY": 8.0
        },
        {
          "series": "g3:t0",
          "x": 5,
          "y": "0",
          "numericY": 0.0
        },
        {
          "series": "g3:t1",
          "x": 6,
          "y": null,
          "numericY": null
        },
        {
          "series": "g3:t2",
          "x": 7,
          "y": "0",
          "numericY": 0.0
        },
        {
          "series": "g3:t3",
          "x": 8,
          "y": "2",
          "numericY": 2.0
        }
      ],
      "summaryFile": "metr20-programs/att-notyet-missing-python-summary.csv",
      "summarySHA256": "dbc6f9c0ac438c0cf6adf2152a63296c7d568de4273f73a9678bd3c1dc9864db",
      "pointsFile": "metr20-programs/att-notyet-missing-python-points.csv",
      "pointsSHA256": "3627a527674e158c54a1aa4891f08466a3aadbf5e7b7cf9cdf06bdad8ebebc39",
      "fullResultFile": "metr20-programs/att-notyet-missing-python.json",
      "fullResultSHA256": "2a2aaafa97ebac3a3e842bd09a2ab0281a50843bb468bef36abc97581035d4e0",
      "plotFile": "metr20-programs/att-notyet-missing-python.svg",
      "plotSHA256": "9727fc23fa0bdcdff1e96c595934f358a7c320cb6fe16a133f193d8041ae30e6"
    },
    {
      "api": "att",
      "variant": "att-notyet-missing",
      "profile": "att-notyet-missing",
      "language": "R",
      "file": "metr20-programs/att-notyet-missing-r.R",
      "codeSHA256": "ec6e48a5536256671101cf4ec15029a8d9889264ab5f03215615e4976e17a120",
      "returnCode": 0,
      "expectedRejection": false,
      "title": {
        "ko": "미도입 비교와 빠진 같은 개체",
        "en": "Not-yet comparisons and missing paired outcomes"
      },
      "code": "# METR20 fixed example. Base R only, finite arithmetic approximate.\r\n# No JavaScript engine,model JSON,derived answer table,private module or internet.\r\noptions(stringsAsFactors=FALSE,digits=17)\r\nargv<-commandArgs(trailingOnly=TRUE);if(length(argv)<1L)stop('Supply a new empty output directory')\r\noutdir<-argv[1];script<-sub('^--file=','',commandArgs(FALSE)[grepl('^--file=',commandArgs(FALSE))][1]);here<-dirname(normalizePath(script,mustWork=TRUE));datadir<-if(length(argv)>=2L)argv[2]else file.path(here,'..','metr20-sources')\r\nunits<-c(country='log teen-employment points',person='recorded real earnings',company='FTE employees');clocks<-c(country='calendar year',person='calendar year',company='survey-wave index');steps<-c(country=1,person=3,company=1);files<-c(country='actual2500-county-mpdta-all6-fields.csv',person='actual38408-NSW-all15-fields.csv',company='actual410-NJPA-all46-fields.csv')\r\nnum<-function(s)ifelse(s=='.',NA_real_,as.numeric(s));mean0<-function(v)if(length(v))mean(v)else NA_real_;var0<-function(v)if(length(v)>1L)sum((v-mean(v))^2)/(length(v)-1L)else NA_real_\r\n\r\nSPEC<-list(id=\"att-notyet-missing\",api=\"att\",title=list(ko=\"미도입 비교와 빠진 같은 개체\",en=\"Not-yet comparisons and missing paired outcomes\"),input=list(rows=list(list(id=\"early:0\",entity=\"early\",time=0,y=\"0\",g=1),list(id=\"early:1\",entity=\"early\",time=1,y=\"2\",g=1),list(id=\"early:2\",entity=\"early\",time=2,y=\"5\",g=1),list(id=\"early:3\",entity=\"early\",time=3,y=\"8\",g=1),list(id=\"late:0\",entity=\"late\",time=0,y=\"0\",g=3),list(id=\"late:1\",entity=\"late\",time=1,y=NA_real_,g=3),list(id=\"late:2\",entity=\"late\",time=2,y=\"0\",g=3),list(id=\"late:3\",entity=\"late\",time=3,y=\"2\",g=3),list(id=\"never:0\",entity=\"never\",time=0,y=\"0\",g=NA_real_),list(id=\"never:1\",entity=\"never\",time=1,y=\"0\",g=NA_real_),list(id=\"never:2\",entity=\"never\",time=2,y=\"0\",g=NA_real_),list(id=\"never:3\",entity=\"never\",time=3,y=\"0\",g=NA_real_)),control=\"notyet\"),expectedReject=FALSE)\r\npanel<-function(rows){G<-list();for(r in rows){key<-r$entity;u<-G[[key]];if(is.null(u))u<-list(g=r$g,rows=list());stopifnot(identical(u$g,r$g),is.null(u$rows[[as.character(r$time)]]));u$rows[[as.character(r$time)]]<-r;G[[key]]<-u};G}\r\ncell<-function(G,g,t,step,control){b<-g-step;members<-list();T<-C<-list();for(key in names(G)){u<-G[[key]];target<-!is.na(u$g)&&u$g==g;comp<-is.na(u$g)||(control=='notyet'&&!is.na(u$g)&&u$g>max(t,b));role<-if(target)'treated'else if(comp)'control'else'excluded-comparison';before<-u$rows[[as.character(b)]];after<-u$rows[[as.character(t)]];yb<-if(is.null(before))NA_real_ else before$y;ya<-if(is.null(after))NA_real_ else after$y;eligible<-role!='excluded-comparison'&&!is.na(yb)&&!is.na(ya);reason<-if(role=='excluded-comparison')'target-or-already-exposed-cohort-not-valid-control'else if(is.null(before))'baseline-source-row-absent'else if(is.null(after))'target-time-source-row-absent'else if(is.na(yb))'baseline-outcome-missing'else if(is.na(ya))'target-outcome-missing'else'';m<-list(entity=key,nativeID=u$rows[[1]]$nativeID,g=u$g,role=role,eligible=eligible,baselineSourceId=if(is.null(before))NA_character_ else before$id,targetSourceId=if(is.null(after))NA_character_ else after$id,before=yb,after=ya,change=if(eligible)ya-yb else NA_real_,reason=reason);members[[key]]<-m;if(eligible){if(role=='treated')T[[length(T)+1L]]<-m else C[[length(C)+1L]]<-m}}\r\n change<-function(a)vapply(a,function(r)r$change,0);d<-mean0(change(T));e<-mean0(change(C));estimate<-if(is.na(d)||is.na(e))NA_real_ else d-e;defined<-!is.na(estimate);scores<-setNames(rep(NA_real_,length(members)),names(members));for(key in names(members)){m<-members[[key]];s<-if(!defined)NA_real_ else if(!m$eligible)0 else if(m$role=='treated')(m$change-d)/length(T)else-(m$change-e)/length(C);m$score<-s;scores[key]<-s;members[[key]]<-m};st<-var0(change(T));sc<-var0(change(C));v<-if(is.na(st)||is.na(sc))NA_real_ else st/length(T)+sc/length(C);level<-function(a,k)mean0(vapply(a,function(r)r[[k]],0))\r\n list(g=g,t=t,baseline=b,event=(t-g)/step,phase=if(t==b)'mechanical-reference'else if(t>=g)'post'else'pre-placebo',defined=defined,estimate=estimate,T=T,C=C,members=members,scores=scores,HC0=if(defined)sum(scores^2)else NA_real_,unbiased=v,treatedMeanBefore=level(T,'before'),treatedMeanAfter=level(T,'after'),treatedMeanChange=d,controlMeanBefore=level(C,'before'),controlMeanAfter=level(C,'after'),controlMeanChange=e)\r\n}\r\ncovariance<-function(cells){n<-length(cells);V<-matrix(NA_real_,n,n);for(i in seq_len(n))for(j in seq_len(n))if(cells[[i]]$defined&&cells[[j]]$defined)V[i,j]<-sum(cells[[i]]$scores*cells[[j]]$scores);V}\r\naggregate_cells<-function(post,V,step){out<-list();push<-function(typ,key,ii,w){est<-if(!length(ii)||any(vapply(post[ii],function(z)is.na(z$estimate),TRUE)))NA_real_ else sum(w*vapply(post[ii],function(z)z$estimate,0));vv<-if(is.na(est)||anyNA(V[ii,ii,drop=FALSE]))NA_real_ else as.numeric(t(w)%*%V[ii,ii,drop=FALSE]%*%w);out[[length(out)+1L]]<<-list(type=typ,key=as.character(key),ii=ii,w=w,estimate=est,variance=vv)};positive<-which(vapply(post,function(c)length(c$T)>0L,TRUE));mass<-sum(vapply(post[positive],function(c)length(c$T),0));push('simple','overall',positive,if(mass)vapply(post[positive],function(c)length(c$T)/mass,0)else numeric())\r\n for(typ in c('event','calendar','group')){keys<-vapply(post,function(c)if(typ=='event')c$event else if(typ=='calendar')c$t else c$g,0);gg<-sort(unique(keys));cohortmass<-if(typ=='group')sum(vapply(gg,function(k)length(post[[which(keys==k)[1]]]$T),0))else 0;allii<-integer();allw<-numeric();for(key in gg){ii<-which(keys==key);jj<-ii[vapply(post[ii],function(c)length(c$T)>0L,TRUE)];if(typ=='group'){stopifnot(length(unique(vapply(post[ii],function(c)length(c$T),0)))<=1L);w<-if(length(jj))rep(1/length(jj),length(jj))else numeric();if(cohortmass){allii<-c(allii,jj);allw<-c(allw,w*length(post[[ii[1]]]$T)/cohortmass)}}else{total<-sum(vapply(post[jj],function(c)length(c$T),0));w<-if(total)vapply(post[jj],function(c)length(c$T)/total,0)else numeric()};push(typ,key,jj,w)};if(typ=='group')push(typ,'overall',allii,allw)};out}\r\ntwfe<-function(G,times){ledger<-list();good<-list();for(key in names(G)){u<-G[[key]];absent<-times[!as.character(times)%in%names(u$rows)];missing<-times[vapply(times,function(t){r<-u$rows[[as.character(t)]];!is.null(r)&&is.na(r$y)},TRUE)];eligible<-length(times)>0L&&!length(absent)&&!length(missing);ledger[[length(ledger)+1L]]<-list(entity=key,g=u$g,nativeID=u$rows[[1]]$nativeID,eligible=eligible,absentTimes=paste(absent,collapse=','),missingOutcomeTimes=paste(missing,collapse=','),originalRows=length(u$rows));if(eligible)good[[key]]<-u};rows<-list();for(key in names(good))for(t in times){r<-good[[key]]$rows[[as.character(t)]];r$D<-as.integer(!is.na(r$g)&&t>=r$g);rows[[length(rows)+1L]]<-r};em<-lapply(good,function(u)list(D=mean(vapply(times,function(t)as.integer(!is.na(u$g)&&t>=u$g),0)),Y=mean(vapply(u$rows[as.character(times)],function(r)r$y,0))));tm<-lapply(times,function(t)list(D=mean(vapply(good,function(u)as.integer(!is.na(u$g)&&t>=u$g),0)),Y=mean(vapply(good,function(u)u$rows[[as.character(t)]]$y,0))));names(tm)<-as.character(times);gd<-mean0(vapply(rows,function(r)r$D,0));gy<-mean0(vapply(rows,function(r)r$y,0));num<-den<-0\r\n for(i in seq_along(rows)){r<-rows[[i]];r$residualD<-r$D-em[[r$entity]]$D-tm[[as.character(r$time)]]$D+gd;r$residualY<-r$y-em[[r$entity]]$Y-tm[[as.character(r$time)]]$Y+gy;num<-num+r$residualD*r$residualY;den<-den+r$residualD^2;rows[[i]]<-r};beta<-if(den!=0)num/den else NA_real_;weights<-list();for(i in seq_along(rows)){r<-rows[[i]];r$projectionCoefficient<-if(den!=0)r$residualD/den else NA_real_;r$regressionResidual<-if(!is.na(beta))r$residualY-beta*r$residualD else NA_real_;rows[[i]]<-r;if(r$D==1L){k<-paste(r$g,r$time,sep=':');z<-weights[[k]];if(is.null(z))z<-list(g=r$g,t=r$time,rows=0,coefficient=if(den!=0)0 else NA_real_);z$rows<-z$rows+1L;if(den!=0)z$coefficient<-z$coefficient+r$projectionCoefficient;weights[[k]]<-z}};list(ledger=ledger,rows=rows,num=num,den=den,beta=beta,weights=weights,balancedEntities=length(good))}\r\nadjacent_pre<-function(G,g,t,step,control){b<-t-step;T<-C<-numeric();for(u in G){target<-!is.na(u$g)&&u$g==g;comp<-is.na(u$g)||(control=='notyet'&&!is.na(u$g)&&u$g>max(t,b));if(!target&&!comp)next;before<-u$rows[[as.character(b)]];after<-u$rows[[as.character(t)]];if(!is.null(before)&&!is.null(after)&&!is.na(before$y)&&!is.na(after$y)){if(target)T<-c(T,after$y-before$y)else C<-c(C,after$y-before$y)}};if(!length(T)||!length(C))NA_real_ else mean(T)-mean(C)}\r\n\r\n# Newly authored bounded teaching projections; base R finite approximation.\r\n# Source helper functions are inlined in each public file, never imported.\r\nqnum<-function(v){if(is.null(v)||is.na(v))return(NA_real_);s<-strsplit(as.character(v),'/',fixed=TRUE)[[1]];if(length(s)==1L)as.numeric(s)else as.numeric(s[1])/as.numeric(s[2])}\r\npaired<-function(T,C){\r\n stats<-function(rr){use<-Filter(function(r)!is.na(qnum(r$before))&&!is.na(qnum(r$after)),rr);a<-vapply(use,function(r)qnum(r$before),0);b<-vapply(use,function(r)qnum(r$after),0);list(sourcePairs=length(rr),eligiblePairs=length(use),excludedPairs=length(rr)-length(use),meanBefore=mean0(a),meanAfter=mean0(b),meanChange=mean0(b-a),sampleChangeVariance=var0(b-a))}\r\n st<-stats(T);sc<-stats(C);defined<-st$eligiblePairs>0L&&sc$eligiblePairs>0L;estimate<-if(defined)st$meanChange-sc$meanChange else NA_real_;rr<-list()\r\n for(role in c('treated','control')){input<-if(role=='treated')T else C;s<-if(role=='treated')st else sc;for(r in input){before<-qnum(r$before);after<-qnum(r$after);eligible<-!is.na(before)&&!is.na(after);change<-if(eligible)after-before else NA_real_;score<-if(!defined)NA_real_ else if(!eligible)0 else (change-s$meanChange)/(if(role=='treated')s$eligiblePairs else -s$eligiblePairs);rr[[length(rr)+1L]]<-list(id=r$id,role=role,before=before,after=after,eligible=eligible,change=change,score=score)}}\r\n list(defined=defined,estimate=estimate,treated=st,control=sc,unbiasedVariance=if(defined&&st$eligiblePairs>=2L&&sc$eligiblePairs>=2L)st$sampleChangeVariance/st$eligiblePairs+sc$sampleChangeVariance/sc$eligiblePairs else NA_real_,HC0=if(defined)sum(vapply(rr,function(r)r$score^2,0))else NA_real_,rows=rr)\r\n}\r\nliteral_panel<-function(rr)lapply(seq_along(rr),function(i){r<-rr[[i]];r$y<-qnum(r$y);r$nativeID<-r$entity;r$sourceRow<-i;r})\r\natt_projection<-function(rows,control='never',step=1){G<-panel(rows);times<-sort(unique(vapply(rows,function(r)r$time,0)));cohorts<-sort(unique(na.omit(vapply(rows,function(r)r$g,0))));cells<-list();for(g in cohorts)for(t in times)cells[[length(cells)+1L]]<-cell(G,g,t,step,control);list(sourceRows=length(rows),sourceEntities=length(G),step=step,control=control,cells=cells,covariance=covariance(cells))}\r\nlinear_aggregate<-function(a){\r\n rr<-lapply(a$cells,function(r){r$estimate<-qnum(r$estimate);r$weight<-qnum(r$weight);r});V<-if(is.null(a$covariance))NULL else do.call(rbind,lapply(a$covariance,function(r)vapply(r,qnum,0)));rank<-NA_real_\r\n if(!is.null(V)){stopifnot(nrow(V)==length(rr),ncol(V)==length(rr),all(V==t(V)));ev<-eigen(V,symmetric=TRUE,only.values=TRUE)$values;if(any(ev< -1e-12))stop('covariance-must-be-positive-semidefinite');rank<-sum(ev>1e-12)}\r\n selected<-which(vapply(rr,function(r)r$time>=r$cohort&&r$weight>0,TRUE));w<-numeric(length(rr));type<-if(is.null(a$type))'simple'else a$type\r\n if(type=='simple'){mass<-sum(vapply(rr[selected],function(r)r$weight,0));if(mass>0)for(i in selected)w[i]<-rr[[i]]$weight/mass}else{g<-vapply(rr,function(r)r$cohort,0);gg<-sort(unique(g[selected]));mass<-sum(vapply(gg,function(gi)rr[[intersect(which(g==gi),selected)[1]]]$weight,0));for(gi in gg){ii<-intersect(which(g==gi),selected);stopifnot(length(unique(vapply(rr[ii],function(r)r$weight,0)))==1L);w[ii]<-rr[[ii[1]]]$weight/mass/length(ii)}}\r\n used<-which(w>0);estimate<-if(!length(used)||any(vapply(rr[used],function(r)is.na(r$estimate),TRUE)))NA_real_ else sum(w[used]*vapply(rr[used],function(r)r$estimate,0));variance<-if(is.na(estimate)||is.null(V))NA_real_ else as.numeric(t(w)%*%V%*%w);weights<-lapply(used,function(i)list(sourceIndex=i-1L,cohort=rr[[i]]$cohort,time=rr[[i]]$time,coefficient=w[i],estimate=rr[[i]]$estimate,contribution=w[i]*rr[[i]]$estimate))\r\n list(type=type,defined=!is.na(estimate),estimate=estimate,variance=variance,covarianceRank=rank,weights=weights,cells=rr,covariance=V)\r\n}\r\nsensitivity_fixed<-function(a){estimate<-qnum(a$estimate);M<-qnum(a$M);h<-if(is.null(a$horizon))1 else a$horizon;stopifnot(M>=0,h>=1);pre<-vapply(a$preDifferences,qnum,0);scale<-if(!is.null(a$scale))qnum(a$scale)else if(length(pre))max(abs(pre))else NA_real_;budget<-M*scale*h;list(defined=!is.na(scale),estimate=estimate,scale=scale,M=M,horizon=h,biasBudget=budget,lower=estimate-budget,upper=estimate+budget,preDifferences=as.list(pre),confidenceLevel=NULL)}\r\nrealdata_fixed<-function(kind){rows<-models[[kind]];G<-panel(rows);times<-sort(unique(vapply(rows,function(r)r$time,0)));step<-unname(steps[kind]);aa<-att_projection(rows,'never',step);post<-Filter(function(r)r$phase=='post',aa$cells);aggs<-aggregate_cells(post,covariance(post),step);tf<-twfe(G,times);list(kind=kind,unit=unname(units[kind]),periodUnit=unname(clocks[kind]),nativeRows=nrow(raw[[kind]]),modelRows=length(rows),entities=length(G),sourceRows=rows,att=aa,aggregations=aggs,twfe=tf,scope='Complete native/model/paired/balanced source frames; never control,universal base,no anticipation;not causal/sampling certification.')}\r\n# JSON encoder deliberately handles matrices and scalar/vector distinctions.\r\nencode<-function(x){\r\n if(is.null(x))return('null')\r\n quote<-function(s){s<-gsub('\\\\','\\\\\\\\',as.character(s),fixed=TRUE);s<-gsub('\"','\\\\\"',s,fixed=TRUE);s<-gsub('\\n','\\\\n',s,fixed=TRUE);s<-gsub('\\r','\\\\r',s,fixed=TRUE);s<-gsub('\\t','\\\\t',s,fixed=TRUE);paste0('\"',s,'\"')}\r\n if(is.matrix(x))return(paste0('[',paste(vapply(seq_len(nrow(x)),function(i)encode(as.list(unname(x[i,]))),''),collapse=','),']'))\r\n if(is.list(x)){if(length(x)&&!is.null(names(x)))return(paste0('{',paste(paste0(vapply(names(x),quote,''),':',vapply(x,encode,'')),collapse=','),'}'));return(paste0('[',paste(vapply(x,encode,''),collapse=','),']'))}\r\n if(length(x)!=1L)return(encode(as.list(unname(x))))\r\n if(is.na(x))return('null');if(is.logical(x))return(if(x)'true'else'false');if(is.numeric(x))return(sprintf('%.17g',unname(x)));quote(x)\r\n}\r\nv9<-function(x){if(is.null(x)||is.na(x))return('undefined');if(is.logical(x))return(if(x)'1'else'0');if(is.numeric(x))return(sprintf('%.9g',unname(x)));as.character(x)}\r\nrun_fixed<-function(spec,out){api<-spec$api;a<-spec$input;summary<-list();points<-list();emit<-function(series,x,y){points[[length(points)+1L]]<<-list(series=series,x=x,y=y,numericY=y)}\r\n if(api=='twobytwo'){result<-paired(a$treated,a$control);summary<-list(defined=result$defined,estimate=result$estimate,treatedPairs=result$treated$eligiblePairs,controlPairs=result$control$eligiblePairs,unbiasedVariance=result$unbiasedVariance,HC0=result$HC0);for(i in seq_along(result$rows)){r<-result$rows[[i]];emit(paste(r$role,r$id,sep=':'),i,r$change)}}\r\n else if(api=='att'){result<-att_projection(literal_panel(a$rows),a$control);summary<-list(sourceRows=result$sourceRows,entities=result$sourceEntities,cells=length(result$cells),supportedCells=sum(vapply(result$cells,function(r)r$defined,TRUE)),postCells=sum(vapply(result$cells,function(r)r$phase=='post',TRUE)));for(i in seq_along(result$cells)){r<-result$cells[[i]];emit(paste0('g',r$g,':t',r$t),i,r$estimate)}}\r\n else if(api=='aggregate'){result<-linear_aggregate(a);summary<-list(defined=result$defined,estimate=result$estimate,variance=result$variance,covarianceRank=result$covarianceRank,sumWeights=sum(vapply(result$weights,function(r)r$coefficient,0)));for(i in seq_along(result$weights)){r<-result$weights[[i]];emit(paste0('g',r$cohort,':t',r$time),i,r$contribution)}}\r\n else if(api=='twfe'){rows<-literal_panel(a$rows);G<-panel(rows);result<-twfe(G,sort(unique(vapply(rows,function(r)r$time,0))));summary<-list(defined=!is.na(result$beta),beta=result$beta,numerator=result$num,denominator=result$den,balancedEntities=result$balancedEntities,negativeTreatedCells=sum(vapply(result$weights,function(r)!is.na(r$coefficient)&&r$coefficient<0,TRUE)));if(length(result$weights)){ord<-order(vapply(result$weights,function(r)r$g,0),vapply(result$weights,function(r)r$t,0));for(i in seq_along(ord)){r<-result$weights[[ord[i]]];emit(paste0('g',r$g,':t',r$t),i,r$coefficient)}}}\r\n else if(api=='sensitivity'){result<-sensitivity_fixed(a);summary<-result[c('defined','estimate','scale','M','horizon','biasBudget','lower','upper')];for(i in seq_along(c('lower','estimate','upper'))){k<-c('lower','estimate','upper')[i];emit(k,i,if(result$defined)result[[k]]else NA_real_)}}\r\n else{result<-realdata_fixed(a$kind);post<-Filter(function(r)r$phase=='post',result$att$cells);simple<-Filter(function(r)r$type=='simple',result$aggregations)[[1]];group<-Filter(function(r)r$type=='group'&&r$key=='overall',result$aggregations)[[1]];summary<-list(nativeRows=result$nativeRows,modelRows=result$modelRows,entities=result$entities,postCells=length(post),simple=simple$estimate,group=group$estimate,TWFE=result$twfe$beta,balancedEntities=result$twfe$balancedEntities);for(i in seq_along(post)){r<-post[[i]];emit(paste0('g',r$g,':t',r$t),i,r$estimate)}}\r\n dir.create(out,recursive=TRUE,showWarnings=FALSE);if(length(list.files(out,all.files=TRUE,no..=TRUE)))stop('use-new-empty-output-directory');shown<-lapply(summary,v9);write.csv(data.frame(name=names(shown),value=unlist(shown,use.names=FALSE)),file.path(out,'summary.csv'),row.names=FALSE,na='');pointframe<-if(length(points))do.call(rbind,lapply(points,function(p)data.frame(series=p$series,x=p$x,y=p$y,numericY=p$numericY,stringsAsFactors=FALSE)))else data.frame(series=character(),x=numeric(),y=numeric(),numericY=numeric());write.csv(pointframe,file.path(out,'points.csv'),row.names=FALSE,na='');full<-list(chapter='METR-20',profile=spec$id,api=api,input=spec$input,summary=shown,points=points,details=result,arithmetic='Base R approximate finite values;bounded teaching projection,not exact fractions or causal/sampling certification.');writeLines(encode(full),file.path(out,'full.json'),useBytes=TRUE)\r\n svg(file.path(out,'plot.svg'),width=9,height=5.6,pointsize=12);par(mar=c(4.5,5.5,4,1));good<-pointframe[!is.na(pointframe$numericY),,drop=FALSE]\r\n if(nrow(good)){plot(good$x,good$numericY,pch=19,col='#315d7c',xlab='Declared cell/unit/bound ordinal',ylab=if(api=='twfe')'Cell weight'else if(!is.null(result$unit))result$unit else 'Stated outcome/bias units',main=spec$title$en);abline(h=0,col='#9eabb2');grid(nx=NA,ny=NULL,col='#e2e5e7');points(good$x,good$numericY,pch=19,col='#315d7c')}else{plot.new();text(.5,.5,'Undefined: no supported plotted quantity');title(main=spec$title$en)};dev.off();cat(encode(shown),'\\n')\r\n}\r\n\r\nrun_fixed(SPEC,outdir)\r\n",
      "arithmetic": "Base R approximate finite arithmetic;not an exact rational result",
      "summary": {
        "sourceRows": "12",
        "entities": "3",
        "cells": "8",
        "supportedCells": "7",
        "postCells": "4"
      },
      "fullResultEmbedded": false,
      "plotEmbedded": false,
      "full": {
        "summary": {
          "sourceRows": "12",
          "entities": "3",
          "cells": "8",
          "supportedCells": "7",
          "postCells": "4"
        },
        "notice": "Complete source/finite projection is retained in the linked external JSON; this short projection is not the full result."
      },
      "plot": null,
      "points": [
        {
          "series": "g1:t0",
          "x": 1,
          "y": 0,
          "numericY": 0
        },
        {
          "series": "g1:t1",
          "x": 2,
          "y": 2,
          "numericY": 2
        },
        {
          "series": "g1:t2",
          "x": 3,
          "y": 5,
          "numericY": 5
        },
        {
          "series": "g1:t3",
          "x": 4,
          "y": 8,
          "numericY": 8
        },
        {
          "series": "g3:t0",
          "x": 5,
          "y": 0,
          "numericY": 0
        },
        {
          "series": "g3:t1",
          "x": 6,
          "y": null,
          "numericY": null
        },
        {
          "series": "g3:t2",
          "x": 7,
          "y": 0,
          "numericY": 0
        },
        {
          "series": "g3:t3",
          "x": 8,
          "y": 2,
          "numericY": 2
        }
      ],
      "summaryFile": "metr20-programs/att-notyet-missing-r-summary.csv",
      "summarySHA256": "7c3acb70d71fd2520ad8506f7ec0f6c2d996c9d2587017d0f555fb0ff41f72ce",
      "pointsFile": "metr20-programs/att-notyet-missing-r-points.csv",
      "pointsSHA256": "569c789d2f1dc6bee30937c73b29a3a1ebd227d116090649c6d3ef285d5dad34",
      "fullResultFile": "metr20-programs/att-notyet-missing-r.json",
      "fullResultSHA256": "5aa8b5c9833f5f90f23a31b630fd497a372a0a422e14b756199eb423ffde9795",
      "plotFile": "metr20-programs/att-notyet-missing-r.svg",
      "plotSHA256": "dfc0885e82b74be3566f7520445b358f3bde411b784aa0546bbd9ae97f20f3a7"
    },
    {
      "api": "aggregate",
      "variant": "aggregate-cell-weighted",
      "profile": "aggregate-cell-weighted",
      "language": "Python",
      "file": "metr20-programs/aggregate-cell-weighted-python.py",
      "codeSHA256": "8206f3eabca7f11a11cf9c70eac2fe6fc36c8a859683de341bdba1ad1c319c4f",
      "returnCode": 0,
      "expectedRejection": false,
      "title": {
        "ko": "네 사후 셀을 같은 비중으로",
        "en": "Four equally weighted post-treatment cells"
      },
      "code": "\"\"\"METR20 actual sources. Python standard library, exact stored-value rationals.\r\nRead ONLY the three native-observation CSVs; no JS engine,model JSON,derived\r\nanswers,private modules or internet needed. Outcome measurement/identification\r\nand valid sampling inference remain separate from exact finite arithmetic.\r\nRun: python metr20-reproduce.py --data-dir PATH --out NEW_EMPTY_DIRECTORY\r\n\"\"\"\r\nfrom pathlib import Path\r\nfrom fractions import Fraction as Q\r\nfrom collections import defaultdict,Counter\r\nimport csv,json,math,argparse,hashlib\r\n\r\nUNIT={'country':'log teen-employment points','person':'recorded real earnings','company':'FTE employees'}\r\nCLOCK={'country':'calendar year','person':'calendar year','company':'survey-wave index'}\r\nSTEP={'country':1,'person':3,'company':1}\r\nFILES={'country':'actual2500-county-mpdta-all6-fields.csv','person':'actual38408-NSW-all15-fields.csv','company':'actual410-NJPA-all46-fields.csv'}\r\ndef avg(v):return sum(v,Q(0))/len(v)if v else None\r\ndef samplevar(v):return sum(((x-avg(v))**2 for x in v),Q(0))/(len(v)-1)if len(v)>1 else None\r\ndef binary(s):return None if s=='.'else Q.from_float(float(s))\r\ndef token(v):\r\n if v is None:return ''\r\n if isinstance(v,bool):return 'true'if v else'false'\r\n return str(v)\r\ndef safe_float(v):\r\n if v is None:return None\r\n try:r=float(v)\r\n except OverflowError:return None\r\n return r if math.isfinite(r)else None\r\ndef read(p):\r\n with p.open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))\r\ndef write(p,rows,head=None):\r\n if head is None:\r\n  assert rows;head=list(rows[0])\r\n with p.open('w',encoding='utf8',newline='')as f:\r\n  w=csv.DictWriter(f,fieldnames=head);w.writeheader();w.writerows({k:token(r.get(k))for k in head}for r in rows)\r\ndef source(data):\r\n raw={k:read(data/n)for k,n in FILES.items()};assert[len(raw[k])for k in FILES]==[2500,38408,410]\r\n models={k:[]for k in FILES}\r\n for r in raw['country']:\r\n  g0=int(r['first.treat']);g=None if g0==0 else g0;assert int(r['treat'])==int(g is not None)\r\n  models['country'].append(dict(id='mpdta:'+r['sourceRow'],entity='county:'+str(int(r['countyreal'])),time=int(r['year']),y=binary(r['lemp']),g=g,sourceRow=int(r['sourceRow']),nativeID=r['countyreal']))\r\n for r in raw['person']:\r\n  selected=int(r['experimental'])==1;assert selected==(int(r['sample'])==1);assert(r['treated']!='.')==selected\r\n  if selected:\r\n   d=int(r['treated']);assert d in[0,1]\r\n   models['person'].append(dict(id='nsw:'+r['sourceRow'],entity='nsw-id:'+str(int(r['id'])),time=int(r['year']),y=binary(r['re']),g=1978 if d else None,sourceRow=int(r['sourceRow']),nativeID=str(int(r['id']))))\r\n for r in raw['company']:\r\n  state=int(r['STATE']);assert state in[0,1]\r\n  for t,suffix in[(0,''),(1,'2')]:\r\n   a=[r[n+suffix]for n in['EMPFT','NMGRS','EMPPT']];y=None if'.'in a else Q(a[0])+Q(a[1])+Q(a[2])/2\r\n   models['company'].append(dict(id='njpa:'+r['sourceRow']+':wave'+str(t),entity='njpa-row:'+r['sourceRow'],time=t,y=y,g=1 if state else None,sourceRow=int(r['sourceRow']),nativeID=r['SHEET']))\r\n assert[len(models[k])for k in FILES]==[2500,1444,820]\r\n return models,raw\r\ndef panel(rows):\r\n groups={}\r\n for r in rows:\r\n  u=groups.setdefault(r['entity'],{'g':r['g'],'rows':{}});assert u['g']==r['g']and r['time']not in u['rows'];u['rows'][r['time']]=r\r\n return groups\r\ndef cell(groups,g,t,step,control):\r\n b=g-step;members=[];T=[];C=[]\r\n for key,u in groups.items():\r\n  role='treated'if u['g']==g else'control'if u['g']is None or(control=='notyet'and u['g']>max(t,b))else'excluded-comparison'\r\n  before=u['rows'].get(b);after=u['rows'].get(t);yb=None if before is None else before['y'];ya=None if after is None else after['y'];eligible=role!='excluded-comparison'and yb is not None and ya is not None\r\n  reason='target-or-already-exposed-cohort-not-valid-control'if role=='excluded-comparison'else'baseline-source-row-absent'if before is None else'target-time-source-row-absent'if after is None else'baseline-outcome-missing'if yb is None else'target-outcome-missing'if ya is None else''\r\n  m={'entity':key,'nativeID':next(iter(u['rows'].values()))['nativeID'],'g':u['g'],'role':role,'eligible':eligible,'baselineSourceId':None if before is None else before['id'],'targetSourceId':None if after is None else after['id'],'before':yb,'after':ya,'change':ya-yb if eligible else None,'reason':reason};members.append(m)\r\n  if eligible:(T if role=='treated'else C).append(m)\r\n d=avg([r['change']for r in T]);e=avg([r['change']for r in C]);estimate=None if d is None or e is None else d-e;defined=estimate is not None;scores={}\r\n for m in members:\r\n  s=None if not defined else Q(0)\r\n  if defined and m['eligible']:s=(m['change']-(d if m['role']=='treated'else e))/(len(T)if m['role']=='treated'else-len(C))\r\n  m['score']=s;scores[m['entity']]=s\r\n st=samplevar([r['change']for r in T]);sc=samplevar([r['change']for r in C]);v=None if st is None or sc is None else st/len(T)+sc/len(C)\r\n return {'g':g,'t':t,'baseline':b,'event':(t-g)//step,'phase':'mechanical-reference'if t==b else'post'if t>=g else'pre-placebo','defined':defined,'estimate':estimate,'T':T,'C':C,'members':members,'scores':scores,'HC0':None if not defined else sum((s*s for s in scores.values()),Q(0)),'unbiased':v,'treatedMeanBefore':avg([r['before']for r in T]),'treatedMeanAfter':avg([r['after']for r in T]),'treatedMeanChange':d,'controlMeanBefore':avg([r['before']for r in C]),'controlMeanAfter':avg([r['after']for r in C]),'controlMeanChange':e}\r\ndef covariance(cells):\r\n return[[None if not a['defined']or not b['defined']else sum((v*b['scores'][i]for i,v in a['scores'].items()),Q(0))for b in cells]for a in cells]\r\ndef aggregate(post,V,step):\r\n out=[]\r\n def push(typ,key,coeff):\r\n  estimate=None if not coeff or any(post[i]['estimate']is None for i in coeff)else sum((w*post[i]['estimate']for i,w in coeff.items()),Q(0));variance=None if estimate is None or any(V[i][j]is None for i in coeff for j in coeff)else sum((a*b*V[i][j]for i,a in coeff.items()for j,b in coeff.items()),Q(0));out.append({'type':typ,'key':key,'coeff':coeff,'estimate':estimate,'variance':variance})\r\n positive=[i for i,c in enumerate(post)if len(c['T'])>0];mass=sum(len(post[i]['T'])for i in positive)\r\n push('simple','overall',{i:Q(len(post[i]['T']),mass)for i in positive}if mass else{})\r\n for typ in['event','calendar','group']:\r\n  groups=defaultdict(list)\r\n  for i,c in enumerate(post):groups[c['event']if typ=='event'else c['t']if typ=='calendar'else c['g']].append(i)\r\n  overall={};cohortMass=sum(len(post[ii[0]]['T'])for ii in groups.values())if typ=='group'else 0\r\n  for key,ii in sorted(groups.items()):\r\n   jj=[i for i in ii if len(post[i]['T'])>0]\r\n   if typ=='group':\r\n    assert len({len(post[i]['T'])for i in ii})<=1\r\n    coeff={i:Q(1,len(jj))for i in jj}if jj else{}\r\n    if cohortMass:\r\n     for i,w in coeff.items():overall[i]=w*Q(len(post[ii[0]]['T']),cohortMass)\r\n   else:\r\n    total=sum(len(post[i]['T'])for i in jj);coeff={i:Q(len(post[i]['T']),total)for i in jj}if total else{}\r\n   push(typ,str(key),coeff)\r\n  if typ=='group':push(typ,'overall',overall)\r\n return out\r\ndef twfe(groups,times):\r\n ledger=[];good={}\r\n for key,u in groups.items():\r\n  absent=[t for t in times if t not in u['rows']];missing=[t for t in times if t in u['rows']and u['rows'][t]['y']is None];eligible=bool(times)and not absent and not missing\r\n  ledger.append({'entity':key,'g':u['g'],'nativeID':next(iter(u['rows'].values()))['nativeID'],'eligible':eligible,'absentTimes':','.join(map(str,absent)),'missingOutcomeTimes':','.join(map(str,missing)),'originalRows':len(u['rows'])})\r\n  if eligible:good[key]=u\r\n rows=[dict(**u['rows'][t],D=Q(u['g']is not None and t>=u['g']))for key,u in good.items()for t in times]\r\n em={k:{'D':avg([Q(u['g']is not None and t>=u['g'])for t in times]),'Y':avg([u['rows'][t]['y']for t in times])}for k,u in good.items()};tm={t:{'D':avg([Q(u['g']is not None and t>=u['g'])for u in good.values()]),'Y':avg([u['rows'][t]['y']for u in good.values()])}for t in times};gd=avg([r['D']for r in rows]);gy=avg([r['y']for r in rows]);num=den=Q(0)\r\n for r in rows:\r\n  r['residualD']=r['D']-em[r['entity']]['D']-tm[r['time']]['D']+gd;r['residualY']=r['y']-em[r['entity']]['Y']-tm[r['time']]['Y']+gy;num+=r['residualD']*r['residualY'];den+=r['residualD']**2\r\n beta=num/den if den else None;weights={}\r\n for r in rows:\r\n  r['projectionCoefficient']=r['residualD']/den if den else None;r['regressionResidual']=r['residualY']-beta*r['residualD']if beta is not None else None\r\n  if r['D']:\r\n   k=(r['g'],r['time']);z=weights.setdefault(k,{'rows':0,'coefficient':Q(0)if den else None});z['rows']+=1\r\n   if den:z['coefficient']+=r['projectionCoefficient']\r\n return {'ledger':ledger,'rows':rows,'num':num,'den':den,'beta':beta,'weights':weights,'balancedEntities':len(good)}\r\ndef adjacent_pre(groups,g,t,step,control):\r\n b=t-step;T=[];C=[]\r\n for u in groups.values():\r\n  if u['g']==g:target=T\r\n  elif u['g']is None or(control=='notyet'and u['g']>max(t,b)):target=C\r\n  else:continue\r\n  before=u['rows'].get(b);after=u['rows'].get(t)\r\n  if before is not None and after is not None and before['y']is not None and after['y']is not None:target.append(after['y']-before['y'])\r\n return None if not T or not C else avg(T)-avg(C)\r\n\r\n\"\"\"New bounded teaching projections. The program is self-contained after build.\r\nExact Fraction finite algebra; figures and9-digit summary are approximations.\r\nIt is not a general parser/API replacement or a causal/inference certificate.\r\n\"\"\"\r\ndef paired(treated,control):\r\n def stats(rr):\r\n  use=[r for r in rr if r['before']is not None and r['after']is not None];delta=[Q(r['after'])-Q(r['before'])for r in use]\r\n  return dict(sourcePairs=len(rr),eligiblePairs=len(use),excludedPairs=len(rr)-len(use),meanBefore=avg([Q(r['before'])for r in use]),meanAfter=avg([Q(r['after'])for r in use]),meanChange=avg(delta),sampleChangeVariance=samplevar(delta))\r\n T,C=stats(treated),stats(control);defined=T['eligiblePairs']>0 and C['eligiblePairs']>0;estimate=T['meanChange']-C['meanChange']if defined else None;records=[]\r\n for group,rr,s in [('treated',treated,T),('control',control,C)]:\r\n  for r in rr:\r\n   before=None if r['before']is None else Q(r['before']);after=None if r['after']is None else Q(r['after']);eligible=before is not None and after is not None;delta=after-before if eligible else None;score=None if not defined else Q(0)if not eligible else(delta-s['meanChange'])/(s['eligiblePairs']if group=='treated'else-s['eligiblePairs']);records.append(dict(id=r['id'],role=group,before=before,after=after,eligible=eligible,change=delta,score=score))\r\n unbiased=None if not defined or T['eligiblePairs']<2 or C['eligiblePairs']<2 else T['sampleChangeVariance']/T['eligiblePairs']+C['sampleChangeVariance']/C['eligiblePairs'];hc0=None if not defined else sum((r['score']**2 for r in records),Q(0))\r\n return dict(defined=defined,estimate=estimate,treated=T,control=C,unbiasedVariance=unbiased,HC0=hc0,rows=records)\r\ndef literal_panel(raw):\r\n return[dict(r,y=None if r['y']is None else Q(r['y']),nativeID=r['entity'],sourceRow=i+1)for i,r in enumerate(raw)]\r\ndef att_projection(rows,control='never',step=1):\r\n G=panel(rows);times=sorted({r['time']for r in rows});cohorts=sorted({r['g']for r in rows if r['g']is not None});cells=[cell(G,g,t,step,control)for g in cohorts for t in times]\r\n return dict(sourceRows=len(rows),sourceEntities=len(G),step=step,control=control,cells=cells,covariance=covariance(cells))\r\ndef psd(V):\r\n A=[r[:]for r in V];rank=0\r\n while A:\r\n  if any(A[i][i]<0 for i in range(len(A))):raise ValueError('covariance-must-be-positive-semidefinite')\r\n  p=next((i for i in range(len(A))if A[i][i]>0),None)\r\n  if p is None:\r\n   if any(v for r in A for v in r):raise ValueError('covariance-must-be-positive-semidefinite')\r\n   return rank\r\n  A[0],A[p]=A[p],A[0]\r\n  for r in A:r[0],r[p]=r[p],r[0]\r\n  d=A[0][0];A=[[A[i][j]-A[i][0]*A[0][j]/d for j in range(1,len(A))]for i in range(1,len(A))];rank+=1\r\n return rank\r\ndef linear_aggregate(a):\r\n rr=[dict(r,estimate=None if r['estimate']is None else Q(r['estimate']),weight=Q(r['weight']))for r in a['cells']];V=[[Q(v)for v in r]for r in a['covariance']]if 'covariance'in a else None\r\n if V is not None:\r\n  assert len(V)==len(rr)and all(len(z)==len(rr)for z in V);assert all(V[i][j]==V[j][i]for i in range(len(rr))for j in range(len(rr)));rank=psd(V)\r\n else:rank=None\r\n selected=[i for i,r in enumerate(rr)if r['time']>=r['cohort']and r['weight']>0];weights={}\r\n if a.get('type','simple')=='simple':\r\n  mass=sum((rr[i]['weight']for i in selected),Q(0));weights={i:rr[i]['weight']/mass for i in selected}if mass else{}\r\n else:\r\n  gg=defaultdict(list)\r\n  for i in selected:gg[rr[i]['cohort']].append(i)\r\n  assert all(len({rr[i]['weight']for i in ii})==1 for ii in gg.values());mass=sum((rr[ii[0]]['weight']for ii in gg.values()),Q(0));weights={i:rr[ii[0]]['weight']/mass/len(ii)for ii in gg.values()for i in ii}if mass else{}\r\n estimate=None if not weights or any(rr[i]['estimate']is None for i in weights)else sum((w*rr[i]['estimate']for i,w in weights.items()),Q(0));variance=None if estimate is None or V is None else sum((x*y*V[i][j]for i,x in weights.items()for j,y in weights.items()),Q(0))\r\n return dict(type=a.get('type','simple'),defined=estimate is not None,estimate=estimate,variance=variance,covarianceRank=rank,weights=[dict(sourceIndex=i,cohort=rr[i]['cohort'],time=rr[i]['time'],coefficient=w,estimate=rr[i]['estimate'],contribution=None if rr[i]['estimate']is None else w*rr[i]['estimate'])for i,w in weights.items()],cells=rr,covariance=V)\r\ndef sensitivity_fixed(a):\r\n estimate=Q(a['estimate']);M=Q(a['M']);h=a.get('horizon',1);assert M>=0 and h>=1\r\n pre=[Q(v)for v in a.get('preDifferences',[])];scale=Q(a['scale'])if 'scale'in a else max(map(abs,pre))if pre else None;budget=None if scale is None else M*scale*h\r\n return dict(defined=scale is not None,estimate=estimate,scale=scale,M=M,horizon=h,biasBudget=budget,lower=None if budget is None else estimate-budget,upper=None if budget is None else estimate+budget,preDifferences=pre,confidenceLevel=None)\r\ndef realdata_fixed(kind,data):\r\n models,raw=source(data);rows=models[kind];G=panel(rows);times=sorted({r['time']for r in rows});step=STEP[kind];aa=att_projection(rows,'never',step);post=[r for r in aa['cells']if r['phase']=='post'];aggs=aggregate(post,covariance(post),step);tf=twfe(G,times)\r\n return dict(kind=kind,unit=UNIT[kind],periodUnit=CLOCK[kind],nativeRows=len(raw[kind]),modelRows=len(rows),entities=len(G),sourceRows=rows,att=aa,aggregations=aggs,twfe=tf,scope='Complete source frame; never-treated comparison,universal baseline,no anticipation. Native/model/paired/balanced denominators differ. All sampling/causal assumptions remain separate.')\r\ndef encode(v):\r\n if isinstance(v,Q):return str(v)\r\n if isinstance(v,dict):return{str(k):encode(x)for k,x in v.items()}\r\n if isinstance(v,(list,tuple)):return[encode(x)for x in v]\r\n return v\r\ndef v9(v):\r\n if v is None:return'undefined'\r\n if isinstance(v,str):return v\r\n if isinstance(v,bool):return'1'if v else'0'\r\n return format(float(v),'.9g')\r\ndef run_fixed(spec,out,data):\r\n api=spec['api'];a=spec['input'];summary={};points=[]\r\n def emit(series,x,y):points.append(dict(series=series,x=x,y=y,numericY=safe_float(y)))\r\n if api=='twobytwo':\r\n  result=paired(a['treated'],a['control']);summary=dict(defined=result['defined'],estimate=result['estimate'],treatedPairs=result['treated']['eligiblePairs'],controlPairs=result['control']['eligiblePairs'],unbiasedVariance=result['unbiasedVariance'],HC0=result['HC0'])\r\n  for i,r in enumerate(result['rows']):emit(r['role']+':'+r['id'],i+1,r['change'])\r\n elif api=='att':\r\n  result=att_projection(literal_panel(a['rows']),a.get('control','never'));summary=dict(sourceRows=result['sourceRows'],entities=result['sourceEntities'],cells=len(result['cells']),supportedCells=sum(r['defined']for r in result['cells']),postCells=sum(r['phase']=='post'for r in result['cells']))\r\n  for i,r in enumerate(result['cells']):emit('g'+str(r['g'])+':t'+str(r['t']),i+1,r['estimate'])\r\n elif api=='aggregate':\r\n  result=linear_aggregate(a);summary=dict(defined=result['defined'],estimate=result['estimate'],variance=result['variance'],covarianceRank=result['covarianceRank'],sumWeights=sum((r['coefficient']for r in result['weights']),Q(0)))\r\n  for i,r in enumerate(result['weights']):emit('g'+str(r['cohort'])+':t'+str(r['time']),i+1,r['contribution'])\r\n elif api=='twfe':\r\n  rows=literal_panel(a['rows']);G=panel(rows);result=twfe(G,sorted({r['time']for r in rows}));summary=dict(defined=result['beta']is not None,beta=result['beta'],numerator=result['num'],denominator=result['den'],balancedEntities=result['balancedEntities'],negativeTreatedCells=sum(v['coefficient']is not None and v['coefficient']<0 for v in result['weights'].values()))\r\n  for i,((g,t),r)in enumerate(sorted(result['weights'].items())):emit('g'+str(g)+':t'+str(t),i+1,r['coefficient'])\r\n elif api=='sensitivity':\r\n  result=sensitivity_fixed(a);summary={k:result[k]for k in['defined','estimate','scale','M','horizon','biasBudget','lower','upper']}\r\n  for i,k in enumerate(['lower','estimate','upper']):emit(k,i+1,result[k]if result['defined']else None)\r\n else:\r\n  result=realdata_fixed(a['kind'],data);post=[r for r in result['att']['cells']if r['phase']=='post'];s=next(r for r in result['aggregations']if r['type']=='simple');g=next(r for r in result['aggregations']if r['type']=='group'and r['key']=='overall');summary=dict(nativeRows=result['nativeRows'],modelRows=result['modelRows'],entities=result['entities'],postCells=len(post),simple=s['estimate'],group=g['estimate'],TWFE=result['twfe']['beta'],balancedEntities=result['twfe']['balancedEntities'])\r\n  for i,r in enumerate(post):emit('g'+str(r['g'])+':t'+str(r['t']),i+1,r['estimate'])\r\n out.mkdir(parents=True,exist_ok=True)\r\n if any(out.iterdir()):raise ValueError('use-new-empty-output-directory')\r\n shown={k:v9(v)for k,v in summary.items()};write(out/'summary.csv',[dict(name=k,value=v)for k,v in shown.items()]);write(out/'points.csv',points,['series','x','y','numericY']);full=dict(chapter='METR-20',profile=spec['id'],api=api,input=spec['input'],summary=shown,points=encode(points),details=encode(result),arithmetic='Python Fraction exact finite stored values;summary/plot approximate;bounded teaching projection,not causal or sampling certification')\r\n (out/'full.json').write_text(json.dumps(full,ensure_ascii=False,indent=2,allow_nan=False)+'\\n',encoding='utf8')\r\n import matplotlib\r\n matplotlib.use('Agg')\r\n import matplotlib.pyplot as plt\r\n plt.rcParams.update({'svg.fonttype':'none','font.family':'DejaVu Sans','font.size':12,'axes.spines.top':False,'axes.spines.right':False});fig,ax=plt.subplots(figsize=(9,5.6));good=[r for r in points if r['numericY']is not None]\r\n if good:\r\n  ax.scatter([r['x']for r in good],[r['numericY']for r in good],color='#315d7c',s=32);ax.axhline(0,color='#9eabb2',lw=.8);ax.set_xlabel('Declared cell/unit/bound ordinal')\r\n else:ax.text(.5,.5,'Undefined: no supported plotted quantity',ha='center',va='center',transform=ax.transAxes);ax.set_xticks([]);ax.set_yticks([])\r\n ax.set_ylabel('Cell weight'if api=='twfe'else result.get('unit','Stated outcome/bias units'));ax.set_title(spec['title']['en'],wrap=True,pad=14);ax.grid(axis='y',alpha=.2);fig.tight_layout(pad=2);fig.savefig(out/'plot.svg');plt.close(fig);print(json.dumps(shown))\r\n\r\nSPEC={'id': 'aggregate-cell-weighted', 'api': 'aggregate', 'title': {'ko': '네 사후 셀을 같은 비중으로', 'en': 'Four equally weighted post-treatment cells'}, 'input': {'cells': [{'cohort': 1, 'time': 1, 'estimate': '1', 'weight': '1'}, {'cohort': 1, 'time': 2, 'estimate': '1', 'weight': '1'}, {'cohort': 1, 'time': 3, 'estimate': '20', 'weight': '1'}, {'cohort': 3, 'time': 3, 'estimate': '1', 'weight': '1'}], 'type': 'simple', 'covariance': [['1', '0', '0', '0'], ['0', '1', '0', '0'], ['0', '0', '1', '0'], ['0', '0', '0', '1']]}, 'expectedReject': False}\r\nif __name__=='__main__':\r\n import sys\r\n run_fixed(SPEC,Path(sys.argv[1]),Path(sys.argv[2])if len(sys.argv)>2 else Path(__file__).resolve().parent.parent/'metr20-sources')\r\n",
      "arithmetic": "Python Fraction exact stored finite values;logs/summary/plots approximate",
      "summary": {
        "defined": "1",
        "estimate": "5.75",
        "variance": "0.25",
        "covarianceRank": "4",
        "sumWeights": "1"
      },
      "fullResultEmbedded": false,
      "plotEmbedded": false,
      "full": {
        "summary": {
          "defined": "1",
          "estimate": "5.75",
          "variance": "0.25",
          "covarianceRank": "4",
          "sumWeights": "1"
        },
        "notice": "Complete source/finite projection is retained in the linked external JSON; this short projection is not the full result."
      },
      "plot": null,
      "points": [
        {
          "series": "g1:t1",
          "x": 1,
          "y": "1/4",
          "numericY": 0.25
        },
        {
          "series": "g1:t2",
          "x": 2,
          "y": "1/4",
          "numericY": 0.25
        },
        {
          "series": "g1:t3",
          "x": 3,
          "y": "5",
          "numericY": 5.0
        },
        {
          "series": "g3:t3",
          "x": 4,
          "y": "1/4",
          "numericY": 0.25
        }
      ],
      "summaryFile": "metr20-programs/aggregate-cell-weighted-python-summary.csv",
      "summarySHA256": "4900560b9fbf2b0b9c827bd0b342c2e6f2e5d8c4ca5e403167c8bdbb12519b5f",
      "pointsFile": "metr20-programs/aggregate-cell-weighted-python-points.csv",
      "pointsSHA256": "04c154d3c410220eb771554e18b2c4e2675087f2af9c2cf010d0884fa83521ed",
      "fullResultFile": "metr20-programs/aggregate-cell-weighted-python.json",
      "fullResultSHA256": "a104a2011d911f8b38449233d47f7e90c92bd68ceda0e89449ce3a3df9eaaf24",
      "plotFile": "metr20-programs/aggregate-cell-weighted-python.svg",
      "plotSHA256": "3382549639f8efdc24c41d3d2a89ca9f271e98bf7be990c10caede3f961cce22"
    },
    {
      "api": "aggregate",
      "variant": "aggregate-cell-weighted",
      "profile": "aggregate-cell-weighted",
      "language": "R",
      "file": "metr20-programs/aggregate-cell-weighted-r.R",
      "codeSHA256": "bbfc361c53936e23295c4e50db51a0325e23d55abf8f33b1e4b7711f8b383792",
      "returnCode": 0,
      "expectedRejection": false,
      "title": {
        "ko": "네 사후 셀을 같은 비중으로",
        "en": "Four equally weighted post-treatment cells"
      },
      "code": "# METR20 fixed example. Base R only, finite arithmetic approximate.\r\n# No JavaScript engine,model JSON,derived answer table,private module or internet.\r\noptions(stringsAsFactors=FALSE,digits=17)\r\nargv<-commandArgs(trailingOnly=TRUE);if(length(argv)<1L)stop('Supply a new empty output directory')\r\noutdir<-argv[1];script<-sub('^--file=','',commandArgs(FALSE)[grepl('^--file=',commandArgs(FALSE))][1]);here<-dirname(normalizePath(script,mustWork=TRUE));datadir<-if(length(argv)>=2L)argv[2]else file.path(here,'..','metr20-sources')\r\nunits<-c(country='log teen-employment points',person='recorded real earnings',company='FTE employees');clocks<-c(country='calendar year',person='calendar year',company='survey-wave index');steps<-c(country=1,person=3,company=1);files<-c(country='actual2500-county-mpdta-all6-fields.csv',person='actual38408-NSW-all15-fields.csv',company='actual410-NJPA-all46-fields.csv')\r\nnum<-function(s)ifelse(s=='.',NA_real_,as.numeric(s));mean0<-function(v)if(length(v))mean(v)else NA_real_;var0<-function(v)if(length(v)>1L)sum((v-mean(v))^2)/(length(v)-1L)else NA_real_\r\n\r\nSPEC<-list(id=\"aggregate-cell-weighted\",api=\"aggregate\",title=list(ko=\"네 사후 셀을 같은 비중으로\",en=\"Four equally weighted post-treatment cells\"),input=list(cells=list(list(cohort=1,time=1,estimate=\"1\",weight=\"1\"),list(cohort=1,time=2,estimate=\"1\",weight=\"1\"),list(cohort=1,time=3,estimate=\"20\",weight=\"1\"),list(cohort=3,time=3,estimate=\"1\",weight=\"1\")),type=\"simple\",covariance=list(list(\"1\",\"0\",\"0\",\"0\"),list(\"0\",\"1\",\"0\",\"0\"),list(\"0\",\"0\",\"1\",\"0\"),list(\"0\",\"0\",\"0\",\"1\"))),expectedReject=FALSE)\r\npanel<-function(rows){G<-list();for(r in rows){key<-r$entity;u<-G[[key]];if(is.null(u))u<-list(g=r$g,rows=list());stopifnot(identical(u$g,r$g),is.null(u$rows[[as.character(r$time)]]));u$rows[[as.character(r$time)]]<-r;G[[key]]<-u};G}\r\ncell<-function(G,g,t,step,control){b<-g-step;members<-list();T<-C<-list();for(key in names(G)){u<-G[[key]];target<-!is.na(u$g)&&u$g==g;comp<-is.na(u$g)||(control=='notyet'&&!is.na(u$g)&&u$g>max(t,b));role<-if(target)'treated'else if(comp)'control'else'excluded-comparison';before<-u$rows[[as.character(b)]];after<-u$rows[[as.character(t)]];yb<-if(is.null(before))NA_real_ else before$y;ya<-if(is.null(after))NA_real_ else after$y;eligible<-role!='excluded-comparison'&&!is.na(yb)&&!is.na(ya);reason<-if(role=='excluded-comparison')'target-or-already-exposed-cohort-not-valid-control'else if(is.null(before))'baseline-source-row-absent'else if(is.null(after))'target-time-source-row-absent'else if(is.na(yb))'baseline-outcome-missing'else if(is.na(ya))'target-outcome-missing'else'';m<-list(entity=key,nativeID=u$rows[[1]]$nativeID,g=u$g,role=role,eligible=eligible,baselineSourceId=if(is.null(before))NA_character_ else before$id,targetSourceId=if(is.null(after))NA_character_ else after$id,before=yb,after=ya,change=if(eligible)ya-yb else NA_real_,reason=reason);members[[key]]<-m;if(eligible){if(role=='treated')T[[length(T)+1L]]<-m else C[[length(C)+1L]]<-m}}\r\n change<-function(a)vapply(a,function(r)r$change,0);d<-mean0(change(T));e<-mean0(change(C));estimate<-if(is.na(d)||is.na(e))NA_real_ else d-e;defined<-!is.na(estimate);scores<-setNames(rep(NA_real_,length(members)),names(members));for(key in names(members)){m<-members[[key]];s<-if(!defined)NA_real_ else if(!m$eligible)0 else if(m$role=='treated')(m$change-d)/length(T)else-(m$change-e)/length(C);m$score<-s;scores[key]<-s;members[[key]]<-m};st<-var0(change(T));sc<-var0(change(C));v<-if(is.na(st)||is.na(sc))NA_real_ else st/length(T)+sc/length(C);level<-function(a,k)mean0(vapply(a,function(r)r[[k]],0))\r\n list(g=g,t=t,baseline=b,event=(t-g)/step,phase=if(t==b)'mechanical-reference'else if(t>=g)'post'else'pre-placebo',defined=defined,estimate=estimate,T=T,C=C,members=members,scores=scores,HC0=if(defined)sum(scores^2)else NA_real_,unbiased=v,treatedMeanBefore=level(T,'before'),treatedMeanAfter=level(T,'after'),treatedMeanChange=d,controlMeanBefore=level(C,'before'),controlMeanAfter=level(C,'after'),controlMeanChange=e)\r\n}\r\ncovariance<-function(cells){n<-length(cells);V<-matrix(NA_real_,n,n);for(i in seq_len(n))for(j in seq_len(n))if(cells[[i]]$defined&&cells[[j]]$defined)V[i,j]<-sum(cells[[i]]$scores*cells[[j]]$scores);V}\r\naggregate_cells<-function(post,V,step){out<-list();push<-function(typ,key,ii,w){est<-if(!length(ii)||any(vapply(post[ii],function(z)is.na(z$estimate),TRUE)))NA_real_ else sum(w*vapply(post[ii],function(z)z$estimate,0));vv<-if(is.na(est)||anyNA(V[ii,ii,drop=FALSE]))NA_real_ else as.numeric(t(w)%*%V[ii,ii,drop=FALSE]%*%w);out[[length(out)+1L]]<<-list(type=typ,key=as.character(key),ii=ii,w=w,estimate=est,variance=vv)};positive<-which(vapply(post,function(c)length(c$T)>0L,TRUE));mass<-sum(vapply(post[positive],function(c)length(c$T),0));push('simple','overall',positive,if(mass)vapply(post[positive],function(c)length(c$T)/mass,0)else numeric())\r\n for(typ in c('event','calendar','group')){keys<-vapply(post,function(c)if(typ=='event')c$event else if(typ=='calendar')c$t else c$g,0);gg<-sort(unique(keys));cohortmass<-if(typ=='group')sum(vapply(gg,function(k)length(post[[which(keys==k)[1]]]$T),0))else 0;allii<-integer();allw<-numeric();for(key in gg){ii<-which(keys==key);jj<-ii[vapply(post[ii],function(c)length(c$T)>0L,TRUE)];if(typ=='group'){stopifnot(length(unique(vapply(post[ii],function(c)length(c$T),0)))<=1L);w<-if(length(jj))rep(1/length(jj),length(jj))else numeric();if(cohortmass){allii<-c(allii,jj);allw<-c(allw,w*length(post[[ii[1]]]$T)/cohortmass)}}else{total<-sum(vapply(post[jj],function(c)length(c$T),0));w<-if(total)vapply(post[jj],function(c)length(c$T)/total,0)else numeric()};push(typ,key,jj,w)};if(typ=='group')push(typ,'overall',allii,allw)};out}\r\ntwfe<-function(G,times){ledger<-list();good<-list();for(key in names(G)){u<-G[[key]];absent<-times[!as.character(times)%in%names(u$rows)];missing<-times[vapply(times,function(t){r<-u$rows[[as.character(t)]];!is.null(r)&&is.na(r$y)},TRUE)];eligible<-length(times)>0L&&!length(absent)&&!length(missing);ledger[[length(ledger)+1L]]<-list(entity=key,g=u$g,nativeID=u$rows[[1]]$nativeID,eligible=eligible,absentTimes=paste(absent,collapse=','),missingOutcomeTimes=paste(missing,collapse=','),originalRows=length(u$rows));if(eligible)good[[key]]<-u};rows<-list();for(key in names(good))for(t in times){r<-good[[key]]$rows[[as.character(t)]];r$D<-as.integer(!is.na(r$g)&&t>=r$g);rows[[length(rows)+1L]]<-r};em<-lapply(good,function(u)list(D=mean(vapply(times,function(t)as.integer(!is.na(u$g)&&t>=u$g),0)),Y=mean(vapply(u$rows[as.character(times)],function(r)r$y,0))));tm<-lapply(times,function(t)list(D=mean(vapply(good,function(u)as.integer(!is.na(u$g)&&t>=u$g),0)),Y=mean(vapply(good,function(u)u$rows[[as.character(t)]]$y,0))));names(tm)<-as.character(times);gd<-mean0(vapply(rows,function(r)r$D,0));gy<-mean0(vapply(rows,function(r)r$y,0));num<-den<-0\r\n for(i in seq_along(rows)){r<-rows[[i]];r$residualD<-r$D-em[[r$entity]]$D-tm[[as.character(r$time)]]$D+gd;r$residualY<-r$y-em[[r$entity]]$Y-tm[[as.character(r$time)]]$Y+gy;num<-num+r$residualD*r$residualY;den<-den+r$residualD^2;rows[[i]]<-r};beta<-if(den!=0)num/den else NA_real_;weights<-list();for(i in seq_along(rows)){r<-rows[[i]];r$projectionCoefficient<-if(den!=0)r$residualD/den else NA_real_;r$regressionResidual<-if(!is.na(beta))r$residualY-beta*r$residualD else NA_real_;rows[[i]]<-r;if(r$D==1L){k<-paste(r$g,r$time,sep=':');z<-weights[[k]];if(is.null(z))z<-list(g=r$g,t=r$time,rows=0,coefficient=if(den!=0)0 else NA_real_);z$rows<-z$rows+1L;if(den!=0)z$coefficient<-z$coefficient+r$projectionCoefficient;weights[[k]]<-z}};list(ledger=ledger,rows=rows,num=num,den=den,beta=beta,weights=weights,balancedEntities=length(good))}\r\nadjacent_pre<-function(G,g,t,step,control){b<-t-step;T<-C<-numeric();for(u in G){target<-!is.na(u$g)&&u$g==g;comp<-is.na(u$g)||(control=='notyet'&&!is.na(u$g)&&u$g>max(t,b));if(!target&&!comp)next;before<-u$rows[[as.character(b)]];after<-u$rows[[as.character(t)]];if(!is.null(before)&&!is.null(after)&&!is.na(before$y)&&!is.na(after$y)){if(target)T<-c(T,after$y-before$y)else C<-c(C,after$y-before$y)}};if(!length(T)||!length(C))NA_real_ else mean(T)-mean(C)}\r\n\r\n# Newly authored bounded teaching projections; base R finite approximation.\r\n# Source helper functions are inlined in each public file, never imported.\r\nqnum<-function(v){if(is.null(v)||is.na(v))return(NA_real_);s<-strsplit(as.character(v),'/',fixed=TRUE)[[1]];if(length(s)==1L)as.numeric(s)else as.numeric(s[1])/as.numeric(s[2])}\r\npaired<-function(T,C){\r\n stats<-function(rr){use<-Filter(function(r)!is.na(qnum(r$before))&&!is.na(qnum(r$after)),rr);a<-vapply(use,function(r)qnum(r$before),0);b<-vapply(use,function(r)qnum(r$after),0);list(sourcePairs=length(rr),eligiblePairs=length(use),excludedPairs=length(rr)-length(use),meanBefore=mean0(a),meanAfter=mean0(b),meanChange=mean0(b-a),sampleChangeVariance=var0(b-a))}\r\n st<-stats(T);sc<-stats(C);defined<-st$eligiblePairs>0L&&sc$eligiblePairs>0L;estimate<-if(defined)st$meanChange-sc$meanChange else NA_real_;rr<-list()\r\n for(role in c('treated','control')){input<-if(role=='treated')T else C;s<-if(role=='treated')st else sc;for(r in input){before<-qnum(r$before);after<-qnum(r$after);eligible<-!is.na(before)&&!is.na(after);change<-if(eligible)after-before else NA_real_;score<-if(!defined)NA_real_ else if(!eligible)0 else (change-s$meanChange)/(if(role=='treated')s$eligiblePairs else -s$eligiblePairs);rr[[length(rr)+1L]]<-list(id=r$id,role=role,before=before,after=after,eligible=eligible,change=change,score=score)}}\r\n list(defined=defined,estimate=estimate,treated=st,control=sc,unbiasedVariance=if(defined&&st$eligiblePairs>=2L&&sc$eligiblePairs>=2L)st$sampleChangeVariance/st$eligiblePairs+sc$sampleChangeVariance/sc$eligiblePairs else NA_real_,HC0=if(defined)sum(vapply(rr,function(r)r$score^2,0))else NA_real_,rows=rr)\r\n}\r\nliteral_panel<-function(rr)lapply(seq_along(rr),function(i){r<-rr[[i]];r$y<-qnum(r$y);r$nativeID<-r$entity;r$sourceRow<-i;r})\r\natt_projection<-function(rows,control='never',step=1){G<-panel(rows);times<-sort(unique(vapply(rows,function(r)r$time,0)));cohorts<-sort(unique(na.omit(vapply(rows,function(r)r$g,0))));cells<-list();for(g in cohorts)for(t in times)cells[[length(cells)+1L]]<-cell(G,g,t,step,control);list(sourceRows=length(rows),sourceEntities=length(G),step=step,control=control,cells=cells,covariance=covariance(cells))}\r\nlinear_aggregate<-function(a){\r\n rr<-lapply(a$cells,function(r){r$estimate<-qnum(r$estimate);r$weight<-qnum(r$weight);r});V<-if(is.null(a$covariance))NULL else do.call(rbind,lapply(a$covariance,function(r)vapply(r,qnum,0)));rank<-NA_real_\r\n if(!is.null(V)){stopifnot(nrow(V)==length(rr),ncol(V)==length(rr),all(V==t(V)));ev<-eigen(V,symmetric=TRUE,only.values=TRUE)$values;if(any(ev< -1e-12))stop('covariance-must-be-positive-semidefinite');rank<-sum(ev>1e-12)}\r\n selected<-which(vapply(rr,function(r)r$time>=r$cohort&&r$weight>0,TRUE));w<-numeric(length(rr));type<-if(is.null(a$type))'simple'else a$type\r\n if(type=='simple'){mass<-sum(vapply(rr[selected],function(r)r$weight,0));if(mass>0)for(i in selected)w[i]<-rr[[i]]$weight/mass}else{g<-vapply(rr,function(r)r$cohort,0);gg<-sort(unique(g[selected]));mass<-sum(vapply(gg,function(gi)rr[[intersect(which(g==gi),selected)[1]]]$weight,0));for(gi in gg){ii<-intersect(which(g==gi),selected);stopifnot(length(unique(vapply(rr[ii],function(r)r$weight,0)))==1L);w[ii]<-rr[[ii[1]]]$weight/mass/length(ii)}}\r\n used<-which(w>0);estimate<-if(!length(used)||any(vapply(rr[used],function(r)is.na(r$estimate),TRUE)))NA_real_ else sum(w[used]*vapply(rr[used],function(r)r$estimate,0));variance<-if(is.na(estimate)||is.null(V))NA_real_ else as.numeric(t(w)%*%V%*%w);weights<-lapply(used,function(i)list(sourceIndex=i-1L,cohort=rr[[i]]$cohort,time=rr[[i]]$time,coefficient=w[i],estimate=rr[[i]]$estimate,contribution=w[i]*rr[[i]]$estimate))\r\n list(type=type,defined=!is.na(estimate),estimate=estimate,variance=variance,covarianceRank=rank,weights=weights,cells=rr,covariance=V)\r\n}\r\nsensitivity_fixed<-function(a){estimate<-qnum(a$estimate);M<-qnum(a$M);h<-if(is.null(a$horizon))1 else a$horizon;stopifnot(M>=0,h>=1);pre<-vapply(a$preDifferences,qnum,0);scale<-if(!is.null(a$scale))qnum(a$scale)else if(length(pre))max(abs(pre))else NA_real_;budget<-M*scale*h;list(defined=!is.na(scale),estimate=estimate,scale=scale,M=M,horizon=h,biasBudget=budget,lower=estimate-budget,upper=estimate+budget,preDifferences=as.list(pre),confidenceLevel=NULL)}\r\nrealdata_fixed<-function(kind){rows<-models[[kind]];G<-panel(rows);times<-sort(unique(vapply(rows,function(r)r$time,0)));step<-unname(steps[kind]);aa<-att_projection(rows,'never',step);post<-Filter(function(r)r$phase=='post',aa$cells);aggs<-aggregate_cells(post,covariance(post),step);tf<-twfe(G,times);list(kind=kind,unit=unname(units[kind]),periodUnit=unname(clocks[kind]),nativeRows=nrow(raw[[kind]]),modelRows=length(rows),entities=length(G),sourceRows=rows,att=aa,aggregations=aggs,twfe=tf,scope='Complete native/model/paired/balanced source frames; never control,universal base,no anticipation;not causal/sampling certification.')}\r\n# JSON encoder deliberately handles matrices and scalar/vector distinctions.\r\nencode<-function(x){\r\n if(is.null(x))return('null')\r\n quote<-function(s){s<-gsub('\\\\','\\\\\\\\',as.character(s),fixed=TRUE);s<-gsub('\"','\\\\\"',s,fixed=TRUE);s<-gsub('\\n','\\\\n',s,fixed=TRUE);s<-gsub('\\r','\\\\r',s,fixed=TRUE);s<-gsub('\\t','\\\\t',s,fixed=TRUE);paste0('\"',s,'\"')}\r\n if(is.matrix(x))return(paste0('[',paste(vapply(seq_len(nrow(x)),function(i)encode(as.list(unname(x[i,]))),''),collapse=','),']'))\r\n if(is.list(x)){if(length(x)&&!is.null(names(x)))return(paste0('{',paste(paste0(vapply(names(x),quote,''),':',vapply(x,encode,'')),collapse=','),'}'));return(paste0('[',paste(vapply(x,encode,''),collapse=','),']'))}\r\n if(length(x)!=1L)return(encode(as.list(unname(x))))\r\n if(is.na(x))return('null');if(is.logical(x))return(if(x)'true'else'false');if(is.numeric(x))return(sprintf('%.17g',unname(x)));quote(x)\r\n}\r\nv9<-function(x){if(is.null(x)||is.na(x))return('undefined');if(is.logical(x))return(if(x)'1'else'0');if(is.numeric(x))return(sprintf('%.9g',unname(x)));as.character(x)}\r\nrun_fixed<-function(spec,out){api<-spec$api;a<-spec$input;summary<-list();points<-list();emit<-function(series,x,y){points[[length(points)+1L]]<<-list(series=series,x=x,y=y,numericY=y)}\r\n if(api=='twobytwo'){result<-paired(a$treated,a$control);summary<-list(defined=result$defined,estimate=result$estimate,treatedPairs=result$treated$eligiblePairs,controlPairs=result$control$eligiblePairs,unbiasedVariance=result$unbiasedVariance,HC0=result$HC0);for(i in seq_along(result$rows)){r<-result$rows[[i]];emit(paste(r$role,r$id,sep=':'),i,r$change)}}\r\n else if(api=='att'){result<-att_projection(literal_panel(a$rows),a$control);summary<-list(sourceRows=result$sourceRows,entities=result$sourceEntities,cells=length(result$cells),supportedCells=sum(vapply(result$cells,function(r)r$defined,TRUE)),postCells=sum(vapply(result$cells,function(r)r$phase=='post',TRUE)));for(i in seq_along(result$cells)){r<-result$cells[[i]];emit(paste0('g',r$g,':t',r$t),i,r$estimate)}}\r\n else if(api=='aggregate'){result<-linear_aggregate(a);summary<-list(defined=result$defined,estimate=result$estimate,variance=result$variance,covarianceRank=result$covarianceRank,sumWeights=sum(vapply(result$weights,function(r)r$coefficient,0)));for(i in seq_along(result$weights)){r<-result$weights[[i]];emit(paste0('g',r$cohort,':t',r$time),i,r$contribution)}}\r\n else if(api=='twfe'){rows<-literal_panel(a$rows);G<-panel(rows);result<-twfe(G,sort(unique(vapply(rows,function(r)r$time,0))));summary<-list(defined=!is.na(result$beta),beta=result$beta,numerator=result$num,denominator=result$den,balancedEntities=result$balancedEntities,negativeTreatedCells=sum(vapply(result$weights,function(r)!is.na(r$coefficient)&&r$coefficient<0,TRUE)));if(length(result$weights)){ord<-order(vapply(result$weights,function(r)r$g,0),vapply(result$weights,function(r)r$t,0));for(i in seq_along(ord)){r<-result$weights[[ord[i]]];emit(paste0('g',r$g,':t',r$t),i,r$coefficient)}}}\r\n else if(api=='sensitivity'){result<-sensitivity_fixed(a);summary<-result[c('defined','estimate','scale','M','horizon','biasBudget','lower','upper')];for(i in seq_along(c('lower','estimate','upper'))){k<-c('lower','estimate','upper')[i];emit(k,i,if(result$defined)result[[k]]else NA_real_)}}\r\n else{result<-realdata_fixed(a$kind);post<-Filter(function(r)r$phase=='post',result$att$cells);simple<-Filter(function(r)r$type=='simple',result$aggregations)[[1]];group<-Filter(function(r)r$type=='group'&&r$key=='overall',result$aggregations)[[1]];summary<-list(nativeRows=result$nativeRows,modelRows=result$modelRows,entities=result$entities,postCells=length(post),simple=simple$estimate,group=group$estimate,TWFE=result$twfe$beta,balancedEntities=result$twfe$balancedEntities);for(i in seq_along(post)){r<-post[[i]];emit(paste0('g',r$g,':t',r$t),i,r$estimate)}}\r\n dir.create(out,recursive=TRUE,showWarnings=FALSE);if(length(list.files(out,all.files=TRUE,no..=TRUE)))stop('use-new-empty-output-directory');shown<-lapply(summary,v9);write.csv(data.frame(name=names(shown),value=unlist(shown,use.names=FALSE)),file.path(out,'summary.csv'),row.names=FALSE,na='');pointframe<-if(length(points))do.call(rbind,lapply(points,function(p)data.frame(series=p$series,x=p$x,y=p$y,numericY=p$numericY,stringsAsFactors=FALSE)))else data.frame(series=character(),x=numeric(),y=numeric(),numericY=numeric());write.csv(pointframe,file.path(out,'points.csv'),row.names=FALSE,na='');full<-list(chapter='METR-20',profile=spec$id,api=api,input=spec$input,summary=shown,points=points,details=result,arithmetic='Base R approximate finite values;bounded teaching projection,not exact fractions or causal/sampling certification.');writeLines(encode(full),file.path(out,'full.json'),useBytes=TRUE)\r\n svg(file.path(out,'plot.svg'),width=9,height=5.6,pointsize=12);par(mar=c(4.5,5.5,4,1));good<-pointframe[!is.na(pointframe$numericY),,drop=FALSE]\r\n if(nrow(good)){plot(good$x,good$numericY,pch=19,col='#315d7c',xlab='Declared cell/unit/bound ordinal',ylab=if(api=='twfe')'Cell weight'else if(!is.null(result$unit))result$unit else 'Stated outcome/bias units',main=spec$title$en);abline(h=0,col='#9eabb2');grid(nx=NA,ny=NULL,col='#e2e5e7');points(good$x,good$numericY,pch=19,col='#315d7c')}else{plot.new();text(.5,.5,'Undefined: no supported plotted quantity');title(main=spec$title$en)};dev.off();cat(encode(shown),'\\n')\r\n}\r\n\r\nrun_fixed(SPEC,outdir)\r\n",
      "arithmetic": "Base R approximate finite arithmetic;not an exact rational result",
      "summary": {
        "defined": "1",
        "estimate": "5.75",
        "variance": "0.25",
        "covarianceRank": "4",
        "sumWeights": "1"
      },
      "fullResultEmbedded": false,
      "plotEmbedded": false,
      "full": {
        "summary": {
          "defined": "1",
          "estimate": "5.75",
          "variance": "0.25",
          "covarianceRank": "4",
          "sumWeights": "1"
        },
        "notice": "Complete source/finite projection is retained in the linked external JSON; this short projection is not the full result."
      },
      "plot": null,
      "points": [
        {
          "series": "g1:t1",
          "x": 1,
          "y": 0.25,
          "numericY": 0.25
        },
        {
          "series": "g1:t2",
          "x": 2,
          "y": 0.25,
          "numericY": 0.25
        },
        {
          "series": "g1:t3",
          "x": 3,
          "y": 5,
          "numericY": 5
        },
        {
          "series": "g3:t3",
          "x": 4,
          "y": 0.25,
          "numericY": 0.25
        }
      ],
      "summaryFile": "metr20-programs/aggregate-cell-weighted-r-summary.csv",
      "summarySHA256": "b69e167781f687a7e82f7b318cc1355c1d39c99835940fab7895c18660586969",
      "pointsFile": "metr20-programs/aggregate-cell-weighted-r-points.csv",
      "pointsSHA256": "e793c43c022e688a69629454b57a3f7653c04ddebc659ea3389f0356694a94b2",
      "fullResultFile": "metr20-programs/aggregate-cell-weighted-r.json",
      "fullResultSHA256": "5fef68affeb09f31f2293ec071f9a0e8221a3dc2461f7459325f9babee74a46f",
      "plotFile": "metr20-programs/aggregate-cell-weighted-r.svg",
      "plotSHA256": "546db4b60475e2c531132ed4e54519542d7d908871e6e1fc662da8a3d032eb3b"
    },
    {
      "api": "aggregate",
      "variant": "aggregate-cohort-weighted",
      "profile": "aggregate-cohort-weighted",
      "language": "Python",
      "file": "metr20-programs/aggregate-cohort-weighted-python.py",
      "codeSHA256": "233307388a63955e01880c6d75a00b0a961b1b25521b1c767da3a40a4a5312e8",
      "returnCode": 0,
      "expectedRejection": false,
      "title": {
        "ko": "시점 평균 뒤 코호트를 같은 비중으로",
        "en": "Equal cohort weights after averaging times"
      },
      "code": "\"\"\"METR20 actual sources. Python standard library, exact stored-value rationals.\r\nRead ONLY the three native-observation CSVs; no JS engine,model JSON,derived\r\nanswers,private modules or internet needed. Outcome measurement/identification\r\nand valid sampling inference remain separate from exact finite arithmetic.\r\nRun: python metr20-reproduce.py --data-dir PATH --out NEW_EMPTY_DIRECTORY\r\n\"\"\"\r\nfrom pathlib import Path\r\nfrom fractions import Fraction as Q\r\nfrom collections import defaultdict,Counter\r\nimport csv,json,math,argparse,hashlib\r\n\r\nUNIT={'country':'log teen-employment points','person':'recorded real earnings','company':'FTE employees'}\r\nCLOCK={'country':'calendar year','person':'calendar year','company':'survey-wave index'}\r\nSTEP={'country':1,'person':3,'company':1}\r\nFILES={'country':'actual2500-county-mpdta-all6-fields.csv','person':'actual38408-NSW-all15-fields.csv','company':'actual410-NJPA-all46-fields.csv'}\r\ndef avg(v):return sum(v,Q(0))/len(v)if v else None\r\ndef samplevar(v):return sum(((x-avg(v))**2 for x in v),Q(0))/(len(v)-1)if len(v)>1 else None\r\ndef binary(s):return None if s=='.'else Q.from_float(float(s))\r\ndef token(v):\r\n if v is None:return ''\r\n if isinstance(v,bool):return 'true'if v else'false'\r\n return str(v)\r\ndef safe_float(v):\r\n if v is None:return None\r\n try:r=float(v)\r\n except OverflowError:return None\r\n return r if math.isfinite(r)else None\r\ndef read(p):\r\n with p.open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))\r\ndef write(p,rows,head=None):\r\n if head is None:\r\n  assert rows;head=list(rows[0])\r\n with p.open('w',encoding='utf8',newline='')as f:\r\n  w=csv.DictWriter(f,fieldnames=head);w.writeheader();w.writerows({k:token(r.get(k))for k in head}for r in rows)\r\ndef source(data):\r\n raw={k:read(data/n)for k,n in FILES.items()};assert[len(raw[k])for k in FILES]==[2500,38408,410]\r\n models={k:[]for k in FILES}\r\n for r in raw['country']:\r\n  g0=int(r['first.treat']);g=None if g0==0 else g0;assert int(r['treat'])==int(g is not None)\r\n  models['country'].append(dict(id='mpdta:'+r['sourceRow'],entity='county:'+str(int(r['countyreal'])),time=int(r['year']),y=binary(r['lemp']),g=g,sourceRow=int(r['sourceRow']),nativeID=r['countyreal']))\r\n for r in raw['person']:\r\n  selected=int(r['experimental'])==1;assert selected==(int(r['sample'])==1);assert(r['treated']!='.')==selected\r\n  if selected:\r\n   d=int(r['treated']);assert d in[0,1]\r\n   models['person'].append(dict(id='nsw:'+r['sourceRow'],entity='nsw-id:'+str(int(r['id'])),time=int(r['year']),y=binary(r['re']),g=1978 if d else None,sourceRow=int(r['sourceRow']),nativeID=str(int(r['id']))))\r\n for r in raw['company']:\r\n  state=int(r['STATE']);assert state in[0,1]\r\n  for t,suffix in[(0,''),(1,'2')]:\r\n   a=[r[n+suffix]for n in['EMPFT','NMGRS','EMPPT']];y=None if'.'in a else Q(a[0])+Q(a[1])+Q(a[2])/2\r\n   models['company'].append(dict(id='njpa:'+r['sourceRow']+':wave'+str(t),entity='njpa-row:'+r['sourceRow'],time=t,y=y,g=1 if state else None,sourceRow=int(r['sourceRow']),nativeID=r['SHEET']))\r\n assert[len(models[k])for k in FILES]==[2500,1444,820]\r\n return models,raw\r\ndef panel(rows):\r\n groups={}\r\n for r in rows:\r\n  u=groups.setdefault(r['entity'],{'g':r['g'],'rows':{}});assert u['g']==r['g']and r['time']not in u['rows'];u['rows'][r['time']]=r\r\n return groups\r\ndef cell(groups,g,t,step,control):\r\n b=g-step;members=[];T=[];C=[]\r\n for key,u in groups.items():\r\n  role='treated'if u['g']==g else'control'if u['g']is None or(control=='notyet'and u['g']>max(t,b))else'excluded-comparison'\r\n  before=u['rows'].get(b);after=u['rows'].get(t);yb=None if before is None else before['y'];ya=None if after is None else after['y'];eligible=role!='excluded-comparison'and yb is not None and ya is not None\r\n  reason='target-or-already-exposed-cohort-not-valid-control'if role=='excluded-comparison'else'baseline-source-row-absent'if before is None else'target-time-source-row-absent'if after is None else'baseline-outcome-missing'if yb is None else'target-outcome-missing'if ya is None else''\r\n  m={'entity':key,'nativeID':next(iter(u['rows'].values()))['nativeID'],'g':u['g'],'role':role,'eligible':eligible,'baselineSourceId':None if before is None else before['id'],'targetSourceId':None if after is None else after['id'],'before':yb,'after':ya,'change':ya-yb if eligible else None,'reason':reason};members.append(m)\r\n  if eligible:(T if role=='treated'else C).append(m)\r\n d=avg([r['change']for r in T]);e=avg([r['change']for r in C]);estimate=None if d is None or e is None else d-e;defined=estimate is not None;scores={}\r\n for m in members:\r\n  s=None if not defined else Q(0)\r\n  if defined and m['eligible']:s=(m['change']-(d if m['role']=='treated'else e))/(len(T)if m['role']=='treated'else-len(C))\r\n  m['score']=s;scores[m['entity']]=s\r\n st=samplevar([r['change']for r in T]);sc=samplevar([r['change']for r in C]);v=None if st is None or sc is None else st/len(T)+sc/len(C)\r\n return {'g':g,'t':t,'baseline':b,'event':(t-g)//step,'phase':'mechanical-reference'if t==b else'post'if t>=g else'pre-placebo','defined':defined,'estimate':estimate,'T':T,'C':C,'members':members,'scores':scores,'HC0':None if not defined else sum((s*s for s in scores.values()),Q(0)),'unbiased':v,'treatedMeanBefore':avg([r['before']for r in T]),'treatedMeanAfter':avg([r['after']for r in T]),'treatedMeanChange':d,'controlMeanBefore':avg([r['before']for r in C]),'controlMeanAfter':avg([r['after']for r in C]),'controlMeanChange':e}\r\ndef covariance(cells):\r\n return[[None if not a['defined']or not b['defined']else sum((v*b['scores'][i]for i,v in a['scores'].items()),Q(0))for b in cells]for a in cells]\r\ndef aggregate(post,V,step):\r\n out=[]\r\n def push(typ,key,coeff):\r\n  estimate=None if not coeff or any(post[i]['estimate']is None for i in coeff)else sum((w*post[i]['estimate']for i,w in coeff.items()),Q(0));variance=None if estimate is None or any(V[i][j]is None for i in coeff for j in coeff)else sum((a*b*V[i][j]for i,a in coeff.items()for j,b in coeff.items()),Q(0));out.append({'type':typ,'key':key,'coeff':coeff,'estimate':estimate,'variance':variance})\r\n positive=[i for i,c in enumerate(post)if len(c['T'])>0];mass=sum(len(post[i]['T'])for i in positive)\r\n push('simple','overall',{i:Q(len(post[i]['T']),mass)for i in positive}if mass else{})\r\n for typ in['event','calendar','group']:\r\n  groups=defaultdict(list)\r\n  for i,c in enumerate(post):groups[c['event']if typ=='event'else c['t']if typ=='calendar'else c['g']].append(i)\r\n  overall={};cohortMass=sum(len(post[ii[0]]['T'])for ii in groups.values())if typ=='group'else 0\r\n  for key,ii in sorted(groups.items()):\r\n   jj=[i for i in ii if len(post[i]['T'])>0]\r\n   if typ=='group':\r\n    assert len({len(post[i]['T'])for i in ii})<=1\r\n    coeff={i:Q(1,len(jj))for i in jj}if jj else{}\r\n    if cohortMass:\r\n     for i,w in coeff.items():overall[i]=w*Q(len(post[ii[0]]['T']),cohortMass)\r\n   else:\r\n    total=sum(len(post[i]['T'])for i in jj);coeff={i:Q(len(post[i]['T']),total)for i in jj}if total else{}\r\n   push(typ,str(key),coeff)\r\n  if typ=='group':push(typ,'overall',overall)\r\n return out\r\ndef twfe(groups,times):\r\n ledger=[];good={}\r\n for key,u in groups.items():\r\n  absent=[t for t in times if t not in u['rows']];missing=[t for t in times if t in u['rows']and u['rows'][t]['y']is None];eligible=bool(times)and not absent and not missing\r\n  ledger.append({'entity':key,'g':u['g'],'nativeID':next(iter(u['rows'].values()))['nativeID'],'eligible':eligible,'absentTimes':','.join(map(str,absent)),'missingOutcomeTimes':','.join(map(str,missing)),'originalRows':len(u['rows'])})\r\n  if eligible:good[key]=u\r\n rows=[dict(**u['rows'][t],D=Q(u['g']is not None and t>=u['g']))for key,u in good.items()for t in times]\r\n em={k:{'D':avg([Q(u['g']is not None and t>=u['g'])for t in times]),'Y':avg([u['rows'][t]['y']for t in times])}for k,u in good.items()};tm={t:{'D':avg([Q(u['g']is not None and t>=u['g'])for u in good.values()]),'Y':avg([u['rows'][t]['y']for u in good.values()])}for t in times};gd=avg([r['D']for r in rows]);gy=avg([r['y']for r in rows]);num=den=Q(0)\r\n for r in rows:\r\n  r['residualD']=r['D']-em[r['entity']]['D']-tm[r['time']]['D']+gd;r['residualY']=r['y']-em[r['entity']]['Y']-tm[r['time']]['Y']+gy;num+=r['residualD']*r['residualY'];den+=r['residualD']**2\r\n beta=num/den if den else None;weights={}\r\n for r in rows:\r\n  r['projectionCoefficient']=r['residualD']/den if den else None;r['regressionResidual']=r['residualY']-beta*r['residualD']if beta is not None else None\r\n  if r['D']:\r\n   k=(r['g'],r['time']);z=weights.setdefault(k,{'rows':0,'coefficient':Q(0)if den else None});z['rows']+=1\r\n   if den:z['coefficient']+=r['projectionCoefficient']\r\n return {'ledger':ledger,'rows':rows,'num':num,'den':den,'beta':beta,'weights':weights,'balancedEntities':len(good)}\r\ndef adjacent_pre(groups,g,t,step,control):\r\n b=t-step;T=[];C=[]\r\n for u in groups.values():\r\n  if u['g']==g:target=T\r\n  elif u['g']is None or(control=='notyet'and u['g']>max(t,b)):target=C\r\n  else:continue\r\n  before=u['rows'].get(b);after=u['rows'].get(t)\r\n  if before is not None and after is not None and before['y']is not None and after['y']is not None:target.append(after['y']-before['y'])\r\n return None if not T or not C else avg(T)-avg(C)\r\n\r\n\"\"\"New bounded teaching projections. The program is self-contained after build.\r\nExact Fraction finite algebra; figures and9-digit summary are approximations.\r\nIt is not a general parser/API replacement or a causal/inference certificate.\r\n\"\"\"\r\ndef paired(treated,control):\r\n def stats(rr):\r\n  use=[r for r in rr if r['before']is not None and r['after']is not None];delta=[Q(r['after'])-Q(r['before'])for r in use]\r\n  return dict(sourcePairs=len(rr),eligiblePairs=len(use),excludedPairs=len(rr)-len(use),meanBefore=avg([Q(r['before'])for r in use]),meanAfter=avg([Q(r['after'])for r in use]),meanChange=avg(delta),sampleChangeVariance=samplevar(delta))\r\n T,C=stats(treated),stats(control);defined=T['eligiblePairs']>0 and C['eligiblePairs']>0;estimate=T['meanChange']-C['meanChange']if defined else None;records=[]\r\n for group,rr,s in [('treated',treated,T),('control',control,C)]:\r\n  for r in rr:\r\n   before=None if r['before']is None else Q(r['before']);after=None if r['after']is None else Q(r['after']);eligible=before is not None and after is not None;delta=after-before if eligible else None;score=None if not defined else Q(0)if not eligible else(delta-s['meanChange'])/(s['eligiblePairs']if group=='treated'else-s['eligiblePairs']);records.append(dict(id=r['id'],role=group,before=before,after=after,eligible=eligible,change=delta,score=score))\r\n unbiased=None if not defined or T['eligiblePairs']<2 or C['eligiblePairs']<2 else T['sampleChangeVariance']/T['eligiblePairs']+C['sampleChangeVariance']/C['eligiblePairs'];hc0=None if not defined else sum((r['score']**2 for r in records),Q(0))\r\n return dict(defined=defined,estimate=estimate,treated=T,control=C,unbiasedVariance=unbiased,HC0=hc0,rows=records)\r\ndef literal_panel(raw):\r\n return[dict(r,y=None if r['y']is None else Q(r['y']),nativeID=r['entity'],sourceRow=i+1)for i,r in enumerate(raw)]\r\ndef att_projection(rows,control='never',step=1):\r\n G=panel(rows);times=sorted({r['time']for r in rows});cohorts=sorted({r['g']for r in rows if r['g']is not None});cells=[cell(G,g,t,step,control)for g in cohorts for t in times]\r\n return dict(sourceRows=len(rows),sourceEntities=len(G),step=step,control=control,cells=cells,covariance=covariance(cells))\r\ndef psd(V):\r\n A=[r[:]for r in V];rank=0\r\n while A:\r\n  if any(A[i][i]<0 for i in range(len(A))):raise ValueError('covariance-must-be-positive-semidefinite')\r\n  p=next((i for i in range(len(A))if A[i][i]>0),None)\r\n  if p is None:\r\n   if any(v for r in A for v in r):raise ValueError('covariance-must-be-positive-semidefinite')\r\n   return rank\r\n  A[0],A[p]=A[p],A[0]\r\n  for r in A:r[0],r[p]=r[p],r[0]\r\n  d=A[0][0];A=[[A[i][j]-A[i][0]*A[0][j]/d for j in range(1,len(A))]for i in range(1,len(A))];rank+=1\r\n return rank\r\ndef linear_aggregate(a):\r\n rr=[dict(r,estimate=None if r['estimate']is None else Q(r['estimate']),weight=Q(r['weight']))for r in a['cells']];V=[[Q(v)for v in r]for r in a['covariance']]if 'covariance'in a else None\r\n if V is not None:\r\n  assert len(V)==len(rr)and all(len(z)==len(rr)for z in V);assert all(V[i][j]==V[j][i]for i in range(len(rr))for j in range(len(rr)));rank=psd(V)\r\n else:rank=None\r\n selected=[i for i,r in enumerate(rr)if r['time']>=r['cohort']and r['weight']>0];weights={}\r\n if a.get('type','simple')=='simple':\r\n  mass=sum((rr[i]['weight']for i in selected),Q(0));weights={i:rr[i]['weight']/mass for i in selected}if mass else{}\r\n else:\r\n  gg=defaultdict(list)\r\n  for i in selected:gg[rr[i]['cohort']].append(i)\r\n  assert all(len({rr[i]['weight']for i in ii})==1 for ii in gg.values());mass=sum((rr[ii[0]]['weight']for ii in gg.values()),Q(0));weights={i:rr[ii[0]]['weight']/mass/len(ii)for ii in gg.values()for i in ii}if mass else{}\r\n estimate=None if not weights or any(rr[i]['estimate']is None for i in weights)else sum((w*rr[i]['estimate']for i,w in weights.items()),Q(0));variance=None if estimate is None or V is None else sum((x*y*V[i][j]for i,x in weights.items()for j,y in weights.items()),Q(0))\r\n return dict(type=a.get('type','simple'),defined=estimate is not None,estimate=estimate,variance=variance,covarianceRank=rank,weights=[dict(sourceIndex=i,cohort=rr[i]['cohort'],time=rr[i]['time'],coefficient=w,estimate=rr[i]['estimate'],contribution=None if rr[i]['estimate']is None else w*rr[i]['estimate'])for i,w in weights.items()],cells=rr,covariance=V)\r\ndef sensitivity_fixed(a):\r\n estimate=Q(a['estimate']);M=Q(a['M']);h=a.get('horizon',1);assert M>=0 and h>=1\r\n pre=[Q(v)for v in a.get('preDifferences',[])];scale=Q(a['scale'])if 'scale'in a else max(map(abs,pre))if pre else None;budget=None if scale is None else M*scale*h\r\n return dict(defined=scale is not None,estimate=estimate,scale=scale,M=M,horizon=h,biasBudget=budget,lower=None if budget is None else estimate-budget,upper=None if budget is None else estimate+budget,preDifferences=pre,confidenceLevel=None)\r\ndef realdata_fixed(kind,data):\r\n models,raw=source(data);rows=models[kind];G=panel(rows);times=sorted({r['time']for r in rows});step=STEP[kind];aa=att_projection(rows,'never',step);post=[r for r in aa['cells']if r['phase']=='post'];aggs=aggregate(post,covariance(post),step);tf=twfe(G,times)\r\n return dict(kind=kind,unit=UNIT[kind],periodUnit=CLOCK[kind],nativeRows=len(raw[kind]),modelRows=len(rows),entities=len(G),sourceRows=rows,att=aa,aggregations=aggs,twfe=tf,scope='Complete source frame; never-treated comparison,universal baseline,no anticipation. Native/model/paired/balanced denominators differ. All sampling/causal assumptions remain separate.')\r\ndef encode(v):\r\n if isinstance(v,Q):return str(v)\r\n if isinstance(v,dict):return{str(k):encode(x)for k,x in v.items()}\r\n if isinstance(v,(list,tuple)):return[encode(x)for x in v]\r\n return v\r\ndef v9(v):\r\n if v is None:return'undefined'\r\n if isinstance(v,str):return v\r\n if isinstance(v,bool):return'1'if v else'0'\r\n return format(float(v),'.9g')\r\ndef run_fixed(spec,out,data):\r\n api=spec['api'];a=spec['input'];summary={};points=[]\r\n def emit(series,x,y):points.append(dict(series=series,x=x,y=y,numericY=safe_float(y)))\r\n if api=='twobytwo':\r\n  result=paired(a['treated'],a['control']);summary=dict(defined=result['defined'],estimate=result['estimate'],treatedPairs=result['treated']['eligiblePairs'],controlPairs=result['control']['eligiblePairs'],unbiasedVariance=result['unbiasedVariance'],HC0=result['HC0'])\r\n  for i,r in enumerate(result['rows']):emit(r['role']+':'+r['id'],i+1,r['change'])\r\n elif api=='att':\r\n  result=att_projection(literal_panel(a['rows']),a.get('control','never'));summary=dict(sourceRows=result['sourceRows'],entities=result['sourceEntities'],cells=len(result['cells']),supportedCells=sum(r['defined']for r in result['cells']),postCells=sum(r['phase']=='post'for r in result['cells']))\r\n  for i,r in enumerate(result['cells']):emit('g'+str(r['g'])+':t'+str(r['t']),i+1,r['estimate'])\r\n elif api=='aggregate':\r\n  result=linear_aggregate(a);summary=dict(defined=result['defined'],estimate=result['estimate'],variance=result['variance'],covarianceRank=result['covarianceRank'],sumWeights=sum((r['coefficient']for r in result['weights']),Q(0)))\r\n  for i,r in enumerate(result['weights']):emit('g'+str(r['cohort'])+':t'+str(r['time']),i+1,r['contribution'])\r\n elif api=='twfe':\r\n  rows=literal_panel(a['rows']);G=panel(rows);result=twfe(G,sorted({r['time']for r in rows}));summary=dict(defined=result['beta']is not None,beta=result['beta'],numerator=result['num'],denominator=result['den'],balancedEntities=result['balancedEntities'],negativeTreatedCells=sum(v['coefficient']is not None and v['coefficient']<0 for v in result['weights'].values()))\r\n  for i,((g,t),r)in enumerate(sorted(result['weights'].items())):emit('g'+str(g)+':t'+str(t),i+1,r['coefficient'])\r\n elif api=='sensitivity':\r\n  result=sensitivity_fixed(a);summary={k:result[k]for k in['defined','estimate','scale','M','horizon','biasBudget','lower','upper']}\r\n  for i,k in enumerate(['lower','estimate','upper']):emit(k,i+1,result[k]if result['defined']else None)\r\n else:\r\n  result=realdata_fixed(a['kind'],data);post=[r for r in result['att']['cells']if r['phase']=='post'];s=next(r for r in result['aggregations']if r['type']=='simple');g=next(r for r in result['aggregations']if r['type']=='group'and r['key']=='overall');summary=dict(nativeRows=result['nativeRows'],modelRows=result['modelRows'],entities=result['entities'],postCells=len(post),simple=s['estimate'],group=g['estimate'],TWFE=result['twfe']['beta'],balancedEntities=result['twfe']['balancedEntities'])\r\n  for i,r in enumerate(post):emit('g'+str(r['g'])+':t'+str(r['t']),i+1,r['estimate'])\r\n out.mkdir(parents=True,exist_ok=True)\r\n if any(out.iterdir()):raise ValueError('use-new-empty-output-directory')\r\n shown={k:v9(v)for k,v in summary.items()};write(out/'summary.csv',[dict(name=k,value=v)for k,v in shown.items()]);write(out/'points.csv',points,['series','x','y','numericY']);full=dict(chapter='METR-20',profile=spec['id'],api=api,input=spec['input'],summary=shown,points=encode(points),details=encode(result),arithmetic='Python Fraction exact finite stored values;summary/plot approximate;bounded teaching projection,not causal or sampling certification')\r\n (out/'full.json').write_text(json.dumps(full,ensure_ascii=False,indent=2,allow_nan=False)+'\\n',encoding='utf8')\r\n import matplotlib\r\n matplotlib.use('Agg')\r\n import matplotlib.pyplot as plt\r\n plt.rcParams.update({'svg.fonttype':'none','font.family':'DejaVu Sans','font.size':12,'axes.spines.top':False,'axes.spines.right':False});fig,ax=plt.subplots(figsize=(9,5.6));good=[r for r in points if r['numericY']is not None]\r\n if good:\r\n  ax.scatter([r['x']for r in good],[r['numericY']for r in good],color='#315d7c',s=32);ax.axhline(0,color='#9eabb2',lw=.8);ax.set_xlabel('Declared cell/unit/bound ordinal')\r\n else:ax.text(.5,.5,'Undefined: no supported plotted quantity',ha='center',va='center',transform=ax.transAxes);ax.set_xticks([]);ax.set_yticks([])\r\n ax.set_ylabel('Cell weight'if api=='twfe'else result.get('unit','Stated outcome/bias units'));ax.set_title(spec['title']['en'],wrap=True,pad=14);ax.grid(axis='y',alpha=.2);fig.tight_layout(pad=2);fig.savefig(out/'plot.svg');plt.close(fig);print(json.dumps(shown))\r\n\r\nSPEC={'id': 'aggregate-cohort-weighted', 'api': 'aggregate', 'title': {'ko': '시점 평균 뒤 코호트를 같은 비중으로', 'en': 'Equal cohort weights after averaging times'}, 'input': {'cells': [{'cohort': 1, 'time': 1, 'estimate': '1', 'weight': '1'}, {'cohort': 1, 'time': 2, 'estimate': '1', 'weight': '1'}, {'cohort': 1, 'time': 3, 'estimate': '20', 'weight': '1'}, {'cohort': 3, 'time': 3, 'estimate': '1', 'weight': '1'}], 'type': 'group', 'covariance': [['1', '0', '0', '0'], ['0', '1', '0', '0'], ['0', '0', '1', '0'], ['0', '0', '0', '1']]}, 'expectedReject': False}\r\nif __name__=='__main__':\r\n import sys\r\n run_fixed(SPEC,Path(sys.argv[1]),Path(sys.argv[2])if len(sys.argv)>2 else Path(__file__).resolve().parent.parent/'metr20-sources')\r\n",
      "arithmetic": "Python Fraction exact stored finite values;logs/summary/plots approximate",
      "summary": {
        "defined": "1",
        "estimate": "4.16666667",
        "variance": "0.333333333",
        "covarianceRank": "4",
        "sumWeights": "1"
      },
      "fullResultEmbedded": false,
      "plotEmbedded": false,
      "full": {
        "summary": {
          "defined": "1",
          "estimate": "4.16666667",
          "variance": "0.333333333",
          "covarianceRank": "4",
          "sumWeights": "1"
        },
        "notice": "Complete source/finite projection is retained in the linked external JSON; this short projection is not the full result."
      },
      "plot": null,
      "points": [
        {
          "series": "g1:t1",
          "x": 1,
          "y": "1/6",
          "numericY": 0.16666666666666666
        },
        {
          "series": "g1:t2",
          "x": 2,
          "y": "1/6",
          "numericY": 0.16666666666666666
        },
        {
          "series": "g1:t3",
          "x": 3,
          "y": "10/3",
          "numericY": 3.3333333333333335
        },
        {
          "series": "g3:t3",
          "x": 4,
          "y": "1/2",
          "numericY": 0.5
        }
      ],
      "summaryFile": "metr20-programs/aggregate-cohort-weighted-python-summary.csv",
      "summarySHA256": "3401b9317cc866f956fc82d6dd09790f1cd6706a2079aedadf5439f9e3064ce1",
      "pointsFile": "metr20-programs/aggregate-cohort-weighted-python-points.csv",
      "pointsSHA256": "b5aff6b60e459242b59bd333ec087114a157f91d2ace37834664182118b28d10",
      "fullResultFile": "metr20-programs/aggregate-cohort-weighted-python.json",
      "fullResultSHA256": "8c4f3a85931471cf63895112c2ca2c70026c312debdb0148cbdad4ef99a46252",
      "plotFile": "metr20-programs/aggregate-cohort-weighted-python.svg",
      "plotSHA256": "062a73f35a8857895f8c9d4d5811c1e92bb884a842b679f3112d8b6a440762e2"
    },
    {
      "api": "aggregate",
      "variant": "aggregate-cohort-weighted",
      "profile": "aggregate-cohort-weighted",
      "language": "R",
      "file": "metr20-programs/aggregate-cohort-weighted-r.R",
      "codeSHA256": "bd6e89d241146bc7f2c96591aadd05662f3899a97fb024d36255c294644409af",
      "returnCode": 0,
      "expectedRejection": false,
      "title": {
        "ko": "시점 평균 뒤 코호트를 같은 비중으로",
        "en": "Equal cohort weights after averaging times"
      },
      "code": "# METR20 fixed example. Base R only, finite arithmetic approximate.\r\n# No JavaScript engine,model JSON,derived answer table,private module or internet.\r\noptions(stringsAsFactors=FALSE,digits=17)\r\nargv<-commandArgs(trailingOnly=TRUE);if(length(argv)<1L)stop('Supply a new empty output directory')\r\noutdir<-argv[1];script<-sub('^--file=','',commandArgs(FALSE)[grepl('^--file=',commandArgs(FALSE))][1]);here<-dirname(normalizePath(script,mustWork=TRUE));datadir<-if(length(argv)>=2L)argv[2]else file.path(here,'..','metr20-sources')\r\nunits<-c(country='log teen-employment points',person='recorded real earnings',company='FTE employees');clocks<-c(country='calendar year',person='calendar year',company='survey-wave index');steps<-c(country=1,person=3,company=1);files<-c(country='actual2500-county-mpdta-all6-fields.csv',person='actual38408-NSW-all15-fields.csv',company='actual410-NJPA-all46-fields.csv')\r\nnum<-function(s)ifelse(s=='.',NA_real_,as.numeric(s));mean0<-function(v)if(length(v))mean(v)else NA_real_;var0<-function(v)if(length(v)>1L)sum((v-mean(v))^2)/(length(v)-1L)else NA_real_\r\n\r\nSPEC<-list(id=\"aggregate-cohort-weighted\",api=\"aggregate\",title=list(ko=\"시점 평균 뒤 코호트를 같은 비중으로\",en=\"Equal cohort weights after averaging times\"),input=list(cells=list(list(cohort=1,time=1,estimate=\"1\",weight=\"1\"),list(cohort=1,time=2,estimate=\"1\",weight=\"1\"),list(cohort=1,time=3,estimate=\"20\",weight=\"1\"),list(cohort=3,time=3,estimate=\"1\",weight=\"1\")),type=\"group\",covariance=list(list(\"1\",\"0\",\"0\",\"0\"),list(\"0\",\"1\",\"0\",\"0\"),list(\"0\",\"0\",\"1\",\"0\"),list(\"0\",\"0\",\"0\",\"1\"))),expectedReject=FALSE)\r\npanel<-function(rows){G<-list();for(r in rows){key<-r$entity;u<-G[[key]];if(is.null(u))u<-list(g=r$g,rows=list());stopifnot(identical(u$g,r$g),is.null(u$rows[[as.character(r$time)]]));u$rows[[as.character(r$time)]]<-r;G[[key]]<-u};G}\r\ncell<-function(G,g,t,step,control){b<-g-step;members<-list();T<-C<-list();for(key in names(G)){u<-G[[key]];target<-!is.na(u$g)&&u$g==g;comp<-is.na(u$g)||(control=='notyet'&&!is.na(u$g)&&u$g>max(t,b));role<-if(target)'treated'else if(comp)'control'else'excluded-comparison';before<-u$rows[[as.character(b)]];after<-u$rows[[as.character(t)]];yb<-if(is.null(before))NA_real_ else before$y;ya<-if(is.null(after))NA_real_ else after$y;eligible<-role!='excluded-comparison'&&!is.na(yb)&&!is.na(ya);reason<-if(role=='excluded-comparison')'target-or-already-exposed-cohort-not-valid-control'else if(is.null(before))'baseline-source-row-absent'else if(is.null(after))'target-time-source-row-absent'else if(is.na(yb))'baseline-outcome-missing'else if(is.na(ya))'target-outcome-missing'else'';m<-list(entity=key,nativeID=u$rows[[1]]$nativeID,g=u$g,role=role,eligible=eligible,baselineSourceId=if(is.null(before))NA_character_ else before$id,targetSourceId=if(is.null(after))NA_character_ else after$id,before=yb,after=ya,change=if(eligible)ya-yb else NA_real_,reason=reason);members[[key]]<-m;if(eligible){if(role=='treated')T[[length(T)+1L]]<-m else C[[length(C)+1L]]<-m}}\r\n change<-function(a)vapply(a,function(r)r$change,0);d<-mean0(change(T));e<-mean0(change(C));estimate<-if(is.na(d)||is.na(e))NA_real_ else d-e;defined<-!is.na(estimate);scores<-setNames(rep(NA_real_,length(members)),names(members));for(key in names(members)){m<-members[[key]];s<-if(!defined)NA_real_ else if(!m$eligible)0 else if(m$role=='treated')(m$change-d)/length(T)else-(m$change-e)/length(C);m$score<-s;scores[key]<-s;members[[key]]<-m};st<-var0(change(T));sc<-var0(change(C));v<-if(is.na(st)||is.na(sc))NA_real_ else st/length(T)+sc/length(C);level<-function(a,k)mean0(vapply(a,function(r)r[[k]],0))\r\n list(g=g,t=t,baseline=b,event=(t-g)/step,phase=if(t==b)'mechanical-reference'else if(t>=g)'post'else'pre-placebo',defined=defined,estimate=estimate,T=T,C=C,members=members,scores=scores,HC0=if(defined)sum(scores^2)else NA_real_,unbiased=v,treatedMeanBefore=level(T,'before'),treatedMeanAfter=level(T,'after'),treatedMeanChange=d,controlMeanBefore=level(C,'before'),controlMeanAfter=level(C,'after'),controlMeanChange=e)\r\n}\r\ncovariance<-function(cells){n<-length(cells);V<-matrix(NA_real_,n,n);for(i in seq_len(n))for(j in seq_len(n))if(cells[[i]]$defined&&cells[[j]]$defined)V[i,j]<-sum(cells[[i]]$scores*cells[[j]]$scores);V}\r\naggregate_cells<-function(post,V,step){out<-list();push<-function(typ,key,ii,w){est<-if(!length(ii)||any(vapply(post[ii],function(z)is.na(z$estimate),TRUE)))NA_real_ else sum(w*vapply(post[ii],function(z)z$estimate,0));vv<-if(is.na(est)||anyNA(V[ii,ii,drop=FALSE]))NA_real_ else as.numeric(t(w)%*%V[ii,ii,drop=FALSE]%*%w);out[[length(out)+1L]]<<-list(type=typ,key=as.character(key),ii=ii,w=w,estimate=est,variance=vv)};positive<-which(vapply(post,function(c)length(c$T)>0L,TRUE));mass<-sum(vapply(post[positive],function(c)length(c$T),0));push('simple','overall',positive,if(mass)vapply(post[positive],function(c)length(c$T)/mass,0)else numeric())\r\n for(typ in c('event','calendar','group')){keys<-vapply(post,function(c)if(typ=='event')c$event else if(typ=='calendar')c$t else c$g,0);gg<-sort(unique(keys));cohortmass<-if(typ=='group')sum(vapply(gg,function(k)length(post[[which(keys==k)[1]]]$T),0))else 0;allii<-integer();allw<-numeric();for(key in gg){ii<-which(keys==key);jj<-ii[vapply(post[ii],function(c)length(c$T)>0L,TRUE)];if(typ=='group'){stopifnot(length(unique(vapply(post[ii],function(c)length(c$T),0)))<=1L);w<-if(length(jj))rep(1/length(jj),length(jj))else numeric();if(cohortmass){allii<-c(allii,jj);allw<-c(allw,w*length(post[[ii[1]]]$T)/cohortmass)}}else{total<-sum(vapply(post[jj],function(c)length(c$T),0));w<-if(total)vapply(post[jj],function(c)length(c$T)/total,0)else numeric()};push(typ,key,jj,w)};if(typ=='group')push(typ,'overall',allii,allw)};out}\r\ntwfe<-function(G,times){ledger<-list();good<-list();for(key in names(G)){u<-G[[key]];absent<-times[!as.character(times)%in%names(u$rows)];missing<-times[vapply(times,function(t){r<-u$rows[[as.character(t)]];!is.null(r)&&is.na(r$y)},TRUE)];eligible<-length(times)>0L&&!length(absent)&&!length(missing);ledger[[length(ledger)+1L]]<-list(entity=key,g=u$g,nativeID=u$rows[[1]]$nativeID,eligible=eligible,absentTimes=paste(absent,collapse=','),missingOutcomeTimes=paste(missing,collapse=','),originalRows=length(u$rows));if(eligible)good[[key]]<-u};rows<-list();for(key in names(good))for(t in times){r<-good[[key]]$rows[[as.character(t)]];r$D<-as.integer(!is.na(r$g)&&t>=r$g);rows[[length(rows)+1L]]<-r};em<-lapply(good,function(u)list(D=mean(vapply(times,function(t)as.integer(!is.na(u$g)&&t>=u$g),0)),Y=mean(vapply(u$rows[as.character(times)],function(r)r$y,0))));tm<-lapply(times,function(t)list(D=mean(vapply(good,function(u)as.integer(!is.na(u$g)&&t>=u$g),0)),Y=mean(vapply(good,function(u)u$rows[[as.character(t)]]$y,0))));names(tm)<-as.character(times);gd<-mean0(vapply(rows,function(r)r$D,0));gy<-mean0(vapply(rows,function(r)r$y,0));num<-den<-0\r\n for(i in seq_along(rows)){r<-rows[[i]];r$residualD<-r$D-em[[r$entity]]$D-tm[[as.character(r$time)]]$D+gd;r$residualY<-r$y-em[[r$entity]]$Y-tm[[as.character(r$time)]]$Y+gy;num<-num+r$residualD*r$residualY;den<-den+r$residualD^2;rows[[i]]<-r};beta<-if(den!=0)num/den else NA_real_;weights<-list();for(i in seq_along(rows)){r<-rows[[i]];r$projectionCoefficient<-if(den!=0)r$residualD/den else NA_real_;r$regressionResidual<-if(!is.na(beta))r$residualY-beta*r$residualD else NA_real_;rows[[i]]<-r;if(r$D==1L){k<-paste(r$g,r$time,sep=':');z<-weights[[k]];if(is.null(z))z<-list(g=r$g,t=r$time,rows=0,coefficient=if(den!=0)0 else NA_real_);z$rows<-z$rows+1L;if(den!=0)z$coefficient<-z$coefficient+r$projectionCoefficient;weights[[k]]<-z}};list(ledger=ledger,rows=rows,num=num,den=den,beta=beta,weights=weights,balancedEntities=length(good))}\r\nadjacent_pre<-function(G,g,t,step,control){b<-t-step;T<-C<-numeric();for(u in G){target<-!is.na(u$g)&&u$g==g;comp<-is.na(u$g)||(control=='notyet'&&!is.na(u$g)&&u$g>max(t,b));if(!target&&!comp)next;before<-u$rows[[as.character(b)]];after<-u$rows[[as.character(t)]];if(!is.null(before)&&!is.null(after)&&!is.na(before$y)&&!is.na(after$y)){if(target)T<-c(T,after$y-before$y)else C<-c(C,after$y-before$y)}};if(!length(T)||!length(C))NA_real_ else mean(T)-mean(C)}\r\n\r\n# Newly authored bounded teaching projections; base R finite approximation.\r\n# Source helper functions are inlined in each public file, never imported.\r\nqnum<-function(v){if(is.null(v)||is.na(v))return(NA_real_);s<-strsplit(as.character(v),'/',fixed=TRUE)[[1]];if(length(s)==1L)as.numeric(s)else as.numeric(s[1])/as.numeric(s[2])}\r\npaired<-function(T,C){\r\n stats<-function(rr){use<-Filter(function(r)!is.na(qnum(r$before))&&!is.na(qnum(r$after)),rr);a<-vapply(use,function(r)qnum(r$before),0);b<-vapply(use,function(r)qnum(r$after),0);list(sourcePairs=length(rr),eligiblePairs=length(use),excludedPairs=length(rr)-length(use),meanBefore=mean0(a),meanAfter=mean0(b),meanChange=mean0(b-a),sampleChangeVariance=var0(b-a))}\r\n st<-stats(T);sc<-stats(C);defined<-st$eligiblePairs>0L&&sc$eligiblePairs>0L;estimate<-if(defined)st$meanChange-sc$meanChange else NA_real_;rr<-list()\r\n for(role in c('treated','control')){input<-if(role=='treated')T else C;s<-if(role=='treated')st else sc;for(r in input){before<-qnum(r$before);after<-qnum(r$after);eligible<-!is.na(before)&&!is.na(after);change<-if(eligible)after-before else NA_real_;score<-if(!defined)NA_real_ else if(!eligible)0 else (change-s$meanChange)/(if(role=='treated')s$eligiblePairs else -s$eligiblePairs);rr[[length(rr)+1L]]<-list(id=r$id,role=role,before=before,after=after,eligible=eligible,change=change,score=score)}}\r\n list(defined=defined,estimate=estimate,treated=st,control=sc,unbiasedVariance=if(defined&&st$eligiblePairs>=2L&&sc$eligiblePairs>=2L)st$sampleChangeVariance/st$eligiblePairs+sc$sampleChangeVariance/sc$eligiblePairs else NA_real_,HC0=if(defined)sum(vapply(rr,function(r)r$score^2,0))else NA_real_,rows=rr)\r\n}\r\nliteral_panel<-function(rr)lapply(seq_along(rr),function(i){r<-rr[[i]];r$y<-qnum(r$y);r$nativeID<-r$entity;r$sourceRow<-i;r})\r\natt_projection<-function(rows,control='never',step=1){G<-panel(rows);times<-sort(unique(vapply(rows,function(r)r$time,0)));cohorts<-sort(unique(na.omit(vapply(rows,function(r)r$g,0))));cells<-list();for(g in cohorts)for(t in times)cells[[length(cells)+1L]]<-cell(G,g,t,step,control);list(sourceRows=length(rows),sourceEntities=length(G),step=step,control=control,cells=cells,covariance=covariance(cells))}\r\nlinear_aggregate<-function(a){\r\n rr<-lapply(a$cells,function(r){r$estimate<-qnum(r$estimate);r$weight<-qnum(r$weight);r});V<-if(is.null(a$covariance))NULL else do.call(rbind,lapply(a$covariance,function(r)vapply(r,qnum,0)));rank<-NA_real_\r\n if(!is.null(V)){stopifnot(nrow(V)==length(rr),ncol(V)==length(rr),all(V==t(V)));ev<-eigen(V,symmetric=TRUE,only.values=TRUE)$values;if(any(ev< -1e-12))stop('covariance-must-be-positive-semidefinite');rank<-sum(ev>1e-12)}\r\n selected<-which(vapply(rr,function(r)r$time>=r$cohort&&r$weight>0,TRUE));w<-numeric(length(rr));type<-if(is.null(a$type))'simple'else a$type\r\n if(type=='simple'){mass<-sum(vapply(rr[selected],function(r)r$weight,0));if(mass>0)for(i in selected)w[i]<-rr[[i]]$weight/mass}else{g<-vapply(rr,function(r)r$cohort,0);gg<-sort(unique(g[selected]));mass<-sum(vapply(gg,function(gi)rr[[intersect(which(g==gi),selected)[1]]]$weight,0));for(gi in gg){ii<-intersect(which(g==gi),selected);stopifnot(length(unique(vapply(rr[ii],function(r)r$weight,0)))==1L);w[ii]<-rr[[ii[1]]]$weight/mass/length(ii)}}\r\n used<-which(w>0);estimate<-if(!length(used)||any(vapply(rr[used],function(r)is.na(r$estimate),TRUE)))NA_real_ else sum(w[used]*vapply(rr[used],function(r)r$estimate,0));variance<-if(is.na(estimate)||is.null(V))NA_real_ else as.numeric(t(w)%*%V%*%w);weights<-lapply(used,function(i)list(sourceIndex=i-1L,cohort=rr[[i]]$cohort,time=rr[[i]]$time,coefficient=w[i],estimate=rr[[i]]$estimate,contribution=w[i]*rr[[i]]$estimate))\r\n list(type=type,defined=!is.na(estimate),estimate=estimate,variance=variance,covarianceRank=rank,weights=weights,cells=rr,covariance=V)\r\n}\r\nsensitivity_fixed<-function(a){estimate<-qnum(a$estimate);M<-qnum(a$M);h<-if(is.null(a$horizon))1 else a$horizon;stopifnot(M>=0,h>=1);pre<-vapply(a$preDifferences,qnum,0);scale<-if(!is.null(a$scale))qnum(a$scale)else if(length(pre))max(abs(pre))else NA_real_;budget<-M*scale*h;list(defined=!is.na(scale),estimate=estimate,scale=scale,M=M,horizon=h,biasBudget=budget,lower=estimate-budget,upper=estimate+budget,preDifferences=as.list(pre),confidenceLevel=NULL)}\r\nrealdata_fixed<-function(kind){rows<-models[[kind]];G<-panel(rows);times<-sort(unique(vapply(rows,function(r)r$time,0)));step<-unname(steps[kind]);aa<-att_projection(rows,'never',step);post<-Filter(function(r)r$phase=='post',aa$cells);aggs<-aggregate_cells(post,covariance(post),step);tf<-twfe(G,times);list(kind=kind,unit=unname(units[kind]),periodUnit=unname(clocks[kind]),nativeRows=nrow(raw[[kind]]),modelRows=length(rows),entities=length(G),sourceRows=rows,att=aa,aggregations=aggs,twfe=tf,scope='Complete native/model/paired/balanced source frames; never control,universal base,no anticipation;not causal/sampling certification.')}\r\n# JSON encoder deliberately handles matrices and scalar/vector distinctions.\r\nencode<-function(x){\r\n if(is.null(x))return('null')\r\n quote<-function(s){s<-gsub('\\\\','\\\\\\\\',as.character(s),fixed=TRUE);s<-gsub('\"','\\\\\"',s,fixed=TRUE);s<-gsub('\\n','\\\\n',s,fixed=TRUE);s<-gsub('\\r','\\\\r',s,fixed=TRUE);s<-gsub('\\t','\\\\t',s,fixed=TRUE);paste0('\"',s,'\"')}\r\n if(is.matrix(x))return(paste0('[',paste(vapply(seq_len(nrow(x)),function(i)encode(as.list(unname(x[i,]))),''),collapse=','),']'))\r\n if(is.list(x)){if(length(x)&&!is.null(names(x)))return(paste0('{',paste(paste0(vapply(names(x),quote,''),':',vapply(x,encode,'')),collapse=','),'}'));return(paste0('[',paste(vapply(x,encode,''),collapse=','),']'))}\r\n if(length(x)!=1L)return(encode(as.list(unname(x))))\r\n if(is.na(x))return('null');if(is.logical(x))return(if(x)'true'else'false');if(is.numeric(x))return(sprintf('%.17g',unname(x)));quote(x)\r\n}\r\nv9<-function(x){if(is.null(x)||is.na(x))return('undefined');if(is.logical(x))return(if(x)'1'else'0');if(is.numeric(x))return(sprintf('%.9g',unname(x)));as.character(x)}\r\nrun_fixed<-function(spec,out){api<-spec$api;a<-spec$input;summary<-list();points<-list();emit<-function(series,x,y){points[[length(points)+1L]]<<-list(series=series,x=x,y=y,numericY=y)}\r\n if(api=='twobytwo'){result<-paired(a$treated,a$control);summary<-list(defined=result$defined,estimate=result$estimate,treatedPairs=result$treated$eligiblePairs,controlPairs=result$control$eligiblePairs,unbiasedVariance=result$unbiasedVariance,HC0=result$HC0);for(i in seq_along(result$rows)){r<-result$rows[[i]];emit(paste(r$role,r$id,sep=':'),i,r$change)}}\r\n else if(api=='att'){result<-att_projection(literal_panel(a$rows),a$control);summary<-list(sourceRows=result$sourceRows,entities=result$sourceEntities,cells=length(result$cells),supportedCells=sum(vapply(result$cells,function(r)r$defined,TRUE)),postCells=sum(vapply(result$cells,function(r)r$phase=='post',TRUE)));for(i in seq_along(result$cells)){r<-result$cells[[i]];emit(paste0('g',r$g,':t',r$t),i,r$estimate)}}\r\n else if(api=='aggregate'){result<-linear_aggregate(a);summary<-list(defined=result$defined,estimate=result$estimate,variance=result$variance,covarianceRank=result$covarianceRank,sumWeights=sum(vapply(result$weights,function(r)r$coefficient,0)));for(i in seq_along(result$weights)){r<-result$weights[[i]];emit(paste0('g',r$cohort,':t',r$time),i,r$contribution)}}\r\n else if(api=='twfe'){rows<-literal_panel(a$rows);G<-panel(rows);result<-twfe(G,sort(unique(vapply(rows,function(r)r$time,0))));summary<-list(defined=!is.na(result$beta),beta=result$beta,numerator=result$num,denominator=result$den,balancedEntities=result$balancedEntities,negativeTreatedCells=sum(vapply(result$weights,function(r)!is.na(r$coefficient)&&r$coefficient<0,TRUE)));if(length(result$weights)){ord<-order(vapply(result$weights,function(r)r$g,0),vapply(result$weights,function(r)r$t,0));for(i in seq_along(ord)){r<-result$weights[[ord[i]]];emit(paste0('g',r$g,':t',r$t),i,r$coefficient)}}}\r\n else if(api=='sensitivity'){result<-sensitivity_fixed(a);summary<-result[c('defined','estimate','scale','M','horizon','biasBudget','lower','upper')];for(i in seq_along(c('lower','estimate','upper'))){k<-c('lower','estimate','upper')[i];emit(k,i,if(result$defined)result[[k]]else NA_real_)}}\r\n else{result<-realdata_fixed(a$kind);post<-Filter(function(r)r$phase=='post',result$att$cells);simple<-Filter(function(r)r$type=='simple',result$aggregations)[[1]];group<-Filter(function(r)r$type=='group'&&r$key=='overall',result$aggregations)[[1]];summary<-list(nativeRows=result$nativeRows,modelRows=result$modelRows,entities=result$entities,postCells=length(post),simple=simple$estimate,group=group$estimate,TWFE=result$twfe$beta,balancedEntities=result$twfe$balancedEntities);for(i in seq_along(post)){r<-post[[i]];emit(paste0('g',r$g,':t',r$t),i,r$estimate)}}\r\n dir.create(out,recursive=TRUE,showWarnings=FALSE);if(length(list.files(out,all.files=TRUE,no..=TRUE)))stop('use-new-empty-output-directory');shown<-lapply(summary,v9);write.csv(data.frame(name=names(shown),value=unlist(shown,use.names=FALSE)),file.path(out,'summary.csv'),row.names=FALSE,na='');pointframe<-if(length(points))do.call(rbind,lapply(points,function(p)data.frame(series=p$series,x=p$x,y=p$y,numericY=p$numericY,stringsAsFactors=FALSE)))else data.frame(series=character(),x=numeric(),y=numeric(),numericY=numeric());write.csv(pointframe,file.path(out,'points.csv'),row.names=FALSE,na='');full<-list(chapter='METR-20',profile=spec$id,api=api,input=spec$input,summary=shown,points=points,details=result,arithmetic='Base R approximate finite values;bounded teaching projection,not exact fractions or causal/sampling certification.');writeLines(encode(full),file.path(out,'full.json'),useBytes=TRUE)\r\n svg(file.path(out,'plot.svg'),width=9,height=5.6,pointsize=12);par(mar=c(4.5,5.5,4,1));good<-pointframe[!is.na(pointframe$numericY),,drop=FALSE]\r\n if(nrow(good)){plot(good$x,good$numericY,pch=19,col='#315d7c',xlab='Declared cell/unit/bound ordinal',ylab=if(api=='twfe')'Cell weight'else if(!is.null(result$unit))result$unit else 'Stated outcome/bias units',main=spec$title$en);abline(h=0,col='#9eabb2');grid(nx=NA,ny=NULL,col='#e2e5e7');points(good$x,good$numericY,pch=19,col='#315d7c')}else{plot.new();text(.5,.5,'Undefined: no supported plotted quantity');title(main=spec$title$en)};dev.off();cat(encode(shown),'\\n')\r\n}\r\n\r\nrun_fixed(SPEC,outdir)\r\n",
      "arithmetic": "Base R approximate finite arithmetic;not an exact rational result",
      "summary": {
        "defined": "1",
        "estimate": "4.16666667",
        "variance": "0.333333333",
        "covarianceRank": "4",
        "sumWeights": "1"
      },
      "fullResultEmbedded": false,
      "plotEmbedded": false,
      "full": {
        "summary": {
          "defined": "1",
          "estimate": "4.16666667",
          "variance": "0.333333333",
          "covarianceRank": "4",
          "sumWeights": "1"
        },
        "notice": "Complete source/finite projection is retained in the linked external JSON; this short projection is not the full result."
      },
      "plot": null,
      "points": [
        {
          "series": "g1:t1",
          "x": 1,
          "y": 0.16666666666666666,
          "numericY": 0.16666666666666666
        },
        {
          "series": "g1:t2",
          "x": 2,
          "y": 0.16666666666666666,
          "numericY": 0.16666666666666666
        },
        {
          "series": "g1:t3",
          "x": 3,
          "y": 3.333333333333333,
          "numericY": 3.333333333333333
        },
        {
          "series": "g3:t3",
          "x": 4,
          "y": 0.5,
          "numericY": 0.5
        }
      ],
      "summaryFile": "metr20-programs/aggregate-cohort-weighted-r-summary.csv",
      "summarySHA256": "861cae1f80db60fc63bcce89159f3fc3b0b5f531dfa3ac7fdd329218ca508fe8",
      "pointsFile": "metr20-programs/aggregate-cohort-weighted-r-points.csv",
      "pointsSHA256": "df23c8c24ed9be13b6a785b8edeb8fe00f1c7453e8959b2c000df7e96bd8e145",
      "fullResultFile": "metr20-programs/aggregate-cohort-weighted-r.json",
      "fullResultSHA256": "4ad426d2e7dc6f26f22f0888ebd1a9ad0359a0e049658cd8d3344a68e6739985",
      "plotFile": "metr20-programs/aggregate-cohort-weighted-r.svg",
      "plotSHA256": "c55faef09015b6bebcc17207d8f36c2b66ed5192894e42adae31054c8704b847"
    },
    {
      "api": "twfe",
      "variant": "twfe-negative-cell",
      "profile": "twfe-negative-cell",
      "language": "Python",
      "file": "metr20-programs/twfe-negative-cell-python.py",
      "codeSHA256": "33811562d5e1ef145a27b9a3fb16f0c65764a6c573a4231cd7d9ab93e0353bbe",
      "returnCode": 0,
      "expectedRejection": false,
      "title": {
        "ko": "양의 효과 네 개와 음의 투영 계수",
        "en": "Four positive effects and a negative projection"
      },
      "code": "\"\"\"METR20 actual sources. Python standard library, exact stored-value rationals.\r\nRead ONLY the three native-observation CSVs; no JS engine,model JSON,derived\r\nanswers,private modules or internet needed. Outcome measurement/identification\r\nand valid sampling inference remain separate from exact finite arithmetic.\r\nRun: python metr20-reproduce.py --data-dir PATH --out NEW_EMPTY_DIRECTORY\r\n\"\"\"\r\nfrom pathlib import Path\r\nfrom fractions import Fraction as Q\r\nfrom collections import defaultdict,Counter\r\nimport csv,json,math,argparse,hashlib\r\n\r\nUNIT={'country':'log teen-employment points','person':'recorded real earnings','company':'FTE employees'}\r\nCLOCK={'country':'calendar year','person':'calendar year','company':'survey-wave index'}\r\nSTEP={'country':1,'person':3,'company':1}\r\nFILES={'country':'actual2500-county-mpdta-all6-fields.csv','person':'actual38408-NSW-all15-fields.csv','company':'actual410-NJPA-all46-fields.csv'}\r\ndef avg(v):return sum(v,Q(0))/len(v)if v else None\r\ndef samplevar(v):return sum(((x-avg(v))**2 for x in v),Q(0))/(len(v)-1)if len(v)>1 else None\r\ndef binary(s):return None if s=='.'else Q.from_float(float(s))\r\ndef token(v):\r\n if v is None:return ''\r\n if isinstance(v,bool):return 'true'if v else'false'\r\n return str(v)\r\ndef safe_float(v):\r\n if v is None:return None\r\n try:r=float(v)\r\n except OverflowError:return None\r\n return r if math.isfinite(r)else None\r\ndef read(p):\r\n with p.open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))\r\ndef write(p,rows,head=None):\r\n if head is None:\r\n  assert rows;head=list(rows[0])\r\n with p.open('w',encoding='utf8',newline='')as f:\r\n  w=csv.DictWriter(f,fieldnames=head);w.writeheader();w.writerows({k:token(r.get(k))for k in head}for r in rows)\r\ndef source(data):\r\n raw={k:read(data/n)for k,n in FILES.items()};assert[len(raw[k])for k in FILES]==[2500,38408,410]\r\n models={k:[]for k in FILES}\r\n for r in raw['country']:\r\n  g0=int(r['first.treat']);g=None if g0==0 else g0;assert int(r['treat'])==int(g is not None)\r\n  models['country'].append(dict(id='mpdta:'+r['sourceRow'],entity='county:'+str(int(r['countyreal'])),time=int(r['year']),y=binary(r['lemp']),g=g,sourceRow=int(r['sourceRow']),nativeID=r['countyreal']))\r\n for r in raw['person']:\r\n  selected=int(r['experimental'])==1;assert selected==(int(r['sample'])==1);assert(r['treated']!='.')==selected\r\n  if selected:\r\n   d=int(r['treated']);assert d in[0,1]\r\n   models['person'].append(dict(id='nsw:'+r['sourceRow'],entity='nsw-id:'+str(int(r['id'])),time=int(r['year']),y=binary(r['re']),g=1978 if d else None,sourceRow=int(r['sourceRow']),nativeID=str(int(r['id']))))\r\n for r in raw['company']:\r\n  state=int(r['STATE']);assert state in[0,1]\r\n  for t,suffix in[(0,''),(1,'2')]:\r\n   a=[r[n+suffix]for n in['EMPFT','NMGRS','EMPPT']];y=None if'.'in a else Q(a[0])+Q(a[1])+Q(a[2])/2\r\n   models['company'].append(dict(id='njpa:'+r['sourceRow']+':wave'+str(t),entity='njpa-row:'+r['sourceRow'],time=t,y=y,g=1 if state else None,sourceRow=int(r['sourceRow']),nativeID=r['SHEET']))\r\n assert[len(models[k])for k in FILES]==[2500,1444,820]\r\n return models,raw\r\ndef panel(rows):\r\n groups={}\r\n for r in rows:\r\n  u=groups.setdefault(r['entity'],{'g':r['g'],'rows':{}});assert u['g']==r['g']and r['time']not in u['rows'];u['rows'][r['time']]=r\r\n return groups\r\ndef cell(groups,g,t,step,control):\r\n b=g-step;members=[];T=[];C=[]\r\n for key,u in groups.items():\r\n  role='treated'if u['g']==g else'control'if u['g']is None or(control=='notyet'and u['g']>max(t,b))else'excluded-comparison'\r\n  before=u['rows'].get(b);after=u['rows'].get(t);yb=None if before is None else before['y'];ya=None if after is None else after['y'];eligible=role!='excluded-comparison'and yb is not None and ya is not None\r\n  reason='target-or-already-exposed-cohort-not-valid-control'if role=='excluded-comparison'else'baseline-source-row-absent'if before is None else'target-time-source-row-absent'if after is None else'baseline-outcome-missing'if yb is None else'target-outcome-missing'if ya is None else''\r\n  m={'entity':key,'nativeID':next(iter(u['rows'].values()))['nativeID'],'g':u['g'],'role':role,'eligible':eligible,'baselineSourceId':None if before is None else before['id'],'targetSourceId':None if after is None else after['id'],'before':yb,'after':ya,'change':ya-yb if eligible else None,'reason':reason};members.append(m)\r\n  if eligible:(T if role=='treated'else C).append(m)\r\n d=avg([r['change']for r in T]);e=avg([r['change']for r in C]);estimate=None if d is None or e is None else d-e;defined=estimate is not None;scores={}\r\n for m in members:\r\n  s=None if not defined else Q(0)\r\n  if defined and m['eligible']:s=(m['change']-(d if m['role']=='treated'else e))/(len(T)if m['role']=='treated'else-len(C))\r\n  m['score']=s;scores[m['entity']]=s\r\n st=samplevar([r['change']for r in T]);sc=samplevar([r['change']for r in C]);v=None if st is None or sc is None else st/len(T)+sc/len(C)\r\n return {'g':g,'t':t,'baseline':b,'event':(t-g)//step,'phase':'mechanical-reference'if t==b else'post'if t>=g else'pre-placebo','defined':defined,'estimate':estimate,'T':T,'C':C,'members':members,'scores':scores,'HC0':None if not defined else sum((s*s for s in scores.values()),Q(0)),'unbiased':v,'treatedMeanBefore':avg([r['before']for r in T]),'treatedMeanAfter':avg([r['after']for r in T]),'treatedMeanChange':d,'controlMeanBefore':avg([r['before']for r in C]),'controlMeanAfter':avg([r['after']for r in C]),'controlMeanChange':e}\r\ndef covariance(cells):\r\n return[[None if not a['defined']or not b['defined']else sum((v*b['scores'][i]for i,v in a['scores'].items()),Q(0))for b in cells]for a in cells]\r\ndef aggregate(post,V,step):\r\n out=[]\r\n def push(typ,key,coeff):\r\n  estimate=None if not coeff or any(post[i]['estimate']is None for i in coeff)else sum((w*post[i]['estimate']for i,w in coeff.items()),Q(0));variance=None if estimate is None or any(V[i][j]is None for i in coeff for j in coeff)else sum((a*b*V[i][j]for i,a in coeff.items()for j,b in coeff.items()),Q(0));out.append({'type':typ,'key':key,'coeff':coeff,'estimate':estimate,'variance':variance})\r\n positive=[i for i,c in enumerate(post)if len(c['T'])>0];mass=sum(len(post[i]['T'])for i in positive)\r\n push('simple','overall',{i:Q(len(post[i]['T']),mass)for i in positive}if mass else{})\r\n for typ in['event','calendar','group']:\r\n  groups=defaultdict(list)\r\n  for i,c in enumerate(post):groups[c['event']if typ=='event'else c['t']if typ=='calendar'else c['g']].append(i)\r\n  overall={};cohortMass=sum(len(post[ii[0]]['T'])for ii in groups.values())if typ=='group'else 0\r\n  for key,ii in sorted(groups.items()):\r\n   jj=[i for i in ii if len(post[i]['T'])>0]\r\n   if typ=='group':\r\n    assert len({len(post[i]['T'])for i in ii})<=1\r\n    coeff={i:Q(1,len(jj))for i in jj}if jj else{}\r\n    if cohortMass:\r\n     for i,w in coeff.items():overall[i]=w*Q(len(post[ii[0]]['T']),cohortMass)\r\n   else:\r\n    total=sum(len(post[i]['T'])for i in jj);coeff={i:Q(len(post[i]['T']),total)for i in jj}if total else{}\r\n   push(typ,str(key),coeff)\r\n  if typ=='group':push(typ,'overall',overall)\r\n return out\r\ndef twfe(groups,times):\r\n ledger=[];good={}\r\n for key,u in groups.items():\r\n  absent=[t for t in times if t not in u['rows']];missing=[t for t in times if t in u['rows']and u['rows'][t]['y']is None];eligible=bool(times)and not absent and not missing\r\n  ledger.append({'entity':key,'g':u['g'],'nativeID':next(iter(u['rows'].values()))['nativeID'],'eligible':eligible,'absentTimes':','.join(map(str,absent)),'missingOutcomeTimes':','.join(map(str,missing)),'originalRows':len(u['rows'])})\r\n  if eligible:good[key]=u\r\n rows=[dict(**u['rows'][t],D=Q(u['g']is not None and t>=u['g']))for key,u in good.items()for t in times]\r\n em={k:{'D':avg([Q(u['g']is not None and t>=u['g'])for t in times]),'Y':avg([u['rows'][t]['y']for t in times])}for k,u in good.items()};tm={t:{'D':avg([Q(u['g']is not None and t>=u['g'])for u in good.values()]),'Y':avg([u['rows'][t]['y']for u in good.values()])}for t in times};gd=avg([r['D']for r in rows]);gy=avg([r['y']for r in rows]);num=den=Q(0)\r\n for r in rows:\r\n  r['residualD']=r['D']-em[r['entity']]['D']-tm[r['time']]['D']+gd;r['residualY']=r['y']-em[r['entity']]['Y']-tm[r['time']]['Y']+gy;num+=r['residualD']*r['residualY'];den+=r['residualD']**2\r\n beta=num/den if den else None;weights={}\r\n for r in rows:\r\n  r['projectionCoefficient']=r['residualD']/den if den else None;r['regressionResidual']=r['residualY']-beta*r['residualD']if beta is not None else None\r\n  if r['D']:\r\n   k=(r['g'],r['time']);z=weights.setdefault(k,{'rows':0,'coefficient':Q(0)if den else None});z['rows']+=1\r\n   if den:z['coefficient']+=r['projectionCoefficient']\r\n return {'ledger':ledger,'rows':rows,'num':num,'den':den,'beta':beta,'weights':weights,'balancedEntities':len(good)}\r\ndef adjacent_pre(groups,g,t,step,control):\r\n b=t-step;T=[];C=[]\r\n for u in groups.values():\r\n  if u['g']==g:target=T\r\n  elif u['g']is None or(control=='notyet'and u['g']>max(t,b)):target=C\r\n  else:continue\r\n  before=u['rows'].get(b);after=u['rows'].get(t)\r\n  if before is not None and after is not None and before['y']is not None and after['y']is not None:target.append(after['y']-before['y'])\r\n return None if not T or not C else avg(T)-avg(C)\r\n\r\n\"\"\"New bounded teaching projections. The program is self-contained after build.\r\nExact Fraction finite algebra; figures and9-digit summary are approximations.\r\nIt is not a general parser/API replacement or a causal/inference certificate.\r\n\"\"\"\r\ndef paired(treated,control):\r\n def stats(rr):\r\n  use=[r for r in rr if r['before']is not None and r['after']is not None];delta=[Q(r['after'])-Q(r['before'])for r in use]\r\n  return dict(sourcePairs=len(rr),eligiblePairs=len(use),excludedPairs=len(rr)-len(use),meanBefore=avg([Q(r['before'])for r in use]),meanAfter=avg([Q(r['after'])for r in use]),meanChange=avg(delta),sampleChangeVariance=samplevar(delta))\r\n T,C=stats(treated),stats(control);defined=T['eligiblePairs']>0 and C['eligiblePairs']>0;estimate=T['meanChange']-C['meanChange']if defined else None;records=[]\r\n for group,rr,s in [('treated',treated,T),('control',control,C)]:\r\n  for r in rr:\r\n   before=None if r['before']is None else Q(r['before']);after=None if r['after']is None else Q(r['after']);eligible=before is not None and after is not None;delta=after-before if eligible else None;score=None if not defined else Q(0)if not eligible else(delta-s['meanChange'])/(s['eligiblePairs']if group=='treated'else-s['eligiblePairs']);records.append(dict(id=r['id'],role=group,before=before,after=after,eligible=eligible,change=delta,score=score))\r\n unbiased=None if not defined or T['eligiblePairs']<2 or C['eligiblePairs']<2 else T['sampleChangeVariance']/T['eligiblePairs']+C['sampleChangeVariance']/C['eligiblePairs'];hc0=None if not defined else sum((r['score']**2 for r in records),Q(0))\r\n return dict(defined=defined,estimate=estimate,treated=T,control=C,unbiasedVariance=unbiased,HC0=hc0,rows=records)\r\ndef literal_panel(raw):\r\n return[dict(r,y=None if r['y']is None else Q(r['y']),nativeID=r['entity'],sourceRow=i+1)for i,r in enumerate(raw)]\r\ndef att_projection(rows,control='never',step=1):\r\n G=panel(rows);times=sorted({r['time']for r in rows});cohorts=sorted({r['g']for r in rows if r['g']is not None});cells=[cell(G,g,t,step,control)for g in cohorts for t in times]\r\n return dict(sourceRows=len(rows),sourceEntities=len(G),step=step,control=control,cells=cells,covariance=covariance(cells))\r\ndef psd(V):\r\n A=[r[:]for r in V];rank=0\r\n while A:\r\n  if any(A[i][i]<0 for i in range(len(A))):raise ValueError('covariance-must-be-positive-semidefinite')\r\n  p=next((i for i in range(len(A))if A[i][i]>0),None)\r\n  if p is None:\r\n   if any(v for r in A for v in r):raise ValueError('covariance-must-be-positive-semidefinite')\r\n   return rank\r\n  A[0],A[p]=A[p],A[0]\r\n  for r in A:r[0],r[p]=r[p],r[0]\r\n  d=A[0][0];A=[[A[i][j]-A[i][0]*A[0][j]/d for j in range(1,len(A))]for i in range(1,len(A))];rank+=1\r\n return rank\r\ndef linear_aggregate(a):\r\n rr=[dict(r,estimate=None if r['estimate']is None else Q(r['estimate']),weight=Q(r['weight']))for r in a['cells']];V=[[Q(v)for v in r]for r in a['covariance']]if 'covariance'in a else None\r\n if V is not None:\r\n  assert len(V)==len(rr)and all(len(z)==len(rr)for z in V);assert all(V[i][j]==V[j][i]for i in range(len(rr))for j in range(len(rr)));rank=psd(V)\r\n else:rank=None\r\n selected=[i for i,r in enumerate(rr)if r['time']>=r['cohort']and r['weight']>0];weights={}\r\n if a.get('type','simple')=='simple':\r\n  mass=sum((rr[i]['weight']for i in selected),Q(0));weights={i:rr[i]['weight']/mass for i in selected}if mass else{}\r\n else:\r\n  gg=defaultdict(list)\r\n  for i in selected:gg[rr[i]['cohort']].append(i)\r\n  assert all(len({rr[i]['weight']for i in ii})==1 for ii in gg.values());mass=sum((rr[ii[0]]['weight']for ii in gg.values()),Q(0));weights={i:rr[ii[0]]['weight']/mass/len(ii)for ii in gg.values()for i in ii}if mass else{}\r\n estimate=None if not weights or any(rr[i]['estimate']is None for i in weights)else sum((w*rr[i]['estimate']for i,w in weights.items()),Q(0));variance=None if estimate is None or V is None else sum((x*y*V[i][j]for i,x in weights.items()for j,y in weights.items()),Q(0))\r\n return dict(type=a.get('type','simple'),defined=estimate is not None,estimate=estimate,variance=variance,covarianceRank=rank,weights=[dict(sourceIndex=i,cohort=rr[i]['cohort'],time=rr[i]['time'],coefficient=w,estimate=rr[i]['estimate'],contribution=None if rr[i]['estimate']is None else w*rr[i]['estimate'])for i,w in weights.items()],cells=rr,covariance=V)\r\ndef sensitivity_fixed(a):\r\n estimate=Q(a['estimate']);M=Q(a['M']);h=a.get('horizon',1);assert M>=0 and h>=1\r\n pre=[Q(v)for v in a.get('preDifferences',[])];scale=Q(a['scale'])if 'scale'in a else max(map(abs,pre))if pre else None;budget=None if scale is None else M*scale*h\r\n return dict(defined=scale is not None,estimate=estimate,scale=scale,M=M,horizon=h,biasBudget=budget,lower=None if budget is None else estimate-budget,upper=None if budget is None else estimate+budget,preDifferences=pre,confidenceLevel=None)\r\ndef realdata_fixed(kind,data):\r\n models,raw=source(data);rows=models[kind];G=panel(rows);times=sorted({r['time']for r in rows});step=STEP[kind];aa=att_projection(rows,'never',step);post=[r for r in aa['cells']if r['phase']=='post'];aggs=aggregate(post,covariance(post),step);tf=twfe(G,times)\r\n return dict(kind=kind,unit=UNIT[kind],periodUnit=CLOCK[kind],nativeRows=len(raw[kind]),modelRows=len(rows),entities=len(G),sourceRows=rows,att=aa,aggregations=aggs,twfe=tf,scope='Complete source frame; never-treated comparison,universal baseline,no anticipation. Native/model/paired/balanced denominators differ. All sampling/causal assumptions remain separate.')\r\ndef encode(v):\r\n if isinstance(v,Q):return str(v)\r\n if isinstance(v,dict):return{str(k):encode(x)for k,x in v.items()}\r\n if isinstance(v,(list,tuple)):return[encode(x)for x in v]\r\n return v\r\ndef v9(v):\r\n if v is None:return'undefined'\r\n if isinstance(v,str):return v\r\n if isinstance(v,bool):return'1'if v else'0'\r\n return format(float(v),'.9g')\r\ndef run_fixed(spec,out,data):\r\n api=spec['api'];a=spec['input'];summary={};points=[]\r\n def emit(series,x,y):points.append(dict(series=series,x=x,y=y,numericY=safe_float(y)))\r\n if api=='twobytwo':\r\n  result=paired(a['treated'],a['control']);summary=dict(defined=result['defined'],estimate=result['estimate'],treatedPairs=result['treated']['eligiblePairs'],controlPairs=result['control']['eligiblePairs'],unbiasedVariance=result['unbiasedVariance'],HC0=result['HC0'])\r\n  for i,r in enumerate(result['rows']):emit(r['role']+':'+r['id'],i+1,r['change'])\r\n elif api=='att':\r\n  result=att_projection(literal_panel(a['rows']),a.get('control','never'));summary=dict(sourceRows=result['sourceRows'],entities=result['sourceEntities'],cells=len(result['cells']),supportedCells=sum(r['defined']for r in result['cells']),postCells=sum(r['phase']=='post'for r in result['cells']))\r\n  for i,r in enumerate(result['cells']):emit('g'+str(r['g'])+':t'+str(r['t']),i+1,r['estimate'])\r\n elif api=='aggregate':\r\n  result=linear_aggregate(a);summary=dict(defined=result['defined'],estimate=result['estimate'],variance=result['variance'],covarianceRank=result['covarianceRank'],sumWeights=sum((r['coefficient']for r in result['weights']),Q(0)))\r\n  for i,r in enumerate(result['weights']):emit('g'+str(r['cohort'])+':t'+str(r['time']),i+1,r['contribution'])\r\n elif api=='twfe':\r\n  rows=literal_panel(a['rows']);G=panel(rows);result=twfe(G,sorted({r['time']for r in rows}));summary=dict(defined=result['beta']is not None,beta=result['beta'],numerator=result['num'],denominator=result['den'],balancedEntities=result['balancedEntities'],negativeTreatedCells=sum(v['coefficient']is not None and v['coefficient']<0 for v in result['weights'].values()))\r\n  for i,((g,t),r)in enumerate(sorted(result['weights'].items())):emit('g'+str(g)+':t'+str(t),i+1,r['coefficient'])\r\n elif api=='sensitivity':\r\n  result=sensitivity_fixed(a);summary={k:result[k]for k in['defined','estimate','scale','M','horizon','biasBudget','lower','upper']}\r\n  for i,k in enumerate(['lower','estimate','upper']):emit(k,i+1,result[k]if result['defined']else None)\r\n else:\r\n  result=realdata_fixed(a['kind'],data);post=[r for r in result['att']['cells']if r['phase']=='post'];s=next(r for r in result['aggregations']if r['type']=='simple');g=next(r for r in result['aggregations']if r['type']=='group'and r['key']=='overall');summary=dict(nativeRows=result['nativeRows'],modelRows=result['modelRows'],entities=result['entities'],postCells=len(post),simple=s['estimate'],group=g['estimate'],TWFE=result['twfe']['beta'],balancedEntities=result['twfe']['balancedEntities'])\r\n  for i,r in enumerate(post):emit('g'+str(r['g'])+':t'+str(r['t']),i+1,r['estimate'])\r\n out.mkdir(parents=True,exist_ok=True)\r\n if any(out.iterdir()):raise ValueError('use-new-empty-output-directory')\r\n shown={k:v9(v)for k,v in summary.items()};write(out/'summary.csv',[dict(name=k,value=v)for k,v in shown.items()]);write(out/'points.csv',points,['series','x','y','numericY']);full=dict(chapter='METR-20',profile=spec['id'],api=api,input=spec['input'],summary=shown,points=encode(points),details=encode(result),arithmetic='Python Fraction exact finite stored values;summary/plot approximate;bounded teaching projection,not causal or sampling certification')\r\n (out/'full.json').write_text(json.dumps(full,ensure_ascii=False,indent=2,allow_nan=False)+'\\n',encoding='utf8')\r\n import matplotlib\r\n matplotlib.use('Agg')\r\n import matplotlib.pyplot as plt\r\n plt.rcParams.update({'svg.fonttype':'none','font.family':'DejaVu Sans','font.size':12,'axes.spines.top':False,'axes.spines.right':False});fig,ax=plt.subplots(figsize=(9,5.6));good=[r for r in points if r['numericY']is not None]\r\n if good:\r\n  ax.scatter([r['x']for r in good],[r['numericY']for r in good],color='#315d7c',s=32);ax.axhline(0,color='#9eabb2',lw=.8);ax.set_xlabel('Declared cell/unit/bound ordinal')\r\n else:ax.text(.5,.5,'Undefined: no supported plotted quantity',ha='center',va='center',transform=ax.transAxes);ax.set_xticks([]);ax.set_yticks([])\r\n ax.set_ylabel('Cell weight'if api=='twfe'else result.get('unit','Stated outcome/bias units'));ax.set_title(spec['title']['en'],wrap=True,pad=14);ax.grid(axis='y',alpha=.2);fig.tight_layout(pad=2);fig.savefig(out/'plot.svg');plt.close(fig);print(json.dumps(shown))\r\n\r\nSPEC={'id': 'twfe-negative-cell', 'api': 'twfe', 'title': {'ko': '양의 효과 네 개와 음의 투영 계수', 'en': 'Four positive effects and a negative projection'}, 'input': {'rows': [{'id': 'early:0', 'entity': 'early', 'time': 0, 'y': '0', 'g': 1}, {'id': 'early:1', 'entity': 'early', 'time': 1, 'y': '1', 'g': 1}, {'id': 'early:2', 'entity': 'early', 'time': 2, 'y': '1', 'g': 1}, {'id': 'early:3', 'entity': 'early', 'time': 3, 'y': '20', 'g': 1}, {'id': 'late:0', 'entity': 'late', 'time': 0, 'y': '0', 'g': 3}, {'id': 'late:1', 'entity': 'late', 'time': 1, 'y': '0', 'g': 3}, {'id': 'late:2', 'entity': 'late', 'time': 2, 'y': '0', 'g': 3}, {'id': 'late:3', 'entity': 'late', 'time': 3, 'y': '1', 'g': 3}, {'id': 'never:0', 'entity': 'never', 'time': 0, 'y': '0', 'g': None}, {'id': 'never:1', 'entity': 'never', 'time': 1, 'y': '0', 'g': None}, {'id': 'never:2', 'entity': 'never', 'time': 2, 'y': '0', 'g': None}, {'id': 'never:3', 'entity': 'never', 'time': 3, 'y': '0', 'g': None}]}, 'expectedReject': False}\r\nif __name__=='__main__':\r\n import sys\r\n run_fixed(SPEC,Path(sys.argv[1]),Path(sys.argv[2])if len(sys.argv)>2 else Path(__file__).resolve().parent.parent/'metr20-sources')\r\n",
      "arithmetic": "Python Fraction exact stored finite values;logs/summary/plots approximate",
      "summary": {
        "defined": "1",
        "beta": "-0.9",
        "numerator": "-0.75",
        "denominator": "0.833333333",
        "balancedEntities": "3",
        "negativeTreatedCells": "1"
      },
      "fullResultEmbedded": false,
      "plotEmbedded": false,
      "full": {
        "summary": {
          "defined": "1",
          "beta": "-0.9",
          "numerator": "-0.75",
          "denominator": "0.833333333",
          "balancedEntities": "3",
          "negativeTreatedCells": "1"
        },
        "notice": "Complete source/finite projection is retained in the linked external JSON; this short projection is not the full result."
      },
      "plot": null,
      "points": [
        {
          "series": "g1:t1",
          "x": 1,
          "y": "3/10",
          "numericY": 0.3
        },
        {
          "series": "g1:t2",
          "x": 2,
          "y": "3/10",
          "numericY": 0.3
        },
        {
          "series": "g1:t3",
          "x": 3,
          "y": "-1/10",
          "numericY": -0.1
        },
        {
          "series": "g3:t3",
          "x": 4,
          "y": "1/2",
          "numericY": 0.5
        }
      ],
      "summaryFile": "metr20-programs/twfe-negative-cell-python-summary.csv",
      "summarySHA256": "57c0e4771d9e4d3b486e0d8d98a94c1915fd30d909fac150b6b69bc31b4d2efd",
      "pointsFile": "metr20-programs/twfe-negative-cell-python-points.csv",
      "pointsSHA256": "c8cafdeaa7fa2d0fd776de6c0bfa509f3b1faa4bbd235ffe75c66734b6d74033",
      "fullResultFile": "metr20-programs/twfe-negative-cell-python.json",
      "fullResultSHA256": "f5941ee13a938775715fb00e7ce858e34eaa183d2d6acf70e3b8a25e434b1549",
      "plotFile": "metr20-programs/twfe-negative-cell-python.svg",
      "plotSHA256": "03a2632577e2c4db74d9004be97ebc9b08af6be181e90f78b6c6500ea3eef32c"
    },
    {
      "api": "twfe",
      "variant": "twfe-negative-cell",
      "profile": "twfe-negative-cell",
      "language": "R",
      "file": "metr20-programs/twfe-negative-cell-r.R",
      "codeSHA256": "fdd9f515325b4aed81f88a23c9e0493d03a755ffa09d54db7a1a97eee7422faf",
      "returnCode": 0,
      "expectedRejection": false,
      "title": {
        "ko": "양의 효과 네 개와 음의 투영 계수",
        "en": "Four positive effects and a negative projection"
      },
      "code": "# METR20 fixed example. Base R only, finite arithmetic approximate.\r\n# No JavaScript engine,model JSON,derived answer table,private module or internet.\r\noptions(stringsAsFactors=FALSE,digits=17)\r\nargv<-commandArgs(trailingOnly=TRUE);if(length(argv)<1L)stop('Supply a new empty output directory')\r\noutdir<-argv[1];script<-sub('^--file=','',commandArgs(FALSE)[grepl('^--file=',commandArgs(FALSE))][1]);here<-dirname(normalizePath(script,mustWork=TRUE));datadir<-if(length(argv)>=2L)argv[2]else file.path(here,'..','metr20-sources')\r\nunits<-c(country='log teen-employment points',person='recorded real earnings',company='FTE employees');clocks<-c(country='calendar year',person='calendar year',company='survey-wave index');steps<-c(country=1,person=3,company=1);files<-c(country='actual2500-county-mpdta-all6-fields.csv',person='actual38408-NSW-all15-fields.csv',company='actual410-NJPA-all46-fields.csv')\r\nnum<-function(s)ifelse(s=='.',NA_real_,as.numeric(s));mean0<-function(v)if(length(v))mean(v)else NA_real_;var0<-function(v)if(length(v)>1L)sum((v-mean(v))^2)/(length(v)-1L)else NA_real_\r\n\r\nSPEC<-list(id=\"twfe-negative-cell\",api=\"twfe\",title=list(ko=\"양의 효과 네 개와 음의 투영 계수\",en=\"Four positive effects and a negative projection\"),input=list(rows=list(list(id=\"early:0\",entity=\"early\",time=0,y=\"0\",g=1),list(id=\"early:1\",entity=\"early\",time=1,y=\"1\",g=1),list(id=\"early:2\",entity=\"early\",time=2,y=\"1\",g=1),list(id=\"early:3\",entity=\"early\",time=3,y=\"20\",g=1),list(id=\"late:0\",entity=\"late\",time=0,y=\"0\",g=3),list(id=\"late:1\",entity=\"late\",time=1,y=\"0\",g=3),list(id=\"late:2\",entity=\"late\",time=2,y=\"0\",g=3),list(id=\"late:3\",entity=\"late\",time=3,y=\"1\",g=3),list(id=\"never:0\",entity=\"never\",time=0,y=\"0\",g=NA_real_),list(id=\"never:1\",entity=\"never\",time=1,y=\"0\",g=NA_real_),list(id=\"never:2\",entity=\"never\",time=2,y=\"0\",g=NA_real_),list(id=\"never:3\",entity=\"never\",time=3,y=\"0\",g=NA_real_))),expectedReject=FALSE)\r\npanel<-function(rows){G<-list();for(r in rows){key<-r$entity;u<-G[[key]];if(is.null(u))u<-list(g=r$g,rows=list());stopifnot(identical(u$g,r$g),is.null(u$rows[[as.character(r$time)]]));u$rows[[as.character(r$time)]]<-r;G[[key]]<-u};G}\r\ncell<-function(G,g,t,step,control){b<-g-step;members<-list();T<-C<-list();for(key in names(G)){u<-G[[key]];target<-!is.na(u$g)&&u$g==g;comp<-is.na(u$g)||(control=='notyet'&&!is.na(u$g)&&u$g>max(t,b));role<-if(target)'treated'else if(comp)'control'else'excluded-comparison';before<-u$rows[[as.character(b)]];after<-u$rows[[as.character(t)]];yb<-if(is.null(before))NA_real_ else before$y;ya<-if(is.null(after))NA_real_ else after$y;eligible<-role!='excluded-comparison'&&!is.na(yb)&&!is.na(ya);reason<-if(role=='excluded-comparison')'target-or-already-exposed-cohort-not-valid-control'else if(is.null(before))'baseline-source-row-absent'else if(is.null(after))'target-time-source-row-absent'else if(is.na(yb))'baseline-outcome-missing'else if(is.na(ya))'target-outcome-missing'else'';m<-list(entity=key,nativeID=u$rows[[1]]$nativeID,g=u$g,role=role,eligible=eligible,baselineSourceId=if(is.null(before))NA_character_ else before$id,targetSourceId=if(is.null(after))NA_character_ else after$id,before=yb,after=ya,change=if(eligible)ya-yb else NA_real_,reason=reason);members[[key]]<-m;if(eligible){if(role=='treated')T[[length(T)+1L]]<-m else C[[length(C)+1L]]<-m}}\r\n change<-function(a)vapply(a,function(r)r$change,0);d<-mean0(change(T));e<-mean0(change(C));estimate<-if(is.na(d)||is.na(e))NA_real_ else d-e;defined<-!is.na(estimate);scores<-setNames(rep(NA_real_,length(members)),names(members));for(key in names(members)){m<-members[[key]];s<-if(!defined)NA_real_ else if(!m$eligible)0 else if(m$role=='treated')(m$change-d)/length(T)else-(m$change-e)/length(C);m$score<-s;scores[key]<-s;members[[key]]<-m};st<-var0(change(T));sc<-var0(change(C));v<-if(is.na(st)||is.na(sc))NA_real_ else st/length(T)+sc/length(C);level<-function(a,k)mean0(vapply(a,function(r)r[[k]],0))\r\n list(g=g,t=t,baseline=b,event=(t-g)/step,phase=if(t==b)'mechanical-reference'else if(t>=g)'post'else'pre-placebo',defined=defined,estimate=estimate,T=T,C=C,members=members,scores=scores,HC0=if(defined)sum(scores^2)else NA_real_,unbiased=v,treatedMeanBefore=level(T,'before'),treatedMeanAfter=level(T,'after'),treatedMeanChange=d,controlMeanBefore=level(C,'before'),controlMeanAfter=level(C,'after'),controlMeanChange=e)\r\n}\r\ncovariance<-function(cells){n<-length(cells);V<-matrix(NA_real_,n,n);for(i in seq_len(n))for(j in seq_len(n))if(cells[[i]]$defined&&cells[[j]]$defined)V[i,j]<-sum(cells[[i]]$scores*cells[[j]]$scores);V}\r\naggregate_cells<-function(post,V,step){out<-list();push<-function(typ,key,ii,w){est<-if(!length(ii)||any(vapply(post[ii],function(z)is.na(z$estimate),TRUE)))NA_real_ else sum(w*vapply(post[ii],function(z)z$estimate,0));vv<-if(is.na(est)||anyNA(V[ii,ii,drop=FALSE]))NA_real_ else as.numeric(t(w)%*%V[ii,ii,drop=FALSE]%*%w);out[[length(out)+1L]]<<-list(type=typ,key=as.character(key),ii=ii,w=w,estimate=est,variance=vv)};positive<-which(vapply(post,function(c)length(c$T)>0L,TRUE));mass<-sum(vapply(post[positive],function(c)length(c$T),0));push('simple','overall',positive,if(mass)vapply(post[positive],function(c)length(c$T)/mass,0)else numeric())\r\n for(typ in c('event','calendar','group')){keys<-vapply(post,function(c)if(typ=='event')c$event else if(typ=='calendar')c$t else c$g,0);gg<-sort(unique(keys));cohortmass<-if(typ=='group')sum(vapply(gg,function(k)length(post[[which(keys==k)[1]]]$T),0))else 0;allii<-integer();allw<-numeric();for(key in gg){ii<-which(keys==key);jj<-ii[vapply(post[ii],function(c)length(c$T)>0L,TRUE)];if(typ=='group'){stopifnot(length(unique(vapply(post[ii],function(c)length(c$T),0)))<=1L);w<-if(length(jj))rep(1/length(jj),length(jj))else numeric();if(cohortmass){allii<-c(allii,jj);allw<-c(allw,w*length(post[[ii[1]]]$T)/cohortmass)}}else{total<-sum(vapply(post[jj],function(c)length(c$T),0));w<-if(total)vapply(post[jj],function(c)length(c$T)/total,0)else numeric()};push(typ,key,jj,w)};if(typ=='group')push(typ,'overall',allii,allw)};out}\r\ntwfe<-function(G,times){ledger<-list();good<-list();for(key in names(G)){u<-G[[key]];absent<-times[!as.character(times)%in%names(u$rows)];missing<-times[vapply(times,function(t){r<-u$rows[[as.character(t)]];!is.null(r)&&is.na(r$y)},TRUE)];eligible<-length(times)>0L&&!length(absent)&&!length(missing);ledger[[length(ledger)+1L]]<-list(entity=key,g=u$g,nativeID=u$rows[[1]]$nativeID,eligible=eligible,absentTimes=paste(absent,collapse=','),missingOutcomeTimes=paste(missing,collapse=','),originalRows=length(u$rows));if(eligible)good[[key]]<-u};rows<-list();for(key in names(good))for(t in times){r<-good[[key]]$rows[[as.character(t)]];r$D<-as.integer(!is.na(r$g)&&t>=r$g);rows[[length(rows)+1L]]<-r};em<-lapply(good,function(u)list(D=mean(vapply(times,function(t)as.integer(!is.na(u$g)&&t>=u$g),0)),Y=mean(vapply(u$rows[as.character(times)],function(r)r$y,0))));tm<-lapply(times,function(t)list(D=mean(vapply(good,function(u)as.integer(!is.na(u$g)&&t>=u$g),0)),Y=mean(vapply(good,function(u)u$rows[[as.character(t)]]$y,0))));names(tm)<-as.character(times);gd<-mean0(vapply(rows,function(r)r$D,0));gy<-mean0(vapply(rows,function(r)r$y,0));num<-den<-0\r\n for(i in seq_along(rows)){r<-rows[[i]];r$residualD<-r$D-em[[r$entity]]$D-tm[[as.character(r$time)]]$D+gd;r$residualY<-r$y-em[[r$entity]]$Y-tm[[as.character(r$time)]]$Y+gy;num<-num+r$residualD*r$residualY;den<-den+r$residualD^2;rows[[i]]<-r};beta<-if(den!=0)num/den else NA_real_;weights<-list();for(i in seq_along(rows)){r<-rows[[i]];r$projectionCoefficient<-if(den!=0)r$residualD/den else NA_real_;r$regressionResidual<-if(!is.na(beta))r$residualY-beta*r$residualD else NA_real_;rows[[i]]<-r;if(r$D==1L){k<-paste(r$g,r$time,sep=':');z<-weights[[k]];if(is.null(z))z<-list(g=r$g,t=r$time,rows=0,coefficient=if(den!=0)0 else NA_real_);z$rows<-z$rows+1L;if(den!=0)z$coefficient<-z$coefficient+r$projectionCoefficient;weights[[k]]<-z}};list(ledger=ledger,rows=rows,num=num,den=den,beta=beta,weights=weights,balancedEntities=length(good))}\r\nadjacent_pre<-function(G,g,t,step,control){b<-t-step;T<-C<-numeric();for(u in G){target<-!is.na(u$g)&&u$g==g;comp<-is.na(u$g)||(control=='notyet'&&!is.na(u$g)&&u$g>max(t,b));if(!target&&!comp)next;before<-u$rows[[as.character(b)]];after<-u$rows[[as.character(t)]];if(!is.null(before)&&!is.null(after)&&!is.na(before$y)&&!is.na(after$y)){if(target)T<-c(T,after$y-before$y)else C<-c(C,after$y-before$y)}};if(!length(T)||!length(C))NA_real_ else mean(T)-mean(C)}\r\n\r\n# Newly authored bounded teaching projections; base R finite approximation.\r\n# Source helper functions are inlined in each public file, never imported.\r\nqnum<-function(v){if(is.null(v)||is.na(v))return(NA_real_);s<-strsplit(as.character(v),'/',fixed=TRUE)[[1]];if(length(s)==1L)as.numeric(s)else as.numeric(s[1])/as.numeric(s[2])}\r\npaired<-function(T,C){\r\n stats<-function(rr){use<-Filter(function(r)!is.na(qnum(r$before))&&!is.na(qnum(r$after)),rr);a<-vapply(use,function(r)qnum(r$before),0);b<-vapply(use,function(r)qnum(r$after),0);list(sourcePairs=length(rr),eligiblePairs=length(use),excludedPairs=length(rr)-length(use),meanBefore=mean0(a),meanAfter=mean0(b),meanChange=mean0(b-a),sampleChangeVariance=var0(b-a))}\r\n st<-stats(T);sc<-stats(C);defined<-st$eligiblePairs>0L&&sc$eligiblePairs>0L;estimate<-if(defined)st$meanChange-sc$meanChange else NA_real_;rr<-list()\r\n for(role in c('treated','control')){input<-if(role=='treated')T else C;s<-if(role=='treated')st else sc;for(r in input){before<-qnum(r$before);after<-qnum(r$after);eligible<-!is.na(before)&&!is.na(after);change<-if(eligible)after-before else NA_real_;score<-if(!defined)NA_real_ else if(!eligible)0 else (change-s$meanChange)/(if(role=='treated')s$eligiblePairs else -s$eligiblePairs);rr[[length(rr)+1L]]<-list(id=r$id,role=role,before=before,after=after,eligible=eligible,change=change,score=score)}}\r\n list(defined=defined,estimate=estimate,treated=st,control=sc,unbiasedVariance=if(defined&&st$eligiblePairs>=2L&&sc$eligiblePairs>=2L)st$sampleChangeVariance/st$eligiblePairs+sc$sampleChangeVariance/sc$eligiblePairs else NA_real_,HC0=if(defined)sum(vapply(rr,function(r)r$score^2,0))else NA_real_,rows=rr)\r\n}\r\nliteral_panel<-function(rr)lapply(seq_along(rr),function(i){r<-rr[[i]];r$y<-qnum(r$y);r$nativeID<-r$entity;r$sourceRow<-i;r})\r\natt_projection<-function(rows,control='never',step=1){G<-panel(rows);times<-sort(unique(vapply(rows,function(r)r$time,0)));cohorts<-sort(unique(na.omit(vapply(rows,function(r)r$g,0))));cells<-list();for(g in cohorts)for(t in times)cells[[length(cells)+1L]]<-cell(G,g,t,step,control);list(sourceRows=length(rows),sourceEntities=length(G),step=step,control=control,cells=cells,covariance=covariance(cells))}\r\nlinear_aggregate<-function(a){\r\n rr<-lapply(a$cells,function(r){r$estimate<-qnum(r$estimate);r$weight<-qnum(r$weight);r});V<-if(is.null(a$covariance))NULL else do.call(rbind,lapply(a$covariance,function(r)vapply(r,qnum,0)));rank<-NA_real_\r\n if(!is.null(V)){stopifnot(nrow(V)==length(rr),ncol(V)==length(rr),all(V==t(V)));ev<-eigen(V,symmetric=TRUE,only.values=TRUE)$values;if(any(ev< -1e-12))stop('covariance-must-be-positive-semidefinite');rank<-sum(ev>1e-12)}\r\n selected<-which(vapply(rr,function(r)r$time>=r$cohort&&r$weight>0,TRUE));w<-numeric(length(rr));type<-if(is.null(a$type))'simple'else a$type\r\n if(type=='simple'){mass<-sum(vapply(rr[selected],function(r)r$weight,0));if(mass>0)for(i in selected)w[i]<-rr[[i]]$weight/mass}else{g<-vapply(rr,function(r)r$cohort,0);gg<-sort(unique(g[selected]));mass<-sum(vapply(gg,function(gi)rr[[intersect(which(g==gi),selected)[1]]]$weight,0));for(gi in gg){ii<-intersect(which(g==gi),selected);stopifnot(length(unique(vapply(rr[ii],function(r)r$weight,0)))==1L);w[ii]<-rr[[ii[1]]]$weight/mass/length(ii)}}\r\n used<-which(w>0);estimate<-if(!length(used)||any(vapply(rr[used],function(r)is.na(r$estimate),TRUE)))NA_real_ else sum(w[used]*vapply(rr[used],function(r)r$estimate,0));variance<-if(is.na(estimate)||is.null(V))NA_real_ else as.numeric(t(w)%*%V%*%w);weights<-lapply(used,function(i)list(sourceIndex=i-1L,cohort=rr[[i]]$cohort,time=rr[[i]]$time,coefficient=w[i],estimate=rr[[i]]$estimate,contribution=w[i]*rr[[i]]$estimate))\r\n list(type=type,defined=!is.na(estimate),estimate=estimate,variance=variance,covarianceRank=rank,weights=weights,cells=rr,covariance=V)\r\n}\r\nsensitivity_fixed<-function(a){estimate<-qnum(a$estimate);M<-qnum(a$M);h<-if(is.null(a$horizon))1 else a$horizon;stopifnot(M>=0,h>=1);pre<-vapply(a$preDifferences,qnum,0);scale<-if(!is.null(a$scale))qnum(a$scale)else if(length(pre))max(abs(pre))else NA_real_;budget<-M*scale*h;list(defined=!is.na(scale),estimate=estimate,scale=scale,M=M,horizon=h,biasBudget=budget,lower=estimate-budget,upper=estimate+budget,preDifferences=as.list(pre),confidenceLevel=NULL)}\r\nrealdata_fixed<-function(kind){rows<-models[[kind]];G<-panel(rows);times<-sort(unique(vapply(rows,function(r)r$time,0)));step<-unname(steps[kind]);aa<-att_projection(rows,'never',step);post<-Filter(function(r)r$phase=='post',aa$cells);aggs<-aggregate_cells(post,covariance(post),step);tf<-twfe(G,times);list(kind=kind,unit=unname(units[kind]),periodUnit=unname(clocks[kind]),nativeRows=nrow(raw[[kind]]),modelRows=length(rows),entities=length(G),sourceRows=rows,att=aa,aggregations=aggs,twfe=tf,scope='Complete native/model/paired/balanced source frames; never control,universal base,no anticipation;not causal/sampling certification.')}\r\n# JSON encoder deliberately handles matrices and scalar/vector distinctions.\r\nencode<-function(x){\r\n if(is.null(x))return('null')\r\n quote<-function(s){s<-gsub('\\\\','\\\\\\\\',as.character(s),fixed=TRUE);s<-gsub('\"','\\\\\"',s,fixed=TRUE);s<-gsub('\\n','\\\\n',s,fixed=TRUE);s<-gsub('\\r','\\\\r',s,fixed=TRUE);s<-gsub('\\t','\\\\t',s,fixed=TRUE);paste0('\"',s,'\"')}\r\n if(is.matrix(x))return(paste0('[',paste(vapply(seq_len(nrow(x)),function(i)encode(as.list(unname(x[i,]))),''),collapse=','),']'))\r\n if(is.list(x)){if(length(x)&&!is.null(names(x)))return(paste0('{',paste(paste0(vapply(names(x),quote,''),':',vapply(x,encode,'')),collapse=','),'}'));return(paste0('[',paste(vapply(x,encode,''),collapse=','),']'))}\r\n if(length(x)!=1L)return(encode(as.list(unname(x))))\r\n if(is.na(x))return('null');if(is.logical(x))return(if(x)'true'else'false');if(is.numeric(x))return(sprintf('%.17g',unname(x)));quote(x)\r\n}\r\nv9<-function(x){if(is.null(x)||is.na(x))return('undefined');if(is.logical(x))return(if(x)'1'else'0');if(is.numeric(x))return(sprintf('%.9g',unname(x)));as.character(x)}\r\nrun_fixed<-function(spec,out){api<-spec$api;a<-spec$input;summary<-list();points<-list();emit<-function(series,x,y){points[[length(points)+1L]]<<-list(series=series,x=x,y=y,numericY=y)}\r\n if(api=='twobytwo'){result<-paired(a$treated,a$control);summary<-list(defined=result$defined,estimate=result$estimate,treatedPairs=result$treated$eligiblePairs,controlPairs=result$control$eligiblePairs,unbiasedVariance=result$unbiasedVariance,HC0=result$HC0);for(i in seq_along(result$rows)){r<-result$rows[[i]];emit(paste(r$role,r$id,sep=':'),i,r$change)}}\r\n else if(api=='att'){result<-att_projection(literal_panel(a$rows),a$control);summary<-list(sourceRows=result$sourceRows,entities=result$sourceEntities,cells=length(result$cells),supportedCells=sum(vapply(result$cells,function(r)r$defined,TRUE)),postCells=sum(vapply(result$cells,function(r)r$phase=='post',TRUE)));for(i in seq_along(result$cells)){r<-result$cells[[i]];emit(paste0('g',r$g,':t',r$t),i,r$estimate)}}\r\n else if(api=='aggregate'){result<-linear_aggregate(a);summary<-list(defined=result$defined,estimate=result$estimate,variance=result$variance,covarianceRank=result$covarianceRank,sumWeights=sum(vapply(result$weights,function(r)r$coefficient,0)));for(i in seq_along(result$weights)){r<-result$weights[[i]];emit(paste0('g',r$cohort,':t',r$time),i,r$contribution)}}\r\n else if(api=='twfe'){rows<-literal_panel(a$rows);G<-panel(rows);result<-twfe(G,sort(unique(vapply(rows,function(r)r$time,0))));summary<-list(defined=!is.na(result$beta),beta=result$beta,numerator=result$num,denominator=result$den,balancedEntities=result$balancedEntities,negativeTreatedCells=sum(vapply(result$weights,function(r)!is.na(r$coefficient)&&r$coefficient<0,TRUE)));if(length(result$weights)){ord<-order(vapply(result$weights,function(r)r$g,0),vapply(result$weights,function(r)r$t,0));for(i in seq_along(ord)){r<-result$weights[[ord[i]]];emit(paste0('g',r$g,':t',r$t),i,r$coefficient)}}}\r\n else if(api=='sensitivity'){result<-sensitivity_fixed(a);summary<-result[c('defined','estimate','scale','M','horizon','biasBudget','lower','upper')];for(i in seq_along(c('lower','estimate','upper'))){k<-c('lower','estimate','upper')[i];emit(k,i,if(result$defined)result[[k]]else NA_real_)}}\r\n else{result<-realdata_fixed(a$kind);post<-Filter(function(r)r$phase=='post',result$att$cells);simple<-Filter(function(r)r$type=='simple',result$aggregations)[[1]];group<-Filter(function(r)r$type=='group'&&r$key=='overall',result$aggregations)[[1]];summary<-list(nativeRows=result$nativeRows,modelRows=result$modelRows,entities=result$entities,postCells=length(post),simple=simple$estimate,group=group$estimate,TWFE=result$twfe$beta,balancedEntities=result$twfe$balancedEntities);for(i in seq_along(post)){r<-post[[i]];emit(paste0('g',r$g,':t',r$t),i,r$estimate)}}\r\n dir.create(out,recursive=TRUE,showWarnings=FALSE);if(length(list.files(out,all.files=TRUE,no..=TRUE)))stop('use-new-empty-output-directory');shown<-lapply(summary,v9);write.csv(data.frame(name=names(shown),value=unlist(shown,use.names=FALSE)),file.path(out,'summary.csv'),row.names=FALSE,na='');pointframe<-if(length(points))do.call(rbind,lapply(points,function(p)data.frame(series=p$series,x=p$x,y=p$y,numericY=p$numericY,stringsAsFactors=FALSE)))else data.frame(series=character(),x=numeric(),y=numeric(),numericY=numeric());write.csv(pointframe,file.path(out,'points.csv'),row.names=FALSE,na='');full<-list(chapter='METR-20',profile=spec$id,api=api,input=spec$input,summary=shown,points=points,details=result,arithmetic='Base R approximate finite values;bounded teaching projection,not exact fractions or causal/sampling certification.');writeLines(encode(full),file.path(out,'full.json'),useBytes=TRUE)\r\n svg(file.path(out,'plot.svg'),width=9,height=5.6,pointsize=12);par(mar=c(4.5,5.5,4,1));good<-pointframe[!is.na(pointframe$numericY),,drop=FALSE]\r\n if(nrow(good)){plot(good$x,good$numericY,pch=19,col='#315d7c',xlab='Declared cell/unit/bound ordinal',ylab=if(api=='twfe')'Cell weight'else if(!is.null(result$unit))result$unit else 'Stated outcome/bias units',main=spec$title$en);abline(h=0,col='#9eabb2');grid(nx=NA,ny=NULL,col='#e2e5e7');points(good$x,good$numericY,pch=19,col='#315d7c')}else{plot.new();text(.5,.5,'Undefined: no supported plotted quantity');title(main=spec$title$en)};dev.off();cat(encode(shown),'\\n')\r\n}\r\n\r\nrun_fixed(SPEC,outdir)\r\n",
      "arithmetic": "Base R approximate finite arithmetic;not an exact rational result",
      "summary": {
        "defined": "1",
        "beta": "-0.9",
        "numerator": "-0.75",
        "denominator": "0.833333333",
        "balancedEntities": "3",
        "negativeTreatedCells": "1"
      },
      "fullResultEmbedded": false,
      "plotEmbedded": false,
      "full": {
        "summary": {
          "defined": "1",
          "beta": "-0.9",
          "numerator": "-0.75",
          "denominator": "0.833333333",
          "balancedEntities": "3",
          "negativeTreatedCells": "1"
        },
        "notice": "Complete source/finite projection is retained in the linked external JSON; this short projection is not the full result."
      },
      "plot": null,
      "points": [
        {
          "series": "g1:t1",
          "x": 1,
          "y": 0.29999999999999993,
          "numericY": 0.29999999999999993
        },
        {
          "series": "g1:t2",
          "x": 2,
          "y": 0.29999999999999993,
          "numericY": 0.29999999999999993
        },
        {
          "series": "g1:t3",
          "x": 3,
          "y": -0.09999999999999996,
          "numericY": -0.09999999999999996
        },
        {
          "series": "g3:t3",
          "x": 4,
          "y": 0.49999999999999994,
          "numericY": 0.49999999999999994
        }
      ],
      "summaryFile": "metr20-programs/twfe-negative-cell-r-summary.csv",
      "summarySHA256": "563a0aabfd0713f6e054471766c586f9f12bc40cfd84b71c028e83e8adc56fe4",
      "pointsFile": "metr20-programs/twfe-negative-cell-r-points.csv",
      "pointsSHA256": "dd316900702826d18556a43f341d8480adf233d2e0e44df5aa5ffeeb3f90f6cb",
      "fullResultFile": "metr20-programs/twfe-negative-cell-r.json",
      "fullResultSHA256": "ec75d3c5c3220bf3d3455c8057c53b4c8405d27109ec04f47da1040f5cf2c9dd",
      "plotFile": "metr20-programs/twfe-negative-cell-r.svg",
      "plotSHA256": "08465962b7804fec54d73a7eb55ffc668cc6b0a0d7e451f68577b5123eecb575"
    },
    {
      "api": "twfe",
      "variant": "twfe-absorbed-exposure",
      "profile": "twfe-absorbed-exposure",
      "language": "Python",
      "file": "metr20-programs/twfe-absorbed-exposure-python.py",
      "codeSHA256": "eb66e8e9497f8af6e6925a6c068de1ec40877866db6fca169e44855a5d516d73",
      "returnCode": 0,
      "expectedRejection": false,
      "title": {
        "ko": "변하지 않는 처치 지표는 미식별",
        "en": "Constant exposure is absorbed by fixed effects"
      },
      "code": "\"\"\"METR20 actual sources. Python standard library, exact stored-value rationals.\r\nRead ONLY the three native-observation CSVs; no JS engine,model JSON,derived\r\nanswers,private modules or internet needed. Outcome measurement/identification\r\nand valid sampling inference remain separate from exact finite arithmetic.\r\nRun: python metr20-reproduce.py --data-dir PATH --out NEW_EMPTY_DIRECTORY\r\n\"\"\"\r\nfrom pathlib import Path\r\nfrom fractions import Fraction as Q\r\nfrom collections import defaultdict,Counter\r\nimport csv,json,math,argparse,hashlib\r\n\r\nUNIT={'country':'log teen-employment points','person':'recorded real earnings','company':'FTE employees'}\r\nCLOCK={'country':'calendar year','person':'calendar year','company':'survey-wave index'}\r\nSTEP={'country':1,'person':3,'company':1}\r\nFILES={'country':'actual2500-county-mpdta-all6-fields.csv','person':'actual38408-NSW-all15-fields.csv','company':'actual410-NJPA-all46-fields.csv'}\r\ndef avg(v):return sum(v,Q(0))/len(v)if v else None\r\ndef samplevar(v):return sum(((x-avg(v))**2 for x in v),Q(0))/(len(v)-1)if len(v)>1 else None\r\ndef binary(s):return None if s=='.'else Q.from_float(float(s))\r\ndef token(v):\r\n if v is None:return ''\r\n if isinstance(v,bool):return 'true'if v else'false'\r\n return str(v)\r\ndef safe_float(v):\r\n if v is None:return None\r\n try:r=float(v)\r\n except OverflowError:return None\r\n return r if math.isfinite(r)else None\r\ndef read(p):\r\n with p.open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))\r\ndef write(p,rows,head=None):\r\n if head is None:\r\n  assert rows;head=list(rows[0])\r\n with p.open('w',encoding='utf8',newline='')as f:\r\n  w=csv.DictWriter(f,fieldnames=head);w.writeheader();w.writerows({k:token(r.get(k))for k in head}for r in rows)\r\ndef source(data):\r\n raw={k:read(data/n)for k,n in FILES.items()};assert[len(raw[k])for k in FILES]==[2500,38408,410]\r\n models={k:[]for k in FILES}\r\n for r in raw['country']:\r\n  g0=int(r['first.treat']);g=None if g0==0 else g0;assert int(r['treat'])==int(g is not None)\r\n  models['country'].append(dict(id='mpdta:'+r['sourceRow'],entity='county:'+str(int(r['countyreal'])),time=int(r['year']),y=binary(r['lemp']),g=g,sourceRow=int(r['sourceRow']),nativeID=r['countyreal']))\r\n for r in raw['person']:\r\n  selected=int(r['experimental'])==1;assert selected==(int(r['sample'])==1);assert(r['treated']!='.')==selected\r\n  if selected:\r\n   d=int(r['treated']);assert d in[0,1]\r\n   models['person'].append(dict(id='nsw:'+r['sourceRow'],entity='nsw-id:'+str(int(r['id'])),time=int(r['year']),y=binary(r['re']),g=1978 if d else None,sourceRow=int(r['sourceRow']),nativeID=str(int(r['id']))))\r\n for r in raw['company']:\r\n  state=int(r['STATE']);assert state in[0,1]\r\n  for t,suffix in[(0,''),(1,'2')]:\r\n   a=[r[n+suffix]for n in['EMPFT','NMGRS','EMPPT']];y=None if'.'in a else Q(a[0])+Q(a[1])+Q(a[2])/2\r\n   models['company'].append(dict(id='njpa:'+r['sourceRow']+':wave'+str(t),entity='njpa-row:'+r['sourceRow'],time=t,y=y,g=1 if state else None,sourceRow=int(r['sourceRow']),nativeID=r['SHEET']))\r\n assert[len(models[k])for k in FILES]==[2500,1444,820]\r\n return models,raw\r\ndef panel(rows):\r\n groups={}\r\n for r in rows:\r\n  u=groups.setdefault(r['entity'],{'g':r['g'],'rows':{}});assert u['g']==r['g']and r['time']not in u['rows'];u['rows'][r['time']]=r\r\n return groups\r\ndef cell(groups,g,t,step,control):\r\n b=g-step;members=[];T=[];C=[]\r\n for key,u in groups.items():\r\n  role='treated'if u['g']==g else'control'if u['g']is None or(control=='notyet'and u['g']>max(t,b))else'excluded-comparison'\r\n  before=u['rows'].get(b);after=u['rows'].get(t);yb=None if before is None else before['y'];ya=None if after is None else after['y'];eligible=role!='excluded-comparison'and yb is not None and ya is not None\r\n  reason='target-or-already-exposed-cohort-not-valid-control'if role=='excluded-comparison'else'baseline-source-row-absent'if before is None else'target-time-source-row-absent'if after is None else'baseline-outcome-missing'if yb is None else'target-outcome-missing'if ya is None else''\r\n  m={'entity':key,'nativeID':next(iter(u['rows'].values()))['nativeID'],'g':u['g'],'role':role,'eligible':eligible,'baselineSourceId':None if before is None else before['id'],'targetSourceId':None if after is None else after['id'],'before':yb,'after':ya,'change':ya-yb if eligible else None,'reason':reason};members.append(m)\r\n  if eligible:(T if role=='treated'else C).append(m)\r\n d=avg([r['change']for r in T]);e=avg([r['change']for r in C]);estimate=None if d is None or e is None else d-e;defined=estimate is not None;scores={}\r\n for m in members:\r\n  s=None if not defined else Q(0)\r\n  if defined and m['eligible']:s=(m['change']-(d if m['role']=='treated'else e))/(len(T)if m['role']=='treated'else-len(C))\r\n  m['score']=s;scores[m['entity']]=s\r\n st=samplevar([r['change']for r in T]);sc=samplevar([r['change']for r in C]);v=None if st is None or sc is None else st/len(T)+sc/len(C)\r\n return {'g':g,'t':t,'baseline':b,'event':(t-g)//step,'phase':'mechanical-reference'if t==b else'post'if t>=g else'pre-placebo','defined':defined,'estimate':estimate,'T':T,'C':C,'members':members,'scores':scores,'HC0':None if not defined else sum((s*s for s in scores.values()),Q(0)),'unbiased':v,'treatedMeanBefore':avg([r['before']for r in T]),'treatedMeanAfter':avg([r['after']for r in T]),'treatedMeanChange':d,'controlMeanBefore':avg([r['before']for r in C]),'controlMeanAfter':avg([r['after']for r in C]),'controlMeanChange':e}\r\ndef covariance(cells):\r\n return[[None if not a['defined']or not b['defined']else sum((v*b['scores'][i]for i,v in a['scores'].items()),Q(0))for b in cells]for a in cells]\r\ndef aggregate(post,V,step):\r\n out=[]\r\n def push(typ,key,coeff):\r\n  estimate=None if not coeff or any(post[i]['estimate']is None for i in coeff)else sum((w*post[i]['estimate']for i,w in coeff.items()),Q(0));variance=None if estimate is None or any(V[i][j]is None for i in coeff for j in coeff)else sum((a*b*V[i][j]for i,a in coeff.items()for j,b in coeff.items()),Q(0));out.append({'type':typ,'key':key,'coeff':coeff,'estimate':estimate,'variance':variance})\r\n positive=[i for i,c in enumerate(post)if len(c['T'])>0];mass=sum(len(post[i]['T'])for i in positive)\r\n push('simple','overall',{i:Q(len(post[i]['T']),mass)for i in positive}if mass else{})\r\n for typ in['event','calendar','group']:\r\n  groups=defaultdict(list)\r\n  for i,c in enumerate(post):groups[c['event']if typ=='event'else c['t']if typ=='calendar'else c['g']].append(i)\r\n  overall={};cohortMass=sum(len(post[ii[0]]['T'])for ii in groups.values())if typ=='group'else 0\r\n  for key,ii in sorted(groups.items()):\r\n   jj=[i for i in ii if len(post[i]['T'])>0]\r\n   if typ=='group':\r\n    assert len({len(post[i]['T'])for i in ii})<=1\r\n    coeff={i:Q(1,len(jj))for i in jj}if jj else{}\r\n    if cohortMass:\r\n     for i,w in coeff.items():overall[i]=w*Q(len(post[ii[0]]['T']),cohortMass)\r\n   else:\r\n    total=sum(len(post[i]['T'])for i in jj);coeff={i:Q(len(post[i]['T']),total)for i in jj}if total else{}\r\n   push(typ,str(key),coeff)\r\n  if typ=='group':push(typ,'overall',overall)\r\n return out\r\ndef twfe(groups,times):\r\n ledger=[];good={}\r\n for key,u in groups.items():\r\n  absent=[t for t in times if t not in u['rows']];missing=[t for t in times if t in u['rows']and u['rows'][t]['y']is None];eligible=bool(times)and not absent and not missing\r\n  ledger.append({'entity':key,'g':u['g'],'nativeID':next(iter(u['rows'].values()))['nativeID'],'eligible':eligible,'absentTimes':','.join(map(str,absent)),'missingOutcomeTimes':','.join(map(str,missing)),'originalRows':len(u['rows'])})\r\n  if eligible:good[key]=u\r\n rows=[dict(**u['rows'][t],D=Q(u['g']is not None and t>=u['g']))for key,u in good.items()for t in times]\r\n em={k:{'D':avg([Q(u['g']is not None and t>=u['g'])for t in times]),'Y':avg([u['rows'][t]['y']for t in times])}for k,u in good.items()};tm={t:{'D':avg([Q(u['g']is not None and t>=u['g'])for u in good.values()]),'Y':avg([u['rows'][t]['y']for u in good.values()])}for t in times};gd=avg([r['D']for r in rows]);gy=avg([r['y']for r in rows]);num=den=Q(0)\r\n for r in rows:\r\n  r['residualD']=r['D']-em[r['entity']]['D']-tm[r['time']]['D']+gd;r['residualY']=r['y']-em[r['entity']]['Y']-tm[r['time']]['Y']+gy;num+=r['residualD']*r['residualY'];den+=r['residualD']**2\r\n beta=num/den if den else None;weights={}\r\n for r in rows:\r\n  r['projectionCoefficient']=r['residualD']/den if den else None;r['regressionResidual']=r['residualY']-beta*r['residualD']if beta is not None else None\r\n  if r['D']:\r\n   k=(r['g'],r['time']);z=weights.setdefault(k,{'rows':0,'coefficient':Q(0)if den else None});z['rows']+=1\r\n   if den:z['coefficient']+=r['projectionCoefficient']\r\n return {'ledger':ledger,'rows':rows,'num':num,'den':den,'beta':beta,'weights':weights,'balancedEntities':len(good)}\r\ndef adjacent_pre(groups,g,t,step,control):\r\n b=t-step;T=[];C=[]\r\n for u in groups.values():\r\n  if u['g']==g:target=T\r\n  elif u['g']is None or(control=='notyet'and u['g']>max(t,b)):target=C\r\n  else:continue\r\n  before=u['rows'].get(b);after=u['rows'].get(t)\r\n  if before is not None and after is not None and before['y']is not None and after['y']is not None:target.append(after['y']-before['y'])\r\n return None if not T or not C else avg(T)-avg(C)\r\n\r\n\"\"\"New bounded teaching projections. The program is self-contained after build.\r\nExact Fraction finite algebra; figures and9-digit summary are approximations.\r\nIt is not a general parser/API replacement or a causal/inference certificate.\r\n\"\"\"\r\ndef paired(treated,control):\r\n def stats(rr):\r\n  use=[r for r in rr if r['before']is not None and r['after']is not None];delta=[Q(r['after'])-Q(r['before'])for r in use]\r\n  return dict(sourcePairs=len(rr),eligiblePairs=len(use),excludedPairs=len(rr)-len(use),meanBefore=avg([Q(r['before'])for r in use]),meanAfter=avg([Q(r['after'])for r in use]),meanChange=avg(delta),sampleChangeVariance=samplevar(delta))\r\n T,C=stats(treated),stats(control);defined=T['eligiblePairs']>0 and C['eligiblePairs']>0;estimate=T['meanChange']-C['meanChange']if defined else None;records=[]\r\n for group,rr,s in [('treated',treated,T),('control',control,C)]:\r\n  for r in rr:\r\n   before=None if r['before']is None else Q(r['before']);after=None if r['after']is None else Q(r['after']);eligible=before is not None and after is not None;delta=after-before if eligible else None;score=None if not defined else Q(0)if not eligible else(delta-s['meanChange'])/(s['eligiblePairs']if group=='treated'else-s['eligiblePairs']);records.append(dict(id=r['id'],role=group,before=before,after=after,eligible=eligible,change=delta,score=score))\r\n unbiased=None if not defined or T['eligiblePairs']<2 or C['eligiblePairs']<2 else T['sampleChangeVariance']/T['eligiblePairs']+C['sampleChangeVariance']/C['eligiblePairs'];hc0=None if not defined else sum((r['score']**2 for r in records),Q(0))\r\n return dict(defined=defined,estimate=estimate,treated=T,control=C,unbiasedVariance=unbiased,HC0=hc0,rows=records)\r\ndef literal_panel(raw):\r\n return[dict(r,y=None if r['y']is None else Q(r['y']),nativeID=r['entity'],sourceRow=i+1)for i,r in enumerate(raw)]\r\ndef att_projection(rows,control='never',step=1):\r\n G=panel(rows);times=sorted({r['time']for r in rows});cohorts=sorted({r['g']for r in rows if r['g']is not None});cells=[cell(G,g,t,step,control)for g in cohorts for t in times]\r\n return dict(sourceRows=len(rows),sourceEntities=len(G),step=step,control=control,cells=cells,covariance=covariance(cells))\r\ndef psd(V):\r\n A=[r[:]for r in V];rank=0\r\n while A:\r\n  if any(A[i][i]<0 for i in range(len(A))):raise ValueError('covariance-must-be-positive-semidefinite')\r\n  p=next((i for i in range(len(A))if A[i][i]>0),None)\r\n  if p is None:\r\n   if any(v for r in A for v in r):raise ValueError('covariance-must-be-positive-semidefinite')\r\n   return rank\r\n  A[0],A[p]=A[p],A[0]\r\n  for r in A:r[0],r[p]=r[p],r[0]\r\n  d=A[0][0];A=[[A[i][j]-A[i][0]*A[0][j]/d for j in range(1,len(A))]for i in range(1,len(A))];rank+=1\r\n return rank\r\ndef linear_aggregate(a):\r\n rr=[dict(r,estimate=None if r['estimate']is None else Q(r['estimate']),weight=Q(r['weight']))for r in a['cells']];V=[[Q(v)for v in r]for r in a['covariance']]if 'covariance'in a else None\r\n if V is not None:\r\n  assert len(V)==len(rr)and all(len(z)==len(rr)for z in V);assert all(V[i][j]==V[j][i]for i in range(len(rr))for j in range(len(rr)));rank=psd(V)\r\n else:rank=None\r\n selected=[i for i,r in enumerate(rr)if r['time']>=r['cohort']and r['weight']>0];weights={}\r\n if a.get('type','simple')=='simple':\r\n  mass=sum((rr[i]['weight']for i in selected),Q(0));weights={i:rr[i]['weight']/mass for i in selected}if mass else{}\r\n else:\r\n  gg=defaultdict(list)\r\n  for i in selected:gg[rr[i]['cohort']].append(i)\r\n  assert all(len({rr[i]['weight']for i in ii})==1 for ii in gg.values());mass=sum((rr[ii[0]]['weight']for ii in gg.values()),Q(0));weights={i:rr[ii[0]]['weight']/mass/len(ii)for ii in gg.values()for i in ii}if mass else{}\r\n estimate=None if not weights or any(rr[i]['estimate']is None for i in weights)else sum((w*rr[i]['estimate']for i,w in weights.items()),Q(0));variance=None if estimate is None or V is None else sum((x*y*V[i][j]for i,x in weights.items()for j,y in weights.items()),Q(0))\r\n return dict(type=a.get('type','simple'),defined=estimate is not None,estimate=estimate,variance=variance,covarianceRank=rank,weights=[dict(sourceIndex=i,cohort=rr[i]['cohort'],time=rr[i]['time'],coefficient=w,estimate=rr[i]['estimate'],contribution=None if rr[i]['estimate']is None else w*rr[i]['estimate'])for i,w in weights.items()],cells=rr,covariance=V)\r\ndef sensitivity_fixed(a):\r\n estimate=Q(a['estimate']);M=Q(a['M']);h=a.get('horizon',1);assert M>=0 and h>=1\r\n pre=[Q(v)for v in a.get('preDifferences',[])];scale=Q(a['scale'])if 'scale'in a else max(map(abs,pre))if pre else None;budget=None if scale is None else M*scale*h\r\n return dict(defined=scale is not None,estimate=estimate,scale=scale,M=M,horizon=h,biasBudget=budget,lower=None if budget is None else estimate-budget,upper=None if budget is None else estimate+budget,preDifferences=pre,confidenceLevel=None)\r\ndef realdata_fixed(kind,data):\r\n models,raw=source(data);rows=models[kind];G=panel(rows);times=sorted({r['time']for r in rows});step=STEP[kind];aa=att_projection(rows,'never',step);post=[r for r in aa['cells']if r['phase']=='post'];aggs=aggregate(post,covariance(post),step);tf=twfe(G,times)\r\n return dict(kind=kind,unit=UNIT[kind],periodUnit=CLOCK[kind],nativeRows=len(raw[kind]),modelRows=len(rows),entities=len(G),sourceRows=rows,att=aa,aggregations=aggs,twfe=tf,scope='Complete source frame; never-treated comparison,universal baseline,no anticipation. Native/model/paired/balanced denominators differ. All sampling/causal assumptions remain separate.')\r\ndef encode(v):\r\n if isinstance(v,Q):return str(v)\r\n if isinstance(v,dict):return{str(k):encode(x)for k,x in v.items()}\r\n if isinstance(v,(list,tuple)):return[encode(x)for x in v]\r\n return v\r\ndef v9(v):\r\n if v is None:return'undefined'\r\n if isinstance(v,str):return v\r\n if isinstance(v,bool):return'1'if v else'0'\r\n return format(float(v),'.9g')\r\ndef run_fixed(spec,out,data):\r\n api=spec['api'];a=spec['input'];summary={};points=[]\r\n def emit(series,x,y):points.append(dict(series=series,x=x,y=y,numericY=safe_float(y)))\r\n if api=='twobytwo':\r\n  result=paired(a['treated'],a['control']);summary=dict(defined=result['defined'],estimate=result['estimate'],treatedPairs=result['treated']['eligiblePairs'],controlPairs=result['control']['eligiblePairs'],unbiasedVariance=result['unbiasedVariance'],HC0=result['HC0'])\r\n  for i,r in enumerate(result['rows']):emit(r['role']+':'+r['id'],i+1,r['change'])\r\n elif api=='att':\r\n  result=att_projection(literal_panel(a['rows']),a.get('control','never'));summary=dict(sourceRows=result['sourceRows'],entities=result['sourceEntities'],cells=len(result['cells']),supportedCells=sum(r['defined']for r in result['cells']),postCells=sum(r['phase']=='post'for r in result['cells']))\r\n  for i,r in enumerate(result['cells']):emit('g'+str(r['g'])+':t'+str(r['t']),i+1,r['estimate'])\r\n elif api=='aggregate':\r\n  result=linear_aggregate(a);summary=dict(defined=result['defined'],estimate=result['estimate'],variance=result['variance'],covarianceRank=result['covarianceRank'],sumWeights=sum((r['coefficient']for r in result['weights']),Q(0)))\r\n  for i,r in enumerate(result['weights']):emit('g'+str(r['cohort'])+':t'+str(r['time']),i+1,r['contribution'])\r\n elif api=='twfe':\r\n  rows=literal_panel(a['rows']);G=panel(rows);result=twfe(G,sorted({r['time']for r in rows}));summary=dict(defined=result['beta']is not None,beta=result['beta'],numerator=result['num'],denominator=result['den'],balancedEntities=result['balancedEntities'],negativeTreatedCells=sum(v['coefficient']is not None and v['coefficient']<0 for v in result['weights'].values()))\r\n  for i,((g,t),r)in enumerate(sorted(result['weights'].items())):emit('g'+str(g)+':t'+str(t),i+1,r['coefficient'])\r\n elif api=='sensitivity':\r\n  result=sensitivity_fixed(a);summary={k:result[k]for k in['defined','estimate','scale','M','horizon','biasBudget','lower','upper']}\r\n  for i,k in enumerate(['lower','estimate','upper']):emit(k,i+1,result[k]if result['defined']else None)\r\n else:\r\n  result=realdata_fixed(a['kind'],data);post=[r for r in result['att']['cells']if r['phase']=='post'];s=next(r for r in result['aggregations']if r['type']=='simple');g=next(r for r in result['aggregations']if r['type']=='group'and r['key']=='overall');summary=dict(nativeRows=result['nativeRows'],modelRows=result['modelRows'],entities=result['entities'],postCells=len(post),simple=s['estimate'],group=g['estimate'],TWFE=result['twfe']['beta'],balancedEntities=result['twfe']['balancedEntities'])\r\n  for i,r in enumerate(post):emit('g'+str(r['g'])+':t'+str(r['t']),i+1,r['estimate'])\r\n out.mkdir(parents=True,exist_ok=True)\r\n if any(out.iterdir()):raise ValueError('use-new-empty-output-directory')\r\n shown={k:v9(v)for k,v in summary.items()};write(out/'summary.csv',[dict(name=k,value=v)for k,v in shown.items()]);write(out/'points.csv',points,['series','x','y','numericY']);full=dict(chapter='METR-20',profile=spec['id'],api=api,input=spec['input'],summary=shown,points=encode(points),details=encode(result),arithmetic='Python Fraction exact finite stored values;summary/plot approximate;bounded teaching projection,not causal or sampling certification')\r\n (out/'full.json').write_text(json.dumps(full,ensure_ascii=False,indent=2,allow_nan=False)+'\\n',encoding='utf8')\r\n import matplotlib\r\n matplotlib.use('Agg')\r\n import matplotlib.pyplot as plt\r\n plt.rcParams.update({'svg.fonttype':'none','font.family':'DejaVu Sans','font.size':12,'axes.spines.top':False,'axes.spines.right':False});fig,ax=plt.subplots(figsize=(9,5.6));good=[r for r in points if r['numericY']is not None]\r\n if good:\r\n  ax.scatter([r['x']for r in good],[r['numericY']for r in good],color='#315d7c',s=32);ax.axhline(0,color='#9eabb2',lw=.8);ax.set_xlabel('Declared cell/unit/bound ordinal')\r\n else:ax.text(.5,.5,'Undefined: no supported plotted quantity',ha='center',va='center',transform=ax.transAxes);ax.set_xticks([]);ax.set_yticks([])\r\n ax.set_ylabel('Cell weight'if api=='twfe'else result.get('unit','Stated outcome/bias units'));ax.set_title(spec['title']['en'],wrap=True,pad=14);ax.grid(axis='y',alpha=.2);fig.tight_layout(pad=2);fig.savefig(out/'plot.svg');plt.close(fig);print(json.dumps(shown))\r\n\r\nSPEC={'id': 'twfe-absorbed-exposure', 'api': 'twfe', 'title': {'ko': '변하지 않는 처치 지표는 미식별', 'en': 'Constant exposure is absorbed by fixed effects'}, 'input': {'rows': [{'id': 'a:0', 'entity': 'a', 'time': 0, 'y': '2', 'g': None}, {'id': 'a:1', 'entity': 'a', 'time': 1, 'y': '4', 'g': None}, {'id': 'a:2', 'entity': 'a', 'time': 2, 'y': '8', 'g': None}, {'id': 'b:0', 'entity': 'b', 'time': 0, 'y': '3', 'g': None}, {'id': 'b:1', 'entity': 'b', 'time': 1, 'y': '5', 'g': None}, {'id': 'b:2', 'entity': 'b', 'time': 2, 'y': '9', 'g': None}]}, 'expectedReject': False}\r\nif __name__=='__main__':\r\n import sys\r\n run_fixed(SPEC,Path(sys.argv[1]),Path(sys.argv[2])if len(sys.argv)>2 else Path(__file__).resolve().parent.parent/'metr20-sources')\r\n",
      "arithmetic": "Python Fraction exact stored finite values;logs/summary/plots approximate",
      "summary": {
        "defined": "0",
        "beta": "undefined",
        "numerator": "0",
        "denominator": "0",
        "balancedEntities": "2",
        "negativeTreatedCells": "0"
      },
      "fullResultEmbedded": false,
      "plotEmbedded": false,
      "full": {
        "summary": {
          "defined": "0",
          "beta": "undefined",
          "numerator": "0",
          "denominator": "0",
          "balancedEntities": "2",
          "negativeTreatedCells": "0"
        },
        "notice": "Complete source/finite projection is retained in the linked external JSON; this short projection is not the full result."
      },
      "plot": null,
      "points": [],
      "summaryFile": "metr20-programs/twfe-absorbed-exposure-python-summary.csv",
      "summarySHA256": "7f817ae261f3f1f14b09e515483bb017ef828d35b28fb337e4a31ca3fca88499",
      "pointsFile": "metr20-programs/twfe-absorbed-exposure-python-points.csv",
      "pointsSHA256": "2249323d68e06c1944de85e94cb9735d1b0659d10bd59ba29881f0313fb116b1",
      "fullResultFile": "metr20-programs/twfe-absorbed-exposure-python.json",
      "fullResultSHA256": "eaf1de45087e79a7f2d26f8d8837fc20e58c8f4328cd1bbb045ec30c7511dc36",
      "plotFile": "metr20-programs/twfe-absorbed-exposure-python.svg",
      "plotSHA256": "7c9e7d4061b4b108e574a1b5ab25f4a600ddbfd421dc2b570db7f0078fd64a3d"
    },
    {
      "api": "twfe",
      "variant": "twfe-absorbed-exposure",
      "profile": "twfe-absorbed-exposure",
      "language": "R",
      "file": "metr20-programs/twfe-absorbed-exposure-r.R",
      "codeSHA256": "5310620369b374b8312b844a6040143f62a7b94286ed7634ea4c5d519eef7348",
      "returnCode": 0,
      "expectedRejection": false,
      "title": {
        "ko": "변하지 않는 처치 지표는 미식별",
        "en": "Constant exposure is absorbed by fixed effects"
      },
      "code": "# METR20 fixed example. Base R only, finite arithmetic approximate.\r\n# No JavaScript engine,model JSON,derived answer table,private module or internet.\r\noptions(stringsAsFactors=FALSE,digits=17)\r\nargv<-commandArgs(trailingOnly=TRUE);if(length(argv)<1L)stop('Supply a new empty output directory')\r\noutdir<-argv[1];script<-sub('^--file=','',commandArgs(FALSE)[grepl('^--file=',commandArgs(FALSE))][1]);here<-dirname(normalizePath(script,mustWork=TRUE));datadir<-if(length(argv)>=2L)argv[2]else file.path(here,'..','metr20-sources')\r\nunits<-c(country='log teen-employment points',person='recorded real earnings',company='FTE employees');clocks<-c(country='calendar year',person='calendar year',company='survey-wave index');steps<-c(country=1,person=3,company=1);files<-c(country='actual2500-county-mpdta-all6-fields.csv',person='actual38408-NSW-all15-fields.csv',company='actual410-NJPA-all46-fields.csv')\r\nnum<-function(s)ifelse(s=='.',NA_real_,as.numeric(s));mean0<-function(v)if(length(v))mean(v)else NA_real_;var0<-function(v)if(length(v)>1L)sum((v-mean(v))^2)/(length(v)-1L)else NA_real_\r\n\r\nSPEC<-list(id=\"twfe-absorbed-exposure\",api=\"twfe\",title=list(ko=\"변하지 않는 처치 지표는 미식별\",en=\"Constant exposure is absorbed by fixed effects\"),input=list(rows=list(list(id=\"a:0\",entity=\"a\",time=0,y=\"2\",g=NA_real_),list(id=\"a:1\",entity=\"a\",time=1,y=\"4\",g=NA_real_),list(id=\"a:2\",entity=\"a\",time=2,y=\"8\",g=NA_real_),list(id=\"b:0\",entity=\"b\",time=0,y=\"3\",g=NA_real_),list(id=\"b:1\",entity=\"b\",time=1,y=\"5\",g=NA_real_),list(id=\"b:2\",entity=\"b\",time=2,y=\"9\",g=NA_real_))),expectedReject=FALSE)\r\npanel<-function(rows){G<-list();for(r in rows){key<-r$entity;u<-G[[key]];if(is.null(u))u<-list(g=r$g,rows=list());stopifnot(identical(u$g,r$g),is.null(u$rows[[as.character(r$time)]]));u$rows[[as.character(r$time)]]<-r;G[[key]]<-u};G}\r\ncell<-function(G,g,t,step,control){b<-g-step;members<-list();T<-C<-list();for(key in names(G)){u<-G[[key]];target<-!is.na(u$g)&&u$g==g;comp<-is.na(u$g)||(control=='notyet'&&!is.na(u$g)&&u$g>max(t,b));role<-if(target)'treated'else if(comp)'control'else'excluded-comparison';before<-u$rows[[as.character(b)]];after<-u$rows[[as.character(t)]];yb<-if(is.null(before))NA_real_ else before$y;ya<-if(is.null(after))NA_real_ else after$y;eligible<-role!='excluded-comparison'&&!is.na(yb)&&!is.na(ya);reason<-if(role=='excluded-comparison')'target-or-already-exposed-cohort-not-valid-control'else if(is.null(before))'baseline-source-row-absent'else if(is.null(after))'target-time-source-row-absent'else if(is.na(yb))'baseline-outcome-missing'else if(is.na(ya))'target-outcome-missing'else'';m<-list(entity=key,nativeID=u$rows[[1]]$nativeID,g=u$g,role=role,eligible=eligible,baselineSourceId=if(is.null(before))NA_character_ else before$id,targetSourceId=if(is.null(after))NA_character_ else after$id,before=yb,after=ya,change=if(eligible)ya-yb else NA_real_,reason=reason);members[[key]]<-m;if(eligible){if(role=='treated')T[[length(T)+1L]]<-m else C[[length(C)+1L]]<-m}}\r\n change<-function(a)vapply(a,function(r)r$change,0);d<-mean0(change(T));e<-mean0(change(C));estimate<-if(is.na(d)||is.na(e))NA_real_ else d-e;defined<-!is.na(estimate);scores<-setNames(rep(NA_real_,length(members)),names(members));for(key in names(members)){m<-members[[key]];s<-if(!defined)NA_real_ else if(!m$eligible)0 else if(m$role=='treated')(m$change-d)/length(T)else-(m$change-e)/length(C);m$score<-s;scores[key]<-s;members[[key]]<-m};st<-var0(change(T));sc<-var0(change(C));v<-if(is.na(st)||is.na(sc))NA_real_ else st/length(T)+sc/length(C);level<-function(a,k)mean0(vapply(a,function(r)r[[k]],0))\r\n list(g=g,t=t,baseline=b,event=(t-g)/step,phase=if(t==b)'mechanical-reference'else if(t>=g)'post'else'pre-placebo',defined=defined,estimate=estimate,T=T,C=C,members=members,scores=scores,HC0=if(defined)sum(scores^2)else NA_real_,unbiased=v,treatedMeanBefore=level(T,'before'),treatedMeanAfter=level(T,'after'),treatedMeanChange=d,controlMeanBefore=level(C,'before'),controlMeanAfter=level(C,'after'),controlMeanChange=e)\r\n}\r\ncovariance<-function(cells){n<-length(cells);V<-matrix(NA_real_,n,n);for(i in seq_len(n))for(j in seq_len(n))if(cells[[i]]$defined&&cells[[j]]$defined)V[i,j]<-sum(cells[[i]]$scores*cells[[j]]$scores);V}\r\naggregate_cells<-function(post,V,step){out<-list();push<-function(typ,key,ii,w){est<-if(!length(ii)||any(vapply(post[ii],function(z)is.na(z$estimate),TRUE)))NA_real_ else sum(w*vapply(post[ii],function(z)z$estimate,0));vv<-if(is.na(est)||anyNA(V[ii,ii,drop=FALSE]))NA_real_ else as.numeric(t(w)%*%V[ii,ii,drop=FALSE]%*%w);out[[length(out)+1L]]<<-list(type=typ,key=as.character(key),ii=ii,w=w,estimate=est,variance=vv)};positive<-which(vapply(post,function(c)length(c$T)>0L,TRUE));mass<-sum(vapply(post[positive],function(c)length(c$T),0));push('simple','overall',positive,if(mass)vapply(post[positive],function(c)length(c$T)/mass,0)else numeric())\r\n for(typ in c('event','calendar','group')){keys<-vapply(post,function(c)if(typ=='event')c$event else if(typ=='calendar')c$t else c$g,0);gg<-sort(unique(keys));cohortmass<-if(typ=='group')sum(vapply(gg,function(k)length(post[[which(keys==k)[1]]]$T),0))else 0;allii<-integer();allw<-numeric();for(key in gg){ii<-which(keys==key);jj<-ii[vapply(post[ii],function(c)length(c$T)>0L,TRUE)];if(typ=='group'){stopifnot(length(unique(vapply(post[ii],function(c)length(c$T),0)))<=1L);w<-if(length(jj))rep(1/length(jj),length(jj))else numeric();if(cohortmass){allii<-c(allii,jj);allw<-c(allw,w*length(post[[ii[1]]]$T)/cohortmass)}}else{total<-sum(vapply(post[jj],function(c)length(c$T),0));w<-if(total)vapply(post[jj],function(c)length(c$T)/total,0)else numeric()};push(typ,key,jj,w)};if(typ=='group')push(typ,'overall',allii,allw)};out}\r\ntwfe<-function(G,times){ledger<-list();good<-list();for(key in names(G)){u<-G[[key]];absent<-times[!as.character(times)%in%names(u$rows)];missing<-times[vapply(times,function(t){r<-u$rows[[as.character(t)]];!is.null(r)&&is.na(r$y)},TRUE)];eligible<-length(times)>0L&&!length(absent)&&!length(missing);ledger[[length(ledger)+1L]]<-list(entity=key,g=u$g,nativeID=u$rows[[1]]$nativeID,eligible=eligible,absentTimes=paste(absent,collapse=','),missingOutcomeTimes=paste(missing,collapse=','),originalRows=length(u$rows));if(eligible)good[[key]]<-u};rows<-list();for(key in names(good))for(t in times){r<-good[[key]]$rows[[as.character(t)]];r$D<-as.integer(!is.na(r$g)&&t>=r$g);rows[[length(rows)+1L]]<-r};em<-lapply(good,function(u)list(D=mean(vapply(times,function(t)as.integer(!is.na(u$g)&&t>=u$g),0)),Y=mean(vapply(u$rows[as.character(times)],function(r)r$y,0))));tm<-lapply(times,function(t)list(D=mean(vapply(good,function(u)as.integer(!is.na(u$g)&&t>=u$g),0)),Y=mean(vapply(good,function(u)u$rows[[as.character(t)]]$y,0))));names(tm)<-as.character(times);gd<-mean0(vapply(rows,function(r)r$D,0));gy<-mean0(vapply(rows,function(r)r$y,0));num<-den<-0\r\n for(i in seq_along(rows)){r<-rows[[i]];r$residualD<-r$D-em[[r$entity]]$D-tm[[as.character(r$time)]]$D+gd;r$residualY<-r$y-em[[r$entity]]$Y-tm[[as.character(r$time)]]$Y+gy;num<-num+r$residualD*r$residualY;den<-den+r$residualD^2;rows[[i]]<-r};beta<-if(den!=0)num/den else NA_real_;weights<-list();for(i in seq_along(rows)){r<-rows[[i]];r$projectionCoefficient<-if(den!=0)r$residualD/den else NA_real_;r$regressionResidual<-if(!is.na(beta))r$residualY-beta*r$residualD else NA_real_;rows[[i]]<-r;if(r$D==1L){k<-paste(r$g,r$time,sep=':');z<-weights[[k]];if(is.null(z))z<-list(g=r$g,t=r$time,rows=0,coefficient=if(den!=0)0 else NA_real_);z$rows<-z$rows+1L;if(den!=0)z$coefficient<-z$coefficient+r$projectionCoefficient;weights[[k]]<-z}};list(ledger=ledger,rows=rows,num=num,den=den,beta=beta,weights=weights,balancedEntities=length(good))}\r\nadjacent_pre<-function(G,g,t,step,control){b<-t-step;T<-C<-numeric();for(u in G){target<-!is.na(u$g)&&u$g==g;comp<-is.na(u$g)||(control=='notyet'&&!is.na(u$g)&&u$g>max(t,b));if(!target&&!comp)next;before<-u$rows[[as.character(b)]];after<-u$rows[[as.character(t)]];if(!is.null(before)&&!is.null(after)&&!is.na(before$y)&&!is.na(after$y)){if(target)T<-c(T,after$y-before$y)else C<-c(C,after$y-before$y)}};if(!length(T)||!length(C))NA_real_ else mean(T)-mean(C)}\r\n\r\n# Newly authored bounded teaching projections; base R finite approximation.\r\n# Source helper functions are inlined in each public file, never imported.\r\nqnum<-function(v){if(is.null(v)||is.na(v))return(NA_real_);s<-strsplit(as.character(v),'/',fixed=TRUE)[[1]];if(length(s)==1L)as.numeric(s)else as.numeric(s[1])/as.numeric(s[2])}\r\npaired<-function(T,C){\r\n stats<-function(rr){use<-Filter(function(r)!is.na(qnum(r$before))&&!is.na(qnum(r$after)),rr);a<-vapply(use,function(r)qnum(r$before),0);b<-vapply(use,function(r)qnum(r$after),0);list(sourcePairs=length(rr),eligiblePairs=length(use),excludedPairs=length(rr)-length(use),meanBefore=mean0(a),meanAfter=mean0(b),meanChange=mean0(b-a),sampleChangeVariance=var0(b-a))}\r\n st<-stats(T);sc<-stats(C);defined<-st$eligiblePairs>0L&&sc$eligiblePairs>0L;estimate<-if(defined)st$meanChange-sc$meanChange else NA_real_;rr<-list()\r\n for(role in c('treated','control')){input<-if(role=='treated')T else C;s<-if(role=='treated')st else sc;for(r in input){before<-qnum(r$before);after<-qnum(r$after);eligible<-!is.na(before)&&!is.na(after);change<-if(eligible)after-before else NA_real_;score<-if(!defined)NA_real_ else if(!eligible)0 else (change-s$meanChange)/(if(role=='treated')s$eligiblePairs else -s$eligiblePairs);rr[[length(rr)+1L]]<-list(id=r$id,role=role,before=before,after=after,eligible=eligible,change=change,score=score)}}\r\n list(defined=defined,estimate=estimate,treated=st,control=sc,unbiasedVariance=if(defined&&st$eligiblePairs>=2L&&sc$eligiblePairs>=2L)st$sampleChangeVariance/st$eligiblePairs+sc$sampleChangeVariance/sc$eligiblePairs else NA_real_,HC0=if(defined)sum(vapply(rr,function(r)r$score^2,0))else NA_real_,rows=rr)\r\n}\r\nliteral_panel<-function(rr)lapply(seq_along(rr),function(i){r<-rr[[i]];r$y<-qnum(r$y);r$nativeID<-r$entity;r$sourceRow<-i;r})\r\natt_projection<-function(rows,control='never',step=1){G<-panel(rows);times<-sort(unique(vapply(rows,function(r)r$time,0)));cohorts<-sort(unique(na.omit(vapply(rows,function(r)r$g,0))));cells<-list();for(g in cohorts)for(t in times)cells[[length(cells)+1L]]<-cell(G,g,t,step,control);list(sourceRows=length(rows),sourceEntities=length(G),step=step,control=control,cells=cells,covariance=covariance(cells))}\r\nlinear_aggregate<-function(a){\r\n rr<-lapply(a$cells,function(r){r$estimate<-qnum(r$estimate);r$weight<-qnum(r$weight);r});V<-if(is.null(a$covariance))NULL else do.call(rbind,lapply(a$covariance,function(r)vapply(r,qnum,0)));rank<-NA_real_\r\n if(!is.null(V)){stopifnot(nrow(V)==length(rr),ncol(V)==length(rr),all(V==t(V)));ev<-eigen(V,symmetric=TRUE,only.values=TRUE)$values;if(any(ev< -1e-12))stop('covariance-must-be-positive-semidefinite');rank<-sum(ev>1e-12)}\r\n selected<-which(vapply(rr,function(r)r$time>=r$cohort&&r$weight>0,TRUE));w<-numeric(length(rr));type<-if(is.null(a$type))'simple'else a$type\r\n if(type=='simple'){mass<-sum(vapply(rr[selected],function(r)r$weight,0));if(mass>0)for(i in selected)w[i]<-rr[[i]]$weight/mass}else{g<-vapply(rr,function(r)r$cohort,0);gg<-sort(unique(g[selected]));mass<-sum(vapply(gg,function(gi)rr[[intersect(which(g==gi),selected)[1]]]$weight,0));for(gi in gg){ii<-intersect(which(g==gi),selected);stopifnot(length(unique(vapply(rr[ii],function(r)r$weight,0)))==1L);w[ii]<-rr[[ii[1]]]$weight/mass/length(ii)}}\r\n used<-which(w>0);estimate<-if(!length(used)||any(vapply(rr[used],function(r)is.na(r$estimate),TRUE)))NA_real_ else sum(w[used]*vapply(rr[used],function(r)r$estimate,0));variance<-if(is.na(estimate)||is.null(V))NA_real_ else as.numeric(t(w)%*%V%*%w);weights<-lapply(used,function(i)list(sourceIndex=i-1L,cohort=rr[[i]]$cohort,time=rr[[i]]$time,coefficient=w[i],estimate=rr[[i]]$estimate,contribution=w[i]*rr[[i]]$estimate))\r\n list(type=type,defined=!is.na(estimate),estimate=estimate,variance=variance,covarianceRank=rank,weights=weights,cells=rr,covariance=V)\r\n}\r\nsensitivity_fixed<-function(a){estimate<-qnum(a$estimate);M<-qnum(a$M);h<-if(is.null(a$horizon))1 else a$horizon;stopifnot(M>=0,h>=1);pre<-vapply(a$preDifferences,qnum,0);scale<-if(!is.null(a$scale))qnum(a$scale)else if(length(pre))max(abs(pre))else NA_real_;budget<-M*scale*h;list(defined=!is.na(scale),estimate=estimate,scale=scale,M=M,horizon=h,biasBudget=budget,lower=estimate-budget,upper=estimate+budget,preDifferences=as.list(pre),confidenceLevel=NULL)}\r\nrealdata_fixed<-function(kind){rows<-models[[kind]];G<-panel(rows);times<-sort(unique(vapply(rows,function(r)r$time,0)));step<-unname(steps[kind]);aa<-att_projection(rows,'never',step);post<-Filter(function(r)r$phase=='post',aa$cells);aggs<-aggregate_cells(post,covariance(post),step);tf<-twfe(G,times);list(kind=kind,unit=unname(units[kind]),periodUnit=unname(clocks[kind]),nativeRows=nrow(raw[[kind]]),modelRows=length(rows),entities=length(G),sourceRows=rows,att=aa,aggregations=aggs,twfe=tf,scope='Complete native/model/paired/balanced source frames; never control,universal base,no anticipation;not causal/sampling certification.')}\r\n# JSON encoder deliberately handles matrices and scalar/vector distinctions.\r\nencode<-function(x){\r\n if(is.null(x))return('null')\r\n quote<-function(s){s<-gsub('\\\\','\\\\\\\\',as.character(s),fixed=TRUE);s<-gsub('\"','\\\\\"',s,fixed=TRUE);s<-gsub('\\n','\\\\n',s,fixed=TRUE);s<-gsub('\\r','\\\\r',s,fixed=TRUE);s<-gsub('\\t','\\\\t',s,fixed=TRUE);paste0('\"',s,'\"')}\r\n if(is.matrix(x))return(paste0('[',paste(vapply(seq_len(nrow(x)),function(i)encode(as.list(unname(x[i,]))),''),collapse=','),']'))\r\n if(is.list(x)){if(length(x)&&!is.null(names(x)))return(paste0('{',paste(paste0(vapply(names(x),quote,''),':',vapply(x,encode,'')),collapse=','),'}'));return(paste0('[',paste(vapply(x,encode,''),collapse=','),']'))}\r\n if(length(x)!=1L)return(encode(as.list(unname(x))))\r\n if(is.na(x))return('null');if(is.logical(x))return(if(x)'true'else'false');if(is.numeric(x))return(sprintf('%.17g',unname(x)));quote(x)\r\n}\r\nv9<-function(x){if(is.null(x)||is.na(x))return('undefined');if(is.logical(x))return(if(x)'1'else'0');if(is.numeric(x))return(sprintf('%.9g',unname(x)));as.character(x)}\r\nrun_fixed<-function(spec,out){api<-spec$api;a<-spec$input;summary<-list();points<-list();emit<-function(series,x,y){points[[length(points)+1L]]<<-list(series=series,x=x,y=y,numericY=y)}\r\n if(api=='twobytwo'){result<-paired(a$treated,a$control);summary<-list(defined=result$defined,estimate=result$estimate,treatedPairs=result$treated$eligiblePairs,controlPairs=result$control$eligiblePairs,unbiasedVariance=result$unbiasedVariance,HC0=result$HC0);for(i in seq_along(result$rows)){r<-result$rows[[i]];emit(paste(r$role,r$id,sep=':'),i,r$change)}}\r\n else if(api=='att'){result<-att_projection(literal_panel(a$rows),a$control);summary<-list(sourceRows=result$sourceRows,entities=result$sourceEntities,cells=length(result$cells),supportedCells=sum(vapply(result$cells,function(r)r$defined,TRUE)),postCells=sum(vapply(result$cells,function(r)r$phase=='post',TRUE)));for(i in seq_along(result$cells)){r<-result$cells[[i]];emit(paste0('g',r$g,':t',r$t),i,r$estimate)}}\r\n else if(api=='aggregate'){result<-linear_aggregate(a);summary<-list(defined=result$defined,estimate=result$estimate,variance=result$variance,covarianceRank=result$covarianceRank,sumWeights=sum(vapply(result$weights,function(r)r$coefficient,0)));for(i in seq_along(result$weights)){r<-result$weights[[i]];emit(paste0('g',r$cohort,':t',r$time),i,r$contribution)}}\r\n else if(api=='twfe'){rows<-literal_panel(a$rows);G<-panel(rows);result<-twfe(G,sort(unique(vapply(rows,function(r)r$time,0))));summary<-list(defined=!is.na(result$beta),beta=result$beta,numerator=result$num,denominator=result$den,balancedEntities=result$balancedEntities,negativeTreatedCells=sum(vapply(result$weights,function(r)!is.na(r$coefficient)&&r$coefficient<0,TRUE)));if(length(result$weights)){ord<-order(vapply(result$weights,function(r)r$g,0),vapply(result$weights,function(r)r$t,0));for(i in seq_along(ord)){r<-result$weights[[ord[i]]];emit(paste0('g',r$g,':t',r$t),i,r$coefficient)}}}\r\n else if(api=='sensitivity'){result<-sensitivity_fixed(a);summary<-result[c('defined','estimate','scale','M','horizon','biasBudget','lower','upper')];for(i in seq_along(c('lower','estimate','upper'))){k<-c('lower','estimate','upper')[i];emit(k,i,if(result$defined)result[[k]]else NA_real_)}}\r\n else{result<-realdata_fixed(a$kind);post<-Filter(function(r)r$phase=='post',result$att$cells);simple<-Filter(function(r)r$type=='simple',result$aggregations)[[1]];group<-Filter(function(r)r$type=='group'&&r$key=='overall',result$aggregations)[[1]];summary<-list(nativeRows=result$nativeRows,modelRows=result$modelRows,entities=result$entities,postCells=length(post),simple=simple$estimate,group=group$estimate,TWFE=result$twfe$beta,balancedEntities=result$twfe$balancedEntities);for(i in seq_along(post)){r<-post[[i]];emit(paste0('g',r$g,':t',r$t),i,r$estimate)}}\r\n dir.create(out,recursive=TRUE,showWarnings=FALSE);if(length(list.files(out,all.files=TRUE,no..=TRUE)))stop('use-new-empty-output-directory');shown<-lapply(summary,v9);write.csv(data.frame(name=names(shown),value=unlist(shown,use.names=FALSE)),file.path(out,'summary.csv'),row.names=FALSE,na='');pointframe<-if(length(points))do.call(rbind,lapply(points,function(p)data.frame(series=p$series,x=p$x,y=p$y,numericY=p$numericY,stringsAsFactors=FALSE)))else data.frame(series=character(),x=numeric(),y=numeric(),numericY=numeric());write.csv(pointframe,file.path(out,'points.csv'),row.names=FALSE,na='');full<-list(chapter='METR-20',profile=spec$id,api=api,input=spec$input,summary=shown,points=points,details=result,arithmetic='Base R approximate finite values;bounded teaching projection,not exact fractions or causal/sampling certification.');writeLines(encode(full),file.path(out,'full.json'),useBytes=TRUE)\r\n svg(file.path(out,'plot.svg'),width=9,height=5.6,pointsize=12);par(mar=c(4.5,5.5,4,1));good<-pointframe[!is.na(pointframe$numericY),,drop=FALSE]\r\n if(nrow(good)){plot(good$x,good$numericY,pch=19,col='#315d7c',xlab='Declared cell/unit/bound ordinal',ylab=if(api=='twfe')'Cell weight'else if(!is.null(result$unit))result$unit else 'Stated outcome/bias units',main=spec$title$en);abline(h=0,col='#9eabb2');grid(nx=NA,ny=NULL,col='#e2e5e7');points(good$x,good$numericY,pch=19,col='#315d7c')}else{plot.new();text(.5,.5,'Undefined: no supported plotted quantity');title(main=spec$title$en)};dev.off();cat(encode(shown),'\\n')\r\n}\r\n\r\nrun_fixed(SPEC,outdir)\r\n",
      "arithmetic": "Base R approximate finite arithmetic;not an exact rational result",
      "summary": {
        "defined": "0",
        "beta": "undefined",
        "numerator": "0",
        "denominator": "0",
        "balancedEntities": "2",
        "negativeTreatedCells": "0"
      },
      "fullResultEmbedded": false,
      "plotEmbedded": false,
      "full": {
        "summary": {
          "defined": "0",
          "beta": "undefined",
          "numerator": "0",
          "denominator": "0",
          "balancedEntities": "2",
          "negativeTreatedCells": "0"
        },
        "notice": "Complete source/finite projection is retained in the linked external JSON; this short projection is not the full result."
      },
      "plot": null,
      "points": [],
      "summaryFile": "metr20-programs/twfe-absorbed-exposure-r-summary.csv",
      "summarySHA256": "585053589ecd551d58b076bc07269c51edbf5c96aaf32989a15297b1c49c0776",
      "pointsFile": "metr20-programs/twfe-absorbed-exposure-r-points.csv",
      "pointsSHA256": "c4a8afc53fa842dd6915db89ef0f29155a4d8a3d91edb464aa28a55eba811105",
      "fullResultFile": "metr20-programs/twfe-absorbed-exposure-r.json",
      "fullResultSHA256": "9c7571b9670281395c36719f73146a8795ade212df6ae09105d4900c1b791dca",
      "plotFile": "metr20-programs/twfe-absorbed-exposure-r.svg",
      "plotSHA256": "3b1ca97281fbf73b1e1856e94dec05d6d8c2baa7e182ee736a41bc1d58e861c0"
    },
    {
      "api": "sensitivity",
      "variant": "sensitivity-stated-budget",
      "profile": "sensitivity-stated-budget",
      "language": "Python",
      "file": "metr20-programs/sensitivity-stated-budget-python.py",
      "codeSHA256": "7a25893c0d7c3cb64b06beafc93cc455bfd0fc06e329efa8d320228edc10d7c6",
      "returnCode": 0,
      "expectedRejection": false,
      "title": {
        "ko": "관측 규모와 선언한 3기간 편의 예산",
        "en": "Observed scale and a stipulated three-period budget"
      },
      "code": "\"\"\"METR20 actual sources. Python standard library, exact stored-value rationals.\r\nRead ONLY the three native-observation CSVs; no JS engine,model JSON,derived\r\nanswers,private modules or internet needed. Outcome measurement/identification\r\nand valid sampling inference remain separate from exact finite arithmetic.\r\nRun: python metr20-reproduce.py --data-dir PATH --out NEW_EMPTY_DIRECTORY\r\n\"\"\"\r\nfrom pathlib import Path\r\nfrom fractions import Fraction as Q\r\nfrom collections import defaultdict,Counter\r\nimport csv,json,math,argparse,hashlib\r\n\r\nUNIT={'country':'log teen-employment points','person':'recorded real earnings','company':'FTE employees'}\r\nCLOCK={'country':'calendar year','person':'calendar year','company':'survey-wave index'}\r\nSTEP={'country':1,'person':3,'company':1}\r\nFILES={'country':'actual2500-county-mpdta-all6-fields.csv','person':'actual38408-NSW-all15-fields.csv','company':'actual410-NJPA-all46-fields.csv'}\r\ndef avg(v):return sum(v,Q(0))/len(v)if v else None\r\ndef samplevar(v):return sum(((x-avg(v))**2 for x in v),Q(0))/(len(v)-1)if len(v)>1 else None\r\ndef binary(s):return None if s=='.'else Q.from_float(float(s))\r\ndef token(v):\r\n if v is None:return ''\r\n if isinstance(v,bool):return 'true'if v else'false'\r\n return str(v)\r\ndef safe_float(v):\r\n if v is None:return None\r\n try:r=float(v)\r\n except OverflowError:return None\r\n return r if math.isfinite(r)else None\r\ndef read(p):\r\n with p.open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))\r\ndef write(p,rows,head=None):\r\n if head is None:\r\n  assert rows;head=list(rows[0])\r\n with p.open('w',encoding='utf8',newline='')as f:\r\n  w=csv.DictWriter(f,fieldnames=head);w.writeheader();w.writerows({k:token(r.get(k))for k in head}for r in rows)\r\ndef source(data):\r\n raw={k:read(data/n)for k,n in FILES.items()};assert[len(raw[k])for k in FILES]==[2500,38408,410]\r\n models={k:[]for k in FILES}\r\n for r in raw['country']:\r\n  g0=int(r['first.treat']);g=None if g0==0 else g0;assert int(r['treat'])==int(g is not None)\r\n  models['country'].append(dict(id='mpdta:'+r['sourceRow'],entity='county:'+str(int(r['countyreal'])),time=int(r['year']),y=binary(r['lemp']),g=g,sourceRow=int(r['sourceRow']),nativeID=r['countyreal']))\r\n for r in raw['person']:\r\n  selected=int(r['experimental'])==1;assert selected==(int(r['sample'])==1);assert(r['treated']!='.')==selected\r\n  if selected:\r\n   d=int(r['treated']);assert d in[0,1]\r\n   models['person'].append(dict(id='nsw:'+r['sourceRow'],entity='nsw-id:'+str(int(r['id'])),time=int(r['year']),y=binary(r['re']),g=1978 if d else None,sourceRow=int(r['sourceRow']),nativeID=str(int(r['id']))))\r\n for r in raw['company']:\r\n  state=int(r['STATE']);assert state in[0,1]\r\n  for t,suffix in[(0,''),(1,'2')]:\r\n   a=[r[n+suffix]for n in['EMPFT','NMGRS','EMPPT']];y=None if'.'in a else Q(a[0])+Q(a[1])+Q(a[2])/2\r\n   models['company'].append(dict(id='njpa:'+r['sourceRow']+':wave'+str(t),entity='njpa-row:'+r['sourceRow'],time=t,y=y,g=1 if state else None,sourceRow=int(r['sourceRow']),nativeID=r['SHEET']))\r\n assert[len(models[k])for k in FILES]==[2500,1444,820]\r\n return models,raw\r\ndef panel(rows):\r\n groups={}\r\n for r in rows:\r\n  u=groups.setdefault(r['entity'],{'g':r['g'],'rows':{}});assert u['g']==r['g']and r['time']not in u['rows'];u['rows'][r['time']]=r\r\n return groups\r\ndef cell(groups,g,t,step,control):\r\n b=g-step;members=[];T=[];C=[]\r\n for key,u in groups.items():\r\n  role='treated'if u['g']==g else'control'if u['g']is None or(control=='notyet'and u['g']>max(t,b))else'excluded-comparison'\r\n  before=u['rows'].get(b);after=u['rows'].get(t);yb=None if before is None else before['y'];ya=None if after is None else after['y'];eligible=role!='excluded-comparison'and yb is not None and ya is not None\r\n  reason='target-or-already-exposed-cohort-not-valid-control'if role=='excluded-comparison'else'baseline-source-row-absent'if before is None else'target-time-source-row-absent'if after is None else'baseline-outcome-missing'if yb is None else'target-outcome-missing'if ya is None else''\r\n  m={'entity':key,'nativeID':next(iter(u['rows'].values()))['nativeID'],'g':u['g'],'role':role,'eligible':eligible,'baselineSourceId':None if before is None else before['id'],'targetSourceId':None if after is None else after['id'],'before':yb,'after':ya,'change':ya-yb if eligible else None,'reason':reason};members.append(m)\r\n  if eligible:(T if role=='treated'else C).append(m)\r\n d=avg([r['change']for r in T]);e=avg([r['change']for r in C]);estimate=None if d is None or e is None else d-e;defined=estimate is not None;scores={}\r\n for m in members:\r\n  s=None if not defined else Q(0)\r\n  if defined and m['eligible']:s=(m['change']-(d if m['role']=='treated'else e))/(len(T)if m['role']=='treated'else-len(C))\r\n  m['score']=s;scores[m['entity']]=s\r\n st=samplevar([r['change']for r in T]);sc=samplevar([r['change']for r in C]);v=None if st is None or sc is None else st/len(T)+sc/len(C)\r\n return {'g':g,'t':t,'baseline':b,'event':(t-g)//step,'phase':'mechanical-reference'if t==b else'post'if t>=g else'pre-placebo','defined':defined,'estimate':estimate,'T':T,'C':C,'members':members,'scores':scores,'HC0':None if not defined else sum((s*s for s in scores.values()),Q(0)),'unbiased':v,'treatedMeanBefore':avg([r['before']for r in T]),'treatedMeanAfter':avg([r['after']for r in T]),'treatedMeanChange':d,'controlMeanBefore':avg([r['before']for r in C]),'controlMeanAfter':avg([r['after']for r in C]),'controlMeanChange':e}\r\ndef covariance(cells):\r\n return[[None if not a['defined']or not b['defined']else sum((v*b['scores'][i]for i,v in a['scores'].items()),Q(0))for b in cells]for a in cells]\r\ndef aggregate(post,V,step):\r\n out=[]\r\n def push(typ,key,coeff):\r\n  estimate=None if not coeff or any(post[i]['estimate']is None for i in coeff)else sum((w*post[i]['estimate']for i,w in coeff.items()),Q(0));variance=None if estimate is None or any(V[i][j]is None for i in coeff for j in coeff)else sum((a*b*V[i][j]for i,a in coeff.items()for j,b in coeff.items()),Q(0));out.append({'type':typ,'key':key,'coeff':coeff,'estimate':estimate,'variance':variance})\r\n positive=[i for i,c in enumerate(post)if len(c['T'])>0];mass=sum(len(post[i]['T'])for i in positive)\r\n push('simple','overall',{i:Q(len(post[i]['T']),mass)for i in positive}if mass else{})\r\n for typ in['event','calendar','group']:\r\n  groups=defaultdict(list)\r\n  for i,c in enumerate(post):groups[c['event']if typ=='event'else c['t']if typ=='calendar'else c['g']].append(i)\r\n  overall={};cohortMass=sum(len(post[ii[0]]['T'])for ii in groups.values())if typ=='group'else 0\r\n  for key,ii in sorted(groups.items()):\r\n   jj=[i for i in ii if len(post[i]['T'])>0]\r\n   if typ=='group':\r\n    assert len({len(post[i]['T'])for i in ii})<=1\r\n    coeff={i:Q(1,len(jj))for i in jj}if jj else{}\r\n    if cohortMass:\r\n     for i,w in coeff.items():overall[i]=w*Q(len(post[ii[0]]['T']),cohortMass)\r\n   else:\r\n    total=sum(len(post[i]['T'])for i in jj);coeff={i:Q(len(post[i]['T']),total)for i in jj}if total else{}\r\n   push(typ,str(key),coeff)\r\n  if typ=='group':push(typ,'overall',overall)\r\n return out\r\ndef twfe(groups,times):\r\n ledger=[];good={}\r\n for key,u in groups.items():\r\n  absent=[t for t in times if t not in u['rows']];missing=[t for t in times if t in u['rows']and u['rows'][t]['y']is None];eligible=bool(times)and not absent and not missing\r\n  ledger.append({'entity':key,'g':u['g'],'nativeID':next(iter(u['rows'].values()))['nativeID'],'eligible':eligible,'absentTimes':','.join(map(str,absent)),'missingOutcomeTimes':','.join(map(str,missing)),'originalRows':len(u['rows'])})\r\n  if eligible:good[key]=u\r\n rows=[dict(**u['rows'][t],D=Q(u['g']is not None and t>=u['g']))for key,u in good.items()for t in times]\r\n em={k:{'D':avg([Q(u['g']is not None and t>=u['g'])for t in times]),'Y':avg([u['rows'][t]['y']for t in times])}for k,u in good.items()};tm={t:{'D':avg([Q(u['g']is not None and t>=u['g'])for u in good.values()]),'Y':avg([u['rows'][t]['y']for u in good.values()])}for t in times};gd=avg([r['D']for r in rows]);gy=avg([r['y']for r in rows]);num=den=Q(0)\r\n for r in rows:\r\n  r['residualD']=r['D']-em[r['entity']]['D']-tm[r['time']]['D']+gd;r['residualY']=r['y']-em[r['entity']]['Y']-tm[r['time']]['Y']+gy;num+=r['residualD']*r['residualY'];den+=r['residualD']**2\r\n beta=num/den if den else None;weights={}\r\n for r in rows:\r\n  r['projectionCoefficient']=r['residualD']/den if den else None;r['regressionResidual']=r['residualY']-beta*r['residualD']if beta is not None else None\r\n  if r['D']:\r\n   k=(r['g'],r['time']);z=weights.setdefault(k,{'rows':0,'coefficient':Q(0)if den else None});z['rows']+=1\r\n   if den:z['coefficient']+=r['projectionCoefficient']\r\n return {'ledger':ledger,'rows':rows,'num':num,'den':den,'beta':beta,'weights':weights,'balancedEntities':len(good)}\r\ndef adjacent_pre(groups,g,t,step,control):\r\n b=t-step;T=[];C=[]\r\n for u in groups.values():\r\n  if u['g']==g:target=T\r\n  elif u['g']is None or(control=='notyet'and u['g']>max(t,b)):target=C\r\n  else:continue\r\n  before=u['rows'].get(b);after=u['rows'].get(t)\r\n  if before is not None and after is not None and before['y']is not None and after['y']is not None:target.append(after['y']-before['y'])\r\n return None if not T or not C else avg(T)-avg(C)\r\n\r\n\"\"\"New bounded teaching projections. The program is self-contained after build.\r\nExact Fraction finite algebra; figures and9-digit summary are approximations.\r\nIt is not a general parser/API replacement or a causal/inference certificate.\r\n\"\"\"\r\ndef paired(treated,control):\r\n def stats(rr):\r\n  use=[r for r in rr if r['before']is not None and r['after']is not None];delta=[Q(r['after'])-Q(r['before'])for r in use]\r\n  return dict(sourcePairs=len(rr),eligiblePairs=len(use),excludedPairs=len(rr)-len(use),meanBefore=avg([Q(r['before'])for r in use]),meanAfter=avg([Q(r['after'])for r in use]),meanChange=avg(delta),sampleChangeVariance=samplevar(delta))\r\n T,C=stats(treated),stats(control);defined=T['eligiblePairs']>0 and C['eligiblePairs']>0;estimate=T['meanChange']-C['meanChange']if defined else None;records=[]\r\n for group,rr,s in [('treated',treated,T),('control',control,C)]:\r\n  for r in rr:\r\n   before=None if r['before']is None else Q(r['before']);after=None if r['after']is None else Q(r['after']);eligible=before is not None and after is not None;delta=after-before if eligible else None;score=None if not defined else Q(0)if not eligible else(delta-s['meanChange'])/(s['eligiblePairs']if group=='treated'else-s['eligiblePairs']);records.append(dict(id=r['id'],role=group,before=before,after=after,eligible=eligible,change=delta,score=score))\r\n unbiased=None if not defined or T['eligiblePairs']<2 or C['eligiblePairs']<2 else T['sampleChangeVariance']/T['eligiblePairs']+C['sampleChangeVariance']/C['eligiblePairs'];hc0=None if not defined else sum((r['score']**2 for r in records),Q(0))\r\n return dict(defined=defined,estimate=estimate,treated=T,control=C,unbiasedVariance=unbiased,HC0=hc0,rows=records)\r\ndef literal_panel(raw):\r\n return[dict(r,y=None if r['y']is None else Q(r['y']),nativeID=r['entity'],sourceRow=i+1)for i,r in enumerate(raw)]\r\ndef att_projection(rows,control='never',step=1):\r\n G=panel(rows);times=sorted({r['time']for r in rows});cohorts=sorted({r['g']for r in rows if r['g']is not None});cells=[cell(G,g,t,step,control)for g in cohorts for t in times]\r\n return dict(sourceRows=len(rows),sourceEntities=len(G),step=step,control=control,cells=cells,covariance=covariance(cells))\r\ndef psd(V):\r\n A=[r[:]for r in V];rank=0\r\n while A:\r\n  if any(A[i][i]<0 for i in range(len(A))):raise ValueError('covariance-must-be-positive-semidefinite')\r\n  p=next((i for i in range(len(A))if A[i][i]>0),None)\r\n  if p is None:\r\n   if any(v for r in A for v in r):raise ValueError('covariance-must-be-positive-semidefinite')\r\n   return rank\r\n  A[0],A[p]=A[p],A[0]\r\n  for r in A:r[0],r[p]=r[p],r[0]\r\n  d=A[0][0];A=[[A[i][j]-A[i][0]*A[0][j]/d for j in range(1,len(A))]for i in range(1,len(A))];rank+=1\r\n return rank\r\ndef linear_aggregate(a):\r\n rr=[dict(r,estimate=None if r['estimate']is None else Q(r['estimate']),weight=Q(r['weight']))for r in a['cells']];V=[[Q(v)for v in r]for r in a['covariance']]if 'covariance'in a else None\r\n if V is not None:\r\n  assert len(V)==len(rr)and all(len(z)==len(rr)for z in V);assert all(V[i][j]==V[j][i]for i in range(len(rr))for j in range(len(rr)));rank=psd(V)\r\n else:rank=None\r\n selected=[i for i,r in enumerate(rr)if r['time']>=r['cohort']and r['weight']>0];weights={}\r\n if a.get('type','simple')=='simple':\r\n  mass=sum((rr[i]['weight']for i in selected),Q(0));weights={i:rr[i]['weight']/mass for i in selected}if mass else{}\r\n else:\r\n  gg=defaultdict(list)\r\n  for i in selected:gg[rr[i]['cohort']].append(i)\r\n  assert all(len({rr[i]['weight']for i in ii})==1 for ii in gg.values());mass=sum((rr[ii[0]]['weight']for ii in gg.values()),Q(0));weights={i:rr[ii[0]]['weight']/mass/len(ii)for ii in gg.values()for i in ii}if mass else{}\r\n estimate=None if not weights or any(rr[i]['estimate']is None for i in weights)else sum((w*rr[i]['estimate']for i,w in weights.items()),Q(0));variance=None if estimate is None or V is None else sum((x*y*V[i][j]for i,x in weights.items()for j,y in weights.items()),Q(0))\r\n return dict(type=a.get('type','simple'),defined=estimate is not None,estimate=estimate,variance=variance,covarianceRank=rank,weights=[dict(sourceIndex=i,cohort=rr[i]['cohort'],time=rr[i]['time'],coefficient=w,estimate=rr[i]['estimate'],contribution=None if rr[i]['estimate']is None else w*rr[i]['estimate'])for i,w in weights.items()],cells=rr,covariance=V)\r\ndef sensitivity_fixed(a):\r\n estimate=Q(a['estimate']);M=Q(a['M']);h=a.get('horizon',1);assert M>=0 and h>=1\r\n pre=[Q(v)for v in a.get('preDifferences',[])];scale=Q(a['scale'])if 'scale'in a else max(map(abs,pre))if pre else None;budget=None if scale is None else M*scale*h\r\n return dict(defined=scale is not None,estimate=estimate,scale=scale,M=M,horizon=h,biasBudget=budget,lower=None if budget is None else estimate-budget,upper=None if budget is None else estimate+budget,preDifferences=pre,confidenceLevel=None)\r\ndef realdata_fixed(kind,data):\r\n models,raw=source(data);rows=models[kind];G=panel(rows);times=sorted({r['time']for r in rows});step=STEP[kind];aa=att_projection(rows,'never',step);post=[r for r in aa['cells']if r['phase']=='post'];aggs=aggregate(post,covariance(post),step);tf=twfe(G,times)\r\n return dict(kind=kind,unit=UNIT[kind],periodUnit=CLOCK[kind],nativeRows=len(raw[kind]),modelRows=len(rows),entities=len(G),sourceRows=rows,att=aa,aggregations=aggs,twfe=tf,scope='Complete source frame; never-treated comparison,universal baseline,no anticipation. Native/model/paired/balanced denominators differ. All sampling/causal assumptions remain separate.')\r\ndef encode(v):\r\n if isinstance(v,Q):return str(v)\r\n if isinstance(v,dict):return{str(k):encode(x)for k,x in v.items()}\r\n if isinstance(v,(list,tuple)):return[encode(x)for x in v]\r\n return v\r\ndef v9(v):\r\n if v is None:return'undefined'\r\n if isinstance(v,str):return v\r\n if isinstance(v,bool):return'1'if v else'0'\r\n return format(float(v),'.9g')\r\ndef run_fixed(spec,out,data):\r\n api=spec['api'];a=spec['input'];summary={};points=[]\r\n def emit(series,x,y):points.append(dict(series=series,x=x,y=y,numericY=safe_float(y)))\r\n if api=='twobytwo':\r\n  result=paired(a['treated'],a['control']);summary=dict(defined=result['defined'],estimate=result['estimate'],treatedPairs=result['treated']['eligiblePairs'],controlPairs=result['control']['eligiblePairs'],unbiasedVariance=result['unbiasedVariance'],HC0=result['HC0'])\r\n  for i,r in enumerate(result['rows']):emit(r['role']+':'+r['id'],i+1,r['change'])\r\n elif api=='att':\r\n  result=att_projection(literal_panel(a['rows']),a.get('control','never'));summary=dict(sourceRows=result['sourceRows'],entities=result['sourceEntities'],cells=len(result['cells']),supportedCells=sum(r['defined']for r in result['cells']),postCells=sum(r['phase']=='post'for r in result['cells']))\r\n  for i,r in enumerate(result['cells']):emit('g'+str(r['g'])+':t'+str(r['t']),i+1,r['estimate'])\r\n elif api=='aggregate':\r\n  result=linear_aggregate(a);summary=dict(defined=result['defined'],estimate=result['estimate'],variance=result['variance'],covarianceRank=result['covarianceRank'],sumWeights=sum((r['coefficient']for r in result['weights']),Q(0)))\r\n  for i,r in enumerate(result['weights']):emit('g'+str(r['cohort'])+':t'+str(r['time']),i+1,r['contribution'])\r\n elif api=='twfe':\r\n  rows=literal_panel(a['rows']);G=panel(rows);result=twfe(G,sorted({r['time']for r in rows}));summary=dict(defined=result['beta']is not None,beta=result['beta'],numerator=result['num'],denominator=result['den'],balancedEntities=result['balancedEntities'],negativeTreatedCells=sum(v['coefficient']is not None and v['coefficient']<0 for v in result['weights'].values()))\r\n  for i,((g,t),r)in enumerate(sorted(result['weights'].items())):emit('g'+str(g)+':t'+str(t),i+1,r['coefficient'])\r\n elif api=='sensitivity':\r\n  result=sensitivity_fixed(a);summary={k:result[k]for k in['defined','estimate','scale','M','horizon','biasBudget','lower','upper']}\r\n  for i,k in enumerate(['lower','estimate','upper']):emit(k,i+1,result[k]if result['defined']else None)\r\n else:\r\n  result=realdata_fixed(a['kind'],data);post=[r for r in result['att']['cells']if r['phase']=='post'];s=next(r for r in result['aggregations']if r['type']=='simple');g=next(r for r in result['aggregations']if r['type']=='group'and r['key']=='overall');summary=dict(nativeRows=result['nativeRows'],modelRows=result['modelRows'],entities=result['entities'],postCells=len(post),simple=s['estimate'],group=g['estimate'],TWFE=result['twfe']['beta'],balancedEntities=result['twfe']['balancedEntities'])\r\n  for i,r in enumerate(post):emit('g'+str(r['g'])+':t'+str(r['t']),i+1,r['estimate'])\r\n out.mkdir(parents=True,exist_ok=True)\r\n if any(out.iterdir()):raise ValueError('use-new-empty-output-directory')\r\n shown={k:v9(v)for k,v in summary.items()};write(out/'summary.csv',[dict(name=k,value=v)for k,v in shown.items()]);write(out/'points.csv',points,['series','x','y','numericY']);full=dict(chapter='METR-20',profile=spec['id'],api=api,input=spec['input'],summary=shown,points=encode(points),details=encode(result),arithmetic='Python Fraction exact finite stored values;summary/plot approximate;bounded teaching projection,not causal or sampling certification')\r\n (out/'full.json').write_text(json.dumps(full,ensure_ascii=False,indent=2,allow_nan=False)+'\\n',encoding='utf8')\r\n import matplotlib\r\n matplotlib.use('Agg')\r\n import matplotlib.pyplot as plt\r\n plt.rcParams.update({'svg.fonttype':'none','font.family':'DejaVu Sans','font.size':12,'axes.spines.top':False,'axes.spines.right':False});fig,ax=plt.subplots(figsize=(9,5.6));good=[r for r in points if r['numericY']is not None]\r\n if good:\r\n  ax.scatter([r['x']for r in good],[r['numericY']for r in good],color='#315d7c',s=32);ax.axhline(0,color='#9eabb2',lw=.8);ax.set_xlabel('Declared cell/unit/bound ordinal')\r\n else:ax.text(.5,.5,'Undefined: no supported plotted quantity',ha='center',va='center',transform=ax.transAxes);ax.set_xticks([]);ax.set_yticks([])\r\n ax.set_ylabel('Cell weight'if api=='twfe'else result.get('unit','Stated outcome/bias units'));ax.set_title(spec['title']['en'],wrap=True,pad=14);ax.grid(axis='y',alpha=.2);fig.tight_layout(pad=2);fig.savefig(out/'plot.svg');plt.close(fig);print(json.dumps(shown))\r\n\r\nSPEC={'id': 'sensitivity-stated-budget', 'api': 'sensitivity', 'title': {'ko': '관측 규모와 선언한 3기간 편의 예산', 'en': 'Observed scale and a stipulated three-period budget'}, 'input': {'estimate': '4', 'preDifferences': ['-1/10', '1/5'], 'M': '2', 'horizon': 3}, 'expectedReject': False}\r\nif __name__=='__main__':\r\n import sys\r\n run_fixed(SPEC,Path(sys.argv[1]),Path(sys.argv[2])if len(sys.argv)>2 else Path(__file__).resolve().parent.parent/'metr20-sources')\r\n",
      "arithmetic": "Python Fraction exact stored finite values;logs/summary/plots approximate",
      "summary": {
        "defined": "1",
        "estimate": "4",
        "scale": "0.2",
        "M": "2",
        "horizon": "3",
        "biasBudget": "1.2",
        "lower": "2.8",
        "upper": "5.2"
      },
      "fullResultEmbedded": false,
      "plotEmbedded": false,
      "full": {
        "summary": {
          "defined": "1",
          "estimate": "4",
          "scale": "0.2",
          "M": "2",
          "horizon": "3",
          "biasBudget": "1.2",
          "lower": "2.8",
          "upper": "5.2"
        },
        "notice": "Complete source/finite projection is retained in the linked external JSON; this short projection is not the full result."
      },
      "plot": null,
      "points": [
        {
          "series": "lower",
          "x": 1,
          "y": "14/5",
          "numericY": 2.8
        },
        {
          "series": "estimate",
          "x": 2,
          "y": "4",
          "numericY": 4.0
        },
        {
          "series": "upper",
          "x": 3,
          "y": "26/5",
          "numericY": 5.2
        }
      ],
      "summaryFile": "metr20-programs/sensitivity-stated-budget-python-summary.csv",
      "summarySHA256": "37858448c0d6b3b0b295b52c85c9bb1ed22e763e5af72f2243aeaf5f42c945a2",
      "pointsFile": "metr20-programs/sensitivity-stated-budget-python-points.csv",
      "pointsSHA256": "ea1099e1a32b6ae063e11d14884def05bc93f92f445900997946c64047218505",
      "fullResultFile": "metr20-programs/sensitivity-stated-budget-python.json",
      "fullResultSHA256": "31ed0388be23920f6663878c3dc33c164407e1578ec1c360a9b36abb6055517c",
      "plotFile": "metr20-programs/sensitivity-stated-budget-python.svg",
      "plotSHA256": "586ed15e2d3c204ef2236420b6b74a9a029463d211c4d568dc45be289f557643"
    },
    {
      "api": "sensitivity",
      "variant": "sensitivity-stated-budget",
      "profile": "sensitivity-stated-budget",
      "language": "R",
      "file": "metr20-programs/sensitivity-stated-budget-r.R",
      "codeSHA256": "020be362f9233f1c651d3c07dc191ca6c724338e4a3cc34b557d3f0f862f1e99",
      "returnCode": 0,
      "expectedRejection": false,
      "title": {
        "ko": "관측 규모와 선언한 3기간 편의 예산",
        "en": "Observed scale and a stipulated three-period budget"
      },
      "code": "# METR20 fixed example. Base R only, finite arithmetic approximate.\r\n# No JavaScript engine,model JSON,derived answer table,private module or internet.\r\noptions(stringsAsFactors=FALSE,digits=17)\r\nargv<-commandArgs(trailingOnly=TRUE);if(length(argv)<1L)stop('Supply a new empty output directory')\r\noutdir<-argv[1];script<-sub('^--file=','',commandArgs(FALSE)[grepl('^--file=',commandArgs(FALSE))][1]);here<-dirname(normalizePath(script,mustWork=TRUE));datadir<-if(length(argv)>=2L)argv[2]else file.path(here,'..','metr20-sources')\r\nunits<-c(country='log teen-employment points',person='recorded real earnings',company='FTE employees');clocks<-c(country='calendar year',person='calendar year',company='survey-wave index');steps<-c(country=1,person=3,company=1);files<-c(country='actual2500-county-mpdta-all6-fields.csv',person='actual38408-NSW-all15-fields.csv',company='actual410-NJPA-all46-fields.csv')\r\nnum<-function(s)ifelse(s=='.',NA_real_,as.numeric(s));mean0<-function(v)if(length(v))mean(v)else NA_real_;var0<-function(v)if(length(v)>1L)sum((v-mean(v))^2)/(length(v)-1L)else NA_real_\r\n\r\nSPEC<-list(id=\"sensitivity-stated-budget\",api=\"sensitivity\",title=list(ko=\"관측 규모와 선언한 3기간 편의 예산\",en=\"Observed scale and a stipulated three-period budget\"),input=list(estimate=\"4\",preDifferences=list(\"-1/10\",\"1/5\"),M=\"2\",horizon=3),expectedReject=FALSE)\r\npanel<-function(rows){G<-list();for(r in rows){key<-r$entity;u<-G[[key]];if(is.null(u))u<-list(g=r$g,rows=list());stopifnot(identical(u$g,r$g),is.null(u$rows[[as.character(r$time)]]));u$rows[[as.character(r$time)]]<-r;G[[key]]<-u};G}\r\ncell<-function(G,g,t,step,control){b<-g-step;members<-list();T<-C<-list();for(key in names(G)){u<-G[[key]];target<-!is.na(u$g)&&u$g==g;comp<-is.na(u$g)||(control=='notyet'&&!is.na(u$g)&&u$g>max(t,b));role<-if(target)'treated'else if(comp)'control'else'excluded-comparison';before<-u$rows[[as.character(b)]];after<-u$rows[[as.character(t)]];yb<-if(is.null(before))NA_real_ else before$y;ya<-if(is.null(after))NA_real_ else after$y;eligible<-role!='excluded-comparison'&&!is.na(yb)&&!is.na(ya);reason<-if(role=='excluded-comparison')'target-or-already-exposed-cohort-not-valid-control'else if(is.null(before))'baseline-source-row-absent'else if(is.null(after))'target-time-source-row-absent'else if(is.na(yb))'baseline-outcome-missing'else if(is.na(ya))'target-outcome-missing'else'';m<-list(entity=key,nativeID=u$rows[[1]]$nativeID,g=u$g,role=role,eligible=eligible,baselineSourceId=if(is.null(before))NA_character_ else before$id,targetSourceId=if(is.null(after))NA_character_ else after$id,before=yb,after=ya,change=if(eligible)ya-yb else NA_real_,reason=reason);members[[key]]<-m;if(eligible){if(role=='treated')T[[length(T)+1L]]<-m else C[[length(C)+1L]]<-m}}\r\n change<-function(a)vapply(a,function(r)r$change,0);d<-mean0(change(T));e<-mean0(change(C));estimate<-if(is.na(d)||is.na(e))NA_real_ else d-e;defined<-!is.na(estimate);scores<-setNames(rep(NA_real_,length(members)),names(members));for(key in names(members)){m<-members[[key]];s<-if(!defined)NA_real_ else if(!m$eligible)0 else if(m$role=='treated')(m$change-d)/length(T)else-(m$change-e)/length(C);m$score<-s;scores[key]<-s;members[[key]]<-m};st<-var0(change(T));sc<-var0(change(C));v<-if(is.na(st)||is.na(sc))NA_real_ else st/length(T)+sc/length(C);level<-function(a,k)mean0(vapply(a,function(r)r[[k]],0))\r\n list(g=g,t=t,baseline=b,event=(t-g)/step,phase=if(t==b)'mechanical-reference'else if(t>=g)'post'else'pre-placebo',defined=defined,estimate=estimate,T=T,C=C,members=members,scores=scores,HC0=if(defined)sum(scores^2)else NA_real_,unbiased=v,treatedMeanBefore=level(T,'before'),treatedMeanAfter=level(T,'after'),treatedMeanChange=d,controlMeanBefore=level(C,'before'),controlMeanAfter=level(C,'after'),controlMeanChange=e)\r\n}\r\ncovariance<-function(cells){n<-length(cells);V<-matrix(NA_real_,n,n);for(i in seq_len(n))for(j in seq_len(n))if(cells[[i]]$defined&&cells[[j]]$defined)V[i,j]<-sum(cells[[i]]$scores*cells[[j]]$scores);V}\r\naggregate_cells<-function(post,V,step){out<-list();push<-function(typ,key,ii,w){est<-if(!length(ii)||any(vapply(post[ii],function(z)is.na(z$estimate),TRUE)))NA_real_ else sum(w*vapply(post[ii],function(z)z$estimate,0));vv<-if(is.na(est)||anyNA(V[ii,ii,drop=FALSE]))NA_real_ else as.numeric(t(w)%*%V[ii,ii,drop=FALSE]%*%w);out[[length(out)+1L]]<<-list(type=typ,key=as.character(key),ii=ii,w=w,estimate=est,variance=vv)};positive<-which(vapply(post,function(c)length(c$T)>0L,TRUE));mass<-sum(vapply(post[positive],function(c)length(c$T),0));push('simple','overall',positive,if(mass)vapply(post[positive],function(c)length(c$T)/mass,0)else numeric())\r\n for(typ in c('event','calendar','group')){keys<-vapply(post,function(c)if(typ=='event')c$event else if(typ=='calendar')c$t else c$g,0);gg<-sort(unique(keys));cohortmass<-if(typ=='group')sum(vapply(gg,function(k)length(post[[which(keys==k)[1]]]$T),0))else 0;allii<-integer();allw<-numeric();for(key in gg){ii<-which(keys==key);jj<-ii[vapply(post[ii],function(c)length(c$T)>0L,TRUE)];if(typ=='group'){stopifnot(length(unique(vapply(post[ii],function(c)length(c$T),0)))<=1L);w<-if(length(jj))rep(1/length(jj),length(jj))else numeric();if(cohortmass){allii<-c(allii,jj);allw<-c(allw,w*length(post[[ii[1]]]$T)/cohortmass)}}else{total<-sum(vapply(post[jj],function(c)length(c$T),0));w<-if(total)vapply(post[jj],function(c)length(c$T)/total,0)else numeric()};push(typ,key,jj,w)};if(typ=='group')push(typ,'overall',allii,allw)};out}\r\ntwfe<-function(G,times){ledger<-list();good<-list();for(key in names(G)){u<-G[[key]];absent<-times[!as.character(times)%in%names(u$rows)];missing<-times[vapply(times,function(t){r<-u$rows[[as.character(t)]];!is.null(r)&&is.na(r$y)},TRUE)];eligible<-length(times)>0L&&!length(absent)&&!length(missing);ledger[[length(ledger)+1L]]<-list(entity=key,g=u$g,nativeID=u$rows[[1]]$nativeID,eligible=eligible,absentTimes=paste(absent,collapse=','),missingOutcomeTimes=paste(missing,collapse=','),originalRows=length(u$rows));if(eligible)good[[key]]<-u};rows<-list();for(key in names(good))for(t in times){r<-good[[key]]$rows[[as.character(t)]];r$D<-as.integer(!is.na(r$g)&&t>=r$g);rows[[length(rows)+1L]]<-r};em<-lapply(good,function(u)list(D=mean(vapply(times,function(t)as.integer(!is.na(u$g)&&t>=u$g),0)),Y=mean(vapply(u$rows[as.character(times)],function(r)r$y,0))));tm<-lapply(times,function(t)list(D=mean(vapply(good,function(u)as.integer(!is.na(u$g)&&t>=u$g),0)),Y=mean(vapply(good,function(u)u$rows[[as.character(t)]]$y,0))));names(tm)<-as.character(times);gd<-mean0(vapply(rows,function(r)r$D,0));gy<-mean0(vapply(rows,function(r)r$y,0));num<-den<-0\r\n for(i in seq_along(rows)){r<-rows[[i]];r$residualD<-r$D-em[[r$entity]]$D-tm[[as.character(r$time)]]$D+gd;r$residualY<-r$y-em[[r$entity]]$Y-tm[[as.character(r$time)]]$Y+gy;num<-num+r$residualD*r$residualY;den<-den+r$residualD^2;rows[[i]]<-r};beta<-if(den!=0)num/den else NA_real_;weights<-list();for(i in seq_along(rows)){r<-rows[[i]];r$projectionCoefficient<-if(den!=0)r$residualD/den else NA_real_;r$regressionResidual<-if(!is.na(beta))r$residualY-beta*r$residualD else NA_real_;rows[[i]]<-r;if(r$D==1L){k<-paste(r$g,r$time,sep=':');z<-weights[[k]];if(is.null(z))z<-list(g=r$g,t=r$time,rows=0,coefficient=if(den!=0)0 else NA_real_);z$rows<-z$rows+1L;if(den!=0)z$coefficient<-z$coefficient+r$projectionCoefficient;weights[[k]]<-z}};list(ledger=ledger,rows=rows,num=num,den=den,beta=beta,weights=weights,balancedEntities=length(good))}\r\nadjacent_pre<-function(G,g,t,step,control){b<-t-step;T<-C<-numeric();for(u in G){target<-!is.na(u$g)&&u$g==g;comp<-is.na(u$g)||(control=='notyet'&&!is.na(u$g)&&u$g>max(t,b));if(!target&&!comp)next;before<-u$rows[[as.character(b)]];after<-u$rows[[as.character(t)]];if(!is.null(before)&&!is.null(after)&&!is.na(before$y)&&!is.na(after$y)){if(target)T<-c(T,after$y-before$y)else C<-c(C,after$y-before$y)}};if(!length(T)||!length(C))NA_real_ else mean(T)-mean(C)}\r\n\r\n# Newly authored bounded teaching projections; base R finite approximation.\r\n# Source helper functions are inlined in each public file, never imported.\r\nqnum<-function(v){if(is.null(v)||is.na(v))return(NA_real_);s<-strsplit(as.character(v),'/',fixed=TRUE)[[1]];if(length(s)==1L)as.numeric(s)else as.numeric(s[1])/as.numeric(s[2])}\r\npaired<-function(T,C){\r\n stats<-function(rr){use<-Filter(function(r)!is.na(qnum(r$before))&&!is.na(qnum(r$after)),rr);a<-vapply(use,function(r)qnum(r$before),0);b<-vapply(use,function(r)qnum(r$after),0);list(sourcePairs=length(rr),eligiblePairs=length(use),excludedPairs=length(rr)-length(use),meanBefore=mean0(a),meanAfter=mean0(b),meanChange=mean0(b-a),sampleChangeVariance=var0(b-a))}\r\n st<-stats(T);sc<-stats(C);defined<-st$eligiblePairs>0L&&sc$eligiblePairs>0L;estimate<-if(defined)st$meanChange-sc$meanChange else NA_real_;rr<-list()\r\n for(role in c('treated','control')){input<-if(role=='treated')T else C;s<-if(role=='treated')st else sc;for(r in input){before<-qnum(r$before);after<-qnum(r$after);eligible<-!is.na(before)&&!is.na(after);change<-if(eligible)after-before else NA_real_;score<-if(!defined)NA_real_ else if(!eligible)0 else (change-s$meanChange)/(if(role=='treated')s$eligiblePairs else -s$eligiblePairs);rr[[length(rr)+1L]]<-list(id=r$id,role=role,before=before,after=after,eligible=eligible,change=change,score=score)}}\r\n list(defined=defined,estimate=estimate,treated=st,control=sc,unbiasedVariance=if(defined&&st$eligiblePairs>=2L&&sc$eligiblePairs>=2L)st$sampleChangeVariance/st$eligiblePairs+sc$sampleChangeVariance/sc$eligiblePairs else NA_real_,HC0=if(defined)sum(vapply(rr,function(r)r$score^2,0))else NA_real_,rows=rr)\r\n}\r\nliteral_panel<-function(rr)lapply(seq_along(rr),function(i){r<-rr[[i]];r$y<-qnum(r$y);r$nativeID<-r$entity;r$sourceRow<-i;r})\r\natt_projection<-function(rows,control='never',step=1){G<-panel(rows);times<-sort(unique(vapply(rows,function(r)r$time,0)));cohorts<-sort(unique(na.omit(vapply(rows,function(r)r$g,0))));cells<-list();for(g in cohorts)for(t in times)cells[[length(cells)+1L]]<-cell(G,g,t,step,control);list(sourceRows=length(rows),sourceEntities=length(G),step=step,control=control,cells=cells,covariance=covariance(cells))}\r\nlinear_aggregate<-function(a){\r\n rr<-lapply(a$cells,function(r){r$estimate<-qnum(r$estimate);r$weight<-qnum(r$weight);r});V<-if(is.null(a$covariance))NULL else do.call(rbind,lapply(a$covariance,function(r)vapply(r,qnum,0)));rank<-NA_real_\r\n if(!is.null(V)){stopifnot(nrow(V)==length(rr),ncol(V)==length(rr),all(V==t(V)));ev<-eigen(V,symmetric=TRUE,only.values=TRUE)$values;if(any(ev< -1e-12))stop('covariance-must-be-positive-semidefinite');rank<-sum(ev>1e-12)}\r\n selected<-which(vapply(rr,function(r)r$time>=r$cohort&&r$weight>0,TRUE));w<-numeric(length(rr));type<-if(is.null(a$type))'simple'else a$type\r\n if(type=='simple'){mass<-sum(vapply(rr[selected],function(r)r$weight,0));if(mass>0)for(i in selected)w[i]<-rr[[i]]$weight/mass}else{g<-vapply(rr,function(r)r$cohort,0);gg<-sort(unique(g[selected]));mass<-sum(vapply(gg,function(gi)rr[[intersect(which(g==gi),selected)[1]]]$weight,0));for(gi in gg){ii<-intersect(which(g==gi),selected);stopifnot(length(unique(vapply(rr[ii],function(r)r$weight,0)))==1L);w[ii]<-rr[[ii[1]]]$weight/mass/length(ii)}}\r\n used<-which(w>0);estimate<-if(!length(used)||any(vapply(rr[used],function(r)is.na(r$estimate),TRUE)))NA_real_ else sum(w[used]*vapply(rr[used],function(r)r$estimate,0));variance<-if(is.na(estimate)||is.null(V))NA_real_ else as.numeric(t(w)%*%V%*%w);weights<-lapply(used,function(i)list(sourceIndex=i-1L,cohort=rr[[i]]$cohort,time=rr[[i]]$time,coefficient=w[i],estimate=rr[[i]]$estimate,contribution=w[i]*rr[[i]]$estimate))\r\n list(type=type,defined=!is.na(estimate),estimate=estimate,variance=variance,covarianceRank=rank,weights=weights,cells=rr,covariance=V)\r\n}\r\nsensitivity_fixed<-function(a){estimate<-qnum(a$estimate);M<-qnum(a$M);h<-if(is.null(a$horizon))1 else a$horizon;stopifnot(M>=0,h>=1);pre<-vapply(a$preDifferences,qnum,0);scale<-if(!is.null(a$scale))qnum(a$scale)else if(length(pre))max(abs(pre))else NA_real_;budget<-M*scale*h;list(defined=!is.na(scale),estimate=estimate,scale=scale,M=M,horizon=h,biasBudget=budget,lower=estimate-budget,upper=estimate+budget,preDifferences=as.list(pre),confidenceLevel=NULL)}\r\nrealdata_fixed<-function(kind){rows<-models[[kind]];G<-panel(rows);times<-sort(unique(vapply(rows,function(r)r$time,0)));step<-unname(steps[kind]);aa<-att_projection(rows,'never',step);post<-Filter(function(r)r$phase=='post',aa$cells);aggs<-aggregate_cells(post,covariance(post),step);tf<-twfe(G,times);list(kind=kind,unit=unname(units[kind]),periodUnit=unname(clocks[kind]),nativeRows=nrow(raw[[kind]]),modelRows=length(rows),entities=length(G),sourceRows=rows,att=aa,aggregations=aggs,twfe=tf,scope='Complete native/model/paired/balanced source frames; never control,universal base,no anticipation;not causal/sampling certification.')}\r\n# JSON encoder deliberately handles matrices and scalar/vector distinctions.\r\nencode<-function(x){\r\n if(is.null(x))return('null')\r\n quote<-function(s){s<-gsub('\\\\','\\\\\\\\',as.character(s),fixed=TRUE);s<-gsub('\"','\\\\\"',s,fixed=TRUE);s<-gsub('\\n','\\\\n',s,fixed=TRUE);s<-gsub('\\r','\\\\r',s,fixed=TRUE);s<-gsub('\\t','\\\\t',s,fixed=TRUE);paste0('\"',s,'\"')}\r\n if(is.matrix(x))return(paste0('[',paste(vapply(seq_len(nrow(x)),function(i)encode(as.list(unname(x[i,]))),''),collapse=','),']'))\r\n if(is.list(x)){if(length(x)&&!is.null(names(x)))return(paste0('{',paste(paste0(vapply(names(x),quote,''),':',vapply(x,encode,'')),collapse=','),'}'));return(paste0('[',paste(vapply(x,encode,''),collapse=','),']'))}\r\n if(length(x)!=1L)return(encode(as.list(unname(x))))\r\n if(is.na(x))return('null');if(is.logical(x))return(if(x)'true'else'false');if(is.numeric(x))return(sprintf('%.17g',unname(x)));quote(x)\r\n}\r\nv9<-function(x){if(is.null(x)||is.na(x))return('undefined');if(is.logical(x))return(if(x)'1'else'0');if(is.numeric(x))return(sprintf('%.9g',unname(x)));as.character(x)}\r\nrun_fixed<-function(spec,out){api<-spec$api;a<-spec$input;summary<-list();points<-list();emit<-function(series,x,y){points[[length(points)+1L]]<<-list(series=series,x=x,y=y,numericY=y)}\r\n if(api=='twobytwo'){result<-paired(a$treated,a$control);summary<-list(defined=result$defined,estimate=result$estimate,treatedPairs=result$treated$eligiblePairs,controlPairs=result$control$eligiblePairs,unbiasedVariance=result$unbiasedVariance,HC0=result$HC0);for(i in seq_along(result$rows)){r<-result$rows[[i]];emit(paste(r$role,r$id,sep=':'),i,r$change)}}\r\n else if(api=='att'){result<-att_projection(literal_panel(a$rows),a$control);summary<-list(sourceRows=result$sourceRows,entities=result$sourceEntities,cells=length(result$cells),supportedCells=sum(vapply(result$cells,function(r)r$defined,TRUE)),postCells=sum(vapply(result$cells,function(r)r$phase=='post',TRUE)));for(i in seq_along(result$cells)){r<-result$cells[[i]];emit(paste0('g',r$g,':t',r$t),i,r$estimate)}}\r\n else if(api=='aggregate'){result<-linear_aggregate(a);summary<-list(defined=result$defined,estimate=result$estimate,variance=result$variance,covarianceRank=result$covarianceRank,sumWeights=sum(vapply(result$weights,function(r)r$coefficient,0)));for(i in seq_along(result$weights)){r<-result$weights[[i]];emit(paste0('g',r$cohort,':t',r$time),i,r$contribution)}}\r\n else if(api=='twfe'){rows<-literal_panel(a$rows);G<-panel(rows);result<-twfe(G,sort(unique(vapply(rows,function(r)r$time,0))));summary<-list(defined=!is.na(result$beta),beta=result$beta,numerator=result$num,denominator=result$den,balancedEntities=result$balancedEntities,negativeTreatedCells=sum(vapply(result$weights,function(r)!is.na(r$coefficient)&&r$coefficient<0,TRUE)));if(length(result$weights)){ord<-order(vapply(result$weights,function(r)r$g,0),vapply(result$weights,function(r)r$t,0));for(i in seq_along(ord)){r<-result$weights[[ord[i]]];emit(paste0('g',r$g,':t',r$t),i,r$coefficient)}}}\r\n else if(api=='sensitivity'){result<-sensitivity_fixed(a);summary<-result[c('defined','estimate','scale','M','horizon','biasBudget','lower','upper')];for(i in seq_along(c('lower','estimate','upper'))){k<-c('lower','estimate','upper')[i];emit(k,i,if(result$defined)result[[k]]else NA_real_)}}\r\n else{result<-realdata_fixed(a$kind);post<-Filter(function(r)r$phase=='post',result$att$cells);simple<-Filter(function(r)r$type=='simple',result$aggregations)[[1]];group<-Filter(function(r)r$type=='group'&&r$key=='overall',result$aggregations)[[1]];summary<-list(nativeRows=result$nativeRows,modelRows=result$modelRows,entities=result$entities,postCells=length(post),simple=simple$estimate,group=group$estimate,TWFE=result$twfe$beta,balancedEntities=result$twfe$balancedEntities);for(i in seq_along(post)){r<-post[[i]];emit(paste0('g',r$g,':t',r$t),i,r$estimate)}}\r\n dir.create(out,recursive=TRUE,showWarnings=FALSE);if(length(list.files(out,all.files=TRUE,no..=TRUE)))stop('use-new-empty-output-directory');shown<-lapply(summary,v9);write.csv(data.frame(name=names(shown),value=unlist(shown,use.names=FALSE)),file.path(out,'summary.csv'),row.names=FALSE,na='');pointframe<-if(length(points))do.call(rbind,lapply(points,function(p)data.frame(series=p$series,x=p$x,y=p$y,numericY=p$numericY,stringsAsFactors=FALSE)))else data.frame(series=character(),x=numeric(),y=numeric(),numericY=numeric());write.csv(pointframe,file.path(out,'points.csv'),row.names=FALSE,na='');full<-list(chapter='METR-20',profile=spec$id,api=api,input=spec$input,summary=shown,points=points,details=result,arithmetic='Base R approximate finite values;bounded teaching projection,not exact fractions or causal/sampling certification.');writeLines(encode(full),file.path(out,'full.json'),useBytes=TRUE)\r\n svg(file.path(out,'plot.svg'),width=9,height=5.6,pointsize=12);par(mar=c(4.5,5.5,4,1));good<-pointframe[!is.na(pointframe$numericY),,drop=FALSE]\r\n if(nrow(good)){plot(good$x,good$numericY,pch=19,col='#315d7c',xlab='Declared cell/unit/bound ordinal',ylab=if(api=='twfe')'Cell weight'else if(!is.null(result$unit))result$unit else 'Stated outcome/bias units',main=spec$title$en);abline(h=0,col='#9eabb2');grid(nx=NA,ny=NULL,col='#e2e5e7');points(good$x,good$numericY,pch=19,col='#315d7c')}else{plot.new();text(.5,.5,'Undefined: no supported plotted quantity');title(main=spec$title$en)};dev.off();cat(encode(shown),'\\n')\r\n}\r\n\r\nrun_fixed(SPEC,outdir)\r\n",
      "arithmetic": "Base R approximate finite arithmetic;not an exact rational result",
      "summary": {
        "defined": "1",
        "estimate": "4",
        "scale": "0.2",
        "M": "2",
        "horizon": "3",
        "biasBudget": "1.2",
        "lower": "2.8",
        "upper": "5.2"
      },
      "fullResultEmbedded": false,
      "plotEmbedded": false,
      "full": {
        "summary": {
          "defined": "1",
          "estimate": "4",
          "scale": "0.2",
          "M": "2",
          "horizon": "3",
          "biasBudget": "1.2",
          "lower": "2.8",
          "upper": "5.2"
        },
        "notice": "Complete source/finite projection is retained in the linked external JSON; this short projection is not the full result."
      },
      "plot": null,
      "points": [
        {
          "series": "lower",
          "x": 1,
          "y": 2.8,
          "numericY": 2.8
        },
        {
          "series": "estimate",
          "x": 2,
          "y": 4,
          "numericY": 4
        },
        {
          "series": "upper",
          "x": 3,
          "y": 5.2,
          "numericY": 5.2
        }
      ],
      "summaryFile": "metr20-programs/sensitivity-stated-budget-r-summary.csv",
      "summarySHA256": "641c86a634b12d57b770b554d48bb827653021d4cb2cc1b3bb8dc06094e79026",
      "pointsFile": "metr20-programs/sensitivity-stated-budget-r-points.csv",
      "pointsSHA256": "1175b5563d59faeff269817b8718a01887891766ee612f2b4588ca1623ba6a7e",
      "fullResultFile": "metr20-programs/sensitivity-stated-budget-r.json",
      "fullResultSHA256": "197d715cdc7ab81c8b98b12b241cceaefe517f864e5078b4db289b6ee47b2233",
      "plotFile": "metr20-programs/sensitivity-stated-budget-r.svg",
      "plotSHA256": "b4e6935ad6ef33684beb9300b5ab8b9e016791d63cce4c5626bd4e979d4bbe9e"
    },
    {
      "api": "sensitivity",
      "variant": "sensitivity-no-preperiod",
      "profile": "sensitivity-no-preperiod",
      "language": "Python",
      "file": "metr20-programs/sensitivity-no-preperiod-python.py",
      "codeSHA256": "839500ec6882a78fa7fb4552cc8677f67169866931a27f9c26b4d5c210af7960",
      "returnCode": 0,
      "expectedRejection": false,
      "title": {
        "ko": "사전 정보가 없으면 0으로 채우지 않기",
        "en": "No preperiod information is not a zero scale"
      },
      "code": "\"\"\"METR20 actual sources. Python standard library, exact stored-value rationals.\r\nRead ONLY the three native-observation CSVs; no JS engine,model JSON,derived\r\nanswers,private modules or internet needed. Outcome measurement/identification\r\nand valid sampling inference remain separate from exact finite arithmetic.\r\nRun: python metr20-reproduce.py --data-dir PATH --out NEW_EMPTY_DIRECTORY\r\n\"\"\"\r\nfrom pathlib import Path\r\nfrom fractions import Fraction as Q\r\nfrom collections import defaultdict,Counter\r\nimport csv,json,math,argparse,hashlib\r\n\r\nUNIT={'country':'log teen-employment points','person':'recorded real earnings','company':'FTE employees'}\r\nCLOCK={'country':'calendar year','person':'calendar year','company':'survey-wave index'}\r\nSTEP={'country':1,'person':3,'company':1}\r\nFILES={'country':'actual2500-county-mpdta-all6-fields.csv','person':'actual38408-NSW-all15-fields.csv','company':'actual410-NJPA-all46-fields.csv'}\r\ndef avg(v):return sum(v,Q(0))/len(v)if v else None\r\ndef samplevar(v):return sum(((x-avg(v))**2 for x in v),Q(0))/(len(v)-1)if len(v)>1 else None\r\ndef binary(s):return None if s=='.'else Q.from_float(float(s))\r\ndef token(v):\r\n if v is None:return ''\r\n if isinstance(v,bool):return 'true'if v else'false'\r\n return str(v)\r\ndef safe_float(v):\r\n if v is None:return None\r\n try:r=float(v)\r\n except OverflowError:return None\r\n return r if math.isfinite(r)else None\r\ndef read(p):\r\n with p.open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))\r\ndef write(p,rows,head=None):\r\n if head is None:\r\n  assert rows;head=list(rows[0])\r\n with p.open('w',encoding='utf8',newline='')as f:\r\n  w=csv.DictWriter(f,fieldnames=head);w.writeheader();w.writerows({k:token(r.get(k))for k in head}for r in rows)\r\ndef source(data):\r\n raw={k:read(data/n)for k,n in FILES.items()};assert[len(raw[k])for k in FILES]==[2500,38408,410]\r\n models={k:[]for k in FILES}\r\n for r in raw['country']:\r\n  g0=int(r['first.treat']);g=None if g0==0 else g0;assert int(r['treat'])==int(g is not None)\r\n  models['country'].append(dict(id='mpdta:'+r['sourceRow'],entity='county:'+str(int(r['countyreal'])),time=int(r['year']),y=binary(r['lemp']),g=g,sourceRow=int(r['sourceRow']),nativeID=r['countyreal']))\r\n for r in raw['person']:\r\n  selected=int(r['experimental'])==1;assert selected==(int(r['sample'])==1);assert(r['treated']!='.')==selected\r\n  if selected:\r\n   d=int(r['treated']);assert d in[0,1]\r\n   models['person'].append(dict(id='nsw:'+r['sourceRow'],entity='nsw-id:'+str(int(r['id'])),time=int(r['year']),y=binary(r['re']),g=1978 if d else None,sourceRow=int(r['sourceRow']),nativeID=str(int(r['id']))))\r\n for r in raw['company']:\r\n  state=int(r['STATE']);assert state in[0,1]\r\n  for t,suffix in[(0,''),(1,'2')]:\r\n   a=[r[n+suffix]for n in['EMPFT','NMGRS','EMPPT']];y=None if'.'in a else Q(a[0])+Q(a[1])+Q(a[2])/2\r\n   models['company'].append(dict(id='njpa:'+r['sourceRow']+':wave'+str(t),entity='njpa-row:'+r['sourceRow'],time=t,y=y,g=1 if state else None,sourceRow=int(r['sourceRow']),nativeID=r['SHEET']))\r\n assert[len(models[k])for k in FILES]==[2500,1444,820]\r\n return models,raw\r\ndef panel(rows):\r\n groups={}\r\n for r in rows:\r\n  u=groups.setdefault(r['entity'],{'g':r['g'],'rows':{}});assert u['g']==r['g']and r['time']not in u['rows'];u['rows'][r['time']]=r\r\n return groups\r\ndef cell(groups,g,t,step,control):\r\n b=g-step;members=[];T=[];C=[]\r\n for key,u in groups.items():\r\n  role='treated'if u['g']==g else'control'if u['g']is None or(control=='notyet'and u['g']>max(t,b))else'excluded-comparison'\r\n  before=u['rows'].get(b);after=u['rows'].get(t);yb=None if before is None else before['y'];ya=None if after is None else after['y'];eligible=role!='excluded-comparison'and yb is not None and ya is not None\r\n  reason='target-or-already-exposed-cohort-not-valid-control'if role=='excluded-comparison'else'baseline-source-row-absent'if before is None else'target-time-source-row-absent'if after is None else'baseline-outcome-missing'if yb is None else'target-outcome-missing'if ya is None else''\r\n  m={'entity':key,'nativeID':next(iter(u['rows'].values()))['nativeID'],'g':u['g'],'role':role,'eligible':eligible,'baselineSourceId':None if before is None else before['id'],'targetSourceId':None if after is None else after['id'],'before':yb,'after':ya,'change':ya-yb if eligible else None,'reason':reason};members.append(m)\r\n  if eligible:(T if role=='treated'else C).append(m)\r\n d=avg([r['change']for r in T]);e=avg([r['change']for r in C]);estimate=None if d is None or e is None else d-e;defined=estimate is not None;scores={}\r\n for m in members:\r\n  s=None if not defined else Q(0)\r\n  if defined and m['eligible']:s=(m['change']-(d if m['role']=='treated'else e))/(len(T)if m['role']=='treated'else-len(C))\r\n  m['score']=s;scores[m['entity']]=s\r\n st=samplevar([r['change']for r in T]);sc=samplevar([r['change']for r in C]);v=None if st is None or sc is None else st/len(T)+sc/len(C)\r\n return {'g':g,'t':t,'baseline':b,'event':(t-g)//step,'phase':'mechanical-reference'if t==b else'post'if t>=g else'pre-placebo','defined':defined,'estimate':estimate,'T':T,'C':C,'members':members,'scores':scores,'HC0':None if not defined else sum((s*s for s in scores.values()),Q(0)),'unbiased':v,'treatedMeanBefore':avg([r['before']for r in T]),'treatedMeanAfter':avg([r['after']for r in T]),'treatedMeanChange':d,'controlMeanBefore':avg([r['before']for r in C]),'controlMeanAfter':avg([r['after']for r in C]),'controlMeanChange':e}\r\ndef covariance(cells):\r\n return[[None if not a['defined']or not b['defined']else sum((v*b['scores'][i]for i,v in a['scores'].items()),Q(0))for b in cells]for a in cells]\r\ndef aggregate(post,V,step):\r\n out=[]\r\n def push(typ,key,coeff):\r\n  estimate=None if not coeff or any(post[i]['estimate']is None for i in coeff)else sum((w*post[i]['estimate']for i,w in coeff.items()),Q(0));variance=None if estimate is None or any(V[i][j]is None for i in coeff for j in coeff)else sum((a*b*V[i][j]for i,a in coeff.items()for j,b in coeff.items()),Q(0));out.append({'type':typ,'key':key,'coeff':coeff,'estimate':estimate,'variance':variance})\r\n positive=[i for i,c in enumerate(post)if len(c['T'])>0];mass=sum(len(post[i]['T'])for i in positive)\r\n push('simple','overall',{i:Q(len(post[i]['T']),mass)for i in positive}if mass else{})\r\n for typ in['event','calendar','group']:\r\n  groups=defaultdict(list)\r\n  for i,c in enumerate(post):groups[c['event']if typ=='event'else c['t']if typ=='calendar'else c['g']].append(i)\r\n  overall={};cohortMass=sum(len(post[ii[0]]['T'])for ii in groups.values())if typ=='group'else 0\r\n  for key,ii in sorted(groups.items()):\r\n   jj=[i for i in ii if len(post[i]['T'])>0]\r\n   if typ=='group':\r\n    assert len({len(post[i]['T'])for i in ii})<=1\r\n    coeff={i:Q(1,len(jj))for i in jj}if jj else{}\r\n    if cohortMass:\r\n     for i,w in coeff.items():overall[i]=w*Q(len(post[ii[0]]['T']),cohortMass)\r\n   else:\r\n    total=sum(len(post[i]['T'])for i in jj);coeff={i:Q(len(post[i]['T']),total)for i in jj}if total else{}\r\n   push(typ,str(key),coeff)\r\n  if typ=='group':push(typ,'overall',overall)\r\n return out\r\ndef twfe(groups,times):\r\n ledger=[];good={}\r\n for key,u in groups.items():\r\n  absent=[t for t in times if t not in u['rows']];missing=[t for t in times if t in u['rows']and u['rows'][t]['y']is None];eligible=bool(times)and not absent and not missing\r\n  ledger.append({'entity':key,'g':u['g'],'nativeID':next(iter(u['rows'].values()))['nativeID'],'eligible':eligible,'absentTimes':','.join(map(str,absent)),'missingOutcomeTimes':','.join(map(str,missing)),'originalRows':len(u['rows'])})\r\n  if eligible:good[key]=u\r\n rows=[dict(**u['rows'][t],D=Q(u['g']is not None and t>=u['g']))for key,u in good.items()for t in times]\r\n em={k:{'D':avg([Q(u['g']is not None and t>=u['g'])for t in times]),'Y':avg([u['rows'][t]['y']for t in times])}for k,u in good.items()};tm={t:{'D':avg([Q(u['g']is not None and t>=u['g'])for u in good.values()]),'Y':avg([u['rows'][t]['y']for u in good.values()])}for t in times};gd=avg([r['D']for r in rows]);gy=avg([r['y']for r in rows]);num=den=Q(0)\r\n for r in rows:\r\n  r['residualD']=r['D']-em[r['entity']]['D']-tm[r['time']]['D']+gd;r['residualY']=r['y']-em[r['entity']]['Y']-tm[r['time']]['Y']+gy;num+=r['residualD']*r['residualY'];den+=r['residualD']**2\r\n beta=num/den if den else None;weights={}\r\n for r in rows:\r\n  r['projectionCoefficient']=r['residualD']/den if den else None;r['regressionResidual']=r['residualY']-beta*r['residualD']if beta is not None else None\r\n  if r['D']:\r\n   k=(r['g'],r['time']);z=weights.setdefault(k,{'rows':0,'coefficient':Q(0)if den else None});z['rows']+=1\r\n   if den:z['coefficient']+=r['projectionCoefficient']\r\n return {'ledger':ledger,'rows':rows,'num':num,'den':den,'beta':beta,'weights':weights,'balancedEntities':len(good)}\r\ndef adjacent_pre(groups,g,t,step,control):\r\n b=t-step;T=[];C=[]\r\n for u in groups.values():\r\n  if u['g']==g:target=T\r\n  elif u['g']is None or(control=='notyet'and u['g']>max(t,b)):target=C\r\n  else:continue\r\n  before=u['rows'].get(b);after=u['rows'].get(t)\r\n  if before is not None and after is not None and before['y']is not None and after['y']is not None:target.append(after['y']-before['y'])\r\n return None if not T or not C else avg(T)-avg(C)\r\n\r\n\"\"\"New bounded teaching projections. The program is self-contained after build.\r\nExact Fraction finite algebra; figures and9-digit summary are approximations.\r\nIt is not a general parser/API replacement or a causal/inference certificate.\r\n\"\"\"\r\ndef paired(treated,control):\r\n def stats(rr):\r\n  use=[r for r in rr if r['before']is not None and r['after']is not None];delta=[Q(r['after'])-Q(r['before'])for r in use]\r\n  return dict(sourcePairs=len(rr),eligiblePairs=len(use),excludedPairs=len(rr)-len(use),meanBefore=avg([Q(r['before'])for r in use]),meanAfter=avg([Q(r['after'])for r in use]),meanChange=avg(delta),sampleChangeVariance=samplevar(delta))\r\n T,C=stats(treated),stats(control);defined=T['eligiblePairs']>0 and C['eligiblePairs']>0;estimate=T['meanChange']-C['meanChange']if defined else None;records=[]\r\n for group,rr,s in [('treated',treated,T),('control',control,C)]:\r\n  for r in rr:\r\n   before=None if r['before']is None else Q(r['before']);after=None if r['after']is None else Q(r['after']);eligible=before is not None and after is not None;delta=after-before if eligible else None;score=None if not defined else Q(0)if not eligible else(delta-s['meanChange'])/(s['eligiblePairs']if group=='treated'else-s['eligiblePairs']);records.append(dict(id=r['id'],role=group,before=before,after=after,eligible=eligible,change=delta,score=score))\r\n unbiased=None if not defined or T['eligiblePairs']<2 or C['eligiblePairs']<2 else T['sampleChangeVariance']/T['eligiblePairs']+C['sampleChangeVariance']/C['eligiblePairs'];hc0=None if not defined else sum((r['score']**2 for r in records),Q(0))\r\n return dict(defined=defined,estimate=estimate,treated=T,control=C,unbiasedVariance=unbiased,HC0=hc0,rows=records)\r\ndef literal_panel(raw):\r\n return[dict(r,y=None if r['y']is None else Q(r['y']),nativeID=r['entity'],sourceRow=i+1)for i,r in enumerate(raw)]\r\ndef att_projection(rows,control='never',step=1):\r\n G=panel(rows);times=sorted({r['time']for r in rows});cohorts=sorted({r['g']for r in rows if r['g']is not None});cells=[cell(G,g,t,step,control)for g in cohorts for t in times]\r\n return dict(sourceRows=len(rows),sourceEntities=len(G),step=step,control=control,cells=cells,covariance=covariance(cells))\r\ndef psd(V):\r\n A=[r[:]for r in V];rank=0\r\n while A:\r\n  if any(A[i][i]<0 for i in range(len(A))):raise ValueError('covariance-must-be-positive-semidefinite')\r\n  p=next((i for i in range(len(A))if A[i][i]>0),None)\r\n  if p is None:\r\n   if any(v for r in A for v in r):raise ValueError('covariance-must-be-positive-semidefinite')\r\n   return rank\r\n  A[0],A[p]=A[p],A[0]\r\n  for r in A:r[0],r[p]=r[p],r[0]\r\n  d=A[0][0];A=[[A[i][j]-A[i][0]*A[0][j]/d for j in range(1,len(A))]for i in range(1,len(A))];rank+=1\r\n return rank\r\ndef linear_aggregate(a):\r\n rr=[dict(r,estimate=None if r['estimate']is None else Q(r['estimate']),weight=Q(r['weight']))for r in a['cells']];V=[[Q(v)for v in r]for r in a['covariance']]if 'covariance'in a else None\r\n if V is not None:\r\n  assert len(V)==len(rr)and all(len(z)==len(rr)for z in V);assert all(V[i][j]==V[j][i]for i in range(len(rr))for j in range(len(rr)));rank=psd(V)\r\n else:rank=None\r\n selected=[i for i,r in enumerate(rr)if r['time']>=r['cohort']and r['weight']>0];weights={}\r\n if a.get('type','simple')=='simple':\r\n  mass=sum((rr[i]['weight']for i in selected),Q(0));weights={i:rr[i]['weight']/mass for i in selected}if mass else{}\r\n else:\r\n  gg=defaultdict(list)\r\n  for i in selected:gg[rr[i]['cohort']].append(i)\r\n  assert all(len({rr[i]['weight']for i in ii})==1 for ii in gg.values());mass=sum((rr[ii[0]]['weight']for ii in gg.values()),Q(0));weights={i:rr[ii[0]]['weight']/mass/len(ii)for ii in gg.values()for i in ii}if mass else{}\r\n estimate=None if not weights or any(rr[i]['estimate']is None for i in weights)else sum((w*rr[i]['estimate']for i,w in weights.items()),Q(0));variance=None if estimate is None or V is None else sum((x*y*V[i][j]for i,x in weights.items()for j,y in weights.items()),Q(0))\r\n return dict(type=a.get('type','simple'),defined=estimate is not None,estimate=estimate,variance=variance,covarianceRank=rank,weights=[dict(sourceIndex=i,cohort=rr[i]['cohort'],time=rr[i]['time'],coefficient=w,estimate=rr[i]['estimate'],contribution=None if rr[i]['estimate']is None else w*rr[i]['estimate'])for i,w in weights.items()],cells=rr,covariance=V)\r\ndef sensitivity_fixed(a):\r\n estimate=Q(a['estimate']);M=Q(a['M']);h=a.get('horizon',1);assert M>=0 and h>=1\r\n pre=[Q(v)for v in a.get('preDifferences',[])];scale=Q(a['scale'])if 'scale'in a else max(map(abs,pre))if pre else None;budget=None if scale is None else M*scale*h\r\n return dict(defined=scale is not None,estimate=estimate,scale=scale,M=M,horizon=h,biasBudget=budget,lower=None if budget is None else estimate-budget,upper=None if budget is None else estimate+budget,preDifferences=pre,confidenceLevel=None)\r\ndef realdata_fixed(kind,data):\r\n models,raw=source(data);rows=models[kind];G=panel(rows);times=sorted({r['time']for r in rows});step=STEP[kind];aa=att_projection(rows,'never',step);post=[r for r in aa['cells']if r['phase']=='post'];aggs=aggregate(post,covariance(post),step);tf=twfe(G,times)\r\n return dict(kind=kind,unit=UNIT[kind],periodUnit=CLOCK[kind],nativeRows=len(raw[kind]),modelRows=len(rows),entities=len(G),sourceRows=rows,att=aa,aggregations=aggs,twfe=tf,scope='Complete source frame; never-treated comparison,universal baseline,no anticipation. Native/model/paired/balanced denominators differ. All sampling/causal assumptions remain separate.')\r\ndef encode(v):\r\n if isinstance(v,Q):return str(v)\r\n if isinstance(v,dict):return{str(k):encode(x)for k,x in v.items()}\r\n if isinstance(v,(list,tuple)):return[encode(x)for x in v]\r\n return v\r\ndef v9(v):\r\n if v is None:return'undefined'\r\n if isinstance(v,str):return v\r\n if isinstance(v,bool):return'1'if v else'0'\r\n return format(float(v),'.9g')\r\ndef run_fixed(spec,out,data):\r\n api=spec['api'];a=spec['input'];summary={};points=[]\r\n def emit(series,x,y):points.append(dict(series=series,x=x,y=y,numericY=safe_float(y)))\r\n if api=='twobytwo':\r\n  result=paired(a['treated'],a['control']);summary=dict(defined=result['defined'],estimate=result['estimate'],treatedPairs=result['treated']['eligiblePairs'],controlPairs=result['control']['eligiblePairs'],unbiasedVariance=result['unbiasedVariance'],HC0=result['HC0'])\r\n  for i,r in enumerate(result['rows']):emit(r['role']+':'+r['id'],i+1,r['change'])\r\n elif api=='att':\r\n  result=att_projection(literal_panel(a['rows']),a.get('control','never'));summary=dict(sourceRows=result['sourceRows'],entities=result['sourceEntities'],cells=len(result['cells']),supportedCells=sum(r['defined']for r in result['cells']),postCells=sum(r['phase']=='post'for r in result['cells']))\r\n  for i,r in enumerate(result['cells']):emit('g'+str(r['g'])+':t'+str(r['t']),i+1,r['estimate'])\r\n elif api=='aggregate':\r\n  result=linear_aggregate(a);summary=dict(defined=result['defined'],estimate=result['estimate'],variance=result['variance'],covarianceRank=result['covarianceRank'],sumWeights=sum((r['coefficient']for r in result['weights']),Q(0)))\r\n  for i,r in enumerate(result['weights']):emit('g'+str(r['cohort'])+':t'+str(r['time']),i+1,r['contribution'])\r\n elif api=='twfe':\r\n  rows=literal_panel(a['rows']);G=panel(rows);result=twfe(G,sorted({r['time']for r in rows}));summary=dict(defined=result['beta']is not None,beta=result['beta'],numerator=result['num'],denominator=result['den'],balancedEntities=result['balancedEntities'],negativeTreatedCells=sum(v['coefficient']is not None and v['coefficient']<0 for v in result['weights'].values()))\r\n  for i,((g,t),r)in enumerate(sorted(result['weights'].items())):emit('g'+str(g)+':t'+str(t),i+1,r['coefficient'])\r\n elif api=='sensitivity':\r\n  result=sensitivity_fixed(a);summary={k:result[k]for k in['defined','estimate','scale','M','horizon','biasBudget','lower','upper']}\r\n  for i,k in enumerate(['lower','estimate','upper']):emit(k,i+1,result[k]if result['defined']else None)\r\n else:\r\n  result=realdata_fixed(a['kind'],data);post=[r for r in result['att']['cells']if r['phase']=='post'];s=next(r for r in result['aggregations']if r['type']=='simple');g=next(r for r in result['aggregations']if r['type']=='group'and r['key']=='overall');summary=dict(nativeRows=result['nativeRows'],modelRows=result['modelRows'],entities=result['entities'],postCells=len(post),simple=s['estimate'],group=g['estimate'],TWFE=result['twfe']['beta'],balancedEntities=result['twfe']['balancedEntities'])\r\n  for i,r in enumerate(post):emit('g'+str(r['g'])+':t'+str(r['t']),i+1,r['estimate'])\r\n out.mkdir(parents=True,exist_ok=True)\r\n if any(out.iterdir()):raise ValueError('use-new-empty-output-directory')\r\n shown={k:v9(v)for k,v in summary.items()};write(out/'summary.csv',[dict(name=k,value=v)for k,v in shown.items()]);write(out/'points.csv',points,['series','x','y','numericY']);full=dict(chapter='METR-20',profile=spec['id'],api=api,input=spec['input'],summary=shown,points=encode(points),details=encode(result),arithmetic='Python Fraction exact finite stored values;summary/plot approximate;bounded teaching projection,not causal or sampling certification')\r\n (out/'full.json').write_text(json.dumps(full,ensure_ascii=False,indent=2,allow_nan=False)+'\\n',encoding='utf8')\r\n import matplotlib\r\n matplotlib.use('Agg')\r\n import matplotlib.pyplot as plt\r\n plt.rcParams.update({'svg.fonttype':'none','font.family':'DejaVu Sans','font.size':12,'axes.spines.top':False,'axes.spines.right':False});fig,ax=plt.subplots(figsize=(9,5.6));good=[r for r in points if r['numericY']is not None]\r\n if good:\r\n  ax.scatter([r['x']for r in good],[r['numericY']for r in good],color='#315d7c',s=32);ax.axhline(0,color='#9eabb2',lw=.8);ax.set_xlabel('Declared cell/unit/bound ordinal')\r\n else:ax.text(.5,.5,'Undefined: no supported plotted quantity',ha='center',va='center',transform=ax.transAxes);ax.set_xticks([]);ax.set_yticks([])\r\n ax.set_ylabel('Cell weight'if api=='twfe'else result.get('unit','Stated outcome/bias units'));ax.set_title(spec['title']['en'],wrap=True,pad=14);ax.grid(axis='y',alpha=.2);fig.tight_layout(pad=2);fig.savefig(out/'plot.svg');plt.close(fig);print(json.dumps(shown))\r\n\r\nSPEC={'id': 'sensitivity-no-preperiod', 'api': 'sensitivity', 'title': {'ko': '사전 정보가 없으면 0으로 채우지 않기', 'en': 'No preperiod information is not a zero scale'}, 'input': {'estimate': '4', 'preDifferences': [], 'M': '1', 'horizon': 1}, 'expectedReject': False}\r\nif __name__=='__main__':\r\n import sys\r\n run_fixed(SPEC,Path(sys.argv[1]),Path(sys.argv[2])if len(sys.argv)>2 else Path(__file__).resolve().parent.parent/'metr20-sources')\r\n",
      "arithmetic": "Python Fraction exact stored finite values;logs/summary/plots approximate",
      "summary": {
        "defined": "0",
        "estimate": "4",
        "scale": "undefined",
        "M": "1",
        "horizon": "1",
        "biasBudget": "undefined",
        "lower": "undefined",
        "upper": "undefined"
      },
      "fullResultEmbedded": false,
      "plotEmbedded": false,
      "full": {
        "summary": {
          "defined": "0",
          "estimate": "4",
          "scale": "undefined",
          "M": "1",
          "horizon": "1",
          "biasBudget": "undefined",
          "lower": "undefined",
          "upper": "undefined"
        },
        "notice": "Complete source/finite projection is retained in the linked external JSON; this short projection is not the full result."
      },
      "plot": null,
      "points": [
        {
          "series": "lower",
          "x": 1,
          "y": null,
          "numericY": null
        },
        {
          "series": "estimate",
          "x": 2,
          "y": null,
          "numericY": null
        },
        {
          "series": "upper",
          "x": 3,
          "y": null,
          "numericY": null
        }
      ],
      "summaryFile": "metr20-programs/sensitivity-no-preperiod-python-summary.csv",
      "summarySHA256": "1af6c621edb6f3855e8de0d1fdb470f11ac4f3e8498dad713313a43a002ab1b9",
      "pointsFile": "metr20-programs/sensitivity-no-preperiod-python-points.csv",
      "pointsSHA256": "a5076800ff00ff5cd8abbcdc4f9f746a4596139059f29b12088b13e2a7e33e74",
      "fullResultFile": "metr20-programs/sensitivity-no-preperiod-python.json",
      "fullResultSHA256": "500b90cc0c969e93ac50690264ee534e4782dd2b65863d6d2359657559689bdb",
      "plotFile": "metr20-programs/sensitivity-no-preperiod-python.svg",
      "plotSHA256": "83e36d6b6fc30260f0885845015ebbaf0e106d5c826f9de4156b06f0afd500c2"
    },
    {
      "api": "sensitivity",
      "variant": "sensitivity-no-preperiod",
      "profile": "sensitivity-no-preperiod",
      "language": "R",
      "file": "metr20-programs/sensitivity-no-preperiod-r.R",
      "codeSHA256": "07dbbe9ad7e5a80afb0809316f057cf8bc1604bf1bf3910a4977b7304a4ae9b0",
      "returnCode": 0,
      "expectedRejection": false,
      "title": {
        "ko": "사전 정보가 없으면 0으로 채우지 않기",
        "en": "No preperiod information is not a zero scale"
      },
      "code": "# METR20 fixed example. Base R only, finite arithmetic approximate.\r\n# No JavaScript engine,model JSON,derived answer table,private module or internet.\r\noptions(stringsAsFactors=FALSE,digits=17)\r\nargv<-commandArgs(trailingOnly=TRUE);if(length(argv)<1L)stop('Supply a new empty output directory')\r\noutdir<-argv[1];script<-sub('^--file=','',commandArgs(FALSE)[grepl('^--file=',commandArgs(FALSE))][1]);here<-dirname(normalizePath(script,mustWork=TRUE));datadir<-if(length(argv)>=2L)argv[2]else file.path(here,'..','metr20-sources')\r\nunits<-c(country='log teen-employment points',person='recorded real earnings',company='FTE employees');clocks<-c(country='calendar year',person='calendar year',company='survey-wave index');steps<-c(country=1,person=3,company=1);files<-c(country='actual2500-county-mpdta-all6-fields.csv',person='actual38408-NSW-all15-fields.csv',company='actual410-NJPA-all46-fields.csv')\r\nnum<-function(s)ifelse(s=='.',NA_real_,as.numeric(s));mean0<-function(v)if(length(v))mean(v)else NA_real_;var0<-function(v)if(length(v)>1L)sum((v-mean(v))^2)/(length(v)-1L)else NA_real_\r\n\r\nSPEC<-list(id=\"sensitivity-no-preperiod\",api=\"sensitivity\",title=list(ko=\"사전 정보가 없으면 0으로 채우지 않기\",en=\"No preperiod information is not a zero scale\"),input=list(estimate=\"4\",preDifferences=list(),M=\"1\",horizon=1),expectedReject=FALSE)\r\npanel<-function(rows){G<-list();for(r in rows){key<-r$entity;u<-G[[key]];if(is.null(u))u<-list(g=r$g,rows=list());stopifnot(identical(u$g,r$g),is.null(u$rows[[as.character(r$time)]]));u$rows[[as.character(r$time)]]<-r;G[[key]]<-u};G}\r\ncell<-function(G,g,t,step,control){b<-g-step;members<-list();T<-C<-list();for(key in names(G)){u<-G[[key]];target<-!is.na(u$g)&&u$g==g;comp<-is.na(u$g)||(control=='notyet'&&!is.na(u$g)&&u$g>max(t,b));role<-if(target)'treated'else if(comp)'control'else'excluded-comparison';before<-u$rows[[as.character(b)]];after<-u$rows[[as.character(t)]];yb<-if(is.null(before))NA_real_ else before$y;ya<-if(is.null(after))NA_real_ else after$y;eligible<-role!='excluded-comparison'&&!is.na(yb)&&!is.na(ya);reason<-if(role=='excluded-comparison')'target-or-already-exposed-cohort-not-valid-control'else if(is.null(before))'baseline-source-row-absent'else if(is.null(after))'target-time-source-row-absent'else if(is.na(yb))'baseline-outcome-missing'else if(is.na(ya))'target-outcome-missing'else'';m<-list(entity=key,nativeID=u$rows[[1]]$nativeID,g=u$g,role=role,eligible=eligible,baselineSourceId=if(is.null(before))NA_character_ else before$id,targetSourceId=if(is.null(after))NA_character_ else after$id,before=yb,after=ya,change=if(eligible)ya-yb else NA_real_,reason=reason);members[[key]]<-m;if(eligible){if(role=='treated')T[[length(T)+1L]]<-m else C[[length(C)+1L]]<-m}}\r\n change<-function(a)vapply(a,function(r)r$change,0);d<-mean0(change(T));e<-mean0(change(C));estimate<-if(is.na(d)||is.na(e))NA_real_ else d-e;defined<-!is.na(estimate);scores<-setNames(rep(NA_real_,length(members)),names(members));for(key in names(members)){m<-members[[key]];s<-if(!defined)NA_real_ else if(!m$eligible)0 else if(m$role=='treated')(m$change-d)/length(T)else-(m$change-e)/length(C);m$score<-s;scores[key]<-s;members[[key]]<-m};st<-var0(change(T));sc<-var0(change(C));v<-if(is.na(st)||is.na(sc))NA_real_ else st/length(T)+sc/length(C);level<-function(a,k)mean0(vapply(a,function(r)r[[k]],0))\r\n list(g=g,t=t,baseline=b,event=(t-g)/step,phase=if(t==b)'mechanical-reference'else if(t>=g)'post'else'pre-placebo',defined=defined,estimate=estimate,T=T,C=C,members=members,scores=scores,HC0=if(defined)sum(scores^2)else NA_real_,unbiased=v,treatedMeanBefore=level(T,'before'),treatedMeanAfter=level(T,'after'),treatedMeanChange=d,controlMeanBefore=level(C,'before'),controlMeanAfter=level(C,'after'),controlMeanChange=e)\r\n}\r\ncovariance<-function(cells){n<-length(cells);V<-matrix(NA_real_,n,n);for(i in seq_len(n))for(j in seq_len(n))if(cells[[i]]$defined&&cells[[j]]$defined)V[i,j]<-sum(cells[[i]]$scores*cells[[j]]$scores);V}\r\naggregate_cells<-function(post,V,step){out<-list();push<-function(typ,key,ii,w){est<-if(!length(ii)||any(vapply(post[ii],function(z)is.na(z$estimate),TRUE)))NA_real_ else sum(w*vapply(post[ii],function(z)z$estimate,0));vv<-if(is.na(est)||anyNA(V[ii,ii,drop=FALSE]))NA_real_ else as.numeric(t(w)%*%V[ii,ii,drop=FALSE]%*%w);out[[length(out)+1L]]<<-list(type=typ,key=as.character(key),ii=ii,w=w,estimate=est,variance=vv)};positive<-which(vapply(post,function(c)length(c$T)>0L,TRUE));mass<-sum(vapply(post[positive],function(c)length(c$T),0));push('simple','overall',positive,if(mass)vapply(post[positive],function(c)length(c$T)/mass,0)else numeric())\r\n for(typ in c('event','calendar','group')){keys<-vapply(post,function(c)if(typ=='event')c$event else if(typ=='calendar')c$t else c$g,0);gg<-sort(unique(keys));cohortmass<-if(typ=='group')sum(vapply(gg,function(k)length(post[[which(keys==k)[1]]]$T),0))else 0;allii<-integer();allw<-numeric();for(key in gg){ii<-which(keys==key);jj<-ii[vapply(post[ii],function(c)length(c$T)>0L,TRUE)];if(typ=='group'){stopifnot(length(unique(vapply(post[ii],function(c)length(c$T),0)))<=1L);w<-if(length(jj))rep(1/length(jj),length(jj))else numeric();if(cohortmass){allii<-c(allii,jj);allw<-c(allw,w*length(post[[ii[1]]]$T)/cohortmass)}}else{total<-sum(vapply(post[jj],function(c)length(c$T),0));w<-if(total)vapply(post[jj],function(c)length(c$T)/total,0)else numeric()};push(typ,key,jj,w)};if(typ=='group')push(typ,'overall',allii,allw)};out}\r\ntwfe<-function(G,times){ledger<-list();good<-list();for(key in names(G)){u<-G[[key]];absent<-times[!as.character(times)%in%names(u$rows)];missing<-times[vapply(times,function(t){r<-u$rows[[as.character(t)]];!is.null(r)&&is.na(r$y)},TRUE)];eligible<-length(times)>0L&&!length(absent)&&!length(missing);ledger[[length(ledger)+1L]]<-list(entity=key,g=u$g,nativeID=u$rows[[1]]$nativeID,eligible=eligible,absentTimes=paste(absent,collapse=','),missingOutcomeTimes=paste(missing,collapse=','),originalRows=length(u$rows));if(eligible)good[[key]]<-u};rows<-list();for(key in names(good))for(t in times){r<-good[[key]]$rows[[as.character(t)]];r$D<-as.integer(!is.na(r$g)&&t>=r$g);rows[[length(rows)+1L]]<-r};em<-lapply(good,function(u)list(D=mean(vapply(times,function(t)as.integer(!is.na(u$g)&&t>=u$g),0)),Y=mean(vapply(u$rows[as.character(times)],function(r)r$y,0))));tm<-lapply(times,function(t)list(D=mean(vapply(good,function(u)as.integer(!is.na(u$g)&&t>=u$g),0)),Y=mean(vapply(good,function(u)u$rows[[as.character(t)]]$y,0))));names(tm)<-as.character(times);gd<-mean0(vapply(rows,function(r)r$D,0));gy<-mean0(vapply(rows,function(r)r$y,0));num<-den<-0\r\n for(i in seq_along(rows)){r<-rows[[i]];r$residualD<-r$D-em[[r$entity]]$D-tm[[as.character(r$time)]]$D+gd;r$residualY<-r$y-em[[r$entity]]$Y-tm[[as.character(r$time)]]$Y+gy;num<-num+r$residualD*r$residualY;den<-den+r$residualD^2;rows[[i]]<-r};beta<-if(den!=0)num/den else NA_real_;weights<-list();for(i in seq_along(rows)){r<-rows[[i]];r$projectionCoefficient<-if(den!=0)r$residualD/den else NA_real_;r$regressionResidual<-if(!is.na(beta))r$residualY-beta*r$residualD else NA_real_;rows[[i]]<-r;if(r$D==1L){k<-paste(r$g,r$time,sep=':');z<-weights[[k]];if(is.null(z))z<-list(g=r$g,t=r$time,rows=0,coefficient=if(den!=0)0 else NA_real_);z$rows<-z$rows+1L;if(den!=0)z$coefficient<-z$coefficient+r$projectionCoefficient;weights[[k]]<-z}};list(ledger=ledger,rows=rows,num=num,den=den,beta=beta,weights=weights,balancedEntities=length(good))}\r\nadjacent_pre<-function(G,g,t,step,control){b<-t-step;T<-C<-numeric();for(u in G){target<-!is.na(u$g)&&u$g==g;comp<-is.na(u$g)||(control=='notyet'&&!is.na(u$g)&&u$g>max(t,b));if(!target&&!comp)next;before<-u$rows[[as.character(b)]];after<-u$rows[[as.character(t)]];if(!is.null(before)&&!is.null(after)&&!is.na(before$y)&&!is.na(after$y)){if(target)T<-c(T,after$y-before$y)else C<-c(C,after$y-before$y)}};if(!length(T)||!length(C))NA_real_ else mean(T)-mean(C)}\r\n\r\n# Newly authored bounded teaching projections; base R finite approximation.\r\n# Source helper functions are inlined in each public file, never imported.\r\nqnum<-function(v){if(is.null(v)||is.na(v))return(NA_real_);s<-strsplit(as.character(v),'/',fixed=TRUE)[[1]];if(length(s)==1L)as.numeric(s)else as.numeric(s[1])/as.numeric(s[2])}\r\npaired<-function(T,C){\r\n stats<-function(rr){use<-Filter(function(r)!is.na(qnum(r$before))&&!is.na(qnum(r$after)),rr);a<-vapply(use,function(r)qnum(r$before),0);b<-vapply(use,function(r)qnum(r$after),0);list(sourcePairs=length(rr),eligiblePairs=length(use),excludedPairs=length(rr)-length(use),meanBefore=mean0(a),meanAfter=mean0(b),meanChange=mean0(b-a),sampleChangeVariance=var0(b-a))}\r\n st<-stats(T);sc<-stats(C);defined<-st$eligiblePairs>0L&&sc$eligiblePairs>0L;estimate<-if(defined)st$meanChange-sc$meanChange else NA_real_;rr<-list()\r\n for(role in c('treated','control')){input<-if(role=='treated')T else C;s<-if(role=='treated')st else sc;for(r in input){before<-qnum(r$before);after<-qnum(r$after);eligible<-!is.na(before)&&!is.na(after);change<-if(eligible)after-before else NA_real_;score<-if(!defined)NA_real_ else if(!eligible)0 else (change-s$meanChange)/(if(role=='treated')s$eligiblePairs else -s$eligiblePairs);rr[[length(rr)+1L]]<-list(id=r$id,role=role,before=before,after=after,eligible=eligible,change=change,score=score)}}\r\n list(defined=defined,estimate=estimate,treated=st,control=sc,unbiasedVariance=if(defined&&st$eligiblePairs>=2L&&sc$eligiblePairs>=2L)st$sampleChangeVariance/st$eligiblePairs+sc$sampleChangeVariance/sc$eligiblePairs else NA_real_,HC0=if(defined)sum(vapply(rr,function(r)r$score^2,0))else NA_real_,rows=rr)\r\n}\r\nliteral_panel<-function(rr)lapply(seq_along(rr),function(i){r<-rr[[i]];r$y<-qnum(r$y);r$nativeID<-r$entity;r$sourceRow<-i;r})\r\natt_projection<-function(rows,control='never',step=1){G<-panel(rows);times<-sort(unique(vapply(rows,function(r)r$time,0)));cohorts<-sort(unique(na.omit(vapply(rows,function(r)r$g,0))));cells<-list();for(g in cohorts)for(t in times)cells[[length(cells)+1L]]<-cell(G,g,t,step,control);list(sourceRows=length(rows),sourceEntities=length(G),step=step,control=control,cells=cells,covariance=covariance(cells))}\r\nlinear_aggregate<-function(a){\r\n rr<-lapply(a$cells,function(r){r$estimate<-qnum(r$estimate);r$weight<-qnum(r$weight);r});V<-if(is.null(a$covariance))NULL else do.call(rbind,lapply(a$covariance,function(r)vapply(r,qnum,0)));rank<-NA_real_\r\n if(!is.null(V)){stopifnot(nrow(V)==length(rr),ncol(V)==length(rr),all(V==t(V)));ev<-eigen(V,symmetric=TRUE,only.values=TRUE)$values;if(any(ev< -1e-12))stop('covariance-must-be-positive-semidefinite');rank<-sum(ev>1e-12)}\r\n selected<-which(vapply(rr,function(r)r$time>=r$cohort&&r$weight>0,TRUE));w<-numeric(length(rr));type<-if(is.null(a$type))'simple'else a$type\r\n if(type=='simple'){mass<-sum(vapply(rr[selected],function(r)r$weight,0));if(mass>0)for(i in selected)w[i]<-rr[[i]]$weight/mass}else{g<-vapply(rr,function(r)r$cohort,0);gg<-sort(unique(g[selected]));mass<-sum(vapply(gg,function(gi)rr[[intersect(which(g==gi),selected)[1]]]$weight,0));for(gi in gg){ii<-intersect(which(g==gi),selected);stopifnot(length(unique(vapply(rr[ii],function(r)r$weight,0)))==1L);w[ii]<-rr[[ii[1]]]$weight/mass/length(ii)}}\r\n used<-which(w>0);estimate<-if(!length(used)||any(vapply(rr[used],function(r)is.na(r$estimate),TRUE)))NA_real_ else sum(w[used]*vapply(rr[used],function(r)r$estimate,0));variance<-if(is.na(estimate)||is.null(V))NA_real_ else as.numeric(t(w)%*%V%*%w);weights<-lapply(used,function(i)list(sourceIndex=i-1L,cohort=rr[[i]]$cohort,time=rr[[i]]$time,coefficient=w[i],estimate=rr[[i]]$estimate,contribution=w[i]*rr[[i]]$estimate))\r\n list(type=type,defined=!is.na(estimate),estimate=estimate,variance=variance,covarianceRank=rank,weights=weights,cells=rr,covariance=V)\r\n}\r\nsensitivity_fixed<-function(a){estimate<-qnum(a$estimate);M<-qnum(a$M);h<-if(is.null(a$horizon))1 else a$horizon;stopifnot(M>=0,h>=1);pre<-vapply(a$preDifferences,qnum,0);scale<-if(!is.null(a$scale))qnum(a$scale)else if(length(pre))max(abs(pre))else NA_real_;budget<-M*scale*h;list(defined=!is.na(scale),estimate=estimate,scale=scale,M=M,horizon=h,biasBudget=budget,lower=estimate-budget,upper=estimate+budget,preDifferences=as.list(pre),confidenceLevel=NULL)}\r\nrealdata_fixed<-function(kind){rows<-models[[kind]];G<-panel(rows);times<-sort(unique(vapply(rows,function(r)r$time,0)));step<-unname(steps[kind]);aa<-att_projection(rows,'never',step);post<-Filter(function(r)r$phase=='post',aa$cells);aggs<-aggregate_cells(post,covariance(post),step);tf<-twfe(G,times);list(kind=kind,unit=unname(units[kind]),periodUnit=unname(clocks[kind]),nativeRows=nrow(raw[[kind]]),modelRows=length(rows),entities=length(G),sourceRows=rows,att=aa,aggregations=aggs,twfe=tf,scope='Complete native/model/paired/balanced source frames; never control,universal base,no anticipation;not causal/sampling certification.')}\r\n# JSON encoder deliberately handles matrices and scalar/vector distinctions.\r\nencode<-function(x){\r\n if(is.null(x))return('null')\r\n quote<-function(s){s<-gsub('\\\\','\\\\\\\\',as.character(s),fixed=TRUE);s<-gsub('\"','\\\\\"',s,fixed=TRUE);s<-gsub('\\n','\\\\n',s,fixed=TRUE);s<-gsub('\\r','\\\\r',s,fixed=TRUE);s<-gsub('\\t','\\\\t',s,fixed=TRUE);paste0('\"',s,'\"')}\r\n if(is.matrix(x))return(paste0('[',paste(vapply(seq_len(nrow(x)),function(i)encode(as.list(unname(x[i,]))),''),collapse=','),']'))\r\n if(is.list(x)){if(length(x)&&!is.null(names(x)))return(paste0('{',paste(paste0(vapply(names(x),quote,''),':',vapply(x,encode,'')),collapse=','),'}'));return(paste0('[',paste(vapply(x,encode,''),collapse=','),']'))}\r\n if(length(x)!=1L)return(encode(as.list(unname(x))))\r\n if(is.na(x))return('null');if(is.logical(x))return(if(x)'true'else'false');if(is.numeric(x))return(sprintf('%.17g',unname(x)));quote(x)\r\n}\r\nv9<-function(x){if(is.null(x)||is.na(x))return('undefined');if(is.logical(x))return(if(x)'1'else'0');if(is.numeric(x))return(sprintf('%.9g',unname(x)));as.character(x)}\r\nrun_fixed<-function(spec,out){api<-spec$api;a<-spec$input;summary<-list();points<-list();emit<-function(series,x,y){points[[length(points)+1L]]<<-list(series=series,x=x,y=y,numericY=y)}\r\n if(api=='twobytwo'){result<-paired(a$treated,a$control);summary<-list(defined=result$defined,estimate=result$estimate,treatedPairs=result$treated$eligiblePairs,controlPairs=result$control$eligiblePairs,unbiasedVariance=result$unbiasedVariance,HC0=result$HC0);for(i in seq_along(result$rows)){r<-result$rows[[i]];emit(paste(r$role,r$id,sep=':'),i,r$change)}}\r\n else if(api=='att'){result<-att_projection(literal_panel(a$rows),a$control);summary<-list(sourceRows=result$sourceRows,entities=result$sourceEntities,cells=length(result$cells),supportedCells=sum(vapply(result$cells,function(r)r$defined,TRUE)),postCells=sum(vapply(result$cells,function(r)r$phase=='post',TRUE)));for(i in seq_along(result$cells)){r<-result$cells[[i]];emit(paste0('g',r$g,':t',r$t),i,r$estimate)}}\r\n else if(api=='aggregate'){result<-linear_aggregate(a);summary<-list(defined=result$defined,estimate=result$estimate,variance=result$variance,covarianceRank=result$covarianceRank,sumWeights=sum(vapply(result$weights,function(r)r$coefficient,0)));for(i in seq_along(result$weights)){r<-result$weights[[i]];emit(paste0('g',r$cohort,':t',r$time),i,r$contribution)}}\r\n else if(api=='twfe'){rows<-literal_panel(a$rows);G<-panel(rows);result<-twfe(G,sort(unique(vapply(rows,function(r)r$time,0))));summary<-list(defined=!is.na(result$beta),beta=result$beta,numerator=result$num,denominator=result$den,balancedEntities=result$balancedEntities,negativeTreatedCells=sum(vapply(result$weights,function(r)!is.na(r$coefficient)&&r$coefficient<0,TRUE)));if(length(result$weights)){ord<-order(vapply(result$weights,function(r)r$g,0),vapply(result$weights,function(r)r$t,0));for(i in seq_along(ord)){r<-result$weights[[ord[i]]];emit(paste0('g',r$g,':t',r$t),i,r$coefficient)}}}\r\n else if(api=='sensitivity'){result<-sensitivity_fixed(a);summary<-result[c('defined','estimate','scale','M','horizon','biasBudget','lower','upper')];for(i in seq_along(c('lower','estimate','upper'))){k<-c('lower','estimate','upper')[i];emit(k,i,if(result$defined)result[[k]]else NA_real_)}}\r\n else{result<-realdata_fixed(a$kind);post<-Filter(function(r)r$phase=='post',result$att$cells);simple<-Filter(function(r)r$type=='simple',result$aggregations)[[1]];group<-Filter(function(r)r$type=='group'&&r$key=='overall',result$aggregations)[[1]];summary<-list(nativeRows=result$nativeRows,modelRows=result$modelRows,entities=result$entities,postCells=length(post),simple=simple$estimate,group=group$estimate,TWFE=result$twfe$beta,balancedEntities=result$twfe$balancedEntities);for(i in seq_along(post)){r<-post[[i]];emit(paste0('g',r$g,':t',r$t),i,r$estimate)}}\r\n dir.create(out,recursive=TRUE,showWarnings=FALSE);if(length(list.files(out,all.files=TRUE,no..=TRUE)))stop('use-new-empty-output-directory');shown<-lapply(summary,v9);write.csv(data.frame(name=names(shown),value=unlist(shown,use.names=FALSE)),file.path(out,'summary.csv'),row.names=FALSE,na='');pointframe<-if(length(points))do.call(rbind,lapply(points,function(p)data.frame(series=p$series,x=p$x,y=p$y,numericY=p$numericY,stringsAsFactors=FALSE)))else data.frame(series=character(),x=numeric(),y=numeric(),numericY=numeric());write.csv(pointframe,file.path(out,'points.csv'),row.names=FALSE,na='');full<-list(chapter='METR-20',profile=spec$id,api=api,input=spec$input,summary=shown,points=points,details=result,arithmetic='Base R approximate finite values;bounded teaching projection,not exact fractions or causal/sampling certification.');writeLines(encode(full),file.path(out,'full.json'),useBytes=TRUE)\r\n svg(file.path(out,'plot.svg'),width=9,height=5.6,pointsize=12);par(mar=c(4.5,5.5,4,1));good<-pointframe[!is.na(pointframe$numericY),,drop=FALSE]\r\n if(nrow(good)){plot(good$x,good$numericY,pch=19,col='#315d7c',xlab='Declared cell/unit/bound ordinal',ylab=if(api=='twfe')'Cell weight'else if(!is.null(result$unit))result$unit else 'Stated outcome/bias units',main=spec$title$en);abline(h=0,col='#9eabb2');grid(nx=NA,ny=NULL,col='#e2e5e7');points(good$x,good$numericY,pch=19,col='#315d7c')}else{plot.new();text(.5,.5,'Undefined: no supported plotted quantity');title(main=spec$title$en)};dev.off();cat(encode(shown),'\\n')\r\n}\r\n\r\nrun_fixed(SPEC,outdir)\r\n",
      "arithmetic": "Base R approximate finite arithmetic;not an exact rational result",
      "summary": {
        "defined": "0",
        "estimate": "4",
        "scale": "undefined",
        "M": "1",
        "horizon": "1",
        "biasBudget": "undefined",
        "lower": "undefined",
        "upper": "undefined"
      },
      "fullResultEmbedded": false,
      "plotEmbedded": false,
      "full": {
        "summary": {
          "defined": "0",
          "estimate": "4",
          "scale": "undefined",
          "M": "1",
          "horizon": "1",
          "biasBudget": "undefined",
          "lower": "undefined",
          "upper": "undefined"
        },
        "notice": "Complete source/finite projection is retained in the linked external JSON; this short projection is not the full result."
      },
      "plot": null,
      "points": [
        {
          "series": "lower",
          "x": 1,
          "y": null,
          "numericY": null
        },
        {
          "series": "estimate",
          "x": 2,
          "y": null,
          "numericY": null
        },
        {
          "series": "upper",
          "x": 3,
          "y": null,
          "numericY": null
        }
      ],
      "summaryFile": "metr20-programs/sensitivity-no-preperiod-r-summary.csv",
      "summarySHA256": "b0e242e0722f0cf311e2f9482acbc4e4c5ce99bbce8791be7d2bd932cec2115d",
      "pointsFile": "metr20-programs/sensitivity-no-preperiod-r-points.csv",
      "pointsSHA256": "02469b64f9b6be216e355b1204b2a145737a8e4f742be37688a22ab47b46b539",
      "fullResultFile": "metr20-programs/sensitivity-no-preperiod-r.json",
      "fullResultSHA256": "61bcda82c57719d8cafd25fa13e83a66929338a16066548c17d3dfe512b1257c",
      "plotFile": "metr20-programs/sensitivity-no-preperiod-r.svg",
      "plotSHA256": "c5035d8d644fa26630900654c9903c0535375a8149c601549069adcfd5b18749"
    },
    {
      "api": "sensitivity",
      "variant": "sensitivity-zero-observed",
      "profile": "sensitivity-zero-observed",
      "language": "Python",
      "file": "metr20-programs/sensitivity-zero-observed-python.py",
      "codeSHA256": "acde57db47133591d7f9d518d823ce4a444c963ea7ab251c43fac5a306cd39cf",
      "returnCode": 0,
      "expectedRejection": false,
      "title": {
        "ko": "관측된 사전 차이 0과 미래 가정",
        "en": "Zero observed precontrasts and a future assumption"
      },
      "code": "\"\"\"METR20 actual sources. Python standard library, exact stored-value rationals.\r\nRead ONLY the three native-observation CSVs; no JS engine,model JSON,derived\r\nanswers,private modules or internet needed. Outcome measurement/identification\r\nand valid sampling inference remain separate from exact finite arithmetic.\r\nRun: python metr20-reproduce.py --data-dir PATH --out NEW_EMPTY_DIRECTORY\r\n\"\"\"\r\nfrom pathlib import Path\r\nfrom fractions import Fraction as Q\r\nfrom collections import defaultdict,Counter\r\nimport csv,json,math,argparse,hashlib\r\n\r\nUNIT={'country':'log teen-employment points','person':'recorded real earnings','company':'FTE employees'}\r\nCLOCK={'country':'calendar year','person':'calendar year','company':'survey-wave index'}\r\nSTEP={'country':1,'person':3,'company':1}\r\nFILES={'country':'actual2500-county-mpdta-all6-fields.csv','person':'actual38408-NSW-all15-fields.csv','company':'actual410-NJPA-all46-fields.csv'}\r\ndef avg(v):return sum(v,Q(0))/len(v)if v else None\r\ndef samplevar(v):return sum(((x-avg(v))**2 for x in v),Q(0))/(len(v)-1)if len(v)>1 else None\r\ndef binary(s):return None if s=='.'else Q.from_float(float(s))\r\ndef token(v):\r\n if v is None:return ''\r\n if isinstance(v,bool):return 'true'if v else'false'\r\n return str(v)\r\ndef safe_float(v):\r\n if v is None:return None\r\n try:r=float(v)\r\n except OverflowError:return None\r\n return r if math.isfinite(r)else None\r\ndef read(p):\r\n with p.open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))\r\ndef write(p,rows,head=None):\r\n if head is None:\r\n  assert rows;head=list(rows[0])\r\n with p.open('w',encoding='utf8',newline='')as f:\r\n  w=csv.DictWriter(f,fieldnames=head);w.writeheader();w.writerows({k:token(r.get(k))for k in head}for r in rows)\r\ndef source(data):\r\n raw={k:read(data/n)for k,n in FILES.items()};assert[len(raw[k])for k in FILES]==[2500,38408,410]\r\n models={k:[]for k in FILES}\r\n for r in raw['country']:\r\n  g0=int(r['first.treat']);g=None if g0==0 else g0;assert int(r['treat'])==int(g is not None)\r\n  models['country'].append(dict(id='mpdta:'+r['sourceRow'],entity='county:'+str(int(r['countyreal'])),time=int(r['year']),y=binary(r['lemp']),g=g,sourceRow=int(r['sourceRow']),nativeID=r['countyreal']))\r\n for r in raw['person']:\r\n  selected=int(r['experimental'])==1;assert selected==(int(r['sample'])==1);assert(r['treated']!='.')==selected\r\n  if selected:\r\n   d=int(r['treated']);assert d in[0,1]\r\n   models['person'].append(dict(id='nsw:'+r['sourceRow'],entity='nsw-id:'+str(int(r['id'])),time=int(r['year']),y=binary(r['re']),g=1978 if d else None,sourceRow=int(r['sourceRow']),nativeID=str(int(r['id']))))\r\n for r in raw['company']:\r\n  state=int(r['STATE']);assert state in[0,1]\r\n  for t,suffix in[(0,''),(1,'2')]:\r\n   a=[r[n+suffix]for n in['EMPFT','NMGRS','EMPPT']];y=None if'.'in a else Q(a[0])+Q(a[1])+Q(a[2])/2\r\n   models['company'].append(dict(id='njpa:'+r['sourceRow']+':wave'+str(t),entity='njpa-row:'+r['sourceRow'],time=t,y=y,g=1 if state else None,sourceRow=int(r['sourceRow']),nativeID=r['SHEET']))\r\n assert[len(models[k])for k in FILES]==[2500,1444,820]\r\n return models,raw\r\ndef panel(rows):\r\n groups={}\r\n for r in rows:\r\n  u=groups.setdefault(r['entity'],{'g':r['g'],'rows':{}});assert u['g']==r['g']and r['time']not in u['rows'];u['rows'][r['time']]=r\r\n return groups\r\ndef cell(groups,g,t,step,control):\r\n b=g-step;members=[];T=[];C=[]\r\n for key,u in groups.items():\r\n  role='treated'if u['g']==g else'control'if u['g']is None or(control=='notyet'and u['g']>max(t,b))else'excluded-comparison'\r\n  before=u['rows'].get(b);after=u['rows'].get(t);yb=None if before is None else before['y'];ya=None if after is None else after['y'];eligible=role!='excluded-comparison'and yb is not None and ya is not None\r\n  reason='target-or-already-exposed-cohort-not-valid-control'if role=='excluded-comparison'else'baseline-source-row-absent'if before is None else'target-time-source-row-absent'if after is None else'baseline-outcome-missing'if yb is None else'target-outcome-missing'if ya is None else''\r\n  m={'entity':key,'nativeID':next(iter(u['rows'].values()))['nativeID'],'g':u['g'],'role':role,'eligible':eligible,'baselineSourceId':None if before is None else before['id'],'targetSourceId':None if after is None else after['id'],'before':yb,'after':ya,'change':ya-yb if eligible else None,'reason':reason};members.append(m)\r\n  if eligible:(T if role=='treated'else C).append(m)\r\n d=avg([r['change']for r in T]);e=avg([r['change']for r in C]);estimate=None if d is None or e is None else d-e;defined=estimate is not None;scores={}\r\n for m in members:\r\n  s=None if not defined else Q(0)\r\n  if defined and m['eligible']:s=(m['change']-(d if m['role']=='treated'else e))/(len(T)if m['role']=='treated'else-len(C))\r\n  m['score']=s;scores[m['entity']]=s\r\n st=samplevar([r['change']for r in T]);sc=samplevar([r['change']for r in C]);v=None if st is None or sc is None else st/len(T)+sc/len(C)\r\n return {'g':g,'t':t,'baseline':b,'event':(t-g)//step,'phase':'mechanical-reference'if t==b else'post'if t>=g else'pre-placebo','defined':defined,'estimate':estimate,'T':T,'C':C,'members':members,'scores':scores,'HC0':None if not defined else sum((s*s for s in scores.values()),Q(0)),'unbiased':v,'treatedMeanBefore':avg([r['before']for r in T]),'treatedMeanAfter':avg([r['after']for r in T]),'treatedMeanChange':d,'controlMeanBefore':avg([r['before']for r in C]),'controlMeanAfter':avg([r['after']for r in C]),'controlMeanChange':e}\r\ndef covariance(cells):\r\n return[[None if not a['defined']or not b['defined']else sum((v*b['scores'][i]for i,v in a['scores'].items()),Q(0))for b in cells]for a in cells]\r\ndef aggregate(post,V,step):\r\n out=[]\r\n def push(typ,key,coeff):\r\n  estimate=None if not coeff or any(post[i]['estimate']is None for i in coeff)else sum((w*post[i]['estimate']for i,w in coeff.items()),Q(0));variance=None if estimate is None or any(V[i][j]is None for i in coeff for j in coeff)else sum((a*b*V[i][j]for i,a in coeff.items()for j,b in coeff.items()),Q(0));out.append({'type':typ,'key':key,'coeff':coeff,'estimate':estimate,'variance':variance})\r\n positive=[i for i,c in enumerate(post)if len(c['T'])>0];mass=sum(len(post[i]['T'])for i in positive)\r\n push('simple','overall',{i:Q(len(post[i]['T']),mass)for i in positive}if mass else{})\r\n for typ in['event','calendar','group']:\r\n  groups=defaultdict(list)\r\n  for i,c in enumerate(post):groups[c['event']if typ=='event'else c['t']if typ=='calendar'else c['g']].append(i)\r\n  overall={};cohortMass=sum(len(post[ii[0]]['T'])for ii in groups.values())if typ=='group'else 0\r\n  for key,ii in sorted(groups.items()):\r\n   jj=[i for i in ii if len(post[i]['T'])>0]\r\n   if typ=='group':\r\n    assert len({len(post[i]['T'])for i in ii})<=1\r\n    coeff={i:Q(1,len(jj))for i in jj}if jj else{}\r\n    if cohortMass:\r\n     for i,w in coeff.items():overall[i]=w*Q(len(post[ii[0]]['T']),cohortMass)\r\n   else:\r\n    total=sum(len(post[i]['T'])for i in jj);coeff={i:Q(len(post[i]['T']),total)for i in jj}if total else{}\r\n   push(typ,str(key),coeff)\r\n  if typ=='group':push(typ,'overall',overall)\r\n return out\r\ndef twfe(groups,times):\r\n ledger=[];good={}\r\n for key,u in groups.items():\r\n  absent=[t for t in times if t not in u['rows']];missing=[t for t in times if t in u['rows']and u['rows'][t]['y']is None];eligible=bool(times)and not absent and not missing\r\n  ledger.append({'entity':key,'g':u['g'],'nativeID':next(iter(u['rows'].values()))['nativeID'],'eligible':eligible,'absentTimes':','.join(map(str,absent)),'missingOutcomeTimes':','.join(map(str,missing)),'originalRows':len(u['rows'])})\r\n  if eligible:good[key]=u\r\n rows=[dict(**u['rows'][t],D=Q(u['g']is not None and t>=u['g']))for key,u in good.items()for t in times]\r\n em={k:{'D':avg([Q(u['g']is not None and t>=u['g'])for t in times]),'Y':avg([u['rows'][t]['y']for t in times])}for k,u in good.items()};tm={t:{'D':avg([Q(u['g']is not None and t>=u['g'])for u in good.values()]),'Y':avg([u['rows'][t]['y']for u in good.values()])}for t in times};gd=avg([r['D']for r in rows]);gy=avg([r['y']for r in rows]);num=den=Q(0)\r\n for r in rows:\r\n  r['residualD']=r['D']-em[r['entity']]['D']-tm[r['time']]['D']+gd;r['residualY']=r['y']-em[r['entity']]['Y']-tm[r['time']]['Y']+gy;num+=r['residualD']*r['residualY'];den+=r['residualD']**2\r\n beta=num/den if den else None;weights={}\r\n for r in rows:\r\n  r['projectionCoefficient']=r['residualD']/den if den else None;r['regressionResidual']=r['residualY']-beta*r['residualD']if beta is not None else None\r\n  if r['D']:\r\n   k=(r['g'],r['time']);z=weights.setdefault(k,{'rows':0,'coefficient':Q(0)if den else None});z['rows']+=1\r\n   if den:z['coefficient']+=r['projectionCoefficient']\r\n return {'ledger':ledger,'rows':rows,'num':num,'den':den,'beta':beta,'weights':weights,'balancedEntities':len(good)}\r\ndef adjacent_pre(groups,g,t,step,control):\r\n b=t-step;T=[];C=[]\r\n for u in groups.values():\r\n  if u['g']==g:target=T\r\n  elif u['g']is None or(control=='notyet'and u['g']>max(t,b)):target=C\r\n  else:continue\r\n  before=u['rows'].get(b);after=u['rows'].get(t)\r\n  if before is not None and after is not None and before['y']is not None and after['y']is not None:target.append(after['y']-before['y'])\r\n return None if not T or not C else avg(T)-avg(C)\r\n\r\n\"\"\"New bounded teaching projections. The program is self-contained after build.\r\nExact Fraction finite algebra; figures and9-digit summary are approximations.\r\nIt is not a general parser/API replacement or a causal/inference certificate.\r\n\"\"\"\r\ndef paired(treated,control):\r\n def stats(rr):\r\n  use=[r for r in rr if r['before']is not None and r['after']is not None];delta=[Q(r['after'])-Q(r['before'])for r in use]\r\n  return dict(sourcePairs=len(rr),eligiblePairs=len(use),excludedPairs=len(rr)-len(use),meanBefore=avg([Q(r['before'])for r in use]),meanAfter=avg([Q(r['after'])for r in use]),meanChange=avg(delta),sampleChangeVariance=samplevar(delta))\r\n T,C=stats(treated),stats(control);defined=T['eligiblePairs']>0 and C['eligiblePairs']>0;estimate=T['meanChange']-C['meanChange']if defined else None;records=[]\r\n for group,rr,s in [('treated',treated,T),('control',control,C)]:\r\n  for r in rr:\r\n   before=None if r['before']is None else Q(r['before']);after=None if r['after']is None else Q(r['after']);eligible=before is not None and after is not None;delta=after-before if eligible else None;score=None if not defined else Q(0)if not eligible else(delta-s['meanChange'])/(s['eligiblePairs']if group=='treated'else-s['eligiblePairs']);records.append(dict(id=r['id'],role=group,before=before,after=after,eligible=eligible,change=delta,score=score))\r\n unbiased=None if not defined or T['eligiblePairs']<2 or C['eligiblePairs']<2 else T['sampleChangeVariance']/T['eligiblePairs']+C['sampleChangeVariance']/C['eligiblePairs'];hc0=None if not defined else sum((r['score']**2 for r in records),Q(0))\r\n return dict(defined=defined,estimate=estimate,treated=T,control=C,unbiasedVariance=unbiased,HC0=hc0,rows=records)\r\ndef literal_panel(raw):\r\n return[dict(r,y=None if r['y']is None else Q(r['y']),nativeID=r['entity'],sourceRow=i+1)for i,r in enumerate(raw)]\r\ndef att_projection(rows,control='never',step=1):\r\n G=panel(rows);times=sorted({r['time']for r in rows});cohorts=sorted({r['g']for r in rows if r['g']is not None});cells=[cell(G,g,t,step,control)for g in cohorts for t in times]\r\n return dict(sourceRows=len(rows),sourceEntities=len(G),step=step,control=control,cells=cells,covariance=covariance(cells))\r\ndef psd(V):\r\n A=[r[:]for r in V];rank=0\r\n while A:\r\n  if any(A[i][i]<0 for i in range(len(A))):raise ValueError('covariance-must-be-positive-semidefinite')\r\n  p=next((i for i in range(len(A))if A[i][i]>0),None)\r\n  if p is None:\r\n   if any(v for r in A for v in r):raise ValueError('covariance-must-be-positive-semidefinite')\r\n   return rank\r\n  A[0],A[p]=A[p],A[0]\r\n  for r in A:r[0],r[p]=r[p],r[0]\r\n  d=A[0][0];A=[[A[i][j]-A[i][0]*A[0][j]/d for j in range(1,len(A))]for i in range(1,len(A))];rank+=1\r\n return rank\r\ndef linear_aggregate(a):\r\n rr=[dict(r,estimate=None if r['estimate']is None else Q(r['estimate']),weight=Q(r['weight']))for r in a['cells']];V=[[Q(v)for v in r]for r in a['covariance']]if 'covariance'in a else None\r\n if V is not None:\r\n  assert len(V)==len(rr)and all(len(z)==len(rr)for z in V);assert all(V[i][j]==V[j][i]for i in range(len(rr))for j in range(len(rr)));rank=psd(V)\r\n else:rank=None\r\n selected=[i for i,r in enumerate(rr)if r['time']>=r['cohort']and r['weight']>0];weights={}\r\n if a.get('type','simple')=='simple':\r\n  mass=sum((rr[i]['weight']for i in selected),Q(0));weights={i:rr[i]['weight']/mass for i in selected}if mass else{}\r\n else:\r\n  gg=defaultdict(list)\r\n  for i in selected:gg[rr[i]['cohort']].append(i)\r\n  assert all(len({rr[i]['weight']for i in ii})==1 for ii in gg.values());mass=sum((rr[ii[0]]['weight']for ii in gg.values()),Q(0));weights={i:rr[ii[0]]['weight']/mass/len(ii)for ii in gg.values()for i in ii}if mass else{}\r\n estimate=None if not weights or any(rr[i]['estimate']is None for i in weights)else sum((w*rr[i]['estimate']for i,w in weights.items()),Q(0));variance=None if estimate is None or V is None else sum((x*y*V[i][j]for i,x in weights.items()for j,y in weights.items()),Q(0))\r\n return dict(type=a.get('type','simple'),defined=estimate is not None,estimate=estimate,variance=variance,covarianceRank=rank,weights=[dict(sourceIndex=i,cohort=rr[i]['cohort'],time=rr[i]['time'],coefficient=w,estimate=rr[i]['estimate'],contribution=None if rr[i]['estimate']is None else w*rr[i]['estimate'])for i,w in weights.items()],cells=rr,covariance=V)\r\ndef sensitivity_fixed(a):\r\n estimate=Q(a['estimate']);M=Q(a['M']);h=a.get('horizon',1);assert M>=0 and h>=1\r\n pre=[Q(v)for v in a.get('preDifferences',[])];scale=Q(a['scale'])if 'scale'in a else max(map(abs,pre))if pre else None;budget=None if scale is None else M*scale*h\r\n return dict(defined=scale is not None,estimate=estimate,scale=scale,M=M,horizon=h,biasBudget=budget,lower=None if budget is None else estimate-budget,upper=None if budget is None else estimate+budget,preDifferences=pre,confidenceLevel=None)\r\ndef realdata_fixed(kind,data):\r\n models,raw=source(data);rows=models[kind];G=panel(rows);times=sorted({r['time']for r in rows});step=STEP[kind];aa=att_projection(rows,'never',step);post=[r for r in aa['cells']if r['phase']=='post'];aggs=aggregate(post,covariance(post),step);tf=twfe(G,times)\r\n return dict(kind=kind,unit=UNIT[kind],periodUnit=CLOCK[kind],nativeRows=len(raw[kind]),modelRows=len(rows),entities=len(G),sourceRows=rows,att=aa,aggregations=aggs,twfe=tf,scope='Complete source frame; never-treated comparison,universal baseline,no anticipation. Native/model/paired/balanced denominators differ. All sampling/causal assumptions remain separate.')\r\ndef encode(v):\r\n if isinstance(v,Q):return str(v)\r\n if isinstance(v,dict):return{str(k):encode(x)for k,x in v.items()}\r\n if isinstance(v,(list,tuple)):return[encode(x)for x in v]\r\n return v\r\ndef v9(v):\r\n if v is None:return'undefined'\r\n if isinstance(v,str):return v\r\n if isinstance(v,bool):return'1'if v else'0'\r\n return format(float(v),'.9g')\r\ndef run_fixed(spec,out,data):\r\n api=spec['api'];a=spec['input'];summary={};points=[]\r\n def emit(series,x,y):points.append(dict(series=series,x=x,y=y,numericY=safe_float(y)))\r\n if api=='twobytwo':\r\n  result=paired(a['treated'],a['control']);summary=dict(defined=result['defined'],estimate=result['estimate'],treatedPairs=result['treated']['eligiblePairs'],controlPairs=result['control']['eligiblePairs'],unbiasedVariance=result['unbiasedVariance'],HC0=result['HC0'])\r\n  for i,r in enumerate(result['rows']):emit(r['role']+':'+r['id'],i+1,r['change'])\r\n elif api=='att':\r\n  result=att_projection(literal_panel(a['rows']),a.get('control','never'));summary=dict(sourceRows=result['sourceRows'],entities=result['sourceEntities'],cells=len(result['cells']),supportedCells=sum(r['defined']for r in result['cells']),postCells=sum(r['phase']=='post'for r in result['cells']))\r\n  for i,r in enumerate(result['cells']):emit('g'+str(r['g'])+':t'+str(r['t']),i+1,r['estimate'])\r\n elif api=='aggregate':\r\n  result=linear_aggregate(a);summary=dict(defined=result['defined'],estimate=result['estimate'],variance=result['variance'],covarianceRank=result['covarianceRank'],sumWeights=sum((r['coefficient']for r in result['weights']),Q(0)))\r\n  for i,r in enumerate(result['weights']):emit('g'+str(r['cohort'])+':t'+str(r['time']),i+1,r['contribution'])\r\n elif api=='twfe':\r\n  rows=literal_panel(a['rows']);G=panel(rows);result=twfe(G,sorted({r['time']for r in rows}));summary=dict(defined=result['beta']is not None,beta=result['beta'],numerator=result['num'],denominator=result['den'],balancedEntities=result['balancedEntities'],negativeTreatedCells=sum(v['coefficient']is not None and v['coefficient']<0 for v in result['weights'].values()))\r\n  for i,((g,t),r)in enumerate(sorted(result['weights'].items())):emit('g'+str(g)+':t'+str(t),i+1,r['coefficient'])\r\n elif api=='sensitivity':\r\n  result=sensitivity_fixed(a);summary={k:result[k]for k in['defined','estimate','scale','M','horizon','biasBudget','lower','upper']}\r\n  for i,k in enumerate(['lower','estimate','upper']):emit(k,i+1,result[k]if result['defined']else None)\r\n else:\r\n  result=realdata_fixed(a['kind'],data);post=[r for r in result['att']['cells']if r['phase']=='post'];s=next(r for r in result['aggregations']if r['type']=='simple');g=next(r for r in result['aggregations']if r['type']=='group'and r['key']=='overall');summary=dict(nativeRows=result['nativeRows'],modelRows=result['modelRows'],entities=result['entities'],postCells=len(post),simple=s['estimate'],group=g['estimate'],TWFE=result['twfe']['beta'],balancedEntities=result['twfe']['balancedEntities'])\r\n  for i,r in enumerate(post):emit('g'+str(r['g'])+':t'+str(r['t']),i+1,r['estimate'])\r\n out.mkdir(parents=True,exist_ok=True)\r\n if any(out.iterdir()):raise ValueError('use-new-empty-output-directory')\r\n shown={k:v9(v)for k,v in summary.items()};write(out/'summary.csv',[dict(name=k,value=v)for k,v in shown.items()]);write(out/'points.csv',points,['series','x','y','numericY']);full=dict(chapter='METR-20',profile=spec['id'],api=api,input=spec['input'],summary=shown,points=encode(points),details=encode(result),arithmetic='Python Fraction exact finite stored values;summary/plot approximate;bounded teaching projection,not causal or sampling certification')\r\n (out/'full.json').write_text(json.dumps(full,ensure_ascii=False,indent=2,allow_nan=False)+'\\n',encoding='utf8')\r\n import matplotlib\r\n matplotlib.use('Agg')\r\n import matplotlib.pyplot as plt\r\n plt.rcParams.update({'svg.fonttype':'none','font.family':'DejaVu Sans','font.size':12,'axes.spines.top':False,'axes.spines.right':False});fig,ax=plt.subplots(figsize=(9,5.6));good=[r for r in points if r['numericY']is not None]\r\n if good:\r\n  ax.scatter([r['x']for r in good],[r['numericY']for r in good],color='#315d7c',s=32);ax.axhline(0,color='#9eabb2',lw=.8);ax.set_xlabel('Declared cell/unit/bound ordinal')\r\n else:ax.text(.5,.5,'Undefined: no supported plotted quantity',ha='center',va='center',transform=ax.transAxes);ax.set_xticks([]);ax.set_yticks([])\r\n ax.set_ylabel('Cell weight'if api=='twfe'else result.get('unit','Stated outcome/bias units'));ax.set_title(spec['title']['en'],wrap=True,pad=14);ax.grid(axis='y',alpha=.2);fig.tight_layout(pad=2);fig.savefig(out/'plot.svg');plt.close(fig);print(json.dumps(shown))\r\n\r\nSPEC={'id': 'sensitivity-zero-observed', 'api': 'sensitivity', 'title': {'ko': '관측된 사전 차이 0과 미래 가정', 'en': 'Zero observed precontrasts and a future assumption'}, 'input': {'estimate': '2', 'preDifferences': ['0', '0'], 'M': '3', 'horizon': 2}, 'expectedReject': False}\r\nif __name__=='__main__':\r\n import sys\r\n run_fixed(SPEC,Path(sys.argv[1]),Path(sys.argv[2])if len(sys.argv)>2 else Path(__file__).resolve().parent.parent/'metr20-sources')\r\n",
      "arithmetic": "Python Fraction exact stored finite values;logs/summary/plots approximate",
      "summary": {
        "defined": "1",
        "estimate": "2",
        "scale": "0",
        "M": "3",
        "horizon": "2",
        "biasBudget": "0",
        "lower": "2",
        "upper": "2"
      },
      "fullResultEmbedded": false,
      "plotEmbedded": false,
      "full": {
        "summary": {
          "defined": "1",
          "estimate": "2",
          "scale": "0",
          "M": "3",
          "horizon": "2",
          "biasBudget": "0",
          "lower": "2",
          "upper": "2"
        },
        "notice": "Complete source/finite projection is retained in the linked external JSON; this short projection is not the full result."
      },
      "plot": null,
      "points": [
        {
          "series": "lower",
          "x": 1,
          "y": "2",
          "numericY": 2.0
        },
        {
          "series": "estimate",
          "x": 2,
          "y": "2",
          "numericY": 2.0
        },
        {
          "series": "upper",
          "x": 3,
          "y": "2",
          "numericY": 2.0
        }
      ],
      "summaryFile": "metr20-programs/sensitivity-zero-observed-python-summary.csv",
      "summarySHA256": "19a9c73b97bdb6216fb8b1cee8346f4d1025c1a3fd46415791a46424bd631886",
      "pointsFile": "metr20-programs/sensitivity-zero-observed-python-points.csv",
      "pointsSHA256": "13892da8308202b1e2d5590f270eec85582855650715cca64fc408b9f291bced",
      "fullResultFile": "metr20-programs/sensitivity-zero-observed-python.json",
      "fullResultSHA256": "c27440ad59430626bec3d23af6370cbc39f80af54a93c198d40c3f03ea798e19",
      "plotFile": "metr20-programs/sensitivity-zero-observed-python.svg",
      "plotSHA256": "9b27c828e475981adc4e6d66b858e01d39a0d9d72d59df213469c955258d7e11"
    },
    {
      "api": "sensitivity",
      "variant": "sensitivity-zero-observed",
      "profile": "sensitivity-zero-observed",
      "language": "R",
      "file": "metr20-programs/sensitivity-zero-observed-r.R",
      "codeSHA256": "15a7b6db5259ce05a5738392af79ec1755f1c89d5315320240f3fb78b7301d1b",
      "returnCode": 0,
      "expectedRejection": false,
      "title": {
        "ko": "관측된 사전 차이 0과 미래 가정",
        "en": "Zero observed precontrasts and a future assumption"
      },
      "code": "# METR20 fixed example. Base R only, finite arithmetic approximate.\r\n# No JavaScript engine,model JSON,derived answer table,private module or internet.\r\noptions(stringsAsFactors=FALSE,digits=17)\r\nargv<-commandArgs(trailingOnly=TRUE);if(length(argv)<1L)stop('Supply a new empty output directory')\r\noutdir<-argv[1];script<-sub('^--file=','',commandArgs(FALSE)[grepl('^--file=',commandArgs(FALSE))][1]);here<-dirname(normalizePath(script,mustWork=TRUE));datadir<-if(length(argv)>=2L)argv[2]else file.path(here,'..','metr20-sources')\r\nunits<-c(country='log teen-employment points',person='recorded real earnings',company='FTE employees');clocks<-c(country='calendar year',person='calendar year',company='survey-wave index');steps<-c(country=1,person=3,company=1);files<-c(country='actual2500-county-mpdta-all6-fields.csv',person='actual38408-NSW-all15-fields.csv',company='actual410-NJPA-all46-fields.csv')\r\nnum<-function(s)ifelse(s=='.',NA_real_,as.numeric(s));mean0<-function(v)if(length(v))mean(v)else NA_real_;var0<-function(v)if(length(v)>1L)sum((v-mean(v))^2)/(length(v)-1L)else NA_real_\r\n\r\nSPEC<-list(id=\"sensitivity-zero-observed\",api=\"sensitivity\",title=list(ko=\"관측된 사전 차이 0과 미래 가정\",en=\"Zero observed precontrasts and a future assumption\"),input=list(estimate=\"2\",preDifferences=list(\"0\",\"0\"),M=\"3\",horizon=2),expectedReject=FALSE)\r\npanel<-function(rows){G<-list();for(r in rows){key<-r$entity;u<-G[[key]];if(is.null(u))u<-list(g=r$g,rows=list());stopifnot(identical(u$g,r$g),is.null(u$rows[[as.character(r$time)]]));u$rows[[as.character(r$time)]]<-r;G[[key]]<-u};G}\r\ncell<-function(G,g,t,step,control){b<-g-step;members<-list();T<-C<-list();for(key in names(G)){u<-G[[key]];target<-!is.na(u$g)&&u$g==g;comp<-is.na(u$g)||(control=='notyet'&&!is.na(u$g)&&u$g>max(t,b));role<-if(target)'treated'else if(comp)'control'else'excluded-comparison';before<-u$rows[[as.character(b)]];after<-u$rows[[as.character(t)]];yb<-if(is.null(before))NA_real_ else before$y;ya<-if(is.null(after))NA_real_ else after$y;eligible<-role!='excluded-comparison'&&!is.na(yb)&&!is.na(ya);reason<-if(role=='excluded-comparison')'target-or-already-exposed-cohort-not-valid-control'else if(is.null(before))'baseline-source-row-absent'else if(is.null(after))'target-time-source-row-absent'else if(is.na(yb))'baseline-outcome-missing'else if(is.na(ya))'target-outcome-missing'else'';m<-list(entity=key,nativeID=u$rows[[1]]$nativeID,g=u$g,role=role,eligible=eligible,baselineSourceId=if(is.null(before))NA_character_ else before$id,targetSourceId=if(is.null(after))NA_character_ else after$id,before=yb,after=ya,change=if(eligible)ya-yb else NA_real_,reason=reason);members[[key]]<-m;if(eligible){if(role=='treated')T[[length(T)+1L]]<-m else C[[length(C)+1L]]<-m}}\r\n change<-function(a)vapply(a,function(r)r$change,0);d<-mean0(change(T));e<-mean0(change(C));estimate<-if(is.na(d)||is.na(e))NA_real_ else d-e;defined<-!is.na(estimate);scores<-setNames(rep(NA_real_,length(members)),names(members));for(key in names(members)){m<-members[[key]];s<-if(!defined)NA_real_ else if(!m$eligible)0 else if(m$role=='treated')(m$change-d)/length(T)else-(m$change-e)/length(C);m$score<-s;scores[key]<-s;members[[key]]<-m};st<-var0(change(T));sc<-var0(change(C));v<-if(is.na(st)||is.na(sc))NA_real_ else st/length(T)+sc/length(C);level<-function(a,k)mean0(vapply(a,function(r)r[[k]],0))\r\n list(g=g,t=t,baseline=b,event=(t-g)/step,phase=if(t==b)'mechanical-reference'else if(t>=g)'post'else'pre-placebo',defined=defined,estimate=estimate,T=T,C=C,members=members,scores=scores,HC0=if(defined)sum(scores^2)else NA_real_,unbiased=v,treatedMeanBefore=level(T,'before'),treatedMeanAfter=level(T,'after'),treatedMeanChange=d,controlMeanBefore=level(C,'before'),controlMeanAfter=level(C,'after'),controlMeanChange=e)\r\n}\r\ncovariance<-function(cells){n<-length(cells);V<-matrix(NA_real_,n,n);for(i in seq_len(n))for(j in seq_len(n))if(cells[[i]]$defined&&cells[[j]]$defined)V[i,j]<-sum(cells[[i]]$scores*cells[[j]]$scores);V}\r\naggregate_cells<-function(post,V,step){out<-list();push<-function(typ,key,ii,w){est<-if(!length(ii)||any(vapply(post[ii],function(z)is.na(z$estimate),TRUE)))NA_real_ else sum(w*vapply(post[ii],function(z)z$estimate,0));vv<-if(is.na(est)||anyNA(V[ii,ii,drop=FALSE]))NA_real_ else as.numeric(t(w)%*%V[ii,ii,drop=FALSE]%*%w);out[[length(out)+1L]]<<-list(type=typ,key=as.character(key),ii=ii,w=w,estimate=est,variance=vv)};positive<-which(vapply(post,function(c)length(c$T)>0L,TRUE));mass<-sum(vapply(post[positive],function(c)length(c$T),0));push('simple','overall',positive,if(mass)vapply(post[positive],function(c)length(c$T)/mass,0)else numeric())\r\n for(typ in c('event','calendar','group')){keys<-vapply(post,function(c)if(typ=='event')c$event else if(typ=='calendar')c$t else c$g,0);gg<-sort(unique(keys));cohortmass<-if(typ=='group')sum(vapply(gg,function(k)length(post[[which(keys==k)[1]]]$T),0))else 0;allii<-integer();allw<-numeric();for(key in gg){ii<-which(keys==key);jj<-ii[vapply(post[ii],function(c)length(c$T)>0L,TRUE)];if(typ=='group'){stopifnot(length(unique(vapply(post[ii],function(c)length(c$T),0)))<=1L);w<-if(length(jj))rep(1/length(jj),length(jj))else numeric();if(cohortmass){allii<-c(allii,jj);allw<-c(allw,w*length(post[[ii[1]]]$T)/cohortmass)}}else{total<-sum(vapply(post[jj],function(c)length(c$T),0));w<-if(total)vapply(post[jj],function(c)length(c$T)/total,0)else numeric()};push(typ,key,jj,w)};if(typ=='group')push(typ,'overall',allii,allw)};out}\r\ntwfe<-function(G,times){ledger<-list();good<-list();for(key in names(G)){u<-G[[key]];absent<-times[!as.character(times)%in%names(u$rows)];missing<-times[vapply(times,function(t){r<-u$rows[[as.character(t)]];!is.null(r)&&is.na(r$y)},TRUE)];eligible<-length(times)>0L&&!length(absent)&&!length(missing);ledger[[length(ledger)+1L]]<-list(entity=key,g=u$g,nativeID=u$rows[[1]]$nativeID,eligible=eligible,absentTimes=paste(absent,collapse=','),missingOutcomeTimes=paste(missing,collapse=','),originalRows=length(u$rows));if(eligible)good[[key]]<-u};rows<-list();for(key in names(good))for(t in times){r<-good[[key]]$rows[[as.character(t)]];r$D<-as.integer(!is.na(r$g)&&t>=r$g);rows[[length(rows)+1L]]<-r};em<-lapply(good,function(u)list(D=mean(vapply(times,function(t)as.integer(!is.na(u$g)&&t>=u$g),0)),Y=mean(vapply(u$rows[as.character(times)],function(r)r$y,0))));tm<-lapply(times,function(t)list(D=mean(vapply(good,function(u)as.integer(!is.na(u$g)&&t>=u$g),0)),Y=mean(vapply(good,function(u)u$rows[[as.character(t)]]$y,0))));names(tm)<-as.character(times);gd<-mean0(vapply(rows,function(r)r$D,0));gy<-mean0(vapply(rows,function(r)r$y,0));num<-den<-0\r\n for(i in seq_along(rows)){r<-rows[[i]];r$residualD<-r$D-em[[r$entity]]$D-tm[[as.character(r$time)]]$D+gd;r$residualY<-r$y-em[[r$entity]]$Y-tm[[as.character(r$time)]]$Y+gy;num<-num+r$residualD*r$residualY;den<-den+r$residualD^2;rows[[i]]<-r};beta<-if(den!=0)num/den else NA_real_;weights<-list();for(i in seq_along(rows)){r<-rows[[i]];r$projectionCoefficient<-if(den!=0)r$residualD/den else NA_real_;r$regressionResidual<-if(!is.na(beta))r$residualY-beta*r$residualD else NA_real_;rows[[i]]<-r;if(r$D==1L){k<-paste(r$g,r$time,sep=':');z<-weights[[k]];if(is.null(z))z<-list(g=r$g,t=r$time,rows=0,coefficient=if(den!=0)0 else NA_real_);z$rows<-z$rows+1L;if(den!=0)z$coefficient<-z$coefficient+r$projectionCoefficient;weights[[k]]<-z}};list(ledger=ledger,rows=rows,num=num,den=den,beta=beta,weights=weights,balancedEntities=length(good))}\r\nadjacent_pre<-function(G,g,t,step,control){b<-t-step;T<-C<-numeric();for(u in G){target<-!is.na(u$g)&&u$g==g;comp<-is.na(u$g)||(control=='notyet'&&!is.na(u$g)&&u$g>max(t,b));if(!target&&!comp)next;before<-u$rows[[as.character(b)]];after<-u$rows[[as.character(t)]];if(!is.null(before)&&!is.null(after)&&!is.na(before$y)&&!is.na(after$y)){if(target)T<-c(T,after$y-before$y)else C<-c(C,after$y-before$y)}};if(!length(T)||!length(C))NA_real_ else mean(T)-mean(C)}\r\n\r\n# Newly authored bounded teaching projections; base R finite approximation.\r\n# Source helper functions are inlined in each public file, never imported.\r\nqnum<-function(v){if(is.null(v)||is.na(v))return(NA_real_);s<-strsplit(as.character(v),'/',fixed=TRUE)[[1]];if(length(s)==1L)as.numeric(s)else as.numeric(s[1])/as.numeric(s[2])}\r\npaired<-function(T,C){\r\n stats<-function(rr){use<-Filter(function(r)!is.na(qnum(r$before))&&!is.na(qnum(r$after)),rr);a<-vapply(use,function(r)qnum(r$before),0);b<-vapply(use,function(r)qnum(r$after),0);list(sourcePairs=length(rr),eligiblePairs=length(use),excludedPairs=length(rr)-length(use),meanBefore=mean0(a),meanAfter=mean0(b),meanChange=mean0(b-a),sampleChangeVariance=var0(b-a))}\r\n st<-stats(T);sc<-stats(C);defined<-st$eligiblePairs>0L&&sc$eligiblePairs>0L;estimate<-if(defined)st$meanChange-sc$meanChange else NA_real_;rr<-list()\r\n for(role in c('treated','control')){input<-if(role=='treated')T else C;s<-if(role=='treated')st else sc;for(r in input){before<-qnum(r$before);after<-qnum(r$after);eligible<-!is.na(before)&&!is.na(after);change<-if(eligible)after-before else NA_real_;score<-if(!defined)NA_real_ else if(!eligible)0 else (change-s$meanChange)/(if(role=='treated')s$eligiblePairs else -s$eligiblePairs);rr[[length(rr)+1L]]<-list(id=r$id,role=role,before=before,after=after,eligible=eligible,change=change,score=score)}}\r\n list(defined=defined,estimate=estimate,treated=st,control=sc,unbiasedVariance=if(defined&&st$eligiblePairs>=2L&&sc$eligiblePairs>=2L)st$sampleChangeVariance/st$eligiblePairs+sc$sampleChangeVariance/sc$eligiblePairs else NA_real_,HC0=if(defined)sum(vapply(rr,function(r)r$score^2,0))else NA_real_,rows=rr)\r\n}\r\nliteral_panel<-function(rr)lapply(seq_along(rr),function(i){r<-rr[[i]];r$y<-qnum(r$y);r$nativeID<-r$entity;r$sourceRow<-i;r})\r\natt_projection<-function(rows,control='never',step=1){G<-panel(rows);times<-sort(unique(vapply(rows,function(r)r$time,0)));cohorts<-sort(unique(na.omit(vapply(rows,function(r)r$g,0))));cells<-list();for(g in cohorts)for(t in times)cells[[length(cells)+1L]]<-cell(G,g,t,step,control);list(sourceRows=length(rows),sourceEntities=length(G),step=step,control=control,cells=cells,covariance=covariance(cells))}\r\nlinear_aggregate<-function(a){\r\n rr<-lapply(a$cells,function(r){r$estimate<-qnum(r$estimate);r$weight<-qnum(r$weight);r});V<-if(is.null(a$covariance))NULL else do.call(rbind,lapply(a$covariance,function(r)vapply(r,qnum,0)));rank<-NA_real_\r\n if(!is.null(V)){stopifnot(nrow(V)==length(rr),ncol(V)==length(rr),all(V==t(V)));ev<-eigen(V,symmetric=TRUE,only.values=TRUE)$values;if(any(ev< -1e-12))stop('covariance-must-be-positive-semidefinite');rank<-sum(ev>1e-12)}\r\n selected<-which(vapply(rr,function(r)r$time>=r$cohort&&r$weight>0,TRUE));w<-numeric(length(rr));type<-if(is.null(a$type))'simple'else a$type\r\n if(type=='simple'){mass<-sum(vapply(rr[selected],function(r)r$weight,0));if(mass>0)for(i in selected)w[i]<-rr[[i]]$weight/mass}else{g<-vapply(rr,function(r)r$cohort,0);gg<-sort(unique(g[selected]));mass<-sum(vapply(gg,function(gi)rr[[intersect(which(g==gi),selected)[1]]]$weight,0));for(gi in gg){ii<-intersect(which(g==gi),selected);stopifnot(length(unique(vapply(rr[ii],function(r)r$weight,0)))==1L);w[ii]<-rr[[ii[1]]]$weight/mass/length(ii)}}\r\n used<-which(w>0);estimate<-if(!length(used)||any(vapply(rr[used],function(r)is.na(r$estimate),TRUE)))NA_real_ else sum(w[used]*vapply(rr[used],function(r)r$estimate,0));variance<-if(is.na(estimate)||is.null(V))NA_real_ else as.numeric(t(w)%*%V%*%w);weights<-lapply(used,function(i)list(sourceIndex=i-1L,cohort=rr[[i]]$cohort,time=rr[[i]]$time,coefficient=w[i],estimate=rr[[i]]$estimate,contribution=w[i]*rr[[i]]$estimate))\r\n list(type=type,defined=!is.na(estimate),estimate=estimate,variance=variance,covarianceRank=rank,weights=weights,cells=rr,covariance=V)\r\n}\r\nsensitivity_fixed<-function(a){estimate<-qnum(a$estimate);M<-qnum(a$M);h<-if(is.null(a$horizon))1 else a$horizon;stopifnot(M>=0,h>=1);pre<-vapply(a$preDifferences,qnum,0);scale<-if(!is.null(a$scale))qnum(a$scale)else if(length(pre))max(abs(pre))else NA_real_;budget<-M*scale*h;list(defined=!is.na(scale),estimate=estimate,scale=scale,M=M,horizon=h,biasBudget=budget,lower=estimate-budget,upper=estimate+budget,preDifferences=as.list(pre),confidenceLevel=NULL)}\r\nrealdata_fixed<-function(kind){rows<-models[[kind]];G<-panel(rows);times<-sort(unique(vapply(rows,function(r)r$time,0)));step<-unname(steps[kind]);aa<-att_projection(rows,'never',step);post<-Filter(function(r)r$phase=='post',aa$cells);aggs<-aggregate_cells(post,covariance(post),step);tf<-twfe(G,times);list(kind=kind,unit=unname(units[kind]),periodUnit=unname(clocks[kind]),nativeRows=nrow(raw[[kind]]),modelRows=length(rows),entities=length(G),sourceRows=rows,att=aa,aggregations=aggs,twfe=tf,scope='Complete native/model/paired/balanced source frames; never control,universal base,no anticipation;not causal/sampling certification.')}\r\n# JSON encoder deliberately handles matrices and scalar/vector distinctions.\r\nencode<-function(x){\r\n if(is.null(x))return('null')\r\n quote<-function(s){s<-gsub('\\\\','\\\\\\\\',as.character(s),fixed=TRUE);s<-gsub('\"','\\\\\"',s,fixed=TRUE);s<-gsub('\\n','\\\\n',s,fixed=TRUE);s<-gsub('\\r','\\\\r',s,fixed=TRUE);s<-gsub('\\t','\\\\t',s,fixed=TRUE);paste0('\"',s,'\"')}\r\n if(is.matrix(x))return(paste0('[',paste(vapply(seq_len(nrow(x)),function(i)encode(as.list(unname(x[i,]))),''),collapse=','),']'))\r\n if(is.list(x)){if(length(x)&&!is.null(names(x)))return(paste0('{',paste(paste0(vapply(names(x),quote,''),':',vapply(x,encode,'')),collapse=','),'}'));return(paste0('[',paste(vapply(x,encode,''),collapse=','),']'))}\r\n if(length(x)!=1L)return(encode(as.list(unname(x))))\r\n if(is.na(x))return('null');if(is.logical(x))return(if(x)'true'else'false');if(is.numeric(x))return(sprintf('%.17g',unname(x)));quote(x)\r\n}\r\nv9<-function(x){if(is.null(x)||is.na(x))return('undefined');if(is.logical(x))return(if(x)'1'else'0');if(is.numeric(x))return(sprintf('%.9g',unname(x)));as.character(x)}\r\nrun_fixed<-function(spec,out){api<-spec$api;a<-spec$input;summary<-list();points<-list();emit<-function(series,x,y){points[[length(points)+1L]]<<-list(series=series,x=x,y=y,numericY=y)}\r\n if(api=='twobytwo'){result<-paired(a$treated,a$control);summary<-list(defined=result$defined,estimate=result$estimate,treatedPairs=result$treated$eligiblePairs,controlPairs=result$control$eligiblePairs,unbiasedVariance=result$unbiasedVariance,HC0=result$HC0);for(i in seq_along(result$rows)){r<-result$rows[[i]];emit(paste(r$role,r$id,sep=':'),i,r$change)}}\r\n else if(api=='att'){result<-att_projection(literal_panel(a$rows),a$control);summary<-list(sourceRows=result$sourceRows,entities=result$sourceEntities,cells=length(result$cells),supportedCells=sum(vapply(result$cells,function(r)r$defined,TRUE)),postCells=sum(vapply(result$cells,function(r)r$phase=='post',TRUE)));for(i in seq_along(result$cells)){r<-result$cells[[i]];emit(paste0('g',r$g,':t',r$t),i,r$estimate)}}\r\n else if(api=='aggregate'){result<-linear_aggregate(a);summary<-list(defined=result$defined,estimate=result$estimate,variance=result$variance,covarianceRank=result$covarianceRank,sumWeights=sum(vapply(result$weights,function(r)r$coefficient,0)));for(i in seq_along(result$weights)){r<-result$weights[[i]];emit(paste0('g',r$cohort,':t',r$time),i,r$contribution)}}\r\n else if(api=='twfe'){rows<-literal_panel(a$rows);G<-panel(rows);result<-twfe(G,sort(unique(vapply(rows,function(r)r$time,0))));summary<-list(defined=!is.na(result$beta),beta=result$beta,numerator=result$num,denominator=result$den,balancedEntities=result$balancedEntities,negativeTreatedCells=sum(vapply(result$weights,function(r)!is.na(r$coefficient)&&r$coefficient<0,TRUE)));if(length(result$weights)){ord<-order(vapply(result$weights,function(r)r$g,0),vapply(result$weights,function(r)r$t,0));for(i in seq_along(ord)){r<-result$weights[[ord[i]]];emit(paste0('g',r$g,':t',r$t),i,r$coefficient)}}}\r\n else if(api=='sensitivity'){result<-sensitivity_fixed(a);summary<-result[c('defined','estimate','scale','M','horizon','biasBudget','lower','upper')];for(i in seq_along(c('lower','estimate','upper'))){k<-c('lower','estimate','upper')[i];emit(k,i,if(result$defined)result[[k]]else NA_real_)}}\r\n else{result<-realdata_fixed(a$kind);post<-Filter(function(r)r$phase=='post',result$att$cells);simple<-Filter(function(r)r$type=='simple',result$aggregations)[[1]];group<-Filter(function(r)r$type=='group'&&r$key=='overall',result$aggregations)[[1]];summary<-list(nativeRows=result$nativeRows,modelRows=result$modelRows,entities=result$entities,postCells=length(post),simple=simple$estimate,group=group$estimate,TWFE=result$twfe$beta,balancedEntities=result$twfe$balancedEntities);for(i in seq_along(post)){r<-post[[i]];emit(paste0('g',r$g,':t',r$t),i,r$estimate)}}\r\n dir.create(out,recursive=TRUE,showWarnings=FALSE);if(length(list.files(out,all.files=TRUE,no..=TRUE)))stop('use-new-empty-output-directory');shown<-lapply(summary,v9);write.csv(data.frame(name=names(shown),value=unlist(shown,use.names=FALSE)),file.path(out,'summary.csv'),row.names=FALSE,na='');pointframe<-if(length(points))do.call(rbind,lapply(points,function(p)data.frame(series=p$series,x=p$x,y=p$y,numericY=p$numericY,stringsAsFactors=FALSE)))else data.frame(series=character(),x=numeric(),y=numeric(),numericY=numeric());write.csv(pointframe,file.path(out,'points.csv'),row.names=FALSE,na='');full<-list(chapter='METR-20',profile=spec$id,api=api,input=spec$input,summary=shown,points=points,details=result,arithmetic='Base R approximate finite values;bounded teaching projection,not exact fractions or causal/sampling certification.');writeLines(encode(full),file.path(out,'full.json'),useBytes=TRUE)\r\n svg(file.path(out,'plot.svg'),width=9,height=5.6,pointsize=12);par(mar=c(4.5,5.5,4,1));good<-pointframe[!is.na(pointframe$numericY),,drop=FALSE]\r\n if(nrow(good)){plot(good$x,good$numericY,pch=19,col='#315d7c',xlab='Declared cell/unit/bound ordinal',ylab=if(api=='twfe')'Cell weight'else if(!is.null(result$unit))result$unit else 'Stated outcome/bias units',main=spec$title$en);abline(h=0,col='#9eabb2');grid(nx=NA,ny=NULL,col='#e2e5e7');points(good$x,good$numericY,pch=19,col='#315d7c')}else{plot.new();text(.5,.5,'Undefined: no supported plotted quantity');title(main=spec$title$en)};dev.off();cat(encode(shown),'\\n')\r\n}\r\n\r\nrun_fixed(SPEC,outdir)\r\n",
      "arithmetic": "Base R approximate finite arithmetic;not an exact rational result",
      "summary": {
        "defined": "1",
        "estimate": "2",
        "scale": "0",
        "M": "3",
        "horizon": "2",
        "biasBudget": "0",
        "lower": "2",
        "upper": "2"
      },
      "fullResultEmbedded": false,
      "plotEmbedded": false,
      "full": {
        "summary": {
          "defined": "1",
          "estimate": "2",
          "scale": "0",
          "M": "3",
          "horizon": "2",
          "biasBudget": "0",
          "lower": "2",
          "upper": "2"
        },
        "notice": "Complete source/finite projection is retained in the linked external JSON; this short projection is not the full result."
      },
      "plot": null,
      "points": [
        {
          "series": "lower",
          "x": 1,
          "y": 2,
          "numericY": 2
        },
        {
          "series": "estimate",
          "x": 2,
          "y": 2,
          "numericY": 2
        },
        {
          "series": "upper",
          "x": 3,
          "y": 2,
          "numericY": 2
        }
      ],
      "summaryFile": "metr20-programs/sensitivity-zero-observed-r-summary.csv",
      "summarySHA256": "71c2e23027676347c8bf93c6ad4a7d40f417e3d4f9f568b941afbfe4f6eddba5",
      "pointsFile": "metr20-programs/sensitivity-zero-observed-r-points.csv",
      "pointsSHA256": "b3ff734acaa57cc671297679f61d7ba8ab8c2fb026bbe490ff3d85c3873adda4",
      "fullResultFile": "metr20-programs/sensitivity-zero-observed-r.json",
      "fullResultSHA256": "ec1635255dd1c17612ae103a138347d3744b318b38126ecfb008bbf12497a93a",
      "plotFile": "metr20-programs/sensitivity-zero-observed-r.svg",
      "plotSHA256": "87752ec72f19aec261042c154d35b68ca6d7770c0e61857c704e6e3f6684590b"
    },
    {
      "api": "realdata",
      "variant": "realdata-country",
      "profile": "realdata-country",
      "language": "Python",
      "file": "metr20-programs/realdata-country-python.py",
      "codeSHA256": "f20de6e1dccc2f3ccc067505763409d7d04352264ff4a2876eb880b7782a1470",
      "returnCode": 0,
      "expectedRejection": false,
      "title": {
        "ko": "실제 미국 500개 카운티",
        "en": "Actual five-hundred-county US panel"
      },
      "code": "\"\"\"METR20 actual sources. Python standard library, exact stored-value rationals.\r\nRead ONLY the three native-observation CSVs; no JS engine,model JSON,derived\r\nanswers,private modules or internet needed. Outcome measurement/identification\r\nand valid sampling inference remain separate from exact finite arithmetic.\r\nRun: python metr20-reproduce.py --data-dir PATH --out NEW_EMPTY_DIRECTORY\r\n\"\"\"\r\nfrom pathlib import Path\r\nfrom fractions import Fraction as Q\r\nfrom collections import defaultdict,Counter\r\nimport csv,json,math,argparse,hashlib\r\n\r\nUNIT={'country':'log teen-employment points','person':'recorded real earnings','company':'FTE employees'}\r\nCLOCK={'country':'calendar year','person':'calendar year','company':'survey-wave index'}\r\nSTEP={'country':1,'person':3,'company':1}\r\nFILES={'country':'actual2500-county-mpdta-all6-fields.csv','person':'actual38408-NSW-all15-fields.csv','company':'actual410-NJPA-all46-fields.csv'}\r\ndef avg(v):return sum(v,Q(0))/len(v)if v else None\r\ndef samplevar(v):return sum(((x-avg(v))**2 for x in v),Q(0))/(len(v)-1)if len(v)>1 else None\r\ndef binary(s):return None if s=='.'else Q.from_float(float(s))\r\ndef token(v):\r\n if v is None:return ''\r\n if isinstance(v,bool):return 'true'if v else'false'\r\n return str(v)\r\ndef safe_float(v):\r\n if v is None:return None\r\n try:r=float(v)\r\n except OverflowError:return None\r\n return r if math.isfinite(r)else None\r\ndef read(p):\r\n with p.open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))\r\ndef write(p,rows,head=None):\r\n if head is None:\r\n  assert rows;head=list(rows[0])\r\n with p.open('w',encoding='utf8',newline='')as f:\r\n  w=csv.DictWriter(f,fieldnames=head);w.writeheader();w.writerows({k:token(r.get(k))for k in head}for r in rows)\r\ndef source(data):\r\n raw={k:read(data/n)for k,n in FILES.items()};assert[len(raw[k])for k in FILES]==[2500,38408,410]\r\n models={k:[]for k in FILES}\r\n for r in raw['country']:\r\n  g0=int(r['first.treat']);g=None if g0==0 else g0;assert int(r['treat'])==int(g is not None)\r\n  models['country'].append(dict(id='mpdta:'+r['sourceRow'],entity='county:'+str(int(r['countyreal'])),time=int(r['year']),y=binary(r['lemp']),g=g,sourceRow=int(r['sourceRow']),nativeID=r['countyreal']))\r\n for r in raw['person']:\r\n  selected=int(r['experimental'])==1;assert selected==(int(r['sample'])==1);assert(r['treated']!='.')==selected\r\n  if selected:\r\n   d=int(r['treated']);assert d in[0,1]\r\n   models['person'].append(dict(id='nsw:'+r['sourceRow'],entity='nsw-id:'+str(int(r['id'])),time=int(r['year']),y=binary(r['re']),g=1978 if d else None,sourceRow=int(r['sourceRow']),nativeID=str(int(r['id']))))\r\n for r in raw['company']:\r\n  state=int(r['STATE']);assert state in[0,1]\r\n  for t,suffix in[(0,''),(1,'2')]:\r\n   a=[r[n+suffix]for n in['EMPFT','NMGRS','EMPPT']];y=None if'.'in a else Q(a[0])+Q(a[1])+Q(a[2])/2\r\n   models['company'].append(dict(id='njpa:'+r['sourceRow']+':wave'+str(t),entity='njpa-row:'+r['sourceRow'],time=t,y=y,g=1 if state else None,sourceRow=int(r['sourceRow']),nativeID=r['SHEET']))\r\n assert[len(models[k])for k in FILES]==[2500,1444,820]\r\n return models,raw\r\ndef panel(rows):\r\n groups={}\r\n for r in rows:\r\n  u=groups.setdefault(r['entity'],{'g':r['g'],'rows':{}});assert u['g']==r['g']and r['time']not in u['rows'];u['rows'][r['time']]=r\r\n return groups\r\ndef cell(groups,g,t,step,control):\r\n b=g-step;members=[];T=[];C=[]\r\n for key,u in groups.items():\r\n  role='treated'if u['g']==g else'control'if u['g']is None or(control=='notyet'and u['g']>max(t,b))else'excluded-comparison'\r\n  before=u['rows'].get(b);after=u['rows'].get(t);yb=None if before is None else before['y'];ya=None if after is None else after['y'];eligible=role!='excluded-comparison'and yb is not None and ya is not None\r\n  reason='target-or-already-exposed-cohort-not-valid-control'if role=='excluded-comparison'else'baseline-source-row-absent'if before is None else'target-time-source-row-absent'if after is None else'baseline-outcome-missing'if yb is None else'target-outcome-missing'if ya is None else''\r\n  m={'entity':key,'nativeID':next(iter(u['rows'].values()))['nativeID'],'g':u['g'],'role':role,'eligible':eligible,'baselineSourceId':None if before is None else before['id'],'targetSourceId':None if after is None else after['id'],'before':yb,'after':ya,'change':ya-yb if eligible else None,'reason':reason};members.append(m)\r\n  if eligible:(T if role=='treated'else C).append(m)\r\n d=avg([r['change']for r in T]);e=avg([r['change']for r in C]);estimate=None if d is None or e is None else d-e;defined=estimate is not None;scores={}\r\n for m in members:\r\n  s=None if not defined else Q(0)\r\n  if defined and m['eligible']:s=(m['change']-(d if m['role']=='treated'else e))/(len(T)if m['role']=='treated'else-len(C))\r\n  m['score']=s;scores[m['entity']]=s\r\n st=samplevar([r['change']for r in T]);sc=samplevar([r['change']for r in C]);v=None if st is None or sc is None else st/len(T)+sc/len(C)\r\n return {'g':g,'t':t,'baseline':b,'event':(t-g)//step,'phase':'mechanical-reference'if t==b else'post'if t>=g else'pre-placebo','defined':defined,'estimate':estimate,'T':T,'C':C,'members':members,'scores':scores,'HC0':None if not defined else sum((s*s for s in scores.values()),Q(0)),'unbiased':v,'treatedMeanBefore':avg([r['before']for r in T]),'treatedMeanAfter':avg([r['after']for r in T]),'treatedMeanChange':d,'controlMeanBefore':avg([r['before']for r in C]),'controlMeanAfter':avg([r['after']for r in C]),'controlMeanChange':e}\r\ndef covariance(cells):\r\n return[[None if not a['defined']or not b['defined']else sum((v*b['scores'][i]for i,v in a['scores'].items()),Q(0))for b in cells]for a in cells]\r\ndef aggregate(post,V,step):\r\n out=[]\r\n def push(typ,key,coeff):\r\n  estimate=None if not coeff or any(post[i]['estimate']is None for i in coeff)else sum((w*post[i]['estimate']for i,w in coeff.items()),Q(0));variance=None if estimate is None or any(V[i][j]is None for i in coeff for j in coeff)else sum((a*b*V[i][j]for i,a in coeff.items()for j,b in coeff.items()),Q(0));out.append({'type':typ,'key':key,'coeff':coeff,'estimate':estimate,'variance':variance})\r\n positive=[i for i,c in enumerate(post)if len(c['T'])>0];mass=sum(len(post[i]['T'])for i in positive)\r\n push('simple','overall',{i:Q(len(post[i]['T']),mass)for i in positive}if mass else{})\r\n for typ in['event','calendar','group']:\r\n  groups=defaultdict(list)\r\n  for i,c in enumerate(post):groups[c['event']if typ=='event'else c['t']if typ=='calendar'else c['g']].append(i)\r\n  overall={};cohortMass=sum(len(post[ii[0]]['T'])for ii in groups.values())if typ=='group'else 0\r\n  for key,ii in sorted(groups.items()):\r\n   jj=[i for i in ii if len(post[i]['T'])>0]\r\n   if typ=='group':\r\n    assert len({len(post[i]['T'])for i in ii})<=1\r\n    coeff={i:Q(1,len(jj))for i in jj}if jj else{}\r\n    if cohortMass:\r\n     for i,w in coeff.items():overall[i]=w*Q(len(post[ii[0]]['T']),cohortMass)\r\n   else:\r\n    total=sum(len(post[i]['T'])for i in jj);coeff={i:Q(len(post[i]['T']),total)for i in jj}if total else{}\r\n   push(typ,str(key),coeff)\r\n  if typ=='group':push(typ,'overall',overall)\r\n return out\r\ndef twfe(groups,times):\r\n ledger=[];good={}\r\n for key,u in groups.items():\r\n  absent=[t for t in times if t not in u['rows']];missing=[t for t in times if t in u['rows']and u['rows'][t]['y']is None];eligible=bool(times)and not absent and not missing\r\n  ledger.append({'entity':key,'g':u['g'],'nativeID':next(iter(u['rows'].values()))['nativeID'],'eligible':eligible,'absentTimes':','.join(map(str,absent)),'missingOutcomeTimes':','.join(map(str,missing)),'originalRows':len(u['rows'])})\r\n  if eligible:good[key]=u\r\n rows=[dict(**u['rows'][t],D=Q(u['g']is not None and t>=u['g']))for key,u in good.items()for t in times]\r\n em={k:{'D':avg([Q(u['g']is not None and t>=u['g'])for t in times]),'Y':avg([u['rows'][t]['y']for t in times])}for k,u in good.items()};tm={t:{'D':avg([Q(u['g']is not None and t>=u['g'])for u in good.values()]),'Y':avg([u['rows'][t]['y']for u in good.values()])}for t in times};gd=avg([r['D']for r in rows]);gy=avg([r['y']for r in rows]);num=den=Q(0)\r\n for r in rows:\r\n  r['residualD']=r['D']-em[r['entity']]['D']-tm[r['time']]['D']+gd;r['residualY']=r['y']-em[r['entity']]['Y']-tm[r['time']]['Y']+gy;num+=r['residualD']*r['residualY'];den+=r['residualD']**2\r\n beta=num/den if den else None;weights={}\r\n for r in rows:\r\n  r['projectionCoefficient']=r['residualD']/den if den else None;r['regressionResidual']=r['residualY']-beta*r['residualD']if beta is not None else None\r\n  if r['D']:\r\n   k=(r['g'],r['time']);z=weights.setdefault(k,{'rows':0,'coefficient':Q(0)if den else None});z['rows']+=1\r\n   if den:z['coefficient']+=r['projectionCoefficient']\r\n return {'ledger':ledger,'rows':rows,'num':num,'den':den,'beta':beta,'weights':weights,'balancedEntities':len(good)}\r\ndef adjacent_pre(groups,g,t,step,control):\r\n b=t-step;T=[];C=[]\r\n for u in groups.values():\r\n  if u['g']==g:target=T\r\n  elif u['g']is None or(control=='notyet'and u['g']>max(t,b)):target=C\r\n  else:continue\r\n  before=u['rows'].get(b);after=u['rows'].get(t)\r\n  if before is not None and after is not None and before['y']is not None and after['y']is not None:target.append(after['y']-before['y'])\r\n return None if not T or not C else avg(T)-avg(C)\r\n\r\n\"\"\"New bounded teaching projections. The program is self-contained after build.\r\nExact Fraction finite algebra; figures and9-digit summary are approximations.\r\nIt is not a general parser/API replacement or a causal/inference certificate.\r\n\"\"\"\r\ndef paired(treated,control):\r\n def stats(rr):\r\n  use=[r for r in rr if r['before']is not None and r['after']is not None];delta=[Q(r['after'])-Q(r['before'])for r in use]\r\n  return dict(sourcePairs=len(rr),eligiblePairs=len(use),excludedPairs=len(rr)-len(use),meanBefore=avg([Q(r['before'])for r in use]),meanAfter=avg([Q(r['after'])for r in use]),meanChange=avg(delta),sampleChangeVariance=samplevar(delta))\r\n T,C=stats(treated),stats(control);defined=T['eligiblePairs']>0 and C['eligiblePairs']>0;estimate=T['meanChange']-C['meanChange']if defined else None;records=[]\r\n for group,rr,s in [('treated',treated,T),('control',control,C)]:\r\n  for r in rr:\r\n   before=None if r['before']is None else Q(r['before']);after=None if r['after']is None else Q(r['after']);eligible=before is not None and after is not None;delta=after-before if eligible else None;score=None if not defined else Q(0)if not eligible else(delta-s['meanChange'])/(s['eligiblePairs']if group=='treated'else-s['eligiblePairs']);records.append(dict(id=r['id'],role=group,before=before,after=after,eligible=eligible,change=delta,score=score))\r\n unbiased=None if not defined or T['eligiblePairs']<2 or C['eligiblePairs']<2 else T['sampleChangeVariance']/T['eligiblePairs']+C['sampleChangeVariance']/C['eligiblePairs'];hc0=None if not defined else sum((r['score']**2 for r in records),Q(0))\r\n return dict(defined=defined,estimate=estimate,treated=T,control=C,unbiasedVariance=unbiased,HC0=hc0,rows=records)\r\ndef literal_panel(raw):\r\n return[dict(r,y=None if r['y']is None else Q(r['y']),nativeID=r['entity'],sourceRow=i+1)for i,r in enumerate(raw)]\r\ndef att_projection(rows,control='never',step=1):\r\n G=panel(rows);times=sorted({r['time']for r in rows});cohorts=sorted({r['g']for r in rows if r['g']is not None});cells=[cell(G,g,t,step,control)for g in cohorts for t in times]\r\n return dict(sourceRows=len(rows),sourceEntities=len(G),step=step,control=control,cells=cells,covariance=covariance(cells))\r\ndef psd(V):\r\n A=[r[:]for r in V];rank=0\r\n while A:\r\n  if any(A[i][i]<0 for i in range(len(A))):raise ValueError('covariance-must-be-positive-semidefinite')\r\n  p=next((i for i in range(len(A))if A[i][i]>0),None)\r\n  if p is None:\r\n   if any(v for r in A for v in r):raise ValueError('covariance-must-be-positive-semidefinite')\r\n   return rank\r\n  A[0],A[p]=A[p],A[0]\r\n  for r in A:r[0],r[p]=r[p],r[0]\r\n  d=A[0][0];A=[[A[i][j]-A[i][0]*A[0][j]/d for j in range(1,len(A))]for i in range(1,len(A))];rank+=1\r\n return rank\r\ndef linear_aggregate(a):\r\n rr=[dict(r,estimate=None if r['estimate']is None else Q(r['estimate']),weight=Q(r['weight']))for r in a['cells']];V=[[Q(v)for v in r]for r in a['covariance']]if 'covariance'in a else None\r\n if V is not None:\r\n  assert len(V)==len(rr)and all(len(z)==len(rr)for z in V);assert all(V[i][j]==V[j][i]for i in range(len(rr))for j in range(len(rr)));rank=psd(V)\r\n else:rank=None\r\n selected=[i for i,r in enumerate(rr)if r['time']>=r['cohort']and r['weight']>0];weights={}\r\n if a.get('type','simple')=='simple':\r\n  mass=sum((rr[i]['weight']for i in selected),Q(0));weights={i:rr[i]['weight']/mass for i in selected}if mass else{}\r\n else:\r\n  gg=defaultdict(list)\r\n  for i in selected:gg[rr[i]['cohort']].append(i)\r\n  assert all(len({rr[i]['weight']for i in ii})==1 for ii in gg.values());mass=sum((rr[ii[0]]['weight']for ii in gg.values()),Q(0));weights={i:rr[ii[0]]['weight']/mass/len(ii)for ii in gg.values()for i in ii}if mass else{}\r\n estimate=None if not weights or any(rr[i]['estimate']is None for i in weights)else sum((w*rr[i]['estimate']for i,w in weights.items()),Q(0));variance=None if estimate is None or V is None else sum((x*y*V[i][j]for i,x in weights.items()for j,y in weights.items()),Q(0))\r\n return dict(type=a.get('type','simple'),defined=estimate is not None,estimate=estimate,variance=variance,covarianceRank=rank,weights=[dict(sourceIndex=i,cohort=rr[i]['cohort'],time=rr[i]['time'],coefficient=w,estimate=rr[i]['estimate'],contribution=None if rr[i]['estimate']is None else w*rr[i]['estimate'])for i,w in weights.items()],cells=rr,covariance=V)\r\ndef sensitivity_fixed(a):\r\n estimate=Q(a['estimate']);M=Q(a['M']);h=a.get('horizon',1);assert M>=0 and h>=1\r\n pre=[Q(v)for v in a.get('preDifferences',[])];scale=Q(a['scale'])if 'scale'in a else max(map(abs,pre))if pre else None;budget=None if scale is None else M*scale*h\r\n return dict(defined=scale is not None,estimate=estimate,scale=scale,M=M,horizon=h,biasBudget=budget,lower=None if budget is None else estimate-budget,upper=None if budget is None else estimate+budget,preDifferences=pre,confidenceLevel=None)\r\ndef realdata_fixed(kind,data):\r\n models,raw=source(data);rows=models[kind];G=panel(rows);times=sorted({r['time']for r in rows});step=STEP[kind];aa=att_projection(rows,'never',step);post=[r for r in aa['cells']if r['phase']=='post'];aggs=aggregate(post,covariance(post),step);tf=twfe(G,times)\r\n return dict(kind=kind,unit=UNIT[kind],periodUnit=CLOCK[kind],nativeRows=len(raw[kind]),modelRows=len(rows),entities=len(G),sourceRows=rows,att=aa,aggregations=aggs,twfe=tf,scope='Complete source frame; never-treated comparison,universal baseline,no anticipation. Native/model/paired/balanced denominators differ. All sampling/causal assumptions remain separate.')\r\ndef encode(v):\r\n if isinstance(v,Q):return str(v)\r\n if isinstance(v,dict):return{str(k):encode(x)for k,x in v.items()}\r\n if isinstance(v,(list,tuple)):return[encode(x)for x in v]\r\n return v\r\ndef v9(v):\r\n if v is None:return'undefined'\r\n if isinstance(v,str):return v\r\n if isinstance(v,bool):return'1'if v else'0'\r\n return format(float(v),'.9g')\r\ndef run_fixed(spec,out,data):\r\n api=spec['api'];a=spec['input'];summary={};points=[]\r\n def emit(series,x,y):points.append(dict(series=series,x=x,y=y,numericY=safe_float(y)))\r\n if api=='twobytwo':\r\n  result=paired(a['treated'],a['control']);summary=dict(defined=result['defined'],estimate=result['estimate'],treatedPairs=result['treated']['eligiblePairs'],controlPairs=result['control']['eligiblePairs'],unbiasedVariance=result['unbiasedVariance'],HC0=result['HC0'])\r\n  for i,r in enumerate(result['rows']):emit(r['role']+':'+r['id'],i+1,r['change'])\r\n elif api=='att':\r\n  result=att_projection(literal_panel(a['rows']),a.get('control','never'));summary=dict(sourceRows=result['sourceRows'],entities=result['sourceEntities'],cells=len(result['cells']),supportedCells=sum(r['defined']for r in result['cells']),postCells=sum(r['phase']=='post'for r in result['cells']))\r\n  for i,r in enumerate(result['cells']):emit('g'+str(r['g'])+':t'+str(r['t']),i+1,r['estimate'])\r\n elif api=='aggregate':\r\n  result=linear_aggregate(a);summary=dict(defined=result['defined'],estimate=result['estimate'],variance=result['variance'],covarianceRank=result['covarianceRank'],sumWeights=sum((r['coefficient']for r in result['weights']),Q(0)))\r\n  for i,r in enumerate(result['weights']):emit('g'+str(r['cohort'])+':t'+str(r['time']),i+1,r['contribution'])\r\n elif api=='twfe':\r\n  rows=literal_panel(a['rows']);G=panel(rows);result=twfe(G,sorted({r['time']for r in rows}));summary=dict(defined=result['beta']is not None,beta=result['beta'],numerator=result['num'],denominator=result['den'],balancedEntities=result['balancedEntities'],negativeTreatedCells=sum(v['coefficient']is not None and v['coefficient']<0 for v in result['weights'].values()))\r\n  for i,((g,t),r)in enumerate(sorted(result['weights'].items())):emit('g'+str(g)+':t'+str(t),i+1,r['coefficient'])\r\n elif api=='sensitivity':\r\n  result=sensitivity_fixed(a);summary={k:result[k]for k in['defined','estimate','scale','M','horizon','biasBudget','lower','upper']}\r\n  for i,k in enumerate(['lower','estimate','upper']):emit(k,i+1,result[k]if result['defined']else None)\r\n else:\r\n  result=realdata_fixed(a['kind'],data);post=[r for r in result['att']['cells']if r['phase']=='post'];s=next(r for r in result['aggregations']if r['type']=='simple');g=next(r for r in result['aggregations']if r['type']=='group'and r['key']=='overall');summary=dict(nativeRows=result['nativeRows'],modelRows=result['modelRows'],entities=result['entities'],postCells=len(post),simple=s['estimate'],group=g['estimate'],TWFE=result['twfe']['beta'],balancedEntities=result['twfe']['balancedEntities'])\r\n  for i,r in enumerate(post):emit('g'+str(r['g'])+':t'+str(r['t']),i+1,r['estimate'])\r\n out.mkdir(parents=True,exist_ok=True)\r\n if any(out.iterdir()):raise ValueError('use-new-empty-output-directory')\r\n shown={k:v9(v)for k,v in summary.items()};write(out/'summary.csv',[dict(name=k,value=v)for k,v in shown.items()]);write(out/'points.csv',points,['series','x','y','numericY']);full=dict(chapter='METR-20',profile=spec['id'],api=api,input=spec['input'],summary=shown,points=encode(points),details=encode(result),arithmetic='Python Fraction exact finite stored values;summary/plot approximate;bounded teaching projection,not causal or sampling certification')\r\n (out/'full.json').write_text(json.dumps(full,ensure_ascii=False,indent=2,allow_nan=False)+'\\n',encoding='utf8')\r\n import matplotlib\r\n matplotlib.use('Agg')\r\n import matplotlib.pyplot as plt\r\n plt.rcParams.update({'svg.fonttype':'none','font.family':'DejaVu Sans','font.size':12,'axes.spines.top':False,'axes.spines.right':False});fig,ax=plt.subplots(figsize=(9,5.6));good=[r for r in points if r['numericY']is not None]\r\n if good:\r\n  ax.scatter([r['x']for r in good],[r['numericY']for r in good],color='#315d7c',s=32);ax.axhline(0,color='#9eabb2',lw=.8);ax.set_xlabel('Declared cell/unit/bound ordinal')\r\n else:ax.text(.5,.5,'Undefined: no supported plotted quantity',ha='center',va='center',transform=ax.transAxes);ax.set_xticks([]);ax.set_yticks([])\r\n ax.set_ylabel('Cell weight'if api=='twfe'else result.get('unit','Stated outcome/bias units'));ax.set_title(spec['title']['en'],wrap=True,pad=14);ax.grid(axis='y',alpha=.2);fig.tight_layout(pad=2);fig.savefig(out/'plot.svg');plt.close(fig);print(json.dumps(shown))\r\n\r\nSPEC={'id': 'realdata-country', 'api': 'realdata', 'title': {'ko': '실제 미국 500개 카운티', 'en': 'Actual five-hundred-county US panel'}, 'input': {'kind': 'country', 'control': 'never'}, 'expectedReject': False}\r\nif __name__=='__main__':\r\n import sys\r\n run_fixed(SPEC,Path(sys.argv[1]),Path(sys.argv[2])if len(sys.argv)>2 else Path(__file__).resolve().parent.parent/'metr20-sources')\r\n",
      "arithmetic": "Python Fraction exact stored finite values;logs/summary/plots approximate",
      "summary": {
        "nativeRows": "2500",
        "modelRows": "2500",
        "entities": "500",
        "postCells": "7",
        "simple": "-0.0399512752",
        "group": "-0.0310182822",
        "TWFE": "-0.0365489367",
        "balancedEntities": "500"
      },
      "fullResultEmbedded": false,
      "plotEmbedded": false,
      "full": {
        "summary": {
          "nativeRows": "2500",
          "modelRows": "2500",
          "entities": "500",
          "postCells": "7",
          "simple": "-0.0399512752",
          "group": "-0.0310182822",
          "TWFE": "-0.0365489367",
          "balancedEntities": "500"
        },
        "notice": "Complete source/finite projection is retained in the linked external JSON; this short projection is not the full result."
      },
      "plot": null,
      "points": [
        {
          "series": "g2004:t2004",
          "x": 1,
          "y": "-29232892943951567/2783224569714966528",
          "numericY": -0.01050324622096353
        },
        {
          "series": "g2004:t2005",
          "x": 2,
          "y": "-65334487969868723/927741523238322176",
          "numericY": -0.07042315810314909
        },
        {
          "series": "g2004:t2006",
          "x": 3,
          "y": "-1910109472425407903/13916122848574832640",
          "numericY": -0.13725873888940443
        },
        {
          "series": "g2004:t2007",
          "x": 4,
          "y": "-6810210258392143/67553994410557440",
          "numericY": -0.10081136308540525
        },
        {
          "series": "g2006:t2006",
          "x": 5,
          "y": "-15984778699238429/3479030712143708160",
          "numericY": -0.004594606952862722
        },
        {
          "series": "g2006:t2007",
          "x": 6,
          "y": "-573684810404746517/13916122848574832640",
          "numericY": -0.04122447154621794
        },
        {
          "series": "g2007:t2007",
          "x": 7,
          "y": "-1583250194044671831/60767069772110102528",
          "numericY": -0.026054410719197237
        }
      ],
      "summaryFile": "metr20-programs/realdata-country-python-summary.csv",
      "summarySHA256": "46156332b56f04d75b85f723390bf5d1c45f06bc31a0f27910a4677d5d39583b",
      "pointsFile": "metr20-programs/realdata-country-python-points.csv",
      "pointsSHA256": "21b1780bace474d7fa197f4106599c8a39655a89b4a1efc33c2263b3b52d8001",
      "fullResultFile": "metr20-programs/realdata-country-python.json",
      "fullResultSHA256": "5577cda2b8a699ac046f7e1aee583aa974b3f6573bc9bec524bad20e74356ac7",
      "plotFile": "metr20-programs/realdata-country-python.svg",
      "plotSHA256": "a4fcda83bad5cc3e7e59170d7d49584707a179a7682c2d85b40e834cd8e756e7"
    },
    {
      "api": "realdata",
      "variant": "realdata-country",
      "profile": "realdata-country",
      "language": "R",
      "file": "metr20-programs/realdata-country-r.R",
      "codeSHA256": "b7e1ef6c392e7309bfaf1757b9b1e09d5acae4533ee4ad635c7452c67ed9b71a",
      "returnCode": 0,
      "expectedRejection": false,
      "title": {
        "ko": "실제 미국 500개 카운티",
        "en": "Actual five-hundred-county US panel"
      },
      "code": "# METR20 fixed example. Base R only, finite arithmetic approximate.\r\n# No JavaScript engine,model JSON,derived answer table,private module or internet.\r\noptions(stringsAsFactors=FALSE,digits=17)\r\nargv<-commandArgs(trailingOnly=TRUE);if(length(argv)<1L)stop('Supply a new empty output directory')\r\noutdir<-argv[1];script<-sub('^--file=','',commandArgs(FALSE)[grepl('^--file=',commandArgs(FALSE))][1]);here<-dirname(normalizePath(script,mustWork=TRUE));datadir<-if(length(argv)>=2L)argv[2]else file.path(here,'..','metr20-sources')\r\nunits<-c(country='log teen-employment points',person='recorded real earnings',company='FTE employees');clocks<-c(country='calendar year',person='calendar year',company='survey-wave index');steps<-c(country=1,person=3,company=1);files<-c(country='actual2500-county-mpdta-all6-fields.csv',person='actual38408-NSW-all15-fields.csv',company='actual410-NJPA-all46-fields.csv')\r\nnum<-function(s)ifelse(s=='.',NA_real_,as.numeric(s));mean0<-function(v)if(length(v))mean(v)else NA_real_;var0<-function(v)if(length(v)>1L)sum((v-mean(v))^2)/(length(v)-1L)else NA_real_\r\n\r\nSPEC<-list(id=\"realdata-country\",api=\"realdata\",title=list(ko=\"실제 미국 500개 카운티\",en=\"Actual five-hundred-county US panel\"),input=list(kind=\"country\",control=\"never\"),expectedReject=FALSE)\r\npanel<-function(rows){G<-list();for(r in rows){key<-r$entity;u<-G[[key]];if(is.null(u))u<-list(g=r$g,rows=list());stopifnot(identical(u$g,r$g),is.null(u$rows[[as.character(r$time)]]));u$rows[[as.character(r$time)]]<-r;G[[key]]<-u};G}\r\ncell<-function(G,g,t,step,control){b<-g-step;members<-list();T<-C<-list();for(key in names(G)){u<-G[[key]];target<-!is.na(u$g)&&u$g==g;comp<-is.na(u$g)||(control=='notyet'&&!is.na(u$g)&&u$g>max(t,b));role<-if(target)'treated'else if(comp)'control'else'excluded-comparison';before<-u$rows[[as.character(b)]];after<-u$rows[[as.character(t)]];yb<-if(is.null(before))NA_real_ else before$y;ya<-if(is.null(after))NA_real_ else after$y;eligible<-role!='excluded-comparison'&&!is.na(yb)&&!is.na(ya);reason<-if(role=='excluded-comparison')'target-or-already-exposed-cohort-not-valid-control'else if(is.null(before))'baseline-source-row-absent'else if(is.null(after))'target-time-source-row-absent'else if(is.na(yb))'baseline-outcome-missing'else if(is.na(ya))'target-outcome-missing'else'';m<-list(entity=key,nativeID=u$rows[[1]]$nativeID,g=u$g,role=role,eligible=eligible,baselineSourceId=if(is.null(before))NA_character_ else before$id,targetSourceId=if(is.null(after))NA_character_ else after$id,before=yb,after=ya,change=if(eligible)ya-yb else NA_real_,reason=reason);members[[key]]<-m;if(eligible){if(role=='treated')T[[length(T)+1L]]<-m else C[[length(C)+1L]]<-m}}\r\n change<-function(a)vapply(a,function(r)r$change,0);d<-mean0(change(T));e<-mean0(change(C));estimate<-if(is.na(d)||is.na(e))NA_real_ else d-e;defined<-!is.na(estimate);scores<-setNames(rep(NA_real_,length(members)),names(members));for(key in names(members)){m<-members[[key]];s<-if(!defined)NA_real_ else if(!m$eligible)0 else if(m$role=='treated')(m$change-d)/length(T)else-(m$change-e)/length(C);m$score<-s;scores[key]<-s;members[[key]]<-m};st<-var0(change(T));sc<-var0(change(C));v<-if(is.na(st)||is.na(sc))NA_real_ else st/length(T)+sc/length(C);level<-function(a,k)mean0(vapply(a,function(r)r[[k]],0))\r\n list(g=g,t=t,baseline=b,event=(t-g)/step,phase=if(t==b)'mechanical-reference'else if(t>=g)'post'else'pre-placebo',defined=defined,estimate=estimate,T=T,C=C,members=members,scores=scores,HC0=if(defined)sum(scores^2)else NA_real_,unbiased=v,treatedMeanBefore=level(T,'before'),treatedMeanAfter=level(T,'after'),treatedMeanChange=d,controlMeanBefore=level(C,'before'),controlMeanAfter=level(C,'after'),controlMeanChange=e)\r\n}\r\ncovariance<-function(cells){n<-length(cells);V<-matrix(NA_real_,n,n);for(i in seq_len(n))for(j in seq_len(n))if(cells[[i]]$defined&&cells[[j]]$defined)V[i,j]<-sum(cells[[i]]$scores*cells[[j]]$scores);V}\r\naggregate_cells<-function(post,V,step){out<-list();push<-function(typ,key,ii,w){est<-if(!length(ii)||any(vapply(post[ii],function(z)is.na(z$estimate),TRUE)))NA_real_ else sum(w*vapply(post[ii],function(z)z$estimate,0));vv<-if(is.na(est)||anyNA(V[ii,ii,drop=FALSE]))NA_real_ else as.numeric(t(w)%*%V[ii,ii,drop=FALSE]%*%w);out[[length(out)+1L]]<<-list(type=typ,key=as.character(key),ii=ii,w=w,estimate=est,variance=vv)};positive<-which(vapply(post,function(c)length(c$T)>0L,TRUE));mass<-sum(vapply(post[positive],function(c)length(c$T),0));push('simple','overall',positive,if(mass)vapply(post[positive],function(c)length(c$T)/mass,0)else numeric())\r\n for(typ in c('event','calendar','group')){keys<-vapply(post,function(c)if(typ=='event')c$event else if(typ=='calendar')c$t else c$g,0);gg<-sort(unique(keys));cohortmass<-if(typ=='group')sum(vapply(gg,function(k)length(post[[which(keys==k)[1]]]$T),0))else 0;allii<-integer();allw<-numeric();for(key in gg){ii<-which(keys==key);jj<-ii[vapply(post[ii],function(c)length(c$T)>0L,TRUE)];if(typ=='group'){stopifnot(length(unique(vapply(post[ii],function(c)length(c$T),0)))<=1L);w<-if(length(jj))rep(1/length(jj),length(jj))else numeric();if(cohortmass){allii<-c(allii,jj);allw<-c(allw,w*length(post[[ii[1]]]$T)/cohortmass)}}else{total<-sum(vapply(post[jj],function(c)length(c$T),0));w<-if(total)vapply(post[jj],function(c)length(c$T)/total,0)else numeric()};push(typ,key,jj,w)};if(typ=='group')push(typ,'overall',allii,allw)};out}\r\ntwfe<-function(G,times){ledger<-list();good<-list();for(key in names(G)){u<-G[[key]];absent<-times[!as.character(times)%in%names(u$rows)];missing<-times[vapply(times,function(t){r<-u$rows[[as.character(t)]];!is.null(r)&&is.na(r$y)},TRUE)];eligible<-length(times)>0L&&!length(absent)&&!length(missing);ledger[[length(ledger)+1L]]<-list(entity=key,g=u$g,nativeID=u$rows[[1]]$nativeID,eligible=eligible,absentTimes=paste(absent,collapse=','),missingOutcomeTimes=paste(missing,collapse=','),originalRows=length(u$rows));if(eligible)good[[key]]<-u};rows<-list();for(key in names(good))for(t in times){r<-good[[key]]$rows[[as.character(t)]];r$D<-as.integer(!is.na(r$g)&&t>=r$g);rows[[length(rows)+1L]]<-r};em<-lapply(good,function(u)list(D=mean(vapply(times,function(t)as.integer(!is.na(u$g)&&t>=u$g),0)),Y=mean(vapply(u$rows[as.character(times)],function(r)r$y,0))));tm<-lapply(times,function(t)list(D=mean(vapply(good,function(u)as.integer(!is.na(u$g)&&t>=u$g),0)),Y=mean(vapply(good,function(u)u$rows[[as.character(t)]]$y,0))));names(tm)<-as.character(times);gd<-mean0(vapply(rows,function(r)r$D,0));gy<-mean0(vapply(rows,function(r)r$y,0));num<-den<-0\r\n for(i in seq_along(rows)){r<-rows[[i]];r$residualD<-r$D-em[[r$entity]]$D-tm[[as.character(r$time)]]$D+gd;r$residualY<-r$y-em[[r$entity]]$Y-tm[[as.character(r$time)]]$Y+gy;num<-num+r$residualD*r$residualY;den<-den+r$residualD^2;rows[[i]]<-r};beta<-if(den!=0)num/den else NA_real_;weights<-list();for(i in seq_along(rows)){r<-rows[[i]];r$projectionCoefficient<-if(den!=0)r$residualD/den else NA_real_;r$regressionResidual<-if(!is.na(beta))r$residualY-beta*r$residualD else NA_real_;rows[[i]]<-r;if(r$D==1L){k<-paste(r$g,r$time,sep=':');z<-weights[[k]];if(is.null(z))z<-list(g=r$g,t=r$time,rows=0,coefficient=if(den!=0)0 else NA_real_);z$rows<-z$rows+1L;if(den!=0)z$coefficient<-z$coefficient+r$projectionCoefficient;weights[[k]]<-z}};list(ledger=ledger,rows=rows,num=num,den=den,beta=beta,weights=weights,balancedEntities=length(good))}\r\nadjacent_pre<-function(G,g,t,step,control){b<-t-step;T<-C<-numeric();for(u in G){target<-!is.na(u$g)&&u$g==g;comp<-is.na(u$g)||(control=='notyet'&&!is.na(u$g)&&u$g>max(t,b));if(!target&&!comp)next;before<-u$rows[[as.character(b)]];after<-u$rows[[as.character(t)]];if(!is.null(before)&&!is.null(after)&&!is.na(before$y)&&!is.na(after$y)){if(target)T<-c(T,after$y-before$y)else C<-c(C,after$y-before$y)}};if(!length(T)||!length(C))NA_real_ else mean(T)-mean(C)}\r\n\r\n# Newly authored bounded teaching projections; base R finite approximation.\r\n# Source helper functions are inlined in each public file, never imported.\r\nqnum<-function(v){if(is.null(v)||is.na(v))return(NA_real_);s<-strsplit(as.character(v),'/',fixed=TRUE)[[1]];if(length(s)==1L)as.numeric(s)else as.numeric(s[1])/as.numeric(s[2])}\r\npaired<-function(T,C){\r\n stats<-function(rr){use<-Filter(function(r)!is.na(qnum(r$before))&&!is.na(qnum(r$after)),rr);a<-vapply(use,function(r)qnum(r$before),0);b<-vapply(use,function(r)qnum(r$after),0);list(sourcePairs=length(rr),eligiblePairs=length(use),excludedPairs=length(rr)-length(use),meanBefore=mean0(a),meanAfter=mean0(b),meanChange=mean0(b-a),sampleChangeVariance=var0(b-a))}\r\n st<-stats(T);sc<-stats(C);defined<-st$eligiblePairs>0L&&sc$eligiblePairs>0L;estimate<-if(defined)st$meanChange-sc$meanChange else NA_real_;rr<-list()\r\n for(role in c('treated','control')){input<-if(role=='treated')T else C;s<-if(role=='treated')st else sc;for(r in input){before<-qnum(r$before);after<-qnum(r$after);eligible<-!is.na(before)&&!is.na(after);change<-if(eligible)after-before else NA_real_;score<-if(!defined)NA_real_ else if(!eligible)0 else (change-s$meanChange)/(if(role=='treated')s$eligiblePairs else -s$eligiblePairs);rr[[length(rr)+1L]]<-list(id=r$id,role=role,before=before,after=after,eligible=eligible,change=change,score=score)}}\r\n list(defined=defined,estimate=estimate,treated=st,control=sc,unbiasedVariance=if(defined&&st$eligiblePairs>=2L&&sc$eligiblePairs>=2L)st$sampleChangeVariance/st$eligiblePairs+sc$sampleChangeVariance/sc$eligiblePairs else NA_real_,HC0=if(defined)sum(vapply(rr,function(r)r$score^2,0))else NA_real_,rows=rr)\r\n}\r\nliteral_panel<-function(rr)lapply(seq_along(rr),function(i){r<-rr[[i]];r$y<-qnum(r$y);r$nativeID<-r$entity;r$sourceRow<-i;r})\r\natt_projection<-function(rows,control='never',step=1){G<-panel(rows);times<-sort(unique(vapply(rows,function(r)r$time,0)));cohorts<-sort(unique(na.omit(vapply(rows,function(r)r$g,0))));cells<-list();for(g in cohorts)for(t in times)cells[[length(cells)+1L]]<-cell(G,g,t,step,control);list(sourceRows=length(rows),sourceEntities=length(G),step=step,control=control,cells=cells,covariance=covariance(cells))}\r\nlinear_aggregate<-function(a){\r\n rr<-lapply(a$cells,function(r){r$estimate<-qnum(r$estimate);r$weight<-qnum(r$weight);r});V<-if(is.null(a$covariance))NULL else do.call(rbind,lapply(a$covariance,function(r)vapply(r,qnum,0)));rank<-NA_real_\r\n if(!is.null(V)){stopifnot(nrow(V)==length(rr),ncol(V)==length(rr),all(V==t(V)));ev<-eigen(V,symmetric=TRUE,only.values=TRUE)$values;if(any(ev< -1e-12))stop('covariance-must-be-positive-semidefinite');rank<-sum(ev>1e-12)}\r\n selected<-which(vapply(rr,function(r)r$time>=r$cohort&&r$weight>0,TRUE));w<-numeric(length(rr));type<-if(is.null(a$type))'simple'else a$type\r\n if(type=='simple'){mass<-sum(vapply(rr[selected],function(r)r$weight,0));if(mass>0)for(i in selected)w[i]<-rr[[i]]$weight/mass}else{g<-vapply(rr,function(r)r$cohort,0);gg<-sort(unique(g[selected]));mass<-sum(vapply(gg,function(gi)rr[[intersect(which(g==gi),selected)[1]]]$weight,0));for(gi in gg){ii<-intersect(which(g==gi),selected);stopifnot(length(unique(vapply(rr[ii],function(r)r$weight,0)))==1L);w[ii]<-rr[[ii[1]]]$weight/mass/length(ii)}}\r\n used<-which(w>0);estimate<-if(!length(used)||any(vapply(rr[used],function(r)is.na(r$estimate),TRUE)))NA_real_ else sum(w[used]*vapply(rr[used],function(r)r$estimate,0));variance<-if(is.na(estimate)||is.null(V))NA_real_ else as.numeric(t(w)%*%V%*%w);weights<-lapply(used,function(i)list(sourceIndex=i-1L,cohort=rr[[i]]$cohort,time=rr[[i]]$time,coefficient=w[i],estimate=rr[[i]]$estimate,contribution=w[i]*rr[[i]]$estimate))\r\n list(type=type,defined=!is.na(estimate),estimate=estimate,variance=variance,covarianceRank=rank,weights=weights,cells=rr,covariance=V)\r\n}\r\nsensitivity_fixed<-function(a){estimate<-qnum(a$estimate);M<-qnum(a$M);h<-if(is.null(a$horizon))1 else a$horizon;stopifnot(M>=0,h>=1);pre<-vapply(a$preDifferences,qnum,0);scale<-if(!is.null(a$scale))qnum(a$scale)else if(length(pre))max(abs(pre))else NA_real_;budget<-M*scale*h;list(defined=!is.na(scale),estimate=estimate,scale=scale,M=M,horizon=h,biasBudget=budget,lower=estimate-budget,upper=estimate+budget,preDifferences=as.list(pre),confidenceLevel=NULL)}\r\nrealdata_fixed<-function(kind){rows<-models[[kind]];G<-panel(rows);times<-sort(unique(vapply(rows,function(r)r$time,0)));step<-unname(steps[kind]);aa<-att_projection(rows,'never',step);post<-Filter(function(r)r$phase=='post',aa$cells);aggs<-aggregate_cells(post,covariance(post),step);tf<-twfe(G,times);list(kind=kind,unit=unname(units[kind]),periodUnit=unname(clocks[kind]),nativeRows=nrow(raw[[kind]]),modelRows=length(rows),entities=length(G),sourceRows=rows,att=aa,aggregations=aggs,twfe=tf,scope='Complete native/model/paired/balanced source frames; never control,universal base,no anticipation;not causal/sampling certification.')}\r\n# JSON encoder deliberately handles matrices and scalar/vector distinctions.\r\nencode<-function(x){\r\n if(is.null(x))return('null')\r\n quote<-function(s){s<-gsub('\\\\','\\\\\\\\',as.character(s),fixed=TRUE);s<-gsub('\"','\\\\\"',s,fixed=TRUE);s<-gsub('\\n','\\\\n',s,fixed=TRUE);s<-gsub('\\r','\\\\r',s,fixed=TRUE);s<-gsub('\\t','\\\\t',s,fixed=TRUE);paste0('\"',s,'\"')}\r\n if(is.matrix(x))return(paste0('[',paste(vapply(seq_len(nrow(x)),function(i)encode(as.list(unname(x[i,]))),''),collapse=','),']'))\r\n if(is.list(x)){if(length(x)&&!is.null(names(x)))return(paste0('{',paste(paste0(vapply(names(x),quote,''),':',vapply(x,encode,'')),collapse=','),'}'));return(paste0('[',paste(vapply(x,encode,''),collapse=','),']'))}\r\n if(length(x)!=1L)return(encode(as.list(unname(x))))\r\n if(is.na(x))return('null');if(is.logical(x))return(if(x)'true'else'false');if(is.numeric(x))return(sprintf('%.17g',unname(x)));quote(x)\r\n}\r\nv9<-function(x){if(is.null(x)||is.na(x))return('undefined');if(is.logical(x))return(if(x)'1'else'0');if(is.numeric(x))return(sprintf('%.9g',unname(x)));as.character(x)}\r\nrun_fixed<-function(spec,out){api<-spec$api;a<-spec$input;summary<-list();points<-list();emit<-function(series,x,y){points[[length(points)+1L]]<<-list(series=series,x=x,y=y,numericY=y)}\r\n if(api=='twobytwo'){result<-paired(a$treated,a$control);summary<-list(defined=result$defined,estimate=result$estimate,treatedPairs=result$treated$eligiblePairs,controlPairs=result$control$eligiblePairs,unbiasedVariance=result$unbiasedVariance,HC0=result$HC0);for(i in seq_along(result$rows)){r<-result$rows[[i]];emit(paste(r$role,r$id,sep=':'),i,r$change)}}\r\n else if(api=='att'){result<-att_projection(literal_panel(a$rows),a$control);summary<-list(sourceRows=result$sourceRows,entities=result$sourceEntities,cells=length(result$cells),supportedCells=sum(vapply(result$cells,function(r)r$defined,TRUE)),postCells=sum(vapply(result$cells,function(r)r$phase=='post',TRUE)));for(i in seq_along(result$cells)){r<-result$cells[[i]];emit(paste0('g',r$g,':t',r$t),i,r$estimate)}}\r\n else if(api=='aggregate'){result<-linear_aggregate(a);summary<-list(defined=result$defined,estimate=result$estimate,variance=result$variance,covarianceRank=result$covarianceRank,sumWeights=sum(vapply(result$weights,function(r)r$coefficient,0)));for(i in seq_along(result$weights)){r<-result$weights[[i]];emit(paste0('g',r$cohort,':t',r$time),i,r$contribution)}}\r\n else if(api=='twfe'){rows<-literal_panel(a$rows);G<-panel(rows);result<-twfe(G,sort(unique(vapply(rows,function(r)r$time,0))));summary<-list(defined=!is.na(result$beta),beta=result$beta,numerator=result$num,denominator=result$den,balancedEntities=result$balancedEntities,negativeTreatedCells=sum(vapply(result$weights,function(r)!is.na(r$coefficient)&&r$coefficient<0,TRUE)));if(length(result$weights)){ord<-order(vapply(result$weights,function(r)r$g,0),vapply(result$weights,function(r)r$t,0));for(i in seq_along(ord)){r<-result$weights[[ord[i]]];emit(paste0('g',r$g,':t',r$t),i,r$coefficient)}}}\r\n else if(api=='sensitivity'){result<-sensitivity_fixed(a);summary<-result[c('defined','estimate','scale','M','horizon','biasBudget','lower','upper')];for(i in seq_along(c('lower','estimate','upper'))){k<-c('lower','estimate','upper')[i];emit(k,i,if(result$defined)result[[k]]else NA_real_)}}\r\n else{result<-realdata_fixed(a$kind);post<-Filter(function(r)r$phase=='post',result$att$cells);simple<-Filter(function(r)r$type=='simple',result$aggregations)[[1]];group<-Filter(function(r)r$type=='group'&&r$key=='overall',result$aggregations)[[1]];summary<-list(nativeRows=result$nativeRows,modelRows=result$modelRows,entities=result$entities,postCells=length(post),simple=simple$estimate,group=group$estimate,TWFE=result$twfe$beta,balancedEntities=result$twfe$balancedEntities);for(i in seq_along(post)){r<-post[[i]];emit(paste0('g',r$g,':t',r$t),i,r$estimate)}}\r\n dir.create(out,recursive=TRUE,showWarnings=FALSE);if(length(list.files(out,all.files=TRUE,no..=TRUE)))stop('use-new-empty-output-directory');shown<-lapply(summary,v9);write.csv(data.frame(name=names(shown),value=unlist(shown,use.names=FALSE)),file.path(out,'summary.csv'),row.names=FALSE,na='');pointframe<-if(length(points))do.call(rbind,lapply(points,function(p)data.frame(series=p$series,x=p$x,y=p$y,numericY=p$numericY,stringsAsFactors=FALSE)))else data.frame(series=character(),x=numeric(),y=numeric(),numericY=numeric());write.csv(pointframe,file.path(out,'points.csv'),row.names=FALSE,na='');full<-list(chapter='METR-20',profile=spec$id,api=api,input=spec$input,summary=shown,points=points,details=result,arithmetic='Base R approximate finite values;bounded teaching projection,not exact fractions or causal/sampling certification.');writeLines(encode(full),file.path(out,'full.json'),useBytes=TRUE)\r\n svg(file.path(out,'plot.svg'),width=9,height=5.6,pointsize=12);par(mar=c(4.5,5.5,4,1));good<-pointframe[!is.na(pointframe$numericY),,drop=FALSE]\r\n if(nrow(good)){plot(good$x,good$numericY,pch=19,col='#315d7c',xlab='Declared cell/unit/bound ordinal',ylab=if(api=='twfe')'Cell weight'else if(!is.null(result$unit))result$unit else 'Stated outcome/bias units',main=spec$title$en);abline(h=0,col='#9eabb2');grid(nx=NA,ny=NULL,col='#e2e5e7');points(good$x,good$numericY,pch=19,col='#315d7c')}else{plot.new();text(.5,.5,'Undefined: no supported plotted quantity');title(main=spec$title$en)};dev.off();cat(encode(shown),'\\n')\r\n}\r\n\r\nraw<-lapply(files,function(n)read.csv(file.path(datadir,n),colClasses='character',check.names=FALSE,na.strings=character()));stopifnot(identical(vapply(raw,nrow,0L),c(country=2500L,person=38408L,company=410L)))\r\nmodels<-list(country=list(),person=list(),company=list())\r\nfor(i in seq_len(nrow(raw$country))){r<-raw$country[i,];g<-as.integer(r$first.treat);if(!g)g<-NA_integer_;stopifnot(as.integer(r$treat)==as.integer(!is.na(g)));models$country[[i]]<-list(id=paste0('mpdta:',r$sourceRow),entity=paste0('county:',as.integer(r$countyreal)),time=as.integer(r$year),y=num(r$lemp),g=g,sourceRow=as.integer(r$sourceRow),nativeID=r$countyreal)}\r\nfor(i in seq_len(nrow(raw$person))){r<-raw$person[i,];selected<-as.integer(r$experimental)==1L;stopifnot(selected==(as.integer(r$sample)==1L),(r$treated!='.')==selected);if(selected){d<-as.integer(r$treated);stopifnot(d%in%0:1);models$person[[length(models$person)+1L]]<-list(id=paste0('nsw:',r$sourceRow),entity=paste0('nsw-id:',as.integer(r$id)),time=as.integer(r$year),y=num(r$re),g=if(d==1L)1978L else NA_integer_,sourceRow=as.integer(r$sourceRow),nativeID=as.character(as.integer(r$id)))}}\r\nfor(i in seq_len(nrow(raw$company))){r<-raw$company[i,];state<-as.integer(r$STATE);stopifnot(state%in%0:1);for(t in 0:1){suffix<-if(t==0)''else'2';v<-vapply(paste0(c('EMPFT','NMGRS','EMPPT'),suffix),function(k)num(r[[k]]),0);y<-if(anyNA(v))NA_real_ else v[1]+v[2]+v[3]/2;models$company[[length(models$company)+1L]]<-list(id=paste0('njpa:',r$sourceRow,':wave',t),entity=paste0('njpa-row:',r$sourceRow),time=t,y=unname(y),g=if(state==1L)1L else NA_integer_,sourceRow=as.integer(r$sourceRow),nativeID=r$SHEET)}}\r\nstopifnot(identical(vapply(models,length,0L),c(country=2500L,person=1444L,company=820L)))\r\n\r\nrun_fixed(SPEC,outdir)\r\n",
      "arithmetic": "Base R approximate finite arithmetic;not an exact rational result",
      "summary": {
        "nativeRows": "2500",
        "modelRows": "2500",
        "entities": "500",
        "postCells": "7",
        "simple": "-0.0399512752",
        "group": "-0.0310182822",
        "TWFE": "-0.0365489367",
        "balancedEntities": "500"
      },
      "fullResultEmbedded": false,
      "plotEmbedded": false,
      "full": {
        "summary": {
          "nativeRows": "2500",
          "modelRows": "2500",
          "entities": "500",
          "postCells": "7",
          "simple": "-0.0399512752",
          "group": "-0.0310182822",
          "TWFE": "-0.0365489367",
          "balancedEntities": "500"
        },
        "notice": "Complete source/finite projection is retained in the linked external JSON; this short projection is not the full result."
      },
      "plot": null,
      "points": [
        {
          "series": "g2004:t2004",
          "x": 1,
          "y": -0.010503246220963533,
          "numericY": -0.010503246220963533
        },
        {
          "series": "g2004:t2005",
          "x": 2,
          "y": -0.07042315810314909,
          "numericY": -0.07042315810314909
        },
        {
          "series": "g2004:t2006",
          "x": 3,
          "y": -0.13725873888940443,
          "numericY": -0.13725873888940443
        },
        {
          "series": "g2004:t2007",
          "x": 4,
          "y": -0.10081136308540525,
          "numericY": -0.10081136308540525
        },
        {
          "series": "g2006:t2006",
          "x": 5,
          "y": -0.00459460695286272,
          "numericY": -0.00459460695286272
        },
        {
          "series": "g2006:t2007",
          "x": 6,
          "y": -0.041224471546217945,
          "numericY": -0.041224471546217945
        },
        {
          "series": "g2007:t2007",
          "x": 7,
          "y": -0.026054410719197237,
          "numericY": -0.026054410719197237
        }
      ],
      "summaryFile": "metr20-programs/realdata-country-r-summary.csv",
      "summarySHA256": "63df3c980538b7e6f5fa739350388291738bb1e5ee2b0bdc194e103765e86191",
      "pointsFile": "metr20-programs/realdata-country-r-points.csv",
      "pointsSHA256": "fcf9e70e7592d2d82ff12fd537dbf26584f73ba7b6ad486e104533db865964fe",
      "fullResultFile": "metr20-programs/realdata-country-r.json",
      "fullResultSHA256": "f20d9a09406621c92d4318ac8f6585f7801dcbf0304f99d1c60425e66de11c9a",
      "plotFile": "metr20-programs/realdata-country-r.svg",
      "plotSHA256": "cb8e040e60c708b49989195cb0d25a107b261b893513724aa6c1f52d9f4b7b61"
    },
    {
      "api": "realdata",
      "variant": "realdata-person",
      "profile": "realdata-person",
      "language": "Python",
      "file": "metr20-programs/realdata-person-python.py",
      "codeSHA256": "f4665bb8f22b709cc4fd955ca5f994f0527be382ca53b50946323059ca9cd689",
      "returnCode": 0,
      "expectedRejection": false,
      "title": {
        "ko": "실제 NSW 실험 표본 722명",
        "en": "Actual 722-person NSW experimental frame"
      },
      "code": "\"\"\"METR20 actual sources. Python standard library, exact stored-value rationals.\r\nRead ONLY the three native-observation CSVs; no JS engine,model JSON,derived\r\nanswers,private modules or internet needed. Outcome measurement/identification\r\nand valid sampling inference remain separate from exact finite arithmetic.\r\nRun: python metr20-reproduce.py --data-dir PATH --out NEW_EMPTY_DIRECTORY\r\n\"\"\"\r\nfrom pathlib import Path\r\nfrom fractions import Fraction as Q\r\nfrom collections import defaultdict,Counter\r\nimport csv,json,math,argparse,hashlib\r\n\r\nUNIT={'country':'log teen-employment points','person':'recorded real earnings','company':'FTE employees'}\r\nCLOCK={'country':'calendar year','person':'calendar year','company':'survey-wave index'}\r\nSTEP={'country':1,'person':3,'company':1}\r\nFILES={'country':'actual2500-county-mpdta-all6-fields.csv','person':'actual38408-NSW-all15-fields.csv','company':'actual410-NJPA-all46-fields.csv'}\r\ndef avg(v):return sum(v,Q(0))/len(v)if v else None\r\ndef samplevar(v):return sum(((x-avg(v))**2 for x in v),Q(0))/(len(v)-1)if len(v)>1 else None\r\ndef binary(s):return None if s=='.'else Q.from_float(float(s))\r\ndef token(v):\r\n if v is None:return ''\r\n if isinstance(v,bool):return 'true'if v else'false'\r\n return str(v)\r\ndef safe_float(v):\r\n if v is None:return None\r\n try:r=float(v)\r\n except OverflowError:return None\r\n return r if math.isfinite(r)else None\r\ndef read(p):\r\n with p.open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))\r\ndef write(p,rows,head=None):\r\n if head is None:\r\n  assert rows;head=list(rows[0])\r\n with p.open('w',encoding='utf8',newline='')as f:\r\n  w=csv.DictWriter(f,fieldnames=head);w.writeheader();w.writerows({k:token(r.get(k))for k in head}for r in rows)\r\ndef source(data):\r\n raw={k:read(data/n)for k,n in FILES.items()};assert[len(raw[k])for k in FILES]==[2500,38408,410]\r\n models={k:[]for k in FILES}\r\n for r in raw['country']:\r\n  g0=int(r['first.treat']);g=None if g0==0 else g0;assert int(r['treat'])==int(g is not None)\r\n  models['country'].append(dict(id='mpdta:'+r['sourceRow'],entity='county:'+str(int(r['countyreal'])),time=int(r['year']),y=binary(r['lemp']),g=g,sourceRow=int(r['sourceRow']),nativeID=r['countyreal']))\r\n for r in raw['person']:\r\n  selected=int(r['experimental'])==1;assert selected==(int(r['sample'])==1);assert(r['treated']!='.')==selected\r\n  if selected:\r\n   d=int(r['treated']);assert d in[0,1]\r\n   models['person'].append(dict(id='nsw:'+r['sourceRow'],entity='nsw-id:'+str(int(r['id'])),time=int(r['year']),y=binary(r['re']),g=1978 if d else None,sourceRow=int(r['sourceRow']),nativeID=str(int(r['id']))))\r\n for r in raw['company']:\r\n  state=int(r['STATE']);assert state in[0,1]\r\n  for t,suffix in[(0,''),(1,'2')]:\r\n   a=[r[n+suffix]for n in['EMPFT','NMGRS','EMPPT']];y=None if'.'in a else Q(a[0])+Q(a[1])+Q(a[2])/2\r\n   models['company'].append(dict(id='njpa:'+r['sourceRow']+':wave'+str(t),entity='njpa-row:'+r['sourceRow'],time=t,y=y,g=1 if state else None,sourceRow=int(r['sourceRow']),nativeID=r['SHEET']))\r\n assert[len(models[k])for k in FILES]==[2500,1444,820]\r\n return models,raw\r\ndef panel(rows):\r\n groups={}\r\n for r in rows:\r\n  u=groups.setdefault(r['entity'],{'g':r['g'],'rows':{}});assert u['g']==r['g']and r['time']not in u['rows'];u['rows'][r['time']]=r\r\n return groups\r\ndef cell(groups,g,t,step,control):\r\n b=g-step;members=[];T=[];C=[]\r\n for key,u in groups.items():\r\n  role='treated'if u['g']==g else'control'if u['g']is None or(control=='notyet'and u['g']>max(t,b))else'excluded-comparison'\r\n  before=u['rows'].get(b);after=u['rows'].get(t);yb=None if before is None else before['y'];ya=None if after is None else after['y'];eligible=role!='excluded-comparison'and yb is not None and ya is not None\r\n  reason='target-or-already-exposed-cohort-not-valid-control'if role=='excluded-comparison'else'baseline-source-row-absent'if before is None else'target-time-source-row-absent'if after is None else'baseline-outcome-missing'if yb is None else'target-outcome-missing'if ya is None else''\r\n  m={'entity':key,'nativeID':next(iter(u['rows'].values()))['nativeID'],'g':u['g'],'role':role,'eligible':eligible,'baselineSourceId':None if before is None else before['id'],'targetSourceId':None if after is None else after['id'],'before':yb,'after':ya,'change':ya-yb if eligible else None,'reason':reason};members.append(m)\r\n  if eligible:(T if role=='treated'else C).append(m)\r\n d=avg([r['change']for r in T]);e=avg([r['change']for r in C]);estimate=None if d is None or e is None else d-e;defined=estimate is not None;scores={}\r\n for m in members:\r\n  s=None if not defined else Q(0)\r\n  if defined and m['eligible']:s=(m['change']-(d if m['role']=='treated'else e))/(len(T)if m['role']=='treated'else-len(C))\r\n  m['score']=s;scores[m['entity']]=s\r\n st=samplevar([r['change']for r in T]);sc=samplevar([r['change']for r in C]);v=None if st is None or sc is None else st/len(T)+sc/len(C)\r\n return {'g':g,'t':t,'baseline':b,'event':(t-g)//step,'phase':'mechanical-reference'if t==b else'post'if t>=g else'pre-placebo','defined':defined,'estimate':estimate,'T':T,'C':C,'members':members,'scores':scores,'HC0':None if not defined else sum((s*s for s in scores.values()),Q(0)),'unbiased':v,'treatedMeanBefore':avg([r['before']for r in T]),'treatedMeanAfter':avg([r['after']for r in T]),'treatedMeanChange':d,'controlMeanBefore':avg([r['before']for r in C]),'controlMeanAfter':avg([r['after']for r in C]),'controlMeanChange':e}\r\ndef covariance(cells):\r\n return[[None if not a['defined']or not b['defined']else sum((v*b['scores'][i]for i,v in a['scores'].items()),Q(0))for b in cells]for a in cells]\r\ndef aggregate(post,V,step):\r\n out=[]\r\n def push(typ,key,coeff):\r\n  estimate=None if not coeff or any(post[i]['estimate']is None for i in coeff)else sum((w*post[i]['estimate']for i,w in coeff.items()),Q(0));variance=None if estimate is None or any(V[i][j]is None for i in coeff for j in coeff)else sum((a*b*V[i][j]for i,a in coeff.items()for j,b in coeff.items()),Q(0));out.append({'type':typ,'key':key,'coeff':coeff,'estimate':estimate,'variance':variance})\r\n positive=[i for i,c in enumerate(post)if len(c['T'])>0];mass=sum(len(post[i]['T'])for i in positive)\r\n push('simple','overall',{i:Q(len(post[i]['T']),mass)for i in positive}if mass else{})\r\n for typ in['event','calendar','group']:\r\n  groups=defaultdict(list)\r\n  for i,c in enumerate(post):groups[c['event']if typ=='event'else c['t']if typ=='calendar'else c['g']].append(i)\r\n  overall={};cohortMass=sum(len(post[ii[0]]['T'])for ii in groups.values())if typ=='group'else 0\r\n  for key,ii in sorted(groups.items()):\r\n   jj=[i for i in ii if len(post[i]['T'])>0]\r\n   if typ=='group':\r\n    assert len({len(post[i]['T'])for i in ii})<=1\r\n    coeff={i:Q(1,len(jj))for i in jj}if jj else{}\r\n    if cohortMass:\r\n     for i,w in coeff.items():overall[i]=w*Q(len(post[ii[0]]['T']),cohortMass)\r\n   else:\r\n    total=sum(len(post[i]['T'])for i in jj);coeff={i:Q(len(post[i]['T']),total)for i in jj}if total else{}\r\n   push(typ,str(key),coeff)\r\n  if typ=='group':push(typ,'overall',overall)\r\n return out\r\ndef twfe(groups,times):\r\n ledger=[];good={}\r\n for key,u in groups.items():\r\n  absent=[t for t in times if t not in u['rows']];missing=[t for t in times if t in u['rows']and u['rows'][t]['y']is None];eligible=bool(times)and not absent and not missing\r\n  ledger.append({'entity':key,'g':u['g'],'nativeID':next(iter(u['rows'].values()))['nativeID'],'eligible':eligible,'absentTimes':','.join(map(str,absent)),'missingOutcomeTimes':','.join(map(str,missing)),'originalRows':len(u['rows'])})\r\n  if eligible:good[key]=u\r\n rows=[dict(**u['rows'][t],D=Q(u['g']is not None and t>=u['g']))for key,u in good.items()for t in times]\r\n em={k:{'D':avg([Q(u['g']is not None and t>=u['g'])for t in times]),'Y':avg([u['rows'][t]['y']for t in times])}for k,u in good.items()};tm={t:{'D':avg([Q(u['g']is not None and t>=u['g'])for u in good.values()]),'Y':avg([u['rows'][t]['y']for u in good.values()])}for t in times};gd=avg([r['D']for r in rows]);gy=avg([r['y']for r in rows]);num=den=Q(0)\r\n for r in rows:\r\n  r['residualD']=r['D']-em[r['entity']]['D']-tm[r['time']]['D']+gd;r['residualY']=r['y']-em[r['entity']]['Y']-tm[r['time']]['Y']+gy;num+=r['residualD']*r['residualY'];den+=r['residualD']**2\r\n beta=num/den if den else None;weights={}\r\n for r in rows:\r\n  r['projectionCoefficient']=r['residualD']/den if den else None;r['regressionResidual']=r['residualY']-beta*r['residualD']if beta is not None else None\r\n  if r['D']:\r\n   k=(r['g'],r['time']);z=weights.setdefault(k,{'rows':0,'coefficient':Q(0)if den else None});z['rows']+=1\r\n   if den:z['coefficient']+=r['projectionCoefficient']\r\n return {'ledger':ledger,'rows':rows,'num':num,'den':den,'beta':beta,'weights':weights,'balancedEntities':len(good)}\r\ndef adjacent_pre(groups,g,t,step,control):\r\n b=t-step;T=[];C=[]\r\n for u in groups.values():\r\n  if u['g']==g:target=T\r\n  elif u['g']is None or(control=='notyet'and u['g']>max(t,b)):target=C\r\n  else:continue\r\n  before=u['rows'].get(b);after=u['rows'].get(t)\r\n  if before is not None and after is not None and before['y']is not None and after['y']is not None:target.append(after['y']-before['y'])\r\n return None if not T or not C else avg(T)-avg(C)\r\n\r\n\"\"\"New bounded teaching projections. The program is self-contained after build.\r\nExact Fraction finite algebra; figures and9-digit summary are approximations.\r\nIt is not a general parser/API replacement or a causal/inference certificate.\r\n\"\"\"\r\ndef paired(treated,control):\r\n def stats(rr):\r\n  use=[r for r in rr if r['before']is not None and r['after']is not None];delta=[Q(r['after'])-Q(r['before'])for r in use]\r\n  return dict(sourcePairs=len(rr),eligiblePairs=len(use),excludedPairs=len(rr)-len(use),meanBefore=avg([Q(r['before'])for r in use]),meanAfter=avg([Q(r['after'])for r in use]),meanChange=avg(delta),sampleChangeVariance=samplevar(delta))\r\n T,C=stats(treated),stats(control);defined=T['eligiblePairs']>0 and C['eligiblePairs']>0;estimate=T['meanChange']-C['meanChange']if defined else None;records=[]\r\n for group,rr,s in [('treated',treated,T),('control',control,C)]:\r\n  for r in rr:\r\n   before=None if r['before']is None else Q(r['before']);after=None if r['after']is None else Q(r['after']);eligible=before is not None and after is not None;delta=after-before if eligible else None;score=None if not defined else Q(0)if not eligible else(delta-s['meanChange'])/(s['eligiblePairs']if group=='treated'else-s['eligiblePairs']);records.append(dict(id=r['id'],role=group,before=before,after=after,eligible=eligible,change=delta,score=score))\r\n unbiased=None if not defined or T['eligiblePairs']<2 or C['eligiblePairs']<2 else T['sampleChangeVariance']/T['eligiblePairs']+C['sampleChangeVariance']/C['eligiblePairs'];hc0=None if not defined else sum((r['score']**2 for r in records),Q(0))\r\n return dict(defined=defined,estimate=estimate,treated=T,control=C,unbiasedVariance=unbiased,HC0=hc0,rows=records)\r\ndef literal_panel(raw):\r\n return[dict(r,y=None if r['y']is None else Q(r['y']),nativeID=r['entity'],sourceRow=i+1)for i,r in enumerate(raw)]\r\ndef att_projection(rows,control='never',step=1):\r\n G=panel(rows);times=sorted({r['time']for r in rows});cohorts=sorted({r['g']for r in rows if r['g']is not None});cells=[cell(G,g,t,step,control)for g in cohorts for t in times]\r\n return dict(sourceRows=len(rows),sourceEntities=len(G),step=step,control=control,cells=cells,covariance=covariance(cells))\r\ndef psd(V):\r\n A=[r[:]for r in V];rank=0\r\n while A:\r\n  if any(A[i][i]<0 for i in range(len(A))):raise ValueError('covariance-must-be-positive-semidefinite')\r\n  p=next((i for i in range(len(A))if A[i][i]>0),None)\r\n  if p is None:\r\n   if any(v for r in A for v in r):raise ValueError('covariance-must-be-positive-semidefinite')\r\n   return rank\r\n  A[0],A[p]=A[p],A[0]\r\n  for r in A:r[0],r[p]=r[p],r[0]\r\n  d=A[0][0];A=[[A[i][j]-A[i][0]*A[0][j]/d for j in range(1,len(A))]for i in range(1,len(A))];rank+=1\r\n return rank\r\ndef linear_aggregate(a):\r\n rr=[dict(r,estimate=None if r['estimate']is None else Q(r['estimate']),weight=Q(r['weight']))for r in a['cells']];V=[[Q(v)for v in r]for r in a['covariance']]if 'covariance'in a else None\r\n if V is not None:\r\n  assert len(V)==len(rr)and all(len(z)==len(rr)for z in V);assert all(V[i][j]==V[j][i]for i in range(len(rr))for j in range(len(rr)));rank=psd(V)\r\n else:rank=None\r\n selected=[i for i,r in enumerate(rr)if r['time']>=r['cohort']and r['weight']>0];weights={}\r\n if a.get('type','simple')=='simple':\r\n  mass=sum((rr[i]['weight']for i in selected),Q(0));weights={i:rr[i]['weight']/mass for i in selected}if mass else{}\r\n else:\r\n  gg=defaultdict(list)\r\n  for i in selected:gg[rr[i]['cohort']].append(i)\r\n  assert all(len({rr[i]['weight']for i in ii})==1 for ii in gg.values());mass=sum((rr[ii[0]]['weight']for ii in gg.values()),Q(0));weights={i:rr[ii[0]]['weight']/mass/len(ii)for ii in gg.values()for i in ii}if mass else{}\r\n estimate=None if not weights or any(rr[i]['estimate']is None for i in weights)else sum((w*rr[i]['estimate']for i,w in weights.items()),Q(0));variance=None if estimate is None or V is None else sum((x*y*V[i][j]for i,x in weights.items()for j,y in weights.items()),Q(0))\r\n return dict(type=a.get('type','simple'),defined=estimate is not None,estimate=estimate,variance=variance,covarianceRank=rank,weights=[dict(sourceIndex=i,cohort=rr[i]['cohort'],time=rr[i]['time'],coefficient=w,estimate=rr[i]['estimate'],contribution=None if rr[i]['estimate']is None else w*rr[i]['estimate'])for i,w in weights.items()],cells=rr,covariance=V)\r\ndef sensitivity_fixed(a):\r\n estimate=Q(a['estimate']);M=Q(a['M']);h=a.get('horizon',1);assert M>=0 and h>=1\r\n pre=[Q(v)for v in a.get('preDifferences',[])];scale=Q(a['scale'])if 'scale'in a else max(map(abs,pre))if pre else None;budget=None if scale is None else M*scale*h\r\n return dict(defined=scale is not None,estimate=estimate,scale=scale,M=M,horizon=h,biasBudget=budget,lower=None if budget is None else estimate-budget,upper=None if budget is None else estimate+budget,preDifferences=pre,confidenceLevel=None)\r\ndef realdata_fixed(kind,data):\r\n models,raw=source(data);rows=models[kind];G=panel(rows);times=sorted({r['time']for r in rows});step=STEP[kind];aa=att_projection(rows,'never',step);post=[r for r in aa['cells']if r['phase']=='post'];aggs=aggregate(post,covariance(post),step);tf=twfe(G,times)\r\n return dict(kind=kind,unit=UNIT[kind],periodUnit=CLOCK[kind],nativeRows=len(raw[kind]),modelRows=len(rows),entities=len(G),sourceRows=rows,att=aa,aggregations=aggs,twfe=tf,scope='Complete source frame; never-treated comparison,universal baseline,no anticipation. Native/model/paired/balanced denominators differ. All sampling/causal assumptions remain separate.')\r\ndef encode(v):\r\n if isinstance(v,Q):return str(v)\r\n if isinstance(v,dict):return{str(k):encode(x)for k,x in v.items()}\r\n if isinstance(v,(list,tuple)):return[encode(x)for x in v]\r\n return v\r\ndef v9(v):\r\n if v is None:return'undefined'\r\n if isinstance(v,str):return v\r\n if isinstance(v,bool):return'1'if v else'0'\r\n return format(float(v),'.9g')\r\ndef run_fixed(spec,out,data):\r\n api=spec['api'];a=spec['input'];summary={};points=[]\r\n def emit(series,x,y):points.append(dict(series=series,x=x,y=y,numericY=safe_float(y)))\r\n if api=='twobytwo':\r\n  result=paired(a['treated'],a['control']);summary=dict(defined=result['defined'],estimate=result['estimate'],treatedPairs=result['treated']['eligiblePairs'],controlPairs=result['control']['eligiblePairs'],unbiasedVariance=result['unbiasedVariance'],HC0=result['HC0'])\r\n  for i,r in enumerate(result['rows']):emit(r['role']+':'+r['id'],i+1,r['change'])\r\n elif api=='att':\r\n  result=att_projection(literal_panel(a['rows']),a.get('control','never'));summary=dict(sourceRows=result['sourceRows'],entities=result['sourceEntities'],cells=len(result['cells']),supportedCells=sum(r['defined']for r in result['cells']),postCells=sum(r['phase']=='post'for r in result['cells']))\r\n  for i,r in enumerate(result['cells']):emit('g'+str(r['g'])+':t'+str(r['t']),i+1,r['estimate'])\r\n elif api=='aggregate':\r\n  result=linear_aggregate(a);summary=dict(defined=result['defined'],estimate=result['estimate'],variance=result['variance'],covarianceRank=result['covarianceRank'],sumWeights=sum((r['coefficient']for r in result['weights']),Q(0)))\r\n  for i,r in enumerate(result['weights']):emit('g'+str(r['cohort'])+':t'+str(r['time']),i+1,r['contribution'])\r\n elif api=='twfe':\r\n  rows=literal_panel(a['rows']);G=panel(rows);result=twfe(G,sorted({r['time']for r in rows}));summary=dict(defined=result['beta']is not None,beta=result['beta'],numerator=result['num'],denominator=result['den'],balancedEntities=result['balancedEntities'],negativeTreatedCells=sum(v['coefficient']is not None and v['coefficient']<0 for v in result['weights'].values()))\r\n  for i,((g,t),r)in enumerate(sorted(result['weights'].items())):emit('g'+str(g)+':t'+str(t),i+1,r['coefficient'])\r\n elif api=='sensitivity':\r\n  result=sensitivity_fixed(a);summary={k:result[k]for k in['defined','estimate','scale','M','horizon','biasBudget','lower','upper']}\r\n  for i,k in enumerate(['lower','estimate','upper']):emit(k,i+1,result[k]if result['defined']else None)\r\n else:\r\n  result=realdata_fixed(a['kind'],data);post=[r for r in result['att']['cells']if r['phase']=='post'];s=next(r for r in result['aggregations']if r['type']=='simple');g=next(r for r in result['aggregations']if r['type']=='group'and r['key']=='overall');summary=dict(nativeRows=result['nativeRows'],modelRows=result['modelRows'],entities=result['entities'],postCells=len(post),simple=s['estimate'],group=g['estimate'],TWFE=result['twfe']['beta'],balancedEntities=result['twfe']['balancedEntities'])\r\n  for i,r in enumerate(post):emit('g'+str(r['g'])+':t'+str(r['t']),i+1,r['estimate'])\r\n out.mkdir(parents=True,exist_ok=True)\r\n if any(out.iterdir()):raise ValueError('use-new-empty-output-directory')\r\n shown={k:v9(v)for k,v in summary.items()};write(out/'summary.csv',[dict(name=k,value=v)for k,v in shown.items()]);write(out/'points.csv',points,['series','x','y','numericY']);full=dict(chapter='METR-20',profile=spec['id'],api=api,input=spec['input'],summary=shown,points=encode(points),details=encode(result),arithmetic='Python Fraction exact finite stored values;summary/plot approximate;bounded teaching projection,not causal or sampling certification')\r\n (out/'full.json').write_text(json.dumps(full,ensure_ascii=False,indent=2,allow_nan=False)+'\\n',encoding='utf8')\r\n import matplotlib\r\n matplotlib.use('Agg')\r\n import matplotlib.pyplot as plt\r\n plt.rcParams.update({'svg.fonttype':'none','font.family':'DejaVu Sans','font.size':12,'axes.spines.top':False,'axes.spines.right':False});fig,ax=plt.subplots(figsize=(9,5.6));good=[r for r in points if r['numericY']is not None]\r\n if good:\r\n  ax.scatter([r['x']for r in good],[r['numericY']for r in good],color='#315d7c',s=32);ax.axhline(0,color='#9eabb2',lw=.8);ax.set_xlabel('Declared cell/unit/bound ordinal')\r\n else:ax.text(.5,.5,'Undefined: no supported plotted quantity',ha='center',va='center',transform=ax.transAxes);ax.set_xticks([]);ax.set_yticks([])\r\n ax.set_ylabel('Cell weight'if api=='twfe'else result.get('unit','Stated outcome/bias units'));ax.set_title(spec['title']['en'],wrap=True,pad=14);ax.grid(axis='y',alpha=.2);fig.tight_layout(pad=2);fig.savefig(out/'plot.svg');plt.close(fig);print(json.dumps(shown))\r\n\r\nSPEC={'id': 'realdata-person', 'api': 'realdata', 'title': {'ko': '실제 NSW 실험 표본 722명', 'en': 'Actual 722-person NSW experimental frame'}, 'input': {'kind': 'person', 'control': 'never'}, 'expectedReject': False}\r\nif __name__=='__main__':\r\n import sys\r\n run_fixed(SPEC,Path(sys.argv[1]),Path(sys.argv[2])if len(sys.argv)>2 else Path(__file__).resolve().parent.parent/'metr20-sources')\r\n",
      "arithmetic": "Python Fraction exact stored finite values;logs/summary/plots approximate",
      "summary": {
        "nativeRows": "38408",
        "modelRows": "1444",
        "entities": "722",
        "postCells": "1",
        "simple": "846.888361",
        "group": "846.888361",
        "TWFE": "846.888361",
        "balancedEntities": "722"
      },
      "fullResultEmbedded": false,
      "plotEmbedded": false,
      "full": {
        "summary": {
          "nativeRows": "38408",
          "modelRows": "1444",
          "entities": "722",
          "postCells": "1",
          "simple": "846.888361",
          "group": "846.888361",
          "TWFE": "846.888361",
          "balancedEntities": "722"
        },
        "notice": "Complete source/finite projection is retained in the linked external JSON; this short projection is not the full result."
      },
      "plot": null,
      "points": [
        {
          "series": "g1978:t1978",
          "x": 1,
          "y": "28022796009599/33089126400",
          "numericY": 846.888360570287
        }
      ],
      "summaryFile": "metr20-programs/realdata-person-python-summary.csv",
      "summarySHA256": "1adc3256316b3dc3d13a09f471bf2cc7af5ca0a2c77fe085694ab2ef06d08303",
      "pointsFile": "metr20-programs/realdata-person-python-points.csv",
      "pointsSHA256": "deafaef2d9dad326a0bcc9db6e6e3ac5273dc5ef8c38de648c09ba91aa3646ba",
      "fullResultFile": "metr20-programs/realdata-person-python.json",
      "fullResultSHA256": "0d63c7401990984c2885800748c52f3cd15d01241ab9c1ff4fbf4361d778baa8",
      "plotFile": "metr20-programs/realdata-person-python.svg",
      "plotSHA256": "8cf6b2b05d7e37d79b24d9e169fc0cdfce5944250689b67b386cac9e26ccdf55"
    },
    {
      "api": "realdata",
      "variant": "realdata-person",
      "profile": "realdata-person",
      "language": "R",
      "file": "metr20-programs/realdata-person-r.R",
      "codeSHA256": "3024ac81aa7d9818ac403fbde7eade439ff9babb919892b286e125d69f4b1730",
      "returnCode": 0,
      "expectedRejection": false,
      "title": {
        "ko": "실제 NSW 실험 표본 722명",
        "en": "Actual 722-person NSW experimental frame"
      },
      "code": "# METR20 fixed example. Base R only, finite arithmetic approximate.\r\n# No JavaScript engine,model JSON,derived answer table,private module or internet.\r\noptions(stringsAsFactors=FALSE,digits=17)\r\nargv<-commandArgs(trailingOnly=TRUE);if(length(argv)<1L)stop('Supply a new empty output directory')\r\noutdir<-argv[1];script<-sub('^--file=','',commandArgs(FALSE)[grepl('^--file=',commandArgs(FALSE))][1]);here<-dirname(normalizePath(script,mustWork=TRUE));datadir<-if(length(argv)>=2L)argv[2]else file.path(here,'..','metr20-sources')\r\nunits<-c(country='log teen-employment points',person='recorded real earnings',company='FTE employees');clocks<-c(country='calendar year',person='calendar year',company='survey-wave index');steps<-c(country=1,person=3,company=1);files<-c(country='actual2500-county-mpdta-all6-fields.csv',person='actual38408-NSW-all15-fields.csv',company='actual410-NJPA-all46-fields.csv')\r\nnum<-function(s)ifelse(s=='.',NA_real_,as.numeric(s));mean0<-function(v)if(length(v))mean(v)else NA_real_;var0<-function(v)if(length(v)>1L)sum((v-mean(v))^2)/(length(v)-1L)else NA_real_\r\n\r\nSPEC<-list(id=\"realdata-person\",api=\"realdata\",title=list(ko=\"실제 NSW 실험 표본 722명\",en=\"Actual 722-person NSW experimental frame\"),input=list(kind=\"person\",control=\"never\"),expectedReject=FALSE)\r\npanel<-function(rows){G<-list();for(r in rows){key<-r$entity;u<-G[[key]];if(is.null(u))u<-list(g=r$g,rows=list());stopifnot(identical(u$g,r$g),is.null(u$rows[[as.character(r$time)]]));u$rows[[as.character(r$time)]]<-r;G[[key]]<-u};G}\r\ncell<-function(G,g,t,step,control){b<-g-step;members<-list();T<-C<-list();for(key in names(G)){u<-G[[key]];target<-!is.na(u$g)&&u$g==g;comp<-is.na(u$g)||(control=='notyet'&&!is.na(u$g)&&u$g>max(t,b));role<-if(target)'treated'else if(comp)'control'else'excluded-comparison';before<-u$rows[[as.character(b)]];after<-u$rows[[as.character(t)]];yb<-if(is.null(before))NA_real_ else before$y;ya<-if(is.null(after))NA_real_ else after$y;eligible<-role!='excluded-comparison'&&!is.na(yb)&&!is.na(ya);reason<-if(role=='excluded-comparison')'target-or-already-exposed-cohort-not-valid-control'else if(is.null(before))'baseline-source-row-absent'else if(is.null(after))'target-time-source-row-absent'else if(is.na(yb))'baseline-outcome-missing'else if(is.na(ya))'target-outcome-missing'else'';m<-list(entity=key,nativeID=u$rows[[1]]$nativeID,g=u$g,role=role,eligible=eligible,baselineSourceId=if(is.null(before))NA_character_ else before$id,targetSourceId=if(is.null(after))NA_character_ else after$id,before=yb,after=ya,change=if(eligible)ya-yb else NA_real_,reason=reason);members[[key]]<-m;if(eligible){if(role=='treated')T[[length(T)+1L]]<-m else C[[length(C)+1L]]<-m}}\r\n change<-function(a)vapply(a,function(r)r$change,0);d<-mean0(change(T));e<-mean0(change(C));estimate<-if(is.na(d)||is.na(e))NA_real_ else d-e;defined<-!is.na(estimate);scores<-setNames(rep(NA_real_,length(members)),names(members));for(key in names(members)){m<-members[[key]];s<-if(!defined)NA_real_ else if(!m$eligible)0 else if(m$role=='treated')(m$change-d)/length(T)else-(m$change-e)/length(C);m$score<-s;scores[key]<-s;members[[key]]<-m};st<-var0(change(T));sc<-var0(change(C));v<-if(is.na(st)||is.na(sc))NA_real_ else st/length(T)+sc/length(C);level<-function(a,k)mean0(vapply(a,function(r)r[[k]],0))\r\n list(g=g,t=t,baseline=b,event=(t-g)/step,phase=if(t==b)'mechanical-reference'else if(t>=g)'post'else'pre-placebo',defined=defined,estimate=estimate,T=T,C=C,members=members,scores=scores,HC0=if(defined)sum(scores^2)else NA_real_,unbiased=v,treatedMeanBefore=level(T,'before'),treatedMeanAfter=level(T,'after'),treatedMeanChange=d,controlMeanBefore=level(C,'before'),controlMeanAfter=level(C,'after'),controlMeanChange=e)\r\n}\r\ncovariance<-function(cells){n<-length(cells);V<-matrix(NA_real_,n,n);for(i in seq_len(n))for(j in seq_len(n))if(cells[[i]]$defined&&cells[[j]]$defined)V[i,j]<-sum(cells[[i]]$scores*cells[[j]]$scores);V}\r\naggregate_cells<-function(post,V,step){out<-list();push<-function(typ,key,ii,w){est<-if(!length(ii)||any(vapply(post[ii],function(z)is.na(z$estimate),TRUE)))NA_real_ else sum(w*vapply(post[ii],function(z)z$estimate,0));vv<-if(is.na(est)||anyNA(V[ii,ii,drop=FALSE]))NA_real_ else as.numeric(t(w)%*%V[ii,ii,drop=FALSE]%*%w);out[[length(out)+1L]]<<-list(type=typ,key=as.character(key),ii=ii,w=w,estimate=est,variance=vv)};positive<-which(vapply(post,function(c)length(c$T)>0L,TRUE));mass<-sum(vapply(post[positive],function(c)length(c$T),0));push('simple','overall',positive,if(mass)vapply(post[positive],function(c)length(c$T)/mass,0)else numeric())\r\n for(typ in c('event','calendar','group')){keys<-vapply(post,function(c)if(typ=='event')c$event else if(typ=='calendar')c$t else c$g,0);gg<-sort(unique(keys));cohortmass<-if(typ=='group')sum(vapply(gg,function(k)length(post[[which(keys==k)[1]]]$T),0))else 0;allii<-integer();allw<-numeric();for(key in gg){ii<-which(keys==key);jj<-ii[vapply(post[ii],function(c)length(c$T)>0L,TRUE)];if(typ=='group'){stopifnot(length(unique(vapply(post[ii],function(c)length(c$T),0)))<=1L);w<-if(length(jj))rep(1/length(jj),length(jj))else numeric();if(cohortmass){allii<-c(allii,jj);allw<-c(allw,w*length(post[[ii[1]]]$T)/cohortmass)}}else{total<-sum(vapply(post[jj],function(c)length(c$T),0));w<-if(total)vapply(post[jj],function(c)length(c$T)/total,0)else numeric()};push(typ,key,jj,w)};if(typ=='group')push(typ,'overall',allii,allw)};out}\r\ntwfe<-function(G,times){ledger<-list();good<-list();for(key in names(G)){u<-G[[key]];absent<-times[!as.character(times)%in%names(u$rows)];missing<-times[vapply(times,function(t){r<-u$rows[[as.character(t)]];!is.null(r)&&is.na(r$y)},TRUE)];eligible<-length(times)>0L&&!length(absent)&&!length(missing);ledger[[length(ledger)+1L]]<-list(entity=key,g=u$g,nativeID=u$rows[[1]]$nativeID,eligible=eligible,absentTimes=paste(absent,collapse=','),missingOutcomeTimes=paste(missing,collapse=','),originalRows=length(u$rows));if(eligible)good[[key]]<-u};rows<-list();for(key in names(good))for(t in times){r<-good[[key]]$rows[[as.character(t)]];r$D<-as.integer(!is.na(r$g)&&t>=r$g);rows[[length(rows)+1L]]<-r};em<-lapply(good,function(u)list(D=mean(vapply(times,function(t)as.integer(!is.na(u$g)&&t>=u$g),0)),Y=mean(vapply(u$rows[as.character(times)],function(r)r$y,0))));tm<-lapply(times,function(t)list(D=mean(vapply(good,function(u)as.integer(!is.na(u$g)&&t>=u$g),0)),Y=mean(vapply(good,function(u)u$rows[[as.character(t)]]$y,0))));names(tm)<-as.character(times);gd<-mean0(vapply(rows,function(r)r$D,0));gy<-mean0(vapply(rows,function(r)r$y,0));num<-den<-0\r\n for(i in seq_along(rows)){r<-rows[[i]];r$residualD<-r$D-em[[r$entity]]$D-tm[[as.character(r$time)]]$D+gd;r$residualY<-r$y-em[[r$entity]]$Y-tm[[as.character(r$time)]]$Y+gy;num<-num+r$residualD*r$residualY;den<-den+r$residualD^2;rows[[i]]<-r};beta<-if(den!=0)num/den else NA_real_;weights<-list();for(i in seq_along(rows)){r<-rows[[i]];r$projectionCoefficient<-if(den!=0)r$residualD/den else NA_real_;r$regressionResidual<-if(!is.na(beta))r$residualY-beta*r$residualD else NA_real_;rows[[i]]<-r;if(r$D==1L){k<-paste(r$g,r$time,sep=':');z<-weights[[k]];if(is.null(z))z<-list(g=r$g,t=r$time,rows=0,coefficient=if(den!=0)0 else NA_real_);z$rows<-z$rows+1L;if(den!=0)z$coefficient<-z$coefficient+r$projectionCoefficient;weights[[k]]<-z}};list(ledger=ledger,rows=rows,num=num,den=den,beta=beta,weights=weights,balancedEntities=length(good))}\r\nadjacent_pre<-function(G,g,t,step,control){b<-t-step;T<-C<-numeric();for(u in G){target<-!is.na(u$g)&&u$g==g;comp<-is.na(u$g)||(control=='notyet'&&!is.na(u$g)&&u$g>max(t,b));if(!target&&!comp)next;before<-u$rows[[as.character(b)]];after<-u$rows[[as.character(t)]];if(!is.null(before)&&!is.null(after)&&!is.na(before$y)&&!is.na(after$y)){if(target)T<-c(T,after$y-before$y)else C<-c(C,after$y-before$y)}};if(!length(T)||!length(C))NA_real_ else mean(T)-mean(C)}\r\n\r\n# Newly authored bounded teaching projections; base R finite approximation.\r\n# Source helper functions are inlined in each public file, never imported.\r\nqnum<-function(v){if(is.null(v)||is.na(v))return(NA_real_);s<-strsplit(as.character(v),'/',fixed=TRUE)[[1]];if(length(s)==1L)as.numeric(s)else as.numeric(s[1])/as.numeric(s[2])}\r\npaired<-function(T,C){\r\n stats<-function(rr){use<-Filter(function(r)!is.na(qnum(r$before))&&!is.na(qnum(r$after)),rr);a<-vapply(use,function(r)qnum(r$before),0);b<-vapply(use,function(r)qnum(r$after),0);list(sourcePairs=length(rr),eligiblePairs=length(use),excludedPairs=length(rr)-length(use),meanBefore=mean0(a),meanAfter=mean0(b),meanChange=mean0(b-a),sampleChangeVariance=var0(b-a))}\r\n st<-stats(T);sc<-stats(C);defined<-st$eligiblePairs>0L&&sc$eligiblePairs>0L;estimate<-if(defined)st$meanChange-sc$meanChange else NA_real_;rr<-list()\r\n for(role in c('treated','control')){input<-if(role=='treated')T else C;s<-if(role=='treated')st else sc;for(r in input){before<-qnum(r$before);after<-qnum(r$after);eligible<-!is.na(before)&&!is.na(after);change<-if(eligible)after-before else NA_real_;score<-if(!defined)NA_real_ else if(!eligible)0 else (change-s$meanChange)/(if(role=='treated')s$eligiblePairs else -s$eligiblePairs);rr[[length(rr)+1L]]<-list(id=r$id,role=role,before=before,after=after,eligible=eligible,change=change,score=score)}}\r\n list(defined=defined,estimate=estimate,treated=st,control=sc,unbiasedVariance=if(defined&&st$eligiblePairs>=2L&&sc$eligiblePairs>=2L)st$sampleChangeVariance/st$eligiblePairs+sc$sampleChangeVariance/sc$eligiblePairs else NA_real_,HC0=if(defined)sum(vapply(rr,function(r)r$score^2,0))else NA_real_,rows=rr)\r\n}\r\nliteral_panel<-function(rr)lapply(seq_along(rr),function(i){r<-rr[[i]];r$y<-qnum(r$y);r$nativeID<-r$entity;r$sourceRow<-i;r})\r\natt_projection<-function(rows,control='never',step=1){G<-panel(rows);times<-sort(unique(vapply(rows,function(r)r$time,0)));cohorts<-sort(unique(na.omit(vapply(rows,function(r)r$g,0))));cells<-list();for(g in cohorts)for(t in times)cells[[length(cells)+1L]]<-cell(G,g,t,step,control);list(sourceRows=length(rows),sourceEntities=length(G),step=step,control=control,cells=cells,covariance=covariance(cells))}\r\nlinear_aggregate<-function(a){\r\n rr<-lapply(a$cells,function(r){r$estimate<-qnum(r$estimate);r$weight<-qnum(r$weight);r});V<-if(is.null(a$covariance))NULL else do.call(rbind,lapply(a$covariance,function(r)vapply(r,qnum,0)));rank<-NA_real_\r\n if(!is.null(V)){stopifnot(nrow(V)==length(rr),ncol(V)==length(rr),all(V==t(V)));ev<-eigen(V,symmetric=TRUE,only.values=TRUE)$values;if(any(ev< -1e-12))stop('covariance-must-be-positive-semidefinite');rank<-sum(ev>1e-12)}\r\n selected<-which(vapply(rr,function(r)r$time>=r$cohort&&r$weight>0,TRUE));w<-numeric(length(rr));type<-if(is.null(a$type))'simple'else a$type\r\n if(type=='simple'){mass<-sum(vapply(rr[selected],function(r)r$weight,0));if(mass>0)for(i in selected)w[i]<-rr[[i]]$weight/mass}else{g<-vapply(rr,function(r)r$cohort,0);gg<-sort(unique(g[selected]));mass<-sum(vapply(gg,function(gi)rr[[intersect(which(g==gi),selected)[1]]]$weight,0));for(gi in gg){ii<-intersect(which(g==gi),selected);stopifnot(length(unique(vapply(rr[ii],function(r)r$weight,0)))==1L);w[ii]<-rr[[ii[1]]]$weight/mass/length(ii)}}\r\n used<-which(w>0);estimate<-if(!length(used)||any(vapply(rr[used],function(r)is.na(r$estimate),TRUE)))NA_real_ else sum(w[used]*vapply(rr[used],function(r)r$estimate,0));variance<-if(is.na(estimate)||is.null(V))NA_real_ else as.numeric(t(w)%*%V%*%w);weights<-lapply(used,function(i)list(sourceIndex=i-1L,cohort=rr[[i]]$cohort,time=rr[[i]]$time,coefficient=w[i],estimate=rr[[i]]$estimate,contribution=w[i]*rr[[i]]$estimate))\r\n list(type=type,defined=!is.na(estimate),estimate=estimate,variance=variance,covarianceRank=rank,weights=weights,cells=rr,covariance=V)\r\n}\r\nsensitivity_fixed<-function(a){estimate<-qnum(a$estimate);M<-qnum(a$M);h<-if(is.null(a$horizon))1 else a$horizon;stopifnot(M>=0,h>=1);pre<-vapply(a$preDifferences,qnum,0);scale<-if(!is.null(a$scale))qnum(a$scale)else if(length(pre))max(abs(pre))else NA_real_;budget<-M*scale*h;list(defined=!is.na(scale),estimate=estimate,scale=scale,M=M,horizon=h,biasBudget=budget,lower=estimate-budget,upper=estimate+budget,preDifferences=as.list(pre),confidenceLevel=NULL)}\r\nrealdata_fixed<-function(kind){rows<-models[[kind]];G<-panel(rows);times<-sort(unique(vapply(rows,function(r)r$time,0)));step<-unname(steps[kind]);aa<-att_projection(rows,'never',step);post<-Filter(function(r)r$phase=='post',aa$cells);aggs<-aggregate_cells(post,covariance(post),step);tf<-twfe(G,times);list(kind=kind,unit=unname(units[kind]),periodUnit=unname(clocks[kind]),nativeRows=nrow(raw[[kind]]),modelRows=length(rows),entities=length(G),sourceRows=rows,att=aa,aggregations=aggs,twfe=tf,scope='Complete native/model/paired/balanced source frames; never control,universal base,no anticipation;not causal/sampling certification.')}\r\n# JSON encoder deliberately handles matrices and scalar/vector distinctions.\r\nencode<-function(x){\r\n if(is.null(x))return('null')\r\n quote<-function(s){s<-gsub('\\\\','\\\\\\\\',as.character(s),fixed=TRUE);s<-gsub('\"','\\\\\"',s,fixed=TRUE);s<-gsub('\\n','\\\\n',s,fixed=TRUE);s<-gsub('\\r','\\\\r',s,fixed=TRUE);s<-gsub('\\t','\\\\t',s,fixed=TRUE);paste0('\"',s,'\"')}\r\n if(is.matrix(x))return(paste0('[',paste(vapply(seq_len(nrow(x)),function(i)encode(as.list(unname(x[i,]))),''),collapse=','),']'))\r\n if(is.list(x)){if(length(x)&&!is.null(names(x)))return(paste0('{',paste(paste0(vapply(names(x),quote,''),':',vapply(x,encode,'')),collapse=','),'}'));return(paste0('[',paste(vapply(x,encode,''),collapse=','),']'))}\r\n if(length(x)!=1L)return(encode(as.list(unname(x))))\r\n if(is.na(x))return('null');if(is.logical(x))return(if(x)'true'else'false');if(is.numeric(x))return(sprintf('%.17g',unname(x)));quote(x)\r\n}\r\nv9<-function(x){if(is.null(x)||is.na(x))return('undefined');if(is.logical(x))return(if(x)'1'else'0');if(is.numeric(x))return(sprintf('%.9g',unname(x)));as.character(x)}\r\nrun_fixed<-function(spec,out){api<-spec$api;a<-spec$input;summary<-list();points<-list();emit<-function(series,x,y){points[[length(points)+1L]]<<-list(series=series,x=x,y=y,numericY=y)}\r\n if(api=='twobytwo'){result<-paired(a$treated,a$control);summary<-list(defined=result$defined,estimate=result$estimate,treatedPairs=result$treated$eligiblePairs,controlPairs=result$control$eligiblePairs,unbiasedVariance=result$unbiasedVariance,HC0=result$HC0);for(i in seq_along(result$rows)){r<-result$rows[[i]];emit(paste(r$role,r$id,sep=':'),i,r$change)}}\r\n else if(api=='att'){result<-att_projection(literal_panel(a$rows),a$control);summary<-list(sourceRows=result$sourceRows,entities=result$sourceEntities,cells=length(result$cells),supportedCells=sum(vapply(result$cells,function(r)r$defined,TRUE)),postCells=sum(vapply(result$cells,function(r)r$phase=='post',TRUE)));for(i in seq_along(result$cells)){r<-result$cells[[i]];emit(paste0('g',r$g,':t',r$t),i,r$estimate)}}\r\n else if(api=='aggregate'){result<-linear_aggregate(a);summary<-list(defined=result$defined,estimate=result$estimate,variance=result$variance,covarianceRank=result$covarianceRank,sumWeights=sum(vapply(result$weights,function(r)r$coefficient,0)));for(i in seq_along(result$weights)){r<-result$weights[[i]];emit(paste0('g',r$cohort,':t',r$time),i,r$contribution)}}\r\n else if(api=='twfe'){rows<-literal_panel(a$rows);G<-panel(rows);result<-twfe(G,sort(unique(vapply(rows,function(r)r$time,0))));summary<-list(defined=!is.na(result$beta),beta=result$beta,numerator=result$num,denominator=result$den,balancedEntities=result$balancedEntities,negativeTreatedCells=sum(vapply(result$weights,function(r)!is.na(r$coefficient)&&r$coefficient<0,TRUE)));if(length(result$weights)){ord<-order(vapply(result$weights,function(r)r$g,0),vapply(result$weights,function(r)r$t,0));for(i in seq_along(ord)){r<-result$weights[[ord[i]]];emit(paste0('g',r$g,':t',r$t),i,r$coefficient)}}}\r\n else if(api=='sensitivity'){result<-sensitivity_fixed(a);summary<-result[c('defined','estimate','scale','M','horizon','biasBudget','lower','upper')];for(i in seq_along(c('lower','estimate','upper'))){k<-c('lower','estimate','upper')[i];emit(k,i,if(result$defined)result[[k]]else NA_real_)}}\r\n else{result<-realdata_fixed(a$kind);post<-Filter(function(r)r$phase=='post',result$att$cells);simple<-Filter(function(r)r$type=='simple',result$aggregations)[[1]];group<-Filter(function(r)r$type=='group'&&r$key=='overall',result$aggregations)[[1]];summary<-list(nativeRows=result$nativeRows,modelRows=result$modelRows,entities=result$entities,postCells=length(post),simple=simple$estimate,group=group$estimate,TWFE=result$twfe$beta,balancedEntities=result$twfe$balancedEntities);for(i in seq_along(post)){r<-post[[i]];emit(paste0('g',r$g,':t',r$t),i,r$estimate)}}\r\n dir.create(out,recursive=TRUE,showWarnings=FALSE);if(length(list.files(out,all.files=TRUE,no..=TRUE)))stop('use-new-empty-output-directory');shown<-lapply(summary,v9);write.csv(data.frame(name=names(shown),value=unlist(shown,use.names=FALSE)),file.path(out,'summary.csv'),row.names=FALSE,na='');pointframe<-if(length(points))do.call(rbind,lapply(points,function(p)data.frame(series=p$series,x=p$x,y=p$y,numericY=p$numericY,stringsAsFactors=FALSE)))else data.frame(series=character(),x=numeric(),y=numeric(),numericY=numeric());write.csv(pointframe,file.path(out,'points.csv'),row.names=FALSE,na='');full<-list(chapter='METR-20',profile=spec$id,api=api,input=spec$input,summary=shown,points=points,details=result,arithmetic='Base R approximate finite values;bounded teaching projection,not exact fractions or causal/sampling certification.');writeLines(encode(full),file.path(out,'full.json'),useBytes=TRUE)\r\n svg(file.path(out,'plot.svg'),width=9,height=5.6,pointsize=12);par(mar=c(4.5,5.5,4,1));good<-pointframe[!is.na(pointframe$numericY),,drop=FALSE]\r\n if(nrow(good)){plot(good$x,good$numericY,pch=19,col='#315d7c',xlab='Declared cell/unit/bound ordinal',ylab=if(api=='twfe')'Cell weight'else if(!is.null(result$unit))result$unit else 'Stated outcome/bias units',main=spec$title$en);abline(h=0,col='#9eabb2');grid(nx=NA,ny=NULL,col='#e2e5e7');points(good$x,good$numericY,pch=19,col='#315d7c')}else{plot.new();text(.5,.5,'Undefined: no supported plotted quantity');title(main=spec$title$en)};dev.off();cat(encode(shown),'\\n')\r\n}\r\n\r\nraw<-lapply(files,function(n)read.csv(file.path(datadir,n),colClasses='character',check.names=FALSE,na.strings=character()));stopifnot(identical(vapply(raw,nrow,0L),c(country=2500L,person=38408L,company=410L)))\r\nmodels<-list(country=list(),person=list(),company=list())\r\nfor(i in seq_len(nrow(raw$country))){r<-raw$country[i,];g<-as.integer(r$first.treat);if(!g)g<-NA_integer_;stopifnot(as.integer(r$treat)==as.integer(!is.na(g)));models$country[[i]]<-list(id=paste0('mpdta:',r$sourceRow),entity=paste0('county:',as.integer(r$countyreal)),time=as.integer(r$year),y=num(r$lemp),g=g,sourceRow=as.integer(r$sourceRow),nativeID=r$countyreal)}\r\nfor(i in seq_len(nrow(raw$person))){r<-raw$person[i,];selected<-as.integer(r$experimental)==1L;stopifnot(selected==(as.integer(r$sample)==1L),(r$treated!='.')==selected);if(selected){d<-as.integer(r$treated);stopifnot(d%in%0:1);models$person[[length(models$person)+1L]]<-list(id=paste0('nsw:',r$sourceRow),entity=paste0('nsw-id:',as.integer(r$id)),time=as.integer(r$year),y=num(r$re),g=if(d==1L)1978L else NA_integer_,sourceRow=as.integer(r$sourceRow),nativeID=as.character(as.integer(r$id)))}}\r\nfor(i in seq_len(nrow(raw$company))){r<-raw$company[i,];state<-as.integer(r$STATE);stopifnot(state%in%0:1);for(t in 0:1){suffix<-if(t==0)''else'2';v<-vapply(paste0(c('EMPFT','NMGRS','EMPPT'),suffix),function(k)num(r[[k]]),0);y<-if(anyNA(v))NA_real_ else v[1]+v[2]+v[3]/2;models$company[[length(models$company)+1L]]<-list(id=paste0('njpa:',r$sourceRow,':wave',t),entity=paste0('njpa-row:',r$sourceRow),time=t,y=unname(y),g=if(state==1L)1L else NA_integer_,sourceRow=as.integer(r$sourceRow),nativeID=r$SHEET)}}\r\nstopifnot(identical(vapply(models,length,0L),c(country=2500L,person=1444L,company=820L)))\r\n\r\nrun_fixed(SPEC,outdir)\r\n",
      "arithmetic": "Base R approximate finite arithmetic;not an exact rational result",
      "summary": {
        "nativeRows": "38408",
        "modelRows": "1444",
        "entities": "722",
        "postCells": "1",
        "simple": "846.888361",
        "group": "846.888361",
        "TWFE": "846.888361",
        "balancedEntities": "722"
      },
      "fullResultEmbedded": false,
      "plotEmbedded": false,
      "full": {
        "summary": {
          "nativeRows": "38408",
          "modelRows": "1444",
          "entities": "722",
          "postCells": "1",
          "simple": "846.888361",
          "group": "846.888361",
          "TWFE": "846.888361",
          "balancedEntities": "722"
        },
        "notice": "Complete source/finite projection is retained in the linked external JSON; this short projection is not the full result."
      },
      "plot": null,
      "points": [
        {
          "series": "g1978:t1978",
          "x": 1,
          "y": 846.8883605702867,
          "numericY": 846.8883605702867
        }
      ],
      "summaryFile": "metr20-programs/realdata-person-r-summary.csv",
      "summarySHA256": "e8b4c01f69f8d475b0749cb7da3265fd35760401fe0d2b717fc1896cd7ebd713",
      "pointsFile": "metr20-programs/realdata-person-r-points.csv",
      "pointsSHA256": "8b0eaf9a07cf08ec739552e4219976b504206f9b146e648a05a06f4760d93715",
      "fullResultFile": "metr20-programs/realdata-person-r.json",
      "fullResultSHA256": "a7fb36ebdbc4f7eede2557156929700ebf8ab1ac47fe337314c4463eabd45282",
      "plotFile": "metr20-programs/realdata-person-r.svg",
      "plotSHA256": "63edb4b7daa05bd7f2fccd55357b5fb2d8a0b74aee532c8d9631c21770fc7309"
    },
    {
      "api": "realdata",
      "variant": "realdata-company",
      "profile": "realdata-company",
      "language": "Python",
      "file": "metr20-programs/realdata-company-python.py",
      "codeSHA256": "2948290a0257e23cd344056f91a3bafc180444e305010048375eb1db879a6395",
      "returnCode": 0,
      "expectedRejection": false,
      "title": {
        "ko": "실제 NJPA 410개 원 점포행",
        "en": "Actual 410-record NJPA source frame"
      },
      "code": "\"\"\"METR20 actual sources. Python standard library, exact stored-value rationals.\r\nRead ONLY the three native-observation CSVs; no JS engine,model JSON,derived\r\nanswers,private modules or internet needed. Outcome measurement/identification\r\nand valid sampling inference remain separate from exact finite arithmetic.\r\nRun: python metr20-reproduce.py --data-dir PATH --out NEW_EMPTY_DIRECTORY\r\n\"\"\"\r\nfrom pathlib import Path\r\nfrom fractions import Fraction as Q\r\nfrom collections import defaultdict,Counter\r\nimport csv,json,math,argparse,hashlib\r\n\r\nUNIT={'country':'log teen-employment points','person':'recorded real earnings','company':'FTE employees'}\r\nCLOCK={'country':'calendar year','person':'calendar year','company':'survey-wave index'}\r\nSTEP={'country':1,'person':3,'company':1}\r\nFILES={'country':'actual2500-county-mpdta-all6-fields.csv','person':'actual38408-NSW-all15-fields.csv','company':'actual410-NJPA-all46-fields.csv'}\r\ndef avg(v):return sum(v,Q(0))/len(v)if v else None\r\ndef samplevar(v):return sum(((x-avg(v))**2 for x in v),Q(0))/(len(v)-1)if len(v)>1 else None\r\ndef binary(s):return None if s=='.'else Q.from_float(float(s))\r\ndef token(v):\r\n if v is None:return ''\r\n if isinstance(v,bool):return 'true'if v else'false'\r\n return str(v)\r\ndef safe_float(v):\r\n if v is None:return None\r\n try:r=float(v)\r\n except OverflowError:return None\r\n return r if math.isfinite(r)else None\r\ndef read(p):\r\n with p.open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))\r\ndef write(p,rows,head=None):\r\n if head is None:\r\n  assert rows;head=list(rows[0])\r\n with p.open('w',encoding='utf8',newline='')as f:\r\n  w=csv.DictWriter(f,fieldnames=head);w.writeheader();w.writerows({k:token(r.get(k))for k in head}for r in rows)\r\ndef source(data):\r\n raw={k:read(data/n)for k,n in FILES.items()};assert[len(raw[k])for k in FILES]==[2500,38408,410]\r\n models={k:[]for k in FILES}\r\n for r in raw['country']:\r\n  g0=int(r['first.treat']);g=None if g0==0 else g0;assert int(r['treat'])==int(g is not None)\r\n  models['country'].append(dict(id='mpdta:'+r['sourceRow'],entity='county:'+str(int(r['countyreal'])),time=int(r['year']),y=binary(r['lemp']),g=g,sourceRow=int(r['sourceRow']),nativeID=r['countyreal']))\r\n for r in raw['person']:\r\n  selected=int(r['experimental'])==1;assert selected==(int(r['sample'])==1);assert(r['treated']!='.')==selected\r\n  if selected:\r\n   d=int(r['treated']);assert d in[0,1]\r\n   models['person'].append(dict(id='nsw:'+r['sourceRow'],entity='nsw-id:'+str(int(r['id'])),time=int(r['year']),y=binary(r['re']),g=1978 if d else None,sourceRow=int(r['sourceRow']),nativeID=str(int(r['id']))))\r\n for r in raw['company']:\r\n  state=int(r['STATE']);assert state in[0,1]\r\n  for t,suffix in[(0,''),(1,'2')]:\r\n   a=[r[n+suffix]for n in['EMPFT','NMGRS','EMPPT']];y=None if'.'in a else Q(a[0])+Q(a[1])+Q(a[2])/2\r\n   models['company'].append(dict(id='njpa:'+r['sourceRow']+':wave'+str(t),entity='njpa-row:'+r['sourceRow'],time=t,y=y,g=1 if state else None,sourceRow=int(r['sourceRow']),nativeID=r['SHEET']))\r\n assert[len(models[k])for k in FILES]==[2500,1444,820]\r\n return models,raw\r\ndef panel(rows):\r\n groups={}\r\n for r in rows:\r\n  u=groups.setdefault(r['entity'],{'g':r['g'],'rows':{}});assert u['g']==r['g']and r['time']not in u['rows'];u['rows'][r['time']]=r\r\n return groups\r\ndef cell(groups,g,t,step,control):\r\n b=g-step;members=[];T=[];C=[]\r\n for key,u in groups.items():\r\n  role='treated'if u['g']==g else'control'if u['g']is None or(control=='notyet'and u['g']>max(t,b))else'excluded-comparison'\r\n  before=u['rows'].get(b);after=u['rows'].get(t);yb=None if before is None else before['y'];ya=None if after is None else after['y'];eligible=role!='excluded-comparison'and yb is not None and ya is not None\r\n  reason='target-or-already-exposed-cohort-not-valid-control'if role=='excluded-comparison'else'baseline-source-row-absent'if before is None else'target-time-source-row-absent'if after is None else'baseline-outcome-missing'if yb is None else'target-outcome-missing'if ya is None else''\r\n  m={'entity':key,'nativeID':next(iter(u['rows'].values()))['nativeID'],'g':u['g'],'role':role,'eligible':eligible,'baselineSourceId':None if before is None else before['id'],'targetSourceId':None if after is None else after['id'],'before':yb,'after':ya,'change':ya-yb if eligible else None,'reason':reason};members.append(m)\r\n  if eligible:(T if role=='treated'else C).append(m)\r\n d=avg([r['change']for r in T]);e=avg([r['change']for r in C]);estimate=None if d is None or e is None else d-e;defined=estimate is not None;scores={}\r\n for m in members:\r\n  s=None if not defined else Q(0)\r\n  if defined and m['eligible']:s=(m['change']-(d if m['role']=='treated'else e))/(len(T)if m['role']=='treated'else-len(C))\r\n  m['score']=s;scores[m['entity']]=s\r\n st=samplevar([r['change']for r in T]);sc=samplevar([r['change']for r in C]);v=None if st is None or sc is None else st/len(T)+sc/len(C)\r\n return {'g':g,'t':t,'baseline':b,'event':(t-g)//step,'phase':'mechanical-reference'if t==b else'post'if t>=g else'pre-placebo','defined':defined,'estimate':estimate,'T':T,'C':C,'members':members,'scores':scores,'HC0':None if not defined else sum((s*s for s in scores.values()),Q(0)),'unbiased':v,'treatedMeanBefore':avg([r['before']for r in T]),'treatedMeanAfter':avg([r['after']for r in T]),'treatedMeanChange':d,'controlMeanBefore':avg([r['before']for r in C]),'controlMeanAfter':avg([r['after']for r in C]),'controlMeanChange':e}\r\ndef covariance(cells):\r\n return[[None if not a['defined']or not b['defined']else sum((v*b['scores'][i]for i,v in a['scores'].items()),Q(0))for b in cells]for a in cells]\r\ndef aggregate(post,V,step):\r\n out=[]\r\n def push(typ,key,coeff):\r\n  estimate=None if not coeff or any(post[i]['estimate']is None for i in coeff)else sum((w*post[i]['estimate']for i,w in coeff.items()),Q(0));variance=None if estimate is None or any(V[i][j]is None for i in coeff for j in coeff)else sum((a*b*V[i][j]for i,a in coeff.items()for j,b in coeff.items()),Q(0));out.append({'type':typ,'key':key,'coeff':coeff,'estimate':estimate,'variance':variance})\r\n positive=[i for i,c in enumerate(post)if len(c['T'])>0];mass=sum(len(post[i]['T'])for i in positive)\r\n push('simple','overall',{i:Q(len(post[i]['T']),mass)for i in positive}if mass else{})\r\n for typ in['event','calendar','group']:\r\n  groups=defaultdict(list)\r\n  for i,c in enumerate(post):groups[c['event']if typ=='event'else c['t']if typ=='calendar'else c['g']].append(i)\r\n  overall={};cohortMass=sum(len(post[ii[0]]['T'])for ii in groups.values())if typ=='group'else 0\r\n  for key,ii in sorted(groups.items()):\r\n   jj=[i for i in ii if len(post[i]['T'])>0]\r\n   if typ=='group':\r\n    assert len({len(post[i]['T'])for i in ii})<=1\r\n    coeff={i:Q(1,len(jj))for i in jj}if jj else{}\r\n    if cohortMass:\r\n     for i,w in coeff.items():overall[i]=w*Q(len(post[ii[0]]['T']),cohortMass)\r\n   else:\r\n    total=sum(len(post[i]['T'])for i in jj);coeff={i:Q(len(post[i]['T']),total)for i in jj}if total else{}\r\n   push(typ,str(key),coeff)\r\n  if typ=='group':push(typ,'overall',overall)\r\n return out\r\ndef twfe(groups,times):\r\n ledger=[];good={}\r\n for key,u in groups.items():\r\n  absent=[t for t in times if t not in u['rows']];missing=[t for t in times if t in u['rows']and u['rows'][t]['y']is None];eligible=bool(times)and not absent and not missing\r\n  ledger.append({'entity':key,'g':u['g'],'nativeID':next(iter(u['rows'].values()))['nativeID'],'eligible':eligible,'absentTimes':','.join(map(str,absent)),'missingOutcomeTimes':','.join(map(str,missing)),'originalRows':len(u['rows'])})\r\n  if eligible:good[key]=u\r\n rows=[dict(**u['rows'][t],D=Q(u['g']is not None and t>=u['g']))for key,u in good.items()for t in times]\r\n em={k:{'D':avg([Q(u['g']is not None and t>=u['g'])for t in times]),'Y':avg([u['rows'][t]['y']for t in times])}for k,u in good.items()};tm={t:{'D':avg([Q(u['g']is not None and t>=u['g'])for u in good.values()]),'Y':avg([u['rows'][t]['y']for u in good.values()])}for t in times};gd=avg([r['D']for r in rows]);gy=avg([r['y']for r in rows]);num=den=Q(0)\r\n for r in rows:\r\n  r['residualD']=r['D']-em[r['entity']]['D']-tm[r['time']]['D']+gd;r['residualY']=r['y']-em[r['entity']]['Y']-tm[r['time']]['Y']+gy;num+=r['residualD']*r['residualY'];den+=r['residualD']**2\r\n beta=num/den if den else None;weights={}\r\n for r in rows:\r\n  r['projectionCoefficient']=r['residualD']/den if den else None;r['regressionResidual']=r['residualY']-beta*r['residualD']if beta is not None else None\r\n  if r['D']:\r\n   k=(r['g'],r['time']);z=weights.setdefault(k,{'rows':0,'coefficient':Q(0)if den else None});z['rows']+=1\r\n   if den:z['coefficient']+=r['projectionCoefficient']\r\n return {'ledger':ledger,'rows':rows,'num':num,'den':den,'beta':beta,'weights':weights,'balancedEntities':len(good)}\r\ndef adjacent_pre(groups,g,t,step,control):\r\n b=t-step;T=[];C=[]\r\n for u in groups.values():\r\n  if u['g']==g:target=T\r\n  elif u['g']is None or(control=='notyet'and u['g']>max(t,b)):target=C\r\n  else:continue\r\n  before=u['rows'].get(b);after=u['rows'].get(t)\r\n  if before is not None and after is not None and before['y']is not None and after['y']is not None:target.append(after['y']-before['y'])\r\n return None if not T or not C else avg(T)-avg(C)\r\n\r\n\"\"\"New bounded teaching projections. The program is self-contained after build.\r\nExact Fraction finite algebra; figures and9-digit summary are approximations.\r\nIt is not a general parser/API replacement or a causal/inference certificate.\r\n\"\"\"\r\ndef paired(treated,control):\r\n def stats(rr):\r\n  use=[r for r in rr if r['before']is not None and r['after']is not None];delta=[Q(r['after'])-Q(r['before'])for r in use]\r\n  return dict(sourcePairs=len(rr),eligiblePairs=len(use),excludedPairs=len(rr)-len(use),meanBefore=avg([Q(r['before'])for r in use]),meanAfter=avg([Q(r['after'])for r in use]),meanChange=avg(delta),sampleChangeVariance=samplevar(delta))\r\n T,C=stats(treated),stats(control);defined=T['eligiblePairs']>0 and C['eligiblePairs']>0;estimate=T['meanChange']-C['meanChange']if defined else None;records=[]\r\n for group,rr,s in [('treated',treated,T),('control',control,C)]:\r\n  for r in rr:\r\n   before=None if r['before']is None else Q(r['before']);after=None if r['after']is None else Q(r['after']);eligible=before is not None and after is not None;delta=after-before if eligible else None;score=None if not defined else Q(0)if not eligible else(delta-s['meanChange'])/(s['eligiblePairs']if group=='treated'else-s['eligiblePairs']);records.append(dict(id=r['id'],role=group,before=before,after=after,eligible=eligible,change=delta,score=score))\r\n unbiased=None if not defined or T['eligiblePairs']<2 or C['eligiblePairs']<2 else T['sampleChangeVariance']/T['eligiblePairs']+C['sampleChangeVariance']/C['eligiblePairs'];hc0=None if not defined else sum((r['score']**2 for r in records),Q(0))\r\n return dict(defined=defined,estimate=estimate,treated=T,control=C,unbiasedVariance=unbiased,HC0=hc0,rows=records)\r\ndef literal_panel(raw):\r\n return[dict(r,y=None if r['y']is None else Q(r['y']),nativeID=r['entity'],sourceRow=i+1)for i,r in enumerate(raw)]\r\ndef att_projection(rows,control='never',step=1):\r\n G=panel(rows);times=sorted({r['time']for r in rows});cohorts=sorted({r['g']for r in rows if r['g']is not None});cells=[cell(G,g,t,step,control)for g in cohorts for t in times]\r\n return dict(sourceRows=len(rows),sourceEntities=len(G),step=step,control=control,cells=cells,covariance=covariance(cells))\r\ndef psd(V):\r\n A=[r[:]for r in V];rank=0\r\n while A:\r\n  if any(A[i][i]<0 for i in range(len(A))):raise ValueError('covariance-must-be-positive-semidefinite')\r\n  p=next((i for i in range(len(A))if A[i][i]>0),None)\r\n  if p is None:\r\n   if any(v for r in A for v in r):raise ValueError('covariance-must-be-positive-semidefinite')\r\n   return rank\r\n  A[0],A[p]=A[p],A[0]\r\n  for r in A:r[0],r[p]=r[p],r[0]\r\n  d=A[0][0];A=[[A[i][j]-A[i][0]*A[0][j]/d for j in range(1,len(A))]for i in range(1,len(A))];rank+=1\r\n return rank\r\ndef linear_aggregate(a):\r\n rr=[dict(r,estimate=None if r['estimate']is None else Q(r['estimate']),weight=Q(r['weight']))for r in a['cells']];V=[[Q(v)for v in r]for r in a['covariance']]if 'covariance'in a else None\r\n if V is not None:\r\n  assert len(V)==len(rr)and all(len(z)==len(rr)for z in V);assert all(V[i][j]==V[j][i]for i in range(len(rr))for j in range(len(rr)));rank=psd(V)\r\n else:rank=None\r\n selected=[i for i,r in enumerate(rr)if r['time']>=r['cohort']and r['weight']>0];weights={}\r\n if a.get('type','simple')=='simple':\r\n  mass=sum((rr[i]['weight']for i in selected),Q(0));weights={i:rr[i]['weight']/mass for i in selected}if mass else{}\r\n else:\r\n  gg=defaultdict(list)\r\n  for i in selected:gg[rr[i]['cohort']].append(i)\r\n  assert all(len({rr[i]['weight']for i in ii})==1 for ii in gg.values());mass=sum((rr[ii[0]]['weight']for ii in gg.values()),Q(0));weights={i:rr[ii[0]]['weight']/mass/len(ii)for ii in gg.values()for i in ii}if mass else{}\r\n estimate=None if not weights or any(rr[i]['estimate']is None for i in weights)else sum((w*rr[i]['estimate']for i,w in weights.items()),Q(0));variance=None if estimate is None or V is None else sum((x*y*V[i][j]for i,x in weights.items()for j,y in weights.items()),Q(0))\r\n return dict(type=a.get('type','simple'),defined=estimate is not None,estimate=estimate,variance=variance,covarianceRank=rank,weights=[dict(sourceIndex=i,cohort=rr[i]['cohort'],time=rr[i]['time'],coefficient=w,estimate=rr[i]['estimate'],contribution=None if rr[i]['estimate']is None else w*rr[i]['estimate'])for i,w in weights.items()],cells=rr,covariance=V)\r\ndef sensitivity_fixed(a):\r\n estimate=Q(a['estimate']);M=Q(a['M']);h=a.get('horizon',1);assert M>=0 and h>=1\r\n pre=[Q(v)for v in a.get('preDifferences',[])];scale=Q(a['scale'])if 'scale'in a else max(map(abs,pre))if pre else None;budget=None if scale is None else M*scale*h\r\n return dict(defined=scale is not None,estimate=estimate,scale=scale,M=M,horizon=h,biasBudget=budget,lower=None if budget is None else estimate-budget,upper=None if budget is None else estimate+budget,preDifferences=pre,confidenceLevel=None)\r\ndef realdata_fixed(kind,data):\r\n models,raw=source(data);rows=models[kind];G=panel(rows);times=sorted({r['time']for r in rows});step=STEP[kind];aa=att_projection(rows,'never',step);post=[r for r in aa['cells']if r['phase']=='post'];aggs=aggregate(post,covariance(post),step);tf=twfe(G,times)\r\n return dict(kind=kind,unit=UNIT[kind],periodUnit=CLOCK[kind],nativeRows=len(raw[kind]),modelRows=len(rows),entities=len(G),sourceRows=rows,att=aa,aggregations=aggs,twfe=tf,scope='Complete source frame; never-treated comparison,universal baseline,no anticipation. Native/model/paired/balanced denominators differ. All sampling/causal assumptions remain separate.')\r\ndef encode(v):\r\n if isinstance(v,Q):return str(v)\r\n if isinstance(v,dict):return{str(k):encode(x)for k,x in v.items()}\r\n if isinstance(v,(list,tuple)):return[encode(x)for x in v]\r\n return v\r\ndef v9(v):\r\n if v is None:return'undefined'\r\n if isinstance(v,str):return v\r\n if isinstance(v,bool):return'1'if v else'0'\r\n return format(float(v),'.9g')\r\ndef run_fixed(spec,out,data):\r\n api=spec['api'];a=spec['input'];summary={};points=[]\r\n def emit(series,x,y):points.append(dict(series=series,x=x,y=y,numericY=safe_float(y)))\r\n if api=='twobytwo':\r\n  result=paired(a['treated'],a['control']);summary=dict(defined=result['defined'],estimate=result['estimate'],treatedPairs=result['treated']['eligiblePairs'],controlPairs=result['control']['eligiblePairs'],unbiasedVariance=result['unbiasedVariance'],HC0=result['HC0'])\r\n  for i,r in enumerate(result['rows']):emit(r['role']+':'+r['id'],i+1,r['change'])\r\n elif api=='att':\r\n  result=att_projection(literal_panel(a['rows']),a.get('control','never'));summary=dict(sourceRows=result['sourceRows'],entities=result['sourceEntities'],cells=len(result['cells']),supportedCells=sum(r['defined']for r in result['cells']),postCells=sum(r['phase']=='post'for r in result['cells']))\r\n  for i,r in enumerate(result['cells']):emit('g'+str(r['g'])+':t'+str(r['t']),i+1,r['estimate'])\r\n elif api=='aggregate':\r\n  result=linear_aggregate(a);summary=dict(defined=result['defined'],estimate=result['estimate'],variance=result['variance'],covarianceRank=result['covarianceRank'],sumWeights=sum((r['coefficient']for r in result['weights']),Q(0)))\r\n  for i,r in enumerate(result['weights']):emit('g'+str(r['cohort'])+':t'+str(r['time']),i+1,r['contribution'])\r\n elif api=='twfe':\r\n  rows=literal_panel(a['rows']);G=panel(rows);result=twfe(G,sorted({r['time']for r in rows}));summary=dict(defined=result['beta']is not None,beta=result['beta'],numerator=result['num'],denominator=result['den'],balancedEntities=result['balancedEntities'],negativeTreatedCells=sum(v['coefficient']is not None and v['coefficient']<0 for v in result['weights'].values()))\r\n  for i,((g,t),r)in enumerate(sorted(result['weights'].items())):emit('g'+str(g)+':t'+str(t),i+1,r['coefficient'])\r\n elif api=='sensitivity':\r\n  result=sensitivity_fixed(a);summary={k:result[k]for k in['defined','estimate','scale','M','horizon','biasBudget','lower','upper']}\r\n  for i,k in enumerate(['lower','estimate','upper']):emit(k,i+1,result[k]if result['defined']else None)\r\n else:\r\n  result=realdata_fixed(a['kind'],data);post=[r for r in result['att']['cells']if r['phase']=='post'];s=next(r for r in result['aggregations']if r['type']=='simple');g=next(r for r in result['aggregations']if r['type']=='group'and r['key']=='overall');summary=dict(nativeRows=result['nativeRows'],modelRows=result['modelRows'],entities=result['entities'],postCells=len(post),simple=s['estimate'],group=g['estimate'],TWFE=result['twfe']['beta'],balancedEntities=result['twfe']['balancedEntities'])\r\n  for i,r in enumerate(post):emit('g'+str(r['g'])+':t'+str(r['t']),i+1,r['estimate'])\r\n out.mkdir(parents=True,exist_ok=True)\r\n if any(out.iterdir()):raise ValueError('use-new-empty-output-directory')\r\n shown={k:v9(v)for k,v in summary.items()};write(out/'summary.csv',[dict(name=k,value=v)for k,v in shown.items()]);write(out/'points.csv',points,['series','x','y','numericY']);full=dict(chapter='METR-20',profile=spec['id'],api=api,input=spec['input'],summary=shown,points=encode(points),details=encode(result),arithmetic='Python Fraction exact finite stored values;summary/plot approximate;bounded teaching projection,not causal or sampling certification')\r\n (out/'full.json').write_text(json.dumps(full,ensure_ascii=False,indent=2,allow_nan=False)+'\\n',encoding='utf8')\r\n import matplotlib\r\n matplotlib.use('Agg')\r\n import matplotlib.pyplot as plt\r\n plt.rcParams.update({'svg.fonttype':'none','font.family':'DejaVu Sans','font.size':12,'axes.spines.top':False,'axes.spines.right':False});fig,ax=plt.subplots(figsize=(9,5.6));good=[r for r in points if r['numericY']is not None]\r\n if good:\r\n  ax.scatter([r['x']for r in good],[r['numericY']for r in good],color='#315d7c',s=32);ax.axhline(0,color='#9eabb2',lw=.8);ax.set_xlabel('Declared cell/unit/bound ordinal')\r\n else:ax.text(.5,.5,'Undefined: no supported plotted quantity',ha='center',va='center',transform=ax.transAxes);ax.set_xticks([]);ax.set_yticks([])\r\n ax.set_ylabel('Cell weight'if api=='twfe'else result.get('unit','Stated outcome/bias units'));ax.set_title(spec['title']['en'],wrap=True,pad=14);ax.grid(axis='y',alpha=.2);fig.tight_layout(pad=2);fig.savefig(out/'plot.svg');plt.close(fig);print(json.dumps(shown))\r\n\r\nSPEC={'id': 'realdata-company', 'api': 'realdata', 'title': {'ko': '실제 NJPA 410개 원 점포행', 'en': 'Actual 410-record NJPA source frame'}, 'input': {'kind': 'company', 'control': 'never'}, 'expectedReject': False}\r\nif __name__=='__main__':\r\n import sys\r\n run_fixed(SPEC,Path(sys.argv[1]),Path(sys.argv[2])if len(sys.argv)>2 else Path(__file__).resolve().parent.parent/'metr20-sources')\r\n",
      "arithmetic": "Python Fraction exact stored finite values;logs/summary/plots approximate",
      "summary": {
        "nativeRows": "410",
        "modelRows": "820",
        "entities": "410",
        "postCells": "1",
        "simple": "2.75",
        "group": "2.75",
        "TWFE": "2.75",
        "balancedEntities": "384"
      },
      "fullResultEmbedded": false,
      "plotEmbedded": false,
      "full": {
        "summary": {
          "nativeRows": "410",
          "modelRows": "820",
          "entities": "410",
          "postCells": "1",
          "simple": "2.75",
          "group": "2.75",
          "TWFE": "2.75",
          "balancedEntities": "384"
        },
        "notice": "Complete source/finite projection is retained in the linked external JSON; this short projection is not the full result."
      },
      "plot": null,
      "points": [
        {
          "series": "g1:t1",
          "x": 1,
          "y": "11/4",
          "numericY": 2.75
        }
      ],
      "summaryFile": "metr20-programs/realdata-company-python-summary.csv",
      "summarySHA256": "91b6927f1b3d551b8185048d945c1ac20c45b4f87965c1606a653564125e36b1",
      "pointsFile": "metr20-programs/realdata-company-python-points.csv",
      "pointsSHA256": "c716d55c01da250c98876361f43dac521e5257730fce2a01255c862079cacf06",
      "fullResultFile": "metr20-programs/realdata-company-python.json",
      "fullResultSHA256": "4497101a87e3d9b68c6c57cd49b0acd9057836884a9d3bafe40b5b4dc6fbefa1",
      "plotFile": "metr20-programs/realdata-company-python.svg",
      "plotSHA256": "1c0afa4f4da69a96e28c1c1bbb881a09e1820ec89dcb2d0021d2eb93305b0078"
    },
    {
      "api": "realdata",
      "variant": "realdata-company",
      "profile": "realdata-company",
      "language": "R",
      "file": "metr20-programs/realdata-company-r.R",
      "codeSHA256": "71521ba5280dd472f263551ebf864319a19b8372bcf74b63febc74f3ea691a0c",
      "returnCode": 0,
      "expectedRejection": false,
      "title": {
        "ko": "실제 NJPA 410개 원 점포행",
        "en": "Actual 410-record NJPA source frame"
      },
      "code": "# METR20 fixed example. Base R only, finite arithmetic approximate.\r\n# No JavaScript engine,model JSON,derived answer table,private module or internet.\r\noptions(stringsAsFactors=FALSE,digits=17)\r\nargv<-commandArgs(trailingOnly=TRUE);if(length(argv)<1L)stop('Supply a new empty output directory')\r\noutdir<-argv[1];script<-sub('^--file=','',commandArgs(FALSE)[grepl('^--file=',commandArgs(FALSE))][1]);here<-dirname(normalizePath(script,mustWork=TRUE));datadir<-if(length(argv)>=2L)argv[2]else file.path(here,'..','metr20-sources')\r\nunits<-c(country='log teen-employment points',person='recorded real earnings',company='FTE employees');clocks<-c(country='calendar year',person='calendar year',company='survey-wave index');steps<-c(country=1,person=3,company=1);files<-c(country='actual2500-county-mpdta-all6-fields.csv',person='actual38408-NSW-all15-fields.csv',company='actual410-NJPA-all46-fields.csv')\r\nnum<-function(s)ifelse(s=='.',NA_real_,as.numeric(s));mean0<-function(v)if(length(v))mean(v)else NA_real_;var0<-function(v)if(length(v)>1L)sum((v-mean(v))^2)/(length(v)-1L)else NA_real_\r\n\r\nSPEC<-list(id=\"realdata-company\",api=\"realdata\",title=list(ko=\"실제 NJPA 410개 원 점포행\",en=\"Actual 410-record NJPA source frame\"),input=list(kind=\"company\",control=\"never\"),expectedReject=FALSE)\r\npanel<-function(rows){G<-list();for(r in rows){key<-r$entity;u<-G[[key]];if(is.null(u))u<-list(g=r$g,rows=list());stopifnot(identical(u$g,r$g),is.null(u$rows[[as.character(r$time)]]));u$rows[[as.character(r$time)]]<-r;G[[key]]<-u};G}\r\ncell<-function(G,g,t,step,control){b<-g-step;members<-list();T<-C<-list();for(key in names(G)){u<-G[[key]];target<-!is.na(u$g)&&u$g==g;comp<-is.na(u$g)||(control=='notyet'&&!is.na(u$g)&&u$g>max(t,b));role<-if(target)'treated'else if(comp)'control'else'excluded-comparison';before<-u$rows[[as.character(b)]];after<-u$rows[[as.character(t)]];yb<-if(is.null(before))NA_real_ else before$y;ya<-if(is.null(after))NA_real_ else after$y;eligible<-role!='excluded-comparison'&&!is.na(yb)&&!is.na(ya);reason<-if(role=='excluded-comparison')'target-or-already-exposed-cohort-not-valid-control'else if(is.null(before))'baseline-source-row-absent'else if(is.null(after))'target-time-source-row-absent'else if(is.na(yb))'baseline-outcome-missing'else if(is.na(ya))'target-outcome-missing'else'';m<-list(entity=key,nativeID=u$rows[[1]]$nativeID,g=u$g,role=role,eligible=eligible,baselineSourceId=if(is.null(before))NA_character_ else before$id,targetSourceId=if(is.null(after))NA_character_ else after$id,before=yb,after=ya,change=if(eligible)ya-yb else NA_real_,reason=reason);members[[key]]<-m;if(eligible){if(role=='treated')T[[length(T)+1L]]<-m else C[[length(C)+1L]]<-m}}\r\n change<-function(a)vapply(a,function(r)r$change,0);d<-mean0(change(T));e<-mean0(change(C));estimate<-if(is.na(d)||is.na(e))NA_real_ else d-e;defined<-!is.na(estimate);scores<-setNames(rep(NA_real_,length(members)),names(members));for(key in names(members)){m<-members[[key]];s<-if(!defined)NA_real_ else if(!m$eligible)0 else if(m$role=='treated')(m$change-d)/length(T)else-(m$change-e)/length(C);m$score<-s;scores[key]<-s;members[[key]]<-m};st<-var0(change(T));sc<-var0(change(C));v<-if(is.na(st)||is.na(sc))NA_real_ else st/length(T)+sc/length(C);level<-function(a,k)mean0(vapply(a,function(r)r[[k]],0))\r\n list(g=g,t=t,baseline=b,event=(t-g)/step,phase=if(t==b)'mechanical-reference'else if(t>=g)'post'else'pre-placebo',defined=defined,estimate=estimate,T=T,C=C,members=members,scores=scores,HC0=if(defined)sum(scores^2)else NA_real_,unbiased=v,treatedMeanBefore=level(T,'before'),treatedMeanAfter=level(T,'after'),treatedMeanChange=d,controlMeanBefore=level(C,'before'),controlMeanAfter=level(C,'after'),controlMeanChange=e)\r\n}\r\ncovariance<-function(cells){n<-length(cells);V<-matrix(NA_real_,n,n);for(i in seq_len(n))for(j in seq_len(n))if(cells[[i]]$defined&&cells[[j]]$defined)V[i,j]<-sum(cells[[i]]$scores*cells[[j]]$scores);V}\r\naggregate_cells<-function(post,V,step){out<-list();push<-function(typ,key,ii,w){est<-if(!length(ii)||any(vapply(post[ii],function(z)is.na(z$estimate),TRUE)))NA_real_ else sum(w*vapply(post[ii],function(z)z$estimate,0));vv<-if(is.na(est)||anyNA(V[ii,ii,drop=FALSE]))NA_real_ else as.numeric(t(w)%*%V[ii,ii,drop=FALSE]%*%w);out[[length(out)+1L]]<<-list(type=typ,key=as.character(key),ii=ii,w=w,estimate=est,variance=vv)};positive<-which(vapply(post,function(c)length(c$T)>0L,TRUE));mass<-sum(vapply(post[positive],function(c)length(c$T),0));push('simple','overall',positive,if(mass)vapply(post[positive],function(c)length(c$T)/mass,0)else numeric())\r\n for(typ in c('event','calendar','group')){keys<-vapply(post,function(c)if(typ=='event')c$event else if(typ=='calendar')c$t else c$g,0);gg<-sort(unique(keys));cohortmass<-if(typ=='group')sum(vapply(gg,function(k)length(post[[which(keys==k)[1]]]$T),0))else 0;allii<-integer();allw<-numeric();for(key in gg){ii<-which(keys==key);jj<-ii[vapply(post[ii],function(c)length(c$T)>0L,TRUE)];if(typ=='group'){stopifnot(length(unique(vapply(post[ii],function(c)length(c$T),0)))<=1L);w<-if(length(jj))rep(1/length(jj),length(jj))else numeric();if(cohortmass){allii<-c(allii,jj);allw<-c(allw,w*length(post[[ii[1]]]$T)/cohortmass)}}else{total<-sum(vapply(post[jj],function(c)length(c$T),0));w<-if(total)vapply(post[jj],function(c)length(c$T)/total,0)else numeric()};push(typ,key,jj,w)};if(typ=='group')push(typ,'overall',allii,allw)};out}\r\ntwfe<-function(G,times){ledger<-list();good<-list();for(key in names(G)){u<-G[[key]];absent<-times[!as.character(times)%in%names(u$rows)];missing<-times[vapply(times,function(t){r<-u$rows[[as.character(t)]];!is.null(r)&&is.na(r$y)},TRUE)];eligible<-length(times)>0L&&!length(absent)&&!length(missing);ledger[[length(ledger)+1L]]<-list(entity=key,g=u$g,nativeID=u$rows[[1]]$nativeID,eligible=eligible,absentTimes=paste(absent,collapse=','),missingOutcomeTimes=paste(missing,collapse=','),originalRows=length(u$rows));if(eligible)good[[key]]<-u};rows<-list();for(key in names(good))for(t in times){r<-good[[key]]$rows[[as.character(t)]];r$D<-as.integer(!is.na(r$g)&&t>=r$g);rows[[length(rows)+1L]]<-r};em<-lapply(good,function(u)list(D=mean(vapply(times,function(t)as.integer(!is.na(u$g)&&t>=u$g),0)),Y=mean(vapply(u$rows[as.character(times)],function(r)r$y,0))));tm<-lapply(times,function(t)list(D=mean(vapply(good,function(u)as.integer(!is.na(u$g)&&t>=u$g),0)),Y=mean(vapply(good,function(u)u$rows[[as.character(t)]]$y,0))));names(tm)<-as.character(times);gd<-mean0(vapply(rows,function(r)r$D,0));gy<-mean0(vapply(rows,function(r)r$y,0));num<-den<-0\r\n for(i in seq_along(rows)){r<-rows[[i]];r$residualD<-r$D-em[[r$entity]]$D-tm[[as.character(r$time)]]$D+gd;r$residualY<-r$y-em[[r$entity]]$Y-tm[[as.character(r$time)]]$Y+gy;num<-num+r$residualD*r$residualY;den<-den+r$residualD^2;rows[[i]]<-r};beta<-if(den!=0)num/den else NA_real_;weights<-list();for(i in seq_along(rows)){r<-rows[[i]];r$projectionCoefficient<-if(den!=0)r$residualD/den else NA_real_;r$regressionResidual<-if(!is.na(beta))r$residualY-beta*r$residualD else NA_real_;rows[[i]]<-r;if(r$D==1L){k<-paste(r$g,r$time,sep=':');z<-weights[[k]];if(is.null(z))z<-list(g=r$g,t=r$time,rows=0,coefficient=if(den!=0)0 else NA_real_);z$rows<-z$rows+1L;if(den!=0)z$coefficient<-z$coefficient+r$projectionCoefficient;weights[[k]]<-z}};list(ledger=ledger,rows=rows,num=num,den=den,beta=beta,weights=weights,balancedEntities=length(good))}\r\nadjacent_pre<-function(G,g,t,step,control){b<-t-step;T<-C<-numeric();for(u in G){target<-!is.na(u$g)&&u$g==g;comp<-is.na(u$g)||(control=='notyet'&&!is.na(u$g)&&u$g>max(t,b));if(!target&&!comp)next;before<-u$rows[[as.character(b)]];after<-u$rows[[as.character(t)]];if(!is.null(before)&&!is.null(after)&&!is.na(before$y)&&!is.na(after$y)){if(target)T<-c(T,after$y-before$y)else C<-c(C,after$y-before$y)}};if(!length(T)||!length(C))NA_real_ else mean(T)-mean(C)}\r\n\r\n# Newly authored bounded teaching projections; base R finite approximation.\r\n# Source helper functions are inlined in each public file, never imported.\r\nqnum<-function(v){if(is.null(v)||is.na(v))return(NA_real_);s<-strsplit(as.character(v),'/',fixed=TRUE)[[1]];if(length(s)==1L)as.numeric(s)else as.numeric(s[1])/as.numeric(s[2])}\r\npaired<-function(T,C){\r\n stats<-function(rr){use<-Filter(function(r)!is.na(qnum(r$before))&&!is.na(qnum(r$after)),rr);a<-vapply(use,function(r)qnum(r$before),0);b<-vapply(use,function(r)qnum(r$after),0);list(sourcePairs=length(rr),eligiblePairs=length(use),excludedPairs=length(rr)-length(use),meanBefore=mean0(a),meanAfter=mean0(b),meanChange=mean0(b-a),sampleChangeVariance=var0(b-a))}\r\n st<-stats(T);sc<-stats(C);defined<-st$eligiblePairs>0L&&sc$eligiblePairs>0L;estimate<-if(defined)st$meanChange-sc$meanChange else NA_real_;rr<-list()\r\n for(role in c('treated','control')){input<-if(role=='treated')T else C;s<-if(role=='treated')st else sc;for(r in input){before<-qnum(r$before);after<-qnum(r$after);eligible<-!is.na(before)&&!is.na(after);change<-if(eligible)after-before else NA_real_;score<-if(!defined)NA_real_ else if(!eligible)0 else (change-s$meanChange)/(if(role=='treated')s$eligiblePairs else -s$eligiblePairs);rr[[length(rr)+1L]]<-list(id=r$id,role=role,before=before,after=after,eligible=eligible,change=change,score=score)}}\r\n list(defined=defined,estimate=estimate,treated=st,control=sc,unbiasedVariance=if(defined&&st$eligiblePairs>=2L&&sc$eligiblePairs>=2L)st$sampleChangeVariance/st$eligiblePairs+sc$sampleChangeVariance/sc$eligiblePairs else NA_real_,HC0=if(defined)sum(vapply(rr,function(r)r$score^2,0))else NA_real_,rows=rr)\r\n}\r\nliteral_panel<-function(rr)lapply(seq_along(rr),function(i){r<-rr[[i]];r$y<-qnum(r$y);r$nativeID<-r$entity;r$sourceRow<-i;r})\r\natt_projection<-function(rows,control='never',step=1){G<-panel(rows);times<-sort(unique(vapply(rows,function(r)r$time,0)));cohorts<-sort(unique(na.omit(vapply(rows,function(r)r$g,0))));cells<-list();for(g in cohorts)for(t in times)cells[[length(cells)+1L]]<-cell(G,g,t,step,control);list(sourceRows=length(rows),sourceEntities=length(G),step=step,control=control,cells=cells,covariance=covariance(cells))}\r\nlinear_aggregate<-function(a){\r\n rr<-lapply(a$cells,function(r){r$estimate<-qnum(r$estimate);r$weight<-qnum(r$weight);r});V<-if(is.null(a$covariance))NULL else do.call(rbind,lapply(a$covariance,function(r)vapply(r,qnum,0)));rank<-NA_real_\r\n if(!is.null(V)){stopifnot(nrow(V)==length(rr),ncol(V)==length(rr),all(V==t(V)));ev<-eigen(V,symmetric=TRUE,only.values=TRUE)$values;if(any(ev< -1e-12))stop('covariance-must-be-positive-semidefinite');rank<-sum(ev>1e-12)}\r\n selected<-which(vapply(rr,function(r)r$time>=r$cohort&&r$weight>0,TRUE));w<-numeric(length(rr));type<-if(is.null(a$type))'simple'else a$type\r\n if(type=='simple'){mass<-sum(vapply(rr[selected],function(r)r$weight,0));if(mass>0)for(i in selected)w[i]<-rr[[i]]$weight/mass}else{g<-vapply(rr,function(r)r$cohort,0);gg<-sort(unique(g[selected]));mass<-sum(vapply(gg,function(gi)rr[[intersect(which(g==gi),selected)[1]]]$weight,0));for(gi in gg){ii<-intersect(which(g==gi),selected);stopifnot(length(unique(vapply(rr[ii],function(r)r$weight,0)))==1L);w[ii]<-rr[[ii[1]]]$weight/mass/length(ii)}}\r\n used<-which(w>0);estimate<-if(!length(used)||any(vapply(rr[used],function(r)is.na(r$estimate),TRUE)))NA_real_ else sum(w[used]*vapply(rr[used],function(r)r$estimate,0));variance<-if(is.na(estimate)||is.null(V))NA_real_ else as.numeric(t(w)%*%V%*%w);weights<-lapply(used,function(i)list(sourceIndex=i-1L,cohort=rr[[i]]$cohort,time=rr[[i]]$time,coefficient=w[i],estimate=rr[[i]]$estimate,contribution=w[i]*rr[[i]]$estimate))\r\n list(type=type,defined=!is.na(estimate),estimate=estimate,variance=variance,covarianceRank=rank,weights=weights,cells=rr,covariance=V)\r\n}\r\nsensitivity_fixed<-function(a){estimate<-qnum(a$estimate);M<-qnum(a$M);h<-if(is.null(a$horizon))1 else a$horizon;stopifnot(M>=0,h>=1);pre<-vapply(a$preDifferences,qnum,0);scale<-if(!is.null(a$scale))qnum(a$scale)else if(length(pre))max(abs(pre))else NA_real_;budget<-M*scale*h;list(defined=!is.na(scale),estimate=estimate,scale=scale,M=M,horizon=h,biasBudget=budget,lower=estimate-budget,upper=estimate+budget,preDifferences=as.list(pre),confidenceLevel=NULL)}\r\nrealdata_fixed<-function(kind){rows<-models[[kind]];G<-panel(rows);times<-sort(unique(vapply(rows,function(r)r$time,0)));step<-unname(steps[kind]);aa<-att_projection(rows,'never',step);post<-Filter(function(r)r$phase=='post',aa$cells);aggs<-aggregate_cells(post,covariance(post),step);tf<-twfe(G,times);list(kind=kind,unit=unname(units[kind]),periodUnit=unname(clocks[kind]),nativeRows=nrow(raw[[kind]]),modelRows=length(rows),entities=length(G),sourceRows=rows,att=aa,aggregations=aggs,twfe=tf,scope='Complete native/model/paired/balanced source frames; never control,universal base,no anticipation;not causal/sampling certification.')}\r\n# JSON encoder deliberately handles matrices and scalar/vector distinctions.\r\nencode<-function(x){\r\n if(is.null(x))return('null')\r\n quote<-function(s){s<-gsub('\\\\','\\\\\\\\',as.character(s),fixed=TRUE);s<-gsub('\"','\\\\\"',s,fixed=TRUE);s<-gsub('\\n','\\\\n',s,fixed=TRUE);s<-gsub('\\r','\\\\r',s,fixed=TRUE);s<-gsub('\\t','\\\\t',s,fixed=TRUE);paste0('\"',s,'\"')}\r\n if(is.matrix(x))return(paste0('[',paste(vapply(seq_len(nrow(x)),function(i)encode(as.list(unname(x[i,]))),''),collapse=','),']'))\r\n if(is.list(x)){if(length(x)&&!is.null(names(x)))return(paste0('{',paste(paste0(vapply(names(x),quote,''),':',vapply(x,encode,'')),collapse=','),'}'));return(paste0('[',paste(vapply(x,encode,''),collapse=','),']'))}\r\n if(length(x)!=1L)return(encode(as.list(unname(x))))\r\n if(is.na(x))return('null');if(is.logical(x))return(if(x)'true'else'false');if(is.numeric(x))return(sprintf('%.17g',unname(x)));quote(x)\r\n}\r\nv9<-function(x){if(is.null(x)||is.na(x))return('undefined');if(is.logical(x))return(if(x)'1'else'0');if(is.numeric(x))return(sprintf('%.9g',unname(x)));as.character(x)}\r\nrun_fixed<-function(spec,out){api<-spec$api;a<-spec$input;summary<-list();points<-list();emit<-function(series,x,y){points[[length(points)+1L]]<<-list(series=series,x=x,y=y,numericY=y)}\r\n if(api=='twobytwo'){result<-paired(a$treated,a$control);summary<-list(defined=result$defined,estimate=result$estimate,treatedPairs=result$treated$eligiblePairs,controlPairs=result$control$eligiblePairs,unbiasedVariance=result$unbiasedVariance,HC0=result$HC0);for(i in seq_along(result$rows)){r<-result$rows[[i]];emit(paste(r$role,r$id,sep=':'),i,r$change)}}\r\n else if(api=='att'){result<-att_projection(literal_panel(a$rows),a$control);summary<-list(sourceRows=result$sourceRows,entities=result$sourceEntities,cells=length(result$cells),supportedCells=sum(vapply(result$cells,function(r)r$defined,TRUE)),postCells=sum(vapply(result$cells,function(r)r$phase=='post',TRUE)));for(i in seq_along(result$cells)){r<-result$cells[[i]];emit(paste0('g',r$g,':t',r$t),i,r$estimate)}}\r\n else if(api=='aggregate'){result<-linear_aggregate(a);summary<-list(defined=result$defined,estimate=result$estimate,variance=result$variance,covarianceRank=result$covarianceRank,sumWeights=sum(vapply(result$weights,function(r)r$coefficient,0)));for(i in seq_along(result$weights)){r<-result$weights[[i]];emit(paste0('g',r$cohort,':t',r$time),i,r$contribution)}}\r\n else if(api=='twfe'){rows<-literal_panel(a$rows);G<-panel(rows);result<-twfe(G,sort(unique(vapply(rows,function(r)r$time,0))));summary<-list(defined=!is.na(result$beta),beta=result$beta,numerator=result$num,denominator=result$den,balancedEntities=result$balancedEntities,negativeTreatedCells=sum(vapply(result$weights,function(r)!is.na(r$coefficient)&&r$coefficient<0,TRUE)));if(length(result$weights)){ord<-order(vapply(result$weights,function(r)r$g,0),vapply(result$weights,function(r)r$t,0));for(i in seq_along(ord)){r<-result$weights[[ord[i]]];emit(paste0('g',r$g,':t',r$t),i,r$coefficient)}}}\r\n else if(api=='sensitivity'){result<-sensitivity_fixed(a);summary<-result[c('defined','estimate','scale','M','horizon','biasBudget','lower','upper')];for(i in seq_along(c('lower','estimate','upper'))){k<-c('lower','estimate','upper')[i];emit(k,i,if(result$defined)result[[k]]else NA_real_)}}\r\n else{result<-realdata_fixed(a$kind);post<-Filter(function(r)r$phase=='post',result$att$cells);simple<-Filter(function(r)r$type=='simple',result$aggregations)[[1]];group<-Filter(function(r)r$type=='group'&&r$key=='overall',result$aggregations)[[1]];summary<-list(nativeRows=result$nativeRows,modelRows=result$modelRows,entities=result$entities,postCells=length(post),simple=simple$estimate,group=group$estimate,TWFE=result$twfe$beta,balancedEntities=result$twfe$balancedEntities);for(i in seq_along(post)){r<-post[[i]];emit(paste0('g',r$g,':t',r$t),i,r$estimate)}}\r\n dir.create(out,recursive=TRUE,showWarnings=FALSE);if(length(list.files(out,all.files=TRUE,no..=TRUE)))stop('use-new-empty-output-directory');shown<-lapply(summary,v9);write.csv(data.frame(name=names(shown),value=unlist(shown,use.names=FALSE)),file.path(out,'summary.csv'),row.names=FALSE,na='');pointframe<-if(length(points))do.call(rbind,lapply(points,function(p)data.frame(series=p$series,x=p$x,y=p$y,numericY=p$numericY,stringsAsFactors=FALSE)))else data.frame(series=character(),x=numeric(),y=numeric(),numericY=numeric());write.csv(pointframe,file.path(out,'points.csv'),row.names=FALSE,na='');full<-list(chapter='METR-20',profile=spec$id,api=api,input=spec$input,summary=shown,points=points,details=result,arithmetic='Base R approximate finite values;bounded teaching projection,not exact fractions or causal/sampling certification.');writeLines(encode(full),file.path(out,'full.json'),useBytes=TRUE)\r\n svg(file.path(out,'plot.svg'),width=9,height=5.6,pointsize=12);par(mar=c(4.5,5.5,4,1));good<-pointframe[!is.na(pointframe$numericY),,drop=FALSE]\r\n if(nrow(good)){plot(good$x,good$numericY,pch=19,col='#315d7c',xlab='Declared cell/unit/bound ordinal',ylab=if(api=='twfe')'Cell weight'else if(!is.null(result$unit))result$unit else 'Stated outcome/bias units',main=spec$title$en);abline(h=0,col='#9eabb2');grid(nx=NA,ny=NULL,col='#e2e5e7');points(good$x,good$numericY,pch=19,col='#315d7c')}else{plot.new();text(.5,.5,'Undefined: no supported plotted quantity');title(main=spec$title$en)};dev.off();cat(encode(shown),'\\n')\r\n}\r\n\r\nraw<-lapply(files,function(n)read.csv(file.path(datadir,n),colClasses='character',check.names=FALSE,na.strings=character()));stopifnot(identical(vapply(raw,nrow,0L),c(country=2500L,person=38408L,company=410L)))\r\nmodels<-list(country=list(),person=list(),company=list())\r\nfor(i in seq_len(nrow(raw$country))){r<-raw$country[i,];g<-as.integer(r$first.treat);if(!g)g<-NA_integer_;stopifnot(as.integer(r$treat)==as.integer(!is.na(g)));models$country[[i]]<-list(id=paste0('mpdta:',r$sourceRow),entity=paste0('county:',as.integer(r$countyreal)),time=as.integer(r$year),y=num(r$lemp),g=g,sourceRow=as.integer(r$sourceRow),nativeID=r$countyreal)}\r\nfor(i in seq_len(nrow(raw$person))){r<-raw$person[i,];selected<-as.integer(r$experimental)==1L;stopifnot(selected==(as.integer(r$sample)==1L),(r$treated!='.')==selected);if(selected){d<-as.integer(r$treated);stopifnot(d%in%0:1);models$person[[length(models$person)+1L]]<-list(id=paste0('nsw:',r$sourceRow),entity=paste0('nsw-id:',as.integer(r$id)),time=as.integer(r$year),y=num(r$re),g=if(d==1L)1978L else NA_integer_,sourceRow=as.integer(r$sourceRow),nativeID=as.character(as.integer(r$id)))}}\r\nfor(i in seq_len(nrow(raw$company))){r<-raw$company[i,];state<-as.integer(r$STATE);stopifnot(state%in%0:1);for(t in 0:1){suffix<-if(t==0)''else'2';v<-vapply(paste0(c('EMPFT','NMGRS','EMPPT'),suffix),function(k)num(r[[k]]),0);y<-if(anyNA(v))NA_real_ else v[1]+v[2]+v[3]/2;models$company[[length(models$company)+1L]]<-list(id=paste0('njpa:',r$sourceRow,':wave',t),entity=paste0('njpa-row:',r$sourceRow),time=t,y=unname(y),g=if(state==1L)1L else NA_integer_,sourceRow=as.integer(r$sourceRow),nativeID=r$SHEET)}}\r\nstopifnot(identical(vapply(models,length,0L),c(country=2500L,person=1444L,company=820L)))\r\n\r\nrun_fixed(SPEC,outdir)\r\n",
      "arithmetic": "Base R approximate finite arithmetic;not an exact rational result",
      "summary": {
        "nativeRows": "410",
        "modelRows": "820",
        "entities": "410",
        "postCells": "1",
        "simple": "2.75",
        "group": "2.75",
        "TWFE": "2.75",
        "balancedEntities": "384"
      },
      "fullResultEmbedded": false,
      "plotEmbedded": false,
      "full": {
        "summary": {
          "nativeRows": "410",
          "modelRows": "820",
          "entities": "410",
          "postCells": "1",
          "simple": "2.75",
          "group": "2.75",
          "TWFE": "2.75",
          "balancedEntities": "384"
        },
        "notice": "Complete source/finite projection is retained in the linked external JSON; this short projection is not the full result."
      },
      "plot": null,
      "points": [
        {
          "series": "g1:t1",
          "x": 1,
          "y": 2.75,
          "numericY": 2.75
        }
      ],
      "summaryFile": "metr20-programs/realdata-company-r-summary.csv",
      "summarySHA256": "a58639dd2d4d432fedcac06ab3450c4228252d9979672dbc521ef40cb51518cb",
      "pointsFile": "metr20-programs/realdata-company-r-points.csv",
      "pointsSHA256": "b5e944d64e15116e1441dc29af824e88ebc91dac36aa2985e97b483cf7ab90e6",
      "fullResultFile": "metr20-programs/realdata-company-r.json",
      "fullResultSHA256": "b420bec6e36964df49a67d4fe66f1f3cee867dc801f72ded3d9ecd014ce39c8f",
      "plotFile": "metr20-programs/realdata-company-r.svg",
      "plotSHA256": "230fe4da24648a5b85f88f406f002e703c0173ebbf4b4c864836a95f3c688ae7"
    },
    {
      "api": "aggregate",
      "variant": "aggregate-invalid-covariance",
      "profile": "aggregate-invalid-covariance",
      "language": "Python",
      "file": "metr20-programs/aggregate-invalid-covariance-python.py",
      "codeSHA256": "0c3ab86b3f1ee96747d92b98ce43f68ba014a0b99bbe02811bfc87faee86a397",
      "returnCode": 1,
      "expectedRejection": true,
      "title": {
        "ko": "대칭이지만 PSD가 아닌 공분산 거부",
        "en": "Reject a symmetric covariance that is not PSD"
      },
      "code": "\"\"\"METR20 actual sources. Python standard library, exact stored-value rationals.\r\nRead ONLY the three native-observation CSVs; no JS engine,model JSON,derived\r\nanswers,private modules or internet needed. Outcome measurement/identification\r\nand valid sampling inference remain separate from exact finite arithmetic.\r\nRun: python metr20-reproduce.py --data-dir PATH --out NEW_EMPTY_DIRECTORY\r\n\"\"\"\r\nfrom pathlib import Path\r\nfrom fractions import Fraction as Q\r\nfrom collections import defaultdict,Counter\r\nimport csv,json,math,argparse,hashlib\r\n\r\nUNIT={'country':'log teen-employment points','person':'recorded real earnings','company':'FTE employees'}\r\nCLOCK={'country':'calendar year','person':'calendar year','company':'survey-wave index'}\r\nSTEP={'country':1,'person':3,'company':1}\r\nFILES={'country':'actual2500-county-mpdta-all6-fields.csv','person':'actual38408-NSW-all15-fields.csv','company':'actual410-NJPA-all46-fields.csv'}\r\ndef avg(v):return sum(v,Q(0))/len(v)if v else None\r\ndef samplevar(v):return sum(((x-avg(v))**2 for x in v),Q(0))/(len(v)-1)if len(v)>1 else None\r\ndef binary(s):return None if s=='.'else Q.from_float(float(s))\r\ndef token(v):\r\n if v is None:return ''\r\n if isinstance(v,bool):return 'true'if v else'false'\r\n return str(v)\r\ndef safe_float(v):\r\n if v is None:return None\r\n try:r=float(v)\r\n except OverflowError:return None\r\n return r if math.isfinite(r)else None\r\ndef read(p):\r\n with p.open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))\r\ndef write(p,rows,head=None):\r\n if head is None:\r\n  assert rows;head=list(rows[0])\r\n with p.open('w',encoding='utf8',newline='')as f:\r\n  w=csv.DictWriter(f,fieldnames=head);w.writeheader();w.writerows({k:token(r.get(k))for k in head}for r in rows)\r\ndef source(data):\r\n raw={k:read(data/n)for k,n in FILES.items()};assert[len(raw[k])for k in FILES]==[2500,38408,410]\r\n models={k:[]for k in FILES}\r\n for r in raw['country']:\r\n  g0=int(r['first.treat']);g=None if g0==0 else g0;assert int(r['treat'])==int(g is not None)\r\n  models['country'].append(dict(id='mpdta:'+r['sourceRow'],entity='county:'+str(int(r['countyreal'])),time=int(r['year']),y=binary(r['lemp']),g=g,sourceRow=int(r['sourceRow']),nativeID=r['countyreal']))\r\n for r in raw['person']:\r\n  selected=int(r['experimental'])==1;assert selected==(int(r['sample'])==1);assert(r['treated']!='.')==selected\r\n  if selected:\r\n   d=int(r['treated']);assert d in[0,1]\r\n   models['person'].append(dict(id='nsw:'+r['sourceRow'],entity='nsw-id:'+str(int(r['id'])),time=int(r['year']),y=binary(r['re']),g=1978 if d else None,sourceRow=int(r['sourceRow']),nativeID=str(int(r['id']))))\r\n for r in raw['company']:\r\n  state=int(r['STATE']);assert state in[0,1]\r\n  for t,suffix in[(0,''),(1,'2')]:\r\n   a=[r[n+suffix]for n in['EMPFT','NMGRS','EMPPT']];y=None if'.'in a else Q(a[0])+Q(a[1])+Q(a[2])/2\r\n   models['company'].append(dict(id='njpa:'+r['sourceRow']+':wave'+str(t),entity='njpa-row:'+r['sourceRow'],time=t,y=y,g=1 if state else None,sourceRow=int(r['sourceRow']),nativeID=r['SHEET']))\r\n assert[len(models[k])for k in FILES]==[2500,1444,820]\r\n return models,raw\r\ndef panel(rows):\r\n groups={}\r\n for r in rows:\r\n  u=groups.setdefault(r['entity'],{'g':r['g'],'rows':{}});assert u['g']==r['g']and r['time']not in u['rows'];u['rows'][r['time']]=r\r\n return groups\r\ndef cell(groups,g,t,step,control):\r\n b=g-step;members=[];T=[];C=[]\r\n for key,u in groups.items():\r\n  role='treated'if u['g']==g else'control'if u['g']is None or(control=='notyet'and u['g']>max(t,b))else'excluded-comparison'\r\n  before=u['rows'].get(b);after=u['rows'].get(t);yb=None if before is None else before['y'];ya=None if after is None else after['y'];eligible=role!='excluded-comparison'and yb is not None and ya is not None\r\n  reason='target-or-already-exposed-cohort-not-valid-control'if role=='excluded-comparison'else'baseline-source-row-absent'if before is None else'target-time-source-row-absent'if after is None else'baseline-outcome-missing'if yb is None else'target-outcome-missing'if ya is None else''\r\n  m={'entity':key,'nativeID':next(iter(u['rows'].values()))['nativeID'],'g':u['g'],'role':role,'eligible':eligible,'baselineSourceId':None if before is None else before['id'],'targetSourceId':None if after is None else after['id'],'before':yb,'after':ya,'change':ya-yb if eligible else None,'reason':reason};members.append(m)\r\n  if eligible:(T if role=='treated'else C).append(m)\r\n d=avg([r['change']for r in T]);e=avg([r['change']for r in C]);estimate=None if d is None or e is None else d-e;defined=estimate is not None;scores={}\r\n for m in members:\r\n  s=None if not defined else Q(0)\r\n  if defined and m['eligible']:s=(m['change']-(d if m['role']=='treated'else e))/(len(T)if m['role']=='treated'else-len(C))\r\n  m['score']=s;scores[m['entity']]=s\r\n st=samplevar([r['change']for r in T]);sc=samplevar([r['change']for r in C]);v=None if st is None or sc is None else st/len(T)+sc/len(C)\r\n return {'g':g,'t':t,'baseline':b,'event':(t-g)//step,'phase':'mechanical-reference'if t==b else'post'if t>=g else'pre-placebo','defined':defined,'estimate':estimate,'T':T,'C':C,'members':members,'scores':scores,'HC0':None if not defined else sum((s*s for s in scores.values()),Q(0)),'unbiased':v,'treatedMeanBefore':avg([r['before']for r in T]),'treatedMeanAfter':avg([r['after']for r in T]),'treatedMeanChange':d,'controlMeanBefore':avg([r['before']for r in C]),'controlMeanAfter':avg([r['after']for r in C]),'controlMeanChange':e}\r\ndef covariance(cells):\r\n return[[None if not a['defined']or not b['defined']else sum((v*b['scores'][i]for i,v in a['scores'].items()),Q(0))for b in cells]for a in cells]\r\ndef aggregate(post,V,step):\r\n out=[]\r\n def push(typ,key,coeff):\r\n  estimate=None if not coeff or any(post[i]['estimate']is None for i in coeff)else sum((w*post[i]['estimate']for i,w in coeff.items()),Q(0));variance=None if estimate is None or any(V[i][j]is None for i in coeff for j in coeff)else sum((a*b*V[i][j]for i,a in coeff.items()for j,b in coeff.items()),Q(0));out.append({'type':typ,'key':key,'coeff':coeff,'estimate':estimate,'variance':variance})\r\n positive=[i for i,c in enumerate(post)if len(c['T'])>0];mass=sum(len(post[i]['T'])for i in positive)\r\n push('simple','overall',{i:Q(len(post[i]['T']),mass)for i in positive}if mass else{})\r\n for typ in['event','calendar','group']:\r\n  groups=defaultdict(list)\r\n  for i,c in enumerate(post):groups[c['event']if typ=='event'else c['t']if typ=='calendar'else c['g']].append(i)\r\n  overall={};cohortMass=sum(len(post[ii[0]]['T'])for ii in groups.values())if typ=='group'else 0\r\n  for key,ii in sorted(groups.items()):\r\n   jj=[i for i in ii if len(post[i]['T'])>0]\r\n   if typ=='group':\r\n    assert len({len(post[i]['T'])for i in ii})<=1\r\n    coeff={i:Q(1,len(jj))for i in jj}if jj else{}\r\n    if cohortMass:\r\n     for i,w in coeff.items():overall[i]=w*Q(len(post[ii[0]]['T']),cohortMass)\r\n   else:\r\n    total=sum(len(post[i]['T'])for i in jj);coeff={i:Q(len(post[i]['T']),total)for i in jj}if total else{}\r\n   push(typ,str(key),coeff)\r\n  if typ=='group':push(typ,'overall',overall)\r\n return out\r\ndef twfe(groups,times):\r\n ledger=[];good={}\r\n for key,u in groups.items():\r\n  absent=[t for t in times if t not in u['rows']];missing=[t for t in times if t in u['rows']and u['rows'][t]['y']is None];eligible=bool(times)and not absent and not missing\r\n  ledger.append({'entity':key,'g':u['g'],'nativeID':next(iter(u['rows'].values()))['nativeID'],'eligible':eligible,'absentTimes':','.join(map(str,absent)),'missingOutcomeTimes':','.join(map(str,missing)),'originalRows':len(u['rows'])})\r\n  if eligible:good[key]=u\r\n rows=[dict(**u['rows'][t],D=Q(u['g']is not None and t>=u['g']))for key,u in good.items()for t in times]\r\n em={k:{'D':avg([Q(u['g']is not None and t>=u['g'])for t in times]),'Y':avg([u['rows'][t]['y']for t in times])}for k,u in good.items()};tm={t:{'D':avg([Q(u['g']is not None and t>=u['g'])for u in good.values()]),'Y':avg([u['rows'][t]['y']for u in good.values()])}for t in times};gd=avg([r['D']for r in rows]);gy=avg([r['y']for r in rows]);num=den=Q(0)\r\n for r in rows:\r\n  r['residualD']=r['D']-em[r['entity']]['D']-tm[r['time']]['D']+gd;r['residualY']=r['y']-em[r['entity']]['Y']-tm[r['time']]['Y']+gy;num+=r['residualD']*r['residualY'];den+=r['residualD']**2\r\n beta=num/den if den else None;weights={}\r\n for r in rows:\r\n  r['projectionCoefficient']=r['residualD']/den if den else None;r['regressionResidual']=r['residualY']-beta*r['residualD']if beta is not None else None\r\n  if r['D']:\r\n   k=(r['g'],r['time']);z=weights.setdefault(k,{'rows':0,'coefficient':Q(0)if den else None});z['rows']+=1\r\n   if den:z['coefficient']+=r['projectionCoefficient']\r\n return {'ledger':ledger,'rows':rows,'num':num,'den':den,'beta':beta,'weights':weights,'balancedEntities':len(good)}\r\ndef adjacent_pre(groups,g,t,step,control):\r\n b=t-step;T=[];C=[]\r\n for u in groups.values():\r\n  if u['g']==g:target=T\r\n  elif u['g']is None or(control=='notyet'and u['g']>max(t,b)):target=C\r\n  else:continue\r\n  before=u['rows'].get(b);after=u['rows'].get(t)\r\n  if before is not None and after is not None and before['y']is not None and after['y']is not None:target.append(after['y']-before['y'])\r\n return None if not T or not C else avg(T)-avg(C)\r\n\r\n\"\"\"New bounded teaching projections. The program is self-contained after build.\r\nExact Fraction finite algebra; figures and9-digit summary are approximations.\r\nIt is not a general parser/API replacement or a causal/inference certificate.\r\n\"\"\"\r\ndef paired(treated,control):\r\n def stats(rr):\r\n  use=[r for r in rr if r['before']is not None and r['after']is not None];delta=[Q(r['after'])-Q(r['before'])for r in use]\r\n  return dict(sourcePairs=len(rr),eligiblePairs=len(use),excludedPairs=len(rr)-len(use),meanBefore=avg([Q(r['before'])for r in use]),meanAfter=avg([Q(r['after'])for r in use]),meanChange=avg(delta),sampleChangeVariance=samplevar(delta))\r\n T,C=stats(treated),stats(control);defined=T['eligiblePairs']>0 and C['eligiblePairs']>0;estimate=T['meanChange']-C['meanChange']if defined else None;records=[]\r\n for group,rr,s in [('treated',treated,T),('control',control,C)]:\r\n  for r in rr:\r\n   before=None if r['before']is None else Q(r['before']);after=None if r['after']is None else Q(r['after']);eligible=before is not None and after is not None;delta=after-before if eligible else None;score=None if not defined else Q(0)if not eligible else(delta-s['meanChange'])/(s['eligiblePairs']if group=='treated'else-s['eligiblePairs']);records.append(dict(id=r['id'],role=group,before=before,after=after,eligible=eligible,change=delta,score=score))\r\n unbiased=None if not defined or T['eligiblePairs']<2 or C['eligiblePairs']<2 else T['sampleChangeVariance']/T['eligiblePairs']+C['sampleChangeVariance']/C['eligiblePairs'];hc0=None if not defined else sum((r['score']**2 for r in records),Q(0))\r\n return dict(defined=defined,estimate=estimate,treated=T,control=C,unbiasedVariance=unbiased,HC0=hc0,rows=records)\r\ndef literal_panel(raw):\r\n return[dict(r,y=None if r['y']is None else Q(r['y']),nativeID=r['entity'],sourceRow=i+1)for i,r in enumerate(raw)]\r\ndef att_projection(rows,control='never',step=1):\r\n G=panel(rows);times=sorted({r['time']for r in rows});cohorts=sorted({r['g']for r in rows if r['g']is not None});cells=[cell(G,g,t,step,control)for g in cohorts for t in times]\r\n return dict(sourceRows=len(rows),sourceEntities=len(G),step=step,control=control,cells=cells,covariance=covariance(cells))\r\ndef psd(V):\r\n A=[r[:]for r in V];rank=0\r\n while A:\r\n  if any(A[i][i]<0 for i in range(len(A))):raise ValueError('covariance-must-be-positive-semidefinite')\r\n  p=next((i for i in range(len(A))if A[i][i]>0),None)\r\n  if p is None:\r\n   if any(v for r in A for v in r):raise ValueError('covariance-must-be-positive-semidefinite')\r\n   return rank\r\n  A[0],A[p]=A[p],A[0]\r\n  for r in A:r[0],r[p]=r[p],r[0]\r\n  d=A[0][0];A=[[A[i][j]-A[i][0]*A[0][j]/d for j in range(1,len(A))]for i in range(1,len(A))];rank+=1\r\n return rank\r\ndef linear_aggregate(a):\r\n rr=[dict(r,estimate=None if r['estimate']is None else Q(r['estimate']),weight=Q(r['weight']))for r in a['cells']];V=[[Q(v)for v in r]for r in a['covariance']]if 'covariance'in a else None\r\n if V is not None:\r\n  assert len(V)==len(rr)and all(len(z)==len(rr)for z in V);assert all(V[i][j]==V[j][i]for i in range(len(rr))for j in range(len(rr)));rank=psd(V)\r\n else:rank=None\r\n selected=[i for i,r in enumerate(rr)if r['time']>=r['cohort']and r['weight']>0];weights={}\r\n if a.get('type','simple')=='simple':\r\n  mass=sum((rr[i]['weight']for i in selected),Q(0));weights={i:rr[i]['weight']/mass for i in selected}if mass else{}\r\n else:\r\n  gg=defaultdict(list)\r\n  for i in selected:gg[rr[i]['cohort']].append(i)\r\n  assert all(len({rr[i]['weight']for i in ii})==1 for ii in gg.values());mass=sum((rr[ii[0]]['weight']for ii in gg.values()),Q(0));weights={i:rr[ii[0]]['weight']/mass/len(ii)for ii in gg.values()for i in ii}if mass else{}\r\n estimate=None if not weights or any(rr[i]['estimate']is None for i in weights)else sum((w*rr[i]['estimate']for i,w in weights.items()),Q(0));variance=None if estimate is None or V is None else sum((x*y*V[i][j]for i,x in weights.items()for j,y in weights.items()),Q(0))\r\n return dict(type=a.get('type','simple'),defined=estimate is not None,estimate=estimate,variance=variance,covarianceRank=rank,weights=[dict(sourceIndex=i,cohort=rr[i]['cohort'],time=rr[i]['time'],coefficient=w,estimate=rr[i]['estimate'],contribution=None if rr[i]['estimate']is None else w*rr[i]['estimate'])for i,w in weights.items()],cells=rr,covariance=V)\r\ndef sensitivity_fixed(a):\r\n estimate=Q(a['estimate']);M=Q(a['M']);h=a.get('horizon',1);assert M>=0 and h>=1\r\n pre=[Q(v)for v in a.get('preDifferences',[])];scale=Q(a['scale'])if 'scale'in a else max(map(abs,pre))if pre else None;budget=None if scale is None else M*scale*h\r\n return dict(defined=scale is not None,estimate=estimate,scale=scale,M=M,horizon=h,biasBudget=budget,lower=None if budget is None else estimate-budget,upper=None if budget is None else estimate+budget,preDifferences=pre,confidenceLevel=None)\r\ndef realdata_fixed(kind,data):\r\n models,raw=source(data);rows=models[kind];G=panel(rows);times=sorted({r['time']for r in rows});step=STEP[kind];aa=att_projection(rows,'never',step);post=[r for r in aa['cells']if r['phase']=='post'];aggs=aggregate(post,covariance(post),step);tf=twfe(G,times)\r\n return dict(kind=kind,unit=UNIT[kind],periodUnit=CLOCK[kind],nativeRows=len(raw[kind]),modelRows=len(rows),entities=len(G),sourceRows=rows,att=aa,aggregations=aggs,twfe=tf,scope='Complete source frame; never-treated comparison,universal baseline,no anticipation. Native/model/paired/balanced denominators differ. All sampling/causal assumptions remain separate.')\r\ndef encode(v):\r\n if isinstance(v,Q):return str(v)\r\n if isinstance(v,dict):return{str(k):encode(x)for k,x in v.items()}\r\n if isinstance(v,(list,tuple)):return[encode(x)for x in v]\r\n return v\r\ndef v9(v):\r\n if v is None:return'undefined'\r\n if isinstance(v,str):return v\r\n if isinstance(v,bool):return'1'if v else'0'\r\n return format(float(v),'.9g')\r\ndef run_fixed(spec,out,data):\r\n api=spec['api'];a=spec['input'];summary={};points=[]\r\n def emit(series,x,y):points.append(dict(series=series,x=x,y=y,numericY=safe_float(y)))\r\n if api=='twobytwo':\r\n  result=paired(a['treated'],a['control']);summary=dict(defined=result['defined'],estimate=result['estimate'],treatedPairs=result['treated']['eligiblePairs'],controlPairs=result['control']['eligiblePairs'],unbiasedVariance=result['unbiasedVariance'],HC0=result['HC0'])\r\n  for i,r in enumerate(result['rows']):emit(r['role']+':'+r['id'],i+1,r['change'])\r\n elif api=='att':\r\n  result=att_projection(literal_panel(a['rows']),a.get('control','never'));summary=dict(sourceRows=result['sourceRows'],entities=result['sourceEntities'],cells=len(result['cells']),supportedCells=sum(r['defined']for r in result['cells']),postCells=sum(r['phase']=='post'for r in result['cells']))\r\n  for i,r in enumerate(result['cells']):emit('g'+str(r['g'])+':t'+str(r['t']),i+1,r['estimate'])\r\n elif api=='aggregate':\r\n  result=linear_aggregate(a);summary=dict(defined=result['defined'],estimate=result['estimate'],variance=result['variance'],covarianceRank=result['covarianceRank'],sumWeights=sum((r['coefficient']for r in result['weights']),Q(0)))\r\n  for i,r in enumerate(result['weights']):emit('g'+str(r['cohort'])+':t'+str(r['time']),i+1,r['contribution'])\r\n elif api=='twfe':\r\n  rows=literal_panel(a['rows']);G=panel(rows);result=twfe(G,sorted({r['time']for r in rows}));summary=dict(defined=result['beta']is not None,beta=result['beta'],numerator=result['num'],denominator=result['den'],balancedEntities=result['balancedEntities'],negativeTreatedCells=sum(v['coefficient']is not None and v['coefficient']<0 for v in result['weights'].values()))\r\n  for i,((g,t),r)in enumerate(sorted(result['weights'].items())):emit('g'+str(g)+':t'+str(t),i+1,r['coefficient'])\r\n elif api=='sensitivity':\r\n  result=sensitivity_fixed(a);summary={k:result[k]for k in['defined','estimate','scale','M','horizon','biasBudget','lower','upper']}\r\n  for i,k in enumerate(['lower','estimate','upper']):emit(k,i+1,result[k]if result['defined']else None)\r\n else:\r\n  result=realdata_fixed(a['kind'],data);post=[r for r in result['att']['cells']if r['phase']=='post'];s=next(r for r in result['aggregations']if r['type']=='simple');g=next(r for r in result['aggregations']if r['type']=='group'and r['key']=='overall');summary=dict(nativeRows=result['nativeRows'],modelRows=result['modelRows'],entities=result['entities'],postCells=len(post),simple=s['estimate'],group=g['estimate'],TWFE=result['twfe']['beta'],balancedEntities=result['twfe']['balancedEntities'])\r\n  for i,r in enumerate(post):emit('g'+str(r['g'])+':t'+str(r['t']),i+1,r['estimate'])\r\n out.mkdir(parents=True,exist_ok=True)\r\n if any(out.iterdir()):raise ValueError('use-new-empty-output-directory')\r\n shown={k:v9(v)for k,v in summary.items()};write(out/'summary.csv',[dict(name=k,value=v)for k,v in shown.items()]);write(out/'points.csv',points,['series','x','y','numericY']);full=dict(chapter='METR-20',profile=spec['id'],api=api,input=spec['input'],summary=shown,points=encode(points),details=encode(result),arithmetic='Python Fraction exact finite stored values;summary/plot approximate;bounded teaching projection,not causal or sampling certification')\r\n (out/'full.json').write_text(json.dumps(full,ensure_ascii=False,indent=2,allow_nan=False)+'\\n',encoding='utf8')\r\n import matplotlib\r\n matplotlib.use('Agg')\r\n import matplotlib.pyplot as plt\r\n plt.rcParams.update({'svg.fonttype':'none','font.family':'DejaVu Sans','font.size':12,'axes.spines.top':False,'axes.spines.right':False});fig,ax=plt.subplots(figsize=(9,5.6));good=[r for r in points if r['numericY']is not None]\r\n if good:\r\n  ax.scatter([r['x']for r in good],[r['numericY']for r in good],color='#315d7c',s=32);ax.axhline(0,color='#9eabb2',lw=.8);ax.set_xlabel('Declared cell/unit/bound ordinal')\r\n else:ax.text(.5,.5,'Undefined: no supported plotted quantity',ha='center',va='center',transform=ax.transAxes);ax.set_xticks([]);ax.set_yticks([])\r\n ax.set_ylabel('Cell weight'if api=='twfe'else result.get('unit','Stated outcome/bias units'));ax.set_title(spec['title']['en'],wrap=True,pad=14);ax.grid(axis='y',alpha=.2);fig.tight_layout(pad=2);fig.savefig(out/'plot.svg');plt.close(fig);print(json.dumps(shown))\r\n\r\nSPEC={'id': 'aggregate-invalid-covariance', 'api': 'aggregate', 'title': {'ko': '대칭이지만 PSD가 아닌 공분산 거부', 'en': 'Reject a symmetric covariance that is not PSD'}, 'input': {'cells': [{'cohort': 1, 'time': 1, 'estimate': '1', 'weight': '1'}, {'cohort': 2, 'time': 2, 'estimate': '2', 'weight': '1'}], 'type': 'simple', 'covariance': [['1', '2'], ['2', '1']]}, 'expectedReject': True}\r\nif __name__=='__main__':\r\n import sys\r\n run_fixed(SPEC,Path(sys.argv[1]),Path(sys.argv[2])if len(sys.argv)>2 else Path(__file__).resolve().parent.parent/'metr20-sources')\r\n",
      "arithmetic": "Python Fraction exact stored finite values;logs/summary/plots approximate",
      "summary": {
        "status": "rejected",
        "reason": "covariance-must-be-positive-semidefinite"
      },
      "fullResultEmbedded": false,
      "plotEmbedded": false,
      "full": {
        "status": "rejected",
        "reason": "covariance-must-be-positive-semidefinite"
      },
      "plot": null,
      "points": [],
      "publicDiagnostic": "A genuinely indefinite symmetric covariance is rejected; no result or figure is supplied."
    },
    {
      "api": "aggregate",
      "variant": "aggregate-invalid-covariance",
      "profile": "aggregate-invalid-covariance",
      "language": "R",
      "file": "metr20-programs/aggregate-invalid-covariance-r.R",
      "codeSHA256": "d28161ebb3a97729dc29fcc4e60cd7e10185dd09ec705a1c5c8dfd75b22b57ce",
      "returnCode": 1,
      "expectedRejection": true,
      "title": {
        "ko": "대칭이지만 PSD가 아닌 공분산 거부",
        "en": "Reject a symmetric covariance that is not PSD"
      },
      "code": "# METR20 fixed example. Base R only, finite arithmetic approximate.\r\n# No JavaScript engine,model JSON,derived answer table,private module or internet.\r\noptions(stringsAsFactors=FALSE,digits=17)\r\nargv<-commandArgs(trailingOnly=TRUE);if(length(argv)<1L)stop('Supply a new empty output directory')\r\noutdir<-argv[1];script<-sub('^--file=','',commandArgs(FALSE)[grepl('^--file=',commandArgs(FALSE))][1]);here<-dirname(normalizePath(script,mustWork=TRUE));datadir<-if(length(argv)>=2L)argv[2]else file.path(here,'..','metr20-sources')\r\nunits<-c(country='log teen-employment points',person='recorded real earnings',company='FTE employees');clocks<-c(country='calendar year',person='calendar year',company='survey-wave index');steps<-c(country=1,person=3,company=1);files<-c(country='actual2500-county-mpdta-all6-fields.csv',person='actual38408-NSW-all15-fields.csv',company='actual410-NJPA-all46-fields.csv')\r\nnum<-function(s)ifelse(s=='.',NA_real_,as.numeric(s));mean0<-function(v)if(length(v))mean(v)else NA_real_;var0<-function(v)if(length(v)>1L)sum((v-mean(v))^2)/(length(v)-1L)else NA_real_\r\n\r\nSPEC<-list(id=\"aggregate-invalid-covariance\",api=\"aggregate\",title=list(ko=\"대칭이지만 PSD가 아닌 공분산 거부\",en=\"Reject a symmetric covariance that is not PSD\"),input=list(cells=list(list(cohort=1,time=1,estimate=\"1\",weight=\"1\"),list(cohort=2,time=2,estimate=\"2\",weight=\"1\")),type=\"simple\",covariance=list(list(\"1\",\"2\"),list(\"2\",\"1\"))),expectedReject=TRUE)\r\npanel<-function(rows){G<-list();for(r in rows){key<-r$entity;u<-G[[key]];if(is.null(u))u<-list(g=r$g,rows=list());stopifnot(identical(u$g,r$g),is.null(u$rows[[as.character(r$time)]]));u$rows[[as.character(r$time)]]<-r;G[[key]]<-u};G}\r\ncell<-function(G,g,t,step,control){b<-g-step;members<-list();T<-C<-list();for(key in names(G)){u<-G[[key]];target<-!is.na(u$g)&&u$g==g;comp<-is.na(u$g)||(control=='notyet'&&!is.na(u$g)&&u$g>max(t,b));role<-if(target)'treated'else if(comp)'control'else'excluded-comparison';before<-u$rows[[as.character(b)]];after<-u$rows[[as.character(t)]];yb<-if(is.null(before))NA_real_ else before$y;ya<-if(is.null(after))NA_real_ else after$y;eligible<-role!='excluded-comparison'&&!is.na(yb)&&!is.na(ya);reason<-if(role=='excluded-comparison')'target-or-already-exposed-cohort-not-valid-control'else if(is.null(before))'baseline-source-row-absent'else if(is.null(after))'target-time-source-row-absent'else if(is.na(yb))'baseline-outcome-missing'else if(is.na(ya))'target-outcome-missing'else'';m<-list(entity=key,nativeID=u$rows[[1]]$nativeID,g=u$g,role=role,eligible=eligible,baselineSourceId=if(is.null(before))NA_character_ else before$id,targetSourceId=if(is.null(after))NA_character_ else after$id,before=yb,after=ya,change=if(eligible)ya-yb else NA_real_,reason=reason);members[[key]]<-m;if(eligible){if(role=='treated')T[[length(T)+1L]]<-m else C[[length(C)+1L]]<-m}}\r\n change<-function(a)vapply(a,function(r)r$change,0);d<-mean0(change(T));e<-mean0(change(C));estimate<-if(is.na(d)||is.na(e))NA_real_ else d-e;defined<-!is.na(estimate);scores<-setNames(rep(NA_real_,length(members)),names(members));for(key in names(members)){m<-members[[key]];s<-if(!defined)NA_real_ else if(!m$eligible)0 else if(m$role=='treated')(m$change-d)/length(T)else-(m$change-e)/length(C);m$score<-s;scores[key]<-s;members[[key]]<-m};st<-var0(change(T));sc<-var0(change(C));v<-if(is.na(st)||is.na(sc))NA_real_ else st/length(T)+sc/length(C);level<-function(a,k)mean0(vapply(a,function(r)r[[k]],0))\r\n list(g=g,t=t,baseline=b,event=(t-g)/step,phase=if(t==b)'mechanical-reference'else if(t>=g)'post'else'pre-placebo',defined=defined,estimate=estimate,T=T,C=C,members=members,scores=scores,HC0=if(defined)sum(scores^2)else NA_real_,unbiased=v,treatedMeanBefore=level(T,'before'),treatedMeanAfter=level(T,'after'),treatedMeanChange=d,controlMeanBefore=level(C,'before'),controlMeanAfter=level(C,'after'),controlMeanChange=e)\r\n}\r\ncovariance<-function(cells){n<-length(cells);V<-matrix(NA_real_,n,n);for(i in seq_len(n))for(j in seq_len(n))if(cells[[i]]$defined&&cells[[j]]$defined)V[i,j]<-sum(cells[[i]]$scores*cells[[j]]$scores);V}\r\naggregate_cells<-function(post,V,step){out<-list();push<-function(typ,key,ii,w){est<-if(!length(ii)||any(vapply(post[ii],function(z)is.na(z$estimate),TRUE)))NA_real_ else sum(w*vapply(post[ii],function(z)z$estimate,0));vv<-if(is.na(est)||anyNA(V[ii,ii,drop=FALSE]))NA_real_ else as.numeric(t(w)%*%V[ii,ii,drop=FALSE]%*%w);out[[length(out)+1L]]<<-list(type=typ,key=as.character(key),ii=ii,w=w,estimate=est,variance=vv)};positive<-which(vapply(post,function(c)length(c$T)>0L,TRUE));mass<-sum(vapply(post[positive],function(c)length(c$T),0));push('simple','overall',positive,if(mass)vapply(post[positive],function(c)length(c$T)/mass,0)else numeric())\r\n for(typ in c('event','calendar','group')){keys<-vapply(post,function(c)if(typ=='event')c$event else if(typ=='calendar')c$t else c$g,0);gg<-sort(unique(keys));cohortmass<-if(typ=='group')sum(vapply(gg,function(k)length(post[[which(keys==k)[1]]]$T),0))else 0;allii<-integer();allw<-numeric();for(key in gg){ii<-which(keys==key);jj<-ii[vapply(post[ii],function(c)length(c$T)>0L,TRUE)];if(typ=='group'){stopifnot(length(unique(vapply(post[ii],function(c)length(c$T),0)))<=1L);w<-if(length(jj))rep(1/length(jj),length(jj))else numeric();if(cohortmass){allii<-c(allii,jj);allw<-c(allw,w*length(post[[ii[1]]]$T)/cohortmass)}}else{total<-sum(vapply(post[jj],function(c)length(c$T),0));w<-if(total)vapply(post[jj],function(c)length(c$T)/total,0)else numeric()};push(typ,key,jj,w)};if(typ=='group')push(typ,'overall',allii,allw)};out}\r\ntwfe<-function(G,times){ledger<-list();good<-list();for(key in names(G)){u<-G[[key]];absent<-times[!as.character(times)%in%names(u$rows)];missing<-times[vapply(times,function(t){r<-u$rows[[as.character(t)]];!is.null(r)&&is.na(r$y)},TRUE)];eligible<-length(times)>0L&&!length(absent)&&!length(missing);ledger[[length(ledger)+1L]]<-list(entity=key,g=u$g,nativeID=u$rows[[1]]$nativeID,eligible=eligible,absentTimes=paste(absent,collapse=','),missingOutcomeTimes=paste(missing,collapse=','),originalRows=length(u$rows));if(eligible)good[[key]]<-u};rows<-list();for(key in names(good))for(t in times){r<-good[[key]]$rows[[as.character(t)]];r$D<-as.integer(!is.na(r$g)&&t>=r$g);rows[[length(rows)+1L]]<-r};em<-lapply(good,function(u)list(D=mean(vapply(times,function(t)as.integer(!is.na(u$g)&&t>=u$g),0)),Y=mean(vapply(u$rows[as.character(times)],function(r)r$y,0))));tm<-lapply(times,function(t)list(D=mean(vapply(good,function(u)as.integer(!is.na(u$g)&&t>=u$g),0)),Y=mean(vapply(good,function(u)u$rows[[as.character(t)]]$y,0))));names(tm)<-as.character(times);gd<-mean0(vapply(rows,function(r)r$D,0));gy<-mean0(vapply(rows,function(r)r$y,0));num<-den<-0\r\n for(i in seq_along(rows)){r<-rows[[i]];r$residualD<-r$D-em[[r$entity]]$D-tm[[as.character(r$time)]]$D+gd;r$residualY<-r$y-em[[r$entity]]$Y-tm[[as.character(r$time)]]$Y+gy;num<-num+r$residualD*r$residualY;den<-den+r$residualD^2;rows[[i]]<-r};beta<-if(den!=0)num/den else NA_real_;weights<-list();for(i in seq_along(rows)){r<-rows[[i]];r$projectionCoefficient<-if(den!=0)r$residualD/den else NA_real_;r$regressionResidual<-if(!is.na(beta))r$residualY-beta*r$residualD else NA_real_;rows[[i]]<-r;if(r$D==1L){k<-paste(r$g,r$time,sep=':');z<-weights[[k]];if(is.null(z))z<-list(g=r$g,t=r$time,rows=0,coefficient=if(den!=0)0 else NA_real_);z$rows<-z$rows+1L;if(den!=0)z$coefficient<-z$coefficient+r$projectionCoefficient;weights[[k]]<-z}};list(ledger=ledger,rows=rows,num=num,den=den,beta=beta,weights=weights,balancedEntities=length(good))}\r\nadjacent_pre<-function(G,g,t,step,control){b<-t-step;T<-C<-numeric();for(u in G){target<-!is.na(u$g)&&u$g==g;comp<-is.na(u$g)||(control=='notyet'&&!is.na(u$g)&&u$g>max(t,b));if(!target&&!comp)next;before<-u$rows[[as.character(b)]];after<-u$rows[[as.character(t)]];if(!is.null(before)&&!is.null(after)&&!is.na(before$y)&&!is.na(after$y)){if(target)T<-c(T,after$y-before$y)else C<-c(C,after$y-before$y)}};if(!length(T)||!length(C))NA_real_ else mean(T)-mean(C)}\r\n\r\n# Newly authored bounded teaching projections; base R finite approximation.\r\n# Source helper functions are inlined in each public file, never imported.\r\nqnum<-function(v){if(is.null(v)||is.na(v))return(NA_real_);s<-strsplit(as.character(v),'/',fixed=TRUE)[[1]];if(length(s)==1L)as.numeric(s)else as.numeric(s[1])/as.numeric(s[2])}\r\npaired<-function(T,C){\r\n stats<-function(rr){use<-Filter(function(r)!is.na(qnum(r$before))&&!is.na(qnum(r$after)),rr);a<-vapply(use,function(r)qnum(r$before),0);b<-vapply(use,function(r)qnum(r$after),0);list(sourcePairs=length(rr),eligiblePairs=length(use),excludedPairs=length(rr)-length(use),meanBefore=mean0(a),meanAfter=mean0(b),meanChange=mean0(b-a),sampleChangeVariance=var0(b-a))}\r\n st<-stats(T);sc<-stats(C);defined<-st$eligiblePairs>0L&&sc$eligiblePairs>0L;estimate<-if(defined)st$meanChange-sc$meanChange else NA_real_;rr<-list()\r\n for(role in c('treated','control')){input<-if(role=='treated')T else C;s<-if(role=='treated')st else sc;for(r in input){before<-qnum(r$before);after<-qnum(r$after);eligible<-!is.na(before)&&!is.na(after);change<-if(eligible)after-before else NA_real_;score<-if(!defined)NA_real_ else if(!eligible)0 else (change-s$meanChange)/(if(role=='treated')s$eligiblePairs else -s$eligiblePairs);rr[[length(rr)+1L]]<-list(id=r$id,role=role,before=before,after=after,eligible=eligible,change=change,score=score)}}\r\n list(defined=defined,estimate=estimate,treated=st,control=sc,unbiasedVariance=if(defined&&st$eligiblePairs>=2L&&sc$eligiblePairs>=2L)st$sampleChangeVariance/st$eligiblePairs+sc$sampleChangeVariance/sc$eligiblePairs else NA_real_,HC0=if(defined)sum(vapply(rr,function(r)r$score^2,0))else NA_real_,rows=rr)\r\n}\r\nliteral_panel<-function(rr)lapply(seq_along(rr),function(i){r<-rr[[i]];r$y<-qnum(r$y);r$nativeID<-r$entity;r$sourceRow<-i;r})\r\natt_projection<-function(rows,control='never',step=1){G<-panel(rows);times<-sort(unique(vapply(rows,function(r)r$time,0)));cohorts<-sort(unique(na.omit(vapply(rows,function(r)r$g,0))));cells<-list();for(g in cohorts)for(t in times)cells[[length(cells)+1L]]<-cell(G,g,t,step,control);list(sourceRows=length(rows),sourceEntities=length(G),step=step,control=control,cells=cells,covariance=covariance(cells))}\r\nlinear_aggregate<-function(a){\r\n rr<-lapply(a$cells,function(r){r$estimate<-qnum(r$estimate);r$weight<-qnum(r$weight);r});V<-if(is.null(a$covariance))NULL else do.call(rbind,lapply(a$covariance,function(r)vapply(r,qnum,0)));rank<-NA_real_\r\n if(!is.null(V)){stopifnot(nrow(V)==length(rr),ncol(V)==length(rr),all(V==t(V)));ev<-eigen(V,symmetric=TRUE,only.values=TRUE)$values;if(any(ev< -1e-12))stop('covariance-must-be-positive-semidefinite');rank<-sum(ev>1e-12)}\r\n selected<-which(vapply(rr,function(r)r$time>=r$cohort&&r$weight>0,TRUE));w<-numeric(length(rr));type<-if(is.null(a$type))'simple'else a$type\r\n if(type=='simple'){mass<-sum(vapply(rr[selected],function(r)r$weight,0));if(mass>0)for(i in selected)w[i]<-rr[[i]]$weight/mass}else{g<-vapply(rr,function(r)r$cohort,0);gg<-sort(unique(g[selected]));mass<-sum(vapply(gg,function(gi)rr[[intersect(which(g==gi),selected)[1]]]$weight,0));for(gi in gg){ii<-intersect(which(g==gi),selected);stopifnot(length(unique(vapply(rr[ii],function(r)r$weight,0)))==1L);w[ii]<-rr[[ii[1]]]$weight/mass/length(ii)}}\r\n used<-which(w>0);estimate<-if(!length(used)||any(vapply(rr[used],function(r)is.na(r$estimate),TRUE)))NA_real_ else sum(w[used]*vapply(rr[used],function(r)r$estimate,0));variance<-if(is.na(estimate)||is.null(V))NA_real_ else as.numeric(t(w)%*%V%*%w);weights<-lapply(used,function(i)list(sourceIndex=i-1L,cohort=rr[[i]]$cohort,time=rr[[i]]$time,coefficient=w[i],estimate=rr[[i]]$estimate,contribution=w[i]*rr[[i]]$estimate))\r\n list(type=type,defined=!is.na(estimate),estimate=estimate,variance=variance,covarianceRank=rank,weights=weights,cells=rr,covariance=V)\r\n}\r\nsensitivity_fixed<-function(a){estimate<-qnum(a$estimate);M<-qnum(a$M);h<-if(is.null(a$horizon))1 else a$horizon;stopifnot(M>=0,h>=1);pre<-vapply(a$preDifferences,qnum,0);scale<-if(!is.null(a$scale))qnum(a$scale)else if(length(pre))max(abs(pre))else NA_real_;budget<-M*scale*h;list(defined=!is.na(scale),estimate=estimate,scale=scale,M=M,horizon=h,biasBudget=budget,lower=estimate-budget,upper=estimate+budget,preDifferences=as.list(pre),confidenceLevel=NULL)}\r\nrealdata_fixed<-function(kind){rows<-models[[kind]];G<-panel(rows);times<-sort(unique(vapply(rows,function(r)r$time,0)));step<-unname(steps[kind]);aa<-att_projection(rows,'never',step);post<-Filter(function(r)r$phase=='post',aa$cells);aggs<-aggregate_cells(post,covariance(post),step);tf<-twfe(G,times);list(kind=kind,unit=unname(units[kind]),periodUnit=unname(clocks[kind]),nativeRows=nrow(raw[[kind]]),modelRows=length(rows),entities=length(G),sourceRows=rows,att=aa,aggregations=aggs,twfe=tf,scope='Complete native/model/paired/balanced source frames; never control,universal base,no anticipation;not causal/sampling certification.')}\r\n# JSON encoder deliberately handles matrices and scalar/vector distinctions.\r\nencode<-function(x){\r\n if(is.null(x))return('null')\r\n quote<-function(s){s<-gsub('\\\\','\\\\\\\\',as.character(s),fixed=TRUE);s<-gsub('\"','\\\\\"',s,fixed=TRUE);s<-gsub('\\n','\\\\n',s,fixed=TRUE);s<-gsub('\\r','\\\\r',s,fixed=TRUE);s<-gsub('\\t','\\\\t',s,fixed=TRUE);paste0('\"',s,'\"')}\r\n if(is.matrix(x))return(paste0('[',paste(vapply(seq_len(nrow(x)),function(i)encode(as.list(unname(x[i,]))),''),collapse=','),']'))\r\n if(is.list(x)){if(length(x)&&!is.null(names(x)))return(paste0('{',paste(paste0(vapply(names(x),quote,''),':',vapply(x,encode,'')),collapse=','),'}'));return(paste0('[',paste(vapply(x,encode,''),collapse=','),']'))}\r\n if(length(x)!=1L)return(encode(as.list(unname(x))))\r\n if(is.na(x))return('null');if(is.logical(x))return(if(x)'true'else'false');if(is.numeric(x))return(sprintf('%.17g',unname(x)));quote(x)\r\n}\r\nv9<-function(x){if(is.null(x)||is.na(x))return('undefined');if(is.logical(x))return(if(x)'1'else'0');if(is.numeric(x))return(sprintf('%.9g',unname(x)));as.character(x)}\r\nrun_fixed<-function(spec,out){api<-spec$api;a<-spec$input;summary<-list();points<-list();emit<-function(series,x,y){points[[length(points)+1L]]<<-list(series=series,x=x,y=y,numericY=y)}\r\n if(api=='twobytwo'){result<-paired(a$treated,a$control);summary<-list(defined=result$defined,estimate=result$estimate,treatedPairs=result$treated$eligiblePairs,controlPairs=result$control$eligiblePairs,unbiasedVariance=result$unbiasedVariance,HC0=result$HC0);for(i in seq_along(result$rows)){r<-result$rows[[i]];emit(paste(r$role,r$id,sep=':'),i,r$change)}}\r\n else if(api=='att'){result<-att_projection(literal_panel(a$rows),a$control);summary<-list(sourceRows=result$sourceRows,entities=result$sourceEntities,cells=length(result$cells),supportedCells=sum(vapply(result$cells,function(r)r$defined,TRUE)),postCells=sum(vapply(result$cells,function(r)r$phase=='post',TRUE)));for(i in seq_along(result$cells)){r<-result$cells[[i]];emit(paste0('g',r$g,':t',r$t),i,r$estimate)}}\r\n else if(api=='aggregate'){result<-linear_aggregate(a);summary<-list(defined=result$defined,estimate=result$estimate,variance=result$variance,covarianceRank=result$covarianceRank,sumWeights=sum(vapply(result$weights,function(r)r$coefficient,0)));for(i in seq_along(result$weights)){r<-result$weights[[i]];emit(paste0('g',r$cohort,':t',r$time),i,r$contribution)}}\r\n else if(api=='twfe'){rows<-literal_panel(a$rows);G<-panel(rows);result<-twfe(G,sort(unique(vapply(rows,function(r)r$time,0))));summary<-list(defined=!is.na(result$beta),beta=result$beta,numerator=result$num,denominator=result$den,balancedEntities=result$balancedEntities,negativeTreatedCells=sum(vapply(result$weights,function(r)!is.na(r$coefficient)&&r$coefficient<0,TRUE)));if(length(result$weights)){ord<-order(vapply(result$weights,function(r)r$g,0),vapply(result$weights,function(r)r$t,0));for(i in seq_along(ord)){r<-result$weights[[ord[i]]];emit(paste0('g',r$g,':t',r$t),i,r$coefficient)}}}\r\n else if(api=='sensitivity'){result<-sensitivity_fixed(a);summary<-result[c('defined','estimate','scale','M','horizon','biasBudget','lower','upper')];for(i in seq_along(c('lower','estimate','upper'))){k<-c('lower','estimate','upper')[i];emit(k,i,if(result$defined)result[[k]]else NA_real_)}}\r\n else{result<-realdata_fixed(a$kind);post<-Filter(function(r)r$phase=='post',result$att$cells);simple<-Filter(function(r)r$type=='simple',result$aggregations)[[1]];group<-Filter(function(r)r$type=='group'&&r$key=='overall',result$aggregations)[[1]];summary<-list(nativeRows=result$nativeRows,modelRows=result$modelRows,entities=result$entities,postCells=length(post),simple=simple$estimate,group=group$estimate,TWFE=result$twfe$beta,balancedEntities=result$twfe$balancedEntities);for(i in seq_along(post)){r<-post[[i]];emit(paste0('g',r$g,':t',r$t),i,r$estimate)}}\r\n dir.create(out,recursive=TRUE,showWarnings=FALSE);if(length(list.files(out,all.files=TRUE,no..=TRUE)))stop('use-new-empty-output-directory');shown<-lapply(summary,v9);write.csv(data.frame(name=names(shown),value=unlist(shown,use.names=FALSE)),file.path(out,'summary.csv'),row.names=FALSE,na='');pointframe<-if(length(points))do.call(rbind,lapply(points,function(p)data.frame(series=p$series,x=p$x,y=p$y,numericY=p$numericY,stringsAsFactors=FALSE)))else data.frame(series=character(),x=numeric(),y=numeric(),numericY=numeric());write.csv(pointframe,file.path(out,'points.csv'),row.names=FALSE,na='');full<-list(chapter='METR-20',profile=spec$id,api=api,input=spec$input,summary=shown,points=points,details=result,arithmetic='Base R approximate finite values;bounded teaching projection,not exact fractions or causal/sampling certification.');writeLines(encode(full),file.path(out,'full.json'),useBytes=TRUE)\r\n svg(file.path(out,'plot.svg'),width=9,height=5.6,pointsize=12);par(mar=c(4.5,5.5,4,1));good<-pointframe[!is.na(pointframe$numericY),,drop=FALSE]\r\n if(nrow(good)){plot(good$x,good$numericY,pch=19,col='#315d7c',xlab='Declared cell/unit/bound ordinal',ylab=if(api=='twfe')'Cell weight'else if(!is.null(result$unit))result$unit else 'Stated outcome/bias units',main=spec$title$en);abline(h=0,col='#9eabb2');grid(nx=NA,ny=NULL,col='#e2e5e7');points(good$x,good$numericY,pch=19,col='#315d7c')}else{plot.new();text(.5,.5,'Undefined: no supported plotted quantity');title(main=spec$title$en)};dev.off();cat(encode(shown),'\\n')\r\n}\r\n\r\nrun_fixed(SPEC,outdir)\r\n",
      "arithmetic": "Base R approximate finite arithmetic;not an exact rational result",
      "summary": {
        "status": "rejected",
        "reason": "covariance-must-be-positive-semidefinite"
      },
      "fullResultEmbedded": false,
      "plotEmbedded": false,
      "full": {
        "status": "rejected",
        "reason": "covariance-must-be-positive-semidefinite"
      },
      "plot": null,
      "points": [],
      "publicDiagnostic": "A genuinely indefinite symmetric covariance is rejected; no result or figure is supplied."
    }
  ],
  "byAPI": {
    "twobytwo": [
      0,
      1,
      2,
      3
    ],
    "att": [
      4,
      5,
      6,
      7
    ],
    "aggregate": [
      8,
      9,
      10,
      11,
      28,
      29
    ],
    "twfe": [
      12,
      13,
      14,
      15
    ],
    "sensitivity": [
      16,
      17,
      18,
      19,
      20,
      21
    ],
    "realdata": [
      22,
      23,
      24,
      25,
      26,
      27
    ]
  }
}
