{
  "rebase": {
    "python": {
      "default": {
        "api": "rebase",
        "variant": "default",
        "language": "python",
        "codeFile": "econ22-code/rebase-default.py",
        "codeSHA256": "87d7ff6cbe0d7e796296a131be9132dbd29b0fd8d6131ec5dc180d7382dc7a76",
        "codeText": "# Fixed stated example, separate from current web controls.\nfrom pathlib import Path\nimport importlib.util,sys\nroot=Path(__file__).resolve().parents[1]\nspec=importlib.util.spec_from_file_location('fixed_support',root/'econ22-fixed-support.py')\nsupport=importlib.util.module_from_spec(spec);spec.loader.exec_module(support)\ntry:support.run('rebase','default',sys.argv[1]if len(sys.argv)>1 else root/'econ22-fixed-results/rebase-default-python')\nexcept ValueError as error:\n print('Rejected declared input: '+str(error),file=sys.stderr);sys.exit(2)\n",
        "supportFiles": [
          {
            "file": "econ22-reproduce.py",
            "sha256": "cc5631d9dfea963b64349bb28d18b69ad3caf15a15162ec6cea786a36e18de48",
            "codeText": "#!/usr/bin/env python3\n\"\"\"ECON22 public reproduction: Python standard library, exact Fraction arithmetic.\nRun: python econ22-reproduce.py --source-dir econ22-sources --output-dir econ22-python-results\nOriginal CSV inputs are read only. Output is a new chosen directory.\nThese are descriptive arithmetic and explicitly assumed examples, not causal estimates.\n\"\"\"\nfrom fractions import Fraction as Q\nfrom pathlib import Path\nfrom collections import defaultdict\nimport argparse,csv,json\n\ndef number(x):\n if x is None:raise ValueError('missing numeric token')\n return Q(str(x))\ndef rebase(values,base=0,scale='100'):\n v=[None if x is None else number(x)for x in values];s=number(scale)\n if not v or not 0<=base<len(v)or v[base]is None or v[base]<=0 or s<=0:raise ValueError('positive observed base/scale required')\n return [None if x is None else s*x/v[base]for x in v]\ndef growth(start,end,periods=1):\n a,b=number(start),number(end)\n if a<=0 or b<0 or not isinstance(periods,int)or not 1<=periods<=12:raise ValueError('growth domain')\n g=b/a;return dict(gross=g,percentChange=(g-1)*100,annualizedGross=g**periods,annualizedPercent=(g**periods-1)*100)\ndef composition(rows):\n seen=set();data=[]\n for r in rows:\n  identifier=str(r['id']);weight=number(r.get('weight','1'))\n  if identifier in seen or weight<0:raise ValueError('unique units/nonnegative fixed weights required')\n  seen.add(identifier);data.append(dict(id=identifier,weight=weight,before=None if r['before']is None else number(r['before']),after=None if r['after']is None else number(r['after'])))\n if not data:raise ValueError('nonempty frame required')\n valid=[r for r in data if r['weight']>0];b=[r for r in valid if r['before']is not None];a=[r for r in valid if r['after']is not None];c=[r for r in valid if r['before']is not None and r['after']is not None]\n def mean(rs,k):\n  mass=sum((r['weight']for r in rs),Q(0));return sum((r[k]*r['weight']for r in rs),Q(0))/mass if mass else None\n mb,ma,cb,ca=mean(b,'before'),mean(a,'after'),mean(c,'before'),mean(c,'after');full=all(x is not None for x in [mb,ma,cb,ca]);change=ma-mb if mb is not None and ma is not None else None\n return dict(sourceUnits=len(data),beforeAvailableUnits=len(b),afterAvailableUnits=len(a),commonUnits=len(c),beforeAvailableMean=mb,afterAvailableMean=ma,beforeCommonMean=cb,afterCommonMean=ca,availableMeanChange=change,commonWithinChange=ca-cb if full else None,afterFrameShift=ma-ca if full else None,beforeFrameShift=cb-mb if full else None,exactDecompositionResidual=change-((ma-ca)+(ca-cb)+(cb-mb))if full else None)\ndef productivity(output0,output1,hours0,hours1):\n o0,o1,h0,h1=map(number,[output0,output1,hours0,hours1])\n if min(o0,o1,h0,h1)<=0:raise ValueError('positive output and hours required')\n go,gh=o1/o0,h1/h0;gp=go/gh\n return dict(outputGross=go,hoursGross=gh,productivityGross=gp,outputPercent=(go-1)*100,hoursPercent=(gh-1)*100,productivityPercent=(gp-1)*100,differenceOfPercentGrowths=(go-gh)*100,exactGrowthIdentityResidual=gp-go/gh)\ndef measurement(numerator,denominator,lower=None,upper=None):\n n,d=number(numerator),number(denominator)\n if d<0:raise ValueError('nonnegative denominator required')\n interval=None\n if lower is not None or upper is not None:\n  lo,hi=number(lower),number(upper)\n  if lo<=0 or hi<lo:raise ValueError('ordered positive scenario bounds')\n  interval=sorted([n/lo,n/hi])\n return dict(ratio=n/d if d else None,denominatorScenarioInterval=interval)\ndef read_csv(folder,name):\n with (folder/name).open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))\ndef load_sources(folder):\n h=read_csv(folder,'actual180-KOR-housing-nominal-real-indexes.csv');b=read_csv(folder,'actual38-US-nonfarm-output-hours-productivity-indexes.csv');p=read_csv(folder,'actual10839-person-wage-panel-original-and-prior-derived-fields.csv');c=read_csv(folder,'actual3-Apple-revenue-and-approximate-periodend-FTE-facts.csv')\n company={}\n for r in c:\n  value=Q(r['originalToken'].replace(',',''))\n  company[('revenue'+r['fiscalYear'])if r['fact']=='consolidated total net sales'else'endpointFTE2024']=value*1000000 if r['fact']=='consolidated total net sales'else value\n return dict(housing=h,bls=b,person=p,company=company)\ndef person_comparison(models,before=1976,after=1980):\n if before not in [1976,1978,1980]or after not in [1976,1978,1980]or before>=after:raise ValueError('ordered observed waves required')\n units=defaultdict(dict)\n for r in models['person']:\n  year=int(r['time'])\n  if year in units[r['unit']]:raise ValueError('duplicate original unit-wave')\n  token=r['wageCentsOriginal'];units[r['unit']][year]=None if token in ['.','','NA']else number(token)/100\n return composition([dict(id=k,before=v[before],after=v[after])for k,v in units.items()])\ndef realdata(models,kind):\n if kind=='country':\n  rows=models['housing'];return dict(originalCount=len(rows),growth=growth(rows[0]['nominal'],rows[-1]['nominal']),rebased=rebase([r['nominal']for r in rows]))\n if kind=='person':return person_comparison(models)\n if kind=='company':\n  c=models['company'];return dict(revenueGrowth=growth(c['revenue2023'],c['revenue2024']),ratio=measurement(c['revenue2024'],c['endpointFTE2024'])['ratio'],proxyGrowth=None)\n raise ValueError('actual case required')\ndef encode(v):\n if isinstance(v,Q):return str(v)\n if isinstance(v,dict):return{k:encode(x)for k,x in v.items()}\n if isinstance(v,(list,tuple)):return[encode(x)for x in v]\n return v\ndef write_csv(path,rows):\n with path.open('w',encoding='utf8',newline='')as f:\n  writer=csv.DictWriter(f,fieldnames=list(rows[0]));writer.writeheader();writer.writerows([{k:''if v is None else str(v)for k,v in r.items()}for r in rows])\ndef full_source(folder,out):\n out.mkdir(parents=True,exist_ok=True);models=load_sources(folder);metrics={};country=[];frames=[]\n for source in ['housing','bls']:\n  data=models[source];columns=['nominal','real']if source=='housing'else['outputIndexOriginalToken','hoursIndexOriginalToken','productivityIndexOriginalToken']\n  for col in columns:\n   values=[r[col]for r in data];rb=rebase(values);g=growth(values[0],values[-1])\n   for k,v in g.items():metrics[source+':'+col+':'+k]=v\n   quarter_base=next((i for i,r in enumerate(data)if r['quarter']=='2010-Q1'),None)if source=='housing'else None\n   qb=rebase(values,quarter_base)if quarter_base is not None else[None]*len(values)\n   country.extend(dict(source=source,series=col,row=i+1,quarter=r['quarter'],originalToken=r[col],rebasedFirst100Exact=rb[i],rebased2010Q1Exact=qb[i])for i,r in enumerate(data))\n for a,b in [(1976,1978),(1978,1980),(1976,1980)]:\n  z=person_comparison(models,a,b);frames.append(dict(before=a,after=b,elapsedYears=b-a,**z));metrics.update({f'person:{a}:{b}:{k}':v for k,v in z.items()})\n c=realdata(models,'company');metrics['company:proxy']=c['ratio'];metrics['company:proxyGrowth']=None;metrics.update({'company:sales:'+k:v for k,v in c['revenueGrowth'].items()})\n changes=[]\n for a,b in zip(models['bls'],models['bls'][1:]):\n  z=productivity(a['outputIndexOriginalToken'],b['outputIndexOriginalToken'],a['hoursIndexOriginalToken'],b['hoursIndexOriginalToken']);g=growth(a['productivityIndexOriginalToken'],b['productivityIndexOriginalToken'],4)\n  changes.append(dict(start=a['quarter'],end=b['quarter'],**z,publishedProductivityPercent=g['percentChange'],publishedAnnualizedPercent=g['annualizedPercent']))\n selected=list(dict.fromkeys(r['unit']for r in models['person']))[:12]\n trajectories=[dict(unit=r['unit'],year=r['time'],nominalUSDPerHourExact=None if r['wageCentsOriginal']in['.','','NA']else number(r['wageCentsOriginal'])/100)for r in models['person']if r['unit']in selected]\n write_csv(out/'metrics.csv',[dict(metric=k,value=v)for k,v in metrics.items()]);write_csv(out/'country-indexes.csv',country);write_csv(out/'wage-frames.csv',frames);write_csv(out/'bls-changes.csv',changes);write_csv(out/'first12-trajectories.csv',trajectories)\n (out/'full-results.json').write_text(json.dumps(encode(dict(metrics=metrics,frames=frames,company=c)),ensure_ascii=False,indent=2)+'\\n',encoding='utf8');return{f.name:len(read_csv(out,f.name))for f in out.glob('*.csv')}\nif __name__=='__main__':\n parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--source-dir',type=Path,default=Path(__file__).parent/'econ22-sources');parser.add_argument('--output-dir',type=Path,default=Path(__file__).parent/'econ22-python-results');args=parser.parse_args();print(json.dumps(full_source(args.source_dir,args.output_dir)))\n"
          },
          {
            "file": "econ22-fixed-support.py",
            "sha256": "deb4273c9c713e16c2f5e5d3525932ae34753f348731a3b26a4babff015c2fd6",
            "codeText": "\"\"\"Public fixed-example support. Requires only Python standard library and econ22-reproduce.py.\nFixed examples are separate from current browser inputs. Missing values remain None.\n\"\"\"\nfrom pathlib import Path\nfrom fractions import Fraction as Q\nimport importlib.util,json,csv,html,math\nROOT=Path(__file__).resolve().parent\nspec=importlib.util.spec_from_file_location('econ22_public',ROOT/'econ22-reproduce.py');M=importlib.util.module_from_spec(spec);spec.loader.exec_module(M)\n\ndef example(api,variant):\n if api=='rebase':\n  values=[0,1]if variant=='invalid'else[80,None,120]if variant=='gap'else[80,100,120];z=M.rebase(values);return dict(rows=len(z),defined=sum(x is not None for x in z),last=z[-1]),list(enumerate(z)),'Position','Rebased index'\n if api=='growth':\n  end=90 if variant=='quarterly'else 120;z=M.growth(100,end,4 if variant=='quarterly'else 1);return z,[(0,Q(100)),(1,Q(end))],'Date','Supplied level'\n if api=='composition':\n  rows=[dict(id='A',before=10,after=None),dict(id='B',before=None,after=20)]if variant=='noCommon'else[dict(id='A',before=10,after=11),dict(id='B',before=100,after=None),dict(id='C',before=None,after=1)];z=M.composition(rows);metrics={k:z[k]for k in ['beforeAvailableMean','afterAvailableMean','availableMeanChange','commonWithinChange','commonUnits','exactDecompositionResidual']};return metrics,[(0,z['beforeAvailableMean']),(1,z['afterAvailableMean'])],'Date','Available mean / assumed units'\n if api=='productivity':\n  o,h=(90,80)if variant=='contraction'else(103,101);z=M.productivity(100,o,100,h);return z,[(0,Q(1)),(1,z['productivityGross'])],'Date','Output per hour / initial=1'\n if api=='measurement':\n  n,d=(0,0)if variant=='zero'else(391035000000,164000);z=M.measurement(n,d);return dict(ratio=z['ratio'],denominatorZero=int(d==0),sourceApproximate=int(variant!='zero')),[(0,z['ratio'])],'Ratio position','USD / approximate endpoint FTE'\n models=M.load_sources(ROOT/'econ22-sources');z=M.realdata(models,variant)\n if variant=='country':return dict(sourceRows=z['originalCount'],first=Q(models['housing'][0]['nominal']),last=Q(models['housing'][-1]['nominal']),percentChange=z['growth']['percentChange']),list(enumerate(z['rebased'])),'Quarter position / original calendar','Nominal housing / first=100'\n if variant=='person':return{k:z[k]for k in ['sourceUnits','beforeAvailableUnits','afterAvailableUnits','commonUnits','availableMeanChange','commonWithinChange','exactDecompositionResidual']},[(1976,z['beforeAvailableMean']),(1980,z['afterAvailableMean'])],'Observed wave','Nominal USD/hour / available mean'\n if variant=='company':return dict(sales2023=models['company']['revenue2023'],sales2024=models['company']['revenue2024'],proxy=z['ratio'],proxyGrowth=None),[(2023,models['company']['revenue2023']/1000000),(2024,models['company']['revenue2024']/1000000)],'Fiscal year','Nominal USD millions'\n raise ValueError('fixed example name required')\n\ndef svg(points,xlabel,ylabel):\n good=[(float(x),float(y))for x,y in points if y is not None]\n if not good:return None\n if any(not math.isfinite(x)or not math.isfinite(y)for x,y in good):raise ValueError('outside finite plotting range')\n w,h,L,R,T,B=640,360,90,22,28,54;xmin=min(float(p[0])for p in points);xmax=max(float(p[0])for p in points);ymin=min(y for x,y in good);ymax=max(y for x,y in good)\n pad=max(1,abs(ymin)*.05)if ymin==ymax else(ymax-ymin)*.08;ymin-=pad;ymax+=pad\n X=lambda x:(L+w-R)/2 if xmax==xmin else L+(float(x)-xmin)/(xmax-xmin)*(w-L-R);Y=lambda y:T+(ymax-float(y))/(ymax-ymin)*(h-T-B);esc=html.escape\n s=f'<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"640\" height=\"360\" viewBox=\"0 0 640 360\" role=\"img\" aria-label=\"{esc(xlabel+\"; \"+ylabel)}\"><title>{esc(xlabel+\"; \"+ylabel)}</title><rect width=\"640\" height=\"360\" fill=\"white\"/><g font-family=\"sans-serif\" font-size=\"13\" fill=\"#222\">'\n for i in range(4):\n  v=ymin+(ymax-ymin)*i/3;y=Y(v);s+=f'<line x1=\"{L}\" x2=\"{w-R}\" y1=\"{y}\" y2=\"{y}\" stroke=\"#ccd6db\"/><text x=\"{L-7}\" y=\"{y+4}\" text-anchor=\"end\">{v:.4g}</text>'\n for x,anchor in([(xmin,'middle')]if xmin==xmax else[(xmin,'start'),(xmax,'end')]):s+=f'<text x=\"{X(x)}\" y=\"{h-B+24}\" text-anchor=\"{anchor}\">{x:g}</text>'\n last=None\n for x,y in points:\n  if y is None:last=None;continue\n  a,b=X(x),Y(y)\n  if last:s+=f'<line x1=\"{last[0]}\" y1=\"{last[1]}\" x2=\"{a}\" y2=\"{b}\" stroke=\"#355c72\" stroke-width=\"2\"/>'\n  s+=f'<circle cx=\"{a}\" cy=\"{b}\" r=\"3\" fill=\"#934b34\"><title>{esc(str(x)+\": \"+str(y))}</title></circle>';last=(a,b)\n return s+f'<text x=\"{L}\" y=\"16\">{esc(ylabel)}</text><text x=\"{w-R}\" y=\"{h-6}\" text-anchor=\"end\">{esc(xlabel)}</text></g></svg>'\n\ndef run(api,variant,output):\n out=Path(output);out.mkdir(parents=True,exist_ok=True);metrics,points,x,y=example(api,variant);encoded=M.encode(metrics);(out/'summary.json').write_text(json.dumps(encoded,indent=2)+'\\n',encoding='utf8')\n M.write_csv(out/'summary.csv',[dict(metric=k,value=v)for k,v in metrics.items()]);M.write_csv(out/'plot-points.csv',[dict(x=a,y=b)for a,b in points]);graphic=svg(points,x,y)\n if graphic is not None:(out/'plot.svg').write_text(graphic,encoding='utf8')\n print(json.dumps(dict(api=api,variant=variant,metrics=encoded,plotProduced=graphic is not None),ensure_ascii=False))\n"
          }
        ],
        "inputFiles": [],
        "returnCode": 0,
        "expectedFailure": false,
        "stdout": "{\"api\": \"rebase\", \"variant\": \"default\", \"metrics\": {\"rows\": 3, \"defined\": 3, \"last\": \"150\"}, \"plotProduced\": true}\n",
        "stderr": "",
        "seconds": 0.125,
        "summary": {
          "rows": "3",
          "defined": "3",
          "last": "150"
        },
        "plotPoints": [
          {
            "x": "0",
            "y": "100"
          },
          {
            "x": "1",
            "y": "125"
          },
          {
            "x": "2",
            "y": "150"
          }
        ],
        "plotFile": "econ22-fixed-results/rebase-default-python/plot.svg",
        "plotSHA256": "f0ad097dd6951525a2be7dd78a2209f8dbeb0820145dd915a66b02bb9e888695",
        "scope": "Actually executed fixed example. Current browser controls are calculated separately by JavaScript. Base-R outputs use finite precision; Python outputs use exact fractions.",
        "summaryFile": "econ22-fixed-results/rebase-default-python/summary.csv",
        "summarySHA256": "a8c64472812c317d8962875696a6bee480649229fc42f8ae1a2858664e4e7f6f",
        "plotPointsFile": "econ22-fixed-results/rebase-default-python/plot-points.csv",
        "plotPointsSHA256": "777ed53d89eb402b13111d44561af6088aa3501871412610451d59879f571acb"
      },
      "gap": {
        "api": "rebase",
        "variant": "gap",
        "language": "python",
        "codeFile": "econ22-code/rebase-gap.py",
        "codeSHA256": "94c20cb7f499683ee6edc6398e379af2e504ead7d93ee44b5500181ab7321e7d",
        "codeText": "# Fixed stated example, separate from current web controls.\nfrom pathlib import Path\nimport importlib.util,sys\nroot=Path(__file__).resolve().parents[1]\nspec=importlib.util.spec_from_file_location('fixed_support',root/'econ22-fixed-support.py')\nsupport=importlib.util.module_from_spec(spec);spec.loader.exec_module(support)\ntry:support.run('rebase','gap',sys.argv[1]if len(sys.argv)>1 else root/'econ22-fixed-results/rebase-gap-python')\nexcept ValueError as error:\n print('Rejected declared input: '+str(error),file=sys.stderr);sys.exit(2)\n",
        "supportFiles": [
          {
            "file": "econ22-reproduce.py",
            "sha256": "cc5631d9dfea963b64349bb28d18b69ad3caf15a15162ec6cea786a36e18de48",
            "codeText": "#!/usr/bin/env python3\n\"\"\"ECON22 public reproduction: Python standard library, exact Fraction arithmetic.\nRun: python econ22-reproduce.py --source-dir econ22-sources --output-dir econ22-python-results\nOriginal CSV inputs are read only. Output is a new chosen directory.\nThese are descriptive arithmetic and explicitly assumed examples, not causal estimates.\n\"\"\"\nfrom fractions import Fraction as Q\nfrom pathlib import Path\nfrom collections import defaultdict\nimport argparse,csv,json\n\ndef number(x):\n if x is None:raise ValueError('missing numeric token')\n return Q(str(x))\ndef rebase(values,base=0,scale='100'):\n v=[None if x is None else number(x)for x in values];s=number(scale)\n if not v or not 0<=base<len(v)or v[base]is None or v[base]<=0 or s<=0:raise ValueError('positive observed base/scale required')\n return [None if x is None else s*x/v[base]for x in v]\ndef growth(start,end,periods=1):\n a,b=number(start),number(end)\n if a<=0 or b<0 or not isinstance(periods,int)or not 1<=periods<=12:raise ValueError('growth domain')\n g=b/a;return dict(gross=g,percentChange=(g-1)*100,annualizedGross=g**periods,annualizedPercent=(g**periods-1)*100)\ndef composition(rows):\n seen=set();data=[]\n for r in rows:\n  identifier=str(r['id']);weight=number(r.get('weight','1'))\n  if identifier in seen or weight<0:raise ValueError('unique units/nonnegative fixed weights required')\n  seen.add(identifier);data.append(dict(id=identifier,weight=weight,before=None if r['before']is None else number(r['before']),after=None if r['after']is None else number(r['after'])))\n if not data:raise ValueError('nonempty frame required')\n valid=[r for r in data if r['weight']>0];b=[r for r in valid if r['before']is not None];a=[r for r in valid if r['after']is not None];c=[r for r in valid if r['before']is not None and r['after']is not None]\n def mean(rs,k):\n  mass=sum((r['weight']for r in rs),Q(0));return sum((r[k]*r['weight']for r in rs),Q(0))/mass if mass else None\n mb,ma,cb,ca=mean(b,'before'),mean(a,'after'),mean(c,'before'),mean(c,'after');full=all(x is not None for x in [mb,ma,cb,ca]);change=ma-mb if mb is not None and ma is not None else None\n return dict(sourceUnits=len(data),beforeAvailableUnits=len(b),afterAvailableUnits=len(a),commonUnits=len(c),beforeAvailableMean=mb,afterAvailableMean=ma,beforeCommonMean=cb,afterCommonMean=ca,availableMeanChange=change,commonWithinChange=ca-cb if full else None,afterFrameShift=ma-ca if full else None,beforeFrameShift=cb-mb if full else None,exactDecompositionResidual=change-((ma-ca)+(ca-cb)+(cb-mb))if full else None)\ndef productivity(output0,output1,hours0,hours1):\n o0,o1,h0,h1=map(number,[output0,output1,hours0,hours1])\n if min(o0,o1,h0,h1)<=0:raise ValueError('positive output and hours required')\n go,gh=o1/o0,h1/h0;gp=go/gh\n return dict(outputGross=go,hoursGross=gh,productivityGross=gp,outputPercent=(go-1)*100,hoursPercent=(gh-1)*100,productivityPercent=(gp-1)*100,differenceOfPercentGrowths=(go-gh)*100,exactGrowthIdentityResidual=gp-go/gh)\ndef measurement(numerator,denominator,lower=None,upper=None):\n n,d=number(numerator),number(denominator)\n if d<0:raise ValueError('nonnegative denominator required')\n interval=None\n if lower is not None or upper is not None:\n  lo,hi=number(lower),number(upper)\n  if lo<=0 or hi<lo:raise ValueError('ordered positive scenario bounds')\n  interval=sorted([n/lo,n/hi])\n return dict(ratio=n/d if d else None,denominatorScenarioInterval=interval)\ndef read_csv(folder,name):\n with (folder/name).open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))\ndef load_sources(folder):\n h=read_csv(folder,'actual180-KOR-housing-nominal-real-indexes.csv');b=read_csv(folder,'actual38-US-nonfarm-output-hours-productivity-indexes.csv');p=read_csv(folder,'actual10839-person-wage-panel-original-and-prior-derived-fields.csv');c=read_csv(folder,'actual3-Apple-revenue-and-approximate-periodend-FTE-facts.csv')\n company={}\n for r in c:\n  value=Q(r['originalToken'].replace(',',''))\n  company[('revenue'+r['fiscalYear'])if r['fact']=='consolidated total net sales'else'endpointFTE2024']=value*1000000 if r['fact']=='consolidated total net sales'else value\n return dict(housing=h,bls=b,person=p,company=company)\ndef person_comparison(models,before=1976,after=1980):\n if before not in [1976,1978,1980]or after not in [1976,1978,1980]or before>=after:raise ValueError('ordered observed waves required')\n units=defaultdict(dict)\n for r in models['person']:\n  year=int(r['time'])\n  if year in units[r['unit']]:raise ValueError('duplicate original unit-wave')\n  token=r['wageCentsOriginal'];units[r['unit']][year]=None if token in ['.','','NA']else number(token)/100\n return composition([dict(id=k,before=v[before],after=v[after])for k,v in units.items()])\ndef realdata(models,kind):\n if kind=='country':\n  rows=models['housing'];return dict(originalCount=len(rows),growth=growth(rows[0]['nominal'],rows[-1]['nominal']),rebased=rebase([r['nominal']for r in rows]))\n if kind=='person':return person_comparison(models)\n if kind=='company':\n  c=models['company'];return dict(revenueGrowth=growth(c['revenue2023'],c['revenue2024']),ratio=measurement(c['revenue2024'],c['endpointFTE2024'])['ratio'],proxyGrowth=None)\n raise ValueError('actual case required')\ndef encode(v):\n if isinstance(v,Q):return str(v)\n if isinstance(v,dict):return{k:encode(x)for k,x in v.items()}\n if isinstance(v,(list,tuple)):return[encode(x)for x in v]\n return v\ndef write_csv(path,rows):\n with path.open('w',encoding='utf8',newline='')as f:\n  writer=csv.DictWriter(f,fieldnames=list(rows[0]));writer.writeheader();writer.writerows([{k:''if v is None else str(v)for k,v in r.items()}for r in rows])\ndef full_source(folder,out):\n out.mkdir(parents=True,exist_ok=True);models=load_sources(folder);metrics={};country=[];frames=[]\n for source in ['housing','bls']:\n  data=models[source];columns=['nominal','real']if source=='housing'else['outputIndexOriginalToken','hoursIndexOriginalToken','productivityIndexOriginalToken']\n  for col in columns:\n   values=[r[col]for r in data];rb=rebase(values);g=growth(values[0],values[-1])\n   for k,v in g.items():metrics[source+':'+col+':'+k]=v\n   quarter_base=next((i for i,r in enumerate(data)if r['quarter']=='2010-Q1'),None)if source=='housing'else None\n   qb=rebase(values,quarter_base)if quarter_base is not None else[None]*len(values)\n   country.extend(dict(source=source,series=col,row=i+1,quarter=r['quarter'],originalToken=r[col],rebasedFirst100Exact=rb[i],rebased2010Q1Exact=qb[i])for i,r in enumerate(data))\n for a,b in [(1976,1978),(1978,1980),(1976,1980)]:\n  z=person_comparison(models,a,b);frames.append(dict(before=a,after=b,elapsedYears=b-a,**z));metrics.update({f'person:{a}:{b}:{k}':v for k,v in z.items()})\n c=realdata(models,'company');metrics['company:proxy']=c['ratio'];metrics['company:proxyGrowth']=None;metrics.update({'company:sales:'+k:v for k,v in c['revenueGrowth'].items()})\n changes=[]\n for a,b in zip(models['bls'],models['bls'][1:]):\n  z=productivity(a['outputIndexOriginalToken'],b['outputIndexOriginalToken'],a['hoursIndexOriginalToken'],b['hoursIndexOriginalToken']);g=growth(a['productivityIndexOriginalToken'],b['productivityIndexOriginalToken'],4)\n  changes.append(dict(start=a['quarter'],end=b['quarter'],**z,publishedProductivityPercent=g['percentChange'],publishedAnnualizedPercent=g['annualizedPercent']))\n selected=list(dict.fromkeys(r['unit']for r in models['person']))[:12]\n trajectories=[dict(unit=r['unit'],year=r['time'],nominalUSDPerHourExact=None if r['wageCentsOriginal']in['.','','NA']else number(r['wageCentsOriginal'])/100)for r in models['person']if r['unit']in selected]\n write_csv(out/'metrics.csv',[dict(metric=k,value=v)for k,v in metrics.items()]);write_csv(out/'country-indexes.csv',country);write_csv(out/'wage-frames.csv',frames);write_csv(out/'bls-changes.csv',changes);write_csv(out/'first12-trajectories.csv',trajectories)\n (out/'full-results.json').write_text(json.dumps(encode(dict(metrics=metrics,frames=frames,company=c)),ensure_ascii=False,indent=2)+'\\n',encoding='utf8');return{f.name:len(read_csv(out,f.name))for f in out.glob('*.csv')}\nif __name__=='__main__':\n parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--source-dir',type=Path,default=Path(__file__).parent/'econ22-sources');parser.add_argument('--output-dir',type=Path,default=Path(__file__).parent/'econ22-python-results');args=parser.parse_args();print(json.dumps(full_source(args.source_dir,args.output_dir)))\n"
          },
          {
            "file": "econ22-fixed-support.py",
            "sha256": "deb4273c9c713e16c2f5e5d3525932ae34753f348731a3b26a4babff015c2fd6",
            "codeText": "\"\"\"Public fixed-example support. Requires only Python standard library and econ22-reproduce.py.\nFixed examples are separate from current browser inputs. Missing values remain None.\n\"\"\"\nfrom pathlib import Path\nfrom fractions import Fraction as Q\nimport importlib.util,json,csv,html,math\nROOT=Path(__file__).resolve().parent\nspec=importlib.util.spec_from_file_location('econ22_public',ROOT/'econ22-reproduce.py');M=importlib.util.module_from_spec(spec);spec.loader.exec_module(M)\n\ndef example(api,variant):\n if api=='rebase':\n  values=[0,1]if variant=='invalid'else[80,None,120]if variant=='gap'else[80,100,120];z=M.rebase(values);return dict(rows=len(z),defined=sum(x is not None for x in z),last=z[-1]),list(enumerate(z)),'Position','Rebased index'\n if api=='growth':\n  end=90 if variant=='quarterly'else 120;z=M.growth(100,end,4 if variant=='quarterly'else 1);return z,[(0,Q(100)),(1,Q(end))],'Date','Supplied level'\n if api=='composition':\n  rows=[dict(id='A',before=10,after=None),dict(id='B',before=None,after=20)]if variant=='noCommon'else[dict(id='A',before=10,after=11),dict(id='B',before=100,after=None),dict(id='C',before=None,after=1)];z=M.composition(rows);metrics={k:z[k]for k in ['beforeAvailableMean','afterAvailableMean','availableMeanChange','commonWithinChange','commonUnits','exactDecompositionResidual']};return metrics,[(0,z['beforeAvailableMean']),(1,z['afterAvailableMean'])],'Date','Available mean / assumed units'\n if api=='productivity':\n  o,h=(90,80)if variant=='contraction'else(103,101);z=M.productivity(100,o,100,h);return z,[(0,Q(1)),(1,z['productivityGross'])],'Date','Output per hour / initial=1'\n if api=='measurement':\n  n,d=(0,0)if variant=='zero'else(391035000000,164000);z=M.measurement(n,d);return dict(ratio=z['ratio'],denominatorZero=int(d==0),sourceApproximate=int(variant!='zero')),[(0,z['ratio'])],'Ratio position','USD / approximate endpoint FTE'\n models=M.load_sources(ROOT/'econ22-sources');z=M.realdata(models,variant)\n if variant=='country':return dict(sourceRows=z['originalCount'],first=Q(models['housing'][0]['nominal']),last=Q(models['housing'][-1]['nominal']),percentChange=z['growth']['percentChange']),list(enumerate(z['rebased'])),'Quarter position / original calendar','Nominal housing / first=100'\n if variant=='person':return{k:z[k]for k in ['sourceUnits','beforeAvailableUnits','afterAvailableUnits','commonUnits','availableMeanChange','commonWithinChange','exactDecompositionResidual']},[(1976,z['beforeAvailableMean']),(1980,z['afterAvailableMean'])],'Observed wave','Nominal USD/hour / available mean'\n if variant=='company':return dict(sales2023=models['company']['revenue2023'],sales2024=models['company']['revenue2024'],proxy=z['ratio'],proxyGrowth=None),[(2023,models['company']['revenue2023']/1000000),(2024,models['company']['revenue2024']/1000000)],'Fiscal year','Nominal USD millions'\n raise ValueError('fixed example name required')\n\ndef svg(points,xlabel,ylabel):\n good=[(float(x),float(y))for x,y in points if y is not None]\n if not good:return None\n if any(not math.isfinite(x)or not math.isfinite(y)for x,y in good):raise ValueError('outside finite plotting range')\n w,h,L,R,T,B=640,360,90,22,28,54;xmin=min(float(p[0])for p in points);xmax=max(float(p[0])for p in points);ymin=min(y for x,y in good);ymax=max(y for x,y in good)\n pad=max(1,abs(ymin)*.05)if ymin==ymax else(ymax-ymin)*.08;ymin-=pad;ymax+=pad\n X=lambda x:(L+w-R)/2 if xmax==xmin else L+(float(x)-xmin)/(xmax-xmin)*(w-L-R);Y=lambda y:T+(ymax-float(y))/(ymax-ymin)*(h-T-B);esc=html.escape\n s=f'<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"640\" height=\"360\" viewBox=\"0 0 640 360\" role=\"img\" aria-label=\"{esc(xlabel+\"; \"+ylabel)}\"><title>{esc(xlabel+\"; \"+ylabel)}</title><rect width=\"640\" height=\"360\" fill=\"white\"/><g font-family=\"sans-serif\" font-size=\"13\" fill=\"#222\">'\n for i in range(4):\n  v=ymin+(ymax-ymin)*i/3;y=Y(v);s+=f'<line x1=\"{L}\" x2=\"{w-R}\" y1=\"{y}\" y2=\"{y}\" stroke=\"#ccd6db\"/><text x=\"{L-7}\" y=\"{y+4}\" text-anchor=\"end\">{v:.4g}</text>'\n for x,anchor in([(xmin,'middle')]if xmin==xmax else[(xmin,'start'),(xmax,'end')]):s+=f'<text x=\"{X(x)}\" y=\"{h-B+24}\" text-anchor=\"{anchor}\">{x:g}</text>'\n last=None\n for x,y in points:\n  if y is None:last=None;continue\n  a,b=X(x),Y(y)\n  if last:s+=f'<line x1=\"{last[0]}\" y1=\"{last[1]}\" x2=\"{a}\" y2=\"{b}\" stroke=\"#355c72\" stroke-width=\"2\"/>'\n  s+=f'<circle cx=\"{a}\" cy=\"{b}\" r=\"3\" fill=\"#934b34\"><title>{esc(str(x)+\": \"+str(y))}</title></circle>';last=(a,b)\n return s+f'<text x=\"{L}\" y=\"16\">{esc(ylabel)}</text><text x=\"{w-R}\" y=\"{h-6}\" text-anchor=\"end\">{esc(xlabel)}</text></g></svg>'\n\ndef run(api,variant,output):\n out=Path(output);out.mkdir(parents=True,exist_ok=True);metrics,points,x,y=example(api,variant);encoded=M.encode(metrics);(out/'summary.json').write_text(json.dumps(encoded,indent=2)+'\\n',encoding='utf8')\n M.write_csv(out/'summary.csv',[dict(metric=k,value=v)for k,v in metrics.items()]);M.write_csv(out/'plot-points.csv',[dict(x=a,y=b)for a,b in points]);graphic=svg(points,x,y)\n if graphic is not None:(out/'plot.svg').write_text(graphic,encoding='utf8')\n print(json.dumps(dict(api=api,variant=variant,metrics=encoded,plotProduced=graphic is not None),ensure_ascii=False))\n"
          }
        ],
        "inputFiles": [],
        "returnCode": 0,
        "expectedFailure": false,
        "stdout": "{\"api\": \"rebase\", \"variant\": \"gap\", \"metrics\": {\"rows\": 3, \"defined\": 2, \"last\": \"150\"}, \"plotProduced\": true}\n",
        "stderr": "",
        "seconds": 0.125,
        "summary": {
          "rows": "3",
          "defined": "2",
          "last": "150"
        },
        "plotPoints": [
          {
            "x": "0",
            "y": "100"
          },
          {
            "x": "1",
            "y": ""
          },
          {
            "x": "2",
            "y": "150"
          }
        ],
        "plotFile": "econ22-fixed-results/rebase-gap-python/plot.svg",
        "plotSHA256": "1df9f91cc22fc701417766a5f329458d0967dd6046e4895b87ba15f10e62d9e2",
        "scope": "Actually executed fixed example. Current browser controls are calculated separately by JavaScript. Base-R outputs use finite precision; Python outputs use exact fractions.",
        "summaryFile": "econ22-fixed-results/rebase-gap-python/summary.csv",
        "summarySHA256": "7a13dc0ff2ba08edf537b508d64e76cd52b3aca6764ef8fbdd62f2798ed8112d",
        "plotPointsFile": "econ22-fixed-results/rebase-gap-python/plot-points.csv",
        "plotPointsSHA256": "687f9e35f07252d7d674dad776d367cd4836489f343b4462151659aedc7a6d71"
      },
      "invalid": {
        "api": "rebase",
        "variant": "invalid",
        "language": "python",
        "codeFile": "econ22-code/rebase-invalid.py",
        "codeSHA256": "f6152fbd4b8eb35beba1e65470822d9f6b75c0c409734f94d2524638549c7163",
        "codeText": "# Fixed stated example, separate from current web controls.\nfrom pathlib import Path\nimport importlib.util,sys\nroot=Path(__file__).resolve().parents[1]\nspec=importlib.util.spec_from_file_location('fixed_support',root/'econ22-fixed-support.py')\nsupport=importlib.util.module_from_spec(spec);spec.loader.exec_module(support)\ntry:support.run('rebase','invalid',sys.argv[1]if len(sys.argv)>1 else root/'econ22-fixed-results/rebase-invalid-python')\nexcept ValueError as error:\n print('Rejected declared input: '+str(error),file=sys.stderr);sys.exit(2)\n",
        "supportFiles": [
          {
            "file": "econ22-reproduce.py",
            "sha256": "cc5631d9dfea963b64349bb28d18b69ad3caf15a15162ec6cea786a36e18de48",
            "codeText": "#!/usr/bin/env python3\n\"\"\"ECON22 public reproduction: Python standard library, exact Fraction arithmetic.\nRun: python econ22-reproduce.py --source-dir econ22-sources --output-dir econ22-python-results\nOriginal CSV inputs are read only. Output is a new chosen directory.\nThese are descriptive arithmetic and explicitly assumed examples, not causal estimates.\n\"\"\"\nfrom fractions import Fraction as Q\nfrom pathlib import Path\nfrom collections import defaultdict\nimport argparse,csv,json\n\ndef number(x):\n if x is None:raise ValueError('missing numeric token')\n return Q(str(x))\ndef rebase(values,base=0,scale='100'):\n v=[None if x is None else number(x)for x in values];s=number(scale)\n if not v or not 0<=base<len(v)or v[base]is None or v[base]<=0 or s<=0:raise ValueError('positive observed base/scale required')\n return [None if x is None else s*x/v[base]for x in v]\ndef growth(start,end,periods=1):\n a,b=number(start),number(end)\n if a<=0 or b<0 or not isinstance(periods,int)or not 1<=periods<=12:raise ValueError('growth domain')\n g=b/a;return dict(gross=g,percentChange=(g-1)*100,annualizedGross=g**periods,annualizedPercent=(g**periods-1)*100)\ndef composition(rows):\n seen=set();data=[]\n for r in rows:\n  identifier=str(r['id']);weight=number(r.get('weight','1'))\n  if identifier in seen or weight<0:raise ValueError('unique units/nonnegative fixed weights required')\n  seen.add(identifier);data.append(dict(id=identifier,weight=weight,before=None if r['before']is None else number(r['before']),after=None if r['after']is None else number(r['after'])))\n if not data:raise ValueError('nonempty frame required')\n valid=[r for r in data if r['weight']>0];b=[r for r in valid if r['before']is not None];a=[r for r in valid if r['after']is not None];c=[r for r in valid if r['before']is not None and r['after']is not None]\n def mean(rs,k):\n  mass=sum((r['weight']for r in rs),Q(0));return sum((r[k]*r['weight']for r in rs),Q(0))/mass if mass else None\n mb,ma,cb,ca=mean(b,'before'),mean(a,'after'),mean(c,'before'),mean(c,'after');full=all(x is not None for x in [mb,ma,cb,ca]);change=ma-mb if mb is not None and ma is not None else None\n return dict(sourceUnits=len(data),beforeAvailableUnits=len(b),afterAvailableUnits=len(a),commonUnits=len(c),beforeAvailableMean=mb,afterAvailableMean=ma,beforeCommonMean=cb,afterCommonMean=ca,availableMeanChange=change,commonWithinChange=ca-cb if full else None,afterFrameShift=ma-ca if full else None,beforeFrameShift=cb-mb if full else None,exactDecompositionResidual=change-((ma-ca)+(ca-cb)+(cb-mb))if full else None)\ndef productivity(output0,output1,hours0,hours1):\n o0,o1,h0,h1=map(number,[output0,output1,hours0,hours1])\n if min(o0,o1,h0,h1)<=0:raise ValueError('positive output and hours required')\n go,gh=o1/o0,h1/h0;gp=go/gh\n return dict(outputGross=go,hoursGross=gh,productivityGross=gp,outputPercent=(go-1)*100,hoursPercent=(gh-1)*100,productivityPercent=(gp-1)*100,differenceOfPercentGrowths=(go-gh)*100,exactGrowthIdentityResidual=gp-go/gh)\ndef measurement(numerator,denominator,lower=None,upper=None):\n n,d=number(numerator),number(denominator)\n if d<0:raise ValueError('nonnegative denominator required')\n interval=None\n if lower is not None or upper is not None:\n  lo,hi=number(lower),number(upper)\n  if lo<=0 or hi<lo:raise ValueError('ordered positive scenario bounds')\n  interval=sorted([n/lo,n/hi])\n return dict(ratio=n/d if d else None,denominatorScenarioInterval=interval)\ndef read_csv(folder,name):\n with (folder/name).open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))\ndef load_sources(folder):\n h=read_csv(folder,'actual180-KOR-housing-nominal-real-indexes.csv');b=read_csv(folder,'actual38-US-nonfarm-output-hours-productivity-indexes.csv');p=read_csv(folder,'actual10839-person-wage-panel-original-and-prior-derived-fields.csv');c=read_csv(folder,'actual3-Apple-revenue-and-approximate-periodend-FTE-facts.csv')\n company={}\n for r in c:\n  value=Q(r['originalToken'].replace(',',''))\n  company[('revenue'+r['fiscalYear'])if r['fact']=='consolidated total net sales'else'endpointFTE2024']=value*1000000 if r['fact']=='consolidated total net sales'else value\n return dict(housing=h,bls=b,person=p,company=company)\ndef person_comparison(models,before=1976,after=1980):\n if before not in [1976,1978,1980]or after not in [1976,1978,1980]or before>=after:raise ValueError('ordered observed waves required')\n units=defaultdict(dict)\n for r in models['person']:\n  year=int(r['time'])\n  if year in units[r['unit']]:raise ValueError('duplicate original unit-wave')\n  token=r['wageCentsOriginal'];units[r['unit']][year]=None if token in ['.','','NA']else number(token)/100\n return composition([dict(id=k,before=v[before],after=v[after])for k,v in units.items()])\ndef realdata(models,kind):\n if kind=='country':\n  rows=models['housing'];return dict(originalCount=len(rows),growth=growth(rows[0]['nominal'],rows[-1]['nominal']),rebased=rebase([r['nominal']for r in rows]))\n if kind=='person':return person_comparison(models)\n if kind=='company':\n  c=models['company'];return dict(revenueGrowth=growth(c['revenue2023'],c['revenue2024']),ratio=measurement(c['revenue2024'],c['endpointFTE2024'])['ratio'],proxyGrowth=None)\n raise ValueError('actual case required')\ndef encode(v):\n if isinstance(v,Q):return str(v)\n if isinstance(v,dict):return{k:encode(x)for k,x in v.items()}\n if isinstance(v,(list,tuple)):return[encode(x)for x in v]\n return v\ndef write_csv(path,rows):\n with path.open('w',encoding='utf8',newline='')as f:\n  writer=csv.DictWriter(f,fieldnames=list(rows[0]));writer.writeheader();writer.writerows([{k:''if v is None else str(v)for k,v in r.items()}for r in rows])\ndef full_source(folder,out):\n out.mkdir(parents=True,exist_ok=True);models=load_sources(folder);metrics={};country=[];frames=[]\n for source in ['housing','bls']:\n  data=models[source];columns=['nominal','real']if source=='housing'else['outputIndexOriginalToken','hoursIndexOriginalToken','productivityIndexOriginalToken']\n  for col in columns:\n   values=[r[col]for r in data];rb=rebase(values);g=growth(values[0],values[-1])\n   for k,v in g.items():metrics[source+':'+col+':'+k]=v\n   quarter_base=next((i for i,r in enumerate(data)if r['quarter']=='2010-Q1'),None)if source=='housing'else None\n   qb=rebase(values,quarter_base)if quarter_base is not None else[None]*len(values)\n   country.extend(dict(source=source,series=col,row=i+1,quarter=r['quarter'],originalToken=r[col],rebasedFirst100Exact=rb[i],rebased2010Q1Exact=qb[i])for i,r in enumerate(data))\n for a,b in [(1976,1978),(1978,1980),(1976,1980)]:\n  z=person_comparison(models,a,b);frames.append(dict(before=a,after=b,elapsedYears=b-a,**z));metrics.update({f'person:{a}:{b}:{k}':v for k,v in z.items()})\n c=realdata(models,'company');metrics['company:proxy']=c['ratio'];metrics['company:proxyGrowth']=None;metrics.update({'company:sales:'+k:v for k,v in c['revenueGrowth'].items()})\n changes=[]\n for a,b in zip(models['bls'],models['bls'][1:]):\n  z=productivity(a['outputIndexOriginalToken'],b['outputIndexOriginalToken'],a['hoursIndexOriginalToken'],b['hoursIndexOriginalToken']);g=growth(a['productivityIndexOriginalToken'],b['productivityIndexOriginalToken'],4)\n  changes.append(dict(start=a['quarter'],end=b['quarter'],**z,publishedProductivityPercent=g['percentChange'],publishedAnnualizedPercent=g['annualizedPercent']))\n selected=list(dict.fromkeys(r['unit']for r in models['person']))[:12]\n trajectories=[dict(unit=r['unit'],year=r['time'],nominalUSDPerHourExact=None if r['wageCentsOriginal']in['.','','NA']else number(r['wageCentsOriginal'])/100)for r in models['person']if r['unit']in selected]\n write_csv(out/'metrics.csv',[dict(metric=k,value=v)for k,v in metrics.items()]);write_csv(out/'country-indexes.csv',country);write_csv(out/'wage-frames.csv',frames);write_csv(out/'bls-changes.csv',changes);write_csv(out/'first12-trajectories.csv',trajectories)\n (out/'full-results.json').write_text(json.dumps(encode(dict(metrics=metrics,frames=frames,company=c)),ensure_ascii=False,indent=2)+'\\n',encoding='utf8');return{f.name:len(read_csv(out,f.name))for f in out.glob('*.csv')}\nif __name__=='__main__':\n parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--source-dir',type=Path,default=Path(__file__).parent/'econ22-sources');parser.add_argument('--output-dir',type=Path,default=Path(__file__).parent/'econ22-python-results');args=parser.parse_args();print(json.dumps(full_source(args.source_dir,args.output_dir)))\n"
          },
          {
            "file": "econ22-fixed-support.py",
            "sha256": "deb4273c9c713e16c2f5e5d3525932ae34753f348731a3b26a4babff015c2fd6",
            "codeText": "\"\"\"Public fixed-example support. Requires only Python standard library and econ22-reproduce.py.\nFixed examples are separate from current browser inputs. Missing values remain None.\n\"\"\"\nfrom pathlib import Path\nfrom fractions import Fraction as Q\nimport importlib.util,json,csv,html,math\nROOT=Path(__file__).resolve().parent\nspec=importlib.util.spec_from_file_location('econ22_public',ROOT/'econ22-reproduce.py');M=importlib.util.module_from_spec(spec);spec.loader.exec_module(M)\n\ndef example(api,variant):\n if api=='rebase':\n  values=[0,1]if variant=='invalid'else[80,None,120]if variant=='gap'else[80,100,120];z=M.rebase(values);return dict(rows=len(z),defined=sum(x is not None for x in z),last=z[-1]),list(enumerate(z)),'Position','Rebased index'\n if api=='growth':\n  end=90 if variant=='quarterly'else 120;z=M.growth(100,end,4 if variant=='quarterly'else 1);return z,[(0,Q(100)),(1,Q(end))],'Date','Supplied level'\n if api=='composition':\n  rows=[dict(id='A',before=10,after=None),dict(id='B',before=None,after=20)]if variant=='noCommon'else[dict(id='A',before=10,after=11),dict(id='B',before=100,after=None),dict(id='C',before=None,after=1)];z=M.composition(rows);metrics={k:z[k]for k in ['beforeAvailableMean','afterAvailableMean','availableMeanChange','commonWithinChange','commonUnits','exactDecompositionResidual']};return metrics,[(0,z['beforeAvailableMean']),(1,z['afterAvailableMean'])],'Date','Available mean / assumed units'\n if api=='productivity':\n  o,h=(90,80)if variant=='contraction'else(103,101);z=M.productivity(100,o,100,h);return z,[(0,Q(1)),(1,z['productivityGross'])],'Date','Output per hour / initial=1'\n if api=='measurement':\n  n,d=(0,0)if variant=='zero'else(391035000000,164000);z=M.measurement(n,d);return dict(ratio=z['ratio'],denominatorZero=int(d==0),sourceApproximate=int(variant!='zero')),[(0,z['ratio'])],'Ratio position','USD / approximate endpoint FTE'\n models=M.load_sources(ROOT/'econ22-sources');z=M.realdata(models,variant)\n if variant=='country':return dict(sourceRows=z['originalCount'],first=Q(models['housing'][0]['nominal']),last=Q(models['housing'][-1]['nominal']),percentChange=z['growth']['percentChange']),list(enumerate(z['rebased'])),'Quarter position / original calendar','Nominal housing / first=100'\n if variant=='person':return{k:z[k]for k in ['sourceUnits','beforeAvailableUnits','afterAvailableUnits','commonUnits','availableMeanChange','commonWithinChange','exactDecompositionResidual']},[(1976,z['beforeAvailableMean']),(1980,z['afterAvailableMean'])],'Observed wave','Nominal USD/hour / available mean'\n if variant=='company':return dict(sales2023=models['company']['revenue2023'],sales2024=models['company']['revenue2024'],proxy=z['ratio'],proxyGrowth=None),[(2023,models['company']['revenue2023']/1000000),(2024,models['company']['revenue2024']/1000000)],'Fiscal year','Nominal USD millions'\n raise ValueError('fixed example name required')\n\ndef svg(points,xlabel,ylabel):\n good=[(float(x),float(y))for x,y in points if y is not None]\n if not good:return None\n if any(not math.isfinite(x)or not math.isfinite(y)for x,y in good):raise ValueError('outside finite plotting range')\n w,h,L,R,T,B=640,360,90,22,28,54;xmin=min(float(p[0])for p in points);xmax=max(float(p[0])for p in points);ymin=min(y for x,y in good);ymax=max(y for x,y in good)\n pad=max(1,abs(ymin)*.05)if ymin==ymax else(ymax-ymin)*.08;ymin-=pad;ymax+=pad\n X=lambda x:(L+w-R)/2 if xmax==xmin else L+(float(x)-xmin)/(xmax-xmin)*(w-L-R);Y=lambda y:T+(ymax-float(y))/(ymax-ymin)*(h-T-B);esc=html.escape\n s=f'<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"640\" height=\"360\" viewBox=\"0 0 640 360\" role=\"img\" aria-label=\"{esc(xlabel+\"; \"+ylabel)}\"><title>{esc(xlabel+\"; \"+ylabel)}</title><rect width=\"640\" height=\"360\" fill=\"white\"/><g font-family=\"sans-serif\" font-size=\"13\" fill=\"#222\">'\n for i in range(4):\n  v=ymin+(ymax-ymin)*i/3;y=Y(v);s+=f'<line x1=\"{L}\" x2=\"{w-R}\" y1=\"{y}\" y2=\"{y}\" stroke=\"#ccd6db\"/><text x=\"{L-7}\" y=\"{y+4}\" text-anchor=\"end\">{v:.4g}</text>'\n for x,anchor in([(xmin,'middle')]if xmin==xmax else[(xmin,'start'),(xmax,'end')]):s+=f'<text x=\"{X(x)}\" y=\"{h-B+24}\" text-anchor=\"{anchor}\">{x:g}</text>'\n last=None\n for x,y in points:\n  if y is None:last=None;continue\n  a,b=X(x),Y(y)\n  if last:s+=f'<line x1=\"{last[0]}\" y1=\"{last[1]}\" x2=\"{a}\" y2=\"{b}\" stroke=\"#355c72\" stroke-width=\"2\"/>'\n  s+=f'<circle cx=\"{a}\" cy=\"{b}\" r=\"3\" fill=\"#934b34\"><title>{esc(str(x)+\": \"+str(y))}</title></circle>';last=(a,b)\n return s+f'<text x=\"{L}\" y=\"16\">{esc(ylabel)}</text><text x=\"{w-R}\" y=\"{h-6}\" text-anchor=\"end\">{esc(xlabel)}</text></g></svg>'\n\ndef run(api,variant,output):\n out=Path(output);out.mkdir(parents=True,exist_ok=True);metrics,points,x,y=example(api,variant);encoded=M.encode(metrics);(out/'summary.json').write_text(json.dumps(encoded,indent=2)+'\\n',encoding='utf8')\n M.write_csv(out/'summary.csv',[dict(metric=k,value=v)for k,v in metrics.items()]);M.write_csv(out/'plot-points.csv',[dict(x=a,y=b)for a,b in points]);graphic=svg(points,x,y)\n if graphic is not None:(out/'plot.svg').write_text(graphic,encoding='utf8')\n print(json.dumps(dict(api=api,variant=variant,metrics=encoded,plotProduced=graphic is not None),ensure_ascii=False))\n"
          }
        ],
        "inputFiles": [],
        "returnCode": 2,
        "expectedFailure": true,
        "stdout": "",
        "stderr": "Rejected declared input: positive observed base/scale required\n",
        "seconds": 0.11000000004423782,
        "summary": {},
        "plotPoints": [],
        "plotFile": null,
        "plotSHA256": null,
        "scope": "Actually executed fixed example. Current browser controls are calculated separately by JavaScript. Base-R outputs use finite precision; Python outputs use exact fractions."
      }
    },
    "r": {
      "default": {
        "api": "rebase",
        "variant": "default",
        "language": "r",
        "codeFile": "econ22-code/rebase-default.R",
        "codeSHA256": "95a01948000d826cece1c3f831b576292bc5f2f42481a3bd930b035323651684",
        "codeText": "# Run from the extracted textbook bundle root.\nsource('econ22-fixed-support.R',encoding='UTF-8')\noptions(digits=17)\nargs<-commandArgs(trailingOnly=TRUE)\noutput<-if(length(args))args[1]else'econ22-fixed-results/rebase-default-r'\ntryCatch(run('rebase','default',output),error=function(error){cat('Rejected declared input: ',conditionMessage(error),'\\n',file=stderr());quit(status=2)})\n",
        "supportFiles": [
          {
            "file": "econ22-reproduce.R",
            "sha256": "2db22759696a6f288479189f44026f265536a54cdc2e72952c1e91af13661480",
            "codeText": "# ECON22 independent public base-R reproduction; binary64 approximations.\n# Run: Rscript --vanilla --encoding=UTF-8 econ22-reproduce.R [source-dir] [output-dir]\n# Source CSVs are never overwritten. No packages or network required.\nrebase <- function(values, base=1L, scale=100) {\n  if (length(base)!=1L || !is.finite(base) || base!=as.integer(base) || !length(values) || base<1 || base>length(values) || is.na(values[base]) || values[base]<=0 || !is.finite(scale) || scale<=0) stop('positive observed base/scale required')\n  scale*values/values[base]\n}\ngrowth <- function(start,end,periods=1L) {\n  if (start<=0 || end<0 || periods<1 || periods>12 || periods!=as.integer(periods)) stop('growth domain')\n  gross<-end/start;list(gross=gross,percentChange=(gross-1)*100,annualizedGross=gross^periods,annualizedPercent=(gross^periods-1)*100)\n}\ncomposition <- function(rows) {\n  if (!nrow(rows) || anyDuplicated(rows$id)) stop('nonempty unique units required')\n  if (!'weight'%in%names(rows)) rows$weight<-rep(1,nrow(rows))\n  if (any(!is.finite(rows$weight)) || any(rows$weight<0)) stop('nonnegative fixed weights required')\n  valid<-rows$weight>0;b<-valid&!is.na(rows$before);a<-valid&!is.na(rows$after);common<-b&a\n  avg<-function(mask,column)if(sum(rows$weight[mask])>0)sum(rows[[column]][mask]*rows$weight[mask])/sum(rows$weight[mask])else NA_real_\n  mb<-avg(b,'before');ma<-avg(a,'after');cb<-avg(common,'before');ca<-avg(common,'after');full<-all(is.finite(c(mb,ma,cb,ca)))\n  list(sourceUnits=nrow(rows),beforeAvailableUnits=sum(b),afterAvailableUnits=sum(a),commonUnits=sum(common),beforeAvailableMean=mb,afterAvailableMean=ma,beforeCommonMean=cb,afterCommonMean=ca,availableMeanChange=ma-mb,commonWithinChange=if(full)ca-cb else NA_real_,afterFrameShift=if(full)ma-ca else NA_real_,beforeFrameShift=if(full)cb-mb else NA_real_,exactDecompositionResidual=if(full)(ma-mb)-((ma-ca)+(ca-cb)+(cb-mb))else NA_real_)\n}\nproductivity <- function(output0,output1,hours0,hours1) {\n  if(any(c(output0,output1,hours0,hours1)<=0))stop('positive output and hours required')\n  go<-output1/output0;gh<-hours1/hours0;gp<-go/gh\n  list(outputGross=go,hoursGross=gh,productivityGross=gp,outputPercent=(go-1)*100,hoursPercent=(gh-1)*100,productivityPercent=(gp-1)*100,differenceOfPercentGrowths=(go-gh)*100,exactGrowthIdentityResidual=gp-go/gh)\n}\nmeasurement <- function(numerator,denominator,lower=NA_real_,upper=NA_real_) {\n  if(denominator<0)stop('nonnegative denominator required');interval<-NULL\n  if(!is.na(lower)||!is.na(upper)){if(any(!is.finite(c(lower,upper)))||lower<=0||upper<lower)stop('ordered positive scenario bounds');interval<-sort(c(numerator/lower,numerator/upper))}\n  list(ratio=if(denominator>0)numerator/denominator else NA_real_,denominatorScenarioInterval=interval)\n}\nload_sources <- function(folder) {\n  read<-function(file)read.csv(file.path(folder,file),stringsAsFactors=FALSE,check.names=FALSE,colClasses='character',na.strings=c('NA','','.'))\n  h<-read('actual180-KOR-housing-nominal-real-indexes.csv');b<-read('actual38-US-nonfarm-output-hours-productivity-indexes.csv');p<-read('actual10839-person-wage-panel-original-and-prior-derived-fields.csv');c<-read('actual3-Apple-revenue-and-approximate-periodend-FTE-facts.csv')\n  company<-list();for(i in seq_len(nrow(c))){value<-as.numeric(gsub(',','',c$originalToken[i],fixed=TRUE));if(c$fact[i]=='consolidated total net sales')company[[paste0('revenue',c$fiscalYear[i])]]<-value*1e6 else company$endpointFTE2024<-value}\n  list(housing=h,bls=b,person=p,company=company)\n}\nperson_comparison <- function(models,before=1976L,after=1980L) {\n  if(!before%in%c(1976,1978,1980)||!after%in%c(1976,1978,1980)||before>=after)stop('ordered observed waves required')\n  p<-models$person;if(anyDuplicated(paste(p$unit,p$time,sep=':')))stop('duplicate original unit-wave')\n  ids<-unique(p$unit);rows<-data.frame(id=ids,before=as.numeric(p$wageCentsOriginal[match(paste(ids,before),paste(p$unit,p$time))])/100,after=as.numeric(p$wageCentsOriginal[match(paste(ids,after),paste(p$unit,p$time))])/100,stringsAsFactors=FALSE)\n  composition(rows)\n}\nrealdata <- function(models,kind) {\n  if(kind=='country'){r<-models$housing;return(list(originalCount=nrow(r),growth=growth(as.numeric(r$nominal[1]),as.numeric(tail(r$nominal,1))),rebased=rebase(as.numeric(r$nominal))))}\n  if(kind=='person')return(person_comparison(models))\n  if(kind=='company'){c<-models$company;return(list(revenueGrowth=growth(c$revenue2023,c$revenue2024),ratio=measurement(c$revenue2024,c$endpointFTE2024)$ratio,proxyGrowth=NA_real_))}\n  stop('actual case required')\n}\nfull_source <- function(folder,out) {\n  dir.create(out,recursive=TRUE,showWarnings=FALSE);models<-load_sources(folder);metrics<-list();country<-list();frames<-list()\n  for(source in c('housing','bls')){data<-models[[source]];columns<-if(source=='housing')c('nominal','real')else c('outputIndexOriginalToken','hoursIndexOriginalToken','productivityIndexOriginalToken')\n    for(col in columns){values<-as.numeric(data[[col]]);rb<-rebase(values);g<-growth(values[1],tail(values,1));for(k in names(g))metrics[[paste(source,col,k,sep=':')]]<-g[[k]];quarterBase<-if(source=='housing')match('2010-Q1',data$quarter)else NA_integer_;qb<-if(!is.na(quarterBase))rebase(values,quarterBase)else rep(NA_real_,length(values));country[[length(country)+1]]<-data.frame(source=source,series=col,row=seq_len(nrow(data)),quarter=data$quarter,originalToken=data[[col]],rebasedFirst100Exact=rb,rebased2010Q1Exact=qb,stringsAsFactors=FALSE)}}\n  for(pair in list(c(1976,1978),c(1978,1980),c(1976,1980))){a<-pair[1];b<-pair[2];z<-person_comparison(models,a,b);frames[[length(frames)+1]]<-as.data.frame(c(list(before=a,after=b,elapsedYears=b-a),z),stringsAsFactors=FALSE);for(k in names(z))metrics[[paste('person',a,b,k,sep=':')]]<-z[[k]]}\n  company<-realdata(models,'company');metrics[['company:proxy']]<-company$ratio;metrics[['company:proxyGrowth']]<-NA_real_;for(k in names(company$revenueGrowth))metrics[[paste('company:sales',k,sep=':')]]<-company$revenueGrowth[[k]]\n  changes<-list();b<-models$bls\n  for(i in seq_len(nrow(b)-1L)){z<-productivity(as.numeric(b$outputIndexOriginalToken[i]),as.numeric(b$outputIndexOriginalToken[i+1]),as.numeric(b$hoursIndexOriginalToken[i]),as.numeric(b$hoursIndexOriginalToken[i+1]));g<-growth(as.numeric(b$productivityIndexOriginalToken[i]),as.numeric(b$productivityIndexOriginalToken[i+1]),4);changes[[i]]<-as.data.frame(c(list(start=b$quarter[i],end=b$quarter[i+1]),z,list(publishedProductivityPercent=g$percentChange,publishedAnnualizedPercent=g$annualizedPercent)),stringsAsFactors=FALSE)}\n  write<-function(name,rows)write.csv(rows,file.path(out,name),row.names=FALSE,na='',fileEncoding='UTF-8')\n  selected<-head(unique(models$person$unit),12);p<-models$person[models$person$unit%in%selected,];trajectories<-data.frame(unit=p$unit,year=p$time,nominalUSDPerHourExact=as.numeric(p$wageCentsOriginal)/100,stringsAsFactors=FALSE)\n  write('metrics.csv',data.frame(metric=names(metrics),value=as.numeric(unlist(metrics))));write('country-indexes.csv',do.call(rbind,country));write('wage-frames.csv',do.call(rbind,frames));write('bls-changes.csv',do.call(rbind,changes));write('first12-trajectories.csv',trajectories);invisible(metrics)\n}\nif(sys.nframe()==0L){args<-commandArgs(trailingOnly=TRUE);folder<-if(length(args)>=1)args[1]else'econ22-sources';out<-if(length(args)>=2)args[2]else'econ22-r-results';options(digits=17);metrics<-full_source(folder,out);cat('metrics:',length(metrics),'\\noutput directory:',out,'\\n')}\n"
          },
          {
            "file": "econ22-fixed-support.R",
            "sha256": "d4d63e1ad02017f20884b5932458dbde6013e0c2e560a4a9922a13d080a59fa1",
            "codeText": "# Run fixed drivers from the extracted bundle root. No packages or network required.\nsource('econ22-reproduce.R',encoding='UTF-8')\nexample <- function(api,variant) {\n  if(api=='rebase'){v<-if(variant=='invalid')c(0,1)else if(variant=='gap')c(80,NA,120)else c(80,100,120);z<-rebase(v);return(list(metrics=list(rows=length(z),defined=sum(!is.na(z)),last=tail(z,1)),x=seq_along(z)-1,y=z,xlabel='Position',ylabel='Rebased index'))}\n  if(api=='growth'){end<-if(variant=='quarterly')90 else 120;z<-growth(100,end,if(variant=='quarterly')4 else 1);return(list(metrics=z,x=c(0,1),y=c(100,end),xlabel='Date',ylabel='Supplied level'))}\n  if(api=='composition'){rows<-if(variant=='noCommon')data.frame(id=c('A','B'),before=c(10,NA),after=c(NA,20))else data.frame(id=c('A','B','C'),before=c(10,100,NA),after=c(11,NA,1));z<-composition(rows);metrics<-z[c('beforeAvailableMean','afterAvailableMean','availableMeanChange','commonWithinChange','commonUnits','exactDecompositionResidual')];return(list(metrics=metrics,x=c(0,1),y=c(z$beforeAvailableMean,z$afterAvailableMean),xlabel='Date',ylabel='Available mean / assumed units'))}\n  if(api=='productivity'){o<-if(variant=='contraction')90 else 103;h<-if(variant=='contraction')80 else 101;z<-productivity(100,o,100,h);return(list(metrics=z,x=c(0,1),y=c(1,z$productivityGross),xlabel='Date',ylabel='Output per hour / initial=1'))}\n  if(api=='measurement'){n<-if(variant=='zero')0 else 391035000000;d<-if(variant=='zero')0 else 164000;z<-measurement(n,d);return(list(metrics=list(ratio=z$ratio,denominatorZero=as.integer(d==0),sourceApproximate=as.integer(variant!='zero')),x=0,y=z$ratio,xlabel='Ratio position',ylabel='USD / approximate endpoint FTE'))}\n  models<-load_sources('econ22-sources');z<-realdata(models,variant)\n  if(variant=='country')return(list(metrics=list(sourceRows=z$originalCount,first=as.numeric(head(models$housing$nominal,1)),last=as.numeric(tail(models$housing$nominal,1)),percentChange=z$growth$percentChange),x=seq_along(z$rebased)-1,y=z$rebased,xlabel='Quarter position / original calendar',ylabel='Nominal housing / first=100'))\n  if(variant=='person')return(list(metrics=z[c('sourceUnits','beforeAvailableUnits','afterAvailableUnits','commonUnits','availableMeanChange','commonWithinChange','exactDecompositionResidual')],x=c(1976,1980),y=c(z$beforeAvailableMean,z$afterAvailableMean),xlabel='Observed wave',ylabel='Nominal USD/hour / available mean'))\n  if(variant=='company')return(list(metrics=list(sales2023=models$company$revenue2023,sales2024=models$company$revenue2024,proxy=z$ratio,proxyGrowth=NA_real_),x=c(2023,2024),y=c(models$company$revenue2023,models$company$revenue2024)/1e6,xlabel='Fiscal year',ylabel='Nominal USD millions'))\n  stop('fixed example name required')\n}\nrun <- function(api,variant,output) {\n  dir.create(output,recursive=TRUE,showWarnings=FALSE);z<-example(api,variant);metrics<-data.frame(metric=names(z$metrics),value=as.numeric(unlist(z$metrics)),stringsAsFactors=FALSE)\n  write.csv(metrics,file.path(output,'summary.csv'),row.names=FALSE,na='',fileEncoding='UTF-8');write.csv(data.frame(x=z$x,y=z$y),file.path(output,'plot-points.csv'),row.names=FALSE,na='',fileEncoding='UTF-8');print(metrics,row.names=FALSE)\n  good<-is.finite(z$x)&is.finite(z$y)\n  if(any(good)){svg(file.path(output,'plot.svg'),width=640/96,height=360/96,pointsize=10);par(mar=c(4.5,5.8,2,1));plot(z$x,z$y,type='o',pch=16,cex=.7,col='#355c72',xlab=z$xlabel,ylab=z$ylabel,cex.axis=.85,cex.lab=.9);grid(col='#d5dde1');dev.off();cat('plotProduced: TRUE\\n')}else cat('plotProduced: FALSE; undefined values retained\\n')\n}\n"
          }
        ],
        "inputFiles": [],
        "returnCode": 0,
        "expectedFailure": false,
        "stdout": "  metric value\n    rows     3\n defined     3\n    last   150\nplotProduced: TRUE\n",
        "stderr": "During startup - Warning messages:\n1: Setting LC_COLLATE=C.UTF-8 failed \n2: Setting LC_CTYPE=C.UTF-8 failed \n3: Setting LC_MONETARY=C.UTF-8 failed \n4: Setting LC_TIME=C.UTF-8 failed \n",
        "seconds": 0.28100000001722947,
        "summary": {
          "rows": "3",
          "defined": "3",
          "last": "150"
        },
        "plotPoints": [
          {
            "x": "0",
            "y": "100"
          },
          {
            "x": "1",
            "y": "125"
          },
          {
            "x": "2",
            "y": "150"
          }
        ],
        "plotFile": "econ22-fixed-results/rebase-default-r/plot.svg",
        "plotSHA256": "d31651783dc330c066c0f34b71071909c6c425945f08ff43322ba7cbd67d7f4d",
        "scope": "Actually executed fixed example. Current browser controls are calculated separately by JavaScript. Base-R outputs use finite precision; Python outputs use exact fractions.",
        "summaryFile": "econ22-fixed-results/rebase-default-r/summary.csv",
        "summarySHA256": "7fb79a07999ce3645fe55fe0e8aa323e22225856b5f66f2fe47c7127cfd6044d",
        "plotPointsFile": "econ22-fixed-results/rebase-default-r/plot-points.csv",
        "plotPointsSHA256": "0f34a801cd56bbdae7edab063fc1070ad0cae7b50bfe74d6f796c417b8890cd2"
      },
      "gap": {
        "api": "rebase",
        "variant": "gap",
        "language": "r",
        "codeFile": "econ22-code/rebase-gap.R",
        "codeSHA256": "5960b665aa727ee78e71837939afcfcdcdb8b41927d35f412d39d990a41aea6c",
        "codeText": "# Run from the extracted textbook bundle root.\nsource('econ22-fixed-support.R',encoding='UTF-8')\noptions(digits=17)\nargs<-commandArgs(trailingOnly=TRUE)\noutput<-if(length(args))args[1]else'econ22-fixed-results/rebase-gap-r'\ntryCatch(run('rebase','gap',output),error=function(error){cat('Rejected declared input: ',conditionMessage(error),'\\n',file=stderr());quit(status=2)})\n",
        "supportFiles": [
          {
            "file": "econ22-reproduce.R",
            "sha256": "2db22759696a6f288479189f44026f265536a54cdc2e72952c1e91af13661480",
            "codeText": "# ECON22 independent public base-R reproduction; binary64 approximations.\n# Run: Rscript --vanilla --encoding=UTF-8 econ22-reproduce.R [source-dir] [output-dir]\n# Source CSVs are never overwritten. No packages or network required.\nrebase <- function(values, base=1L, scale=100) {\n  if (length(base)!=1L || !is.finite(base) || base!=as.integer(base) || !length(values) || base<1 || base>length(values) || is.na(values[base]) || values[base]<=0 || !is.finite(scale) || scale<=0) stop('positive observed base/scale required')\n  scale*values/values[base]\n}\ngrowth <- function(start,end,periods=1L) {\n  if (start<=0 || end<0 || periods<1 || periods>12 || periods!=as.integer(periods)) stop('growth domain')\n  gross<-end/start;list(gross=gross,percentChange=(gross-1)*100,annualizedGross=gross^periods,annualizedPercent=(gross^periods-1)*100)\n}\ncomposition <- function(rows) {\n  if (!nrow(rows) || anyDuplicated(rows$id)) stop('nonempty unique units required')\n  if (!'weight'%in%names(rows)) rows$weight<-rep(1,nrow(rows))\n  if (any(!is.finite(rows$weight)) || any(rows$weight<0)) stop('nonnegative fixed weights required')\n  valid<-rows$weight>0;b<-valid&!is.na(rows$before);a<-valid&!is.na(rows$after);common<-b&a\n  avg<-function(mask,column)if(sum(rows$weight[mask])>0)sum(rows[[column]][mask]*rows$weight[mask])/sum(rows$weight[mask])else NA_real_\n  mb<-avg(b,'before');ma<-avg(a,'after');cb<-avg(common,'before');ca<-avg(common,'after');full<-all(is.finite(c(mb,ma,cb,ca)))\n  list(sourceUnits=nrow(rows),beforeAvailableUnits=sum(b),afterAvailableUnits=sum(a),commonUnits=sum(common),beforeAvailableMean=mb,afterAvailableMean=ma,beforeCommonMean=cb,afterCommonMean=ca,availableMeanChange=ma-mb,commonWithinChange=if(full)ca-cb else NA_real_,afterFrameShift=if(full)ma-ca else NA_real_,beforeFrameShift=if(full)cb-mb else NA_real_,exactDecompositionResidual=if(full)(ma-mb)-((ma-ca)+(ca-cb)+(cb-mb))else NA_real_)\n}\nproductivity <- function(output0,output1,hours0,hours1) {\n  if(any(c(output0,output1,hours0,hours1)<=0))stop('positive output and hours required')\n  go<-output1/output0;gh<-hours1/hours0;gp<-go/gh\n  list(outputGross=go,hoursGross=gh,productivityGross=gp,outputPercent=(go-1)*100,hoursPercent=(gh-1)*100,productivityPercent=(gp-1)*100,differenceOfPercentGrowths=(go-gh)*100,exactGrowthIdentityResidual=gp-go/gh)\n}\nmeasurement <- function(numerator,denominator,lower=NA_real_,upper=NA_real_) {\n  if(denominator<0)stop('nonnegative denominator required');interval<-NULL\n  if(!is.na(lower)||!is.na(upper)){if(any(!is.finite(c(lower,upper)))||lower<=0||upper<lower)stop('ordered positive scenario bounds');interval<-sort(c(numerator/lower,numerator/upper))}\n  list(ratio=if(denominator>0)numerator/denominator else NA_real_,denominatorScenarioInterval=interval)\n}\nload_sources <- function(folder) {\n  read<-function(file)read.csv(file.path(folder,file),stringsAsFactors=FALSE,check.names=FALSE,colClasses='character',na.strings=c('NA','','.'))\n  h<-read('actual180-KOR-housing-nominal-real-indexes.csv');b<-read('actual38-US-nonfarm-output-hours-productivity-indexes.csv');p<-read('actual10839-person-wage-panel-original-and-prior-derived-fields.csv');c<-read('actual3-Apple-revenue-and-approximate-periodend-FTE-facts.csv')\n  company<-list();for(i in seq_len(nrow(c))){value<-as.numeric(gsub(',','',c$originalToken[i],fixed=TRUE));if(c$fact[i]=='consolidated total net sales')company[[paste0('revenue',c$fiscalYear[i])]]<-value*1e6 else company$endpointFTE2024<-value}\n  list(housing=h,bls=b,person=p,company=company)\n}\nperson_comparison <- function(models,before=1976L,after=1980L) {\n  if(!before%in%c(1976,1978,1980)||!after%in%c(1976,1978,1980)||before>=after)stop('ordered observed waves required')\n  p<-models$person;if(anyDuplicated(paste(p$unit,p$time,sep=':')))stop('duplicate original unit-wave')\n  ids<-unique(p$unit);rows<-data.frame(id=ids,before=as.numeric(p$wageCentsOriginal[match(paste(ids,before),paste(p$unit,p$time))])/100,after=as.numeric(p$wageCentsOriginal[match(paste(ids,after),paste(p$unit,p$time))])/100,stringsAsFactors=FALSE)\n  composition(rows)\n}\nrealdata <- function(models,kind) {\n  if(kind=='country'){r<-models$housing;return(list(originalCount=nrow(r),growth=growth(as.numeric(r$nominal[1]),as.numeric(tail(r$nominal,1))),rebased=rebase(as.numeric(r$nominal))))}\n  if(kind=='person')return(person_comparison(models))\n  if(kind=='company'){c<-models$company;return(list(revenueGrowth=growth(c$revenue2023,c$revenue2024),ratio=measurement(c$revenue2024,c$endpointFTE2024)$ratio,proxyGrowth=NA_real_))}\n  stop('actual case required')\n}\nfull_source <- function(folder,out) {\n  dir.create(out,recursive=TRUE,showWarnings=FALSE);models<-load_sources(folder);metrics<-list();country<-list();frames<-list()\n  for(source in c('housing','bls')){data<-models[[source]];columns<-if(source=='housing')c('nominal','real')else c('outputIndexOriginalToken','hoursIndexOriginalToken','productivityIndexOriginalToken')\n    for(col in columns){values<-as.numeric(data[[col]]);rb<-rebase(values);g<-growth(values[1],tail(values,1));for(k in names(g))metrics[[paste(source,col,k,sep=':')]]<-g[[k]];quarterBase<-if(source=='housing')match('2010-Q1',data$quarter)else NA_integer_;qb<-if(!is.na(quarterBase))rebase(values,quarterBase)else rep(NA_real_,length(values));country[[length(country)+1]]<-data.frame(source=source,series=col,row=seq_len(nrow(data)),quarter=data$quarter,originalToken=data[[col]],rebasedFirst100Exact=rb,rebased2010Q1Exact=qb,stringsAsFactors=FALSE)}}\n  for(pair in list(c(1976,1978),c(1978,1980),c(1976,1980))){a<-pair[1];b<-pair[2];z<-person_comparison(models,a,b);frames[[length(frames)+1]]<-as.data.frame(c(list(before=a,after=b,elapsedYears=b-a),z),stringsAsFactors=FALSE);for(k in names(z))metrics[[paste('person',a,b,k,sep=':')]]<-z[[k]]}\n  company<-realdata(models,'company');metrics[['company:proxy']]<-company$ratio;metrics[['company:proxyGrowth']]<-NA_real_;for(k in names(company$revenueGrowth))metrics[[paste('company:sales',k,sep=':')]]<-company$revenueGrowth[[k]]\n  changes<-list();b<-models$bls\n  for(i in seq_len(nrow(b)-1L)){z<-productivity(as.numeric(b$outputIndexOriginalToken[i]),as.numeric(b$outputIndexOriginalToken[i+1]),as.numeric(b$hoursIndexOriginalToken[i]),as.numeric(b$hoursIndexOriginalToken[i+1]));g<-growth(as.numeric(b$productivityIndexOriginalToken[i]),as.numeric(b$productivityIndexOriginalToken[i+1]),4);changes[[i]]<-as.data.frame(c(list(start=b$quarter[i],end=b$quarter[i+1]),z,list(publishedProductivityPercent=g$percentChange,publishedAnnualizedPercent=g$annualizedPercent)),stringsAsFactors=FALSE)}\n  write<-function(name,rows)write.csv(rows,file.path(out,name),row.names=FALSE,na='',fileEncoding='UTF-8')\n  selected<-head(unique(models$person$unit),12);p<-models$person[models$person$unit%in%selected,];trajectories<-data.frame(unit=p$unit,year=p$time,nominalUSDPerHourExact=as.numeric(p$wageCentsOriginal)/100,stringsAsFactors=FALSE)\n  write('metrics.csv',data.frame(metric=names(metrics),value=as.numeric(unlist(metrics))));write('country-indexes.csv',do.call(rbind,country));write('wage-frames.csv',do.call(rbind,frames));write('bls-changes.csv',do.call(rbind,changes));write('first12-trajectories.csv',trajectories);invisible(metrics)\n}\nif(sys.nframe()==0L){args<-commandArgs(trailingOnly=TRUE);folder<-if(length(args)>=1)args[1]else'econ22-sources';out<-if(length(args)>=2)args[2]else'econ22-r-results';options(digits=17);metrics<-full_source(folder,out);cat('metrics:',length(metrics),'\\noutput directory:',out,'\\n')}\n"
          },
          {
            "file": "econ22-fixed-support.R",
            "sha256": "d4d63e1ad02017f20884b5932458dbde6013e0c2e560a4a9922a13d080a59fa1",
            "codeText": "# Run fixed drivers from the extracted bundle root. No packages or network required.\nsource('econ22-reproduce.R',encoding='UTF-8')\nexample <- function(api,variant) {\n  if(api=='rebase'){v<-if(variant=='invalid')c(0,1)else if(variant=='gap')c(80,NA,120)else c(80,100,120);z<-rebase(v);return(list(metrics=list(rows=length(z),defined=sum(!is.na(z)),last=tail(z,1)),x=seq_along(z)-1,y=z,xlabel='Position',ylabel='Rebased index'))}\n  if(api=='growth'){end<-if(variant=='quarterly')90 else 120;z<-growth(100,end,if(variant=='quarterly')4 else 1);return(list(metrics=z,x=c(0,1),y=c(100,end),xlabel='Date',ylabel='Supplied level'))}\n  if(api=='composition'){rows<-if(variant=='noCommon')data.frame(id=c('A','B'),before=c(10,NA),after=c(NA,20))else data.frame(id=c('A','B','C'),before=c(10,100,NA),after=c(11,NA,1));z<-composition(rows);metrics<-z[c('beforeAvailableMean','afterAvailableMean','availableMeanChange','commonWithinChange','commonUnits','exactDecompositionResidual')];return(list(metrics=metrics,x=c(0,1),y=c(z$beforeAvailableMean,z$afterAvailableMean),xlabel='Date',ylabel='Available mean / assumed units'))}\n  if(api=='productivity'){o<-if(variant=='contraction')90 else 103;h<-if(variant=='contraction')80 else 101;z<-productivity(100,o,100,h);return(list(metrics=z,x=c(0,1),y=c(1,z$productivityGross),xlabel='Date',ylabel='Output per hour / initial=1'))}\n  if(api=='measurement'){n<-if(variant=='zero')0 else 391035000000;d<-if(variant=='zero')0 else 164000;z<-measurement(n,d);return(list(metrics=list(ratio=z$ratio,denominatorZero=as.integer(d==0),sourceApproximate=as.integer(variant!='zero')),x=0,y=z$ratio,xlabel='Ratio position',ylabel='USD / approximate endpoint FTE'))}\n  models<-load_sources('econ22-sources');z<-realdata(models,variant)\n  if(variant=='country')return(list(metrics=list(sourceRows=z$originalCount,first=as.numeric(head(models$housing$nominal,1)),last=as.numeric(tail(models$housing$nominal,1)),percentChange=z$growth$percentChange),x=seq_along(z$rebased)-1,y=z$rebased,xlabel='Quarter position / original calendar',ylabel='Nominal housing / first=100'))\n  if(variant=='person')return(list(metrics=z[c('sourceUnits','beforeAvailableUnits','afterAvailableUnits','commonUnits','availableMeanChange','commonWithinChange','exactDecompositionResidual')],x=c(1976,1980),y=c(z$beforeAvailableMean,z$afterAvailableMean),xlabel='Observed wave',ylabel='Nominal USD/hour / available mean'))\n  if(variant=='company')return(list(metrics=list(sales2023=models$company$revenue2023,sales2024=models$company$revenue2024,proxy=z$ratio,proxyGrowth=NA_real_),x=c(2023,2024),y=c(models$company$revenue2023,models$company$revenue2024)/1e6,xlabel='Fiscal year',ylabel='Nominal USD millions'))\n  stop('fixed example name required')\n}\nrun <- function(api,variant,output) {\n  dir.create(output,recursive=TRUE,showWarnings=FALSE);z<-example(api,variant);metrics<-data.frame(metric=names(z$metrics),value=as.numeric(unlist(z$metrics)),stringsAsFactors=FALSE)\n  write.csv(metrics,file.path(output,'summary.csv'),row.names=FALSE,na='',fileEncoding='UTF-8');write.csv(data.frame(x=z$x,y=z$y),file.path(output,'plot-points.csv'),row.names=FALSE,na='',fileEncoding='UTF-8');print(metrics,row.names=FALSE)\n  good<-is.finite(z$x)&is.finite(z$y)\n  if(any(good)){svg(file.path(output,'plot.svg'),width=640/96,height=360/96,pointsize=10);par(mar=c(4.5,5.8,2,1));plot(z$x,z$y,type='o',pch=16,cex=.7,col='#355c72',xlab=z$xlabel,ylab=z$ylabel,cex.axis=.85,cex.lab=.9);grid(col='#d5dde1');dev.off();cat('plotProduced: TRUE\\n')}else cat('plotProduced: FALSE; undefined values retained\\n')\n}\n"
          }
        ],
        "inputFiles": [],
        "returnCode": 0,
        "expectedFailure": false,
        "stdout": "  metric value\n    rows     3\n defined     2\n    last   150\nplotProduced: TRUE\n",
        "stderr": "During startup - Warning messages:\n1: Setting LC_COLLATE=C.UTF-8 failed \n2: Setting LC_CTYPE=C.UTF-8 failed \n3: Setting LC_MONETARY=C.UTF-8 failed \n4: Setting LC_TIME=C.UTF-8 failed \n",
        "seconds": 0.28100000001722947,
        "summary": {
          "rows": "3",
          "defined": "2",
          "last": "150"
        },
        "plotPoints": [
          {
            "x": "0",
            "y": "100"
          },
          {
            "x": "1",
            "y": ""
          },
          {
            "x": "2",
            "y": "150"
          }
        ],
        "plotFile": "econ22-fixed-results/rebase-gap-r/plot.svg",
        "plotSHA256": "cf8058ebfd78d0c20c48bfe9ecf64e928ab15d6597f4155e9cb6a0b568a7c72a",
        "scope": "Actually executed fixed example. Current browser controls are calculated separately by JavaScript. Base-R outputs use finite precision; Python outputs use exact fractions.",
        "summaryFile": "econ22-fixed-results/rebase-gap-r/summary.csv",
        "summarySHA256": "18c35af4d5976fb437fd8bd515f584282f66e820dba46ec0393c5363ed4befb6",
        "plotPointsFile": "econ22-fixed-results/rebase-gap-r/plot-points.csv",
        "plotPointsSHA256": "079f6c85cdbb531287f9e4eaa065bc532b7b7142051239766b7486239a4056e8"
      },
      "invalid": {
        "api": "rebase",
        "variant": "invalid",
        "language": "r",
        "codeFile": "econ22-code/rebase-invalid.R",
        "codeSHA256": "ad15ff7bf50aa6d2589ff2aff1ecd220aad0bc59311b3b3e418dfde157d492bd",
        "codeText": "# Run from the extracted textbook bundle root.\nsource('econ22-fixed-support.R',encoding='UTF-8')\noptions(digits=17)\nargs<-commandArgs(trailingOnly=TRUE)\noutput<-if(length(args))args[1]else'econ22-fixed-results/rebase-invalid-r'\ntryCatch(run('rebase','invalid',output),error=function(error){cat('Rejected declared input: ',conditionMessage(error),'\\n',file=stderr());quit(status=2)})\n",
        "supportFiles": [
          {
            "file": "econ22-reproduce.R",
            "sha256": "2db22759696a6f288479189f44026f265536a54cdc2e72952c1e91af13661480",
            "codeText": "# ECON22 independent public base-R reproduction; binary64 approximations.\n# Run: Rscript --vanilla --encoding=UTF-8 econ22-reproduce.R [source-dir] [output-dir]\n# Source CSVs are never overwritten. No packages or network required.\nrebase <- function(values, base=1L, scale=100) {\n  if (length(base)!=1L || !is.finite(base) || base!=as.integer(base) || !length(values) || base<1 || base>length(values) || is.na(values[base]) || values[base]<=0 || !is.finite(scale) || scale<=0) stop('positive observed base/scale required')\n  scale*values/values[base]\n}\ngrowth <- function(start,end,periods=1L) {\n  if (start<=0 || end<0 || periods<1 || periods>12 || periods!=as.integer(periods)) stop('growth domain')\n  gross<-end/start;list(gross=gross,percentChange=(gross-1)*100,annualizedGross=gross^periods,annualizedPercent=(gross^periods-1)*100)\n}\ncomposition <- function(rows) {\n  if (!nrow(rows) || anyDuplicated(rows$id)) stop('nonempty unique units required')\n  if (!'weight'%in%names(rows)) rows$weight<-rep(1,nrow(rows))\n  if (any(!is.finite(rows$weight)) || any(rows$weight<0)) stop('nonnegative fixed weights required')\n  valid<-rows$weight>0;b<-valid&!is.na(rows$before);a<-valid&!is.na(rows$after);common<-b&a\n  avg<-function(mask,column)if(sum(rows$weight[mask])>0)sum(rows[[column]][mask]*rows$weight[mask])/sum(rows$weight[mask])else NA_real_\n  mb<-avg(b,'before');ma<-avg(a,'after');cb<-avg(common,'before');ca<-avg(common,'after');full<-all(is.finite(c(mb,ma,cb,ca)))\n  list(sourceUnits=nrow(rows),beforeAvailableUnits=sum(b),afterAvailableUnits=sum(a),commonUnits=sum(common),beforeAvailableMean=mb,afterAvailableMean=ma,beforeCommonMean=cb,afterCommonMean=ca,availableMeanChange=ma-mb,commonWithinChange=if(full)ca-cb else NA_real_,afterFrameShift=if(full)ma-ca else NA_real_,beforeFrameShift=if(full)cb-mb else NA_real_,exactDecompositionResidual=if(full)(ma-mb)-((ma-ca)+(ca-cb)+(cb-mb))else NA_real_)\n}\nproductivity <- function(output0,output1,hours0,hours1) {\n  if(any(c(output0,output1,hours0,hours1)<=0))stop('positive output and hours required')\n  go<-output1/output0;gh<-hours1/hours0;gp<-go/gh\n  list(outputGross=go,hoursGross=gh,productivityGross=gp,outputPercent=(go-1)*100,hoursPercent=(gh-1)*100,productivityPercent=(gp-1)*100,differenceOfPercentGrowths=(go-gh)*100,exactGrowthIdentityResidual=gp-go/gh)\n}\nmeasurement <- function(numerator,denominator,lower=NA_real_,upper=NA_real_) {\n  if(denominator<0)stop('nonnegative denominator required');interval<-NULL\n  if(!is.na(lower)||!is.na(upper)){if(any(!is.finite(c(lower,upper)))||lower<=0||upper<lower)stop('ordered positive scenario bounds');interval<-sort(c(numerator/lower,numerator/upper))}\n  list(ratio=if(denominator>0)numerator/denominator else NA_real_,denominatorScenarioInterval=interval)\n}\nload_sources <- function(folder) {\n  read<-function(file)read.csv(file.path(folder,file),stringsAsFactors=FALSE,check.names=FALSE,colClasses='character',na.strings=c('NA','','.'))\n  h<-read('actual180-KOR-housing-nominal-real-indexes.csv');b<-read('actual38-US-nonfarm-output-hours-productivity-indexes.csv');p<-read('actual10839-person-wage-panel-original-and-prior-derived-fields.csv');c<-read('actual3-Apple-revenue-and-approximate-periodend-FTE-facts.csv')\n  company<-list();for(i in seq_len(nrow(c))){value<-as.numeric(gsub(',','',c$originalToken[i],fixed=TRUE));if(c$fact[i]=='consolidated total net sales')company[[paste0('revenue',c$fiscalYear[i])]]<-value*1e6 else company$endpointFTE2024<-value}\n  list(housing=h,bls=b,person=p,company=company)\n}\nperson_comparison <- function(models,before=1976L,after=1980L) {\n  if(!before%in%c(1976,1978,1980)||!after%in%c(1976,1978,1980)||before>=after)stop('ordered observed waves required')\n  p<-models$person;if(anyDuplicated(paste(p$unit,p$time,sep=':')))stop('duplicate original unit-wave')\n  ids<-unique(p$unit);rows<-data.frame(id=ids,before=as.numeric(p$wageCentsOriginal[match(paste(ids,before),paste(p$unit,p$time))])/100,after=as.numeric(p$wageCentsOriginal[match(paste(ids,after),paste(p$unit,p$time))])/100,stringsAsFactors=FALSE)\n  composition(rows)\n}\nrealdata <- function(models,kind) {\n  if(kind=='country'){r<-models$housing;return(list(originalCount=nrow(r),growth=growth(as.numeric(r$nominal[1]),as.numeric(tail(r$nominal,1))),rebased=rebase(as.numeric(r$nominal))))}\n  if(kind=='person')return(person_comparison(models))\n  if(kind=='company'){c<-models$company;return(list(revenueGrowth=growth(c$revenue2023,c$revenue2024),ratio=measurement(c$revenue2024,c$endpointFTE2024)$ratio,proxyGrowth=NA_real_))}\n  stop('actual case required')\n}\nfull_source <- function(folder,out) {\n  dir.create(out,recursive=TRUE,showWarnings=FALSE);models<-load_sources(folder);metrics<-list();country<-list();frames<-list()\n  for(source in c('housing','bls')){data<-models[[source]];columns<-if(source=='housing')c('nominal','real')else c('outputIndexOriginalToken','hoursIndexOriginalToken','productivityIndexOriginalToken')\n    for(col in columns){values<-as.numeric(data[[col]]);rb<-rebase(values);g<-growth(values[1],tail(values,1));for(k in names(g))metrics[[paste(source,col,k,sep=':')]]<-g[[k]];quarterBase<-if(source=='housing')match('2010-Q1',data$quarter)else NA_integer_;qb<-if(!is.na(quarterBase))rebase(values,quarterBase)else rep(NA_real_,length(values));country[[length(country)+1]]<-data.frame(source=source,series=col,row=seq_len(nrow(data)),quarter=data$quarter,originalToken=data[[col]],rebasedFirst100Exact=rb,rebased2010Q1Exact=qb,stringsAsFactors=FALSE)}}\n  for(pair in list(c(1976,1978),c(1978,1980),c(1976,1980))){a<-pair[1];b<-pair[2];z<-person_comparison(models,a,b);frames[[length(frames)+1]]<-as.data.frame(c(list(before=a,after=b,elapsedYears=b-a),z),stringsAsFactors=FALSE);for(k in names(z))metrics[[paste('person',a,b,k,sep=':')]]<-z[[k]]}\n  company<-realdata(models,'company');metrics[['company:proxy']]<-company$ratio;metrics[['company:proxyGrowth']]<-NA_real_;for(k in names(company$revenueGrowth))metrics[[paste('company:sales',k,sep=':')]]<-company$revenueGrowth[[k]]\n  changes<-list();b<-models$bls\n  for(i in seq_len(nrow(b)-1L)){z<-productivity(as.numeric(b$outputIndexOriginalToken[i]),as.numeric(b$outputIndexOriginalToken[i+1]),as.numeric(b$hoursIndexOriginalToken[i]),as.numeric(b$hoursIndexOriginalToken[i+1]));g<-growth(as.numeric(b$productivityIndexOriginalToken[i]),as.numeric(b$productivityIndexOriginalToken[i+1]),4);changes[[i]]<-as.data.frame(c(list(start=b$quarter[i],end=b$quarter[i+1]),z,list(publishedProductivityPercent=g$percentChange,publishedAnnualizedPercent=g$annualizedPercent)),stringsAsFactors=FALSE)}\n  write<-function(name,rows)write.csv(rows,file.path(out,name),row.names=FALSE,na='',fileEncoding='UTF-8')\n  selected<-head(unique(models$person$unit),12);p<-models$person[models$person$unit%in%selected,];trajectories<-data.frame(unit=p$unit,year=p$time,nominalUSDPerHourExact=as.numeric(p$wageCentsOriginal)/100,stringsAsFactors=FALSE)\n  write('metrics.csv',data.frame(metric=names(metrics),value=as.numeric(unlist(metrics))));write('country-indexes.csv',do.call(rbind,country));write('wage-frames.csv',do.call(rbind,frames));write('bls-changes.csv',do.call(rbind,changes));write('first12-trajectories.csv',trajectories);invisible(metrics)\n}\nif(sys.nframe()==0L){args<-commandArgs(trailingOnly=TRUE);folder<-if(length(args)>=1)args[1]else'econ22-sources';out<-if(length(args)>=2)args[2]else'econ22-r-results';options(digits=17);metrics<-full_source(folder,out);cat('metrics:',length(metrics),'\\noutput directory:',out,'\\n')}\n"
          },
          {
            "file": "econ22-fixed-support.R",
            "sha256": "d4d63e1ad02017f20884b5932458dbde6013e0c2e560a4a9922a13d080a59fa1",
            "codeText": "# Run fixed drivers from the extracted bundle root. No packages or network required.\nsource('econ22-reproduce.R',encoding='UTF-8')\nexample <- function(api,variant) {\n  if(api=='rebase'){v<-if(variant=='invalid')c(0,1)else if(variant=='gap')c(80,NA,120)else c(80,100,120);z<-rebase(v);return(list(metrics=list(rows=length(z),defined=sum(!is.na(z)),last=tail(z,1)),x=seq_along(z)-1,y=z,xlabel='Position',ylabel='Rebased index'))}\n  if(api=='growth'){end<-if(variant=='quarterly')90 else 120;z<-growth(100,end,if(variant=='quarterly')4 else 1);return(list(metrics=z,x=c(0,1),y=c(100,end),xlabel='Date',ylabel='Supplied level'))}\n  if(api=='composition'){rows<-if(variant=='noCommon')data.frame(id=c('A','B'),before=c(10,NA),after=c(NA,20))else data.frame(id=c('A','B','C'),before=c(10,100,NA),after=c(11,NA,1));z<-composition(rows);metrics<-z[c('beforeAvailableMean','afterAvailableMean','availableMeanChange','commonWithinChange','commonUnits','exactDecompositionResidual')];return(list(metrics=metrics,x=c(0,1),y=c(z$beforeAvailableMean,z$afterAvailableMean),xlabel='Date',ylabel='Available mean / assumed units'))}\n  if(api=='productivity'){o<-if(variant=='contraction')90 else 103;h<-if(variant=='contraction')80 else 101;z<-productivity(100,o,100,h);return(list(metrics=z,x=c(0,1),y=c(1,z$productivityGross),xlabel='Date',ylabel='Output per hour / initial=1'))}\n  if(api=='measurement'){n<-if(variant=='zero')0 else 391035000000;d<-if(variant=='zero')0 else 164000;z<-measurement(n,d);return(list(metrics=list(ratio=z$ratio,denominatorZero=as.integer(d==0),sourceApproximate=as.integer(variant!='zero')),x=0,y=z$ratio,xlabel='Ratio position',ylabel='USD / approximate endpoint FTE'))}\n  models<-load_sources('econ22-sources');z<-realdata(models,variant)\n  if(variant=='country')return(list(metrics=list(sourceRows=z$originalCount,first=as.numeric(head(models$housing$nominal,1)),last=as.numeric(tail(models$housing$nominal,1)),percentChange=z$growth$percentChange),x=seq_along(z$rebased)-1,y=z$rebased,xlabel='Quarter position / original calendar',ylabel='Nominal housing / first=100'))\n  if(variant=='person')return(list(metrics=z[c('sourceUnits','beforeAvailableUnits','afterAvailableUnits','commonUnits','availableMeanChange','commonWithinChange','exactDecompositionResidual')],x=c(1976,1980),y=c(z$beforeAvailableMean,z$afterAvailableMean),xlabel='Observed wave',ylabel='Nominal USD/hour / available mean'))\n  if(variant=='company')return(list(metrics=list(sales2023=models$company$revenue2023,sales2024=models$company$revenue2024,proxy=z$ratio,proxyGrowth=NA_real_),x=c(2023,2024),y=c(models$company$revenue2023,models$company$revenue2024)/1e6,xlabel='Fiscal year',ylabel='Nominal USD millions'))\n  stop('fixed example name required')\n}\nrun <- function(api,variant,output) {\n  dir.create(output,recursive=TRUE,showWarnings=FALSE);z<-example(api,variant);metrics<-data.frame(metric=names(z$metrics),value=as.numeric(unlist(z$metrics)),stringsAsFactors=FALSE)\n  write.csv(metrics,file.path(output,'summary.csv'),row.names=FALSE,na='',fileEncoding='UTF-8');write.csv(data.frame(x=z$x,y=z$y),file.path(output,'plot-points.csv'),row.names=FALSE,na='',fileEncoding='UTF-8');print(metrics,row.names=FALSE)\n  good<-is.finite(z$x)&is.finite(z$y)\n  if(any(good)){svg(file.path(output,'plot.svg'),width=640/96,height=360/96,pointsize=10);par(mar=c(4.5,5.8,2,1));plot(z$x,z$y,type='o',pch=16,cex=.7,col='#355c72',xlab=z$xlabel,ylab=z$ylabel,cex.axis=.85,cex.lab=.9);grid(col='#d5dde1');dev.off();cat('plotProduced: TRUE\\n')}else cat('plotProduced: FALSE; undefined values retained\\n')\n}\n"
          }
        ],
        "inputFiles": [],
        "returnCode": 2,
        "expectedFailure": true,
        "stdout": "",
        "stderr": "During startup - Warning messages:\n1: Setting LC_COLLATE=C.UTF-8 failed \n2: Setting LC_CTYPE=C.UTF-8 failed \n3: Setting LC_MONETARY=C.UTF-8 failed \n4: Setting LC_TIME=C.UTF-8 failed \nRejected declared input:  positive observed base/scale required \n",
        "seconds": 0.2809999999590218,
        "summary": {},
        "plotPoints": [],
        "plotFile": null,
        "plotSHA256": null,
        "scope": "Actually executed fixed example. Current browser controls are calculated separately by JavaScript. Base-R outputs use finite precision; Python outputs use exact fractions."
      }
    }
  },
  "growth": {
    "python": {
      "default": {
        "api": "growth",
        "variant": "default",
        "language": "python",
        "codeFile": "econ22-code/growth-default.py",
        "codeSHA256": "d0932352d7dd7783b88cf5ee946f7cfa8effe4e6b39fc109fc9fe9844e9b8a4f",
        "codeText": "# Fixed stated example, separate from current web controls.\nfrom pathlib import Path\nimport importlib.util,sys\nroot=Path(__file__).resolve().parents[1]\nspec=importlib.util.spec_from_file_location('fixed_support',root/'econ22-fixed-support.py')\nsupport=importlib.util.module_from_spec(spec);spec.loader.exec_module(support)\ntry:support.run('growth','default',sys.argv[1]if len(sys.argv)>1 else root/'econ22-fixed-results/growth-default-python')\nexcept ValueError as error:\n print('Rejected declared input: '+str(error),file=sys.stderr);sys.exit(2)\n",
        "supportFiles": [
          {
            "file": "econ22-reproduce.py",
            "sha256": "cc5631d9dfea963b64349bb28d18b69ad3caf15a15162ec6cea786a36e18de48",
            "codeText": "#!/usr/bin/env python3\n\"\"\"ECON22 public reproduction: Python standard library, exact Fraction arithmetic.\nRun: python econ22-reproduce.py --source-dir econ22-sources --output-dir econ22-python-results\nOriginal CSV inputs are read only. Output is a new chosen directory.\nThese are descriptive arithmetic and explicitly assumed examples, not causal estimates.\n\"\"\"\nfrom fractions import Fraction as Q\nfrom pathlib import Path\nfrom collections import defaultdict\nimport argparse,csv,json\n\ndef number(x):\n if x is None:raise ValueError('missing numeric token')\n return Q(str(x))\ndef rebase(values,base=0,scale='100'):\n v=[None if x is None else number(x)for x in values];s=number(scale)\n if not v or not 0<=base<len(v)or v[base]is None or v[base]<=0 or s<=0:raise ValueError('positive observed base/scale required')\n return [None if x is None else s*x/v[base]for x in v]\ndef growth(start,end,periods=1):\n a,b=number(start),number(end)\n if a<=0 or b<0 or not isinstance(periods,int)or not 1<=periods<=12:raise ValueError('growth domain')\n g=b/a;return dict(gross=g,percentChange=(g-1)*100,annualizedGross=g**periods,annualizedPercent=(g**periods-1)*100)\ndef composition(rows):\n seen=set();data=[]\n for r in rows:\n  identifier=str(r['id']);weight=number(r.get('weight','1'))\n  if identifier in seen or weight<0:raise ValueError('unique units/nonnegative fixed weights required')\n  seen.add(identifier);data.append(dict(id=identifier,weight=weight,before=None if r['before']is None else number(r['before']),after=None if r['after']is None else number(r['after'])))\n if not data:raise ValueError('nonempty frame required')\n valid=[r for r in data if r['weight']>0];b=[r for r in valid if r['before']is not None];a=[r for r in valid if r['after']is not None];c=[r for r in valid if r['before']is not None and r['after']is not None]\n def mean(rs,k):\n  mass=sum((r['weight']for r in rs),Q(0));return sum((r[k]*r['weight']for r in rs),Q(0))/mass if mass else None\n mb,ma,cb,ca=mean(b,'before'),mean(a,'after'),mean(c,'before'),mean(c,'after');full=all(x is not None for x in [mb,ma,cb,ca]);change=ma-mb if mb is not None and ma is not None else None\n return dict(sourceUnits=len(data),beforeAvailableUnits=len(b),afterAvailableUnits=len(a),commonUnits=len(c),beforeAvailableMean=mb,afterAvailableMean=ma,beforeCommonMean=cb,afterCommonMean=ca,availableMeanChange=change,commonWithinChange=ca-cb if full else None,afterFrameShift=ma-ca if full else None,beforeFrameShift=cb-mb if full else None,exactDecompositionResidual=change-((ma-ca)+(ca-cb)+(cb-mb))if full else None)\ndef productivity(output0,output1,hours0,hours1):\n o0,o1,h0,h1=map(number,[output0,output1,hours0,hours1])\n if min(o0,o1,h0,h1)<=0:raise ValueError('positive output and hours required')\n go,gh=o1/o0,h1/h0;gp=go/gh\n return dict(outputGross=go,hoursGross=gh,productivityGross=gp,outputPercent=(go-1)*100,hoursPercent=(gh-1)*100,productivityPercent=(gp-1)*100,differenceOfPercentGrowths=(go-gh)*100,exactGrowthIdentityResidual=gp-go/gh)\ndef measurement(numerator,denominator,lower=None,upper=None):\n n,d=number(numerator),number(denominator)\n if d<0:raise ValueError('nonnegative denominator required')\n interval=None\n if lower is not None or upper is not None:\n  lo,hi=number(lower),number(upper)\n  if lo<=0 or hi<lo:raise ValueError('ordered positive scenario bounds')\n  interval=sorted([n/lo,n/hi])\n return dict(ratio=n/d if d else None,denominatorScenarioInterval=interval)\ndef read_csv(folder,name):\n with (folder/name).open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))\ndef load_sources(folder):\n h=read_csv(folder,'actual180-KOR-housing-nominal-real-indexes.csv');b=read_csv(folder,'actual38-US-nonfarm-output-hours-productivity-indexes.csv');p=read_csv(folder,'actual10839-person-wage-panel-original-and-prior-derived-fields.csv');c=read_csv(folder,'actual3-Apple-revenue-and-approximate-periodend-FTE-facts.csv')\n company={}\n for r in c:\n  value=Q(r['originalToken'].replace(',',''))\n  company[('revenue'+r['fiscalYear'])if r['fact']=='consolidated total net sales'else'endpointFTE2024']=value*1000000 if r['fact']=='consolidated total net sales'else value\n return dict(housing=h,bls=b,person=p,company=company)\ndef person_comparison(models,before=1976,after=1980):\n if before not in [1976,1978,1980]or after not in [1976,1978,1980]or before>=after:raise ValueError('ordered observed waves required')\n units=defaultdict(dict)\n for r in models['person']:\n  year=int(r['time'])\n  if year in units[r['unit']]:raise ValueError('duplicate original unit-wave')\n  token=r['wageCentsOriginal'];units[r['unit']][year]=None if token in ['.','','NA']else number(token)/100\n return composition([dict(id=k,before=v[before],after=v[after])for k,v in units.items()])\ndef realdata(models,kind):\n if kind=='country':\n  rows=models['housing'];return dict(originalCount=len(rows),growth=growth(rows[0]['nominal'],rows[-1]['nominal']),rebased=rebase([r['nominal']for r in rows]))\n if kind=='person':return person_comparison(models)\n if kind=='company':\n  c=models['company'];return dict(revenueGrowth=growth(c['revenue2023'],c['revenue2024']),ratio=measurement(c['revenue2024'],c['endpointFTE2024'])['ratio'],proxyGrowth=None)\n raise ValueError('actual case required')\ndef encode(v):\n if isinstance(v,Q):return str(v)\n if isinstance(v,dict):return{k:encode(x)for k,x in v.items()}\n if isinstance(v,(list,tuple)):return[encode(x)for x in v]\n return v\ndef write_csv(path,rows):\n with path.open('w',encoding='utf8',newline='')as f:\n  writer=csv.DictWriter(f,fieldnames=list(rows[0]));writer.writeheader();writer.writerows([{k:''if v is None else str(v)for k,v in r.items()}for r in rows])\ndef full_source(folder,out):\n out.mkdir(parents=True,exist_ok=True);models=load_sources(folder);metrics={};country=[];frames=[]\n for source in ['housing','bls']:\n  data=models[source];columns=['nominal','real']if source=='housing'else['outputIndexOriginalToken','hoursIndexOriginalToken','productivityIndexOriginalToken']\n  for col in columns:\n   values=[r[col]for r in data];rb=rebase(values);g=growth(values[0],values[-1])\n   for k,v in g.items():metrics[source+':'+col+':'+k]=v\n   quarter_base=next((i for i,r in enumerate(data)if r['quarter']=='2010-Q1'),None)if source=='housing'else None\n   qb=rebase(values,quarter_base)if quarter_base is not None else[None]*len(values)\n   country.extend(dict(source=source,series=col,row=i+1,quarter=r['quarter'],originalToken=r[col],rebasedFirst100Exact=rb[i],rebased2010Q1Exact=qb[i])for i,r in enumerate(data))\n for a,b in [(1976,1978),(1978,1980),(1976,1980)]:\n  z=person_comparison(models,a,b);frames.append(dict(before=a,after=b,elapsedYears=b-a,**z));metrics.update({f'person:{a}:{b}:{k}':v for k,v in z.items()})\n c=realdata(models,'company');metrics['company:proxy']=c['ratio'];metrics['company:proxyGrowth']=None;metrics.update({'company:sales:'+k:v for k,v in c['revenueGrowth'].items()})\n changes=[]\n for a,b in zip(models['bls'],models['bls'][1:]):\n  z=productivity(a['outputIndexOriginalToken'],b['outputIndexOriginalToken'],a['hoursIndexOriginalToken'],b['hoursIndexOriginalToken']);g=growth(a['productivityIndexOriginalToken'],b['productivityIndexOriginalToken'],4)\n  changes.append(dict(start=a['quarter'],end=b['quarter'],**z,publishedProductivityPercent=g['percentChange'],publishedAnnualizedPercent=g['annualizedPercent']))\n selected=list(dict.fromkeys(r['unit']for r in models['person']))[:12]\n trajectories=[dict(unit=r['unit'],year=r['time'],nominalUSDPerHourExact=None if r['wageCentsOriginal']in['.','','NA']else number(r['wageCentsOriginal'])/100)for r in models['person']if r['unit']in selected]\n write_csv(out/'metrics.csv',[dict(metric=k,value=v)for k,v in metrics.items()]);write_csv(out/'country-indexes.csv',country);write_csv(out/'wage-frames.csv',frames);write_csv(out/'bls-changes.csv',changes);write_csv(out/'first12-trajectories.csv',trajectories)\n (out/'full-results.json').write_text(json.dumps(encode(dict(metrics=metrics,frames=frames,company=c)),ensure_ascii=False,indent=2)+'\\n',encoding='utf8');return{f.name:len(read_csv(out,f.name))for f in out.glob('*.csv')}\nif __name__=='__main__':\n parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--source-dir',type=Path,default=Path(__file__).parent/'econ22-sources');parser.add_argument('--output-dir',type=Path,default=Path(__file__).parent/'econ22-python-results');args=parser.parse_args();print(json.dumps(full_source(args.source_dir,args.output_dir)))\n"
          },
          {
            "file": "econ22-fixed-support.py",
            "sha256": "deb4273c9c713e16c2f5e5d3525932ae34753f348731a3b26a4babff015c2fd6",
            "codeText": "\"\"\"Public fixed-example support. Requires only Python standard library and econ22-reproduce.py.\nFixed examples are separate from current browser inputs. Missing values remain None.\n\"\"\"\nfrom pathlib import Path\nfrom fractions import Fraction as Q\nimport importlib.util,json,csv,html,math\nROOT=Path(__file__).resolve().parent\nspec=importlib.util.spec_from_file_location('econ22_public',ROOT/'econ22-reproduce.py');M=importlib.util.module_from_spec(spec);spec.loader.exec_module(M)\n\ndef example(api,variant):\n if api=='rebase':\n  values=[0,1]if variant=='invalid'else[80,None,120]if variant=='gap'else[80,100,120];z=M.rebase(values);return dict(rows=len(z),defined=sum(x is not None for x in z),last=z[-1]),list(enumerate(z)),'Position','Rebased index'\n if api=='growth':\n  end=90 if variant=='quarterly'else 120;z=M.growth(100,end,4 if variant=='quarterly'else 1);return z,[(0,Q(100)),(1,Q(end))],'Date','Supplied level'\n if api=='composition':\n  rows=[dict(id='A',before=10,after=None),dict(id='B',before=None,after=20)]if variant=='noCommon'else[dict(id='A',before=10,after=11),dict(id='B',before=100,after=None),dict(id='C',before=None,after=1)];z=M.composition(rows);metrics={k:z[k]for k in ['beforeAvailableMean','afterAvailableMean','availableMeanChange','commonWithinChange','commonUnits','exactDecompositionResidual']};return metrics,[(0,z['beforeAvailableMean']),(1,z['afterAvailableMean'])],'Date','Available mean / assumed units'\n if api=='productivity':\n  o,h=(90,80)if variant=='contraction'else(103,101);z=M.productivity(100,o,100,h);return z,[(0,Q(1)),(1,z['productivityGross'])],'Date','Output per hour / initial=1'\n if api=='measurement':\n  n,d=(0,0)if variant=='zero'else(391035000000,164000);z=M.measurement(n,d);return dict(ratio=z['ratio'],denominatorZero=int(d==0),sourceApproximate=int(variant!='zero')),[(0,z['ratio'])],'Ratio position','USD / approximate endpoint FTE'\n models=M.load_sources(ROOT/'econ22-sources');z=M.realdata(models,variant)\n if variant=='country':return dict(sourceRows=z['originalCount'],first=Q(models['housing'][0]['nominal']),last=Q(models['housing'][-1]['nominal']),percentChange=z['growth']['percentChange']),list(enumerate(z['rebased'])),'Quarter position / original calendar','Nominal housing / first=100'\n if variant=='person':return{k:z[k]for k in ['sourceUnits','beforeAvailableUnits','afterAvailableUnits','commonUnits','availableMeanChange','commonWithinChange','exactDecompositionResidual']},[(1976,z['beforeAvailableMean']),(1980,z['afterAvailableMean'])],'Observed wave','Nominal USD/hour / available mean'\n if variant=='company':return dict(sales2023=models['company']['revenue2023'],sales2024=models['company']['revenue2024'],proxy=z['ratio'],proxyGrowth=None),[(2023,models['company']['revenue2023']/1000000),(2024,models['company']['revenue2024']/1000000)],'Fiscal year','Nominal USD millions'\n raise ValueError('fixed example name required')\n\ndef svg(points,xlabel,ylabel):\n good=[(float(x),float(y))for x,y in points if y is not None]\n if not good:return None\n if any(not math.isfinite(x)or not math.isfinite(y)for x,y in good):raise ValueError('outside finite plotting range')\n w,h,L,R,T,B=640,360,90,22,28,54;xmin=min(float(p[0])for p in points);xmax=max(float(p[0])for p in points);ymin=min(y for x,y in good);ymax=max(y for x,y in good)\n pad=max(1,abs(ymin)*.05)if ymin==ymax else(ymax-ymin)*.08;ymin-=pad;ymax+=pad\n X=lambda x:(L+w-R)/2 if xmax==xmin else L+(float(x)-xmin)/(xmax-xmin)*(w-L-R);Y=lambda y:T+(ymax-float(y))/(ymax-ymin)*(h-T-B);esc=html.escape\n s=f'<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"640\" height=\"360\" viewBox=\"0 0 640 360\" role=\"img\" aria-label=\"{esc(xlabel+\"; \"+ylabel)}\"><title>{esc(xlabel+\"; \"+ylabel)}</title><rect width=\"640\" height=\"360\" fill=\"white\"/><g font-family=\"sans-serif\" font-size=\"13\" fill=\"#222\">'\n for i in range(4):\n  v=ymin+(ymax-ymin)*i/3;y=Y(v);s+=f'<line x1=\"{L}\" x2=\"{w-R}\" y1=\"{y}\" y2=\"{y}\" stroke=\"#ccd6db\"/><text x=\"{L-7}\" y=\"{y+4}\" text-anchor=\"end\">{v:.4g}</text>'\n for x,anchor in([(xmin,'middle')]if xmin==xmax else[(xmin,'start'),(xmax,'end')]):s+=f'<text x=\"{X(x)}\" y=\"{h-B+24}\" text-anchor=\"{anchor}\">{x:g}</text>'\n last=None\n for x,y in points:\n  if y is None:last=None;continue\n  a,b=X(x),Y(y)\n  if last:s+=f'<line x1=\"{last[0]}\" y1=\"{last[1]}\" x2=\"{a}\" y2=\"{b}\" stroke=\"#355c72\" stroke-width=\"2\"/>'\n  s+=f'<circle cx=\"{a}\" cy=\"{b}\" r=\"3\" fill=\"#934b34\"><title>{esc(str(x)+\": \"+str(y))}</title></circle>';last=(a,b)\n return s+f'<text x=\"{L}\" y=\"16\">{esc(ylabel)}</text><text x=\"{w-R}\" y=\"{h-6}\" text-anchor=\"end\">{esc(xlabel)}</text></g></svg>'\n\ndef run(api,variant,output):\n out=Path(output);out.mkdir(parents=True,exist_ok=True);metrics,points,x,y=example(api,variant);encoded=M.encode(metrics);(out/'summary.json').write_text(json.dumps(encoded,indent=2)+'\\n',encoding='utf8')\n M.write_csv(out/'summary.csv',[dict(metric=k,value=v)for k,v in metrics.items()]);M.write_csv(out/'plot-points.csv',[dict(x=a,y=b)for a,b in points]);graphic=svg(points,x,y)\n if graphic is not None:(out/'plot.svg').write_text(graphic,encoding='utf8')\n print(json.dumps(dict(api=api,variant=variant,metrics=encoded,plotProduced=graphic is not None),ensure_ascii=False))\n"
          }
        ],
        "inputFiles": [],
        "returnCode": 0,
        "expectedFailure": false,
        "stdout": "{\"api\": \"growth\", \"variant\": \"default\", \"metrics\": {\"gross\": \"6/5\", \"percentChange\": \"20\", \"annualizedGross\": \"6/5\", \"annualizedPercent\": \"20\"}, \"plotProduced\": true}\n",
        "stderr": "",
        "seconds": 0.125,
        "summary": {
          "gross": "6/5",
          "percentChange": "20",
          "annualizedGross": "6/5",
          "annualizedPercent": "20"
        },
        "plotPoints": [
          {
            "x": "0",
            "y": "100"
          },
          {
            "x": "1",
            "y": "120"
          }
        ],
        "plotFile": "econ22-fixed-results/growth-default-python/plot.svg",
        "plotSHA256": "12c9a4365e9bf0dc00413d78d18d066f8febc71b8846963bde1def4c9dabd5d8",
        "scope": "Actually executed fixed example. Current browser controls are calculated separately by JavaScript. Base-R outputs use finite precision; Python outputs use exact fractions.",
        "summaryFile": "econ22-fixed-results/growth-default-python/summary.csv",
        "summarySHA256": "6224fbfc460bf8afa0ed97ef8d78cee532d233f7cdca45031be65c57155dfca9",
        "plotPointsFile": "econ22-fixed-results/growth-default-python/plot-points.csv",
        "plotPointsSHA256": "b281bbf0ee37ce68f971be020ef5638a0a604dc0a876b16e7c79f9d820b94d51"
      },
      "quarterly": {
        "api": "growth",
        "variant": "quarterly",
        "language": "python",
        "codeFile": "econ22-code/growth-quarterly.py",
        "codeSHA256": "4ae6d324ff55601d8b50e9bb49af2b90afd1a5a4e7042e3bab5b74c9743545f5",
        "codeText": "# Fixed stated example, separate from current web controls.\nfrom pathlib import Path\nimport importlib.util,sys\nroot=Path(__file__).resolve().parents[1]\nspec=importlib.util.spec_from_file_location('fixed_support',root/'econ22-fixed-support.py')\nsupport=importlib.util.module_from_spec(spec);spec.loader.exec_module(support)\ntry:support.run('growth','quarterly',sys.argv[1]if len(sys.argv)>1 else root/'econ22-fixed-results/growth-quarterly-python')\nexcept ValueError as error:\n print('Rejected declared input: '+str(error),file=sys.stderr);sys.exit(2)\n",
        "supportFiles": [
          {
            "file": "econ22-reproduce.py",
            "sha256": "cc5631d9dfea963b64349bb28d18b69ad3caf15a15162ec6cea786a36e18de48",
            "codeText": "#!/usr/bin/env python3\n\"\"\"ECON22 public reproduction: Python standard library, exact Fraction arithmetic.\nRun: python econ22-reproduce.py --source-dir econ22-sources --output-dir econ22-python-results\nOriginal CSV inputs are read only. Output is a new chosen directory.\nThese are descriptive arithmetic and explicitly assumed examples, not causal estimates.\n\"\"\"\nfrom fractions import Fraction as Q\nfrom pathlib import Path\nfrom collections import defaultdict\nimport argparse,csv,json\n\ndef number(x):\n if x is None:raise ValueError('missing numeric token')\n return Q(str(x))\ndef rebase(values,base=0,scale='100'):\n v=[None if x is None else number(x)for x in values];s=number(scale)\n if not v or not 0<=base<len(v)or v[base]is None or v[base]<=0 or s<=0:raise ValueError('positive observed base/scale required')\n return [None if x is None else s*x/v[base]for x in v]\ndef growth(start,end,periods=1):\n a,b=number(start),number(end)\n if a<=0 or b<0 or not isinstance(periods,int)or not 1<=periods<=12:raise ValueError('growth domain')\n g=b/a;return dict(gross=g,percentChange=(g-1)*100,annualizedGross=g**periods,annualizedPercent=(g**periods-1)*100)\ndef composition(rows):\n seen=set();data=[]\n for r in rows:\n  identifier=str(r['id']);weight=number(r.get('weight','1'))\n  if identifier in seen or weight<0:raise ValueError('unique units/nonnegative fixed weights required')\n  seen.add(identifier);data.append(dict(id=identifier,weight=weight,before=None if r['before']is None else number(r['before']),after=None if r['after']is None else number(r['after'])))\n if not data:raise ValueError('nonempty frame required')\n valid=[r for r in data if r['weight']>0];b=[r for r in valid if r['before']is not None];a=[r for r in valid if r['after']is not None];c=[r for r in valid if r['before']is not None and r['after']is not None]\n def mean(rs,k):\n  mass=sum((r['weight']for r in rs),Q(0));return sum((r[k]*r['weight']for r in rs),Q(0))/mass if mass else None\n mb,ma,cb,ca=mean(b,'before'),mean(a,'after'),mean(c,'before'),mean(c,'after');full=all(x is not None for x in [mb,ma,cb,ca]);change=ma-mb if mb is not None and ma is not None else None\n return dict(sourceUnits=len(data),beforeAvailableUnits=len(b),afterAvailableUnits=len(a),commonUnits=len(c),beforeAvailableMean=mb,afterAvailableMean=ma,beforeCommonMean=cb,afterCommonMean=ca,availableMeanChange=change,commonWithinChange=ca-cb if full else None,afterFrameShift=ma-ca if full else None,beforeFrameShift=cb-mb if full else None,exactDecompositionResidual=change-((ma-ca)+(ca-cb)+(cb-mb))if full else None)\ndef productivity(output0,output1,hours0,hours1):\n o0,o1,h0,h1=map(number,[output0,output1,hours0,hours1])\n if min(o0,o1,h0,h1)<=0:raise ValueError('positive output and hours required')\n go,gh=o1/o0,h1/h0;gp=go/gh\n return dict(outputGross=go,hoursGross=gh,productivityGross=gp,outputPercent=(go-1)*100,hoursPercent=(gh-1)*100,productivityPercent=(gp-1)*100,differenceOfPercentGrowths=(go-gh)*100,exactGrowthIdentityResidual=gp-go/gh)\ndef measurement(numerator,denominator,lower=None,upper=None):\n n,d=number(numerator),number(denominator)\n if d<0:raise ValueError('nonnegative denominator required')\n interval=None\n if lower is not None or upper is not None:\n  lo,hi=number(lower),number(upper)\n  if lo<=0 or hi<lo:raise ValueError('ordered positive scenario bounds')\n  interval=sorted([n/lo,n/hi])\n return dict(ratio=n/d if d else None,denominatorScenarioInterval=interval)\ndef read_csv(folder,name):\n with (folder/name).open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))\ndef load_sources(folder):\n h=read_csv(folder,'actual180-KOR-housing-nominal-real-indexes.csv');b=read_csv(folder,'actual38-US-nonfarm-output-hours-productivity-indexes.csv');p=read_csv(folder,'actual10839-person-wage-panel-original-and-prior-derived-fields.csv');c=read_csv(folder,'actual3-Apple-revenue-and-approximate-periodend-FTE-facts.csv')\n company={}\n for r in c:\n  value=Q(r['originalToken'].replace(',',''))\n  company[('revenue'+r['fiscalYear'])if r['fact']=='consolidated total net sales'else'endpointFTE2024']=value*1000000 if r['fact']=='consolidated total net sales'else value\n return dict(housing=h,bls=b,person=p,company=company)\ndef person_comparison(models,before=1976,after=1980):\n if before not in [1976,1978,1980]or after not in [1976,1978,1980]or before>=after:raise ValueError('ordered observed waves required')\n units=defaultdict(dict)\n for r in models['person']:\n  year=int(r['time'])\n  if year in units[r['unit']]:raise ValueError('duplicate original unit-wave')\n  token=r['wageCentsOriginal'];units[r['unit']][year]=None if token in ['.','','NA']else number(token)/100\n return composition([dict(id=k,before=v[before],after=v[after])for k,v in units.items()])\ndef realdata(models,kind):\n if kind=='country':\n  rows=models['housing'];return dict(originalCount=len(rows),growth=growth(rows[0]['nominal'],rows[-1]['nominal']),rebased=rebase([r['nominal']for r in rows]))\n if kind=='person':return person_comparison(models)\n if kind=='company':\n  c=models['company'];return dict(revenueGrowth=growth(c['revenue2023'],c['revenue2024']),ratio=measurement(c['revenue2024'],c['endpointFTE2024'])['ratio'],proxyGrowth=None)\n raise ValueError('actual case required')\ndef encode(v):\n if isinstance(v,Q):return str(v)\n if isinstance(v,dict):return{k:encode(x)for k,x in v.items()}\n if isinstance(v,(list,tuple)):return[encode(x)for x in v]\n return v\ndef write_csv(path,rows):\n with path.open('w',encoding='utf8',newline='')as f:\n  writer=csv.DictWriter(f,fieldnames=list(rows[0]));writer.writeheader();writer.writerows([{k:''if v is None else str(v)for k,v in r.items()}for r in rows])\ndef full_source(folder,out):\n out.mkdir(parents=True,exist_ok=True);models=load_sources(folder);metrics={};country=[];frames=[]\n for source in ['housing','bls']:\n  data=models[source];columns=['nominal','real']if source=='housing'else['outputIndexOriginalToken','hoursIndexOriginalToken','productivityIndexOriginalToken']\n  for col in columns:\n   values=[r[col]for r in data];rb=rebase(values);g=growth(values[0],values[-1])\n   for k,v in g.items():metrics[source+':'+col+':'+k]=v\n   quarter_base=next((i for i,r in enumerate(data)if r['quarter']=='2010-Q1'),None)if source=='housing'else None\n   qb=rebase(values,quarter_base)if quarter_base is not None else[None]*len(values)\n   country.extend(dict(source=source,series=col,row=i+1,quarter=r['quarter'],originalToken=r[col],rebasedFirst100Exact=rb[i],rebased2010Q1Exact=qb[i])for i,r in enumerate(data))\n for a,b in [(1976,1978),(1978,1980),(1976,1980)]:\n  z=person_comparison(models,a,b);frames.append(dict(before=a,after=b,elapsedYears=b-a,**z));metrics.update({f'person:{a}:{b}:{k}':v for k,v in z.items()})\n c=realdata(models,'company');metrics['company:proxy']=c['ratio'];metrics['company:proxyGrowth']=None;metrics.update({'company:sales:'+k:v for k,v in c['revenueGrowth'].items()})\n changes=[]\n for a,b in zip(models['bls'],models['bls'][1:]):\n  z=productivity(a['outputIndexOriginalToken'],b['outputIndexOriginalToken'],a['hoursIndexOriginalToken'],b['hoursIndexOriginalToken']);g=growth(a['productivityIndexOriginalToken'],b['productivityIndexOriginalToken'],4)\n  changes.append(dict(start=a['quarter'],end=b['quarter'],**z,publishedProductivityPercent=g['percentChange'],publishedAnnualizedPercent=g['annualizedPercent']))\n selected=list(dict.fromkeys(r['unit']for r in models['person']))[:12]\n trajectories=[dict(unit=r['unit'],year=r['time'],nominalUSDPerHourExact=None if r['wageCentsOriginal']in['.','','NA']else number(r['wageCentsOriginal'])/100)for r in models['person']if r['unit']in selected]\n write_csv(out/'metrics.csv',[dict(metric=k,value=v)for k,v in metrics.items()]);write_csv(out/'country-indexes.csv',country);write_csv(out/'wage-frames.csv',frames);write_csv(out/'bls-changes.csv',changes);write_csv(out/'first12-trajectories.csv',trajectories)\n (out/'full-results.json').write_text(json.dumps(encode(dict(metrics=metrics,frames=frames,company=c)),ensure_ascii=False,indent=2)+'\\n',encoding='utf8');return{f.name:len(read_csv(out,f.name))for f in out.glob('*.csv')}\nif __name__=='__main__':\n parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--source-dir',type=Path,default=Path(__file__).parent/'econ22-sources');parser.add_argument('--output-dir',type=Path,default=Path(__file__).parent/'econ22-python-results');args=parser.parse_args();print(json.dumps(full_source(args.source_dir,args.output_dir)))\n"
          },
          {
            "file": "econ22-fixed-support.py",
            "sha256": "deb4273c9c713e16c2f5e5d3525932ae34753f348731a3b26a4babff015c2fd6",
            "codeText": "\"\"\"Public fixed-example support. Requires only Python standard library and econ22-reproduce.py.\nFixed examples are separate from current browser inputs. Missing values remain None.\n\"\"\"\nfrom pathlib import Path\nfrom fractions import Fraction as Q\nimport importlib.util,json,csv,html,math\nROOT=Path(__file__).resolve().parent\nspec=importlib.util.spec_from_file_location('econ22_public',ROOT/'econ22-reproduce.py');M=importlib.util.module_from_spec(spec);spec.loader.exec_module(M)\n\ndef example(api,variant):\n if api=='rebase':\n  values=[0,1]if variant=='invalid'else[80,None,120]if variant=='gap'else[80,100,120];z=M.rebase(values);return dict(rows=len(z),defined=sum(x is not None for x in z),last=z[-1]),list(enumerate(z)),'Position','Rebased index'\n if api=='growth':\n  end=90 if variant=='quarterly'else 120;z=M.growth(100,end,4 if variant=='quarterly'else 1);return z,[(0,Q(100)),(1,Q(end))],'Date','Supplied level'\n if api=='composition':\n  rows=[dict(id='A',before=10,after=None),dict(id='B',before=None,after=20)]if variant=='noCommon'else[dict(id='A',before=10,after=11),dict(id='B',before=100,after=None),dict(id='C',before=None,after=1)];z=M.composition(rows);metrics={k:z[k]for k in ['beforeAvailableMean','afterAvailableMean','availableMeanChange','commonWithinChange','commonUnits','exactDecompositionResidual']};return metrics,[(0,z['beforeAvailableMean']),(1,z['afterAvailableMean'])],'Date','Available mean / assumed units'\n if api=='productivity':\n  o,h=(90,80)if variant=='contraction'else(103,101);z=M.productivity(100,o,100,h);return z,[(0,Q(1)),(1,z['productivityGross'])],'Date','Output per hour / initial=1'\n if api=='measurement':\n  n,d=(0,0)if variant=='zero'else(391035000000,164000);z=M.measurement(n,d);return dict(ratio=z['ratio'],denominatorZero=int(d==0),sourceApproximate=int(variant!='zero')),[(0,z['ratio'])],'Ratio position','USD / approximate endpoint FTE'\n models=M.load_sources(ROOT/'econ22-sources');z=M.realdata(models,variant)\n if variant=='country':return dict(sourceRows=z['originalCount'],first=Q(models['housing'][0]['nominal']),last=Q(models['housing'][-1]['nominal']),percentChange=z['growth']['percentChange']),list(enumerate(z['rebased'])),'Quarter position / original calendar','Nominal housing / first=100'\n if variant=='person':return{k:z[k]for k in ['sourceUnits','beforeAvailableUnits','afterAvailableUnits','commonUnits','availableMeanChange','commonWithinChange','exactDecompositionResidual']},[(1976,z['beforeAvailableMean']),(1980,z['afterAvailableMean'])],'Observed wave','Nominal USD/hour / available mean'\n if variant=='company':return dict(sales2023=models['company']['revenue2023'],sales2024=models['company']['revenue2024'],proxy=z['ratio'],proxyGrowth=None),[(2023,models['company']['revenue2023']/1000000),(2024,models['company']['revenue2024']/1000000)],'Fiscal year','Nominal USD millions'\n raise ValueError('fixed example name required')\n\ndef svg(points,xlabel,ylabel):\n good=[(float(x),float(y))for x,y in points if y is not None]\n if not good:return None\n if any(not math.isfinite(x)or not math.isfinite(y)for x,y in good):raise ValueError('outside finite plotting range')\n w,h,L,R,T,B=640,360,90,22,28,54;xmin=min(float(p[0])for p in points);xmax=max(float(p[0])for p in points);ymin=min(y for x,y in good);ymax=max(y for x,y in good)\n pad=max(1,abs(ymin)*.05)if ymin==ymax else(ymax-ymin)*.08;ymin-=pad;ymax+=pad\n X=lambda x:(L+w-R)/2 if xmax==xmin else L+(float(x)-xmin)/(xmax-xmin)*(w-L-R);Y=lambda y:T+(ymax-float(y))/(ymax-ymin)*(h-T-B);esc=html.escape\n s=f'<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"640\" height=\"360\" viewBox=\"0 0 640 360\" role=\"img\" aria-label=\"{esc(xlabel+\"; \"+ylabel)}\"><title>{esc(xlabel+\"; \"+ylabel)}</title><rect width=\"640\" height=\"360\" fill=\"white\"/><g font-family=\"sans-serif\" font-size=\"13\" fill=\"#222\">'\n for i in range(4):\n  v=ymin+(ymax-ymin)*i/3;y=Y(v);s+=f'<line x1=\"{L}\" x2=\"{w-R}\" y1=\"{y}\" y2=\"{y}\" stroke=\"#ccd6db\"/><text x=\"{L-7}\" y=\"{y+4}\" text-anchor=\"end\">{v:.4g}</text>'\n for x,anchor in([(xmin,'middle')]if xmin==xmax else[(xmin,'start'),(xmax,'end')]):s+=f'<text x=\"{X(x)}\" y=\"{h-B+24}\" text-anchor=\"{anchor}\">{x:g}</text>'\n last=None\n for x,y in points:\n  if y is None:last=None;continue\n  a,b=X(x),Y(y)\n  if last:s+=f'<line x1=\"{last[0]}\" y1=\"{last[1]}\" x2=\"{a}\" y2=\"{b}\" stroke=\"#355c72\" stroke-width=\"2\"/>'\n  s+=f'<circle cx=\"{a}\" cy=\"{b}\" r=\"3\" fill=\"#934b34\"><title>{esc(str(x)+\": \"+str(y))}</title></circle>';last=(a,b)\n return s+f'<text x=\"{L}\" y=\"16\">{esc(ylabel)}</text><text x=\"{w-R}\" y=\"{h-6}\" text-anchor=\"end\">{esc(xlabel)}</text></g></svg>'\n\ndef run(api,variant,output):\n out=Path(output);out.mkdir(parents=True,exist_ok=True);metrics,points,x,y=example(api,variant);encoded=M.encode(metrics);(out/'summary.json').write_text(json.dumps(encoded,indent=2)+'\\n',encoding='utf8')\n M.write_csv(out/'summary.csv',[dict(metric=k,value=v)for k,v in metrics.items()]);M.write_csv(out/'plot-points.csv',[dict(x=a,y=b)for a,b in points]);graphic=svg(points,x,y)\n if graphic is not None:(out/'plot.svg').write_text(graphic,encoding='utf8')\n print(json.dumps(dict(api=api,variant=variant,metrics=encoded,plotProduced=graphic is not None),ensure_ascii=False))\n"
          }
        ],
        "inputFiles": [],
        "returnCode": 0,
        "expectedFailure": false,
        "stdout": "{\"api\": \"growth\", \"variant\": \"quarterly\", \"metrics\": {\"gross\": \"9/10\", \"percentChange\": \"-10\", \"annualizedGross\": \"6561/10000\", \"annualizedPercent\": \"-3439/100\"}, \"plotProduced\": true}\n",
        "stderr": "",
        "seconds": 0.125,
        "summary": {
          "gross": "9/10",
          "percentChange": "-10",
          "annualizedGross": "6561/10000",
          "annualizedPercent": "-3439/100"
        },
        "plotPoints": [
          {
            "x": "0",
            "y": "100"
          },
          {
            "x": "1",
            "y": "90"
          }
        ],
        "plotFile": "econ22-fixed-results/growth-quarterly-python/plot.svg",
        "plotSHA256": "acb52ba3059e227b7b7c0ab67a61e96eba145343ab919ba6134c046b4f31c9a1",
        "scope": "Actually executed fixed example. Current browser controls are calculated separately by JavaScript. Base-R outputs use finite precision; Python outputs use exact fractions.",
        "summaryFile": "econ22-fixed-results/growth-quarterly-python/summary.csv",
        "summarySHA256": "b08c5009e7dc8ff89c1fe284bad7f06e1a93c97d5b1df1d3d866b62b01f2a93a",
        "plotPointsFile": "econ22-fixed-results/growth-quarterly-python/plot-points.csv",
        "plotPointsSHA256": "e3c69d52f50d301e7049127d48a26003335a76f1e04a652a17f2882096075dfb"
      }
    },
    "r": {
      "default": {
        "api": "growth",
        "variant": "default",
        "language": "r",
        "codeFile": "econ22-code/growth-default.R",
        "codeSHA256": "19a2d521cef89864894ba57adb1252316a9428324ce1ff8938c0be1a0e2e24d8",
        "codeText": "# Run from the extracted textbook bundle root.\nsource('econ22-fixed-support.R',encoding='UTF-8')\noptions(digits=17)\nargs<-commandArgs(trailingOnly=TRUE)\noutput<-if(length(args))args[1]else'econ22-fixed-results/growth-default-r'\ntryCatch(run('growth','default',output),error=function(error){cat('Rejected declared input: ',conditionMessage(error),'\\n',file=stderr());quit(status=2)})\n",
        "supportFiles": [
          {
            "file": "econ22-reproduce.R",
            "sha256": "2db22759696a6f288479189f44026f265536a54cdc2e72952c1e91af13661480",
            "codeText": "# ECON22 independent public base-R reproduction; binary64 approximations.\n# Run: Rscript --vanilla --encoding=UTF-8 econ22-reproduce.R [source-dir] [output-dir]\n# Source CSVs are never overwritten. No packages or network required.\nrebase <- function(values, base=1L, scale=100) {\n  if (length(base)!=1L || !is.finite(base) || base!=as.integer(base) || !length(values) || base<1 || base>length(values) || is.na(values[base]) || values[base]<=0 || !is.finite(scale) || scale<=0) stop('positive observed base/scale required')\n  scale*values/values[base]\n}\ngrowth <- function(start,end,periods=1L) {\n  if (start<=0 || end<0 || periods<1 || periods>12 || periods!=as.integer(periods)) stop('growth domain')\n  gross<-end/start;list(gross=gross,percentChange=(gross-1)*100,annualizedGross=gross^periods,annualizedPercent=(gross^periods-1)*100)\n}\ncomposition <- function(rows) {\n  if (!nrow(rows) || anyDuplicated(rows$id)) stop('nonempty unique units required')\n  if (!'weight'%in%names(rows)) rows$weight<-rep(1,nrow(rows))\n  if (any(!is.finite(rows$weight)) || any(rows$weight<0)) stop('nonnegative fixed weights required')\n  valid<-rows$weight>0;b<-valid&!is.na(rows$before);a<-valid&!is.na(rows$after);common<-b&a\n  avg<-function(mask,column)if(sum(rows$weight[mask])>0)sum(rows[[column]][mask]*rows$weight[mask])/sum(rows$weight[mask])else NA_real_\n  mb<-avg(b,'before');ma<-avg(a,'after');cb<-avg(common,'before');ca<-avg(common,'after');full<-all(is.finite(c(mb,ma,cb,ca)))\n  list(sourceUnits=nrow(rows),beforeAvailableUnits=sum(b),afterAvailableUnits=sum(a),commonUnits=sum(common),beforeAvailableMean=mb,afterAvailableMean=ma,beforeCommonMean=cb,afterCommonMean=ca,availableMeanChange=ma-mb,commonWithinChange=if(full)ca-cb else NA_real_,afterFrameShift=if(full)ma-ca else NA_real_,beforeFrameShift=if(full)cb-mb else NA_real_,exactDecompositionResidual=if(full)(ma-mb)-((ma-ca)+(ca-cb)+(cb-mb))else NA_real_)\n}\nproductivity <- function(output0,output1,hours0,hours1) {\n  if(any(c(output0,output1,hours0,hours1)<=0))stop('positive output and hours required')\n  go<-output1/output0;gh<-hours1/hours0;gp<-go/gh\n  list(outputGross=go,hoursGross=gh,productivityGross=gp,outputPercent=(go-1)*100,hoursPercent=(gh-1)*100,productivityPercent=(gp-1)*100,differenceOfPercentGrowths=(go-gh)*100,exactGrowthIdentityResidual=gp-go/gh)\n}\nmeasurement <- function(numerator,denominator,lower=NA_real_,upper=NA_real_) {\n  if(denominator<0)stop('nonnegative denominator required');interval<-NULL\n  if(!is.na(lower)||!is.na(upper)){if(any(!is.finite(c(lower,upper)))||lower<=0||upper<lower)stop('ordered positive scenario bounds');interval<-sort(c(numerator/lower,numerator/upper))}\n  list(ratio=if(denominator>0)numerator/denominator else NA_real_,denominatorScenarioInterval=interval)\n}\nload_sources <- function(folder) {\n  read<-function(file)read.csv(file.path(folder,file),stringsAsFactors=FALSE,check.names=FALSE,colClasses='character',na.strings=c('NA','','.'))\n  h<-read('actual180-KOR-housing-nominal-real-indexes.csv');b<-read('actual38-US-nonfarm-output-hours-productivity-indexes.csv');p<-read('actual10839-person-wage-panel-original-and-prior-derived-fields.csv');c<-read('actual3-Apple-revenue-and-approximate-periodend-FTE-facts.csv')\n  company<-list();for(i in seq_len(nrow(c))){value<-as.numeric(gsub(',','',c$originalToken[i],fixed=TRUE));if(c$fact[i]=='consolidated total net sales')company[[paste0('revenue',c$fiscalYear[i])]]<-value*1e6 else company$endpointFTE2024<-value}\n  list(housing=h,bls=b,person=p,company=company)\n}\nperson_comparison <- function(models,before=1976L,after=1980L) {\n  if(!before%in%c(1976,1978,1980)||!after%in%c(1976,1978,1980)||before>=after)stop('ordered observed waves required')\n  p<-models$person;if(anyDuplicated(paste(p$unit,p$time,sep=':')))stop('duplicate original unit-wave')\n  ids<-unique(p$unit);rows<-data.frame(id=ids,before=as.numeric(p$wageCentsOriginal[match(paste(ids,before),paste(p$unit,p$time))])/100,after=as.numeric(p$wageCentsOriginal[match(paste(ids,after),paste(p$unit,p$time))])/100,stringsAsFactors=FALSE)\n  composition(rows)\n}\nrealdata <- function(models,kind) {\n  if(kind=='country'){r<-models$housing;return(list(originalCount=nrow(r),growth=growth(as.numeric(r$nominal[1]),as.numeric(tail(r$nominal,1))),rebased=rebase(as.numeric(r$nominal))))}\n  if(kind=='person')return(person_comparison(models))\n  if(kind=='company'){c<-models$company;return(list(revenueGrowth=growth(c$revenue2023,c$revenue2024),ratio=measurement(c$revenue2024,c$endpointFTE2024)$ratio,proxyGrowth=NA_real_))}\n  stop('actual case required')\n}\nfull_source <- function(folder,out) {\n  dir.create(out,recursive=TRUE,showWarnings=FALSE);models<-load_sources(folder);metrics<-list();country<-list();frames<-list()\n  for(source in c('housing','bls')){data<-models[[source]];columns<-if(source=='housing')c('nominal','real')else c('outputIndexOriginalToken','hoursIndexOriginalToken','productivityIndexOriginalToken')\n    for(col in columns){values<-as.numeric(data[[col]]);rb<-rebase(values);g<-growth(values[1],tail(values,1));for(k in names(g))metrics[[paste(source,col,k,sep=':')]]<-g[[k]];quarterBase<-if(source=='housing')match('2010-Q1',data$quarter)else NA_integer_;qb<-if(!is.na(quarterBase))rebase(values,quarterBase)else rep(NA_real_,length(values));country[[length(country)+1]]<-data.frame(source=source,series=col,row=seq_len(nrow(data)),quarter=data$quarter,originalToken=data[[col]],rebasedFirst100Exact=rb,rebased2010Q1Exact=qb,stringsAsFactors=FALSE)}}\n  for(pair in list(c(1976,1978),c(1978,1980),c(1976,1980))){a<-pair[1];b<-pair[2];z<-person_comparison(models,a,b);frames[[length(frames)+1]]<-as.data.frame(c(list(before=a,after=b,elapsedYears=b-a),z),stringsAsFactors=FALSE);for(k in names(z))metrics[[paste('person',a,b,k,sep=':')]]<-z[[k]]}\n  company<-realdata(models,'company');metrics[['company:proxy']]<-company$ratio;metrics[['company:proxyGrowth']]<-NA_real_;for(k in names(company$revenueGrowth))metrics[[paste('company:sales',k,sep=':')]]<-company$revenueGrowth[[k]]\n  changes<-list();b<-models$bls\n  for(i in seq_len(nrow(b)-1L)){z<-productivity(as.numeric(b$outputIndexOriginalToken[i]),as.numeric(b$outputIndexOriginalToken[i+1]),as.numeric(b$hoursIndexOriginalToken[i]),as.numeric(b$hoursIndexOriginalToken[i+1]));g<-growth(as.numeric(b$productivityIndexOriginalToken[i]),as.numeric(b$productivityIndexOriginalToken[i+1]),4);changes[[i]]<-as.data.frame(c(list(start=b$quarter[i],end=b$quarter[i+1]),z,list(publishedProductivityPercent=g$percentChange,publishedAnnualizedPercent=g$annualizedPercent)),stringsAsFactors=FALSE)}\n  write<-function(name,rows)write.csv(rows,file.path(out,name),row.names=FALSE,na='',fileEncoding='UTF-8')\n  selected<-head(unique(models$person$unit),12);p<-models$person[models$person$unit%in%selected,];trajectories<-data.frame(unit=p$unit,year=p$time,nominalUSDPerHourExact=as.numeric(p$wageCentsOriginal)/100,stringsAsFactors=FALSE)\n  write('metrics.csv',data.frame(metric=names(metrics),value=as.numeric(unlist(metrics))));write('country-indexes.csv',do.call(rbind,country));write('wage-frames.csv',do.call(rbind,frames));write('bls-changes.csv',do.call(rbind,changes));write('first12-trajectories.csv',trajectories);invisible(metrics)\n}\nif(sys.nframe()==0L){args<-commandArgs(trailingOnly=TRUE);folder<-if(length(args)>=1)args[1]else'econ22-sources';out<-if(length(args)>=2)args[2]else'econ22-r-results';options(digits=17);metrics<-full_source(folder,out);cat('metrics:',length(metrics),'\\noutput directory:',out,'\\n')}\n"
          },
          {
            "file": "econ22-fixed-support.R",
            "sha256": "d4d63e1ad02017f20884b5932458dbde6013e0c2e560a4a9922a13d080a59fa1",
            "codeText": "# Run fixed drivers from the extracted bundle root. No packages or network required.\nsource('econ22-reproduce.R',encoding='UTF-8')\nexample <- function(api,variant) {\n  if(api=='rebase'){v<-if(variant=='invalid')c(0,1)else if(variant=='gap')c(80,NA,120)else c(80,100,120);z<-rebase(v);return(list(metrics=list(rows=length(z),defined=sum(!is.na(z)),last=tail(z,1)),x=seq_along(z)-1,y=z,xlabel='Position',ylabel='Rebased index'))}\n  if(api=='growth'){end<-if(variant=='quarterly')90 else 120;z<-growth(100,end,if(variant=='quarterly')4 else 1);return(list(metrics=z,x=c(0,1),y=c(100,end),xlabel='Date',ylabel='Supplied level'))}\n  if(api=='composition'){rows<-if(variant=='noCommon')data.frame(id=c('A','B'),before=c(10,NA),after=c(NA,20))else data.frame(id=c('A','B','C'),before=c(10,100,NA),after=c(11,NA,1));z<-composition(rows);metrics<-z[c('beforeAvailableMean','afterAvailableMean','availableMeanChange','commonWithinChange','commonUnits','exactDecompositionResidual')];return(list(metrics=metrics,x=c(0,1),y=c(z$beforeAvailableMean,z$afterAvailableMean),xlabel='Date',ylabel='Available mean / assumed units'))}\n  if(api=='productivity'){o<-if(variant=='contraction')90 else 103;h<-if(variant=='contraction')80 else 101;z<-productivity(100,o,100,h);return(list(metrics=z,x=c(0,1),y=c(1,z$productivityGross),xlabel='Date',ylabel='Output per hour / initial=1'))}\n  if(api=='measurement'){n<-if(variant=='zero')0 else 391035000000;d<-if(variant=='zero')0 else 164000;z<-measurement(n,d);return(list(metrics=list(ratio=z$ratio,denominatorZero=as.integer(d==0),sourceApproximate=as.integer(variant!='zero')),x=0,y=z$ratio,xlabel='Ratio position',ylabel='USD / approximate endpoint FTE'))}\n  models<-load_sources('econ22-sources');z<-realdata(models,variant)\n  if(variant=='country')return(list(metrics=list(sourceRows=z$originalCount,first=as.numeric(head(models$housing$nominal,1)),last=as.numeric(tail(models$housing$nominal,1)),percentChange=z$growth$percentChange),x=seq_along(z$rebased)-1,y=z$rebased,xlabel='Quarter position / original calendar',ylabel='Nominal housing / first=100'))\n  if(variant=='person')return(list(metrics=z[c('sourceUnits','beforeAvailableUnits','afterAvailableUnits','commonUnits','availableMeanChange','commonWithinChange','exactDecompositionResidual')],x=c(1976,1980),y=c(z$beforeAvailableMean,z$afterAvailableMean),xlabel='Observed wave',ylabel='Nominal USD/hour / available mean'))\n  if(variant=='company')return(list(metrics=list(sales2023=models$company$revenue2023,sales2024=models$company$revenue2024,proxy=z$ratio,proxyGrowth=NA_real_),x=c(2023,2024),y=c(models$company$revenue2023,models$company$revenue2024)/1e6,xlabel='Fiscal year',ylabel='Nominal USD millions'))\n  stop('fixed example name required')\n}\nrun <- function(api,variant,output) {\n  dir.create(output,recursive=TRUE,showWarnings=FALSE);z<-example(api,variant);metrics<-data.frame(metric=names(z$metrics),value=as.numeric(unlist(z$metrics)),stringsAsFactors=FALSE)\n  write.csv(metrics,file.path(output,'summary.csv'),row.names=FALSE,na='',fileEncoding='UTF-8');write.csv(data.frame(x=z$x,y=z$y),file.path(output,'plot-points.csv'),row.names=FALSE,na='',fileEncoding='UTF-8');print(metrics,row.names=FALSE)\n  good<-is.finite(z$x)&is.finite(z$y)\n  if(any(good)){svg(file.path(output,'plot.svg'),width=640/96,height=360/96,pointsize=10);par(mar=c(4.5,5.8,2,1));plot(z$x,z$y,type='o',pch=16,cex=.7,col='#355c72',xlab=z$xlabel,ylab=z$ylabel,cex.axis=.85,cex.lab=.9);grid(col='#d5dde1');dev.off();cat('plotProduced: TRUE\\n')}else cat('plotProduced: FALSE; undefined values retained\\n')\n}\n"
          }
        ],
        "inputFiles": [],
        "returnCode": 0,
        "expectedFailure": false,
        "stdout": "            metric              value\n             gross  1.200000000000000\n     percentChange 19.999999999999996\n   annualizedGross  1.200000000000000\n annualizedPercent 19.999999999999996\nplotProduced: TRUE\n",
        "stderr": "During startup - Warning messages:\n1: Setting LC_COLLATE=C.UTF-8 failed \n2: Setting LC_CTYPE=C.UTF-8 failed \n3: Setting LC_MONETARY=C.UTF-8 failed \n4: Setting LC_TIME=C.UTF-8 failed \n",
        "seconds": 0.2970000000204891,
        "summary": {
          "gross": "1.2",
          "percentChange": "20",
          "annualizedGross": "1.2",
          "annualizedPercent": "20"
        },
        "plotPoints": [
          {
            "x": "0",
            "y": "100"
          },
          {
            "x": "1",
            "y": "120"
          }
        ],
        "plotFile": "econ22-fixed-results/growth-default-r/plot.svg",
        "plotSHA256": "20e783e47bf60d69386cb7993b1b941b8548b21febc619fbaa6f48c771417834",
        "scope": "Actually executed fixed example. Current browser controls are calculated separately by JavaScript. Base-R outputs use finite precision; Python outputs use exact fractions.",
        "summaryFile": "econ22-fixed-results/growth-default-r/summary.csv",
        "summarySHA256": "2a5073a6ba3d95474b4cc0bbafc51d7de595d7891d9d6806fe4066c82354308d",
        "plotPointsFile": "econ22-fixed-results/growth-default-r/plot-points.csv",
        "plotPointsSHA256": "0fbab3e24db393b3be7c77f7cf82e3f5f6a21c0cd79d645bebb3c2fe5cb2d570"
      },
      "quarterly": {
        "api": "growth",
        "variant": "quarterly",
        "language": "r",
        "codeFile": "econ22-code/growth-quarterly.R",
        "codeSHA256": "913ac46aa21a85f638bd6b374ea2f8b8fd64f70f8447729e4c2fcd1b6d72c4e0",
        "codeText": "# Run from the extracted textbook bundle root.\nsource('econ22-fixed-support.R',encoding='UTF-8')\noptions(digits=17)\nargs<-commandArgs(trailingOnly=TRUE)\noutput<-if(length(args))args[1]else'econ22-fixed-results/growth-quarterly-r'\ntryCatch(run('growth','quarterly',output),error=function(error){cat('Rejected declared input: ',conditionMessage(error),'\\n',file=stderr());quit(status=2)})\n",
        "supportFiles": [
          {
            "file": "econ22-reproduce.R",
            "sha256": "2db22759696a6f288479189f44026f265536a54cdc2e72952c1e91af13661480",
            "codeText": "# ECON22 independent public base-R reproduction; binary64 approximations.\n# Run: Rscript --vanilla --encoding=UTF-8 econ22-reproduce.R [source-dir] [output-dir]\n# Source CSVs are never overwritten. No packages or network required.\nrebase <- function(values, base=1L, scale=100) {\n  if (length(base)!=1L || !is.finite(base) || base!=as.integer(base) || !length(values) || base<1 || base>length(values) || is.na(values[base]) || values[base]<=0 || !is.finite(scale) || scale<=0) stop('positive observed base/scale required')\n  scale*values/values[base]\n}\ngrowth <- function(start,end,periods=1L) {\n  if (start<=0 || end<0 || periods<1 || periods>12 || periods!=as.integer(periods)) stop('growth domain')\n  gross<-end/start;list(gross=gross,percentChange=(gross-1)*100,annualizedGross=gross^periods,annualizedPercent=(gross^periods-1)*100)\n}\ncomposition <- function(rows) {\n  if (!nrow(rows) || anyDuplicated(rows$id)) stop('nonempty unique units required')\n  if (!'weight'%in%names(rows)) rows$weight<-rep(1,nrow(rows))\n  if (any(!is.finite(rows$weight)) || any(rows$weight<0)) stop('nonnegative fixed weights required')\n  valid<-rows$weight>0;b<-valid&!is.na(rows$before);a<-valid&!is.na(rows$after);common<-b&a\n  avg<-function(mask,column)if(sum(rows$weight[mask])>0)sum(rows[[column]][mask]*rows$weight[mask])/sum(rows$weight[mask])else NA_real_\n  mb<-avg(b,'before');ma<-avg(a,'after');cb<-avg(common,'before');ca<-avg(common,'after');full<-all(is.finite(c(mb,ma,cb,ca)))\n  list(sourceUnits=nrow(rows),beforeAvailableUnits=sum(b),afterAvailableUnits=sum(a),commonUnits=sum(common),beforeAvailableMean=mb,afterAvailableMean=ma,beforeCommonMean=cb,afterCommonMean=ca,availableMeanChange=ma-mb,commonWithinChange=if(full)ca-cb else NA_real_,afterFrameShift=if(full)ma-ca else NA_real_,beforeFrameShift=if(full)cb-mb else NA_real_,exactDecompositionResidual=if(full)(ma-mb)-((ma-ca)+(ca-cb)+(cb-mb))else NA_real_)\n}\nproductivity <- function(output0,output1,hours0,hours1) {\n  if(any(c(output0,output1,hours0,hours1)<=0))stop('positive output and hours required')\n  go<-output1/output0;gh<-hours1/hours0;gp<-go/gh\n  list(outputGross=go,hoursGross=gh,productivityGross=gp,outputPercent=(go-1)*100,hoursPercent=(gh-1)*100,productivityPercent=(gp-1)*100,differenceOfPercentGrowths=(go-gh)*100,exactGrowthIdentityResidual=gp-go/gh)\n}\nmeasurement <- function(numerator,denominator,lower=NA_real_,upper=NA_real_) {\n  if(denominator<0)stop('nonnegative denominator required');interval<-NULL\n  if(!is.na(lower)||!is.na(upper)){if(any(!is.finite(c(lower,upper)))||lower<=0||upper<lower)stop('ordered positive scenario bounds');interval<-sort(c(numerator/lower,numerator/upper))}\n  list(ratio=if(denominator>0)numerator/denominator else NA_real_,denominatorScenarioInterval=interval)\n}\nload_sources <- function(folder) {\n  read<-function(file)read.csv(file.path(folder,file),stringsAsFactors=FALSE,check.names=FALSE,colClasses='character',na.strings=c('NA','','.'))\n  h<-read('actual180-KOR-housing-nominal-real-indexes.csv');b<-read('actual38-US-nonfarm-output-hours-productivity-indexes.csv');p<-read('actual10839-person-wage-panel-original-and-prior-derived-fields.csv');c<-read('actual3-Apple-revenue-and-approximate-periodend-FTE-facts.csv')\n  company<-list();for(i in seq_len(nrow(c))){value<-as.numeric(gsub(',','',c$originalToken[i],fixed=TRUE));if(c$fact[i]=='consolidated total net sales')company[[paste0('revenue',c$fiscalYear[i])]]<-value*1e6 else company$endpointFTE2024<-value}\n  list(housing=h,bls=b,person=p,company=company)\n}\nperson_comparison <- function(models,before=1976L,after=1980L) {\n  if(!before%in%c(1976,1978,1980)||!after%in%c(1976,1978,1980)||before>=after)stop('ordered observed waves required')\n  p<-models$person;if(anyDuplicated(paste(p$unit,p$time,sep=':')))stop('duplicate original unit-wave')\n  ids<-unique(p$unit);rows<-data.frame(id=ids,before=as.numeric(p$wageCentsOriginal[match(paste(ids,before),paste(p$unit,p$time))])/100,after=as.numeric(p$wageCentsOriginal[match(paste(ids,after),paste(p$unit,p$time))])/100,stringsAsFactors=FALSE)\n  composition(rows)\n}\nrealdata <- function(models,kind) {\n  if(kind=='country'){r<-models$housing;return(list(originalCount=nrow(r),growth=growth(as.numeric(r$nominal[1]),as.numeric(tail(r$nominal,1))),rebased=rebase(as.numeric(r$nominal))))}\n  if(kind=='person')return(person_comparison(models))\n  if(kind=='company'){c<-models$company;return(list(revenueGrowth=growth(c$revenue2023,c$revenue2024),ratio=measurement(c$revenue2024,c$endpointFTE2024)$ratio,proxyGrowth=NA_real_))}\n  stop('actual case required')\n}\nfull_source <- function(folder,out) {\n  dir.create(out,recursive=TRUE,showWarnings=FALSE);models<-load_sources(folder);metrics<-list();country<-list();frames<-list()\n  for(source in c('housing','bls')){data<-models[[source]];columns<-if(source=='housing')c('nominal','real')else c('outputIndexOriginalToken','hoursIndexOriginalToken','productivityIndexOriginalToken')\n    for(col in columns){values<-as.numeric(data[[col]]);rb<-rebase(values);g<-growth(values[1],tail(values,1));for(k in names(g))metrics[[paste(source,col,k,sep=':')]]<-g[[k]];quarterBase<-if(source=='housing')match('2010-Q1',data$quarter)else NA_integer_;qb<-if(!is.na(quarterBase))rebase(values,quarterBase)else rep(NA_real_,length(values));country[[length(country)+1]]<-data.frame(source=source,series=col,row=seq_len(nrow(data)),quarter=data$quarter,originalToken=data[[col]],rebasedFirst100Exact=rb,rebased2010Q1Exact=qb,stringsAsFactors=FALSE)}}\n  for(pair in list(c(1976,1978),c(1978,1980),c(1976,1980))){a<-pair[1];b<-pair[2];z<-person_comparison(models,a,b);frames[[length(frames)+1]]<-as.data.frame(c(list(before=a,after=b,elapsedYears=b-a),z),stringsAsFactors=FALSE);for(k in names(z))metrics[[paste('person',a,b,k,sep=':')]]<-z[[k]]}\n  company<-realdata(models,'company');metrics[['company:proxy']]<-company$ratio;metrics[['company:proxyGrowth']]<-NA_real_;for(k in names(company$revenueGrowth))metrics[[paste('company:sales',k,sep=':')]]<-company$revenueGrowth[[k]]\n  changes<-list();b<-models$bls\n  for(i in seq_len(nrow(b)-1L)){z<-productivity(as.numeric(b$outputIndexOriginalToken[i]),as.numeric(b$outputIndexOriginalToken[i+1]),as.numeric(b$hoursIndexOriginalToken[i]),as.numeric(b$hoursIndexOriginalToken[i+1]));g<-growth(as.numeric(b$productivityIndexOriginalToken[i]),as.numeric(b$productivityIndexOriginalToken[i+1]),4);changes[[i]]<-as.data.frame(c(list(start=b$quarter[i],end=b$quarter[i+1]),z,list(publishedProductivityPercent=g$percentChange,publishedAnnualizedPercent=g$annualizedPercent)),stringsAsFactors=FALSE)}\n  write<-function(name,rows)write.csv(rows,file.path(out,name),row.names=FALSE,na='',fileEncoding='UTF-8')\n  selected<-head(unique(models$person$unit),12);p<-models$person[models$person$unit%in%selected,];trajectories<-data.frame(unit=p$unit,year=p$time,nominalUSDPerHourExact=as.numeric(p$wageCentsOriginal)/100,stringsAsFactors=FALSE)\n  write('metrics.csv',data.frame(metric=names(metrics),value=as.numeric(unlist(metrics))));write('country-indexes.csv',do.call(rbind,country));write('wage-frames.csv',do.call(rbind,frames));write('bls-changes.csv',do.call(rbind,changes));write('first12-trajectories.csv',trajectories);invisible(metrics)\n}\nif(sys.nframe()==0L){args<-commandArgs(trailingOnly=TRUE);folder<-if(length(args)>=1)args[1]else'econ22-sources';out<-if(length(args)>=2)args[2]else'econ22-r-results';options(digits=17);metrics<-full_source(folder,out);cat('metrics:',length(metrics),'\\noutput directory:',out,'\\n')}\n"
          },
          {
            "file": "econ22-fixed-support.R",
            "sha256": "d4d63e1ad02017f20884b5932458dbde6013e0c2e560a4a9922a13d080a59fa1",
            "codeText": "# Run fixed drivers from the extracted bundle root. No packages or network required.\nsource('econ22-reproduce.R',encoding='UTF-8')\nexample <- function(api,variant) {\n  if(api=='rebase'){v<-if(variant=='invalid')c(0,1)else if(variant=='gap')c(80,NA,120)else c(80,100,120);z<-rebase(v);return(list(metrics=list(rows=length(z),defined=sum(!is.na(z)),last=tail(z,1)),x=seq_along(z)-1,y=z,xlabel='Position',ylabel='Rebased index'))}\n  if(api=='growth'){end<-if(variant=='quarterly')90 else 120;z<-growth(100,end,if(variant=='quarterly')4 else 1);return(list(metrics=z,x=c(0,1),y=c(100,end),xlabel='Date',ylabel='Supplied level'))}\n  if(api=='composition'){rows<-if(variant=='noCommon')data.frame(id=c('A','B'),before=c(10,NA),after=c(NA,20))else data.frame(id=c('A','B','C'),before=c(10,100,NA),after=c(11,NA,1));z<-composition(rows);metrics<-z[c('beforeAvailableMean','afterAvailableMean','availableMeanChange','commonWithinChange','commonUnits','exactDecompositionResidual')];return(list(metrics=metrics,x=c(0,1),y=c(z$beforeAvailableMean,z$afterAvailableMean),xlabel='Date',ylabel='Available mean / assumed units'))}\n  if(api=='productivity'){o<-if(variant=='contraction')90 else 103;h<-if(variant=='contraction')80 else 101;z<-productivity(100,o,100,h);return(list(metrics=z,x=c(0,1),y=c(1,z$productivityGross),xlabel='Date',ylabel='Output per hour / initial=1'))}\n  if(api=='measurement'){n<-if(variant=='zero')0 else 391035000000;d<-if(variant=='zero')0 else 164000;z<-measurement(n,d);return(list(metrics=list(ratio=z$ratio,denominatorZero=as.integer(d==0),sourceApproximate=as.integer(variant!='zero')),x=0,y=z$ratio,xlabel='Ratio position',ylabel='USD / approximate endpoint FTE'))}\n  models<-load_sources('econ22-sources');z<-realdata(models,variant)\n  if(variant=='country')return(list(metrics=list(sourceRows=z$originalCount,first=as.numeric(head(models$housing$nominal,1)),last=as.numeric(tail(models$housing$nominal,1)),percentChange=z$growth$percentChange),x=seq_along(z$rebased)-1,y=z$rebased,xlabel='Quarter position / original calendar',ylabel='Nominal housing / first=100'))\n  if(variant=='person')return(list(metrics=z[c('sourceUnits','beforeAvailableUnits','afterAvailableUnits','commonUnits','availableMeanChange','commonWithinChange','exactDecompositionResidual')],x=c(1976,1980),y=c(z$beforeAvailableMean,z$afterAvailableMean),xlabel='Observed wave',ylabel='Nominal USD/hour / available mean'))\n  if(variant=='company')return(list(metrics=list(sales2023=models$company$revenue2023,sales2024=models$company$revenue2024,proxy=z$ratio,proxyGrowth=NA_real_),x=c(2023,2024),y=c(models$company$revenue2023,models$company$revenue2024)/1e6,xlabel='Fiscal year',ylabel='Nominal USD millions'))\n  stop('fixed example name required')\n}\nrun <- function(api,variant,output) {\n  dir.create(output,recursive=TRUE,showWarnings=FALSE);z<-example(api,variant);metrics<-data.frame(metric=names(z$metrics),value=as.numeric(unlist(z$metrics)),stringsAsFactors=FALSE)\n  write.csv(metrics,file.path(output,'summary.csv'),row.names=FALSE,na='',fileEncoding='UTF-8');write.csv(data.frame(x=z$x,y=z$y),file.path(output,'plot-points.csv'),row.names=FALSE,na='',fileEncoding='UTF-8');print(metrics,row.names=FALSE)\n  good<-is.finite(z$x)&is.finite(z$y)\n  if(any(good)){svg(file.path(output,'plot.svg'),width=640/96,height=360/96,pointsize=10);par(mar=c(4.5,5.8,2,1));plot(z$x,z$y,type='o',pch=16,cex=.7,col='#355c72',xlab=z$xlabel,ylab=z$ylabel,cex.axis=.85,cex.lab=.9);grid(col='#d5dde1');dev.off();cat('plotProduced: TRUE\\n')}else cat('plotProduced: FALSE; undefined values retained\\n')\n}\n"
          }
        ],
        "inputFiles": [],
        "returnCode": 0,
        "expectedFailure": false,
        "stdout": "            metric                 value\n             gross   0.90000000000000002\n     percentChange  -9.99999999999999822\n   annualizedGross   0.65610000000000002\n annualizedPercent -34.39000000000000057\nplotProduced: TRUE\n",
        "stderr": "During startup - Warning messages:\n1: Setting LC_COLLATE=C.UTF-8 failed \n2: Setting LC_CTYPE=C.UTF-8 failed \n3: Setting LC_MONETARY=C.UTF-8 failed \n4: Setting LC_TIME=C.UTF-8 failed \n",
        "seconds": 0.28100000001722947,
        "summary": {
          "gross": "0.9",
          "percentChange": "-10",
          "annualizedGross": "0.6561",
          "annualizedPercent": "-34.39"
        },
        "plotPoints": [
          {
            "x": "0",
            "y": "100"
          },
          {
            "x": "1",
            "y": "90"
          }
        ],
        "plotFile": "econ22-fixed-results/growth-quarterly-r/plot.svg",
        "plotSHA256": "27688e5f0d6143664629167e9243d8fa8661b23e4ef7571c91b4f6e846ee0cbb",
        "scope": "Actually executed fixed example. Current browser controls are calculated separately by JavaScript. Base-R outputs use finite precision; Python outputs use exact fractions.",
        "summaryFile": "econ22-fixed-results/growth-quarterly-r/summary.csv",
        "summarySHA256": "ea92c49fe36441bac911e077130466074446546cd1d6c8e0aaec4a19a7353802",
        "plotPointsFile": "econ22-fixed-results/growth-quarterly-r/plot-points.csv",
        "plotPointsSHA256": "f28ba40d653f6e03ba04f1c256dc22604ccbdac0970e6e11664e2126ad318269"
      }
    }
  },
  "composition": {
    "python": {
      "default": {
        "api": "composition",
        "variant": "default",
        "language": "python",
        "codeFile": "econ22-code/composition-default.py",
        "codeSHA256": "9117635d245bf40b8c0f5ae89c805fd684452e64a3200172c7ed9738e093ebc9",
        "codeText": "# Fixed stated example, separate from current web controls.\nfrom pathlib import Path\nimport importlib.util,sys\nroot=Path(__file__).resolve().parents[1]\nspec=importlib.util.spec_from_file_location('fixed_support',root/'econ22-fixed-support.py')\nsupport=importlib.util.module_from_spec(spec);spec.loader.exec_module(support)\ntry:support.run('composition','default',sys.argv[1]if len(sys.argv)>1 else root/'econ22-fixed-results/composition-default-python')\nexcept ValueError as error:\n print('Rejected declared input: '+str(error),file=sys.stderr);sys.exit(2)\n",
        "supportFiles": [
          {
            "file": "econ22-reproduce.py",
            "sha256": "cc5631d9dfea963b64349bb28d18b69ad3caf15a15162ec6cea786a36e18de48",
            "codeText": "#!/usr/bin/env python3\n\"\"\"ECON22 public reproduction: Python standard library, exact Fraction arithmetic.\nRun: python econ22-reproduce.py --source-dir econ22-sources --output-dir econ22-python-results\nOriginal CSV inputs are read only. Output is a new chosen directory.\nThese are descriptive arithmetic and explicitly assumed examples, not causal estimates.\n\"\"\"\nfrom fractions import Fraction as Q\nfrom pathlib import Path\nfrom collections import defaultdict\nimport argparse,csv,json\n\ndef number(x):\n if x is None:raise ValueError('missing numeric token')\n return Q(str(x))\ndef rebase(values,base=0,scale='100'):\n v=[None if x is None else number(x)for x in values];s=number(scale)\n if not v or not 0<=base<len(v)or v[base]is None or v[base]<=0 or s<=0:raise ValueError('positive observed base/scale required')\n return [None if x is None else s*x/v[base]for x in v]\ndef growth(start,end,periods=1):\n a,b=number(start),number(end)\n if a<=0 or b<0 or not isinstance(periods,int)or not 1<=periods<=12:raise ValueError('growth domain')\n g=b/a;return dict(gross=g,percentChange=(g-1)*100,annualizedGross=g**periods,annualizedPercent=(g**periods-1)*100)\ndef composition(rows):\n seen=set();data=[]\n for r in rows:\n  identifier=str(r['id']);weight=number(r.get('weight','1'))\n  if identifier in seen or weight<0:raise ValueError('unique units/nonnegative fixed weights required')\n  seen.add(identifier);data.append(dict(id=identifier,weight=weight,before=None if r['before']is None else number(r['before']),after=None if r['after']is None else number(r['after'])))\n if not data:raise ValueError('nonempty frame required')\n valid=[r for r in data if r['weight']>0];b=[r for r in valid if r['before']is not None];a=[r for r in valid if r['after']is not None];c=[r for r in valid if r['before']is not None and r['after']is not None]\n def mean(rs,k):\n  mass=sum((r['weight']for r in rs),Q(0));return sum((r[k]*r['weight']for r in rs),Q(0))/mass if mass else None\n mb,ma,cb,ca=mean(b,'before'),mean(a,'after'),mean(c,'before'),mean(c,'after');full=all(x is not None for x in [mb,ma,cb,ca]);change=ma-mb if mb is not None and ma is not None else None\n return dict(sourceUnits=len(data),beforeAvailableUnits=len(b),afterAvailableUnits=len(a),commonUnits=len(c),beforeAvailableMean=mb,afterAvailableMean=ma,beforeCommonMean=cb,afterCommonMean=ca,availableMeanChange=change,commonWithinChange=ca-cb if full else None,afterFrameShift=ma-ca if full else None,beforeFrameShift=cb-mb if full else None,exactDecompositionResidual=change-((ma-ca)+(ca-cb)+(cb-mb))if full else None)\ndef productivity(output0,output1,hours0,hours1):\n o0,o1,h0,h1=map(number,[output0,output1,hours0,hours1])\n if min(o0,o1,h0,h1)<=0:raise ValueError('positive output and hours required')\n go,gh=o1/o0,h1/h0;gp=go/gh\n return dict(outputGross=go,hoursGross=gh,productivityGross=gp,outputPercent=(go-1)*100,hoursPercent=(gh-1)*100,productivityPercent=(gp-1)*100,differenceOfPercentGrowths=(go-gh)*100,exactGrowthIdentityResidual=gp-go/gh)\ndef measurement(numerator,denominator,lower=None,upper=None):\n n,d=number(numerator),number(denominator)\n if d<0:raise ValueError('nonnegative denominator required')\n interval=None\n if lower is not None or upper is not None:\n  lo,hi=number(lower),number(upper)\n  if lo<=0 or hi<lo:raise ValueError('ordered positive scenario bounds')\n  interval=sorted([n/lo,n/hi])\n return dict(ratio=n/d if d else None,denominatorScenarioInterval=interval)\ndef read_csv(folder,name):\n with (folder/name).open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))\ndef load_sources(folder):\n h=read_csv(folder,'actual180-KOR-housing-nominal-real-indexes.csv');b=read_csv(folder,'actual38-US-nonfarm-output-hours-productivity-indexes.csv');p=read_csv(folder,'actual10839-person-wage-panel-original-and-prior-derived-fields.csv');c=read_csv(folder,'actual3-Apple-revenue-and-approximate-periodend-FTE-facts.csv')\n company={}\n for r in c:\n  value=Q(r['originalToken'].replace(',',''))\n  company[('revenue'+r['fiscalYear'])if r['fact']=='consolidated total net sales'else'endpointFTE2024']=value*1000000 if r['fact']=='consolidated total net sales'else value\n return dict(housing=h,bls=b,person=p,company=company)\ndef person_comparison(models,before=1976,after=1980):\n if before not in [1976,1978,1980]or after not in [1976,1978,1980]or before>=after:raise ValueError('ordered observed waves required')\n units=defaultdict(dict)\n for r in models['person']:\n  year=int(r['time'])\n  if year in units[r['unit']]:raise ValueError('duplicate original unit-wave')\n  token=r['wageCentsOriginal'];units[r['unit']][year]=None if token in ['.','','NA']else number(token)/100\n return composition([dict(id=k,before=v[before],after=v[after])for k,v in units.items()])\ndef realdata(models,kind):\n if kind=='country':\n  rows=models['housing'];return dict(originalCount=len(rows),growth=growth(rows[0]['nominal'],rows[-1]['nominal']),rebased=rebase([r['nominal']for r in rows]))\n if kind=='person':return person_comparison(models)\n if kind=='company':\n  c=models['company'];return dict(revenueGrowth=growth(c['revenue2023'],c['revenue2024']),ratio=measurement(c['revenue2024'],c['endpointFTE2024'])['ratio'],proxyGrowth=None)\n raise ValueError('actual case required')\ndef encode(v):\n if isinstance(v,Q):return str(v)\n if isinstance(v,dict):return{k:encode(x)for k,x in v.items()}\n if isinstance(v,(list,tuple)):return[encode(x)for x in v]\n return v\ndef write_csv(path,rows):\n with path.open('w',encoding='utf8',newline='')as f:\n  writer=csv.DictWriter(f,fieldnames=list(rows[0]));writer.writeheader();writer.writerows([{k:''if v is None else str(v)for k,v in r.items()}for r in rows])\ndef full_source(folder,out):\n out.mkdir(parents=True,exist_ok=True);models=load_sources(folder);metrics={};country=[];frames=[]\n for source in ['housing','bls']:\n  data=models[source];columns=['nominal','real']if source=='housing'else['outputIndexOriginalToken','hoursIndexOriginalToken','productivityIndexOriginalToken']\n  for col in columns:\n   values=[r[col]for r in data];rb=rebase(values);g=growth(values[0],values[-1])\n   for k,v in g.items():metrics[source+':'+col+':'+k]=v\n   quarter_base=next((i for i,r in enumerate(data)if r['quarter']=='2010-Q1'),None)if source=='housing'else None\n   qb=rebase(values,quarter_base)if quarter_base is not None else[None]*len(values)\n   country.extend(dict(source=source,series=col,row=i+1,quarter=r['quarter'],originalToken=r[col],rebasedFirst100Exact=rb[i],rebased2010Q1Exact=qb[i])for i,r in enumerate(data))\n for a,b in [(1976,1978),(1978,1980),(1976,1980)]:\n  z=person_comparison(models,a,b);frames.append(dict(before=a,after=b,elapsedYears=b-a,**z));metrics.update({f'person:{a}:{b}:{k}':v for k,v in z.items()})\n c=realdata(models,'company');metrics['company:proxy']=c['ratio'];metrics['company:proxyGrowth']=None;metrics.update({'company:sales:'+k:v for k,v in c['revenueGrowth'].items()})\n changes=[]\n for a,b in zip(models['bls'],models['bls'][1:]):\n  z=productivity(a['outputIndexOriginalToken'],b['outputIndexOriginalToken'],a['hoursIndexOriginalToken'],b['hoursIndexOriginalToken']);g=growth(a['productivityIndexOriginalToken'],b['productivityIndexOriginalToken'],4)\n  changes.append(dict(start=a['quarter'],end=b['quarter'],**z,publishedProductivityPercent=g['percentChange'],publishedAnnualizedPercent=g['annualizedPercent']))\n selected=list(dict.fromkeys(r['unit']for r in models['person']))[:12]\n trajectories=[dict(unit=r['unit'],year=r['time'],nominalUSDPerHourExact=None if r['wageCentsOriginal']in['.','','NA']else number(r['wageCentsOriginal'])/100)for r in models['person']if r['unit']in selected]\n write_csv(out/'metrics.csv',[dict(metric=k,value=v)for k,v in metrics.items()]);write_csv(out/'country-indexes.csv',country);write_csv(out/'wage-frames.csv',frames);write_csv(out/'bls-changes.csv',changes);write_csv(out/'first12-trajectories.csv',trajectories)\n (out/'full-results.json').write_text(json.dumps(encode(dict(metrics=metrics,frames=frames,company=c)),ensure_ascii=False,indent=2)+'\\n',encoding='utf8');return{f.name:len(read_csv(out,f.name))for f in out.glob('*.csv')}\nif __name__=='__main__':\n parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--source-dir',type=Path,default=Path(__file__).parent/'econ22-sources');parser.add_argument('--output-dir',type=Path,default=Path(__file__).parent/'econ22-python-results');args=parser.parse_args();print(json.dumps(full_source(args.source_dir,args.output_dir)))\n"
          },
          {
            "file": "econ22-fixed-support.py",
            "sha256": "deb4273c9c713e16c2f5e5d3525932ae34753f348731a3b26a4babff015c2fd6",
            "codeText": "\"\"\"Public fixed-example support. Requires only Python standard library and econ22-reproduce.py.\nFixed examples are separate from current browser inputs. Missing values remain None.\n\"\"\"\nfrom pathlib import Path\nfrom fractions import Fraction as Q\nimport importlib.util,json,csv,html,math\nROOT=Path(__file__).resolve().parent\nspec=importlib.util.spec_from_file_location('econ22_public',ROOT/'econ22-reproduce.py');M=importlib.util.module_from_spec(spec);spec.loader.exec_module(M)\n\ndef example(api,variant):\n if api=='rebase':\n  values=[0,1]if variant=='invalid'else[80,None,120]if variant=='gap'else[80,100,120];z=M.rebase(values);return dict(rows=len(z),defined=sum(x is not None for x in z),last=z[-1]),list(enumerate(z)),'Position','Rebased index'\n if api=='growth':\n  end=90 if variant=='quarterly'else 120;z=M.growth(100,end,4 if variant=='quarterly'else 1);return z,[(0,Q(100)),(1,Q(end))],'Date','Supplied level'\n if api=='composition':\n  rows=[dict(id='A',before=10,after=None),dict(id='B',before=None,after=20)]if variant=='noCommon'else[dict(id='A',before=10,after=11),dict(id='B',before=100,after=None),dict(id='C',before=None,after=1)];z=M.composition(rows);metrics={k:z[k]for k in ['beforeAvailableMean','afterAvailableMean','availableMeanChange','commonWithinChange','commonUnits','exactDecompositionResidual']};return metrics,[(0,z['beforeAvailableMean']),(1,z['afterAvailableMean'])],'Date','Available mean / assumed units'\n if api=='productivity':\n  o,h=(90,80)if variant=='contraction'else(103,101);z=M.productivity(100,o,100,h);return z,[(0,Q(1)),(1,z['productivityGross'])],'Date','Output per hour / initial=1'\n if api=='measurement':\n  n,d=(0,0)if variant=='zero'else(391035000000,164000);z=M.measurement(n,d);return dict(ratio=z['ratio'],denominatorZero=int(d==0),sourceApproximate=int(variant!='zero')),[(0,z['ratio'])],'Ratio position','USD / approximate endpoint FTE'\n models=M.load_sources(ROOT/'econ22-sources');z=M.realdata(models,variant)\n if variant=='country':return dict(sourceRows=z['originalCount'],first=Q(models['housing'][0]['nominal']),last=Q(models['housing'][-1]['nominal']),percentChange=z['growth']['percentChange']),list(enumerate(z['rebased'])),'Quarter position / original calendar','Nominal housing / first=100'\n if variant=='person':return{k:z[k]for k in ['sourceUnits','beforeAvailableUnits','afterAvailableUnits','commonUnits','availableMeanChange','commonWithinChange','exactDecompositionResidual']},[(1976,z['beforeAvailableMean']),(1980,z['afterAvailableMean'])],'Observed wave','Nominal USD/hour / available mean'\n if variant=='company':return dict(sales2023=models['company']['revenue2023'],sales2024=models['company']['revenue2024'],proxy=z['ratio'],proxyGrowth=None),[(2023,models['company']['revenue2023']/1000000),(2024,models['company']['revenue2024']/1000000)],'Fiscal year','Nominal USD millions'\n raise ValueError('fixed example name required')\n\ndef svg(points,xlabel,ylabel):\n good=[(float(x),float(y))for x,y in points if y is not None]\n if not good:return None\n if any(not math.isfinite(x)or not math.isfinite(y)for x,y in good):raise ValueError('outside finite plotting range')\n w,h,L,R,T,B=640,360,90,22,28,54;xmin=min(float(p[0])for p in points);xmax=max(float(p[0])for p in points);ymin=min(y for x,y in good);ymax=max(y for x,y in good)\n pad=max(1,abs(ymin)*.05)if ymin==ymax else(ymax-ymin)*.08;ymin-=pad;ymax+=pad\n X=lambda x:(L+w-R)/2 if xmax==xmin else L+(float(x)-xmin)/(xmax-xmin)*(w-L-R);Y=lambda y:T+(ymax-float(y))/(ymax-ymin)*(h-T-B);esc=html.escape\n s=f'<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"640\" height=\"360\" viewBox=\"0 0 640 360\" role=\"img\" aria-label=\"{esc(xlabel+\"; \"+ylabel)}\"><title>{esc(xlabel+\"; \"+ylabel)}</title><rect width=\"640\" height=\"360\" fill=\"white\"/><g font-family=\"sans-serif\" font-size=\"13\" fill=\"#222\">'\n for i in range(4):\n  v=ymin+(ymax-ymin)*i/3;y=Y(v);s+=f'<line x1=\"{L}\" x2=\"{w-R}\" y1=\"{y}\" y2=\"{y}\" stroke=\"#ccd6db\"/><text x=\"{L-7}\" y=\"{y+4}\" text-anchor=\"end\">{v:.4g}</text>'\n for x,anchor in([(xmin,'middle')]if xmin==xmax else[(xmin,'start'),(xmax,'end')]):s+=f'<text x=\"{X(x)}\" y=\"{h-B+24}\" text-anchor=\"{anchor}\">{x:g}</text>'\n last=None\n for x,y in points:\n  if y is None:last=None;continue\n  a,b=X(x),Y(y)\n  if last:s+=f'<line x1=\"{last[0]}\" y1=\"{last[1]}\" x2=\"{a}\" y2=\"{b}\" stroke=\"#355c72\" stroke-width=\"2\"/>'\n  s+=f'<circle cx=\"{a}\" cy=\"{b}\" r=\"3\" fill=\"#934b34\"><title>{esc(str(x)+\": \"+str(y))}</title></circle>';last=(a,b)\n return s+f'<text x=\"{L}\" y=\"16\">{esc(ylabel)}</text><text x=\"{w-R}\" y=\"{h-6}\" text-anchor=\"end\">{esc(xlabel)}</text></g></svg>'\n\ndef run(api,variant,output):\n out=Path(output);out.mkdir(parents=True,exist_ok=True);metrics,points,x,y=example(api,variant);encoded=M.encode(metrics);(out/'summary.json').write_text(json.dumps(encoded,indent=2)+'\\n',encoding='utf8')\n M.write_csv(out/'summary.csv',[dict(metric=k,value=v)for k,v in metrics.items()]);M.write_csv(out/'plot-points.csv',[dict(x=a,y=b)for a,b in points]);graphic=svg(points,x,y)\n if graphic is not None:(out/'plot.svg').write_text(graphic,encoding='utf8')\n print(json.dumps(dict(api=api,variant=variant,metrics=encoded,plotProduced=graphic is not None),ensure_ascii=False))\n"
          }
        ],
        "inputFiles": [],
        "returnCode": 0,
        "expectedFailure": false,
        "stdout": "{\"api\": \"composition\", \"variant\": \"default\", \"metrics\": {\"beforeAvailableMean\": \"55\", \"afterAvailableMean\": \"6\", \"availableMeanChange\": \"-49\", \"commonWithinChange\": \"1\", \"commonUnits\": 1, \"exactDecompositionResidual\": \"0\"}, \"plotProduced\": true}\n",
        "stderr": "",
        "seconds": 0.125,
        "summary": {
          "beforeAvailableMean": "55",
          "afterAvailableMean": "6",
          "availableMeanChange": "-49",
          "commonWithinChange": "1",
          "commonUnits": "1",
          "exactDecompositionResidual": "0"
        },
        "plotPoints": [
          {
            "x": "0",
            "y": "55"
          },
          {
            "x": "1",
            "y": "6"
          }
        ],
        "plotFile": "econ22-fixed-results/composition-default-python/plot.svg",
        "plotSHA256": "fc116caa8e37afda70ba410a31da92b1a0afa52dc5d224ec64bcc80e5de5f4fd",
        "scope": "Actually executed fixed example. Current browser controls are calculated separately by JavaScript. Base-R outputs use finite precision; Python outputs use exact fractions.",
        "summaryFile": "econ22-fixed-results/composition-default-python/summary.csv",
        "summarySHA256": "c8aa7457ee4a067e1c7fa6eb1e31998e1d2121e0e58f67f496a71763cc734908",
        "plotPointsFile": "econ22-fixed-results/composition-default-python/plot-points.csv",
        "plotPointsSHA256": "ef2c0b5750620d817977c7c81d21cf8adfacc7352d8ac19ff5d0a496bfe951c3"
      },
      "noCommon": {
        "api": "composition",
        "variant": "noCommon",
        "language": "python",
        "codeFile": "econ22-code/composition-noCommon.py",
        "codeSHA256": "2ffcdcefaf43094922a9c09594d874623c762dedee93aed69534745ac275251e",
        "codeText": "# Fixed stated example, separate from current web controls.\nfrom pathlib import Path\nimport importlib.util,sys\nroot=Path(__file__).resolve().parents[1]\nspec=importlib.util.spec_from_file_location('fixed_support',root/'econ22-fixed-support.py')\nsupport=importlib.util.module_from_spec(spec);spec.loader.exec_module(support)\ntry:support.run('composition','noCommon',sys.argv[1]if len(sys.argv)>1 else root/'econ22-fixed-results/composition-noCommon-python')\nexcept ValueError as error:\n print('Rejected declared input: '+str(error),file=sys.stderr);sys.exit(2)\n",
        "supportFiles": [
          {
            "file": "econ22-reproduce.py",
            "sha256": "cc5631d9dfea963b64349bb28d18b69ad3caf15a15162ec6cea786a36e18de48",
            "codeText": "#!/usr/bin/env python3\n\"\"\"ECON22 public reproduction: Python standard library, exact Fraction arithmetic.\nRun: python econ22-reproduce.py --source-dir econ22-sources --output-dir econ22-python-results\nOriginal CSV inputs are read only. Output is a new chosen directory.\nThese are descriptive arithmetic and explicitly assumed examples, not causal estimates.\n\"\"\"\nfrom fractions import Fraction as Q\nfrom pathlib import Path\nfrom collections import defaultdict\nimport argparse,csv,json\n\ndef number(x):\n if x is None:raise ValueError('missing numeric token')\n return Q(str(x))\ndef rebase(values,base=0,scale='100'):\n v=[None if x is None else number(x)for x in values];s=number(scale)\n if not v or not 0<=base<len(v)or v[base]is None or v[base]<=0 or s<=0:raise ValueError('positive observed base/scale required')\n return [None if x is None else s*x/v[base]for x in v]\ndef growth(start,end,periods=1):\n a,b=number(start),number(end)\n if a<=0 or b<0 or not isinstance(periods,int)or not 1<=periods<=12:raise ValueError('growth domain')\n g=b/a;return dict(gross=g,percentChange=(g-1)*100,annualizedGross=g**periods,annualizedPercent=(g**periods-1)*100)\ndef composition(rows):\n seen=set();data=[]\n for r in rows:\n  identifier=str(r['id']);weight=number(r.get('weight','1'))\n  if identifier in seen or weight<0:raise ValueError('unique units/nonnegative fixed weights required')\n  seen.add(identifier);data.append(dict(id=identifier,weight=weight,before=None if r['before']is None else number(r['before']),after=None if r['after']is None else number(r['after'])))\n if not data:raise ValueError('nonempty frame required')\n valid=[r for r in data if r['weight']>0];b=[r for r in valid if r['before']is not None];a=[r for r in valid if r['after']is not None];c=[r for r in valid if r['before']is not None and r['after']is not None]\n def mean(rs,k):\n  mass=sum((r['weight']for r in rs),Q(0));return sum((r[k]*r['weight']for r in rs),Q(0))/mass if mass else None\n mb,ma,cb,ca=mean(b,'before'),mean(a,'after'),mean(c,'before'),mean(c,'after');full=all(x is not None for x in [mb,ma,cb,ca]);change=ma-mb if mb is not None and ma is not None else None\n return dict(sourceUnits=len(data),beforeAvailableUnits=len(b),afterAvailableUnits=len(a),commonUnits=len(c),beforeAvailableMean=mb,afterAvailableMean=ma,beforeCommonMean=cb,afterCommonMean=ca,availableMeanChange=change,commonWithinChange=ca-cb if full else None,afterFrameShift=ma-ca if full else None,beforeFrameShift=cb-mb if full else None,exactDecompositionResidual=change-((ma-ca)+(ca-cb)+(cb-mb))if full else None)\ndef productivity(output0,output1,hours0,hours1):\n o0,o1,h0,h1=map(number,[output0,output1,hours0,hours1])\n if min(o0,o1,h0,h1)<=0:raise ValueError('positive output and hours required')\n go,gh=o1/o0,h1/h0;gp=go/gh\n return dict(outputGross=go,hoursGross=gh,productivityGross=gp,outputPercent=(go-1)*100,hoursPercent=(gh-1)*100,productivityPercent=(gp-1)*100,differenceOfPercentGrowths=(go-gh)*100,exactGrowthIdentityResidual=gp-go/gh)\ndef measurement(numerator,denominator,lower=None,upper=None):\n n,d=number(numerator),number(denominator)\n if d<0:raise ValueError('nonnegative denominator required')\n interval=None\n if lower is not None or upper is not None:\n  lo,hi=number(lower),number(upper)\n  if lo<=0 or hi<lo:raise ValueError('ordered positive scenario bounds')\n  interval=sorted([n/lo,n/hi])\n return dict(ratio=n/d if d else None,denominatorScenarioInterval=interval)\ndef read_csv(folder,name):\n with (folder/name).open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))\ndef load_sources(folder):\n h=read_csv(folder,'actual180-KOR-housing-nominal-real-indexes.csv');b=read_csv(folder,'actual38-US-nonfarm-output-hours-productivity-indexes.csv');p=read_csv(folder,'actual10839-person-wage-panel-original-and-prior-derived-fields.csv');c=read_csv(folder,'actual3-Apple-revenue-and-approximate-periodend-FTE-facts.csv')\n company={}\n for r in c:\n  value=Q(r['originalToken'].replace(',',''))\n  company[('revenue'+r['fiscalYear'])if r['fact']=='consolidated total net sales'else'endpointFTE2024']=value*1000000 if r['fact']=='consolidated total net sales'else value\n return dict(housing=h,bls=b,person=p,company=company)\ndef person_comparison(models,before=1976,after=1980):\n if before not in [1976,1978,1980]or after not in [1976,1978,1980]or before>=after:raise ValueError('ordered observed waves required')\n units=defaultdict(dict)\n for r in models['person']:\n  year=int(r['time'])\n  if year in units[r['unit']]:raise ValueError('duplicate original unit-wave')\n  token=r['wageCentsOriginal'];units[r['unit']][year]=None if token in ['.','','NA']else number(token)/100\n return composition([dict(id=k,before=v[before],after=v[after])for k,v in units.items()])\ndef realdata(models,kind):\n if kind=='country':\n  rows=models['housing'];return dict(originalCount=len(rows),growth=growth(rows[0]['nominal'],rows[-1]['nominal']),rebased=rebase([r['nominal']for r in rows]))\n if kind=='person':return person_comparison(models)\n if kind=='company':\n  c=models['company'];return dict(revenueGrowth=growth(c['revenue2023'],c['revenue2024']),ratio=measurement(c['revenue2024'],c['endpointFTE2024'])['ratio'],proxyGrowth=None)\n raise ValueError('actual case required')\ndef encode(v):\n if isinstance(v,Q):return str(v)\n if isinstance(v,dict):return{k:encode(x)for k,x in v.items()}\n if isinstance(v,(list,tuple)):return[encode(x)for x in v]\n return v\ndef write_csv(path,rows):\n with path.open('w',encoding='utf8',newline='')as f:\n  writer=csv.DictWriter(f,fieldnames=list(rows[0]));writer.writeheader();writer.writerows([{k:''if v is None else str(v)for k,v in r.items()}for r in rows])\ndef full_source(folder,out):\n out.mkdir(parents=True,exist_ok=True);models=load_sources(folder);metrics={};country=[];frames=[]\n for source in ['housing','bls']:\n  data=models[source];columns=['nominal','real']if source=='housing'else['outputIndexOriginalToken','hoursIndexOriginalToken','productivityIndexOriginalToken']\n  for col in columns:\n   values=[r[col]for r in data];rb=rebase(values);g=growth(values[0],values[-1])\n   for k,v in g.items():metrics[source+':'+col+':'+k]=v\n   quarter_base=next((i for i,r in enumerate(data)if r['quarter']=='2010-Q1'),None)if source=='housing'else None\n   qb=rebase(values,quarter_base)if quarter_base is not None else[None]*len(values)\n   country.extend(dict(source=source,series=col,row=i+1,quarter=r['quarter'],originalToken=r[col],rebasedFirst100Exact=rb[i],rebased2010Q1Exact=qb[i])for i,r in enumerate(data))\n for a,b in [(1976,1978),(1978,1980),(1976,1980)]:\n  z=person_comparison(models,a,b);frames.append(dict(before=a,after=b,elapsedYears=b-a,**z));metrics.update({f'person:{a}:{b}:{k}':v for k,v in z.items()})\n c=realdata(models,'company');metrics['company:proxy']=c['ratio'];metrics['company:proxyGrowth']=None;metrics.update({'company:sales:'+k:v for k,v in c['revenueGrowth'].items()})\n changes=[]\n for a,b in zip(models['bls'],models['bls'][1:]):\n  z=productivity(a['outputIndexOriginalToken'],b['outputIndexOriginalToken'],a['hoursIndexOriginalToken'],b['hoursIndexOriginalToken']);g=growth(a['productivityIndexOriginalToken'],b['productivityIndexOriginalToken'],4)\n  changes.append(dict(start=a['quarter'],end=b['quarter'],**z,publishedProductivityPercent=g['percentChange'],publishedAnnualizedPercent=g['annualizedPercent']))\n selected=list(dict.fromkeys(r['unit']for r in models['person']))[:12]\n trajectories=[dict(unit=r['unit'],year=r['time'],nominalUSDPerHourExact=None if r['wageCentsOriginal']in['.','','NA']else number(r['wageCentsOriginal'])/100)for r in models['person']if r['unit']in selected]\n write_csv(out/'metrics.csv',[dict(metric=k,value=v)for k,v in metrics.items()]);write_csv(out/'country-indexes.csv',country);write_csv(out/'wage-frames.csv',frames);write_csv(out/'bls-changes.csv',changes);write_csv(out/'first12-trajectories.csv',trajectories)\n (out/'full-results.json').write_text(json.dumps(encode(dict(metrics=metrics,frames=frames,company=c)),ensure_ascii=False,indent=2)+'\\n',encoding='utf8');return{f.name:len(read_csv(out,f.name))for f in out.glob('*.csv')}\nif __name__=='__main__':\n parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--source-dir',type=Path,default=Path(__file__).parent/'econ22-sources');parser.add_argument('--output-dir',type=Path,default=Path(__file__).parent/'econ22-python-results');args=parser.parse_args();print(json.dumps(full_source(args.source_dir,args.output_dir)))\n"
          },
          {
            "file": "econ22-fixed-support.py",
            "sha256": "deb4273c9c713e16c2f5e5d3525932ae34753f348731a3b26a4babff015c2fd6",
            "codeText": "\"\"\"Public fixed-example support. Requires only Python standard library and econ22-reproduce.py.\nFixed examples are separate from current browser inputs. Missing values remain None.\n\"\"\"\nfrom pathlib import Path\nfrom fractions import Fraction as Q\nimport importlib.util,json,csv,html,math\nROOT=Path(__file__).resolve().parent\nspec=importlib.util.spec_from_file_location('econ22_public',ROOT/'econ22-reproduce.py');M=importlib.util.module_from_spec(spec);spec.loader.exec_module(M)\n\ndef example(api,variant):\n if api=='rebase':\n  values=[0,1]if variant=='invalid'else[80,None,120]if variant=='gap'else[80,100,120];z=M.rebase(values);return dict(rows=len(z),defined=sum(x is not None for x in z),last=z[-1]),list(enumerate(z)),'Position','Rebased index'\n if api=='growth':\n  end=90 if variant=='quarterly'else 120;z=M.growth(100,end,4 if variant=='quarterly'else 1);return z,[(0,Q(100)),(1,Q(end))],'Date','Supplied level'\n if api=='composition':\n  rows=[dict(id='A',before=10,after=None),dict(id='B',before=None,after=20)]if variant=='noCommon'else[dict(id='A',before=10,after=11),dict(id='B',before=100,after=None),dict(id='C',before=None,after=1)];z=M.composition(rows);metrics={k:z[k]for k in ['beforeAvailableMean','afterAvailableMean','availableMeanChange','commonWithinChange','commonUnits','exactDecompositionResidual']};return metrics,[(0,z['beforeAvailableMean']),(1,z['afterAvailableMean'])],'Date','Available mean / assumed units'\n if api=='productivity':\n  o,h=(90,80)if variant=='contraction'else(103,101);z=M.productivity(100,o,100,h);return z,[(0,Q(1)),(1,z['productivityGross'])],'Date','Output per hour / initial=1'\n if api=='measurement':\n  n,d=(0,0)if variant=='zero'else(391035000000,164000);z=M.measurement(n,d);return dict(ratio=z['ratio'],denominatorZero=int(d==0),sourceApproximate=int(variant!='zero')),[(0,z['ratio'])],'Ratio position','USD / approximate endpoint FTE'\n models=M.load_sources(ROOT/'econ22-sources');z=M.realdata(models,variant)\n if variant=='country':return dict(sourceRows=z['originalCount'],first=Q(models['housing'][0]['nominal']),last=Q(models['housing'][-1]['nominal']),percentChange=z['growth']['percentChange']),list(enumerate(z['rebased'])),'Quarter position / original calendar','Nominal housing / first=100'\n if variant=='person':return{k:z[k]for k in ['sourceUnits','beforeAvailableUnits','afterAvailableUnits','commonUnits','availableMeanChange','commonWithinChange','exactDecompositionResidual']},[(1976,z['beforeAvailableMean']),(1980,z['afterAvailableMean'])],'Observed wave','Nominal USD/hour / available mean'\n if variant=='company':return dict(sales2023=models['company']['revenue2023'],sales2024=models['company']['revenue2024'],proxy=z['ratio'],proxyGrowth=None),[(2023,models['company']['revenue2023']/1000000),(2024,models['company']['revenue2024']/1000000)],'Fiscal year','Nominal USD millions'\n raise ValueError('fixed example name required')\n\ndef svg(points,xlabel,ylabel):\n good=[(float(x),float(y))for x,y in points if y is not None]\n if not good:return None\n if any(not math.isfinite(x)or not math.isfinite(y)for x,y in good):raise ValueError('outside finite plotting range')\n w,h,L,R,T,B=640,360,90,22,28,54;xmin=min(float(p[0])for p in points);xmax=max(float(p[0])for p in points);ymin=min(y for x,y in good);ymax=max(y for x,y in good)\n pad=max(1,abs(ymin)*.05)if ymin==ymax else(ymax-ymin)*.08;ymin-=pad;ymax+=pad\n X=lambda x:(L+w-R)/2 if xmax==xmin else L+(float(x)-xmin)/(xmax-xmin)*(w-L-R);Y=lambda y:T+(ymax-float(y))/(ymax-ymin)*(h-T-B);esc=html.escape\n s=f'<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"640\" height=\"360\" viewBox=\"0 0 640 360\" role=\"img\" aria-label=\"{esc(xlabel+\"; \"+ylabel)}\"><title>{esc(xlabel+\"; \"+ylabel)}</title><rect width=\"640\" height=\"360\" fill=\"white\"/><g font-family=\"sans-serif\" font-size=\"13\" fill=\"#222\">'\n for i in range(4):\n  v=ymin+(ymax-ymin)*i/3;y=Y(v);s+=f'<line x1=\"{L}\" x2=\"{w-R}\" y1=\"{y}\" y2=\"{y}\" stroke=\"#ccd6db\"/><text x=\"{L-7}\" y=\"{y+4}\" text-anchor=\"end\">{v:.4g}</text>'\n for x,anchor in([(xmin,'middle')]if xmin==xmax else[(xmin,'start'),(xmax,'end')]):s+=f'<text x=\"{X(x)}\" y=\"{h-B+24}\" text-anchor=\"{anchor}\">{x:g}</text>'\n last=None\n for x,y in points:\n  if y is None:last=None;continue\n  a,b=X(x),Y(y)\n  if last:s+=f'<line x1=\"{last[0]}\" y1=\"{last[1]}\" x2=\"{a}\" y2=\"{b}\" stroke=\"#355c72\" stroke-width=\"2\"/>'\n  s+=f'<circle cx=\"{a}\" cy=\"{b}\" r=\"3\" fill=\"#934b34\"><title>{esc(str(x)+\": \"+str(y))}</title></circle>';last=(a,b)\n return s+f'<text x=\"{L}\" y=\"16\">{esc(ylabel)}</text><text x=\"{w-R}\" y=\"{h-6}\" text-anchor=\"end\">{esc(xlabel)}</text></g></svg>'\n\ndef run(api,variant,output):\n out=Path(output);out.mkdir(parents=True,exist_ok=True);metrics,points,x,y=example(api,variant);encoded=M.encode(metrics);(out/'summary.json').write_text(json.dumps(encoded,indent=2)+'\\n',encoding='utf8')\n M.write_csv(out/'summary.csv',[dict(metric=k,value=v)for k,v in metrics.items()]);M.write_csv(out/'plot-points.csv',[dict(x=a,y=b)for a,b in points]);graphic=svg(points,x,y)\n if graphic is not None:(out/'plot.svg').write_text(graphic,encoding='utf8')\n print(json.dumps(dict(api=api,variant=variant,metrics=encoded,plotProduced=graphic is not None),ensure_ascii=False))\n"
          }
        ],
        "inputFiles": [],
        "returnCode": 0,
        "expectedFailure": false,
        "stdout": "{\"api\": \"composition\", \"variant\": \"noCommon\", \"metrics\": {\"beforeAvailableMean\": \"10\", \"afterAvailableMean\": \"20\", \"availableMeanChange\": \"10\", \"commonWithinChange\": null, \"commonUnits\": 0, \"exactDecompositionResidual\": null}, \"plotProduced\": true}\n",
        "stderr": "",
        "seconds": 0.125,
        "summary": {
          "beforeAvailableMean": "10",
          "afterAvailableMean": "20",
          "availableMeanChange": "10",
          "commonWithinChange": null,
          "commonUnits": "0",
          "exactDecompositionResidual": null
        },
        "plotPoints": [
          {
            "x": "0",
            "y": "10"
          },
          {
            "x": "1",
            "y": "20"
          }
        ],
        "plotFile": "econ22-fixed-results/composition-noCommon-python/plot.svg",
        "plotSHA256": "0b944266fc67b005e6b94452e4b94a015e89a41f6757429a7f787aa305f2bd1a",
        "scope": "Actually executed fixed example. Current browser controls are calculated separately by JavaScript. Base-R outputs use finite precision; Python outputs use exact fractions.",
        "summaryFile": "econ22-fixed-results/composition-noCommon-python/summary.csv",
        "summarySHA256": "9e06e91ea032644e38de04b3e3a279cf808bd6f38151f8d76080580cea3f8be8",
        "plotPointsFile": "econ22-fixed-results/composition-noCommon-python/plot-points.csv",
        "plotPointsSHA256": "b6b7a3194b6ff6823b1e2e06a5a97b80be05dbba80c653935726767775a17fc7"
      }
    },
    "r": {
      "default": {
        "api": "composition",
        "variant": "default",
        "language": "r",
        "codeFile": "econ22-code/composition-default.R",
        "codeSHA256": "a1371840ec0e4c1e3c4d26e21f87b32da196d3fb356ce2403563dc8f965dc662",
        "codeText": "# Run from the extracted textbook bundle root.\nsource('econ22-fixed-support.R',encoding='UTF-8')\noptions(digits=17)\nargs<-commandArgs(trailingOnly=TRUE)\noutput<-if(length(args))args[1]else'econ22-fixed-results/composition-default-r'\ntryCatch(run('composition','default',output),error=function(error){cat('Rejected declared input: ',conditionMessage(error),'\\n',file=stderr());quit(status=2)})\n",
        "supportFiles": [
          {
            "file": "econ22-reproduce.R",
            "sha256": "2db22759696a6f288479189f44026f265536a54cdc2e72952c1e91af13661480",
            "codeText": "# ECON22 independent public base-R reproduction; binary64 approximations.\n# Run: Rscript --vanilla --encoding=UTF-8 econ22-reproduce.R [source-dir] [output-dir]\n# Source CSVs are never overwritten. No packages or network required.\nrebase <- function(values, base=1L, scale=100) {\n  if (length(base)!=1L || !is.finite(base) || base!=as.integer(base) || !length(values) || base<1 || base>length(values) || is.na(values[base]) || values[base]<=0 || !is.finite(scale) || scale<=0) stop('positive observed base/scale required')\n  scale*values/values[base]\n}\ngrowth <- function(start,end,periods=1L) {\n  if (start<=0 || end<0 || periods<1 || periods>12 || periods!=as.integer(periods)) stop('growth domain')\n  gross<-end/start;list(gross=gross,percentChange=(gross-1)*100,annualizedGross=gross^periods,annualizedPercent=(gross^periods-1)*100)\n}\ncomposition <- function(rows) {\n  if (!nrow(rows) || anyDuplicated(rows$id)) stop('nonempty unique units required')\n  if (!'weight'%in%names(rows)) rows$weight<-rep(1,nrow(rows))\n  if (any(!is.finite(rows$weight)) || any(rows$weight<0)) stop('nonnegative fixed weights required')\n  valid<-rows$weight>0;b<-valid&!is.na(rows$before);a<-valid&!is.na(rows$after);common<-b&a\n  avg<-function(mask,column)if(sum(rows$weight[mask])>0)sum(rows[[column]][mask]*rows$weight[mask])/sum(rows$weight[mask])else NA_real_\n  mb<-avg(b,'before');ma<-avg(a,'after');cb<-avg(common,'before');ca<-avg(common,'after');full<-all(is.finite(c(mb,ma,cb,ca)))\n  list(sourceUnits=nrow(rows),beforeAvailableUnits=sum(b),afterAvailableUnits=sum(a),commonUnits=sum(common),beforeAvailableMean=mb,afterAvailableMean=ma,beforeCommonMean=cb,afterCommonMean=ca,availableMeanChange=ma-mb,commonWithinChange=if(full)ca-cb else NA_real_,afterFrameShift=if(full)ma-ca else NA_real_,beforeFrameShift=if(full)cb-mb else NA_real_,exactDecompositionResidual=if(full)(ma-mb)-((ma-ca)+(ca-cb)+(cb-mb))else NA_real_)\n}\nproductivity <- function(output0,output1,hours0,hours1) {\n  if(any(c(output0,output1,hours0,hours1)<=0))stop('positive output and hours required')\n  go<-output1/output0;gh<-hours1/hours0;gp<-go/gh\n  list(outputGross=go,hoursGross=gh,productivityGross=gp,outputPercent=(go-1)*100,hoursPercent=(gh-1)*100,productivityPercent=(gp-1)*100,differenceOfPercentGrowths=(go-gh)*100,exactGrowthIdentityResidual=gp-go/gh)\n}\nmeasurement <- function(numerator,denominator,lower=NA_real_,upper=NA_real_) {\n  if(denominator<0)stop('nonnegative denominator required');interval<-NULL\n  if(!is.na(lower)||!is.na(upper)){if(any(!is.finite(c(lower,upper)))||lower<=0||upper<lower)stop('ordered positive scenario bounds');interval<-sort(c(numerator/lower,numerator/upper))}\n  list(ratio=if(denominator>0)numerator/denominator else NA_real_,denominatorScenarioInterval=interval)\n}\nload_sources <- function(folder) {\n  read<-function(file)read.csv(file.path(folder,file),stringsAsFactors=FALSE,check.names=FALSE,colClasses='character',na.strings=c('NA','','.'))\n  h<-read('actual180-KOR-housing-nominal-real-indexes.csv');b<-read('actual38-US-nonfarm-output-hours-productivity-indexes.csv');p<-read('actual10839-person-wage-panel-original-and-prior-derived-fields.csv');c<-read('actual3-Apple-revenue-and-approximate-periodend-FTE-facts.csv')\n  company<-list();for(i in seq_len(nrow(c))){value<-as.numeric(gsub(',','',c$originalToken[i],fixed=TRUE));if(c$fact[i]=='consolidated total net sales')company[[paste0('revenue',c$fiscalYear[i])]]<-value*1e6 else company$endpointFTE2024<-value}\n  list(housing=h,bls=b,person=p,company=company)\n}\nperson_comparison <- function(models,before=1976L,after=1980L) {\n  if(!before%in%c(1976,1978,1980)||!after%in%c(1976,1978,1980)||before>=after)stop('ordered observed waves required')\n  p<-models$person;if(anyDuplicated(paste(p$unit,p$time,sep=':')))stop('duplicate original unit-wave')\n  ids<-unique(p$unit);rows<-data.frame(id=ids,before=as.numeric(p$wageCentsOriginal[match(paste(ids,before),paste(p$unit,p$time))])/100,after=as.numeric(p$wageCentsOriginal[match(paste(ids,after),paste(p$unit,p$time))])/100,stringsAsFactors=FALSE)\n  composition(rows)\n}\nrealdata <- function(models,kind) {\n  if(kind=='country'){r<-models$housing;return(list(originalCount=nrow(r),growth=growth(as.numeric(r$nominal[1]),as.numeric(tail(r$nominal,1))),rebased=rebase(as.numeric(r$nominal))))}\n  if(kind=='person')return(person_comparison(models))\n  if(kind=='company'){c<-models$company;return(list(revenueGrowth=growth(c$revenue2023,c$revenue2024),ratio=measurement(c$revenue2024,c$endpointFTE2024)$ratio,proxyGrowth=NA_real_))}\n  stop('actual case required')\n}\nfull_source <- function(folder,out) {\n  dir.create(out,recursive=TRUE,showWarnings=FALSE);models<-load_sources(folder);metrics<-list();country<-list();frames<-list()\n  for(source in c('housing','bls')){data<-models[[source]];columns<-if(source=='housing')c('nominal','real')else c('outputIndexOriginalToken','hoursIndexOriginalToken','productivityIndexOriginalToken')\n    for(col in columns){values<-as.numeric(data[[col]]);rb<-rebase(values);g<-growth(values[1],tail(values,1));for(k in names(g))metrics[[paste(source,col,k,sep=':')]]<-g[[k]];quarterBase<-if(source=='housing')match('2010-Q1',data$quarter)else NA_integer_;qb<-if(!is.na(quarterBase))rebase(values,quarterBase)else rep(NA_real_,length(values));country[[length(country)+1]]<-data.frame(source=source,series=col,row=seq_len(nrow(data)),quarter=data$quarter,originalToken=data[[col]],rebasedFirst100Exact=rb,rebased2010Q1Exact=qb,stringsAsFactors=FALSE)}}\n  for(pair in list(c(1976,1978),c(1978,1980),c(1976,1980))){a<-pair[1];b<-pair[2];z<-person_comparison(models,a,b);frames[[length(frames)+1]]<-as.data.frame(c(list(before=a,after=b,elapsedYears=b-a),z),stringsAsFactors=FALSE);for(k in names(z))metrics[[paste('person',a,b,k,sep=':')]]<-z[[k]]}\n  company<-realdata(models,'company');metrics[['company:proxy']]<-company$ratio;metrics[['company:proxyGrowth']]<-NA_real_;for(k in names(company$revenueGrowth))metrics[[paste('company:sales',k,sep=':')]]<-company$revenueGrowth[[k]]\n  changes<-list();b<-models$bls\n  for(i in seq_len(nrow(b)-1L)){z<-productivity(as.numeric(b$outputIndexOriginalToken[i]),as.numeric(b$outputIndexOriginalToken[i+1]),as.numeric(b$hoursIndexOriginalToken[i]),as.numeric(b$hoursIndexOriginalToken[i+1]));g<-growth(as.numeric(b$productivityIndexOriginalToken[i]),as.numeric(b$productivityIndexOriginalToken[i+1]),4);changes[[i]]<-as.data.frame(c(list(start=b$quarter[i],end=b$quarter[i+1]),z,list(publishedProductivityPercent=g$percentChange,publishedAnnualizedPercent=g$annualizedPercent)),stringsAsFactors=FALSE)}\n  write<-function(name,rows)write.csv(rows,file.path(out,name),row.names=FALSE,na='',fileEncoding='UTF-8')\n  selected<-head(unique(models$person$unit),12);p<-models$person[models$person$unit%in%selected,];trajectories<-data.frame(unit=p$unit,year=p$time,nominalUSDPerHourExact=as.numeric(p$wageCentsOriginal)/100,stringsAsFactors=FALSE)\n  write('metrics.csv',data.frame(metric=names(metrics),value=as.numeric(unlist(metrics))));write('country-indexes.csv',do.call(rbind,country));write('wage-frames.csv',do.call(rbind,frames));write('bls-changes.csv',do.call(rbind,changes));write('first12-trajectories.csv',trajectories);invisible(metrics)\n}\nif(sys.nframe()==0L){args<-commandArgs(trailingOnly=TRUE);folder<-if(length(args)>=1)args[1]else'econ22-sources';out<-if(length(args)>=2)args[2]else'econ22-r-results';options(digits=17);metrics<-full_source(folder,out);cat('metrics:',length(metrics),'\\noutput directory:',out,'\\n')}\n"
          },
          {
            "file": "econ22-fixed-support.R",
            "sha256": "d4d63e1ad02017f20884b5932458dbde6013e0c2e560a4a9922a13d080a59fa1",
            "codeText": "# Run fixed drivers from the extracted bundle root. No packages or network required.\nsource('econ22-reproduce.R',encoding='UTF-8')\nexample <- function(api,variant) {\n  if(api=='rebase'){v<-if(variant=='invalid')c(0,1)else if(variant=='gap')c(80,NA,120)else c(80,100,120);z<-rebase(v);return(list(metrics=list(rows=length(z),defined=sum(!is.na(z)),last=tail(z,1)),x=seq_along(z)-1,y=z,xlabel='Position',ylabel='Rebased index'))}\n  if(api=='growth'){end<-if(variant=='quarterly')90 else 120;z<-growth(100,end,if(variant=='quarterly')4 else 1);return(list(metrics=z,x=c(0,1),y=c(100,end),xlabel='Date',ylabel='Supplied level'))}\n  if(api=='composition'){rows<-if(variant=='noCommon')data.frame(id=c('A','B'),before=c(10,NA),after=c(NA,20))else data.frame(id=c('A','B','C'),before=c(10,100,NA),after=c(11,NA,1));z<-composition(rows);metrics<-z[c('beforeAvailableMean','afterAvailableMean','availableMeanChange','commonWithinChange','commonUnits','exactDecompositionResidual')];return(list(metrics=metrics,x=c(0,1),y=c(z$beforeAvailableMean,z$afterAvailableMean),xlabel='Date',ylabel='Available mean / assumed units'))}\n  if(api=='productivity'){o<-if(variant=='contraction')90 else 103;h<-if(variant=='contraction')80 else 101;z<-productivity(100,o,100,h);return(list(metrics=z,x=c(0,1),y=c(1,z$productivityGross),xlabel='Date',ylabel='Output per hour / initial=1'))}\n  if(api=='measurement'){n<-if(variant=='zero')0 else 391035000000;d<-if(variant=='zero')0 else 164000;z<-measurement(n,d);return(list(metrics=list(ratio=z$ratio,denominatorZero=as.integer(d==0),sourceApproximate=as.integer(variant!='zero')),x=0,y=z$ratio,xlabel='Ratio position',ylabel='USD / approximate endpoint FTE'))}\n  models<-load_sources('econ22-sources');z<-realdata(models,variant)\n  if(variant=='country')return(list(metrics=list(sourceRows=z$originalCount,first=as.numeric(head(models$housing$nominal,1)),last=as.numeric(tail(models$housing$nominal,1)),percentChange=z$growth$percentChange),x=seq_along(z$rebased)-1,y=z$rebased,xlabel='Quarter position / original calendar',ylabel='Nominal housing / first=100'))\n  if(variant=='person')return(list(metrics=z[c('sourceUnits','beforeAvailableUnits','afterAvailableUnits','commonUnits','availableMeanChange','commonWithinChange','exactDecompositionResidual')],x=c(1976,1980),y=c(z$beforeAvailableMean,z$afterAvailableMean),xlabel='Observed wave',ylabel='Nominal USD/hour / available mean'))\n  if(variant=='company')return(list(metrics=list(sales2023=models$company$revenue2023,sales2024=models$company$revenue2024,proxy=z$ratio,proxyGrowth=NA_real_),x=c(2023,2024),y=c(models$company$revenue2023,models$company$revenue2024)/1e6,xlabel='Fiscal year',ylabel='Nominal USD millions'))\n  stop('fixed example name required')\n}\nrun <- function(api,variant,output) {\n  dir.create(output,recursive=TRUE,showWarnings=FALSE);z<-example(api,variant);metrics<-data.frame(metric=names(z$metrics),value=as.numeric(unlist(z$metrics)),stringsAsFactors=FALSE)\n  write.csv(metrics,file.path(output,'summary.csv'),row.names=FALSE,na='',fileEncoding='UTF-8');write.csv(data.frame(x=z$x,y=z$y),file.path(output,'plot-points.csv'),row.names=FALSE,na='',fileEncoding='UTF-8');print(metrics,row.names=FALSE)\n  good<-is.finite(z$x)&is.finite(z$y)\n  if(any(good)){svg(file.path(output,'plot.svg'),width=640/96,height=360/96,pointsize=10);par(mar=c(4.5,5.8,2,1));plot(z$x,z$y,type='o',pch=16,cex=.7,col='#355c72',xlab=z$xlabel,ylab=z$ylabel,cex.axis=.85,cex.lab=.9);grid(col='#d5dde1');dev.off();cat('plotProduced: TRUE\\n')}else cat('plotProduced: FALSE; undefined values retained\\n')\n}\n"
          }
        ],
        "inputFiles": [],
        "returnCode": 0,
        "expectedFailure": false,
        "stdout": "                     metric value\n        beforeAvailableMean    55\n         afterAvailableMean     6\n        availableMeanChange   -49\n         commonWithinChange     1\n                commonUnits     1\n exactDecompositionResidual     0\nplotProduced: TRUE\n",
        "stderr": "During startup - Warning messages:\n1: Setting LC_COLLATE=C.UTF-8 failed \n2: Setting LC_CTYPE=C.UTF-8 failed \n3: Setting LC_MONETARY=C.UTF-8 failed \n4: Setting LC_TIME=C.UTF-8 failed \n",
        "seconds": 0.28200000000651926,
        "summary": {
          "beforeAvailableMean": "55",
          "afterAvailableMean": "6",
          "availableMeanChange": "-49",
          "commonWithinChange": "1",
          "commonUnits": "1",
          "exactDecompositionResidual": "0"
        },
        "plotPoints": [
          {
            "x": "0",
            "y": "55"
          },
          {
            "x": "1",
            "y": "6"
          }
        ],
        "plotFile": "econ22-fixed-results/composition-default-r/plot.svg",
        "plotSHA256": "7d7b80c94e0b409391d798ea800580f6eccbbc05662b90f0a18fde43438f2faf",
        "scope": "Actually executed fixed example. Current browser controls are calculated separately by JavaScript. Base-R outputs use finite precision; Python outputs use exact fractions.",
        "summaryFile": "econ22-fixed-results/composition-default-r/summary.csv",
        "summarySHA256": "01bb5d522d22588885f428f8e3d91878bee2b3079d203966de0618905d943bfd",
        "plotPointsFile": "econ22-fixed-results/composition-default-r/plot-points.csv",
        "plotPointsSHA256": "0939c2b38f3d37fabed313fd15edb5c58497b68e41efa75c71387f2f92f223fa"
      },
      "noCommon": {
        "api": "composition",
        "variant": "noCommon",
        "language": "r",
        "codeFile": "econ22-code/composition-noCommon.R",
        "codeSHA256": "fdfc68428705617193d08c5320a187e9563bbd83516f30ee666b4e9b025cb991",
        "codeText": "# Run from the extracted textbook bundle root.\nsource('econ22-fixed-support.R',encoding='UTF-8')\noptions(digits=17)\nargs<-commandArgs(trailingOnly=TRUE)\noutput<-if(length(args))args[1]else'econ22-fixed-results/composition-noCommon-r'\ntryCatch(run('composition','noCommon',output),error=function(error){cat('Rejected declared input: ',conditionMessage(error),'\\n',file=stderr());quit(status=2)})\n",
        "supportFiles": [
          {
            "file": "econ22-reproduce.R",
            "sha256": "2db22759696a6f288479189f44026f265536a54cdc2e72952c1e91af13661480",
            "codeText": "# ECON22 independent public base-R reproduction; binary64 approximations.\n# Run: Rscript --vanilla --encoding=UTF-8 econ22-reproduce.R [source-dir] [output-dir]\n# Source CSVs are never overwritten. No packages or network required.\nrebase <- function(values, base=1L, scale=100) {\n  if (length(base)!=1L || !is.finite(base) || base!=as.integer(base) || !length(values) || base<1 || base>length(values) || is.na(values[base]) || values[base]<=0 || !is.finite(scale) || scale<=0) stop('positive observed base/scale required')\n  scale*values/values[base]\n}\ngrowth <- function(start,end,periods=1L) {\n  if (start<=0 || end<0 || periods<1 || periods>12 || periods!=as.integer(periods)) stop('growth domain')\n  gross<-end/start;list(gross=gross,percentChange=(gross-1)*100,annualizedGross=gross^periods,annualizedPercent=(gross^periods-1)*100)\n}\ncomposition <- function(rows) {\n  if (!nrow(rows) || anyDuplicated(rows$id)) stop('nonempty unique units required')\n  if (!'weight'%in%names(rows)) rows$weight<-rep(1,nrow(rows))\n  if (any(!is.finite(rows$weight)) || any(rows$weight<0)) stop('nonnegative fixed weights required')\n  valid<-rows$weight>0;b<-valid&!is.na(rows$before);a<-valid&!is.na(rows$after);common<-b&a\n  avg<-function(mask,column)if(sum(rows$weight[mask])>0)sum(rows[[column]][mask]*rows$weight[mask])/sum(rows$weight[mask])else NA_real_\n  mb<-avg(b,'before');ma<-avg(a,'after');cb<-avg(common,'before');ca<-avg(common,'after');full<-all(is.finite(c(mb,ma,cb,ca)))\n  list(sourceUnits=nrow(rows),beforeAvailableUnits=sum(b),afterAvailableUnits=sum(a),commonUnits=sum(common),beforeAvailableMean=mb,afterAvailableMean=ma,beforeCommonMean=cb,afterCommonMean=ca,availableMeanChange=ma-mb,commonWithinChange=if(full)ca-cb else NA_real_,afterFrameShift=if(full)ma-ca else NA_real_,beforeFrameShift=if(full)cb-mb else NA_real_,exactDecompositionResidual=if(full)(ma-mb)-((ma-ca)+(ca-cb)+(cb-mb))else NA_real_)\n}\nproductivity <- function(output0,output1,hours0,hours1) {\n  if(any(c(output0,output1,hours0,hours1)<=0))stop('positive output and hours required')\n  go<-output1/output0;gh<-hours1/hours0;gp<-go/gh\n  list(outputGross=go,hoursGross=gh,productivityGross=gp,outputPercent=(go-1)*100,hoursPercent=(gh-1)*100,productivityPercent=(gp-1)*100,differenceOfPercentGrowths=(go-gh)*100,exactGrowthIdentityResidual=gp-go/gh)\n}\nmeasurement <- function(numerator,denominator,lower=NA_real_,upper=NA_real_) {\n  if(denominator<0)stop('nonnegative denominator required');interval<-NULL\n  if(!is.na(lower)||!is.na(upper)){if(any(!is.finite(c(lower,upper)))||lower<=0||upper<lower)stop('ordered positive scenario bounds');interval<-sort(c(numerator/lower,numerator/upper))}\n  list(ratio=if(denominator>0)numerator/denominator else NA_real_,denominatorScenarioInterval=interval)\n}\nload_sources <- function(folder) {\n  read<-function(file)read.csv(file.path(folder,file),stringsAsFactors=FALSE,check.names=FALSE,colClasses='character',na.strings=c('NA','','.'))\n  h<-read('actual180-KOR-housing-nominal-real-indexes.csv');b<-read('actual38-US-nonfarm-output-hours-productivity-indexes.csv');p<-read('actual10839-person-wage-panel-original-and-prior-derived-fields.csv');c<-read('actual3-Apple-revenue-and-approximate-periodend-FTE-facts.csv')\n  company<-list();for(i in seq_len(nrow(c))){value<-as.numeric(gsub(',','',c$originalToken[i],fixed=TRUE));if(c$fact[i]=='consolidated total net sales')company[[paste0('revenue',c$fiscalYear[i])]]<-value*1e6 else company$endpointFTE2024<-value}\n  list(housing=h,bls=b,person=p,company=company)\n}\nperson_comparison <- function(models,before=1976L,after=1980L) {\n  if(!before%in%c(1976,1978,1980)||!after%in%c(1976,1978,1980)||before>=after)stop('ordered observed waves required')\n  p<-models$person;if(anyDuplicated(paste(p$unit,p$time,sep=':')))stop('duplicate original unit-wave')\n  ids<-unique(p$unit);rows<-data.frame(id=ids,before=as.numeric(p$wageCentsOriginal[match(paste(ids,before),paste(p$unit,p$time))])/100,after=as.numeric(p$wageCentsOriginal[match(paste(ids,after),paste(p$unit,p$time))])/100,stringsAsFactors=FALSE)\n  composition(rows)\n}\nrealdata <- function(models,kind) {\n  if(kind=='country'){r<-models$housing;return(list(originalCount=nrow(r),growth=growth(as.numeric(r$nominal[1]),as.numeric(tail(r$nominal,1))),rebased=rebase(as.numeric(r$nominal))))}\n  if(kind=='person')return(person_comparison(models))\n  if(kind=='company'){c<-models$company;return(list(revenueGrowth=growth(c$revenue2023,c$revenue2024),ratio=measurement(c$revenue2024,c$endpointFTE2024)$ratio,proxyGrowth=NA_real_))}\n  stop('actual case required')\n}\nfull_source <- function(folder,out) {\n  dir.create(out,recursive=TRUE,showWarnings=FALSE);models<-load_sources(folder);metrics<-list();country<-list();frames<-list()\n  for(source in c('housing','bls')){data<-models[[source]];columns<-if(source=='housing')c('nominal','real')else c('outputIndexOriginalToken','hoursIndexOriginalToken','productivityIndexOriginalToken')\n    for(col in columns){values<-as.numeric(data[[col]]);rb<-rebase(values);g<-growth(values[1],tail(values,1));for(k in names(g))metrics[[paste(source,col,k,sep=':')]]<-g[[k]];quarterBase<-if(source=='housing')match('2010-Q1',data$quarter)else NA_integer_;qb<-if(!is.na(quarterBase))rebase(values,quarterBase)else rep(NA_real_,length(values));country[[length(country)+1]]<-data.frame(source=source,series=col,row=seq_len(nrow(data)),quarter=data$quarter,originalToken=data[[col]],rebasedFirst100Exact=rb,rebased2010Q1Exact=qb,stringsAsFactors=FALSE)}}\n  for(pair in list(c(1976,1978),c(1978,1980),c(1976,1980))){a<-pair[1];b<-pair[2];z<-person_comparison(models,a,b);frames[[length(frames)+1]]<-as.data.frame(c(list(before=a,after=b,elapsedYears=b-a),z),stringsAsFactors=FALSE);for(k in names(z))metrics[[paste('person',a,b,k,sep=':')]]<-z[[k]]}\n  company<-realdata(models,'company');metrics[['company:proxy']]<-company$ratio;metrics[['company:proxyGrowth']]<-NA_real_;for(k in names(company$revenueGrowth))metrics[[paste('company:sales',k,sep=':')]]<-company$revenueGrowth[[k]]\n  changes<-list();b<-models$bls\n  for(i in seq_len(nrow(b)-1L)){z<-productivity(as.numeric(b$outputIndexOriginalToken[i]),as.numeric(b$outputIndexOriginalToken[i+1]),as.numeric(b$hoursIndexOriginalToken[i]),as.numeric(b$hoursIndexOriginalToken[i+1]));g<-growth(as.numeric(b$productivityIndexOriginalToken[i]),as.numeric(b$productivityIndexOriginalToken[i+1]),4);changes[[i]]<-as.data.frame(c(list(start=b$quarter[i],end=b$quarter[i+1]),z,list(publishedProductivityPercent=g$percentChange,publishedAnnualizedPercent=g$annualizedPercent)),stringsAsFactors=FALSE)}\n  write<-function(name,rows)write.csv(rows,file.path(out,name),row.names=FALSE,na='',fileEncoding='UTF-8')\n  selected<-head(unique(models$person$unit),12);p<-models$person[models$person$unit%in%selected,];trajectories<-data.frame(unit=p$unit,year=p$time,nominalUSDPerHourExact=as.numeric(p$wageCentsOriginal)/100,stringsAsFactors=FALSE)\n  write('metrics.csv',data.frame(metric=names(metrics),value=as.numeric(unlist(metrics))));write('country-indexes.csv',do.call(rbind,country));write('wage-frames.csv',do.call(rbind,frames));write('bls-changes.csv',do.call(rbind,changes));write('first12-trajectories.csv',trajectories);invisible(metrics)\n}\nif(sys.nframe()==0L){args<-commandArgs(trailingOnly=TRUE);folder<-if(length(args)>=1)args[1]else'econ22-sources';out<-if(length(args)>=2)args[2]else'econ22-r-results';options(digits=17);metrics<-full_source(folder,out);cat('metrics:',length(metrics),'\\noutput directory:',out,'\\n')}\n"
          },
          {
            "file": "econ22-fixed-support.R",
            "sha256": "d4d63e1ad02017f20884b5932458dbde6013e0c2e560a4a9922a13d080a59fa1",
            "codeText": "# Run fixed drivers from the extracted bundle root. No packages or network required.\nsource('econ22-reproduce.R',encoding='UTF-8')\nexample <- function(api,variant) {\n  if(api=='rebase'){v<-if(variant=='invalid')c(0,1)else if(variant=='gap')c(80,NA,120)else c(80,100,120);z<-rebase(v);return(list(metrics=list(rows=length(z),defined=sum(!is.na(z)),last=tail(z,1)),x=seq_along(z)-1,y=z,xlabel='Position',ylabel='Rebased index'))}\n  if(api=='growth'){end<-if(variant=='quarterly')90 else 120;z<-growth(100,end,if(variant=='quarterly')4 else 1);return(list(metrics=z,x=c(0,1),y=c(100,end),xlabel='Date',ylabel='Supplied level'))}\n  if(api=='composition'){rows<-if(variant=='noCommon')data.frame(id=c('A','B'),before=c(10,NA),after=c(NA,20))else data.frame(id=c('A','B','C'),before=c(10,100,NA),after=c(11,NA,1));z<-composition(rows);metrics<-z[c('beforeAvailableMean','afterAvailableMean','availableMeanChange','commonWithinChange','commonUnits','exactDecompositionResidual')];return(list(metrics=metrics,x=c(0,1),y=c(z$beforeAvailableMean,z$afterAvailableMean),xlabel='Date',ylabel='Available mean / assumed units'))}\n  if(api=='productivity'){o<-if(variant=='contraction')90 else 103;h<-if(variant=='contraction')80 else 101;z<-productivity(100,o,100,h);return(list(metrics=z,x=c(0,1),y=c(1,z$productivityGross),xlabel='Date',ylabel='Output per hour / initial=1'))}\n  if(api=='measurement'){n<-if(variant=='zero')0 else 391035000000;d<-if(variant=='zero')0 else 164000;z<-measurement(n,d);return(list(metrics=list(ratio=z$ratio,denominatorZero=as.integer(d==0),sourceApproximate=as.integer(variant!='zero')),x=0,y=z$ratio,xlabel='Ratio position',ylabel='USD / approximate endpoint FTE'))}\n  models<-load_sources('econ22-sources');z<-realdata(models,variant)\n  if(variant=='country')return(list(metrics=list(sourceRows=z$originalCount,first=as.numeric(head(models$housing$nominal,1)),last=as.numeric(tail(models$housing$nominal,1)),percentChange=z$growth$percentChange),x=seq_along(z$rebased)-1,y=z$rebased,xlabel='Quarter position / original calendar',ylabel='Nominal housing / first=100'))\n  if(variant=='person')return(list(metrics=z[c('sourceUnits','beforeAvailableUnits','afterAvailableUnits','commonUnits','availableMeanChange','commonWithinChange','exactDecompositionResidual')],x=c(1976,1980),y=c(z$beforeAvailableMean,z$afterAvailableMean),xlabel='Observed wave',ylabel='Nominal USD/hour / available mean'))\n  if(variant=='company')return(list(metrics=list(sales2023=models$company$revenue2023,sales2024=models$company$revenue2024,proxy=z$ratio,proxyGrowth=NA_real_),x=c(2023,2024),y=c(models$company$revenue2023,models$company$revenue2024)/1e6,xlabel='Fiscal year',ylabel='Nominal USD millions'))\n  stop('fixed example name required')\n}\nrun <- function(api,variant,output) {\n  dir.create(output,recursive=TRUE,showWarnings=FALSE);z<-example(api,variant);metrics<-data.frame(metric=names(z$metrics),value=as.numeric(unlist(z$metrics)),stringsAsFactors=FALSE)\n  write.csv(metrics,file.path(output,'summary.csv'),row.names=FALSE,na='',fileEncoding='UTF-8');write.csv(data.frame(x=z$x,y=z$y),file.path(output,'plot-points.csv'),row.names=FALSE,na='',fileEncoding='UTF-8');print(metrics,row.names=FALSE)\n  good<-is.finite(z$x)&is.finite(z$y)\n  if(any(good)){svg(file.path(output,'plot.svg'),width=640/96,height=360/96,pointsize=10);par(mar=c(4.5,5.8,2,1));plot(z$x,z$y,type='o',pch=16,cex=.7,col='#355c72',xlab=z$xlabel,ylab=z$ylabel,cex.axis=.85,cex.lab=.9);grid(col='#d5dde1');dev.off();cat('plotProduced: TRUE\\n')}else cat('plotProduced: FALSE; undefined values retained\\n')\n}\n"
          }
        ],
        "inputFiles": [],
        "returnCode": 0,
        "expectedFailure": false,
        "stdout": "                     metric value\n        beforeAvailableMean    10\n         afterAvailableMean    20\n        availableMeanChange    10\n         commonWithinChange    NA\n                commonUnits     0\n exactDecompositionResidual    NA\nplotProduced: TRUE\n",
        "stderr": "During startup - Warning messages:\n1: Setting LC_COLLATE=C.UTF-8 failed \n2: Setting LC_CTYPE=C.UTF-8 failed \n3: Setting LC_MONETARY=C.UTF-8 failed \n4: Setting LC_TIME=C.UTF-8 failed \n",
        "seconds": 0.2970000000204891,
        "summary": {
          "beforeAvailableMean": "10",
          "afterAvailableMean": "20",
          "availableMeanChange": "10",
          "commonWithinChange": null,
          "commonUnits": "0",
          "exactDecompositionResidual": null
        },
        "plotPoints": [
          {
            "x": "0",
            "y": "10"
          },
          {
            "x": "1",
            "y": "20"
          }
        ],
        "plotFile": "econ22-fixed-results/composition-noCommon-r/plot.svg",
        "plotSHA256": "11fb65ba10e34af2f985d033567071c34ef6280b562c471af0223a6e12b06619",
        "scope": "Actually executed fixed example. Current browser controls are calculated separately by JavaScript. Base-R outputs use finite precision; Python outputs use exact fractions.",
        "summaryFile": "econ22-fixed-results/composition-noCommon-r/summary.csv",
        "summarySHA256": "bac4dfeec21388470da57acf60e7c5a99fc066d44116a21bb9ec9c7a2b7ae41e",
        "plotPointsFile": "econ22-fixed-results/composition-noCommon-r/plot-points.csv",
        "plotPointsSHA256": "b157a2afd1220c9fa450014a63fee447f37958050bdf08bffd8d605866c46789"
      }
    }
  },
  "productivity": {
    "python": {
      "default": {
        "api": "productivity",
        "variant": "default",
        "language": "python",
        "codeFile": "econ22-code/productivity-default.py",
        "codeSHA256": "cfa0f431b9de6459bee4ea4b8028eb2b3ca76ff0c14628f6f74ea528cbbab9e0",
        "codeText": "# Fixed stated example, separate from current web controls.\nfrom pathlib import Path\nimport importlib.util,sys\nroot=Path(__file__).resolve().parents[1]\nspec=importlib.util.spec_from_file_location('fixed_support',root/'econ22-fixed-support.py')\nsupport=importlib.util.module_from_spec(spec);spec.loader.exec_module(support)\ntry:support.run('productivity','default',sys.argv[1]if len(sys.argv)>1 else root/'econ22-fixed-results/productivity-default-python')\nexcept ValueError as error:\n print('Rejected declared input: '+str(error),file=sys.stderr);sys.exit(2)\n",
        "supportFiles": [
          {
            "file": "econ22-reproduce.py",
            "sha256": "cc5631d9dfea963b64349bb28d18b69ad3caf15a15162ec6cea786a36e18de48",
            "codeText": "#!/usr/bin/env python3\n\"\"\"ECON22 public reproduction: Python standard library, exact Fraction arithmetic.\nRun: python econ22-reproduce.py --source-dir econ22-sources --output-dir econ22-python-results\nOriginal CSV inputs are read only. Output is a new chosen directory.\nThese are descriptive arithmetic and explicitly assumed examples, not causal estimates.\n\"\"\"\nfrom fractions import Fraction as Q\nfrom pathlib import Path\nfrom collections import defaultdict\nimport argparse,csv,json\n\ndef number(x):\n if x is None:raise ValueError('missing numeric token')\n return Q(str(x))\ndef rebase(values,base=0,scale='100'):\n v=[None if x is None else number(x)for x in values];s=number(scale)\n if not v or not 0<=base<len(v)or v[base]is None or v[base]<=0 or s<=0:raise ValueError('positive observed base/scale required')\n return [None if x is None else s*x/v[base]for x in v]\ndef growth(start,end,periods=1):\n a,b=number(start),number(end)\n if a<=0 or b<0 or not isinstance(periods,int)or not 1<=periods<=12:raise ValueError('growth domain')\n g=b/a;return dict(gross=g,percentChange=(g-1)*100,annualizedGross=g**periods,annualizedPercent=(g**periods-1)*100)\ndef composition(rows):\n seen=set();data=[]\n for r in rows:\n  identifier=str(r['id']);weight=number(r.get('weight','1'))\n  if identifier in seen or weight<0:raise ValueError('unique units/nonnegative fixed weights required')\n  seen.add(identifier);data.append(dict(id=identifier,weight=weight,before=None if r['before']is None else number(r['before']),after=None if r['after']is None else number(r['after'])))\n if not data:raise ValueError('nonempty frame required')\n valid=[r for r in data if r['weight']>0];b=[r for r in valid if r['before']is not None];a=[r for r in valid if r['after']is not None];c=[r for r in valid if r['before']is not None and r['after']is not None]\n def mean(rs,k):\n  mass=sum((r['weight']for r in rs),Q(0));return sum((r[k]*r['weight']for r in rs),Q(0))/mass if mass else None\n mb,ma,cb,ca=mean(b,'before'),mean(a,'after'),mean(c,'before'),mean(c,'after');full=all(x is not None for x in [mb,ma,cb,ca]);change=ma-mb if mb is not None and ma is not None else None\n return dict(sourceUnits=len(data),beforeAvailableUnits=len(b),afterAvailableUnits=len(a),commonUnits=len(c),beforeAvailableMean=mb,afterAvailableMean=ma,beforeCommonMean=cb,afterCommonMean=ca,availableMeanChange=change,commonWithinChange=ca-cb if full else None,afterFrameShift=ma-ca if full else None,beforeFrameShift=cb-mb if full else None,exactDecompositionResidual=change-((ma-ca)+(ca-cb)+(cb-mb))if full else None)\ndef productivity(output0,output1,hours0,hours1):\n o0,o1,h0,h1=map(number,[output0,output1,hours0,hours1])\n if min(o0,o1,h0,h1)<=0:raise ValueError('positive output and hours required')\n go,gh=o1/o0,h1/h0;gp=go/gh\n return dict(outputGross=go,hoursGross=gh,productivityGross=gp,outputPercent=(go-1)*100,hoursPercent=(gh-1)*100,productivityPercent=(gp-1)*100,differenceOfPercentGrowths=(go-gh)*100,exactGrowthIdentityResidual=gp-go/gh)\ndef measurement(numerator,denominator,lower=None,upper=None):\n n,d=number(numerator),number(denominator)\n if d<0:raise ValueError('nonnegative denominator required')\n interval=None\n if lower is not None or upper is not None:\n  lo,hi=number(lower),number(upper)\n  if lo<=0 or hi<lo:raise ValueError('ordered positive scenario bounds')\n  interval=sorted([n/lo,n/hi])\n return dict(ratio=n/d if d else None,denominatorScenarioInterval=interval)\ndef read_csv(folder,name):\n with (folder/name).open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))\ndef load_sources(folder):\n h=read_csv(folder,'actual180-KOR-housing-nominal-real-indexes.csv');b=read_csv(folder,'actual38-US-nonfarm-output-hours-productivity-indexes.csv');p=read_csv(folder,'actual10839-person-wage-panel-original-and-prior-derived-fields.csv');c=read_csv(folder,'actual3-Apple-revenue-and-approximate-periodend-FTE-facts.csv')\n company={}\n for r in c:\n  value=Q(r['originalToken'].replace(',',''))\n  company[('revenue'+r['fiscalYear'])if r['fact']=='consolidated total net sales'else'endpointFTE2024']=value*1000000 if r['fact']=='consolidated total net sales'else value\n return dict(housing=h,bls=b,person=p,company=company)\ndef person_comparison(models,before=1976,after=1980):\n if before not in [1976,1978,1980]or after not in [1976,1978,1980]or before>=after:raise ValueError('ordered observed waves required')\n units=defaultdict(dict)\n for r in models['person']:\n  year=int(r['time'])\n  if year in units[r['unit']]:raise ValueError('duplicate original unit-wave')\n  token=r['wageCentsOriginal'];units[r['unit']][year]=None if token in ['.','','NA']else number(token)/100\n return composition([dict(id=k,before=v[before],after=v[after])for k,v in units.items()])\ndef realdata(models,kind):\n if kind=='country':\n  rows=models['housing'];return dict(originalCount=len(rows),growth=growth(rows[0]['nominal'],rows[-1]['nominal']),rebased=rebase([r['nominal']for r in rows]))\n if kind=='person':return person_comparison(models)\n if kind=='company':\n  c=models['company'];return dict(revenueGrowth=growth(c['revenue2023'],c['revenue2024']),ratio=measurement(c['revenue2024'],c['endpointFTE2024'])['ratio'],proxyGrowth=None)\n raise ValueError('actual case required')\ndef encode(v):\n if isinstance(v,Q):return str(v)\n if isinstance(v,dict):return{k:encode(x)for k,x in v.items()}\n if isinstance(v,(list,tuple)):return[encode(x)for x in v]\n return v\ndef write_csv(path,rows):\n with path.open('w',encoding='utf8',newline='')as f:\n  writer=csv.DictWriter(f,fieldnames=list(rows[0]));writer.writeheader();writer.writerows([{k:''if v is None else str(v)for k,v in r.items()}for r in rows])\ndef full_source(folder,out):\n out.mkdir(parents=True,exist_ok=True);models=load_sources(folder);metrics={};country=[];frames=[]\n for source in ['housing','bls']:\n  data=models[source];columns=['nominal','real']if source=='housing'else['outputIndexOriginalToken','hoursIndexOriginalToken','productivityIndexOriginalToken']\n  for col in columns:\n   values=[r[col]for r in data];rb=rebase(values);g=growth(values[0],values[-1])\n   for k,v in g.items():metrics[source+':'+col+':'+k]=v\n   quarter_base=next((i for i,r in enumerate(data)if r['quarter']=='2010-Q1'),None)if source=='housing'else None\n   qb=rebase(values,quarter_base)if quarter_base is not None else[None]*len(values)\n   country.extend(dict(source=source,series=col,row=i+1,quarter=r['quarter'],originalToken=r[col],rebasedFirst100Exact=rb[i],rebased2010Q1Exact=qb[i])for i,r in enumerate(data))\n for a,b in [(1976,1978),(1978,1980),(1976,1980)]:\n  z=person_comparison(models,a,b);frames.append(dict(before=a,after=b,elapsedYears=b-a,**z));metrics.update({f'person:{a}:{b}:{k}':v for k,v in z.items()})\n c=realdata(models,'company');metrics['company:proxy']=c['ratio'];metrics['company:proxyGrowth']=None;metrics.update({'company:sales:'+k:v for k,v in c['revenueGrowth'].items()})\n changes=[]\n for a,b in zip(models['bls'],models['bls'][1:]):\n  z=productivity(a['outputIndexOriginalToken'],b['outputIndexOriginalToken'],a['hoursIndexOriginalToken'],b['hoursIndexOriginalToken']);g=growth(a['productivityIndexOriginalToken'],b['productivityIndexOriginalToken'],4)\n  changes.append(dict(start=a['quarter'],end=b['quarter'],**z,publishedProductivityPercent=g['percentChange'],publishedAnnualizedPercent=g['annualizedPercent']))\n selected=list(dict.fromkeys(r['unit']for r in models['person']))[:12]\n trajectories=[dict(unit=r['unit'],year=r['time'],nominalUSDPerHourExact=None if r['wageCentsOriginal']in['.','','NA']else number(r['wageCentsOriginal'])/100)for r in models['person']if r['unit']in selected]\n write_csv(out/'metrics.csv',[dict(metric=k,value=v)for k,v in metrics.items()]);write_csv(out/'country-indexes.csv',country);write_csv(out/'wage-frames.csv',frames);write_csv(out/'bls-changes.csv',changes);write_csv(out/'first12-trajectories.csv',trajectories)\n (out/'full-results.json').write_text(json.dumps(encode(dict(metrics=metrics,frames=frames,company=c)),ensure_ascii=False,indent=2)+'\\n',encoding='utf8');return{f.name:len(read_csv(out,f.name))for f in out.glob('*.csv')}\nif __name__=='__main__':\n parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--source-dir',type=Path,default=Path(__file__).parent/'econ22-sources');parser.add_argument('--output-dir',type=Path,default=Path(__file__).parent/'econ22-python-results');args=parser.parse_args();print(json.dumps(full_source(args.source_dir,args.output_dir)))\n"
          },
          {
            "file": "econ22-fixed-support.py",
            "sha256": "deb4273c9c713e16c2f5e5d3525932ae34753f348731a3b26a4babff015c2fd6",
            "codeText": "\"\"\"Public fixed-example support. Requires only Python standard library and econ22-reproduce.py.\nFixed examples are separate from current browser inputs. Missing values remain None.\n\"\"\"\nfrom pathlib import Path\nfrom fractions import Fraction as Q\nimport importlib.util,json,csv,html,math\nROOT=Path(__file__).resolve().parent\nspec=importlib.util.spec_from_file_location('econ22_public',ROOT/'econ22-reproduce.py');M=importlib.util.module_from_spec(spec);spec.loader.exec_module(M)\n\ndef example(api,variant):\n if api=='rebase':\n  values=[0,1]if variant=='invalid'else[80,None,120]if variant=='gap'else[80,100,120];z=M.rebase(values);return dict(rows=len(z),defined=sum(x is not None for x in z),last=z[-1]),list(enumerate(z)),'Position','Rebased index'\n if api=='growth':\n  end=90 if variant=='quarterly'else 120;z=M.growth(100,end,4 if variant=='quarterly'else 1);return z,[(0,Q(100)),(1,Q(end))],'Date','Supplied level'\n if api=='composition':\n  rows=[dict(id='A',before=10,after=None),dict(id='B',before=None,after=20)]if variant=='noCommon'else[dict(id='A',before=10,after=11),dict(id='B',before=100,after=None),dict(id='C',before=None,after=1)];z=M.composition(rows);metrics={k:z[k]for k in ['beforeAvailableMean','afterAvailableMean','availableMeanChange','commonWithinChange','commonUnits','exactDecompositionResidual']};return metrics,[(0,z['beforeAvailableMean']),(1,z['afterAvailableMean'])],'Date','Available mean / assumed units'\n if api=='productivity':\n  o,h=(90,80)if variant=='contraction'else(103,101);z=M.productivity(100,o,100,h);return z,[(0,Q(1)),(1,z['productivityGross'])],'Date','Output per hour / initial=1'\n if api=='measurement':\n  n,d=(0,0)if variant=='zero'else(391035000000,164000);z=M.measurement(n,d);return dict(ratio=z['ratio'],denominatorZero=int(d==0),sourceApproximate=int(variant!='zero')),[(0,z['ratio'])],'Ratio position','USD / approximate endpoint FTE'\n models=M.load_sources(ROOT/'econ22-sources');z=M.realdata(models,variant)\n if variant=='country':return dict(sourceRows=z['originalCount'],first=Q(models['housing'][0]['nominal']),last=Q(models['housing'][-1]['nominal']),percentChange=z['growth']['percentChange']),list(enumerate(z['rebased'])),'Quarter position / original calendar','Nominal housing / first=100'\n if variant=='person':return{k:z[k]for k in ['sourceUnits','beforeAvailableUnits','afterAvailableUnits','commonUnits','availableMeanChange','commonWithinChange','exactDecompositionResidual']},[(1976,z['beforeAvailableMean']),(1980,z['afterAvailableMean'])],'Observed wave','Nominal USD/hour / available mean'\n if variant=='company':return dict(sales2023=models['company']['revenue2023'],sales2024=models['company']['revenue2024'],proxy=z['ratio'],proxyGrowth=None),[(2023,models['company']['revenue2023']/1000000),(2024,models['company']['revenue2024']/1000000)],'Fiscal year','Nominal USD millions'\n raise ValueError('fixed example name required')\n\ndef svg(points,xlabel,ylabel):\n good=[(float(x),float(y))for x,y in points if y is not None]\n if not good:return None\n if any(not math.isfinite(x)or not math.isfinite(y)for x,y in good):raise ValueError('outside finite plotting range')\n w,h,L,R,T,B=640,360,90,22,28,54;xmin=min(float(p[0])for p in points);xmax=max(float(p[0])for p in points);ymin=min(y for x,y in good);ymax=max(y for x,y in good)\n pad=max(1,abs(ymin)*.05)if ymin==ymax else(ymax-ymin)*.08;ymin-=pad;ymax+=pad\n X=lambda x:(L+w-R)/2 if xmax==xmin else L+(float(x)-xmin)/(xmax-xmin)*(w-L-R);Y=lambda y:T+(ymax-float(y))/(ymax-ymin)*(h-T-B);esc=html.escape\n s=f'<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"640\" height=\"360\" viewBox=\"0 0 640 360\" role=\"img\" aria-label=\"{esc(xlabel+\"; \"+ylabel)}\"><title>{esc(xlabel+\"; \"+ylabel)}</title><rect width=\"640\" height=\"360\" fill=\"white\"/><g font-family=\"sans-serif\" font-size=\"13\" fill=\"#222\">'\n for i in range(4):\n  v=ymin+(ymax-ymin)*i/3;y=Y(v);s+=f'<line x1=\"{L}\" x2=\"{w-R}\" y1=\"{y}\" y2=\"{y}\" stroke=\"#ccd6db\"/><text x=\"{L-7}\" y=\"{y+4}\" text-anchor=\"end\">{v:.4g}</text>'\n for x,anchor in([(xmin,'middle')]if xmin==xmax else[(xmin,'start'),(xmax,'end')]):s+=f'<text x=\"{X(x)}\" y=\"{h-B+24}\" text-anchor=\"{anchor}\">{x:g}</text>'\n last=None\n for x,y in points:\n  if y is None:last=None;continue\n  a,b=X(x),Y(y)\n  if last:s+=f'<line x1=\"{last[0]}\" y1=\"{last[1]}\" x2=\"{a}\" y2=\"{b}\" stroke=\"#355c72\" stroke-width=\"2\"/>'\n  s+=f'<circle cx=\"{a}\" cy=\"{b}\" r=\"3\" fill=\"#934b34\"><title>{esc(str(x)+\": \"+str(y))}</title></circle>';last=(a,b)\n return s+f'<text x=\"{L}\" y=\"16\">{esc(ylabel)}</text><text x=\"{w-R}\" y=\"{h-6}\" text-anchor=\"end\">{esc(xlabel)}</text></g></svg>'\n\ndef run(api,variant,output):\n out=Path(output);out.mkdir(parents=True,exist_ok=True);metrics,points,x,y=example(api,variant);encoded=M.encode(metrics);(out/'summary.json').write_text(json.dumps(encoded,indent=2)+'\\n',encoding='utf8')\n M.write_csv(out/'summary.csv',[dict(metric=k,value=v)for k,v in metrics.items()]);M.write_csv(out/'plot-points.csv',[dict(x=a,y=b)for a,b in points]);graphic=svg(points,x,y)\n if graphic is not None:(out/'plot.svg').write_text(graphic,encoding='utf8')\n print(json.dumps(dict(api=api,variant=variant,metrics=encoded,plotProduced=graphic is not None),ensure_ascii=False))\n"
          }
        ],
        "inputFiles": [],
        "returnCode": 0,
        "expectedFailure": false,
        "stdout": "{\"api\": \"productivity\", \"variant\": \"default\", \"metrics\": {\"outputGross\": \"103/100\", \"hoursGross\": \"101/100\", \"productivityGross\": \"103/101\", \"outputPercent\": \"3\", \"hoursPercent\": \"1\", \"productivityPercent\": \"200/101\", \"differenceOfPercentGrowths\": \"2\", \"exactGrowthIdentityResidual\": \"0\"}, \"plotProduced\": true}\n",
        "stderr": "",
        "seconds": 0.125,
        "summary": {
          "outputGross": "103/100",
          "hoursGross": "101/100",
          "productivityGross": "103/101",
          "outputPercent": "3",
          "hoursPercent": "1",
          "productivityPercent": "200/101",
          "differenceOfPercentGrowths": "2",
          "exactGrowthIdentityResidual": "0"
        },
        "plotPoints": [
          {
            "x": "0",
            "y": "1"
          },
          {
            "x": "1",
            "y": "103/101"
          }
        ],
        "plotFile": "econ22-fixed-results/productivity-default-python/plot.svg",
        "plotSHA256": "6c5bf2819b7be456e6f5c76f795e723f79fcc3cbae20e1f3d1bf1bfef29fdd1e",
        "scope": "Actually executed fixed example. Current browser controls are calculated separately by JavaScript. Base-R outputs use finite precision; Python outputs use exact fractions.",
        "summaryFile": "econ22-fixed-results/productivity-default-python/summary.csv",
        "summarySHA256": "9350be14c5768ce90a5715ad7a58a2b542e78e6d856110423d8d243079e6dd68",
        "plotPointsFile": "econ22-fixed-results/productivity-default-python/plot-points.csv",
        "plotPointsSHA256": "f93684b3b8bf66222b99efb6966322309463d22047dc40f9dbbacafa9a435cac"
      },
      "contraction": {
        "api": "productivity",
        "variant": "contraction",
        "language": "python",
        "codeFile": "econ22-code/productivity-contraction.py",
        "codeSHA256": "ea75d21fab1f0396ed719f780e052088687574c6b4a128d40e0f5cc54a580799",
        "codeText": "# Fixed stated example, separate from current web controls.\nfrom pathlib import Path\nimport importlib.util,sys\nroot=Path(__file__).resolve().parents[1]\nspec=importlib.util.spec_from_file_location('fixed_support',root/'econ22-fixed-support.py')\nsupport=importlib.util.module_from_spec(spec);spec.loader.exec_module(support)\ntry:support.run('productivity','contraction',sys.argv[1]if len(sys.argv)>1 else root/'econ22-fixed-results/productivity-contraction-python')\nexcept ValueError as error:\n print('Rejected declared input: '+str(error),file=sys.stderr);sys.exit(2)\n",
        "supportFiles": [
          {
            "file": "econ22-reproduce.py",
            "sha256": "cc5631d9dfea963b64349bb28d18b69ad3caf15a15162ec6cea786a36e18de48",
            "codeText": "#!/usr/bin/env python3\n\"\"\"ECON22 public reproduction: Python standard library, exact Fraction arithmetic.\nRun: python econ22-reproduce.py --source-dir econ22-sources --output-dir econ22-python-results\nOriginal CSV inputs are read only. Output is a new chosen directory.\nThese are descriptive arithmetic and explicitly assumed examples, not causal estimates.\n\"\"\"\nfrom fractions import Fraction as Q\nfrom pathlib import Path\nfrom collections import defaultdict\nimport argparse,csv,json\n\ndef number(x):\n if x is None:raise ValueError('missing numeric token')\n return Q(str(x))\ndef rebase(values,base=0,scale='100'):\n v=[None if x is None else number(x)for x in values];s=number(scale)\n if not v or not 0<=base<len(v)or v[base]is None or v[base]<=0 or s<=0:raise ValueError('positive observed base/scale required')\n return [None if x is None else s*x/v[base]for x in v]\ndef growth(start,end,periods=1):\n a,b=number(start),number(end)\n if a<=0 or b<0 or not isinstance(periods,int)or not 1<=periods<=12:raise ValueError('growth domain')\n g=b/a;return dict(gross=g,percentChange=(g-1)*100,annualizedGross=g**periods,annualizedPercent=(g**periods-1)*100)\ndef composition(rows):\n seen=set();data=[]\n for r in rows:\n  identifier=str(r['id']);weight=number(r.get('weight','1'))\n  if identifier in seen or weight<0:raise ValueError('unique units/nonnegative fixed weights required')\n  seen.add(identifier);data.append(dict(id=identifier,weight=weight,before=None if r['before']is None else number(r['before']),after=None if r['after']is None else number(r['after'])))\n if not data:raise ValueError('nonempty frame required')\n valid=[r for r in data if r['weight']>0];b=[r for r in valid if r['before']is not None];a=[r for r in valid if r['after']is not None];c=[r for r in valid if r['before']is not None and r['after']is not None]\n def mean(rs,k):\n  mass=sum((r['weight']for r in rs),Q(0));return sum((r[k]*r['weight']for r in rs),Q(0))/mass if mass else None\n mb,ma,cb,ca=mean(b,'before'),mean(a,'after'),mean(c,'before'),mean(c,'after');full=all(x is not None for x in [mb,ma,cb,ca]);change=ma-mb if mb is not None and ma is not None else None\n return dict(sourceUnits=len(data),beforeAvailableUnits=len(b),afterAvailableUnits=len(a),commonUnits=len(c),beforeAvailableMean=mb,afterAvailableMean=ma,beforeCommonMean=cb,afterCommonMean=ca,availableMeanChange=change,commonWithinChange=ca-cb if full else None,afterFrameShift=ma-ca if full else None,beforeFrameShift=cb-mb if full else None,exactDecompositionResidual=change-((ma-ca)+(ca-cb)+(cb-mb))if full else None)\ndef productivity(output0,output1,hours0,hours1):\n o0,o1,h0,h1=map(number,[output0,output1,hours0,hours1])\n if min(o0,o1,h0,h1)<=0:raise ValueError('positive output and hours required')\n go,gh=o1/o0,h1/h0;gp=go/gh\n return dict(outputGross=go,hoursGross=gh,productivityGross=gp,outputPercent=(go-1)*100,hoursPercent=(gh-1)*100,productivityPercent=(gp-1)*100,differenceOfPercentGrowths=(go-gh)*100,exactGrowthIdentityResidual=gp-go/gh)\ndef measurement(numerator,denominator,lower=None,upper=None):\n n,d=number(numerator),number(denominator)\n if d<0:raise ValueError('nonnegative denominator required')\n interval=None\n if lower is not None or upper is not None:\n  lo,hi=number(lower),number(upper)\n  if lo<=0 or hi<lo:raise ValueError('ordered positive scenario bounds')\n  interval=sorted([n/lo,n/hi])\n return dict(ratio=n/d if d else None,denominatorScenarioInterval=interval)\ndef read_csv(folder,name):\n with (folder/name).open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))\ndef load_sources(folder):\n h=read_csv(folder,'actual180-KOR-housing-nominal-real-indexes.csv');b=read_csv(folder,'actual38-US-nonfarm-output-hours-productivity-indexes.csv');p=read_csv(folder,'actual10839-person-wage-panel-original-and-prior-derived-fields.csv');c=read_csv(folder,'actual3-Apple-revenue-and-approximate-periodend-FTE-facts.csv')\n company={}\n for r in c:\n  value=Q(r['originalToken'].replace(',',''))\n  company[('revenue'+r['fiscalYear'])if r['fact']=='consolidated total net sales'else'endpointFTE2024']=value*1000000 if r['fact']=='consolidated total net sales'else value\n return dict(housing=h,bls=b,person=p,company=company)\ndef person_comparison(models,before=1976,after=1980):\n if before not in [1976,1978,1980]or after not in [1976,1978,1980]or before>=after:raise ValueError('ordered observed waves required')\n units=defaultdict(dict)\n for r in models['person']:\n  year=int(r['time'])\n  if year in units[r['unit']]:raise ValueError('duplicate original unit-wave')\n  token=r['wageCentsOriginal'];units[r['unit']][year]=None if token in ['.','','NA']else number(token)/100\n return composition([dict(id=k,before=v[before],after=v[after])for k,v in units.items()])\ndef realdata(models,kind):\n if kind=='country':\n  rows=models['housing'];return dict(originalCount=len(rows),growth=growth(rows[0]['nominal'],rows[-1]['nominal']),rebased=rebase([r['nominal']for r in rows]))\n if kind=='person':return person_comparison(models)\n if kind=='company':\n  c=models['company'];return dict(revenueGrowth=growth(c['revenue2023'],c['revenue2024']),ratio=measurement(c['revenue2024'],c['endpointFTE2024'])['ratio'],proxyGrowth=None)\n raise ValueError('actual case required')\ndef encode(v):\n if isinstance(v,Q):return str(v)\n if isinstance(v,dict):return{k:encode(x)for k,x in v.items()}\n if isinstance(v,(list,tuple)):return[encode(x)for x in v]\n return v\ndef write_csv(path,rows):\n with path.open('w',encoding='utf8',newline='')as f:\n  writer=csv.DictWriter(f,fieldnames=list(rows[0]));writer.writeheader();writer.writerows([{k:''if v is None else str(v)for k,v in r.items()}for r in rows])\ndef full_source(folder,out):\n out.mkdir(parents=True,exist_ok=True);models=load_sources(folder);metrics={};country=[];frames=[]\n for source in ['housing','bls']:\n  data=models[source];columns=['nominal','real']if source=='housing'else['outputIndexOriginalToken','hoursIndexOriginalToken','productivityIndexOriginalToken']\n  for col in columns:\n   values=[r[col]for r in data];rb=rebase(values);g=growth(values[0],values[-1])\n   for k,v in g.items():metrics[source+':'+col+':'+k]=v\n   quarter_base=next((i for i,r in enumerate(data)if r['quarter']=='2010-Q1'),None)if source=='housing'else None\n   qb=rebase(values,quarter_base)if quarter_base is not None else[None]*len(values)\n   country.extend(dict(source=source,series=col,row=i+1,quarter=r['quarter'],originalToken=r[col],rebasedFirst100Exact=rb[i],rebased2010Q1Exact=qb[i])for i,r in enumerate(data))\n for a,b in [(1976,1978),(1978,1980),(1976,1980)]:\n  z=person_comparison(models,a,b);frames.append(dict(before=a,after=b,elapsedYears=b-a,**z));metrics.update({f'person:{a}:{b}:{k}':v for k,v in z.items()})\n c=realdata(models,'company');metrics['company:proxy']=c['ratio'];metrics['company:proxyGrowth']=None;metrics.update({'company:sales:'+k:v for k,v in c['revenueGrowth'].items()})\n changes=[]\n for a,b in zip(models['bls'],models['bls'][1:]):\n  z=productivity(a['outputIndexOriginalToken'],b['outputIndexOriginalToken'],a['hoursIndexOriginalToken'],b['hoursIndexOriginalToken']);g=growth(a['productivityIndexOriginalToken'],b['productivityIndexOriginalToken'],4)\n  changes.append(dict(start=a['quarter'],end=b['quarter'],**z,publishedProductivityPercent=g['percentChange'],publishedAnnualizedPercent=g['annualizedPercent']))\n selected=list(dict.fromkeys(r['unit']for r in models['person']))[:12]\n trajectories=[dict(unit=r['unit'],year=r['time'],nominalUSDPerHourExact=None if r['wageCentsOriginal']in['.','','NA']else number(r['wageCentsOriginal'])/100)for r in models['person']if r['unit']in selected]\n write_csv(out/'metrics.csv',[dict(metric=k,value=v)for k,v in metrics.items()]);write_csv(out/'country-indexes.csv',country);write_csv(out/'wage-frames.csv',frames);write_csv(out/'bls-changes.csv',changes);write_csv(out/'first12-trajectories.csv',trajectories)\n (out/'full-results.json').write_text(json.dumps(encode(dict(metrics=metrics,frames=frames,company=c)),ensure_ascii=False,indent=2)+'\\n',encoding='utf8');return{f.name:len(read_csv(out,f.name))for f in out.glob('*.csv')}\nif __name__=='__main__':\n parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--source-dir',type=Path,default=Path(__file__).parent/'econ22-sources');parser.add_argument('--output-dir',type=Path,default=Path(__file__).parent/'econ22-python-results');args=parser.parse_args();print(json.dumps(full_source(args.source_dir,args.output_dir)))\n"
          },
          {
            "file": "econ22-fixed-support.py",
            "sha256": "deb4273c9c713e16c2f5e5d3525932ae34753f348731a3b26a4babff015c2fd6",
            "codeText": "\"\"\"Public fixed-example support. Requires only Python standard library and econ22-reproduce.py.\nFixed examples are separate from current browser inputs. Missing values remain None.\n\"\"\"\nfrom pathlib import Path\nfrom fractions import Fraction as Q\nimport importlib.util,json,csv,html,math\nROOT=Path(__file__).resolve().parent\nspec=importlib.util.spec_from_file_location('econ22_public',ROOT/'econ22-reproduce.py');M=importlib.util.module_from_spec(spec);spec.loader.exec_module(M)\n\ndef example(api,variant):\n if api=='rebase':\n  values=[0,1]if variant=='invalid'else[80,None,120]if variant=='gap'else[80,100,120];z=M.rebase(values);return dict(rows=len(z),defined=sum(x is not None for x in z),last=z[-1]),list(enumerate(z)),'Position','Rebased index'\n if api=='growth':\n  end=90 if variant=='quarterly'else 120;z=M.growth(100,end,4 if variant=='quarterly'else 1);return z,[(0,Q(100)),(1,Q(end))],'Date','Supplied level'\n if api=='composition':\n  rows=[dict(id='A',before=10,after=None),dict(id='B',before=None,after=20)]if variant=='noCommon'else[dict(id='A',before=10,after=11),dict(id='B',before=100,after=None),dict(id='C',before=None,after=1)];z=M.composition(rows);metrics={k:z[k]for k in ['beforeAvailableMean','afterAvailableMean','availableMeanChange','commonWithinChange','commonUnits','exactDecompositionResidual']};return metrics,[(0,z['beforeAvailableMean']),(1,z['afterAvailableMean'])],'Date','Available mean / assumed units'\n if api=='productivity':\n  o,h=(90,80)if variant=='contraction'else(103,101);z=M.productivity(100,o,100,h);return z,[(0,Q(1)),(1,z['productivityGross'])],'Date','Output per hour / initial=1'\n if api=='measurement':\n  n,d=(0,0)if variant=='zero'else(391035000000,164000);z=M.measurement(n,d);return dict(ratio=z['ratio'],denominatorZero=int(d==0),sourceApproximate=int(variant!='zero')),[(0,z['ratio'])],'Ratio position','USD / approximate endpoint FTE'\n models=M.load_sources(ROOT/'econ22-sources');z=M.realdata(models,variant)\n if variant=='country':return dict(sourceRows=z['originalCount'],first=Q(models['housing'][0]['nominal']),last=Q(models['housing'][-1]['nominal']),percentChange=z['growth']['percentChange']),list(enumerate(z['rebased'])),'Quarter position / original calendar','Nominal housing / first=100'\n if variant=='person':return{k:z[k]for k in ['sourceUnits','beforeAvailableUnits','afterAvailableUnits','commonUnits','availableMeanChange','commonWithinChange','exactDecompositionResidual']},[(1976,z['beforeAvailableMean']),(1980,z['afterAvailableMean'])],'Observed wave','Nominal USD/hour / available mean'\n if variant=='company':return dict(sales2023=models['company']['revenue2023'],sales2024=models['company']['revenue2024'],proxy=z['ratio'],proxyGrowth=None),[(2023,models['company']['revenue2023']/1000000),(2024,models['company']['revenue2024']/1000000)],'Fiscal year','Nominal USD millions'\n raise ValueError('fixed example name required')\n\ndef svg(points,xlabel,ylabel):\n good=[(float(x),float(y))for x,y in points if y is not None]\n if not good:return None\n if any(not math.isfinite(x)or not math.isfinite(y)for x,y in good):raise ValueError('outside finite plotting range')\n w,h,L,R,T,B=640,360,90,22,28,54;xmin=min(float(p[0])for p in points);xmax=max(float(p[0])for p in points);ymin=min(y for x,y in good);ymax=max(y for x,y in good)\n pad=max(1,abs(ymin)*.05)if ymin==ymax else(ymax-ymin)*.08;ymin-=pad;ymax+=pad\n X=lambda x:(L+w-R)/2 if xmax==xmin else L+(float(x)-xmin)/(xmax-xmin)*(w-L-R);Y=lambda y:T+(ymax-float(y))/(ymax-ymin)*(h-T-B);esc=html.escape\n s=f'<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"640\" height=\"360\" viewBox=\"0 0 640 360\" role=\"img\" aria-label=\"{esc(xlabel+\"; \"+ylabel)}\"><title>{esc(xlabel+\"; \"+ylabel)}</title><rect width=\"640\" height=\"360\" fill=\"white\"/><g font-family=\"sans-serif\" font-size=\"13\" fill=\"#222\">'\n for i in range(4):\n  v=ymin+(ymax-ymin)*i/3;y=Y(v);s+=f'<line x1=\"{L}\" x2=\"{w-R}\" y1=\"{y}\" y2=\"{y}\" stroke=\"#ccd6db\"/><text x=\"{L-7}\" y=\"{y+4}\" text-anchor=\"end\">{v:.4g}</text>'\n for x,anchor in([(xmin,'middle')]if xmin==xmax else[(xmin,'start'),(xmax,'end')]):s+=f'<text x=\"{X(x)}\" y=\"{h-B+24}\" text-anchor=\"{anchor}\">{x:g}</text>'\n last=None\n for x,y in points:\n  if y is None:last=None;continue\n  a,b=X(x),Y(y)\n  if last:s+=f'<line x1=\"{last[0]}\" y1=\"{last[1]}\" x2=\"{a}\" y2=\"{b}\" stroke=\"#355c72\" stroke-width=\"2\"/>'\n  s+=f'<circle cx=\"{a}\" cy=\"{b}\" r=\"3\" fill=\"#934b34\"><title>{esc(str(x)+\": \"+str(y))}</title></circle>';last=(a,b)\n return s+f'<text x=\"{L}\" y=\"16\">{esc(ylabel)}</text><text x=\"{w-R}\" y=\"{h-6}\" text-anchor=\"end\">{esc(xlabel)}</text></g></svg>'\n\ndef run(api,variant,output):\n out=Path(output);out.mkdir(parents=True,exist_ok=True);metrics,points,x,y=example(api,variant);encoded=M.encode(metrics);(out/'summary.json').write_text(json.dumps(encoded,indent=2)+'\\n',encoding='utf8')\n M.write_csv(out/'summary.csv',[dict(metric=k,value=v)for k,v in metrics.items()]);M.write_csv(out/'plot-points.csv',[dict(x=a,y=b)for a,b in points]);graphic=svg(points,x,y)\n if graphic is not None:(out/'plot.svg').write_text(graphic,encoding='utf8')\n print(json.dumps(dict(api=api,variant=variant,metrics=encoded,plotProduced=graphic is not None),ensure_ascii=False))\n"
          }
        ],
        "inputFiles": [],
        "returnCode": 0,
        "expectedFailure": false,
        "stdout": "{\"api\": \"productivity\", \"variant\": \"contraction\", \"metrics\": {\"outputGross\": \"9/10\", \"hoursGross\": \"4/5\", \"productivityGross\": \"9/8\", \"outputPercent\": \"-10\", \"hoursPercent\": \"-20\", \"productivityPercent\": \"25/2\", \"differenceOfPercentGrowths\": \"10\", \"exactGrowthIdentityResidual\": \"0\"}, \"plotProduced\": true}\n",
        "stderr": "",
        "seconds": 0.10899999999674037,
        "summary": {
          "outputGross": "9/10",
          "hoursGross": "4/5",
          "productivityGross": "9/8",
          "outputPercent": "-10",
          "hoursPercent": "-20",
          "productivityPercent": "25/2",
          "differenceOfPercentGrowths": "10",
          "exactGrowthIdentityResidual": "0"
        },
        "plotPoints": [
          {
            "x": "0",
            "y": "1"
          },
          {
            "x": "1",
            "y": "9/8"
          }
        ],
        "plotFile": "econ22-fixed-results/productivity-contraction-python/plot.svg",
        "plotSHA256": "1c4c38e961d3549ea0d2163b10b0139250919d5a18e7a26b31c84b983e48fd8a",
        "scope": "Actually executed fixed example. Current browser controls are calculated separately by JavaScript. Base-R outputs use finite precision; Python outputs use exact fractions.",
        "summaryFile": "econ22-fixed-results/productivity-contraction-python/summary.csv",
        "summarySHA256": "3d8f6b4eab08d2cd33c388cd176fd9cf35663d520496d82e2749727364da1460",
        "plotPointsFile": "econ22-fixed-results/productivity-contraction-python/plot-points.csv",
        "plotPointsSHA256": "c372224c8bdf55c8579aae0de20501bdf3116f3ce1691d7f2846cc8c524064d2"
      }
    },
    "r": {
      "default": {
        "api": "productivity",
        "variant": "default",
        "language": "r",
        "codeFile": "econ22-code/productivity-default.R",
        "codeSHA256": "03ed2c76aea239e122072eae293e1995550a3fb8c4799740f2bef7ac6a84df2d",
        "codeText": "# Run from the extracted textbook bundle root.\nsource('econ22-fixed-support.R',encoding='UTF-8')\noptions(digits=17)\nargs<-commandArgs(trailingOnly=TRUE)\noutput<-if(length(args))args[1]else'econ22-fixed-results/productivity-default-r'\ntryCatch(run('productivity','default',output),error=function(error){cat('Rejected declared input: ',conditionMessage(error),'\\n',file=stderr());quit(status=2)})\n",
        "supportFiles": [
          {
            "file": "econ22-reproduce.R",
            "sha256": "2db22759696a6f288479189f44026f265536a54cdc2e72952c1e91af13661480",
            "codeText": "# ECON22 independent public base-R reproduction; binary64 approximations.\n# Run: Rscript --vanilla --encoding=UTF-8 econ22-reproduce.R [source-dir] [output-dir]\n# Source CSVs are never overwritten. No packages or network required.\nrebase <- function(values, base=1L, scale=100) {\n  if (length(base)!=1L || !is.finite(base) || base!=as.integer(base) || !length(values) || base<1 || base>length(values) || is.na(values[base]) || values[base]<=0 || !is.finite(scale) || scale<=0) stop('positive observed base/scale required')\n  scale*values/values[base]\n}\ngrowth <- function(start,end,periods=1L) {\n  if (start<=0 || end<0 || periods<1 || periods>12 || periods!=as.integer(periods)) stop('growth domain')\n  gross<-end/start;list(gross=gross,percentChange=(gross-1)*100,annualizedGross=gross^periods,annualizedPercent=(gross^periods-1)*100)\n}\ncomposition <- function(rows) {\n  if (!nrow(rows) || anyDuplicated(rows$id)) stop('nonempty unique units required')\n  if (!'weight'%in%names(rows)) rows$weight<-rep(1,nrow(rows))\n  if (any(!is.finite(rows$weight)) || any(rows$weight<0)) stop('nonnegative fixed weights required')\n  valid<-rows$weight>0;b<-valid&!is.na(rows$before);a<-valid&!is.na(rows$after);common<-b&a\n  avg<-function(mask,column)if(sum(rows$weight[mask])>0)sum(rows[[column]][mask]*rows$weight[mask])/sum(rows$weight[mask])else NA_real_\n  mb<-avg(b,'before');ma<-avg(a,'after');cb<-avg(common,'before');ca<-avg(common,'after');full<-all(is.finite(c(mb,ma,cb,ca)))\n  list(sourceUnits=nrow(rows),beforeAvailableUnits=sum(b),afterAvailableUnits=sum(a),commonUnits=sum(common),beforeAvailableMean=mb,afterAvailableMean=ma,beforeCommonMean=cb,afterCommonMean=ca,availableMeanChange=ma-mb,commonWithinChange=if(full)ca-cb else NA_real_,afterFrameShift=if(full)ma-ca else NA_real_,beforeFrameShift=if(full)cb-mb else NA_real_,exactDecompositionResidual=if(full)(ma-mb)-((ma-ca)+(ca-cb)+(cb-mb))else NA_real_)\n}\nproductivity <- function(output0,output1,hours0,hours1) {\n  if(any(c(output0,output1,hours0,hours1)<=0))stop('positive output and hours required')\n  go<-output1/output0;gh<-hours1/hours0;gp<-go/gh\n  list(outputGross=go,hoursGross=gh,productivityGross=gp,outputPercent=(go-1)*100,hoursPercent=(gh-1)*100,productivityPercent=(gp-1)*100,differenceOfPercentGrowths=(go-gh)*100,exactGrowthIdentityResidual=gp-go/gh)\n}\nmeasurement <- function(numerator,denominator,lower=NA_real_,upper=NA_real_) {\n  if(denominator<0)stop('nonnegative denominator required');interval<-NULL\n  if(!is.na(lower)||!is.na(upper)){if(any(!is.finite(c(lower,upper)))||lower<=0||upper<lower)stop('ordered positive scenario bounds');interval<-sort(c(numerator/lower,numerator/upper))}\n  list(ratio=if(denominator>0)numerator/denominator else NA_real_,denominatorScenarioInterval=interval)\n}\nload_sources <- function(folder) {\n  read<-function(file)read.csv(file.path(folder,file),stringsAsFactors=FALSE,check.names=FALSE,colClasses='character',na.strings=c('NA','','.'))\n  h<-read('actual180-KOR-housing-nominal-real-indexes.csv');b<-read('actual38-US-nonfarm-output-hours-productivity-indexes.csv');p<-read('actual10839-person-wage-panel-original-and-prior-derived-fields.csv');c<-read('actual3-Apple-revenue-and-approximate-periodend-FTE-facts.csv')\n  company<-list();for(i in seq_len(nrow(c))){value<-as.numeric(gsub(',','',c$originalToken[i],fixed=TRUE));if(c$fact[i]=='consolidated total net sales')company[[paste0('revenue',c$fiscalYear[i])]]<-value*1e6 else company$endpointFTE2024<-value}\n  list(housing=h,bls=b,person=p,company=company)\n}\nperson_comparison <- function(models,before=1976L,after=1980L) {\n  if(!before%in%c(1976,1978,1980)||!after%in%c(1976,1978,1980)||before>=after)stop('ordered observed waves required')\n  p<-models$person;if(anyDuplicated(paste(p$unit,p$time,sep=':')))stop('duplicate original unit-wave')\n  ids<-unique(p$unit);rows<-data.frame(id=ids,before=as.numeric(p$wageCentsOriginal[match(paste(ids,before),paste(p$unit,p$time))])/100,after=as.numeric(p$wageCentsOriginal[match(paste(ids,after),paste(p$unit,p$time))])/100,stringsAsFactors=FALSE)\n  composition(rows)\n}\nrealdata <- function(models,kind) {\n  if(kind=='country'){r<-models$housing;return(list(originalCount=nrow(r),growth=growth(as.numeric(r$nominal[1]),as.numeric(tail(r$nominal,1))),rebased=rebase(as.numeric(r$nominal))))}\n  if(kind=='person')return(person_comparison(models))\n  if(kind=='company'){c<-models$company;return(list(revenueGrowth=growth(c$revenue2023,c$revenue2024),ratio=measurement(c$revenue2024,c$endpointFTE2024)$ratio,proxyGrowth=NA_real_))}\n  stop('actual case required')\n}\nfull_source <- function(folder,out) {\n  dir.create(out,recursive=TRUE,showWarnings=FALSE);models<-load_sources(folder);metrics<-list();country<-list();frames<-list()\n  for(source in c('housing','bls')){data<-models[[source]];columns<-if(source=='housing')c('nominal','real')else c('outputIndexOriginalToken','hoursIndexOriginalToken','productivityIndexOriginalToken')\n    for(col in columns){values<-as.numeric(data[[col]]);rb<-rebase(values);g<-growth(values[1],tail(values,1));for(k in names(g))metrics[[paste(source,col,k,sep=':')]]<-g[[k]];quarterBase<-if(source=='housing')match('2010-Q1',data$quarter)else NA_integer_;qb<-if(!is.na(quarterBase))rebase(values,quarterBase)else rep(NA_real_,length(values));country[[length(country)+1]]<-data.frame(source=source,series=col,row=seq_len(nrow(data)),quarter=data$quarter,originalToken=data[[col]],rebasedFirst100Exact=rb,rebased2010Q1Exact=qb,stringsAsFactors=FALSE)}}\n  for(pair in list(c(1976,1978),c(1978,1980),c(1976,1980))){a<-pair[1];b<-pair[2];z<-person_comparison(models,a,b);frames[[length(frames)+1]]<-as.data.frame(c(list(before=a,after=b,elapsedYears=b-a),z),stringsAsFactors=FALSE);for(k in names(z))metrics[[paste('person',a,b,k,sep=':')]]<-z[[k]]}\n  company<-realdata(models,'company');metrics[['company:proxy']]<-company$ratio;metrics[['company:proxyGrowth']]<-NA_real_;for(k in names(company$revenueGrowth))metrics[[paste('company:sales',k,sep=':')]]<-company$revenueGrowth[[k]]\n  changes<-list();b<-models$bls\n  for(i in seq_len(nrow(b)-1L)){z<-productivity(as.numeric(b$outputIndexOriginalToken[i]),as.numeric(b$outputIndexOriginalToken[i+1]),as.numeric(b$hoursIndexOriginalToken[i]),as.numeric(b$hoursIndexOriginalToken[i+1]));g<-growth(as.numeric(b$productivityIndexOriginalToken[i]),as.numeric(b$productivityIndexOriginalToken[i+1]),4);changes[[i]]<-as.data.frame(c(list(start=b$quarter[i],end=b$quarter[i+1]),z,list(publishedProductivityPercent=g$percentChange,publishedAnnualizedPercent=g$annualizedPercent)),stringsAsFactors=FALSE)}\n  write<-function(name,rows)write.csv(rows,file.path(out,name),row.names=FALSE,na='',fileEncoding='UTF-8')\n  selected<-head(unique(models$person$unit),12);p<-models$person[models$person$unit%in%selected,];trajectories<-data.frame(unit=p$unit,year=p$time,nominalUSDPerHourExact=as.numeric(p$wageCentsOriginal)/100,stringsAsFactors=FALSE)\n  write('metrics.csv',data.frame(metric=names(metrics),value=as.numeric(unlist(metrics))));write('country-indexes.csv',do.call(rbind,country));write('wage-frames.csv',do.call(rbind,frames));write('bls-changes.csv',do.call(rbind,changes));write('first12-trajectories.csv',trajectories);invisible(metrics)\n}\nif(sys.nframe()==0L){args<-commandArgs(trailingOnly=TRUE);folder<-if(length(args)>=1)args[1]else'econ22-sources';out<-if(length(args)>=2)args[2]else'econ22-r-results';options(digits=17);metrics<-full_source(folder,out);cat('metrics:',length(metrics),'\\noutput directory:',out,'\\n')}\n"
          },
          {
            "file": "econ22-fixed-support.R",
            "sha256": "d4d63e1ad02017f20884b5932458dbde6013e0c2e560a4a9922a13d080a59fa1",
            "codeText": "# Run fixed drivers from the extracted bundle root. No packages or network required.\nsource('econ22-reproduce.R',encoding='UTF-8')\nexample <- function(api,variant) {\n  if(api=='rebase'){v<-if(variant=='invalid')c(0,1)else if(variant=='gap')c(80,NA,120)else c(80,100,120);z<-rebase(v);return(list(metrics=list(rows=length(z),defined=sum(!is.na(z)),last=tail(z,1)),x=seq_along(z)-1,y=z,xlabel='Position',ylabel='Rebased index'))}\n  if(api=='growth'){end<-if(variant=='quarterly')90 else 120;z<-growth(100,end,if(variant=='quarterly')4 else 1);return(list(metrics=z,x=c(0,1),y=c(100,end),xlabel='Date',ylabel='Supplied level'))}\n  if(api=='composition'){rows<-if(variant=='noCommon')data.frame(id=c('A','B'),before=c(10,NA),after=c(NA,20))else data.frame(id=c('A','B','C'),before=c(10,100,NA),after=c(11,NA,1));z<-composition(rows);metrics<-z[c('beforeAvailableMean','afterAvailableMean','availableMeanChange','commonWithinChange','commonUnits','exactDecompositionResidual')];return(list(metrics=metrics,x=c(0,1),y=c(z$beforeAvailableMean,z$afterAvailableMean),xlabel='Date',ylabel='Available mean / assumed units'))}\n  if(api=='productivity'){o<-if(variant=='contraction')90 else 103;h<-if(variant=='contraction')80 else 101;z<-productivity(100,o,100,h);return(list(metrics=z,x=c(0,1),y=c(1,z$productivityGross),xlabel='Date',ylabel='Output per hour / initial=1'))}\n  if(api=='measurement'){n<-if(variant=='zero')0 else 391035000000;d<-if(variant=='zero')0 else 164000;z<-measurement(n,d);return(list(metrics=list(ratio=z$ratio,denominatorZero=as.integer(d==0),sourceApproximate=as.integer(variant!='zero')),x=0,y=z$ratio,xlabel='Ratio position',ylabel='USD / approximate endpoint FTE'))}\n  models<-load_sources('econ22-sources');z<-realdata(models,variant)\n  if(variant=='country')return(list(metrics=list(sourceRows=z$originalCount,first=as.numeric(head(models$housing$nominal,1)),last=as.numeric(tail(models$housing$nominal,1)),percentChange=z$growth$percentChange),x=seq_along(z$rebased)-1,y=z$rebased,xlabel='Quarter position / original calendar',ylabel='Nominal housing / first=100'))\n  if(variant=='person')return(list(metrics=z[c('sourceUnits','beforeAvailableUnits','afterAvailableUnits','commonUnits','availableMeanChange','commonWithinChange','exactDecompositionResidual')],x=c(1976,1980),y=c(z$beforeAvailableMean,z$afterAvailableMean),xlabel='Observed wave',ylabel='Nominal USD/hour / available mean'))\n  if(variant=='company')return(list(metrics=list(sales2023=models$company$revenue2023,sales2024=models$company$revenue2024,proxy=z$ratio,proxyGrowth=NA_real_),x=c(2023,2024),y=c(models$company$revenue2023,models$company$revenue2024)/1e6,xlabel='Fiscal year',ylabel='Nominal USD millions'))\n  stop('fixed example name required')\n}\nrun <- function(api,variant,output) {\n  dir.create(output,recursive=TRUE,showWarnings=FALSE);z<-example(api,variant);metrics<-data.frame(metric=names(z$metrics),value=as.numeric(unlist(z$metrics)),stringsAsFactors=FALSE)\n  write.csv(metrics,file.path(output,'summary.csv'),row.names=FALSE,na='',fileEncoding='UTF-8');write.csv(data.frame(x=z$x,y=z$y),file.path(output,'plot-points.csv'),row.names=FALSE,na='',fileEncoding='UTF-8');print(metrics,row.names=FALSE)\n  good<-is.finite(z$x)&is.finite(z$y)\n  if(any(good)){svg(file.path(output,'plot.svg'),width=640/96,height=360/96,pointsize=10);par(mar=c(4.5,5.8,2,1));plot(z$x,z$y,type='o',pch=16,cex=.7,col='#355c72',xlab=z$xlabel,ylab=z$ylabel,cex.axis=.85,cex.lab=.9);grid(col='#d5dde1');dev.off();cat('plotProduced: TRUE\\n')}else cat('plotProduced: FALSE; undefined values retained\\n')\n}\n"
          }
        ],
        "inputFiles": [],
        "returnCode": 0,
        "expectedFailure": false,
        "stdout": "                      metric              value\n                 outputGross 1.0300000000000000\n                  hoursGross 1.0100000000000000\n           productivityGross 1.0198019801980198\n               outputPercent 3.0000000000000027\n                hoursPercent 1.0000000000000009\n         productivityPercent 1.9801980198019820\n  differenceOfPercentGrowths 2.0000000000000018\n exactGrowthIdentityResidual 0.0000000000000000\nplotProduced: TRUE\n",
        "stderr": "During startup - Warning messages:\n1: Setting LC_COLLATE=C.UTF-8 failed \n2: Setting LC_CTYPE=C.UTF-8 failed \n3: Setting LC_MONETARY=C.UTF-8 failed \n4: Setting LC_TIME=C.UTF-8 failed \n",
        "seconds": 0.2809999999590218,
        "summary": {
          "outputGross": "1.03",
          "hoursGross": "1.01",
          "productivityGross": "1.01980198019802",
          "outputPercent": "3",
          "hoursPercent": "1",
          "productivityPercent": "1.98019801980198",
          "differenceOfPercentGrowths": "2",
          "exactGrowthIdentityResidual": "0"
        },
        "plotPoints": [
          {
            "x": "0",
            "y": "1"
          },
          {
            "x": "1",
            "y": "1.01980198019802"
          }
        ],
        "plotFile": "econ22-fixed-results/productivity-default-r/plot.svg",
        "plotSHA256": "f6944c5ce865908a5950ba3e322e9f571a64d5fbcbe422d2dc57c1d91be5c6fd",
        "scope": "Actually executed fixed example. Current browser controls are calculated separately by JavaScript. Base-R outputs use finite precision; Python outputs use exact fractions.",
        "summaryFile": "econ22-fixed-results/productivity-default-r/summary.csv",
        "summarySHA256": "1f4c56d9869f13e77467bfca31f197cc888d17be291fd463a04999a52cbcd6fe",
        "plotPointsFile": "econ22-fixed-results/productivity-default-r/plot-points.csv",
        "plotPointsSHA256": "ddb6c573bfbc25bf384946d6d6468fbf8feaa4e82c91a82bc9328c19bd2d6ece"
      },
      "contraction": {
        "api": "productivity",
        "variant": "contraction",
        "language": "r",
        "codeFile": "econ22-code/productivity-contraction.R",
        "codeSHA256": "d90796edb0da711d6cc3e4feaaf6bcaa4f727db5e2e4a4f0258c1326d67f44df",
        "codeText": "# Run from the extracted textbook bundle root.\nsource('econ22-fixed-support.R',encoding='UTF-8')\noptions(digits=17)\nargs<-commandArgs(trailingOnly=TRUE)\noutput<-if(length(args))args[1]else'econ22-fixed-results/productivity-contraction-r'\ntryCatch(run('productivity','contraction',output),error=function(error){cat('Rejected declared input: ',conditionMessage(error),'\\n',file=stderr());quit(status=2)})\n",
        "supportFiles": [
          {
            "file": "econ22-reproduce.R",
            "sha256": "2db22759696a6f288479189f44026f265536a54cdc2e72952c1e91af13661480",
            "codeText": "# ECON22 independent public base-R reproduction; binary64 approximations.\n# Run: Rscript --vanilla --encoding=UTF-8 econ22-reproduce.R [source-dir] [output-dir]\n# Source CSVs are never overwritten. No packages or network required.\nrebase <- function(values, base=1L, scale=100) {\n  if (length(base)!=1L || !is.finite(base) || base!=as.integer(base) || !length(values) || base<1 || base>length(values) || is.na(values[base]) || values[base]<=0 || !is.finite(scale) || scale<=0) stop('positive observed base/scale required')\n  scale*values/values[base]\n}\ngrowth <- function(start,end,periods=1L) {\n  if (start<=0 || end<0 || periods<1 || periods>12 || periods!=as.integer(periods)) stop('growth domain')\n  gross<-end/start;list(gross=gross,percentChange=(gross-1)*100,annualizedGross=gross^periods,annualizedPercent=(gross^periods-1)*100)\n}\ncomposition <- function(rows) {\n  if (!nrow(rows) || anyDuplicated(rows$id)) stop('nonempty unique units required')\n  if (!'weight'%in%names(rows)) rows$weight<-rep(1,nrow(rows))\n  if (any(!is.finite(rows$weight)) || any(rows$weight<0)) stop('nonnegative fixed weights required')\n  valid<-rows$weight>0;b<-valid&!is.na(rows$before);a<-valid&!is.na(rows$after);common<-b&a\n  avg<-function(mask,column)if(sum(rows$weight[mask])>0)sum(rows[[column]][mask]*rows$weight[mask])/sum(rows$weight[mask])else NA_real_\n  mb<-avg(b,'before');ma<-avg(a,'after');cb<-avg(common,'before');ca<-avg(common,'after');full<-all(is.finite(c(mb,ma,cb,ca)))\n  list(sourceUnits=nrow(rows),beforeAvailableUnits=sum(b),afterAvailableUnits=sum(a),commonUnits=sum(common),beforeAvailableMean=mb,afterAvailableMean=ma,beforeCommonMean=cb,afterCommonMean=ca,availableMeanChange=ma-mb,commonWithinChange=if(full)ca-cb else NA_real_,afterFrameShift=if(full)ma-ca else NA_real_,beforeFrameShift=if(full)cb-mb else NA_real_,exactDecompositionResidual=if(full)(ma-mb)-((ma-ca)+(ca-cb)+(cb-mb))else NA_real_)\n}\nproductivity <- function(output0,output1,hours0,hours1) {\n  if(any(c(output0,output1,hours0,hours1)<=0))stop('positive output and hours required')\n  go<-output1/output0;gh<-hours1/hours0;gp<-go/gh\n  list(outputGross=go,hoursGross=gh,productivityGross=gp,outputPercent=(go-1)*100,hoursPercent=(gh-1)*100,productivityPercent=(gp-1)*100,differenceOfPercentGrowths=(go-gh)*100,exactGrowthIdentityResidual=gp-go/gh)\n}\nmeasurement <- function(numerator,denominator,lower=NA_real_,upper=NA_real_) {\n  if(denominator<0)stop('nonnegative denominator required');interval<-NULL\n  if(!is.na(lower)||!is.na(upper)){if(any(!is.finite(c(lower,upper)))||lower<=0||upper<lower)stop('ordered positive scenario bounds');interval<-sort(c(numerator/lower,numerator/upper))}\n  list(ratio=if(denominator>0)numerator/denominator else NA_real_,denominatorScenarioInterval=interval)\n}\nload_sources <- function(folder) {\n  read<-function(file)read.csv(file.path(folder,file),stringsAsFactors=FALSE,check.names=FALSE,colClasses='character',na.strings=c('NA','','.'))\n  h<-read('actual180-KOR-housing-nominal-real-indexes.csv');b<-read('actual38-US-nonfarm-output-hours-productivity-indexes.csv');p<-read('actual10839-person-wage-panel-original-and-prior-derived-fields.csv');c<-read('actual3-Apple-revenue-and-approximate-periodend-FTE-facts.csv')\n  company<-list();for(i in seq_len(nrow(c))){value<-as.numeric(gsub(',','',c$originalToken[i],fixed=TRUE));if(c$fact[i]=='consolidated total net sales')company[[paste0('revenue',c$fiscalYear[i])]]<-value*1e6 else company$endpointFTE2024<-value}\n  list(housing=h,bls=b,person=p,company=company)\n}\nperson_comparison <- function(models,before=1976L,after=1980L) {\n  if(!before%in%c(1976,1978,1980)||!after%in%c(1976,1978,1980)||before>=after)stop('ordered observed waves required')\n  p<-models$person;if(anyDuplicated(paste(p$unit,p$time,sep=':')))stop('duplicate original unit-wave')\n  ids<-unique(p$unit);rows<-data.frame(id=ids,before=as.numeric(p$wageCentsOriginal[match(paste(ids,before),paste(p$unit,p$time))])/100,after=as.numeric(p$wageCentsOriginal[match(paste(ids,after),paste(p$unit,p$time))])/100,stringsAsFactors=FALSE)\n  composition(rows)\n}\nrealdata <- function(models,kind) {\n  if(kind=='country'){r<-models$housing;return(list(originalCount=nrow(r),growth=growth(as.numeric(r$nominal[1]),as.numeric(tail(r$nominal,1))),rebased=rebase(as.numeric(r$nominal))))}\n  if(kind=='person')return(person_comparison(models))\n  if(kind=='company'){c<-models$company;return(list(revenueGrowth=growth(c$revenue2023,c$revenue2024),ratio=measurement(c$revenue2024,c$endpointFTE2024)$ratio,proxyGrowth=NA_real_))}\n  stop('actual case required')\n}\nfull_source <- function(folder,out) {\n  dir.create(out,recursive=TRUE,showWarnings=FALSE);models<-load_sources(folder);metrics<-list();country<-list();frames<-list()\n  for(source in c('housing','bls')){data<-models[[source]];columns<-if(source=='housing')c('nominal','real')else c('outputIndexOriginalToken','hoursIndexOriginalToken','productivityIndexOriginalToken')\n    for(col in columns){values<-as.numeric(data[[col]]);rb<-rebase(values);g<-growth(values[1],tail(values,1));for(k in names(g))metrics[[paste(source,col,k,sep=':')]]<-g[[k]];quarterBase<-if(source=='housing')match('2010-Q1',data$quarter)else NA_integer_;qb<-if(!is.na(quarterBase))rebase(values,quarterBase)else rep(NA_real_,length(values));country[[length(country)+1]]<-data.frame(source=source,series=col,row=seq_len(nrow(data)),quarter=data$quarter,originalToken=data[[col]],rebasedFirst100Exact=rb,rebased2010Q1Exact=qb,stringsAsFactors=FALSE)}}\n  for(pair in list(c(1976,1978),c(1978,1980),c(1976,1980))){a<-pair[1];b<-pair[2];z<-person_comparison(models,a,b);frames[[length(frames)+1]]<-as.data.frame(c(list(before=a,after=b,elapsedYears=b-a),z),stringsAsFactors=FALSE);for(k in names(z))metrics[[paste('person',a,b,k,sep=':')]]<-z[[k]]}\n  company<-realdata(models,'company');metrics[['company:proxy']]<-company$ratio;metrics[['company:proxyGrowth']]<-NA_real_;for(k in names(company$revenueGrowth))metrics[[paste('company:sales',k,sep=':')]]<-company$revenueGrowth[[k]]\n  changes<-list();b<-models$bls\n  for(i in seq_len(nrow(b)-1L)){z<-productivity(as.numeric(b$outputIndexOriginalToken[i]),as.numeric(b$outputIndexOriginalToken[i+1]),as.numeric(b$hoursIndexOriginalToken[i]),as.numeric(b$hoursIndexOriginalToken[i+1]));g<-growth(as.numeric(b$productivityIndexOriginalToken[i]),as.numeric(b$productivityIndexOriginalToken[i+1]),4);changes[[i]]<-as.data.frame(c(list(start=b$quarter[i],end=b$quarter[i+1]),z,list(publishedProductivityPercent=g$percentChange,publishedAnnualizedPercent=g$annualizedPercent)),stringsAsFactors=FALSE)}\n  write<-function(name,rows)write.csv(rows,file.path(out,name),row.names=FALSE,na='',fileEncoding='UTF-8')\n  selected<-head(unique(models$person$unit),12);p<-models$person[models$person$unit%in%selected,];trajectories<-data.frame(unit=p$unit,year=p$time,nominalUSDPerHourExact=as.numeric(p$wageCentsOriginal)/100,stringsAsFactors=FALSE)\n  write('metrics.csv',data.frame(metric=names(metrics),value=as.numeric(unlist(metrics))));write('country-indexes.csv',do.call(rbind,country));write('wage-frames.csv',do.call(rbind,frames));write('bls-changes.csv',do.call(rbind,changes));write('first12-trajectories.csv',trajectories);invisible(metrics)\n}\nif(sys.nframe()==0L){args<-commandArgs(trailingOnly=TRUE);folder<-if(length(args)>=1)args[1]else'econ22-sources';out<-if(length(args)>=2)args[2]else'econ22-r-results';options(digits=17);metrics<-full_source(folder,out);cat('metrics:',length(metrics),'\\noutput directory:',out,'\\n')}\n"
          },
          {
            "file": "econ22-fixed-support.R",
            "sha256": "d4d63e1ad02017f20884b5932458dbde6013e0c2e560a4a9922a13d080a59fa1",
            "codeText": "# Run fixed drivers from the extracted bundle root. No packages or network required.\nsource('econ22-reproduce.R',encoding='UTF-8')\nexample <- function(api,variant) {\n  if(api=='rebase'){v<-if(variant=='invalid')c(0,1)else if(variant=='gap')c(80,NA,120)else c(80,100,120);z<-rebase(v);return(list(metrics=list(rows=length(z),defined=sum(!is.na(z)),last=tail(z,1)),x=seq_along(z)-1,y=z,xlabel='Position',ylabel='Rebased index'))}\n  if(api=='growth'){end<-if(variant=='quarterly')90 else 120;z<-growth(100,end,if(variant=='quarterly')4 else 1);return(list(metrics=z,x=c(0,1),y=c(100,end),xlabel='Date',ylabel='Supplied level'))}\n  if(api=='composition'){rows<-if(variant=='noCommon')data.frame(id=c('A','B'),before=c(10,NA),after=c(NA,20))else data.frame(id=c('A','B','C'),before=c(10,100,NA),after=c(11,NA,1));z<-composition(rows);metrics<-z[c('beforeAvailableMean','afterAvailableMean','availableMeanChange','commonWithinChange','commonUnits','exactDecompositionResidual')];return(list(metrics=metrics,x=c(0,1),y=c(z$beforeAvailableMean,z$afterAvailableMean),xlabel='Date',ylabel='Available mean / assumed units'))}\n  if(api=='productivity'){o<-if(variant=='contraction')90 else 103;h<-if(variant=='contraction')80 else 101;z<-productivity(100,o,100,h);return(list(metrics=z,x=c(0,1),y=c(1,z$productivityGross),xlabel='Date',ylabel='Output per hour / initial=1'))}\n  if(api=='measurement'){n<-if(variant=='zero')0 else 391035000000;d<-if(variant=='zero')0 else 164000;z<-measurement(n,d);return(list(metrics=list(ratio=z$ratio,denominatorZero=as.integer(d==0),sourceApproximate=as.integer(variant!='zero')),x=0,y=z$ratio,xlabel='Ratio position',ylabel='USD / approximate endpoint FTE'))}\n  models<-load_sources('econ22-sources');z<-realdata(models,variant)\n  if(variant=='country')return(list(metrics=list(sourceRows=z$originalCount,first=as.numeric(head(models$housing$nominal,1)),last=as.numeric(tail(models$housing$nominal,1)),percentChange=z$growth$percentChange),x=seq_along(z$rebased)-1,y=z$rebased,xlabel='Quarter position / original calendar',ylabel='Nominal housing / first=100'))\n  if(variant=='person')return(list(metrics=z[c('sourceUnits','beforeAvailableUnits','afterAvailableUnits','commonUnits','availableMeanChange','commonWithinChange','exactDecompositionResidual')],x=c(1976,1980),y=c(z$beforeAvailableMean,z$afterAvailableMean),xlabel='Observed wave',ylabel='Nominal USD/hour / available mean'))\n  if(variant=='company')return(list(metrics=list(sales2023=models$company$revenue2023,sales2024=models$company$revenue2024,proxy=z$ratio,proxyGrowth=NA_real_),x=c(2023,2024),y=c(models$company$revenue2023,models$company$revenue2024)/1e6,xlabel='Fiscal year',ylabel='Nominal USD millions'))\n  stop('fixed example name required')\n}\nrun <- function(api,variant,output) {\n  dir.create(output,recursive=TRUE,showWarnings=FALSE);z<-example(api,variant);metrics<-data.frame(metric=names(z$metrics),value=as.numeric(unlist(z$metrics)),stringsAsFactors=FALSE)\n  write.csv(metrics,file.path(output,'summary.csv'),row.names=FALSE,na='',fileEncoding='UTF-8');write.csv(data.frame(x=z$x,y=z$y),file.path(output,'plot-points.csv'),row.names=FALSE,na='',fileEncoding='UTF-8');print(metrics,row.names=FALSE)\n  good<-is.finite(z$x)&is.finite(z$y)\n  if(any(good)){svg(file.path(output,'plot.svg'),width=640/96,height=360/96,pointsize=10);par(mar=c(4.5,5.8,2,1));plot(z$x,z$y,type='o',pch=16,cex=.7,col='#355c72',xlab=z$xlabel,ylab=z$ylabel,cex.axis=.85,cex.lab=.9);grid(col='#d5dde1');dev.off();cat('plotProduced: TRUE\\n')}else cat('plotProduced: FALSE; undefined values retained\\n')\n}\n"
          }
        ],
        "inputFiles": [],
        "returnCode": 0,
        "expectedFailure": false,
        "stdout": "                      metric                 value\n                 outputGross   0.90000000000000002\n                  hoursGross   0.80000000000000004\n           productivityGross   1.12500000000000000\n               outputPercent  -9.99999999999999822\n                hoursPercent -19.99999999999999645\n         productivityPercent  12.50000000000000000\n  differenceOfPercentGrowths   9.99999999999999822\n exactGrowthIdentityResidual   0.00000000000000000\nplotProduced: TRUE\n",
        "stderr": "During startup - Warning messages:\n1: Setting LC_COLLATE=C.UTF-8 failed \n2: Setting LC_CTYPE=C.UTF-8 failed \n3: Setting LC_MONETARY=C.UTF-8 failed \n4: Setting LC_TIME=C.UTF-8 failed \n",
        "seconds": 0.28100000001722947,
        "summary": {
          "outputGross": "0.9",
          "hoursGross": "0.8",
          "productivityGross": "1.125",
          "outputPercent": "-10",
          "hoursPercent": "-20",
          "productivityPercent": "12.5",
          "differenceOfPercentGrowths": "10",
          "exactGrowthIdentityResidual": "0"
        },
        "plotPoints": [
          {
            "x": "0",
            "y": "1"
          },
          {
            "x": "1",
            "y": "1.125"
          }
        ],
        "plotFile": "econ22-fixed-results/productivity-contraction-r/plot.svg",
        "plotSHA256": "dd1371078bb171e96a52486ba5554eba88348271d229e19f11f9f50dfc4c9fca",
        "scope": "Actually executed fixed example. Current browser controls are calculated separately by JavaScript. Base-R outputs use finite precision; Python outputs use exact fractions.",
        "summaryFile": "econ22-fixed-results/productivity-contraction-r/summary.csv",
        "summarySHA256": "0a6cb1c5ae5c872bc736b7068680e9192d934dacf63444ea2cd1233768fe5cbc",
        "plotPointsFile": "econ22-fixed-results/productivity-contraction-r/plot-points.csv",
        "plotPointsSHA256": "5938784c34db9592d82a9d7d28b5dc1a05fc230659800e89ef3629de230c57eb"
      }
    }
  },
  "measurement": {
    "python": {
      "default": {
        "api": "measurement",
        "variant": "default",
        "language": "python",
        "codeFile": "econ22-code/measurement-default.py",
        "codeSHA256": "053a264db2cf5e2cf546bb1e75027cbcf356a17775bf270c34be0fe7f9a45178",
        "codeText": "# Fixed stated example, separate from current web controls.\nfrom pathlib import Path\nimport importlib.util,sys\nroot=Path(__file__).resolve().parents[1]\nspec=importlib.util.spec_from_file_location('fixed_support',root/'econ22-fixed-support.py')\nsupport=importlib.util.module_from_spec(spec);spec.loader.exec_module(support)\ntry:support.run('measurement','default',sys.argv[1]if len(sys.argv)>1 else root/'econ22-fixed-results/measurement-default-python')\nexcept ValueError as error:\n print('Rejected declared input: '+str(error),file=sys.stderr);sys.exit(2)\n",
        "supportFiles": [
          {
            "file": "econ22-reproduce.py",
            "sha256": "cc5631d9dfea963b64349bb28d18b69ad3caf15a15162ec6cea786a36e18de48",
            "codeText": "#!/usr/bin/env python3\n\"\"\"ECON22 public reproduction: Python standard library, exact Fraction arithmetic.\nRun: python econ22-reproduce.py --source-dir econ22-sources --output-dir econ22-python-results\nOriginal CSV inputs are read only. Output is a new chosen directory.\nThese are descriptive arithmetic and explicitly assumed examples, not causal estimates.\n\"\"\"\nfrom fractions import Fraction as Q\nfrom pathlib import Path\nfrom collections import defaultdict\nimport argparse,csv,json\n\ndef number(x):\n if x is None:raise ValueError('missing numeric token')\n return Q(str(x))\ndef rebase(values,base=0,scale='100'):\n v=[None if x is None else number(x)for x in values];s=number(scale)\n if not v or not 0<=base<len(v)or v[base]is None or v[base]<=0 or s<=0:raise ValueError('positive observed base/scale required')\n return [None if x is None else s*x/v[base]for x in v]\ndef growth(start,end,periods=1):\n a,b=number(start),number(end)\n if a<=0 or b<0 or not isinstance(periods,int)or not 1<=periods<=12:raise ValueError('growth domain')\n g=b/a;return dict(gross=g,percentChange=(g-1)*100,annualizedGross=g**periods,annualizedPercent=(g**periods-1)*100)\ndef composition(rows):\n seen=set();data=[]\n for r in rows:\n  identifier=str(r['id']);weight=number(r.get('weight','1'))\n  if identifier in seen or weight<0:raise ValueError('unique units/nonnegative fixed weights required')\n  seen.add(identifier);data.append(dict(id=identifier,weight=weight,before=None if r['before']is None else number(r['before']),after=None if r['after']is None else number(r['after'])))\n if not data:raise ValueError('nonempty frame required')\n valid=[r for r in data if r['weight']>0];b=[r for r in valid if r['before']is not None];a=[r for r in valid if r['after']is not None];c=[r for r in valid if r['before']is not None and r['after']is not None]\n def mean(rs,k):\n  mass=sum((r['weight']for r in rs),Q(0));return sum((r[k]*r['weight']for r in rs),Q(0))/mass if mass else None\n mb,ma,cb,ca=mean(b,'before'),mean(a,'after'),mean(c,'before'),mean(c,'after');full=all(x is not None for x in [mb,ma,cb,ca]);change=ma-mb if mb is not None and ma is not None else None\n return dict(sourceUnits=len(data),beforeAvailableUnits=len(b),afterAvailableUnits=len(a),commonUnits=len(c),beforeAvailableMean=mb,afterAvailableMean=ma,beforeCommonMean=cb,afterCommonMean=ca,availableMeanChange=change,commonWithinChange=ca-cb if full else None,afterFrameShift=ma-ca if full else None,beforeFrameShift=cb-mb if full else None,exactDecompositionResidual=change-((ma-ca)+(ca-cb)+(cb-mb))if full else None)\ndef productivity(output0,output1,hours0,hours1):\n o0,o1,h0,h1=map(number,[output0,output1,hours0,hours1])\n if min(o0,o1,h0,h1)<=0:raise ValueError('positive output and hours required')\n go,gh=o1/o0,h1/h0;gp=go/gh\n return dict(outputGross=go,hoursGross=gh,productivityGross=gp,outputPercent=(go-1)*100,hoursPercent=(gh-1)*100,productivityPercent=(gp-1)*100,differenceOfPercentGrowths=(go-gh)*100,exactGrowthIdentityResidual=gp-go/gh)\ndef measurement(numerator,denominator,lower=None,upper=None):\n n,d=number(numerator),number(denominator)\n if d<0:raise ValueError('nonnegative denominator required')\n interval=None\n if lower is not None or upper is not None:\n  lo,hi=number(lower),number(upper)\n  if lo<=0 or hi<lo:raise ValueError('ordered positive scenario bounds')\n  interval=sorted([n/lo,n/hi])\n return dict(ratio=n/d if d else None,denominatorScenarioInterval=interval)\ndef read_csv(folder,name):\n with (folder/name).open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))\ndef load_sources(folder):\n h=read_csv(folder,'actual180-KOR-housing-nominal-real-indexes.csv');b=read_csv(folder,'actual38-US-nonfarm-output-hours-productivity-indexes.csv');p=read_csv(folder,'actual10839-person-wage-panel-original-and-prior-derived-fields.csv');c=read_csv(folder,'actual3-Apple-revenue-and-approximate-periodend-FTE-facts.csv')\n company={}\n for r in c:\n  value=Q(r['originalToken'].replace(',',''))\n  company[('revenue'+r['fiscalYear'])if r['fact']=='consolidated total net sales'else'endpointFTE2024']=value*1000000 if r['fact']=='consolidated total net sales'else value\n return dict(housing=h,bls=b,person=p,company=company)\ndef person_comparison(models,before=1976,after=1980):\n if before not in [1976,1978,1980]or after not in [1976,1978,1980]or before>=after:raise ValueError('ordered observed waves required')\n units=defaultdict(dict)\n for r in models['person']:\n  year=int(r['time'])\n  if year in units[r['unit']]:raise ValueError('duplicate original unit-wave')\n  token=r['wageCentsOriginal'];units[r['unit']][year]=None if token in ['.','','NA']else number(token)/100\n return composition([dict(id=k,before=v[before],after=v[after])for k,v in units.items()])\ndef realdata(models,kind):\n if kind=='country':\n  rows=models['housing'];return dict(originalCount=len(rows),growth=growth(rows[0]['nominal'],rows[-1]['nominal']),rebased=rebase([r['nominal']for r in rows]))\n if kind=='person':return person_comparison(models)\n if kind=='company':\n  c=models['company'];return dict(revenueGrowth=growth(c['revenue2023'],c['revenue2024']),ratio=measurement(c['revenue2024'],c['endpointFTE2024'])['ratio'],proxyGrowth=None)\n raise ValueError('actual case required')\ndef encode(v):\n if isinstance(v,Q):return str(v)\n if isinstance(v,dict):return{k:encode(x)for k,x in v.items()}\n if isinstance(v,(list,tuple)):return[encode(x)for x in v]\n return v\ndef write_csv(path,rows):\n with path.open('w',encoding='utf8',newline='')as f:\n  writer=csv.DictWriter(f,fieldnames=list(rows[0]));writer.writeheader();writer.writerows([{k:''if v is None else str(v)for k,v in r.items()}for r in rows])\ndef full_source(folder,out):\n out.mkdir(parents=True,exist_ok=True);models=load_sources(folder);metrics={};country=[];frames=[]\n for source in ['housing','bls']:\n  data=models[source];columns=['nominal','real']if source=='housing'else['outputIndexOriginalToken','hoursIndexOriginalToken','productivityIndexOriginalToken']\n  for col in columns:\n   values=[r[col]for r in data];rb=rebase(values);g=growth(values[0],values[-1])\n   for k,v in g.items():metrics[source+':'+col+':'+k]=v\n   quarter_base=next((i for i,r in enumerate(data)if r['quarter']=='2010-Q1'),None)if source=='housing'else None\n   qb=rebase(values,quarter_base)if quarter_base is not None else[None]*len(values)\n   country.extend(dict(source=source,series=col,row=i+1,quarter=r['quarter'],originalToken=r[col],rebasedFirst100Exact=rb[i],rebased2010Q1Exact=qb[i])for i,r in enumerate(data))\n for a,b in [(1976,1978),(1978,1980),(1976,1980)]:\n  z=person_comparison(models,a,b);frames.append(dict(before=a,after=b,elapsedYears=b-a,**z));metrics.update({f'person:{a}:{b}:{k}':v for k,v in z.items()})\n c=realdata(models,'company');metrics['company:proxy']=c['ratio'];metrics['company:proxyGrowth']=None;metrics.update({'company:sales:'+k:v for k,v in c['revenueGrowth'].items()})\n changes=[]\n for a,b in zip(models['bls'],models['bls'][1:]):\n  z=productivity(a['outputIndexOriginalToken'],b['outputIndexOriginalToken'],a['hoursIndexOriginalToken'],b['hoursIndexOriginalToken']);g=growth(a['productivityIndexOriginalToken'],b['productivityIndexOriginalToken'],4)\n  changes.append(dict(start=a['quarter'],end=b['quarter'],**z,publishedProductivityPercent=g['percentChange'],publishedAnnualizedPercent=g['annualizedPercent']))\n selected=list(dict.fromkeys(r['unit']for r in models['person']))[:12]\n trajectories=[dict(unit=r['unit'],year=r['time'],nominalUSDPerHourExact=None if r['wageCentsOriginal']in['.','','NA']else number(r['wageCentsOriginal'])/100)for r in models['person']if r['unit']in selected]\n write_csv(out/'metrics.csv',[dict(metric=k,value=v)for k,v in metrics.items()]);write_csv(out/'country-indexes.csv',country);write_csv(out/'wage-frames.csv',frames);write_csv(out/'bls-changes.csv',changes);write_csv(out/'first12-trajectories.csv',trajectories)\n (out/'full-results.json').write_text(json.dumps(encode(dict(metrics=metrics,frames=frames,company=c)),ensure_ascii=False,indent=2)+'\\n',encoding='utf8');return{f.name:len(read_csv(out,f.name))for f in out.glob('*.csv')}\nif __name__=='__main__':\n parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--source-dir',type=Path,default=Path(__file__).parent/'econ22-sources');parser.add_argument('--output-dir',type=Path,default=Path(__file__).parent/'econ22-python-results');args=parser.parse_args();print(json.dumps(full_source(args.source_dir,args.output_dir)))\n"
          },
          {
            "file": "econ22-fixed-support.py",
            "sha256": "deb4273c9c713e16c2f5e5d3525932ae34753f348731a3b26a4babff015c2fd6",
            "codeText": "\"\"\"Public fixed-example support. Requires only Python standard library and econ22-reproduce.py.\nFixed examples are separate from current browser inputs. Missing values remain None.\n\"\"\"\nfrom pathlib import Path\nfrom fractions import Fraction as Q\nimport importlib.util,json,csv,html,math\nROOT=Path(__file__).resolve().parent\nspec=importlib.util.spec_from_file_location('econ22_public',ROOT/'econ22-reproduce.py');M=importlib.util.module_from_spec(spec);spec.loader.exec_module(M)\n\ndef example(api,variant):\n if api=='rebase':\n  values=[0,1]if variant=='invalid'else[80,None,120]if variant=='gap'else[80,100,120];z=M.rebase(values);return dict(rows=len(z),defined=sum(x is not None for x in z),last=z[-1]),list(enumerate(z)),'Position','Rebased index'\n if api=='growth':\n  end=90 if variant=='quarterly'else 120;z=M.growth(100,end,4 if variant=='quarterly'else 1);return z,[(0,Q(100)),(1,Q(end))],'Date','Supplied level'\n if api=='composition':\n  rows=[dict(id='A',before=10,after=None),dict(id='B',before=None,after=20)]if variant=='noCommon'else[dict(id='A',before=10,after=11),dict(id='B',before=100,after=None),dict(id='C',before=None,after=1)];z=M.composition(rows);metrics={k:z[k]for k in ['beforeAvailableMean','afterAvailableMean','availableMeanChange','commonWithinChange','commonUnits','exactDecompositionResidual']};return metrics,[(0,z['beforeAvailableMean']),(1,z['afterAvailableMean'])],'Date','Available mean / assumed units'\n if api=='productivity':\n  o,h=(90,80)if variant=='contraction'else(103,101);z=M.productivity(100,o,100,h);return z,[(0,Q(1)),(1,z['productivityGross'])],'Date','Output per hour / initial=1'\n if api=='measurement':\n  n,d=(0,0)if variant=='zero'else(391035000000,164000);z=M.measurement(n,d);return dict(ratio=z['ratio'],denominatorZero=int(d==0),sourceApproximate=int(variant!='zero')),[(0,z['ratio'])],'Ratio position','USD / approximate endpoint FTE'\n models=M.load_sources(ROOT/'econ22-sources');z=M.realdata(models,variant)\n if variant=='country':return dict(sourceRows=z['originalCount'],first=Q(models['housing'][0]['nominal']),last=Q(models['housing'][-1]['nominal']),percentChange=z['growth']['percentChange']),list(enumerate(z['rebased'])),'Quarter position / original calendar','Nominal housing / first=100'\n if variant=='person':return{k:z[k]for k in ['sourceUnits','beforeAvailableUnits','afterAvailableUnits','commonUnits','availableMeanChange','commonWithinChange','exactDecompositionResidual']},[(1976,z['beforeAvailableMean']),(1980,z['afterAvailableMean'])],'Observed wave','Nominal USD/hour / available mean'\n if variant=='company':return dict(sales2023=models['company']['revenue2023'],sales2024=models['company']['revenue2024'],proxy=z['ratio'],proxyGrowth=None),[(2023,models['company']['revenue2023']/1000000),(2024,models['company']['revenue2024']/1000000)],'Fiscal year','Nominal USD millions'\n raise ValueError('fixed example name required')\n\ndef svg(points,xlabel,ylabel):\n good=[(float(x),float(y))for x,y in points if y is not None]\n if not good:return None\n if any(not math.isfinite(x)or not math.isfinite(y)for x,y in good):raise ValueError('outside finite plotting range')\n w,h,L,R,T,B=640,360,90,22,28,54;xmin=min(float(p[0])for p in points);xmax=max(float(p[0])for p in points);ymin=min(y for x,y in good);ymax=max(y for x,y in good)\n pad=max(1,abs(ymin)*.05)if ymin==ymax else(ymax-ymin)*.08;ymin-=pad;ymax+=pad\n X=lambda x:(L+w-R)/2 if xmax==xmin else L+(float(x)-xmin)/(xmax-xmin)*(w-L-R);Y=lambda y:T+(ymax-float(y))/(ymax-ymin)*(h-T-B);esc=html.escape\n s=f'<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"640\" height=\"360\" viewBox=\"0 0 640 360\" role=\"img\" aria-label=\"{esc(xlabel+\"; \"+ylabel)}\"><title>{esc(xlabel+\"; \"+ylabel)}</title><rect width=\"640\" height=\"360\" fill=\"white\"/><g font-family=\"sans-serif\" font-size=\"13\" fill=\"#222\">'\n for i in range(4):\n  v=ymin+(ymax-ymin)*i/3;y=Y(v);s+=f'<line x1=\"{L}\" x2=\"{w-R}\" y1=\"{y}\" y2=\"{y}\" stroke=\"#ccd6db\"/><text x=\"{L-7}\" y=\"{y+4}\" text-anchor=\"end\">{v:.4g}</text>'\n for x,anchor in([(xmin,'middle')]if xmin==xmax else[(xmin,'start'),(xmax,'end')]):s+=f'<text x=\"{X(x)}\" y=\"{h-B+24}\" text-anchor=\"{anchor}\">{x:g}</text>'\n last=None\n for x,y in points:\n  if y is None:last=None;continue\n  a,b=X(x),Y(y)\n  if last:s+=f'<line x1=\"{last[0]}\" y1=\"{last[1]}\" x2=\"{a}\" y2=\"{b}\" stroke=\"#355c72\" stroke-width=\"2\"/>'\n  s+=f'<circle cx=\"{a}\" cy=\"{b}\" r=\"3\" fill=\"#934b34\"><title>{esc(str(x)+\": \"+str(y))}</title></circle>';last=(a,b)\n return s+f'<text x=\"{L}\" y=\"16\">{esc(ylabel)}</text><text x=\"{w-R}\" y=\"{h-6}\" text-anchor=\"end\">{esc(xlabel)}</text></g></svg>'\n\ndef run(api,variant,output):\n out=Path(output);out.mkdir(parents=True,exist_ok=True);metrics,points,x,y=example(api,variant);encoded=M.encode(metrics);(out/'summary.json').write_text(json.dumps(encoded,indent=2)+'\\n',encoding='utf8')\n M.write_csv(out/'summary.csv',[dict(metric=k,value=v)for k,v in metrics.items()]);M.write_csv(out/'plot-points.csv',[dict(x=a,y=b)for a,b in points]);graphic=svg(points,x,y)\n if graphic is not None:(out/'plot.svg').write_text(graphic,encoding='utf8')\n print(json.dumps(dict(api=api,variant=variant,metrics=encoded,plotProduced=graphic is not None),ensure_ascii=False))\n"
          }
        ],
        "inputFiles": [],
        "returnCode": 0,
        "expectedFailure": false,
        "stdout": "{\"api\": \"measurement\", \"variant\": \"default\", \"metrics\": {\"ratio\": \"97758750/41\", \"denominatorZero\": 0, \"sourceApproximate\": 1}, \"plotProduced\": true}\n",
        "stderr": "",
        "seconds": 0.125,
        "summary": {
          "ratio": "97758750/41",
          "denominatorZero": "0",
          "sourceApproximate": "1"
        },
        "plotPoints": [
          {
            "x": "0",
            "y": "97758750/41"
          }
        ],
        "plotFile": "econ22-fixed-results/measurement-default-python/plot.svg",
        "plotSHA256": "f60cf6db6a38685e2183a337cc2530b998fd3b4bedfe6d9e9305c6c667efbc9e",
        "scope": "Actually executed fixed example. Current browser controls are calculated separately by JavaScript. Base-R outputs use finite precision; Python outputs use exact fractions.",
        "summaryFile": "econ22-fixed-results/measurement-default-python/summary.csv",
        "summarySHA256": "3c5664509146052addeaa48ddbf0208d8a7180ea5d7e6cc6720b403a58ee846c",
        "plotPointsFile": "econ22-fixed-results/measurement-default-python/plot-points.csv",
        "plotPointsSHA256": "61fc8b2f1fc5719a9bf8cc02892011401e1cf207d14d6efa69544c219b231f79"
      },
      "zero": {
        "api": "measurement",
        "variant": "zero",
        "language": "python",
        "codeFile": "econ22-code/measurement-zero.py",
        "codeSHA256": "c9627ee8a1658c610056477e1796dc3cf39ee6d9204a11eaf61483df68ef1bc4",
        "codeText": "# Fixed stated example, separate from current web controls.\nfrom pathlib import Path\nimport importlib.util,sys\nroot=Path(__file__).resolve().parents[1]\nspec=importlib.util.spec_from_file_location('fixed_support',root/'econ22-fixed-support.py')\nsupport=importlib.util.module_from_spec(spec);spec.loader.exec_module(support)\ntry:support.run('measurement','zero',sys.argv[1]if len(sys.argv)>1 else root/'econ22-fixed-results/measurement-zero-python')\nexcept ValueError as error:\n print('Rejected declared input: '+str(error),file=sys.stderr);sys.exit(2)\n",
        "supportFiles": [
          {
            "file": "econ22-reproduce.py",
            "sha256": "cc5631d9dfea963b64349bb28d18b69ad3caf15a15162ec6cea786a36e18de48",
            "codeText": "#!/usr/bin/env python3\n\"\"\"ECON22 public reproduction: Python standard library, exact Fraction arithmetic.\nRun: python econ22-reproduce.py --source-dir econ22-sources --output-dir econ22-python-results\nOriginal CSV inputs are read only. Output is a new chosen directory.\nThese are descriptive arithmetic and explicitly assumed examples, not causal estimates.\n\"\"\"\nfrom fractions import Fraction as Q\nfrom pathlib import Path\nfrom collections import defaultdict\nimport argparse,csv,json\n\ndef number(x):\n if x is None:raise ValueError('missing numeric token')\n return Q(str(x))\ndef rebase(values,base=0,scale='100'):\n v=[None if x is None else number(x)for x in values];s=number(scale)\n if not v or not 0<=base<len(v)or v[base]is None or v[base]<=0 or s<=0:raise ValueError('positive observed base/scale required')\n return [None if x is None else s*x/v[base]for x in v]\ndef growth(start,end,periods=1):\n a,b=number(start),number(end)\n if a<=0 or b<0 or not isinstance(periods,int)or not 1<=periods<=12:raise ValueError('growth domain')\n g=b/a;return dict(gross=g,percentChange=(g-1)*100,annualizedGross=g**periods,annualizedPercent=(g**periods-1)*100)\ndef composition(rows):\n seen=set();data=[]\n for r in rows:\n  identifier=str(r['id']);weight=number(r.get('weight','1'))\n  if identifier in seen or weight<0:raise ValueError('unique units/nonnegative fixed weights required')\n  seen.add(identifier);data.append(dict(id=identifier,weight=weight,before=None if r['before']is None else number(r['before']),after=None if r['after']is None else number(r['after'])))\n if not data:raise ValueError('nonempty frame required')\n valid=[r for r in data if r['weight']>0];b=[r for r in valid if r['before']is not None];a=[r for r in valid if r['after']is not None];c=[r for r in valid if r['before']is not None and r['after']is not None]\n def mean(rs,k):\n  mass=sum((r['weight']for r in rs),Q(0));return sum((r[k]*r['weight']for r in rs),Q(0))/mass if mass else None\n mb,ma,cb,ca=mean(b,'before'),mean(a,'after'),mean(c,'before'),mean(c,'after');full=all(x is not None for x in [mb,ma,cb,ca]);change=ma-mb if mb is not None and ma is not None else None\n return dict(sourceUnits=len(data),beforeAvailableUnits=len(b),afterAvailableUnits=len(a),commonUnits=len(c),beforeAvailableMean=mb,afterAvailableMean=ma,beforeCommonMean=cb,afterCommonMean=ca,availableMeanChange=change,commonWithinChange=ca-cb if full else None,afterFrameShift=ma-ca if full else None,beforeFrameShift=cb-mb if full else None,exactDecompositionResidual=change-((ma-ca)+(ca-cb)+(cb-mb))if full else None)\ndef productivity(output0,output1,hours0,hours1):\n o0,o1,h0,h1=map(number,[output0,output1,hours0,hours1])\n if min(o0,o1,h0,h1)<=0:raise ValueError('positive output and hours required')\n go,gh=o1/o0,h1/h0;gp=go/gh\n return dict(outputGross=go,hoursGross=gh,productivityGross=gp,outputPercent=(go-1)*100,hoursPercent=(gh-1)*100,productivityPercent=(gp-1)*100,differenceOfPercentGrowths=(go-gh)*100,exactGrowthIdentityResidual=gp-go/gh)\ndef measurement(numerator,denominator,lower=None,upper=None):\n n,d=number(numerator),number(denominator)\n if d<0:raise ValueError('nonnegative denominator required')\n interval=None\n if lower is not None or upper is not None:\n  lo,hi=number(lower),number(upper)\n  if lo<=0 or hi<lo:raise ValueError('ordered positive scenario bounds')\n  interval=sorted([n/lo,n/hi])\n return dict(ratio=n/d if d else None,denominatorScenarioInterval=interval)\ndef read_csv(folder,name):\n with (folder/name).open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))\ndef load_sources(folder):\n h=read_csv(folder,'actual180-KOR-housing-nominal-real-indexes.csv');b=read_csv(folder,'actual38-US-nonfarm-output-hours-productivity-indexes.csv');p=read_csv(folder,'actual10839-person-wage-panel-original-and-prior-derived-fields.csv');c=read_csv(folder,'actual3-Apple-revenue-and-approximate-periodend-FTE-facts.csv')\n company={}\n for r in c:\n  value=Q(r['originalToken'].replace(',',''))\n  company[('revenue'+r['fiscalYear'])if r['fact']=='consolidated total net sales'else'endpointFTE2024']=value*1000000 if r['fact']=='consolidated total net sales'else value\n return dict(housing=h,bls=b,person=p,company=company)\ndef person_comparison(models,before=1976,after=1980):\n if before not in [1976,1978,1980]or after not in [1976,1978,1980]or before>=after:raise ValueError('ordered observed waves required')\n units=defaultdict(dict)\n for r in models['person']:\n  year=int(r['time'])\n  if year in units[r['unit']]:raise ValueError('duplicate original unit-wave')\n  token=r['wageCentsOriginal'];units[r['unit']][year]=None if token in ['.','','NA']else number(token)/100\n return composition([dict(id=k,before=v[before],after=v[after])for k,v in units.items()])\ndef realdata(models,kind):\n if kind=='country':\n  rows=models['housing'];return dict(originalCount=len(rows),growth=growth(rows[0]['nominal'],rows[-1]['nominal']),rebased=rebase([r['nominal']for r in rows]))\n if kind=='person':return person_comparison(models)\n if kind=='company':\n  c=models['company'];return dict(revenueGrowth=growth(c['revenue2023'],c['revenue2024']),ratio=measurement(c['revenue2024'],c['endpointFTE2024'])['ratio'],proxyGrowth=None)\n raise ValueError('actual case required')\ndef encode(v):\n if isinstance(v,Q):return str(v)\n if isinstance(v,dict):return{k:encode(x)for k,x in v.items()}\n if isinstance(v,(list,tuple)):return[encode(x)for x in v]\n return v\ndef write_csv(path,rows):\n with path.open('w',encoding='utf8',newline='')as f:\n  writer=csv.DictWriter(f,fieldnames=list(rows[0]));writer.writeheader();writer.writerows([{k:''if v is None else str(v)for k,v in r.items()}for r in rows])\ndef full_source(folder,out):\n out.mkdir(parents=True,exist_ok=True);models=load_sources(folder);metrics={};country=[];frames=[]\n for source in ['housing','bls']:\n  data=models[source];columns=['nominal','real']if source=='housing'else['outputIndexOriginalToken','hoursIndexOriginalToken','productivityIndexOriginalToken']\n  for col in columns:\n   values=[r[col]for r in data];rb=rebase(values);g=growth(values[0],values[-1])\n   for k,v in g.items():metrics[source+':'+col+':'+k]=v\n   quarter_base=next((i for i,r in enumerate(data)if r['quarter']=='2010-Q1'),None)if source=='housing'else None\n   qb=rebase(values,quarter_base)if quarter_base is not None else[None]*len(values)\n   country.extend(dict(source=source,series=col,row=i+1,quarter=r['quarter'],originalToken=r[col],rebasedFirst100Exact=rb[i],rebased2010Q1Exact=qb[i])for i,r in enumerate(data))\n for a,b in [(1976,1978),(1978,1980),(1976,1980)]:\n  z=person_comparison(models,a,b);frames.append(dict(before=a,after=b,elapsedYears=b-a,**z));metrics.update({f'person:{a}:{b}:{k}':v for k,v in z.items()})\n c=realdata(models,'company');metrics['company:proxy']=c['ratio'];metrics['company:proxyGrowth']=None;metrics.update({'company:sales:'+k:v for k,v in c['revenueGrowth'].items()})\n changes=[]\n for a,b in zip(models['bls'],models['bls'][1:]):\n  z=productivity(a['outputIndexOriginalToken'],b['outputIndexOriginalToken'],a['hoursIndexOriginalToken'],b['hoursIndexOriginalToken']);g=growth(a['productivityIndexOriginalToken'],b['productivityIndexOriginalToken'],4)\n  changes.append(dict(start=a['quarter'],end=b['quarter'],**z,publishedProductivityPercent=g['percentChange'],publishedAnnualizedPercent=g['annualizedPercent']))\n selected=list(dict.fromkeys(r['unit']for r in models['person']))[:12]\n trajectories=[dict(unit=r['unit'],year=r['time'],nominalUSDPerHourExact=None if r['wageCentsOriginal']in['.','','NA']else number(r['wageCentsOriginal'])/100)for r in models['person']if r['unit']in selected]\n write_csv(out/'metrics.csv',[dict(metric=k,value=v)for k,v in metrics.items()]);write_csv(out/'country-indexes.csv',country);write_csv(out/'wage-frames.csv',frames);write_csv(out/'bls-changes.csv',changes);write_csv(out/'first12-trajectories.csv',trajectories)\n (out/'full-results.json').write_text(json.dumps(encode(dict(metrics=metrics,frames=frames,company=c)),ensure_ascii=False,indent=2)+'\\n',encoding='utf8');return{f.name:len(read_csv(out,f.name))for f in out.glob('*.csv')}\nif __name__=='__main__':\n parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--source-dir',type=Path,default=Path(__file__).parent/'econ22-sources');parser.add_argument('--output-dir',type=Path,default=Path(__file__).parent/'econ22-python-results');args=parser.parse_args();print(json.dumps(full_source(args.source_dir,args.output_dir)))\n"
          },
          {
            "file": "econ22-fixed-support.py",
            "sha256": "deb4273c9c713e16c2f5e5d3525932ae34753f348731a3b26a4babff015c2fd6",
            "codeText": "\"\"\"Public fixed-example support. Requires only Python standard library and econ22-reproduce.py.\nFixed examples are separate from current browser inputs. Missing values remain None.\n\"\"\"\nfrom pathlib import Path\nfrom fractions import Fraction as Q\nimport importlib.util,json,csv,html,math\nROOT=Path(__file__).resolve().parent\nspec=importlib.util.spec_from_file_location('econ22_public',ROOT/'econ22-reproduce.py');M=importlib.util.module_from_spec(spec);spec.loader.exec_module(M)\n\ndef example(api,variant):\n if api=='rebase':\n  values=[0,1]if variant=='invalid'else[80,None,120]if variant=='gap'else[80,100,120];z=M.rebase(values);return dict(rows=len(z),defined=sum(x is not None for x in z),last=z[-1]),list(enumerate(z)),'Position','Rebased index'\n if api=='growth':\n  end=90 if variant=='quarterly'else 120;z=M.growth(100,end,4 if variant=='quarterly'else 1);return z,[(0,Q(100)),(1,Q(end))],'Date','Supplied level'\n if api=='composition':\n  rows=[dict(id='A',before=10,after=None),dict(id='B',before=None,after=20)]if variant=='noCommon'else[dict(id='A',before=10,after=11),dict(id='B',before=100,after=None),dict(id='C',before=None,after=1)];z=M.composition(rows);metrics={k:z[k]for k in ['beforeAvailableMean','afterAvailableMean','availableMeanChange','commonWithinChange','commonUnits','exactDecompositionResidual']};return metrics,[(0,z['beforeAvailableMean']),(1,z['afterAvailableMean'])],'Date','Available mean / assumed units'\n if api=='productivity':\n  o,h=(90,80)if variant=='contraction'else(103,101);z=M.productivity(100,o,100,h);return z,[(0,Q(1)),(1,z['productivityGross'])],'Date','Output per hour / initial=1'\n if api=='measurement':\n  n,d=(0,0)if variant=='zero'else(391035000000,164000);z=M.measurement(n,d);return dict(ratio=z['ratio'],denominatorZero=int(d==0),sourceApproximate=int(variant!='zero')),[(0,z['ratio'])],'Ratio position','USD / approximate endpoint FTE'\n models=M.load_sources(ROOT/'econ22-sources');z=M.realdata(models,variant)\n if variant=='country':return dict(sourceRows=z['originalCount'],first=Q(models['housing'][0]['nominal']),last=Q(models['housing'][-1]['nominal']),percentChange=z['growth']['percentChange']),list(enumerate(z['rebased'])),'Quarter position / original calendar','Nominal housing / first=100'\n if variant=='person':return{k:z[k]for k in ['sourceUnits','beforeAvailableUnits','afterAvailableUnits','commonUnits','availableMeanChange','commonWithinChange','exactDecompositionResidual']},[(1976,z['beforeAvailableMean']),(1980,z['afterAvailableMean'])],'Observed wave','Nominal USD/hour / available mean'\n if variant=='company':return dict(sales2023=models['company']['revenue2023'],sales2024=models['company']['revenue2024'],proxy=z['ratio'],proxyGrowth=None),[(2023,models['company']['revenue2023']/1000000),(2024,models['company']['revenue2024']/1000000)],'Fiscal year','Nominal USD millions'\n raise ValueError('fixed example name required')\n\ndef svg(points,xlabel,ylabel):\n good=[(float(x),float(y))for x,y in points if y is not None]\n if not good:return None\n if any(not math.isfinite(x)or not math.isfinite(y)for x,y in good):raise ValueError('outside finite plotting range')\n w,h,L,R,T,B=640,360,90,22,28,54;xmin=min(float(p[0])for p in points);xmax=max(float(p[0])for p in points);ymin=min(y for x,y in good);ymax=max(y for x,y in good)\n pad=max(1,abs(ymin)*.05)if ymin==ymax else(ymax-ymin)*.08;ymin-=pad;ymax+=pad\n X=lambda x:(L+w-R)/2 if xmax==xmin else L+(float(x)-xmin)/(xmax-xmin)*(w-L-R);Y=lambda y:T+(ymax-float(y))/(ymax-ymin)*(h-T-B);esc=html.escape\n s=f'<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"640\" height=\"360\" viewBox=\"0 0 640 360\" role=\"img\" aria-label=\"{esc(xlabel+\"; \"+ylabel)}\"><title>{esc(xlabel+\"; \"+ylabel)}</title><rect width=\"640\" height=\"360\" fill=\"white\"/><g font-family=\"sans-serif\" font-size=\"13\" fill=\"#222\">'\n for i in range(4):\n  v=ymin+(ymax-ymin)*i/3;y=Y(v);s+=f'<line x1=\"{L}\" x2=\"{w-R}\" y1=\"{y}\" y2=\"{y}\" stroke=\"#ccd6db\"/><text x=\"{L-7}\" y=\"{y+4}\" text-anchor=\"end\">{v:.4g}</text>'\n for x,anchor in([(xmin,'middle')]if xmin==xmax else[(xmin,'start'),(xmax,'end')]):s+=f'<text x=\"{X(x)}\" y=\"{h-B+24}\" text-anchor=\"{anchor}\">{x:g}</text>'\n last=None\n for x,y in points:\n  if y is None:last=None;continue\n  a,b=X(x),Y(y)\n  if last:s+=f'<line x1=\"{last[0]}\" y1=\"{last[1]}\" x2=\"{a}\" y2=\"{b}\" stroke=\"#355c72\" stroke-width=\"2\"/>'\n  s+=f'<circle cx=\"{a}\" cy=\"{b}\" r=\"3\" fill=\"#934b34\"><title>{esc(str(x)+\": \"+str(y))}</title></circle>';last=(a,b)\n return s+f'<text x=\"{L}\" y=\"16\">{esc(ylabel)}</text><text x=\"{w-R}\" y=\"{h-6}\" text-anchor=\"end\">{esc(xlabel)}</text></g></svg>'\n\ndef run(api,variant,output):\n out=Path(output);out.mkdir(parents=True,exist_ok=True);metrics,points,x,y=example(api,variant);encoded=M.encode(metrics);(out/'summary.json').write_text(json.dumps(encoded,indent=2)+'\\n',encoding='utf8')\n M.write_csv(out/'summary.csv',[dict(metric=k,value=v)for k,v in metrics.items()]);M.write_csv(out/'plot-points.csv',[dict(x=a,y=b)for a,b in points]);graphic=svg(points,x,y)\n if graphic is not None:(out/'plot.svg').write_text(graphic,encoding='utf8')\n print(json.dumps(dict(api=api,variant=variant,metrics=encoded,plotProduced=graphic is not None),ensure_ascii=False))\n"
          }
        ],
        "inputFiles": [],
        "returnCode": 0,
        "expectedFailure": false,
        "stdout": "{\"api\": \"measurement\", \"variant\": \"zero\", \"metrics\": {\"ratio\": null, \"denominatorZero\": 1, \"sourceApproximate\": 0}, \"plotProduced\": false}\n",
        "stderr": "",
        "seconds": 0.10999999998603016,
        "summary": {
          "ratio": null,
          "denominatorZero": "1",
          "sourceApproximate": "0"
        },
        "plotPoints": [
          {
            "x": "0",
            "y": ""
          }
        ],
        "plotFile": null,
        "plotSHA256": null,
        "scope": "Actually executed fixed example. Current browser controls are calculated separately by JavaScript. Base-R outputs use finite precision; Python outputs use exact fractions.",
        "summaryFile": "econ22-fixed-results/measurement-zero-python/summary.csv",
        "summarySHA256": "ce49191118d31ff06e7d3712716293584a7fbb7fd7782bcdb4c188425e8cf96e",
        "plotPointsFile": "econ22-fixed-results/measurement-zero-python/plot-points.csv",
        "plotPointsSHA256": "4a300fe00878daea1c55e5546fd8c4cffedeca66b5f864234bbfc0d166dccee2"
      }
    },
    "r": {
      "default": {
        "api": "measurement",
        "variant": "default",
        "language": "r",
        "codeFile": "econ22-code/measurement-default.R",
        "codeSHA256": "9b3c88d02f639f2cfee6b8869aaceffa2194cf3090fe229dba0c0520a5a144f2",
        "codeText": "# Run from the extracted textbook bundle root.\nsource('econ22-fixed-support.R',encoding='UTF-8')\noptions(digits=17)\nargs<-commandArgs(trailingOnly=TRUE)\noutput<-if(length(args))args[1]else'econ22-fixed-results/measurement-default-r'\ntryCatch(run('measurement','default',output),error=function(error){cat('Rejected declared input: ',conditionMessage(error),'\\n',file=stderr());quit(status=2)})\n",
        "supportFiles": [
          {
            "file": "econ22-reproduce.R",
            "sha256": "2db22759696a6f288479189f44026f265536a54cdc2e72952c1e91af13661480",
            "codeText": "# ECON22 independent public base-R reproduction; binary64 approximations.\n# Run: Rscript --vanilla --encoding=UTF-8 econ22-reproduce.R [source-dir] [output-dir]\n# Source CSVs are never overwritten. No packages or network required.\nrebase <- function(values, base=1L, scale=100) {\n  if (length(base)!=1L || !is.finite(base) || base!=as.integer(base) || !length(values) || base<1 || base>length(values) || is.na(values[base]) || values[base]<=0 || !is.finite(scale) || scale<=0) stop('positive observed base/scale required')\n  scale*values/values[base]\n}\ngrowth <- function(start,end,periods=1L) {\n  if (start<=0 || end<0 || periods<1 || periods>12 || periods!=as.integer(periods)) stop('growth domain')\n  gross<-end/start;list(gross=gross,percentChange=(gross-1)*100,annualizedGross=gross^periods,annualizedPercent=(gross^periods-1)*100)\n}\ncomposition <- function(rows) {\n  if (!nrow(rows) || anyDuplicated(rows$id)) stop('nonempty unique units required')\n  if (!'weight'%in%names(rows)) rows$weight<-rep(1,nrow(rows))\n  if (any(!is.finite(rows$weight)) || any(rows$weight<0)) stop('nonnegative fixed weights required')\n  valid<-rows$weight>0;b<-valid&!is.na(rows$before);a<-valid&!is.na(rows$after);common<-b&a\n  avg<-function(mask,column)if(sum(rows$weight[mask])>0)sum(rows[[column]][mask]*rows$weight[mask])/sum(rows$weight[mask])else NA_real_\n  mb<-avg(b,'before');ma<-avg(a,'after');cb<-avg(common,'before');ca<-avg(common,'after');full<-all(is.finite(c(mb,ma,cb,ca)))\n  list(sourceUnits=nrow(rows),beforeAvailableUnits=sum(b),afterAvailableUnits=sum(a),commonUnits=sum(common),beforeAvailableMean=mb,afterAvailableMean=ma,beforeCommonMean=cb,afterCommonMean=ca,availableMeanChange=ma-mb,commonWithinChange=if(full)ca-cb else NA_real_,afterFrameShift=if(full)ma-ca else NA_real_,beforeFrameShift=if(full)cb-mb else NA_real_,exactDecompositionResidual=if(full)(ma-mb)-((ma-ca)+(ca-cb)+(cb-mb))else NA_real_)\n}\nproductivity <- function(output0,output1,hours0,hours1) {\n  if(any(c(output0,output1,hours0,hours1)<=0))stop('positive output and hours required')\n  go<-output1/output0;gh<-hours1/hours0;gp<-go/gh\n  list(outputGross=go,hoursGross=gh,productivityGross=gp,outputPercent=(go-1)*100,hoursPercent=(gh-1)*100,productivityPercent=(gp-1)*100,differenceOfPercentGrowths=(go-gh)*100,exactGrowthIdentityResidual=gp-go/gh)\n}\nmeasurement <- function(numerator,denominator,lower=NA_real_,upper=NA_real_) {\n  if(denominator<0)stop('nonnegative denominator required');interval<-NULL\n  if(!is.na(lower)||!is.na(upper)){if(any(!is.finite(c(lower,upper)))||lower<=0||upper<lower)stop('ordered positive scenario bounds');interval<-sort(c(numerator/lower,numerator/upper))}\n  list(ratio=if(denominator>0)numerator/denominator else NA_real_,denominatorScenarioInterval=interval)\n}\nload_sources <- function(folder) {\n  read<-function(file)read.csv(file.path(folder,file),stringsAsFactors=FALSE,check.names=FALSE,colClasses='character',na.strings=c('NA','','.'))\n  h<-read('actual180-KOR-housing-nominal-real-indexes.csv');b<-read('actual38-US-nonfarm-output-hours-productivity-indexes.csv');p<-read('actual10839-person-wage-panel-original-and-prior-derived-fields.csv');c<-read('actual3-Apple-revenue-and-approximate-periodend-FTE-facts.csv')\n  company<-list();for(i in seq_len(nrow(c))){value<-as.numeric(gsub(',','',c$originalToken[i],fixed=TRUE));if(c$fact[i]=='consolidated total net sales')company[[paste0('revenue',c$fiscalYear[i])]]<-value*1e6 else company$endpointFTE2024<-value}\n  list(housing=h,bls=b,person=p,company=company)\n}\nperson_comparison <- function(models,before=1976L,after=1980L) {\n  if(!before%in%c(1976,1978,1980)||!after%in%c(1976,1978,1980)||before>=after)stop('ordered observed waves required')\n  p<-models$person;if(anyDuplicated(paste(p$unit,p$time,sep=':')))stop('duplicate original unit-wave')\n  ids<-unique(p$unit);rows<-data.frame(id=ids,before=as.numeric(p$wageCentsOriginal[match(paste(ids,before),paste(p$unit,p$time))])/100,after=as.numeric(p$wageCentsOriginal[match(paste(ids,after),paste(p$unit,p$time))])/100,stringsAsFactors=FALSE)\n  composition(rows)\n}\nrealdata <- function(models,kind) {\n  if(kind=='country'){r<-models$housing;return(list(originalCount=nrow(r),growth=growth(as.numeric(r$nominal[1]),as.numeric(tail(r$nominal,1))),rebased=rebase(as.numeric(r$nominal))))}\n  if(kind=='person')return(person_comparison(models))\n  if(kind=='company'){c<-models$company;return(list(revenueGrowth=growth(c$revenue2023,c$revenue2024),ratio=measurement(c$revenue2024,c$endpointFTE2024)$ratio,proxyGrowth=NA_real_))}\n  stop('actual case required')\n}\nfull_source <- function(folder,out) {\n  dir.create(out,recursive=TRUE,showWarnings=FALSE);models<-load_sources(folder);metrics<-list();country<-list();frames<-list()\n  for(source in c('housing','bls')){data<-models[[source]];columns<-if(source=='housing')c('nominal','real')else c('outputIndexOriginalToken','hoursIndexOriginalToken','productivityIndexOriginalToken')\n    for(col in columns){values<-as.numeric(data[[col]]);rb<-rebase(values);g<-growth(values[1],tail(values,1));for(k in names(g))metrics[[paste(source,col,k,sep=':')]]<-g[[k]];quarterBase<-if(source=='housing')match('2010-Q1',data$quarter)else NA_integer_;qb<-if(!is.na(quarterBase))rebase(values,quarterBase)else rep(NA_real_,length(values));country[[length(country)+1]]<-data.frame(source=source,series=col,row=seq_len(nrow(data)),quarter=data$quarter,originalToken=data[[col]],rebasedFirst100Exact=rb,rebased2010Q1Exact=qb,stringsAsFactors=FALSE)}}\n  for(pair in list(c(1976,1978),c(1978,1980),c(1976,1980))){a<-pair[1];b<-pair[2];z<-person_comparison(models,a,b);frames[[length(frames)+1]]<-as.data.frame(c(list(before=a,after=b,elapsedYears=b-a),z),stringsAsFactors=FALSE);for(k in names(z))metrics[[paste('person',a,b,k,sep=':')]]<-z[[k]]}\n  company<-realdata(models,'company');metrics[['company:proxy']]<-company$ratio;metrics[['company:proxyGrowth']]<-NA_real_;for(k in names(company$revenueGrowth))metrics[[paste('company:sales',k,sep=':')]]<-company$revenueGrowth[[k]]\n  changes<-list();b<-models$bls\n  for(i in seq_len(nrow(b)-1L)){z<-productivity(as.numeric(b$outputIndexOriginalToken[i]),as.numeric(b$outputIndexOriginalToken[i+1]),as.numeric(b$hoursIndexOriginalToken[i]),as.numeric(b$hoursIndexOriginalToken[i+1]));g<-growth(as.numeric(b$productivityIndexOriginalToken[i]),as.numeric(b$productivityIndexOriginalToken[i+1]),4);changes[[i]]<-as.data.frame(c(list(start=b$quarter[i],end=b$quarter[i+1]),z,list(publishedProductivityPercent=g$percentChange,publishedAnnualizedPercent=g$annualizedPercent)),stringsAsFactors=FALSE)}\n  write<-function(name,rows)write.csv(rows,file.path(out,name),row.names=FALSE,na='',fileEncoding='UTF-8')\n  selected<-head(unique(models$person$unit),12);p<-models$person[models$person$unit%in%selected,];trajectories<-data.frame(unit=p$unit,year=p$time,nominalUSDPerHourExact=as.numeric(p$wageCentsOriginal)/100,stringsAsFactors=FALSE)\n  write('metrics.csv',data.frame(metric=names(metrics),value=as.numeric(unlist(metrics))));write('country-indexes.csv',do.call(rbind,country));write('wage-frames.csv',do.call(rbind,frames));write('bls-changes.csv',do.call(rbind,changes));write('first12-trajectories.csv',trajectories);invisible(metrics)\n}\nif(sys.nframe()==0L){args<-commandArgs(trailingOnly=TRUE);folder<-if(length(args)>=1)args[1]else'econ22-sources';out<-if(length(args)>=2)args[2]else'econ22-r-results';options(digits=17);metrics<-full_source(folder,out);cat('metrics:',length(metrics),'\\noutput directory:',out,'\\n')}\n"
          },
          {
            "file": "econ22-fixed-support.R",
            "sha256": "d4d63e1ad02017f20884b5932458dbde6013e0c2e560a4a9922a13d080a59fa1",
            "codeText": "# Run fixed drivers from the extracted bundle root. No packages or network required.\nsource('econ22-reproduce.R',encoding='UTF-8')\nexample <- function(api,variant) {\n  if(api=='rebase'){v<-if(variant=='invalid')c(0,1)else if(variant=='gap')c(80,NA,120)else c(80,100,120);z<-rebase(v);return(list(metrics=list(rows=length(z),defined=sum(!is.na(z)),last=tail(z,1)),x=seq_along(z)-1,y=z,xlabel='Position',ylabel='Rebased index'))}\n  if(api=='growth'){end<-if(variant=='quarterly')90 else 120;z<-growth(100,end,if(variant=='quarterly')4 else 1);return(list(metrics=z,x=c(0,1),y=c(100,end),xlabel='Date',ylabel='Supplied level'))}\n  if(api=='composition'){rows<-if(variant=='noCommon')data.frame(id=c('A','B'),before=c(10,NA),after=c(NA,20))else data.frame(id=c('A','B','C'),before=c(10,100,NA),after=c(11,NA,1));z<-composition(rows);metrics<-z[c('beforeAvailableMean','afterAvailableMean','availableMeanChange','commonWithinChange','commonUnits','exactDecompositionResidual')];return(list(metrics=metrics,x=c(0,1),y=c(z$beforeAvailableMean,z$afterAvailableMean),xlabel='Date',ylabel='Available mean / assumed units'))}\n  if(api=='productivity'){o<-if(variant=='contraction')90 else 103;h<-if(variant=='contraction')80 else 101;z<-productivity(100,o,100,h);return(list(metrics=z,x=c(0,1),y=c(1,z$productivityGross),xlabel='Date',ylabel='Output per hour / initial=1'))}\n  if(api=='measurement'){n<-if(variant=='zero')0 else 391035000000;d<-if(variant=='zero')0 else 164000;z<-measurement(n,d);return(list(metrics=list(ratio=z$ratio,denominatorZero=as.integer(d==0),sourceApproximate=as.integer(variant!='zero')),x=0,y=z$ratio,xlabel='Ratio position',ylabel='USD / approximate endpoint FTE'))}\n  models<-load_sources('econ22-sources');z<-realdata(models,variant)\n  if(variant=='country')return(list(metrics=list(sourceRows=z$originalCount,first=as.numeric(head(models$housing$nominal,1)),last=as.numeric(tail(models$housing$nominal,1)),percentChange=z$growth$percentChange),x=seq_along(z$rebased)-1,y=z$rebased,xlabel='Quarter position / original calendar',ylabel='Nominal housing / first=100'))\n  if(variant=='person')return(list(metrics=z[c('sourceUnits','beforeAvailableUnits','afterAvailableUnits','commonUnits','availableMeanChange','commonWithinChange','exactDecompositionResidual')],x=c(1976,1980),y=c(z$beforeAvailableMean,z$afterAvailableMean),xlabel='Observed wave',ylabel='Nominal USD/hour / available mean'))\n  if(variant=='company')return(list(metrics=list(sales2023=models$company$revenue2023,sales2024=models$company$revenue2024,proxy=z$ratio,proxyGrowth=NA_real_),x=c(2023,2024),y=c(models$company$revenue2023,models$company$revenue2024)/1e6,xlabel='Fiscal year',ylabel='Nominal USD millions'))\n  stop('fixed example name required')\n}\nrun <- function(api,variant,output) {\n  dir.create(output,recursive=TRUE,showWarnings=FALSE);z<-example(api,variant);metrics<-data.frame(metric=names(z$metrics),value=as.numeric(unlist(z$metrics)),stringsAsFactors=FALSE)\n  write.csv(metrics,file.path(output,'summary.csv'),row.names=FALSE,na='',fileEncoding='UTF-8');write.csv(data.frame(x=z$x,y=z$y),file.path(output,'plot-points.csv'),row.names=FALSE,na='',fileEncoding='UTF-8');print(metrics,row.names=FALSE)\n  good<-is.finite(z$x)&is.finite(z$y)\n  if(any(good)){svg(file.path(output,'plot.svg'),width=640/96,height=360/96,pointsize=10);par(mar=c(4.5,5.8,2,1));plot(z$x,z$y,type='o',pch=16,cex=.7,col='#355c72',xlab=z$xlabel,ylab=z$ylabel,cex.axis=.85,cex.lab=.9);grid(col='#d5dde1');dev.off();cat('plotProduced: TRUE\\n')}else cat('plotProduced: FALSE; undefined values retained\\n')\n}\n"
          }
        ],
        "inputFiles": [],
        "returnCode": 0,
        "expectedFailure": false,
        "stdout": "            metric              value\n             ratio 2384359.7560975607\n   denominatorZero       0.0000000000\n sourceApproximate       1.0000000000\nplotProduced: TRUE\n",
        "stderr": "During startup - Warning messages:\n1: Setting LC_COLLATE=C.UTF-8 failed \n2: Setting LC_CTYPE=C.UTF-8 failed \n3: Setting LC_MONETARY=C.UTF-8 failed \n4: Setting LC_TIME=C.UTF-8 failed \n",
        "seconds": 0.28100000001722947,
        "summary": {
          "ratio": "2384359.75609756",
          "denominatorZero": "0",
          "sourceApproximate": "1"
        },
        "plotPoints": [
          {
            "x": "0",
            "y": "2384359.75609756"
          }
        ],
        "plotFile": "econ22-fixed-results/measurement-default-r/plot.svg",
        "plotSHA256": "b705326af7125b096fae5c29372d8ced0ecf579a4b65f35f3c691efb31b0da8e",
        "scope": "Actually executed fixed example. Current browser controls are calculated separately by JavaScript. Base-R outputs use finite precision; Python outputs use exact fractions.",
        "summaryFile": "econ22-fixed-results/measurement-default-r/summary.csv",
        "summarySHA256": "412d5a956222de1c23a0b46f07c2b5ab1b97695374bf4f588a0c2d527d6c319b",
        "plotPointsFile": "econ22-fixed-results/measurement-default-r/plot-points.csv",
        "plotPointsSHA256": "c9735d5ba3d9454e9c1f8a24864ce7228d261e4b7bba253849857b2e41876c9a"
      },
      "zero": {
        "api": "measurement",
        "variant": "zero",
        "language": "r",
        "codeFile": "econ22-code/measurement-zero.R",
        "codeSHA256": "035839fd3640e281b9c70a60c22503e03ca0781bacd5589ed0528afdfac06b74",
        "codeText": "# Run from the extracted textbook bundle root.\nsource('econ22-fixed-support.R',encoding='UTF-8')\noptions(digits=17)\nargs<-commandArgs(trailingOnly=TRUE)\noutput<-if(length(args))args[1]else'econ22-fixed-results/measurement-zero-r'\ntryCatch(run('measurement','zero',output),error=function(error){cat('Rejected declared input: ',conditionMessage(error),'\\n',file=stderr());quit(status=2)})\n",
        "supportFiles": [
          {
            "file": "econ22-reproduce.R",
            "sha256": "2db22759696a6f288479189f44026f265536a54cdc2e72952c1e91af13661480",
            "codeText": "# ECON22 independent public base-R reproduction; binary64 approximations.\n# Run: Rscript --vanilla --encoding=UTF-8 econ22-reproduce.R [source-dir] [output-dir]\n# Source CSVs are never overwritten. No packages or network required.\nrebase <- function(values, base=1L, scale=100) {\n  if (length(base)!=1L || !is.finite(base) || base!=as.integer(base) || !length(values) || base<1 || base>length(values) || is.na(values[base]) || values[base]<=0 || !is.finite(scale) || scale<=0) stop('positive observed base/scale required')\n  scale*values/values[base]\n}\ngrowth <- function(start,end,periods=1L) {\n  if (start<=0 || end<0 || periods<1 || periods>12 || periods!=as.integer(periods)) stop('growth domain')\n  gross<-end/start;list(gross=gross,percentChange=(gross-1)*100,annualizedGross=gross^periods,annualizedPercent=(gross^periods-1)*100)\n}\ncomposition <- function(rows) {\n  if (!nrow(rows) || anyDuplicated(rows$id)) stop('nonempty unique units required')\n  if (!'weight'%in%names(rows)) rows$weight<-rep(1,nrow(rows))\n  if (any(!is.finite(rows$weight)) || any(rows$weight<0)) stop('nonnegative fixed weights required')\n  valid<-rows$weight>0;b<-valid&!is.na(rows$before);a<-valid&!is.na(rows$after);common<-b&a\n  avg<-function(mask,column)if(sum(rows$weight[mask])>0)sum(rows[[column]][mask]*rows$weight[mask])/sum(rows$weight[mask])else NA_real_\n  mb<-avg(b,'before');ma<-avg(a,'after');cb<-avg(common,'before');ca<-avg(common,'after');full<-all(is.finite(c(mb,ma,cb,ca)))\n  list(sourceUnits=nrow(rows),beforeAvailableUnits=sum(b),afterAvailableUnits=sum(a),commonUnits=sum(common),beforeAvailableMean=mb,afterAvailableMean=ma,beforeCommonMean=cb,afterCommonMean=ca,availableMeanChange=ma-mb,commonWithinChange=if(full)ca-cb else NA_real_,afterFrameShift=if(full)ma-ca else NA_real_,beforeFrameShift=if(full)cb-mb else NA_real_,exactDecompositionResidual=if(full)(ma-mb)-((ma-ca)+(ca-cb)+(cb-mb))else NA_real_)\n}\nproductivity <- function(output0,output1,hours0,hours1) {\n  if(any(c(output0,output1,hours0,hours1)<=0))stop('positive output and hours required')\n  go<-output1/output0;gh<-hours1/hours0;gp<-go/gh\n  list(outputGross=go,hoursGross=gh,productivityGross=gp,outputPercent=(go-1)*100,hoursPercent=(gh-1)*100,productivityPercent=(gp-1)*100,differenceOfPercentGrowths=(go-gh)*100,exactGrowthIdentityResidual=gp-go/gh)\n}\nmeasurement <- function(numerator,denominator,lower=NA_real_,upper=NA_real_) {\n  if(denominator<0)stop('nonnegative denominator required');interval<-NULL\n  if(!is.na(lower)||!is.na(upper)){if(any(!is.finite(c(lower,upper)))||lower<=0||upper<lower)stop('ordered positive scenario bounds');interval<-sort(c(numerator/lower,numerator/upper))}\n  list(ratio=if(denominator>0)numerator/denominator else NA_real_,denominatorScenarioInterval=interval)\n}\nload_sources <- function(folder) {\n  read<-function(file)read.csv(file.path(folder,file),stringsAsFactors=FALSE,check.names=FALSE,colClasses='character',na.strings=c('NA','','.'))\n  h<-read('actual180-KOR-housing-nominal-real-indexes.csv');b<-read('actual38-US-nonfarm-output-hours-productivity-indexes.csv');p<-read('actual10839-person-wage-panel-original-and-prior-derived-fields.csv');c<-read('actual3-Apple-revenue-and-approximate-periodend-FTE-facts.csv')\n  company<-list();for(i in seq_len(nrow(c))){value<-as.numeric(gsub(',','',c$originalToken[i],fixed=TRUE));if(c$fact[i]=='consolidated total net sales')company[[paste0('revenue',c$fiscalYear[i])]]<-value*1e6 else company$endpointFTE2024<-value}\n  list(housing=h,bls=b,person=p,company=company)\n}\nperson_comparison <- function(models,before=1976L,after=1980L) {\n  if(!before%in%c(1976,1978,1980)||!after%in%c(1976,1978,1980)||before>=after)stop('ordered observed waves required')\n  p<-models$person;if(anyDuplicated(paste(p$unit,p$time,sep=':')))stop('duplicate original unit-wave')\n  ids<-unique(p$unit);rows<-data.frame(id=ids,before=as.numeric(p$wageCentsOriginal[match(paste(ids,before),paste(p$unit,p$time))])/100,after=as.numeric(p$wageCentsOriginal[match(paste(ids,after),paste(p$unit,p$time))])/100,stringsAsFactors=FALSE)\n  composition(rows)\n}\nrealdata <- function(models,kind) {\n  if(kind=='country'){r<-models$housing;return(list(originalCount=nrow(r),growth=growth(as.numeric(r$nominal[1]),as.numeric(tail(r$nominal,1))),rebased=rebase(as.numeric(r$nominal))))}\n  if(kind=='person')return(person_comparison(models))\n  if(kind=='company'){c<-models$company;return(list(revenueGrowth=growth(c$revenue2023,c$revenue2024),ratio=measurement(c$revenue2024,c$endpointFTE2024)$ratio,proxyGrowth=NA_real_))}\n  stop('actual case required')\n}\nfull_source <- function(folder,out) {\n  dir.create(out,recursive=TRUE,showWarnings=FALSE);models<-load_sources(folder);metrics<-list();country<-list();frames<-list()\n  for(source in c('housing','bls')){data<-models[[source]];columns<-if(source=='housing')c('nominal','real')else c('outputIndexOriginalToken','hoursIndexOriginalToken','productivityIndexOriginalToken')\n    for(col in columns){values<-as.numeric(data[[col]]);rb<-rebase(values);g<-growth(values[1],tail(values,1));for(k in names(g))metrics[[paste(source,col,k,sep=':')]]<-g[[k]];quarterBase<-if(source=='housing')match('2010-Q1',data$quarter)else NA_integer_;qb<-if(!is.na(quarterBase))rebase(values,quarterBase)else rep(NA_real_,length(values));country[[length(country)+1]]<-data.frame(source=source,series=col,row=seq_len(nrow(data)),quarter=data$quarter,originalToken=data[[col]],rebasedFirst100Exact=rb,rebased2010Q1Exact=qb,stringsAsFactors=FALSE)}}\n  for(pair in list(c(1976,1978),c(1978,1980),c(1976,1980))){a<-pair[1];b<-pair[2];z<-person_comparison(models,a,b);frames[[length(frames)+1]]<-as.data.frame(c(list(before=a,after=b,elapsedYears=b-a),z),stringsAsFactors=FALSE);for(k in names(z))metrics[[paste('person',a,b,k,sep=':')]]<-z[[k]]}\n  company<-realdata(models,'company');metrics[['company:proxy']]<-company$ratio;metrics[['company:proxyGrowth']]<-NA_real_;for(k in names(company$revenueGrowth))metrics[[paste('company:sales',k,sep=':')]]<-company$revenueGrowth[[k]]\n  changes<-list();b<-models$bls\n  for(i in seq_len(nrow(b)-1L)){z<-productivity(as.numeric(b$outputIndexOriginalToken[i]),as.numeric(b$outputIndexOriginalToken[i+1]),as.numeric(b$hoursIndexOriginalToken[i]),as.numeric(b$hoursIndexOriginalToken[i+1]));g<-growth(as.numeric(b$productivityIndexOriginalToken[i]),as.numeric(b$productivityIndexOriginalToken[i+1]),4);changes[[i]]<-as.data.frame(c(list(start=b$quarter[i],end=b$quarter[i+1]),z,list(publishedProductivityPercent=g$percentChange,publishedAnnualizedPercent=g$annualizedPercent)),stringsAsFactors=FALSE)}\n  write<-function(name,rows)write.csv(rows,file.path(out,name),row.names=FALSE,na='',fileEncoding='UTF-8')\n  selected<-head(unique(models$person$unit),12);p<-models$person[models$person$unit%in%selected,];trajectories<-data.frame(unit=p$unit,year=p$time,nominalUSDPerHourExact=as.numeric(p$wageCentsOriginal)/100,stringsAsFactors=FALSE)\n  write('metrics.csv',data.frame(metric=names(metrics),value=as.numeric(unlist(metrics))));write('country-indexes.csv',do.call(rbind,country));write('wage-frames.csv',do.call(rbind,frames));write('bls-changes.csv',do.call(rbind,changes));write('first12-trajectories.csv',trajectories);invisible(metrics)\n}\nif(sys.nframe()==0L){args<-commandArgs(trailingOnly=TRUE);folder<-if(length(args)>=1)args[1]else'econ22-sources';out<-if(length(args)>=2)args[2]else'econ22-r-results';options(digits=17);metrics<-full_source(folder,out);cat('metrics:',length(metrics),'\\noutput directory:',out,'\\n')}\n"
          },
          {
            "file": "econ22-fixed-support.R",
            "sha256": "d4d63e1ad02017f20884b5932458dbde6013e0c2e560a4a9922a13d080a59fa1",
            "codeText": "# Run fixed drivers from the extracted bundle root. No packages or network required.\nsource('econ22-reproduce.R',encoding='UTF-8')\nexample <- function(api,variant) {\n  if(api=='rebase'){v<-if(variant=='invalid')c(0,1)else if(variant=='gap')c(80,NA,120)else c(80,100,120);z<-rebase(v);return(list(metrics=list(rows=length(z),defined=sum(!is.na(z)),last=tail(z,1)),x=seq_along(z)-1,y=z,xlabel='Position',ylabel='Rebased index'))}\n  if(api=='growth'){end<-if(variant=='quarterly')90 else 120;z<-growth(100,end,if(variant=='quarterly')4 else 1);return(list(metrics=z,x=c(0,1),y=c(100,end),xlabel='Date',ylabel='Supplied level'))}\n  if(api=='composition'){rows<-if(variant=='noCommon')data.frame(id=c('A','B'),before=c(10,NA),after=c(NA,20))else data.frame(id=c('A','B','C'),before=c(10,100,NA),after=c(11,NA,1));z<-composition(rows);metrics<-z[c('beforeAvailableMean','afterAvailableMean','availableMeanChange','commonWithinChange','commonUnits','exactDecompositionResidual')];return(list(metrics=metrics,x=c(0,1),y=c(z$beforeAvailableMean,z$afterAvailableMean),xlabel='Date',ylabel='Available mean / assumed units'))}\n  if(api=='productivity'){o<-if(variant=='contraction')90 else 103;h<-if(variant=='contraction')80 else 101;z<-productivity(100,o,100,h);return(list(metrics=z,x=c(0,1),y=c(1,z$productivityGross),xlabel='Date',ylabel='Output per hour / initial=1'))}\n  if(api=='measurement'){n<-if(variant=='zero')0 else 391035000000;d<-if(variant=='zero')0 else 164000;z<-measurement(n,d);return(list(metrics=list(ratio=z$ratio,denominatorZero=as.integer(d==0),sourceApproximate=as.integer(variant!='zero')),x=0,y=z$ratio,xlabel='Ratio position',ylabel='USD / approximate endpoint FTE'))}\n  models<-load_sources('econ22-sources');z<-realdata(models,variant)\n  if(variant=='country')return(list(metrics=list(sourceRows=z$originalCount,first=as.numeric(head(models$housing$nominal,1)),last=as.numeric(tail(models$housing$nominal,1)),percentChange=z$growth$percentChange),x=seq_along(z$rebased)-1,y=z$rebased,xlabel='Quarter position / original calendar',ylabel='Nominal housing / first=100'))\n  if(variant=='person')return(list(metrics=z[c('sourceUnits','beforeAvailableUnits','afterAvailableUnits','commonUnits','availableMeanChange','commonWithinChange','exactDecompositionResidual')],x=c(1976,1980),y=c(z$beforeAvailableMean,z$afterAvailableMean),xlabel='Observed wave',ylabel='Nominal USD/hour / available mean'))\n  if(variant=='company')return(list(metrics=list(sales2023=models$company$revenue2023,sales2024=models$company$revenue2024,proxy=z$ratio,proxyGrowth=NA_real_),x=c(2023,2024),y=c(models$company$revenue2023,models$company$revenue2024)/1e6,xlabel='Fiscal year',ylabel='Nominal USD millions'))\n  stop('fixed example name required')\n}\nrun <- function(api,variant,output) {\n  dir.create(output,recursive=TRUE,showWarnings=FALSE);z<-example(api,variant);metrics<-data.frame(metric=names(z$metrics),value=as.numeric(unlist(z$metrics)),stringsAsFactors=FALSE)\n  write.csv(metrics,file.path(output,'summary.csv'),row.names=FALSE,na='',fileEncoding='UTF-8');write.csv(data.frame(x=z$x,y=z$y),file.path(output,'plot-points.csv'),row.names=FALSE,na='',fileEncoding='UTF-8');print(metrics,row.names=FALSE)\n  good<-is.finite(z$x)&is.finite(z$y)\n  if(any(good)){svg(file.path(output,'plot.svg'),width=640/96,height=360/96,pointsize=10);par(mar=c(4.5,5.8,2,1));plot(z$x,z$y,type='o',pch=16,cex=.7,col='#355c72',xlab=z$xlabel,ylab=z$ylabel,cex.axis=.85,cex.lab=.9);grid(col='#d5dde1');dev.off();cat('plotProduced: TRUE\\n')}else cat('plotProduced: FALSE; undefined values retained\\n')\n}\n"
          }
        ],
        "inputFiles": [],
        "returnCode": 0,
        "expectedFailure": false,
        "stdout": "            metric value\n             ratio    NA\n   denominatorZero     1\n sourceApproximate     0\nplotProduced: FALSE; undefined values retained\n",
        "stderr": "During startup - Warning messages:\n1: Setting LC_COLLATE=C.UTF-8 failed \n2: Setting LC_CTYPE=C.UTF-8 failed \n3: Setting LC_MONETARY=C.UTF-8 failed \n4: Setting LC_TIME=C.UTF-8 failed \n",
        "seconds": 0.2809999999590218,
        "summary": {
          "ratio": null,
          "denominatorZero": "1",
          "sourceApproximate": "0"
        },
        "plotPoints": [
          {
            "x": "0",
            "y": ""
          }
        ],
        "plotFile": null,
        "plotSHA256": null,
        "scope": "Actually executed fixed example. Current browser controls are calculated separately by JavaScript. Base-R outputs use finite precision; Python outputs use exact fractions.",
        "summaryFile": "econ22-fixed-results/measurement-zero-r/summary.csv",
        "summarySHA256": "0c9e01d2cb9049a37be9227d32661433a8ff8eb71a602b5bcf30b04abbaa7c73",
        "plotPointsFile": "econ22-fixed-results/measurement-zero-r/plot-points.csv",
        "plotPointsSHA256": "4c46a10d60a06370ec1e05cc4b59d8e782ce1c872a5cb9f608d76dd519011d3e"
      }
    }
  },
  "realdata": {
    "python": {
      "country": {
        "api": "realdata",
        "variant": "country",
        "language": "python",
        "codeFile": "econ22-code/realdata-country.py",
        "codeSHA256": "8530eed9daa592f72417f17396b716e360a46595b11ce00d9f9741a13d0b120a",
        "codeText": "# Fixed stated example, separate from current web controls.\nfrom pathlib import Path\nimport importlib.util,sys\nroot=Path(__file__).resolve().parents[1]\nspec=importlib.util.spec_from_file_location('fixed_support',root/'econ22-fixed-support.py')\nsupport=importlib.util.module_from_spec(spec);spec.loader.exec_module(support)\ntry:support.run('realdata','country',sys.argv[1]if len(sys.argv)>1 else root/'econ22-fixed-results/realdata-country-python')\nexcept ValueError as error:\n print('Rejected declared input: '+str(error),file=sys.stderr);sys.exit(2)\n",
        "supportFiles": [
          {
            "file": "econ22-reproduce.py",
            "sha256": "cc5631d9dfea963b64349bb28d18b69ad3caf15a15162ec6cea786a36e18de48",
            "codeText": "#!/usr/bin/env python3\n\"\"\"ECON22 public reproduction: Python standard library, exact Fraction arithmetic.\nRun: python econ22-reproduce.py --source-dir econ22-sources --output-dir econ22-python-results\nOriginal CSV inputs are read only. Output is a new chosen directory.\nThese are descriptive arithmetic and explicitly assumed examples, not causal estimates.\n\"\"\"\nfrom fractions import Fraction as Q\nfrom pathlib import Path\nfrom collections import defaultdict\nimport argparse,csv,json\n\ndef number(x):\n if x is None:raise ValueError('missing numeric token')\n return Q(str(x))\ndef rebase(values,base=0,scale='100'):\n v=[None if x is None else number(x)for x in values];s=number(scale)\n if not v or not 0<=base<len(v)or v[base]is None or v[base]<=0 or s<=0:raise ValueError('positive observed base/scale required')\n return [None if x is None else s*x/v[base]for x in v]\ndef growth(start,end,periods=1):\n a,b=number(start),number(end)\n if a<=0 or b<0 or not isinstance(periods,int)or not 1<=periods<=12:raise ValueError('growth domain')\n g=b/a;return dict(gross=g,percentChange=(g-1)*100,annualizedGross=g**periods,annualizedPercent=(g**periods-1)*100)\ndef composition(rows):\n seen=set();data=[]\n for r in rows:\n  identifier=str(r['id']);weight=number(r.get('weight','1'))\n  if identifier in seen or weight<0:raise ValueError('unique units/nonnegative fixed weights required')\n  seen.add(identifier);data.append(dict(id=identifier,weight=weight,before=None if r['before']is None else number(r['before']),after=None if r['after']is None else number(r['after'])))\n if not data:raise ValueError('nonempty frame required')\n valid=[r for r in data if r['weight']>0];b=[r for r in valid if r['before']is not None];a=[r for r in valid if r['after']is not None];c=[r for r in valid if r['before']is not None and r['after']is not None]\n def mean(rs,k):\n  mass=sum((r['weight']for r in rs),Q(0));return sum((r[k]*r['weight']for r in rs),Q(0))/mass if mass else None\n mb,ma,cb,ca=mean(b,'before'),mean(a,'after'),mean(c,'before'),mean(c,'after');full=all(x is not None for x in [mb,ma,cb,ca]);change=ma-mb if mb is not None and ma is not None else None\n return dict(sourceUnits=len(data),beforeAvailableUnits=len(b),afterAvailableUnits=len(a),commonUnits=len(c),beforeAvailableMean=mb,afterAvailableMean=ma,beforeCommonMean=cb,afterCommonMean=ca,availableMeanChange=change,commonWithinChange=ca-cb if full else None,afterFrameShift=ma-ca if full else None,beforeFrameShift=cb-mb if full else None,exactDecompositionResidual=change-((ma-ca)+(ca-cb)+(cb-mb))if full else None)\ndef productivity(output0,output1,hours0,hours1):\n o0,o1,h0,h1=map(number,[output0,output1,hours0,hours1])\n if min(o0,o1,h0,h1)<=0:raise ValueError('positive output and hours required')\n go,gh=o1/o0,h1/h0;gp=go/gh\n return dict(outputGross=go,hoursGross=gh,productivityGross=gp,outputPercent=(go-1)*100,hoursPercent=(gh-1)*100,productivityPercent=(gp-1)*100,differenceOfPercentGrowths=(go-gh)*100,exactGrowthIdentityResidual=gp-go/gh)\ndef measurement(numerator,denominator,lower=None,upper=None):\n n,d=number(numerator),number(denominator)\n if d<0:raise ValueError('nonnegative denominator required')\n interval=None\n if lower is not None or upper is not None:\n  lo,hi=number(lower),number(upper)\n  if lo<=0 or hi<lo:raise ValueError('ordered positive scenario bounds')\n  interval=sorted([n/lo,n/hi])\n return dict(ratio=n/d if d else None,denominatorScenarioInterval=interval)\ndef read_csv(folder,name):\n with (folder/name).open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))\ndef load_sources(folder):\n h=read_csv(folder,'actual180-KOR-housing-nominal-real-indexes.csv');b=read_csv(folder,'actual38-US-nonfarm-output-hours-productivity-indexes.csv');p=read_csv(folder,'actual10839-person-wage-panel-original-and-prior-derived-fields.csv');c=read_csv(folder,'actual3-Apple-revenue-and-approximate-periodend-FTE-facts.csv')\n company={}\n for r in c:\n  value=Q(r['originalToken'].replace(',',''))\n  company[('revenue'+r['fiscalYear'])if r['fact']=='consolidated total net sales'else'endpointFTE2024']=value*1000000 if r['fact']=='consolidated total net sales'else value\n return dict(housing=h,bls=b,person=p,company=company)\ndef person_comparison(models,before=1976,after=1980):\n if before not in [1976,1978,1980]or after not in [1976,1978,1980]or before>=after:raise ValueError('ordered observed waves required')\n units=defaultdict(dict)\n for r in models['person']:\n  year=int(r['time'])\n  if year in units[r['unit']]:raise ValueError('duplicate original unit-wave')\n  token=r['wageCentsOriginal'];units[r['unit']][year]=None if token in ['.','','NA']else number(token)/100\n return composition([dict(id=k,before=v[before],after=v[after])for k,v in units.items()])\ndef realdata(models,kind):\n if kind=='country':\n  rows=models['housing'];return dict(originalCount=len(rows),growth=growth(rows[0]['nominal'],rows[-1]['nominal']),rebased=rebase([r['nominal']for r in rows]))\n if kind=='person':return person_comparison(models)\n if kind=='company':\n  c=models['company'];return dict(revenueGrowth=growth(c['revenue2023'],c['revenue2024']),ratio=measurement(c['revenue2024'],c['endpointFTE2024'])['ratio'],proxyGrowth=None)\n raise ValueError('actual case required')\ndef encode(v):\n if isinstance(v,Q):return str(v)\n if isinstance(v,dict):return{k:encode(x)for k,x in v.items()}\n if isinstance(v,(list,tuple)):return[encode(x)for x in v]\n return v\ndef write_csv(path,rows):\n with path.open('w',encoding='utf8',newline='')as f:\n  writer=csv.DictWriter(f,fieldnames=list(rows[0]));writer.writeheader();writer.writerows([{k:''if v is None else str(v)for k,v in r.items()}for r in rows])\ndef full_source(folder,out):\n out.mkdir(parents=True,exist_ok=True);models=load_sources(folder);metrics={};country=[];frames=[]\n for source in ['housing','bls']:\n  data=models[source];columns=['nominal','real']if source=='housing'else['outputIndexOriginalToken','hoursIndexOriginalToken','productivityIndexOriginalToken']\n  for col in columns:\n   values=[r[col]for r in data];rb=rebase(values);g=growth(values[0],values[-1])\n   for k,v in g.items():metrics[source+':'+col+':'+k]=v\n   quarter_base=next((i for i,r in enumerate(data)if r['quarter']=='2010-Q1'),None)if source=='housing'else None\n   qb=rebase(values,quarter_base)if quarter_base is not None else[None]*len(values)\n   country.extend(dict(source=source,series=col,row=i+1,quarter=r['quarter'],originalToken=r[col],rebasedFirst100Exact=rb[i],rebased2010Q1Exact=qb[i])for i,r in enumerate(data))\n for a,b in [(1976,1978),(1978,1980),(1976,1980)]:\n  z=person_comparison(models,a,b);frames.append(dict(before=a,after=b,elapsedYears=b-a,**z));metrics.update({f'person:{a}:{b}:{k}':v for k,v in z.items()})\n c=realdata(models,'company');metrics['company:proxy']=c['ratio'];metrics['company:proxyGrowth']=None;metrics.update({'company:sales:'+k:v for k,v in c['revenueGrowth'].items()})\n changes=[]\n for a,b in zip(models['bls'],models['bls'][1:]):\n  z=productivity(a['outputIndexOriginalToken'],b['outputIndexOriginalToken'],a['hoursIndexOriginalToken'],b['hoursIndexOriginalToken']);g=growth(a['productivityIndexOriginalToken'],b['productivityIndexOriginalToken'],4)\n  changes.append(dict(start=a['quarter'],end=b['quarter'],**z,publishedProductivityPercent=g['percentChange'],publishedAnnualizedPercent=g['annualizedPercent']))\n selected=list(dict.fromkeys(r['unit']for r in models['person']))[:12]\n trajectories=[dict(unit=r['unit'],year=r['time'],nominalUSDPerHourExact=None if r['wageCentsOriginal']in['.','','NA']else number(r['wageCentsOriginal'])/100)for r in models['person']if r['unit']in selected]\n write_csv(out/'metrics.csv',[dict(metric=k,value=v)for k,v in metrics.items()]);write_csv(out/'country-indexes.csv',country);write_csv(out/'wage-frames.csv',frames);write_csv(out/'bls-changes.csv',changes);write_csv(out/'first12-trajectories.csv',trajectories)\n (out/'full-results.json').write_text(json.dumps(encode(dict(metrics=metrics,frames=frames,company=c)),ensure_ascii=False,indent=2)+'\\n',encoding='utf8');return{f.name:len(read_csv(out,f.name))for f in out.glob('*.csv')}\nif __name__=='__main__':\n parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--source-dir',type=Path,default=Path(__file__).parent/'econ22-sources');parser.add_argument('--output-dir',type=Path,default=Path(__file__).parent/'econ22-python-results');args=parser.parse_args();print(json.dumps(full_source(args.source_dir,args.output_dir)))\n"
          },
          {
            "file": "econ22-fixed-support.py",
            "sha256": "deb4273c9c713e16c2f5e5d3525932ae34753f348731a3b26a4babff015c2fd6",
            "codeText": "\"\"\"Public fixed-example support. Requires only Python standard library and econ22-reproduce.py.\nFixed examples are separate from current browser inputs. Missing values remain None.\n\"\"\"\nfrom pathlib import Path\nfrom fractions import Fraction as Q\nimport importlib.util,json,csv,html,math\nROOT=Path(__file__).resolve().parent\nspec=importlib.util.spec_from_file_location('econ22_public',ROOT/'econ22-reproduce.py');M=importlib.util.module_from_spec(spec);spec.loader.exec_module(M)\n\ndef example(api,variant):\n if api=='rebase':\n  values=[0,1]if variant=='invalid'else[80,None,120]if variant=='gap'else[80,100,120];z=M.rebase(values);return dict(rows=len(z),defined=sum(x is not None for x in z),last=z[-1]),list(enumerate(z)),'Position','Rebased index'\n if api=='growth':\n  end=90 if variant=='quarterly'else 120;z=M.growth(100,end,4 if variant=='quarterly'else 1);return z,[(0,Q(100)),(1,Q(end))],'Date','Supplied level'\n if api=='composition':\n  rows=[dict(id='A',before=10,after=None),dict(id='B',before=None,after=20)]if variant=='noCommon'else[dict(id='A',before=10,after=11),dict(id='B',before=100,after=None),dict(id='C',before=None,after=1)];z=M.composition(rows);metrics={k:z[k]for k in ['beforeAvailableMean','afterAvailableMean','availableMeanChange','commonWithinChange','commonUnits','exactDecompositionResidual']};return metrics,[(0,z['beforeAvailableMean']),(1,z['afterAvailableMean'])],'Date','Available mean / assumed units'\n if api=='productivity':\n  o,h=(90,80)if variant=='contraction'else(103,101);z=M.productivity(100,o,100,h);return z,[(0,Q(1)),(1,z['productivityGross'])],'Date','Output per hour / initial=1'\n if api=='measurement':\n  n,d=(0,0)if variant=='zero'else(391035000000,164000);z=M.measurement(n,d);return dict(ratio=z['ratio'],denominatorZero=int(d==0),sourceApproximate=int(variant!='zero')),[(0,z['ratio'])],'Ratio position','USD / approximate endpoint FTE'\n models=M.load_sources(ROOT/'econ22-sources');z=M.realdata(models,variant)\n if variant=='country':return dict(sourceRows=z['originalCount'],first=Q(models['housing'][0]['nominal']),last=Q(models['housing'][-1]['nominal']),percentChange=z['growth']['percentChange']),list(enumerate(z['rebased'])),'Quarter position / original calendar','Nominal housing / first=100'\n if variant=='person':return{k:z[k]for k in ['sourceUnits','beforeAvailableUnits','afterAvailableUnits','commonUnits','availableMeanChange','commonWithinChange','exactDecompositionResidual']},[(1976,z['beforeAvailableMean']),(1980,z['afterAvailableMean'])],'Observed wave','Nominal USD/hour / available mean'\n if variant=='company':return dict(sales2023=models['company']['revenue2023'],sales2024=models['company']['revenue2024'],proxy=z['ratio'],proxyGrowth=None),[(2023,models['company']['revenue2023']/1000000),(2024,models['company']['revenue2024']/1000000)],'Fiscal year','Nominal USD millions'\n raise ValueError('fixed example name required')\n\ndef svg(points,xlabel,ylabel):\n good=[(float(x),float(y))for x,y in points if y is not None]\n if not good:return None\n if any(not math.isfinite(x)or not math.isfinite(y)for x,y in good):raise ValueError('outside finite plotting range')\n w,h,L,R,T,B=640,360,90,22,28,54;xmin=min(float(p[0])for p in points);xmax=max(float(p[0])for p in points);ymin=min(y for x,y in good);ymax=max(y for x,y in good)\n pad=max(1,abs(ymin)*.05)if ymin==ymax else(ymax-ymin)*.08;ymin-=pad;ymax+=pad\n X=lambda x:(L+w-R)/2 if xmax==xmin else L+(float(x)-xmin)/(xmax-xmin)*(w-L-R);Y=lambda y:T+(ymax-float(y))/(ymax-ymin)*(h-T-B);esc=html.escape\n s=f'<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"640\" height=\"360\" viewBox=\"0 0 640 360\" role=\"img\" aria-label=\"{esc(xlabel+\"; \"+ylabel)}\"><title>{esc(xlabel+\"; \"+ylabel)}</title><rect width=\"640\" height=\"360\" fill=\"white\"/><g font-family=\"sans-serif\" font-size=\"13\" fill=\"#222\">'\n for i in range(4):\n  v=ymin+(ymax-ymin)*i/3;y=Y(v);s+=f'<line x1=\"{L}\" x2=\"{w-R}\" y1=\"{y}\" y2=\"{y}\" stroke=\"#ccd6db\"/><text x=\"{L-7}\" y=\"{y+4}\" text-anchor=\"end\">{v:.4g}</text>'\n for x,anchor in([(xmin,'middle')]if xmin==xmax else[(xmin,'start'),(xmax,'end')]):s+=f'<text x=\"{X(x)}\" y=\"{h-B+24}\" text-anchor=\"{anchor}\">{x:g}</text>'\n last=None\n for x,y in points:\n  if y is None:last=None;continue\n  a,b=X(x),Y(y)\n  if last:s+=f'<line x1=\"{last[0]}\" y1=\"{last[1]}\" x2=\"{a}\" y2=\"{b}\" stroke=\"#355c72\" stroke-width=\"2\"/>'\n  s+=f'<circle cx=\"{a}\" cy=\"{b}\" r=\"3\" fill=\"#934b34\"><title>{esc(str(x)+\": \"+str(y))}</title></circle>';last=(a,b)\n return s+f'<text x=\"{L}\" y=\"16\">{esc(ylabel)}</text><text x=\"{w-R}\" y=\"{h-6}\" text-anchor=\"end\">{esc(xlabel)}</text></g></svg>'\n\ndef run(api,variant,output):\n out=Path(output);out.mkdir(parents=True,exist_ok=True);metrics,points,x,y=example(api,variant);encoded=M.encode(metrics);(out/'summary.json').write_text(json.dumps(encoded,indent=2)+'\\n',encoding='utf8')\n M.write_csv(out/'summary.csv',[dict(metric=k,value=v)for k,v in metrics.items()]);M.write_csv(out/'plot-points.csv',[dict(x=a,y=b)for a,b in points]);graphic=svg(points,x,y)\n if graphic is not None:(out/'plot.svg').write_text(graphic,encoding='utf8')\n print(json.dumps(dict(api=api,variant=variant,metrics=encoded,plotProduced=graphic is not None),ensure_ascii=False))\n"
          }
        ],
        "inputFiles": [
          {
            "file": "econ22-sources/actual10839-person-wage-panel-original-and-prior-derived-fields.csv",
            "sha256": "971fae34928d73c1d7e8234d5fc6dd38767d993d85adb5d5060f26a7aa781d0f"
          },
          {
            "file": "econ22-sources/actual180-KOR-housing-nominal-real-indexes.csv",
            "sha256": "0db7456684f2da50d1fd15aee53b24217849744188d4f96e1e055cbdd2992777"
          },
          {
            "file": "econ22-sources/actual3-Apple-revenue-and-approximate-periodend-FTE-facts.csv",
            "sha256": "897e50d6ef2d05d1e934aa5a8048dda3296a53bc705bb3239610edd9db0e2922"
          },
          {
            "file": "econ22-sources/actual38-US-nonfarm-output-hours-productivity-indexes.csv",
            "sha256": "265369587eea705ef3ef8124988ad02ac3150efdd14142b469ba042c2495588b"
          }
        ],
        "returnCode": 0,
        "expectedFailure": false,
        "stdout": "{\"api\": \"realdata\", \"variant\": \"country\", \"metrics\": {\"sourceRows\": 180, \"first\": \"231287/10000\", \"last\": \"57073/400\", \"percentChange\": \"119553800/231287\"}, \"plotProduced\": true}\n",
        "stderr": "",
        "seconds": 0.125,
        "summary": {
          "sourceRows": "180",
          "first": "231287/10000",
          "last": "57073/400",
          "percentChange": "119553800/231287"
        },
        "plotPoints": [
          {
            "x": "0",
            "y": "100"
          },
          {
            "x": "1",
            "y": "23977200/231287"
          },
          {
            "x": "2",
            "y": "24063400/231287"
          },
          {
            "x": "3",
            "y": "24654500/231287"
          },
          {
            "x": "4",
            "y": "25056700/231287"
          },
          {
            "x": "5",
            "y": "25465200/231287"
          },
          {
            "x": "6",
            "y": "26329900/231287"
          },
          {
            "x": "7",
            "y": "26147700/231287"
          },
          {
            "x": "8",
            "y": "26214000/231287"
          },
          {
            "x": "9",
            "y": "26476900/231287"
          },
          {
            "x": "10",
            "y": "27331700/231287"
          },
          {
            "x": "11",
            "y": "28546300/231287"
          },
          {
            "x": "12",
            "y": "1602800/12173"
          },
          {
            "x": "13",
            "y": "31730900/231287"
          },
          {
            "x": "14",
            "y": "32799600/231287"
          },
          {
            "x": "15",
            "y": "37700/259"
          },
          {
            "x": "16",
            "y": "35119100/231287"
          },
          {
            "x": "17",
            "y": "36210000/231287"
          },
          {
            "x": "18",
            "y": "36941900/231287"
          },
          {
            "x": "19",
            "y": "37374800/231287"
          },
          {
            "x": "20",
            "y": "37977300/231287"
          },
          {
            "x": "21",
            "y": "822800/4921"
          },
          {
            "x": "22",
            "y": "2069800/12173"
          },
          {
            "x": "23",
            "y": "5693700/33041"
          },
          {
            "x": "24",
            "y": "42379300/231287"
          },
          {
            "x": "25",
            "y": "41914300/231287"
          },
          {
            "x": "26",
            "y": "41597300/231287"
          },
          {
            "x": "27",
            "y": "41385900/231287"
          },
          {
            "x": "28",
            "y": "41089900/231287"
          },
          {
            "x": "29",
            "y": "41089900/231287"
          },
          {
            "x": "30",
            "y": "41808600/231287"
          },
          {
            "x": "31",
            "y": "2311700/12173"
          },
          {
            "x": "32",
            "y": "45803500/231287"
          },
          {
            "x": "33",
            "y": "48297700/231287"
          },
          {
            "x": "34",
            "y": "7138200/33041"
          },
          {
            "x": "35",
            "y": "50009700/231287"
          },
          {
            "x": "36",
            "y": "52081100/231287"
          },
          {
            "x": "37",
            "y": "56139400/231287"
          },
          {
            "x": "38",
            "y": "56287400/231287"
          },
          {
            "x": "39",
            "y": "8140700/33041"
          },
          {
            "x": "40",
            "y": "8590600/33041"
          },
          {
            "x": "41",
            "y": "1743500/6251"
          },
          {
            "x": "42",
            "y": "496000/1739"
          },
          {
            "x": "43",
            "y": "68842600/231287"
          },
          {
            "x": "44",
            "y": "70660300/231287"
          },
          {
            "x": "45",
            "y": "73154500/231287"
          },
          {
            "x": "46",
            "y": "1954300/6251"
          },
          {
            "x": "47",
            "y": "10024900/33041"
          },
          {
            "x": "48",
            "y": "9780300/33041"
          },
          {
            "x": "49",
            "y": "504900/1739"
          },
          {
            "x": "50",
            "y": "66094800/231287"
          },
          {
            "x": "51",
            "y": "65925700/231287"
          },
          {
            "x": "52",
            "y": "9363600/33041"
          },
          {
            "x": "53",
            "y": "9285100/33041"
          },
          {
            "x": "54",
            "y": "9161300/33041"
          },
          {
            "x": "55",
            "y": "63748600/231287"
          },
          {
            "x": "56",
            "y": "63643000/231287"
          },
          {
            "x": "57",
            "y": "63537200/231287"
          },
          {
            "x": "58",
            "y": "63495000/231287"
          },
          {
            "x": "59",
            "y": "63558400/231287"
          },
          {
            "x": "60",
            "y": "63495000/231287"
          },
          {
            "x": "61",
            "y": "63495000/231287"
          },
          {
            "x": "62",
            "y": "63431600/231287"
          },
          {
            "x": "63",
            "y": "63431600/231287"
          },
          {
            "x": "64",
            "y": "63621800/231287"
          },
          {
            "x": "65",
            "y": "63833200/231287"
          },
          {
            "x": "66",
            "y": "9131100/33041"
          },
          {
            "x": "67",
            "y": "64298200/231287"
          },
          {
            "x": "68",
            "y": "9360600/33041"
          },
          {
            "x": "69",
            "y": "65904600/231287"
          },
          {
            "x": "70",
            "y": "65925700/231287"
          },
          {
            "x": "71",
            "y": "65883400/231287"
          },
          {
            "x": "72",
            "y": "1361300/4921"
          },
          {
            "x": "73",
            "y": "8497000/33041"
          },
          {
            "x": "74",
            "y": "58105100/231287"
          },
          {
            "x": "75",
            "y": "57449800/231287"
          },
          {
            "x": "76",
            "y": "58358700/231287"
          },
          {
            "x": "77",
            "y": "3088200/12173"
          },
          {
            "x": "78",
            "y": "59309900/231287"
          },
          {
            "x": "79",
            "y": "59627000/231287"
          },
          {
            "x": "80",
            "y": "59922900/231287"
          },
          {
            "x": "81",
            "y": "8590600/33041"
          },
          {
            "x": "82",
            "y": "60113100/231287"
          },
          {
            "x": "83",
            "y": "60049700/231287"
          },
          {
            "x": "84",
            "y": "59922900/231287"
          },
          {
            "x": "85",
            "y": "61085400/231287"
          },
          {
            "x": "86",
            "y": "9067700/33041"
          },
          {
            "x": "87",
            "y": "9315300/33041"
          },
          {
            "x": "88",
            "y": "69011700/231287"
          },
          {
            "x": "89",
            "y": "3775700/12173"
          },
          {
            "x": "90",
            "y": "74232500/231287"
          },
          {
            "x": "91",
            "y": "76303900/231287"
          },
          {
            "x": "92",
            "y": "10970000/33041"
          },
          {
            "x": "93",
            "y": "79030600/231287"
          },
          {
            "x": "94",
            "y": "80412400/231287"
          },
          {
            "x": "95",
            "y": "81340600/231287"
          },
          {
            "x": "96",
            "y": "80628200/231287"
          },
          {
            "x": "97",
            "y": "2185100/6251"
          },
          {
            "x": "98",
            "y": "80221300/231287"
          },
          {
            "x": "99",
            "y": "79462700/231287"
          },
          {
            "x": "100",
            "y": "11310800/33041"
          },
          {
            "x": "101",
            "y": "1711200/4921"
          },
          {
            "x": "102",
            "y": "81942600/231287"
          },
          {
            "x": "103",
            "y": "11742400/33041"
          },
          {
            "x": "104",
            "y": "83000000/231287"
          },
          {
            "x": "105",
            "y": "84926400/231287"
          },
          {
            "x": "106",
            "y": "85943700/231287"
          },
          {
            "x": "107",
            "y": "12831500/33041"
          },
          {
            "x": "108",
            "y": "13275700/33041"
          },
          {
            "x": "109",
            "y": "2522700/6251"
          },
          {
            "x": "110",
            "y": "93878000/231287"
          },
          {
            "x": "111",
            "y": "94558000/231287"
          },
          {
            "x": "112",
            "y": "95429500/231287"
          },
          {
            "x": "113",
            "y": "97439200/231287"
          },
          {
            "x": "114",
            "y": "14088200/33041"
          },
          {
            "x": "115",
            "y": "98280900/231287"
          },
          {
            "x": "116",
            "y": "96914600/231287"
          },
          {
            "x": "117",
            "y": "2619200/6251"
          },
          {
            "x": "118",
            "y": "97772900/231287"
          },
          {
            "x": "119",
            "y": "14132600/33041"
          },
          {
            "x": "120",
            "y": "384200/893"
          },
          {
            "x": "121",
            "y": "99995800/231287"
          },
          {
            "x": "122",
            "y": "99923300/231287"
          },
          {
            "x": "123",
            "y": "100573100/231287"
          },
          {
            "x": "124",
            "y": "102323000/231287"
          },
          {
            "x": "125",
            "y": "104762900/231287"
          },
          {
            "x": "126",
            "y": "106319100/231287"
          },
          {
            "x": "127",
            "y": "107647200/231287"
          },
          {
            "x": "128",
            "y": "108251900/231287"
          },
          {
            "x": "129",
            "y": "108559900/231287"
          },
          {
            "x": "130",
            "y": "108301700/231287"
          },
          {
            "x": "131",
            "y": "2917700/6251"
          },
          {
            "x": "132",
            "y": "107760300/231287"
          },
          {
            "x": "133",
            "y": "107685100/231287"
          },
          {
            "x": "134",
            "y": "5665200/12173"
          },
          {
            "x": "135",
            "y": "108075900/231287"
          },
          {
            "x": "136",
            "y": "15517000/33041"
          },
          {
            "x": "137",
            "y": "109180000/231287"
          },
          {
            "x": "138",
            "y": "109553200/231287"
          },
          {
            "x": "139",
            "y": "15763200/33041"
          },
          {
            "x": "140",
            "y": "111019900/231287"
          },
          {
            "x": "141",
            "y": "112409800/231287"
          },
          {
            "x": "142",
            "y": "16263700/33041"
          },
          {
            "x": "143",
            "y": "115134200/231287"
          },
          {
            "x": "144",
            "y": "115601900/231287"
          },
          {
            "x": "145",
            "y": "16541300/33041"
          },
          {
            "x": "146",
            "y": "116185400/231287"
          },
          {
            "x": "147",
            "y": "116845800/231287"
          },
          {
            "x": "148",
            "y": "117046500/231287"
          },
          {
            "x": "149",
            "y": "117224400/231287"
          },
          {
            "x": "150",
            "y": "117875300/231287"
          },
          {
            "x": "151",
            "y": "118316700/231287"
          },
          {
            "x": "152",
            "y": "16991800/33041"
          },
          {
            "x": "153",
            "y": "119545700/231287"
          },
          {
            "x": "154",
            "y": "120365600/231287"
          },
          {
            "x": "155",
            "y": "122074600/231287"
          },
          {
            "x": "156",
            "y": "122127800/231287"
          },
          {
            "x": "157",
            "y": "6408300/12173"
          },
          {
            "x": "158",
            "y": "121718000/231287"
          },
          {
            "x": "159",
            "y": "122154600/231287"
          },
          {
            "x": "160",
            "y": "123460700/231287"
          },
          {
            "x": "161",
            "y": "124671000/231287"
          },
          {
            "x": "162",
            "y": "127222700/231287"
          },
          {
            "x": "163",
            "y": "130911100/231287"
          },
          {
            "x": "164",
            "y": "136115300/231287"
          },
          {
            "x": "165",
            "y": "140889500/231287"
          },
          {
            "x": "166",
            "y": "146408900/231287"
          },
          {
            "x": "167",
            "y": "151529500/231287"
          },
          {
            "x": "168",
            "y": "21896800/33041"
          },
          {
            "x": "169",
            "y": "154115000/231287"
          },
          {
            "x": "170",
            "y": "4165400/6251"
          },
          {
            "x": "171",
            "y": "151392400/231287"
          },
          {
            "x": "172",
            "y": "20949700/33041"
          },
          {
            "x": "173",
            "y": "20520100/33041"
          },
          {
            "x": "174",
            "y": "20404600/33041"
          },
          {
            "x": "175",
            "y": "142915300/231287"
          },
          {
            "x": "176",
            "y": "142547400/231287"
          },
          {
            "x": "177",
            "y": "142251400/231287"
          },
          {
            "x": "178",
            "y": "1070400/1739"
          },
          {
            "x": "179",
            "y": "142682500/231287"
          }
        ],
        "plotFile": "econ22-fixed-results/realdata-country-python/plot.svg",
        "plotSHA256": "c59a6719d6eba00470125c79cc2a572d522e70541b98cb6c963f180c94a314ec",
        "scope": "Actually executed fixed example. Current browser controls are calculated separately by JavaScript. Base-R outputs use finite precision; Python outputs use exact fractions.",
        "summaryFile": "econ22-fixed-results/realdata-country-python/summary.csv",
        "summarySHA256": "81685746235a66cc1a35bf1d4898e991a682a29291d5f4646aceee11178dd19a",
        "plotPointsFile": "econ22-fixed-results/realdata-country-python/plot-points.csv",
        "plotPointsSHA256": "c8e0221b70c7aa7b88d7e4ad5efe8cd4a19059d20526c3dd356e504c620b9594"
      },
      "person": {
        "api": "realdata",
        "variant": "person",
        "language": "python",
        "codeFile": "econ22-code/realdata-person.py",
        "codeSHA256": "6a48c1b0a44564e3d9ecbc4ad2e109b302d6e7fcb199ea2ef3883b7ea8156dc9",
        "codeText": "# Fixed stated example, separate from current web controls.\nfrom pathlib import Path\nimport importlib.util,sys\nroot=Path(__file__).resolve().parents[1]\nspec=importlib.util.spec_from_file_location('fixed_support',root/'econ22-fixed-support.py')\nsupport=importlib.util.module_from_spec(spec);spec.loader.exec_module(support)\ntry:support.run('realdata','person',sys.argv[1]if len(sys.argv)>1 else root/'econ22-fixed-results/realdata-person-python')\nexcept ValueError as error:\n print('Rejected declared input: '+str(error),file=sys.stderr);sys.exit(2)\n",
        "supportFiles": [
          {
            "file": "econ22-reproduce.py",
            "sha256": "cc5631d9dfea963b64349bb28d18b69ad3caf15a15162ec6cea786a36e18de48",
            "codeText": "#!/usr/bin/env python3\n\"\"\"ECON22 public reproduction: Python standard library, exact Fraction arithmetic.\nRun: python econ22-reproduce.py --source-dir econ22-sources --output-dir econ22-python-results\nOriginal CSV inputs are read only. Output is a new chosen directory.\nThese are descriptive arithmetic and explicitly assumed examples, not causal estimates.\n\"\"\"\nfrom fractions import Fraction as Q\nfrom pathlib import Path\nfrom collections import defaultdict\nimport argparse,csv,json\n\ndef number(x):\n if x is None:raise ValueError('missing numeric token')\n return Q(str(x))\ndef rebase(values,base=0,scale='100'):\n v=[None if x is None else number(x)for x in values];s=number(scale)\n if not v or not 0<=base<len(v)or v[base]is None or v[base]<=0 or s<=0:raise ValueError('positive observed base/scale required')\n return [None if x is None else s*x/v[base]for x in v]\ndef growth(start,end,periods=1):\n a,b=number(start),number(end)\n if a<=0 or b<0 or not isinstance(periods,int)or not 1<=periods<=12:raise ValueError('growth domain')\n g=b/a;return dict(gross=g,percentChange=(g-1)*100,annualizedGross=g**periods,annualizedPercent=(g**periods-1)*100)\ndef composition(rows):\n seen=set();data=[]\n for r in rows:\n  identifier=str(r['id']);weight=number(r.get('weight','1'))\n  if identifier in seen or weight<0:raise ValueError('unique units/nonnegative fixed weights required')\n  seen.add(identifier);data.append(dict(id=identifier,weight=weight,before=None if r['before']is None else number(r['before']),after=None if r['after']is None else number(r['after'])))\n if not data:raise ValueError('nonempty frame required')\n valid=[r for r in data if r['weight']>0];b=[r for r in valid if r['before']is not None];a=[r for r in valid if r['after']is not None];c=[r for r in valid if r['before']is not None and r['after']is not None]\n def mean(rs,k):\n  mass=sum((r['weight']for r in rs),Q(0));return sum((r[k]*r['weight']for r in rs),Q(0))/mass if mass else None\n mb,ma,cb,ca=mean(b,'before'),mean(a,'after'),mean(c,'before'),mean(c,'after');full=all(x is not None for x in [mb,ma,cb,ca]);change=ma-mb if mb is not None and ma is not None else None\n return dict(sourceUnits=len(data),beforeAvailableUnits=len(b),afterAvailableUnits=len(a),commonUnits=len(c),beforeAvailableMean=mb,afterAvailableMean=ma,beforeCommonMean=cb,afterCommonMean=ca,availableMeanChange=change,commonWithinChange=ca-cb if full else None,afterFrameShift=ma-ca if full else None,beforeFrameShift=cb-mb if full else None,exactDecompositionResidual=change-((ma-ca)+(ca-cb)+(cb-mb))if full else None)\ndef productivity(output0,output1,hours0,hours1):\n o0,o1,h0,h1=map(number,[output0,output1,hours0,hours1])\n if min(o0,o1,h0,h1)<=0:raise ValueError('positive output and hours required')\n go,gh=o1/o0,h1/h0;gp=go/gh\n return dict(outputGross=go,hoursGross=gh,productivityGross=gp,outputPercent=(go-1)*100,hoursPercent=(gh-1)*100,productivityPercent=(gp-1)*100,differenceOfPercentGrowths=(go-gh)*100,exactGrowthIdentityResidual=gp-go/gh)\ndef measurement(numerator,denominator,lower=None,upper=None):\n n,d=number(numerator),number(denominator)\n if d<0:raise ValueError('nonnegative denominator required')\n interval=None\n if lower is not None or upper is not None:\n  lo,hi=number(lower),number(upper)\n  if lo<=0 or hi<lo:raise ValueError('ordered positive scenario bounds')\n  interval=sorted([n/lo,n/hi])\n return dict(ratio=n/d if d else None,denominatorScenarioInterval=interval)\ndef read_csv(folder,name):\n with (folder/name).open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))\ndef load_sources(folder):\n h=read_csv(folder,'actual180-KOR-housing-nominal-real-indexes.csv');b=read_csv(folder,'actual38-US-nonfarm-output-hours-productivity-indexes.csv');p=read_csv(folder,'actual10839-person-wage-panel-original-and-prior-derived-fields.csv');c=read_csv(folder,'actual3-Apple-revenue-and-approximate-periodend-FTE-facts.csv')\n company={}\n for r in c:\n  value=Q(r['originalToken'].replace(',',''))\n  company[('revenue'+r['fiscalYear'])if r['fact']=='consolidated total net sales'else'endpointFTE2024']=value*1000000 if r['fact']=='consolidated total net sales'else value\n return dict(housing=h,bls=b,person=p,company=company)\ndef person_comparison(models,before=1976,after=1980):\n if before not in [1976,1978,1980]or after not in [1976,1978,1980]or before>=after:raise ValueError('ordered observed waves required')\n units=defaultdict(dict)\n for r in models['person']:\n  year=int(r['time'])\n  if year in units[r['unit']]:raise ValueError('duplicate original unit-wave')\n  token=r['wageCentsOriginal'];units[r['unit']][year]=None if token in ['.','','NA']else number(token)/100\n return composition([dict(id=k,before=v[before],after=v[after])for k,v in units.items()])\ndef realdata(models,kind):\n if kind=='country':\n  rows=models['housing'];return dict(originalCount=len(rows),growth=growth(rows[0]['nominal'],rows[-1]['nominal']),rebased=rebase([r['nominal']for r in rows]))\n if kind=='person':return person_comparison(models)\n if kind=='company':\n  c=models['company'];return dict(revenueGrowth=growth(c['revenue2023'],c['revenue2024']),ratio=measurement(c['revenue2024'],c['endpointFTE2024'])['ratio'],proxyGrowth=None)\n raise ValueError('actual case required')\ndef encode(v):\n if isinstance(v,Q):return str(v)\n if isinstance(v,dict):return{k:encode(x)for k,x in v.items()}\n if isinstance(v,(list,tuple)):return[encode(x)for x in v]\n return v\ndef write_csv(path,rows):\n with path.open('w',encoding='utf8',newline='')as f:\n  writer=csv.DictWriter(f,fieldnames=list(rows[0]));writer.writeheader();writer.writerows([{k:''if v is None else str(v)for k,v in r.items()}for r in rows])\ndef full_source(folder,out):\n out.mkdir(parents=True,exist_ok=True);models=load_sources(folder);metrics={};country=[];frames=[]\n for source in ['housing','bls']:\n  data=models[source];columns=['nominal','real']if source=='housing'else['outputIndexOriginalToken','hoursIndexOriginalToken','productivityIndexOriginalToken']\n  for col in columns:\n   values=[r[col]for r in data];rb=rebase(values);g=growth(values[0],values[-1])\n   for k,v in g.items():metrics[source+':'+col+':'+k]=v\n   quarter_base=next((i for i,r in enumerate(data)if r['quarter']=='2010-Q1'),None)if source=='housing'else None\n   qb=rebase(values,quarter_base)if quarter_base is not None else[None]*len(values)\n   country.extend(dict(source=source,series=col,row=i+1,quarter=r['quarter'],originalToken=r[col],rebasedFirst100Exact=rb[i],rebased2010Q1Exact=qb[i])for i,r in enumerate(data))\n for a,b in [(1976,1978),(1978,1980),(1976,1980)]:\n  z=person_comparison(models,a,b);frames.append(dict(before=a,after=b,elapsedYears=b-a,**z));metrics.update({f'person:{a}:{b}:{k}':v for k,v in z.items()})\n c=realdata(models,'company');metrics['company:proxy']=c['ratio'];metrics['company:proxyGrowth']=None;metrics.update({'company:sales:'+k:v for k,v in c['revenueGrowth'].items()})\n changes=[]\n for a,b in zip(models['bls'],models['bls'][1:]):\n  z=productivity(a['outputIndexOriginalToken'],b['outputIndexOriginalToken'],a['hoursIndexOriginalToken'],b['hoursIndexOriginalToken']);g=growth(a['productivityIndexOriginalToken'],b['productivityIndexOriginalToken'],4)\n  changes.append(dict(start=a['quarter'],end=b['quarter'],**z,publishedProductivityPercent=g['percentChange'],publishedAnnualizedPercent=g['annualizedPercent']))\n selected=list(dict.fromkeys(r['unit']for r in models['person']))[:12]\n trajectories=[dict(unit=r['unit'],year=r['time'],nominalUSDPerHourExact=None if r['wageCentsOriginal']in['.','','NA']else number(r['wageCentsOriginal'])/100)for r in models['person']if r['unit']in selected]\n write_csv(out/'metrics.csv',[dict(metric=k,value=v)for k,v in metrics.items()]);write_csv(out/'country-indexes.csv',country);write_csv(out/'wage-frames.csv',frames);write_csv(out/'bls-changes.csv',changes);write_csv(out/'first12-trajectories.csv',trajectories)\n (out/'full-results.json').write_text(json.dumps(encode(dict(metrics=metrics,frames=frames,company=c)),ensure_ascii=False,indent=2)+'\\n',encoding='utf8');return{f.name:len(read_csv(out,f.name))for f in out.glob('*.csv')}\nif __name__=='__main__':\n parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--source-dir',type=Path,default=Path(__file__).parent/'econ22-sources');parser.add_argument('--output-dir',type=Path,default=Path(__file__).parent/'econ22-python-results');args=parser.parse_args();print(json.dumps(full_source(args.source_dir,args.output_dir)))\n"
          },
          {
            "file": "econ22-fixed-support.py",
            "sha256": "deb4273c9c713e16c2f5e5d3525932ae34753f348731a3b26a4babff015c2fd6",
            "codeText": "\"\"\"Public fixed-example support. Requires only Python standard library and econ22-reproduce.py.\nFixed examples are separate from current browser inputs. Missing values remain None.\n\"\"\"\nfrom pathlib import Path\nfrom fractions import Fraction as Q\nimport importlib.util,json,csv,html,math\nROOT=Path(__file__).resolve().parent\nspec=importlib.util.spec_from_file_location('econ22_public',ROOT/'econ22-reproduce.py');M=importlib.util.module_from_spec(spec);spec.loader.exec_module(M)\n\ndef example(api,variant):\n if api=='rebase':\n  values=[0,1]if variant=='invalid'else[80,None,120]if variant=='gap'else[80,100,120];z=M.rebase(values);return dict(rows=len(z),defined=sum(x is not None for x in z),last=z[-1]),list(enumerate(z)),'Position','Rebased index'\n if api=='growth':\n  end=90 if variant=='quarterly'else 120;z=M.growth(100,end,4 if variant=='quarterly'else 1);return z,[(0,Q(100)),(1,Q(end))],'Date','Supplied level'\n if api=='composition':\n  rows=[dict(id='A',before=10,after=None),dict(id='B',before=None,after=20)]if variant=='noCommon'else[dict(id='A',before=10,after=11),dict(id='B',before=100,after=None),dict(id='C',before=None,after=1)];z=M.composition(rows);metrics={k:z[k]for k in ['beforeAvailableMean','afterAvailableMean','availableMeanChange','commonWithinChange','commonUnits','exactDecompositionResidual']};return metrics,[(0,z['beforeAvailableMean']),(1,z['afterAvailableMean'])],'Date','Available mean / assumed units'\n if api=='productivity':\n  o,h=(90,80)if variant=='contraction'else(103,101);z=M.productivity(100,o,100,h);return z,[(0,Q(1)),(1,z['productivityGross'])],'Date','Output per hour / initial=1'\n if api=='measurement':\n  n,d=(0,0)if variant=='zero'else(391035000000,164000);z=M.measurement(n,d);return dict(ratio=z['ratio'],denominatorZero=int(d==0),sourceApproximate=int(variant!='zero')),[(0,z['ratio'])],'Ratio position','USD / approximate endpoint FTE'\n models=M.load_sources(ROOT/'econ22-sources');z=M.realdata(models,variant)\n if variant=='country':return dict(sourceRows=z['originalCount'],first=Q(models['housing'][0]['nominal']),last=Q(models['housing'][-1]['nominal']),percentChange=z['growth']['percentChange']),list(enumerate(z['rebased'])),'Quarter position / original calendar','Nominal housing / first=100'\n if variant=='person':return{k:z[k]for k in ['sourceUnits','beforeAvailableUnits','afterAvailableUnits','commonUnits','availableMeanChange','commonWithinChange','exactDecompositionResidual']},[(1976,z['beforeAvailableMean']),(1980,z['afterAvailableMean'])],'Observed wave','Nominal USD/hour / available mean'\n if variant=='company':return dict(sales2023=models['company']['revenue2023'],sales2024=models['company']['revenue2024'],proxy=z['ratio'],proxyGrowth=None),[(2023,models['company']['revenue2023']/1000000),(2024,models['company']['revenue2024']/1000000)],'Fiscal year','Nominal USD millions'\n raise ValueError('fixed example name required')\n\ndef svg(points,xlabel,ylabel):\n good=[(float(x),float(y))for x,y in points if y is not None]\n if not good:return None\n if any(not math.isfinite(x)or not math.isfinite(y)for x,y in good):raise ValueError('outside finite plotting range')\n w,h,L,R,T,B=640,360,90,22,28,54;xmin=min(float(p[0])for p in points);xmax=max(float(p[0])for p in points);ymin=min(y for x,y in good);ymax=max(y for x,y in good)\n pad=max(1,abs(ymin)*.05)if ymin==ymax else(ymax-ymin)*.08;ymin-=pad;ymax+=pad\n X=lambda x:(L+w-R)/2 if xmax==xmin else L+(float(x)-xmin)/(xmax-xmin)*(w-L-R);Y=lambda y:T+(ymax-float(y))/(ymax-ymin)*(h-T-B);esc=html.escape\n s=f'<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"640\" height=\"360\" viewBox=\"0 0 640 360\" role=\"img\" aria-label=\"{esc(xlabel+\"; \"+ylabel)}\"><title>{esc(xlabel+\"; \"+ylabel)}</title><rect width=\"640\" height=\"360\" fill=\"white\"/><g font-family=\"sans-serif\" font-size=\"13\" fill=\"#222\">'\n for i in range(4):\n  v=ymin+(ymax-ymin)*i/3;y=Y(v);s+=f'<line x1=\"{L}\" x2=\"{w-R}\" y1=\"{y}\" y2=\"{y}\" stroke=\"#ccd6db\"/><text x=\"{L-7}\" y=\"{y+4}\" text-anchor=\"end\">{v:.4g}</text>'\n for x,anchor in([(xmin,'middle')]if xmin==xmax else[(xmin,'start'),(xmax,'end')]):s+=f'<text x=\"{X(x)}\" y=\"{h-B+24}\" text-anchor=\"{anchor}\">{x:g}</text>'\n last=None\n for x,y in points:\n  if y is None:last=None;continue\n  a,b=X(x),Y(y)\n  if last:s+=f'<line x1=\"{last[0]}\" y1=\"{last[1]}\" x2=\"{a}\" y2=\"{b}\" stroke=\"#355c72\" stroke-width=\"2\"/>'\n  s+=f'<circle cx=\"{a}\" cy=\"{b}\" r=\"3\" fill=\"#934b34\"><title>{esc(str(x)+\": \"+str(y))}</title></circle>';last=(a,b)\n return s+f'<text x=\"{L}\" y=\"16\">{esc(ylabel)}</text><text x=\"{w-R}\" y=\"{h-6}\" text-anchor=\"end\">{esc(xlabel)}</text></g></svg>'\n\ndef run(api,variant,output):\n out=Path(output);out.mkdir(parents=True,exist_ok=True);metrics,points,x,y=example(api,variant);encoded=M.encode(metrics);(out/'summary.json').write_text(json.dumps(encoded,indent=2)+'\\n',encoding='utf8')\n M.write_csv(out/'summary.csv',[dict(metric=k,value=v)for k,v in metrics.items()]);M.write_csv(out/'plot-points.csv',[dict(x=a,y=b)for a,b in points]);graphic=svg(points,x,y)\n if graphic is not None:(out/'plot.svg').write_text(graphic,encoding='utf8')\n print(json.dumps(dict(api=api,variant=variant,metrics=encoded,plotProduced=graphic is not None),ensure_ascii=False))\n"
          }
        ],
        "inputFiles": [
          {
            "file": "econ22-sources/actual10839-person-wage-panel-original-and-prior-derived-fields.csv",
            "sha256": "971fae34928d73c1d7e8234d5fc6dd38767d993d85adb5d5060f26a7aa781d0f"
          },
          {
            "file": "econ22-sources/actual180-KOR-housing-nominal-real-indexes.csv",
            "sha256": "0db7456684f2da50d1fd15aee53b24217849744188d4f96e1e055cbdd2992777"
          },
          {
            "file": "econ22-sources/actual3-Apple-revenue-and-approximate-periodend-FTE-facts.csv",
            "sha256": "897e50d6ef2d05d1e934aa5a8048dda3296a53bc705bb3239610edd9db0e2922"
          },
          {
            "file": "econ22-sources/actual38-US-nonfarm-output-hours-productivity-indexes.csv",
            "sha256": "265369587eea705ef3ef8124988ad02ac3150efdd14142b469ba042c2495588b"
          }
        ],
        "returnCode": 0,
        "expectedFailure": false,
        "stdout": "{\"api\": \"realdata\", \"variant\": \"person\", \"metrics\": {\"sourceUnits\": 3613, \"beforeAvailableUnits\": 3017, \"afterAvailableUnits\": 2520, \"commonUnits\": 2334, \"availableMeanChange\": \"106369241/36204000\", \"commonWithinChange\": \"698353/233400\", \"exactDecompositionResidual\": \"0\"}, \"plotProduced\": true}\n",
        "stderr": "",
        "seconds": 0.17099999997299165,
        "summary": {
          "sourceUnits": "3613",
          "beforeAvailableUnits": "3017",
          "afterAvailableUnits": "2520",
          "commonUnits": "2334",
          "availableMeanChange": "106369241/36204000",
          "commonWithinChange": "698353/233400",
          "exactDecompositionResidual": "0"
        },
        "plotPoints": [
          {
            "x": "1976",
            "y": "86903/15085"
          },
          {
            "x": "1980",
            "y": "730711/84000"
          }
        ],
        "plotFile": "econ22-fixed-results/realdata-person-python/plot.svg",
        "plotSHA256": "a3c4e7456cfffcdd4a5c1101249bf2fcc3d9af897cff2c97e9639e19b999aa62",
        "scope": "Actually executed fixed example. Current browser controls are calculated separately by JavaScript. Base-R outputs use finite precision; Python outputs use exact fractions.",
        "summaryFile": "econ22-fixed-results/realdata-person-python/summary.csv",
        "summarySHA256": "5f72079b130773b1198235ee327c29d5d39893b1502b3640abf807ef4fbf47d4",
        "plotPointsFile": "econ22-fixed-results/realdata-person-python/plot-points.csv",
        "plotPointsSHA256": "1f0dedf8d0cfe2c50b9ed46fb5e0fcf9e7ed3e44e496abf6d91c45fe118864c9"
      },
      "company": {
        "api": "realdata",
        "variant": "company",
        "language": "python",
        "codeFile": "econ22-code/realdata-company.py",
        "codeSHA256": "21077c5f1469afbeee313828d8eed2992035fd3e9d94a991e64bec0310eee556",
        "codeText": "# Fixed stated example, separate from current web controls.\nfrom pathlib import Path\nimport importlib.util,sys\nroot=Path(__file__).resolve().parents[1]\nspec=importlib.util.spec_from_file_location('fixed_support',root/'econ22-fixed-support.py')\nsupport=importlib.util.module_from_spec(spec);spec.loader.exec_module(support)\ntry:support.run('realdata','company',sys.argv[1]if len(sys.argv)>1 else root/'econ22-fixed-results/realdata-company-python')\nexcept ValueError as error:\n print('Rejected declared input: '+str(error),file=sys.stderr);sys.exit(2)\n",
        "supportFiles": [
          {
            "file": "econ22-reproduce.py",
            "sha256": "cc5631d9dfea963b64349bb28d18b69ad3caf15a15162ec6cea786a36e18de48",
            "codeText": "#!/usr/bin/env python3\n\"\"\"ECON22 public reproduction: Python standard library, exact Fraction arithmetic.\nRun: python econ22-reproduce.py --source-dir econ22-sources --output-dir econ22-python-results\nOriginal CSV inputs are read only. Output is a new chosen directory.\nThese are descriptive arithmetic and explicitly assumed examples, not causal estimates.\n\"\"\"\nfrom fractions import Fraction as Q\nfrom pathlib import Path\nfrom collections import defaultdict\nimport argparse,csv,json\n\ndef number(x):\n if x is None:raise ValueError('missing numeric token')\n return Q(str(x))\ndef rebase(values,base=0,scale='100'):\n v=[None if x is None else number(x)for x in values];s=number(scale)\n if not v or not 0<=base<len(v)or v[base]is None or v[base]<=0 or s<=0:raise ValueError('positive observed base/scale required')\n return [None if x is None else s*x/v[base]for x in v]\ndef growth(start,end,periods=1):\n a,b=number(start),number(end)\n if a<=0 or b<0 or not isinstance(periods,int)or not 1<=periods<=12:raise ValueError('growth domain')\n g=b/a;return dict(gross=g,percentChange=(g-1)*100,annualizedGross=g**periods,annualizedPercent=(g**periods-1)*100)\ndef composition(rows):\n seen=set();data=[]\n for r in rows:\n  identifier=str(r['id']);weight=number(r.get('weight','1'))\n  if identifier in seen or weight<0:raise ValueError('unique units/nonnegative fixed weights required')\n  seen.add(identifier);data.append(dict(id=identifier,weight=weight,before=None if r['before']is None else number(r['before']),after=None if r['after']is None else number(r['after'])))\n if not data:raise ValueError('nonempty frame required')\n valid=[r for r in data if r['weight']>0];b=[r for r in valid if r['before']is not None];a=[r for r in valid if r['after']is not None];c=[r for r in valid if r['before']is not None and r['after']is not None]\n def mean(rs,k):\n  mass=sum((r['weight']for r in rs),Q(0));return sum((r[k]*r['weight']for r in rs),Q(0))/mass if mass else None\n mb,ma,cb,ca=mean(b,'before'),mean(a,'after'),mean(c,'before'),mean(c,'after');full=all(x is not None for x in [mb,ma,cb,ca]);change=ma-mb if mb is not None and ma is not None else None\n return dict(sourceUnits=len(data),beforeAvailableUnits=len(b),afterAvailableUnits=len(a),commonUnits=len(c),beforeAvailableMean=mb,afterAvailableMean=ma,beforeCommonMean=cb,afterCommonMean=ca,availableMeanChange=change,commonWithinChange=ca-cb if full else None,afterFrameShift=ma-ca if full else None,beforeFrameShift=cb-mb if full else None,exactDecompositionResidual=change-((ma-ca)+(ca-cb)+(cb-mb))if full else None)\ndef productivity(output0,output1,hours0,hours1):\n o0,o1,h0,h1=map(number,[output0,output1,hours0,hours1])\n if min(o0,o1,h0,h1)<=0:raise ValueError('positive output and hours required')\n go,gh=o1/o0,h1/h0;gp=go/gh\n return dict(outputGross=go,hoursGross=gh,productivityGross=gp,outputPercent=(go-1)*100,hoursPercent=(gh-1)*100,productivityPercent=(gp-1)*100,differenceOfPercentGrowths=(go-gh)*100,exactGrowthIdentityResidual=gp-go/gh)\ndef measurement(numerator,denominator,lower=None,upper=None):\n n,d=number(numerator),number(denominator)\n if d<0:raise ValueError('nonnegative denominator required')\n interval=None\n if lower is not None or upper is not None:\n  lo,hi=number(lower),number(upper)\n  if lo<=0 or hi<lo:raise ValueError('ordered positive scenario bounds')\n  interval=sorted([n/lo,n/hi])\n return dict(ratio=n/d if d else None,denominatorScenarioInterval=interval)\ndef read_csv(folder,name):\n with (folder/name).open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))\ndef load_sources(folder):\n h=read_csv(folder,'actual180-KOR-housing-nominal-real-indexes.csv');b=read_csv(folder,'actual38-US-nonfarm-output-hours-productivity-indexes.csv');p=read_csv(folder,'actual10839-person-wage-panel-original-and-prior-derived-fields.csv');c=read_csv(folder,'actual3-Apple-revenue-and-approximate-periodend-FTE-facts.csv')\n company={}\n for r in c:\n  value=Q(r['originalToken'].replace(',',''))\n  company[('revenue'+r['fiscalYear'])if r['fact']=='consolidated total net sales'else'endpointFTE2024']=value*1000000 if r['fact']=='consolidated total net sales'else value\n return dict(housing=h,bls=b,person=p,company=company)\ndef person_comparison(models,before=1976,after=1980):\n if before not in [1976,1978,1980]or after not in [1976,1978,1980]or before>=after:raise ValueError('ordered observed waves required')\n units=defaultdict(dict)\n for r in models['person']:\n  year=int(r['time'])\n  if year in units[r['unit']]:raise ValueError('duplicate original unit-wave')\n  token=r['wageCentsOriginal'];units[r['unit']][year]=None if token in ['.','','NA']else number(token)/100\n return composition([dict(id=k,before=v[before],after=v[after])for k,v in units.items()])\ndef realdata(models,kind):\n if kind=='country':\n  rows=models['housing'];return dict(originalCount=len(rows),growth=growth(rows[0]['nominal'],rows[-1]['nominal']),rebased=rebase([r['nominal']for r in rows]))\n if kind=='person':return person_comparison(models)\n if kind=='company':\n  c=models['company'];return dict(revenueGrowth=growth(c['revenue2023'],c['revenue2024']),ratio=measurement(c['revenue2024'],c['endpointFTE2024'])['ratio'],proxyGrowth=None)\n raise ValueError('actual case required')\ndef encode(v):\n if isinstance(v,Q):return str(v)\n if isinstance(v,dict):return{k:encode(x)for k,x in v.items()}\n if isinstance(v,(list,tuple)):return[encode(x)for x in v]\n return v\ndef write_csv(path,rows):\n with path.open('w',encoding='utf8',newline='')as f:\n  writer=csv.DictWriter(f,fieldnames=list(rows[0]));writer.writeheader();writer.writerows([{k:''if v is None else str(v)for k,v in r.items()}for r in rows])\ndef full_source(folder,out):\n out.mkdir(parents=True,exist_ok=True);models=load_sources(folder);metrics={};country=[];frames=[]\n for source in ['housing','bls']:\n  data=models[source];columns=['nominal','real']if source=='housing'else['outputIndexOriginalToken','hoursIndexOriginalToken','productivityIndexOriginalToken']\n  for col in columns:\n   values=[r[col]for r in data];rb=rebase(values);g=growth(values[0],values[-1])\n   for k,v in g.items():metrics[source+':'+col+':'+k]=v\n   quarter_base=next((i for i,r in enumerate(data)if r['quarter']=='2010-Q1'),None)if source=='housing'else None\n   qb=rebase(values,quarter_base)if quarter_base is not None else[None]*len(values)\n   country.extend(dict(source=source,series=col,row=i+1,quarter=r['quarter'],originalToken=r[col],rebasedFirst100Exact=rb[i],rebased2010Q1Exact=qb[i])for i,r in enumerate(data))\n for a,b in [(1976,1978),(1978,1980),(1976,1980)]:\n  z=person_comparison(models,a,b);frames.append(dict(before=a,after=b,elapsedYears=b-a,**z));metrics.update({f'person:{a}:{b}:{k}':v for k,v in z.items()})\n c=realdata(models,'company');metrics['company:proxy']=c['ratio'];metrics['company:proxyGrowth']=None;metrics.update({'company:sales:'+k:v for k,v in c['revenueGrowth'].items()})\n changes=[]\n for a,b in zip(models['bls'],models['bls'][1:]):\n  z=productivity(a['outputIndexOriginalToken'],b['outputIndexOriginalToken'],a['hoursIndexOriginalToken'],b['hoursIndexOriginalToken']);g=growth(a['productivityIndexOriginalToken'],b['productivityIndexOriginalToken'],4)\n  changes.append(dict(start=a['quarter'],end=b['quarter'],**z,publishedProductivityPercent=g['percentChange'],publishedAnnualizedPercent=g['annualizedPercent']))\n selected=list(dict.fromkeys(r['unit']for r in models['person']))[:12]\n trajectories=[dict(unit=r['unit'],year=r['time'],nominalUSDPerHourExact=None if r['wageCentsOriginal']in['.','','NA']else number(r['wageCentsOriginal'])/100)for r in models['person']if r['unit']in selected]\n write_csv(out/'metrics.csv',[dict(metric=k,value=v)for k,v in metrics.items()]);write_csv(out/'country-indexes.csv',country);write_csv(out/'wage-frames.csv',frames);write_csv(out/'bls-changes.csv',changes);write_csv(out/'first12-trajectories.csv',trajectories)\n (out/'full-results.json').write_text(json.dumps(encode(dict(metrics=metrics,frames=frames,company=c)),ensure_ascii=False,indent=2)+'\\n',encoding='utf8');return{f.name:len(read_csv(out,f.name))for f in out.glob('*.csv')}\nif __name__=='__main__':\n parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--source-dir',type=Path,default=Path(__file__).parent/'econ22-sources');parser.add_argument('--output-dir',type=Path,default=Path(__file__).parent/'econ22-python-results');args=parser.parse_args();print(json.dumps(full_source(args.source_dir,args.output_dir)))\n"
          },
          {
            "file": "econ22-fixed-support.py",
            "sha256": "deb4273c9c713e16c2f5e5d3525932ae34753f348731a3b26a4babff015c2fd6",
            "codeText": "\"\"\"Public fixed-example support. Requires only Python standard library and econ22-reproduce.py.\nFixed examples are separate from current browser inputs. Missing values remain None.\n\"\"\"\nfrom pathlib import Path\nfrom fractions import Fraction as Q\nimport importlib.util,json,csv,html,math\nROOT=Path(__file__).resolve().parent\nspec=importlib.util.spec_from_file_location('econ22_public',ROOT/'econ22-reproduce.py');M=importlib.util.module_from_spec(spec);spec.loader.exec_module(M)\n\ndef example(api,variant):\n if api=='rebase':\n  values=[0,1]if variant=='invalid'else[80,None,120]if variant=='gap'else[80,100,120];z=M.rebase(values);return dict(rows=len(z),defined=sum(x is not None for x in z),last=z[-1]),list(enumerate(z)),'Position','Rebased index'\n if api=='growth':\n  end=90 if variant=='quarterly'else 120;z=M.growth(100,end,4 if variant=='quarterly'else 1);return z,[(0,Q(100)),(1,Q(end))],'Date','Supplied level'\n if api=='composition':\n  rows=[dict(id='A',before=10,after=None),dict(id='B',before=None,after=20)]if variant=='noCommon'else[dict(id='A',before=10,after=11),dict(id='B',before=100,after=None),dict(id='C',before=None,after=1)];z=M.composition(rows);metrics={k:z[k]for k in ['beforeAvailableMean','afterAvailableMean','availableMeanChange','commonWithinChange','commonUnits','exactDecompositionResidual']};return metrics,[(0,z['beforeAvailableMean']),(1,z['afterAvailableMean'])],'Date','Available mean / assumed units'\n if api=='productivity':\n  o,h=(90,80)if variant=='contraction'else(103,101);z=M.productivity(100,o,100,h);return z,[(0,Q(1)),(1,z['productivityGross'])],'Date','Output per hour / initial=1'\n if api=='measurement':\n  n,d=(0,0)if variant=='zero'else(391035000000,164000);z=M.measurement(n,d);return dict(ratio=z['ratio'],denominatorZero=int(d==0),sourceApproximate=int(variant!='zero')),[(0,z['ratio'])],'Ratio position','USD / approximate endpoint FTE'\n models=M.load_sources(ROOT/'econ22-sources');z=M.realdata(models,variant)\n if variant=='country':return dict(sourceRows=z['originalCount'],first=Q(models['housing'][0]['nominal']),last=Q(models['housing'][-1]['nominal']),percentChange=z['growth']['percentChange']),list(enumerate(z['rebased'])),'Quarter position / original calendar','Nominal housing / first=100'\n if variant=='person':return{k:z[k]for k in ['sourceUnits','beforeAvailableUnits','afterAvailableUnits','commonUnits','availableMeanChange','commonWithinChange','exactDecompositionResidual']},[(1976,z['beforeAvailableMean']),(1980,z['afterAvailableMean'])],'Observed wave','Nominal USD/hour / available mean'\n if variant=='company':return dict(sales2023=models['company']['revenue2023'],sales2024=models['company']['revenue2024'],proxy=z['ratio'],proxyGrowth=None),[(2023,models['company']['revenue2023']/1000000),(2024,models['company']['revenue2024']/1000000)],'Fiscal year','Nominal USD millions'\n raise ValueError('fixed example name required')\n\ndef svg(points,xlabel,ylabel):\n good=[(float(x),float(y))for x,y in points if y is not None]\n if not good:return None\n if any(not math.isfinite(x)or not math.isfinite(y)for x,y in good):raise ValueError('outside finite plotting range')\n w,h,L,R,T,B=640,360,90,22,28,54;xmin=min(float(p[0])for p in points);xmax=max(float(p[0])for p in points);ymin=min(y for x,y in good);ymax=max(y for x,y in good)\n pad=max(1,abs(ymin)*.05)if ymin==ymax else(ymax-ymin)*.08;ymin-=pad;ymax+=pad\n X=lambda x:(L+w-R)/2 if xmax==xmin else L+(float(x)-xmin)/(xmax-xmin)*(w-L-R);Y=lambda y:T+(ymax-float(y))/(ymax-ymin)*(h-T-B);esc=html.escape\n s=f'<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"640\" height=\"360\" viewBox=\"0 0 640 360\" role=\"img\" aria-label=\"{esc(xlabel+\"; \"+ylabel)}\"><title>{esc(xlabel+\"; \"+ylabel)}</title><rect width=\"640\" height=\"360\" fill=\"white\"/><g font-family=\"sans-serif\" font-size=\"13\" fill=\"#222\">'\n for i in range(4):\n  v=ymin+(ymax-ymin)*i/3;y=Y(v);s+=f'<line x1=\"{L}\" x2=\"{w-R}\" y1=\"{y}\" y2=\"{y}\" stroke=\"#ccd6db\"/><text x=\"{L-7}\" y=\"{y+4}\" text-anchor=\"end\">{v:.4g}</text>'\n for x,anchor in([(xmin,'middle')]if xmin==xmax else[(xmin,'start'),(xmax,'end')]):s+=f'<text x=\"{X(x)}\" y=\"{h-B+24}\" text-anchor=\"{anchor}\">{x:g}</text>'\n last=None\n for x,y in points:\n  if y is None:last=None;continue\n  a,b=X(x),Y(y)\n  if last:s+=f'<line x1=\"{last[0]}\" y1=\"{last[1]}\" x2=\"{a}\" y2=\"{b}\" stroke=\"#355c72\" stroke-width=\"2\"/>'\n  s+=f'<circle cx=\"{a}\" cy=\"{b}\" r=\"3\" fill=\"#934b34\"><title>{esc(str(x)+\": \"+str(y))}</title></circle>';last=(a,b)\n return s+f'<text x=\"{L}\" y=\"16\">{esc(ylabel)}</text><text x=\"{w-R}\" y=\"{h-6}\" text-anchor=\"end\">{esc(xlabel)}</text></g></svg>'\n\ndef run(api,variant,output):\n out=Path(output);out.mkdir(parents=True,exist_ok=True);metrics,points,x,y=example(api,variant);encoded=M.encode(metrics);(out/'summary.json').write_text(json.dumps(encoded,indent=2)+'\\n',encoding='utf8')\n M.write_csv(out/'summary.csv',[dict(metric=k,value=v)for k,v in metrics.items()]);M.write_csv(out/'plot-points.csv',[dict(x=a,y=b)for a,b in points]);graphic=svg(points,x,y)\n if graphic is not None:(out/'plot.svg').write_text(graphic,encoding='utf8')\n print(json.dumps(dict(api=api,variant=variant,metrics=encoded,plotProduced=graphic is not None),ensure_ascii=False))\n"
          }
        ],
        "inputFiles": [
          {
            "file": "econ22-sources/actual10839-person-wage-panel-original-and-prior-derived-fields.csv",
            "sha256": "971fae34928d73c1d7e8234d5fc6dd38767d993d85adb5d5060f26a7aa781d0f"
          },
          {
            "file": "econ22-sources/actual180-KOR-housing-nominal-real-indexes.csv",
            "sha256": "0db7456684f2da50d1fd15aee53b24217849744188d4f96e1e055cbdd2992777"
          },
          {
            "file": "econ22-sources/actual3-Apple-revenue-and-approximate-periodend-FTE-facts.csv",
            "sha256": "897e50d6ef2d05d1e934aa5a8048dda3296a53bc705bb3239610edd9db0e2922"
          },
          {
            "file": "econ22-sources/actual38-US-nonfarm-output-hours-productivity-indexes.csv",
            "sha256": "265369587eea705ef3ef8124988ad02ac3150efdd14142b469ba042c2495588b"
          }
        ],
        "returnCode": 0,
        "expectedFailure": false,
        "stdout": "{\"api\": \"realdata\", \"variant\": \"company\", \"metrics\": {\"sales2023\": \"383285000000\", \"sales2024\": \"391035000000\", \"proxy\": \"97758750/41\", \"proxyGrowth\": null}, \"plotProduced\": true}\n",
        "stderr": "",
        "seconds": 0.14100000000325963,
        "summary": {
          "sales2023": "383285000000",
          "sales2024": "391035000000",
          "proxy": "97758750/41",
          "proxyGrowth": null
        },
        "plotPoints": [
          {
            "x": "2023",
            "y": "383285"
          },
          {
            "x": "2024",
            "y": "391035"
          }
        ],
        "plotFile": "econ22-fixed-results/realdata-company-python/plot.svg",
        "plotSHA256": "a457b9d97ba8e16bb252321ac6537744c3add8a391f746fd700b2845dfba7c27",
        "scope": "Actually executed fixed example. Current browser controls are calculated separately by JavaScript. Base-R outputs use finite precision; Python outputs use exact fractions.",
        "summaryFile": "econ22-fixed-results/realdata-company-python/summary.csv",
        "summarySHA256": "f321606e17d90ea5f48292b22fdcbfcd4784834bf18e554e6dac065718294daf",
        "plotPointsFile": "econ22-fixed-results/realdata-company-python/plot-points.csv",
        "plotPointsSHA256": "42b4f5728ed1eab7f36d75fdf1d66940f07d2d4c4bdddb4291ec971b67f27570"
      }
    },
    "r": {
      "country": {
        "api": "realdata",
        "variant": "country",
        "language": "r",
        "codeFile": "econ22-code/realdata-country.R",
        "codeSHA256": "8f45c86ac8526efbe98db25323ce8c04d18dbb9f2a7fd8addede59011f2e1e72",
        "codeText": "# Run from the extracted textbook bundle root.\nsource('econ22-fixed-support.R',encoding='UTF-8')\noptions(digits=17)\nargs<-commandArgs(trailingOnly=TRUE)\noutput<-if(length(args))args[1]else'econ22-fixed-results/realdata-country-r'\ntryCatch(run('realdata','country',output),error=function(error){cat('Rejected declared input: ',conditionMessage(error),'\\n',file=stderr());quit(status=2)})\n",
        "supportFiles": [
          {
            "file": "econ22-reproduce.R",
            "sha256": "2db22759696a6f288479189f44026f265536a54cdc2e72952c1e91af13661480",
            "codeText": "# ECON22 independent public base-R reproduction; binary64 approximations.\n# Run: Rscript --vanilla --encoding=UTF-8 econ22-reproduce.R [source-dir] [output-dir]\n# Source CSVs are never overwritten. No packages or network required.\nrebase <- function(values, base=1L, scale=100) {\n  if (length(base)!=1L || !is.finite(base) || base!=as.integer(base) || !length(values) || base<1 || base>length(values) || is.na(values[base]) || values[base]<=0 || !is.finite(scale) || scale<=0) stop('positive observed base/scale required')\n  scale*values/values[base]\n}\ngrowth <- function(start,end,periods=1L) {\n  if (start<=0 || end<0 || periods<1 || periods>12 || periods!=as.integer(periods)) stop('growth domain')\n  gross<-end/start;list(gross=gross,percentChange=(gross-1)*100,annualizedGross=gross^periods,annualizedPercent=(gross^periods-1)*100)\n}\ncomposition <- function(rows) {\n  if (!nrow(rows) || anyDuplicated(rows$id)) stop('nonempty unique units required')\n  if (!'weight'%in%names(rows)) rows$weight<-rep(1,nrow(rows))\n  if (any(!is.finite(rows$weight)) || any(rows$weight<0)) stop('nonnegative fixed weights required')\n  valid<-rows$weight>0;b<-valid&!is.na(rows$before);a<-valid&!is.na(rows$after);common<-b&a\n  avg<-function(mask,column)if(sum(rows$weight[mask])>0)sum(rows[[column]][mask]*rows$weight[mask])/sum(rows$weight[mask])else NA_real_\n  mb<-avg(b,'before');ma<-avg(a,'after');cb<-avg(common,'before');ca<-avg(common,'after');full<-all(is.finite(c(mb,ma,cb,ca)))\n  list(sourceUnits=nrow(rows),beforeAvailableUnits=sum(b),afterAvailableUnits=sum(a),commonUnits=sum(common),beforeAvailableMean=mb,afterAvailableMean=ma,beforeCommonMean=cb,afterCommonMean=ca,availableMeanChange=ma-mb,commonWithinChange=if(full)ca-cb else NA_real_,afterFrameShift=if(full)ma-ca else NA_real_,beforeFrameShift=if(full)cb-mb else NA_real_,exactDecompositionResidual=if(full)(ma-mb)-((ma-ca)+(ca-cb)+(cb-mb))else NA_real_)\n}\nproductivity <- function(output0,output1,hours0,hours1) {\n  if(any(c(output0,output1,hours0,hours1)<=0))stop('positive output and hours required')\n  go<-output1/output0;gh<-hours1/hours0;gp<-go/gh\n  list(outputGross=go,hoursGross=gh,productivityGross=gp,outputPercent=(go-1)*100,hoursPercent=(gh-1)*100,productivityPercent=(gp-1)*100,differenceOfPercentGrowths=(go-gh)*100,exactGrowthIdentityResidual=gp-go/gh)\n}\nmeasurement <- function(numerator,denominator,lower=NA_real_,upper=NA_real_) {\n  if(denominator<0)stop('nonnegative denominator required');interval<-NULL\n  if(!is.na(lower)||!is.na(upper)){if(any(!is.finite(c(lower,upper)))||lower<=0||upper<lower)stop('ordered positive scenario bounds');interval<-sort(c(numerator/lower,numerator/upper))}\n  list(ratio=if(denominator>0)numerator/denominator else NA_real_,denominatorScenarioInterval=interval)\n}\nload_sources <- function(folder) {\n  read<-function(file)read.csv(file.path(folder,file),stringsAsFactors=FALSE,check.names=FALSE,colClasses='character',na.strings=c('NA','','.'))\n  h<-read('actual180-KOR-housing-nominal-real-indexes.csv');b<-read('actual38-US-nonfarm-output-hours-productivity-indexes.csv');p<-read('actual10839-person-wage-panel-original-and-prior-derived-fields.csv');c<-read('actual3-Apple-revenue-and-approximate-periodend-FTE-facts.csv')\n  company<-list();for(i in seq_len(nrow(c))){value<-as.numeric(gsub(',','',c$originalToken[i],fixed=TRUE));if(c$fact[i]=='consolidated total net sales')company[[paste0('revenue',c$fiscalYear[i])]]<-value*1e6 else company$endpointFTE2024<-value}\n  list(housing=h,bls=b,person=p,company=company)\n}\nperson_comparison <- function(models,before=1976L,after=1980L) {\n  if(!before%in%c(1976,1978,1980)||!after%in%c(1976,1978,1980)||before>=after)stop('ordered observed waves required')\n  p<-models$person;if(anyDuplicated(paste(p$unit,p$time,sep=':')))stop('duplicate original unit-wave')\n  ids<-unique(p$unit);rows<-data.frame(id=ids,before=as.numeric(p$wageCentsOriginal[match(paste(ids,before),paste(p$unit,p$time))])/100,after=as.numeric(p$wageCentsOriginal[match(paste(ids,after),paste(p$unit,p$time))])/100,stringsAsFactors=FALSE)\n  composition(rows)\n}\nrealdata <- function(models,kind) {\n  if(kind=='country'){r<-models$housing;return(list(originalCount=nrow(r),growth=growth(as.numeric(r$nominal[1]),as.numeric(tail(r$nominal,1))),rebased=rebase(as.numeric(r$nominal))))}\n  if(kind=='person')return(person_comparison(models))\n  if(kind=='company'){c<-models$company;return(list(revenueGrowth=growth(c$revenue2023,c$revenue2024),ratio=measurement(c$revenue2024,c$endpointFTE2024)$ratio,proxyGrowth=NA_real_))}\n  stop('actual case required')\n}\nfull_source <- function(folder,out) {\n  dir.create(out,recursive=TRUE,showWarnings=FALSE);models<-load_sources(folder);metrics<-list();country<-list();frames<-list()\n  for(source in c('housing','bls')){data<-models[[source]];columns<-if(source=='housing')c('nominal','real')else c('outputIndexOriginalToken','hoursIndexOriginalToken','productivityIndexOriginalToken')\n    for(col in columns){values<-as.numeric(data[[col]]);rb<-rebase(values);g<-growth(values[1],tail(values,1));for(k in names(g))metrics[[paste(source,col,k,sep=':')]]<-g[[k]];quarterBase<-if(source=='housing')match('2010-Q1',data$quarter)else NA_integer_;qb<-if(!is.na(quarterBase))rebase(values,quarterBase)else rep(NA_real_,length(values));country[[length(country)+1]]<-data.frame(source=source,series=col,row=seq_len(nrow(data)),quarter=data$quarter,originalToken=data[[col]],rebasedFirst100Exact=rb,rebased2010Q1Exact=qb,stringsAsFactors=FALSE)}}\n  for(pair in list(c(1976,1978),c(1978,1980),c(1976,1980))){a<-pair[1];b<-pair[2];z<-person_comparison(models,a,b);frames[[length(frames)+1]]<-as.data.frame(c(list(before=a,after=b,elapsedYears=b-a),z),stringsAsFactors=FALSE);for(k in names(z))metrics[[paste('person',a,b,k,sep=':')]]<-z[[k]]}\n  company<-realdata(models,'company');metrics[['company:proxy']]<-company$ratio;metrics[['company:proxyGrowth']]<-NA_real_;for(k in names(company$revenueGrowth))metrics[[paste('company:sales',k,sep=':')]]<-company$revenueGrowth[[k]]\n  changes<-list();b<-models$bls\n  for(i in seq_len(nrow(b)-1L)){z<-productivity(as.numeric(b$outputIndexOriginalToken[i]),as.numeric(b$outputIndexOriginalToken[i+1]),as.numeric(b$hoursIndexOriginalToken[i]),as.numeric(b$hoursIndexOriginalToken[i+1]));g<-growth(as.numeric(b$productivityIndexOriginalToken[i]),as.numeric(b$productivityIndexOriginalToken[i+1]),4);changes[[i]]<-as.data.frame(c(list(start=b$quarter[i],end=b$quarter[i+1]),z,list(publishedProductivityPercent=g$percentChange,publishedAnnualizedPercent=g$annualizedPercent)),stringsAsFactors=FALSE)}\n  write<-function(name,rows)write.csv(rows,file.path(out,name),row.names=FALSE,na='',fileEncoding='UTF-8')\n  selected<-head(unique(models$person$unit),12);p<-models$person[models$person$unit%in%selected,];trajectories<-data.frame(unit=p$unit,year=p$time,nominalUSDPerHourExact=as.numeric(p$wageCentsOriginal)/100,stringsAsFactors=FALSE)\n  write('metrics.csv',data.frame(metric=names(metrics),value=as.numeric(unlist(metrics))));write('country-indexes.csv',do.call(rbind,country));write('wage-frames.csv',do.call(rbind,frames));write('bls-changes.csv',do.call(rbind,changes));write('first12-trajectories.csv',trajectories);invisible(metrics)\n}\nif(sys.nframe()==0L){args<-commandArgs(trailingOnly=TRUE);folder<-if(length(args)>=1)args[1]else'econ22-sources';out<-if(length(args)>=2)args[2]else'econ22-r-results';options(digits=17);metrics<-full_source(folder,out);cat('metrics:',length(metrics),'\\noutput directory:',out,'\\n')}\n"
          },
          {
            "file": "econ22-fixed-support.R",
            "sha256": "d4d63e1ad02017f20884b5932458dbde6013e0c2e560a4a9922a13d080a59fa1",
            "codeText": "# Run fixed drivers from the extracted bundle root. No packages or network required.\nsource('econ22-reproduce.R',encoding='UTF-8')\nexample <- function(api,variant) {\n  if(api=='rebase'){v<-if(variant=='invalid')c(0,1)else if(variant=='gap')c(80,NA,120)else c(80,100,120);z<-rebase(v);return(list(metrics=list(rows=length(z),defined=sum(!is.na(z)),last=tail(z,1)),x=seq_along(z)-1,y=z,xlabel='Position',ylabel='Rebased index'))}\n  if(api=='growth'){end<-if(variant=='quarterly')90 else 120;z<-growth(100,end,if(variant=='quarterly')4 else 1);return(list(metrics=z,x=c(0,1),y=c(100,end),xlabel='Date',ylabel='Supplied level'))}\n  if(api=='composition'){rows<-if(variant=='noCommon')data.frame(id=c('A','B'),before=c(10,NA),after=c(NA,20))else data.frame(id=c('A','B','C'),before=c(10,100,NA),after=c(11,NA,1));z<-composition(rows);metrics<-z[c('beforeAvailableMean','afterAvailableMean','availableMeanChange','commonWithinChange','commonUnits','exactDecompositionResidual')];return(list(metrics=metrics,x=c(0,1),y=c(z$beforeAvailableMean,z$afterAvailableMean),xlabel='Date',ylabel='Available mean / assumed units'))}\n  if(api=='productivity'){o<-if(variant=='contraction')90 else 103;h<-if(variant=='contraction')80 else 101;z<-productivity(100,o,100,h);return(list(metrics=z,x=c(0,1),y=c(1,z$productivityGross),xlabel='Date',ylabel='Output per hour / initial=1'))}\n  if(api=='measurement'){n<-if(variant=='zero')0 else 391035000000;d<-if(variant=='zero')0 else 164000;z<-measurement(n,d);return(list(metrics=list(ratio=z$ratio,denominatorZero=as.integer(d==0),sourceApproximate=as.integer(variant!='zero')),x=0,y=z$ratio,xlabel='Ratio position',ylabel='USD / approximate endpoint FTE'))}\n  models<-load_sources('econ22-sources');z<-realdata(models,variant)\n  if(variant=='country')return(list(metrics=list(sourceRows=z$originalCount,first=as.numeric(head(models$housing$nominal,1)),last=as.numeric(tail(models$housing$nominal,1)),percentChange=z$growth$percentChange),x=seq_along(z$rebased)-1,y=z$rebased,xlabel='Quarter position / original calendar',ylabel='Nominal housing / first=100'))\n  if(variant=='person')return(list(metrics=z[c('sourceUnits','beforeAvailableUnits','afterAvailableUnits','commonUnits','availableMeanChange','commonWithinChange','exactDecompositionResidual')],x=c(1976,1980),y=c(z$beforeAvailableMean,z$afterAvailableMean),xlabel='Observed wave',ylabel='Nominal USD/hour / available mean'))\n  if(variant=='company')return(list(metrics=list(sales2023=models$company$revenue2023,sales2024=models$company$revenue2024,proxy=z$ratio,proxyGrowth=NA_real_),x=c(2023,2024),y=c(models$company$revenue2023,models$company$revenue2024)/1e6,xlabel='Fiscal year',ylabel='Nominal USD millions'))\n  stop('fixed example name required')\n}\nrun <- function(api,variant,output) {\n  dir.create(output,recursive=TRUE,showWarnings=FALSE);z<-example(api,variant);metrics<-data.frame(metric=names(z$metrics),value=as.numeric(unlist(z$metrics)),stringsAsFactors=FALSE)\n  write.csv(metrics,file.path(output,'summary.csv'),row.names=FALSE,na='',fileEncoding='UTF-8');write.csv(data.frame(x=z$x,y=z$y),file.path(output,'plot-points.csv'),row.names=FALSE,na='',fileEncoding='UTF-8');print(metrics,row.names=FALSE)\n  good<-is.finite(z$x)&is.finite(z$y)\n  if(any(good)){svg(file.path(output,'plot.svg'),width=640/96,height=360/96,pointsize=10);par(mar=c(4.5,5.8,2,1));plot(z$x,z$y,type='o',pch=16,cex=.7,col='#355c72',xlab=z$xlabel,ylab=z$ylabel,cex.axis=.85,cex.lab=.9);grid(col='#d5dde1');dev.off();cat('plotProduced: TRUE\\n')}else cat('plotProduced: FALSE; undefined values retained\\n')\n}\n"
          }
        ],
        "inputFiles": [
          {
            "file": "econ22-sources/actual10839-person-wage-panel-original-and-prior-derived-fields.csv",
            "sha256": "971fae34928d73c1d7e8234d5fc6dd38767d993d85adb5d5060f26a7aa781d0f"
          },
          {
            "file": "econ22-sources/actual180-KOR-housing-nominal-real-indexes.csv",
            "sha256": "0db7456684f2da50d1fd15aee53b24217849744188d4f96e1e055cbdd2992777"
          },
          {
            "file": "econ22-sources/actual3-Apple-revenue-and-approximate-periodend-FTE-facts.csv",
            "sha256": "897e50d6ef2d05d1e934aa5a8048dda3296a53bc705bb3239610edd9db0e2922"
          },
          {
            "file": "econ22-sources/actual38-US-nonfarm-output-hours-productivity-indexes.csv",
            "sha256": "265369587eea705ef3ef8124988ad02ac3150efdd14142b469ba042c2495588b"
          }
        ],
        "returnCode": 0,
        "expectedFailure": false,
        "stdout": "        metric               value\n    sourceRows 180.000000000000000\n         first  23.128699999999998\n          last 142.682500000000005\n percentChange 516.906700333352092\nplotProduced: TRUE\n",
        "stderr": "During startup - Warning messages:\n1: Setting LC_COLLATE=C.UTF-8 failed \n2: Setting LC_CTYPE=C.UTF-8 failed \n3: Setting LC_MONETARY=C.UTF-8 failed \n4: Setting LC_TIME=C.UTF-8 failed \n",
        "seconds": 0.3130000000237487,
        "summary": {
          "sourceRows": "180",
          "first": "23.1287",
          "last": "142.6825",
          "percentChange": "516.906700333352"
        },
        "plotPoints": [
          {
            "x": "0",
            "y": "100"
          },
          {
            "x": "1",
            "y": "103.668602212835"
          },
          {
            "x": "2",
            "y": "104.041299338052"
          },
          {
            "x": "3",
            "y": "106.596998534289"
          },
          {
            "x": "4",
            "y": "108.33596354313"
          },
          {
            "x": "5",
            "y": "110.102167436994"
          },
          {
            "x": "6",
            "y": "113.840812497027"
          },
          {
            "x": "7",
            "y": "113.053046647672"
          },
          {
            "x": "8",
            "y": "113.33970348528"
          },
          {
            "x": "9",
            "y": "114.476386480866"
          },
          {
            "x": "10",
            "y": "118.172227578723"
          },
          {
            "x": "11",
            "y": "123.423711665593"
          },
          {
            "x": "12",
            "y": "131.668446562064"
          },
          {
            "x": "13",
            "y": "137.192751862405"
          },
          {
            "x": "14",
            "y": "141.813417961234"
          },
          {
            "x": "15",
            "y": "145.559845559846"
          },
          {
            "x": "16",
            "y": "151.842083644995"
          },
          {
            "x": "17",
            "y": "156.558734386282"
          },
          {
            "x": "18",
            "y": "159.72320104459"
          },
          {
            "x": "19",
            "y": "161.594901572505"
          },
          {
            "x": "20",
            "y": "164.199890179733"
          },
          {
            "x": "21",
            "y": "167.20178825442"
          },
          {
            "x": "22",
            "y": "170.032038117145"
          },
          {
            "x": "23",
            "y": "172.322266275234"
          },
          {
            "x": "24",
            "y": "183.232520634536"
          },
          {
            "x": "25",
            "y": "181.222031501987"
          },
          {
            "x": "26",
            "y": "179.851439985818"
          },
          {
            "x": "27",
            "y": "178.937424066203"
          },
          {
            "x": "28",
            "y": "177.657628833441"
          },
          {
            "x": "29",
            "y": "177.657628833441"
          },
          {
            "x": "30",
            "y": "180.765023542179"
          },
          {
            "x": "31",
            "y": "189.903885648567"
          },
          {
            "x": "32",
            "y": "198.037503188679"
          },
          {
            "x": "33",
            "y": "208.821507477722"
          },
          {
            "x": "34",
            "y": "216.040676734966"
          },
          {
            "x": "35",
            "y": "216.22356639154"
          },
          {
            "x": "36",
            "y": "225.179538841353"
          },
          {
            "x": "37",
            "y": "242.726136791086"
          },
          {
            "x": "38",
            "y": "243.366034407468"
          },
          {
            "x": "39",
            "y": "246.381768106292"
          },
          {
            "x": "40",
            "y": "259.998184074332"
          },
          {
            "x": "41",
            "y": "278.915373540234"
          },
          {
            "x": "42",
            "y": "285.22139160437"
          },
          {
            "x": "43",
            "y": "297.650105712816"
          },
          {
            "x": "44",
            "y": "305.50917258644"
          },
          {
            "x": "45",
            "y": "316.293176875484"
          },
          {
            "x": "46",
            "y": "312.637977923532"
          },
          {
            "x": "47",
            "y": "303.407887170485"
          },
          {
            "x": "48",
            "y": "296.00496353016"
          },
          {
            "x": "49",
            "y": "290.339275445658"
          },
          {
            "x": "50",
            "y": "285.769628210838"
          },
          {
            "x": "51",
            "y": "285.038501947797"
          },
          {
            "x": "52",
            "y": "283.39335976514"
          },
          {
            "x": "53",
            "y": "281.017523682697"
          },
          {
            "x": "54",
            "y": "277.270663720832"
          },
          {
            "x": "55",
            "y": "275.625521538176"
          },
          {
            "x": "56",
            "y": "275.168945941622"
          },
          {
            "x": "57",
            "y": "274.711505618561"
          },
          {
            "x": "58",
            "y": "274.529048325241"
          },
          {
            "x": "59",
            "y": "274.803166628475"
          },
          {
            "x": "60",
            "y": "274.529048325241"
          },
          {
            "x": "61",
            "y": "274.529048325241"
          },
          {
            "x": "62",
            "y": "274.254930022007"
          },
          {
            "x": "63",
            "y": "274.254930022007"
          },
          {
            "x": "64",
            "y": "275.077284931708"
          },
          {
            "x": "65",
            "y": "275.991300851323"
          },
          {
            "x": "66",
            "y": "276.356647801217"
          },
          {
            "x": "67",
            "y": "278.001789983873"
          },
          {
            "x": "68",
            "y": "283.302563481735"
          },
          {
            "x": "69",
            "y": "284.947273301137"
          },
          {
            "x": "70",
            "y": "285.038501947797"
          },
          {
            "x": "71",
            "y": "284.855612291223"
          },
          {
            "x": "72",
            "y": "276.63076610445"
          },
          {
            "x": "73",
            "y": "257.165340032081"
          },
          {
            "x": "74",
            "y": "251.225101281092"
          },
          {
            "x": "75",
            "y": "248.391824875588"
          },
          {
            "x": "76",
            "y": "252.321574494027"
          },
          {
            "x": "77",
            "y": "253.692598373449"
          },
          {
            "x": "78",
            "y": "256.43421376904"
          },
          {
            "x": "79",
            "y": "257.805237648463"
          },
          {
            "x": "80",
            "y": "259.084600517971"
          },
          {
            "x": "81",
            "y": "259.998184074332"
          },
          {
            "x": "82",
            "y": "259.906955427672"
          },
          {
            "x": "83",
            "y": "259.632837124438"
          },
          {
            "x": "84",
            "y": "259.084600517971"
          },
          {
            "x": "85",
            "y": "264.110823349345"
          },
          {
            "x": "86",
            "y": "274.437819678581"
          },
          {
            "x": "87",
            "y": "281.931539602312"
          },
          {
            "x": "88",
            "y": "298.381231975857"
          },
          {
            "x": "89",
            "y": "310.170048467921"
          },
          {
            "x": "90",
            "y": "320.954052756964"
          },
          {
            "x": "91",
            "y": "329.910025206778"
          },
          {
            "x": "92",
            "y": "332.011742985987"
          },
          {
            "x": "93",
            "y": "341.699274062096"
          },
          {
            "x": "94",
            "y": "347.673669510176"
          },
          {
            "x": "95",
            "y": "351.686865236697"
          },
          {
            "x": "96",
            "y": "348.60670941298"
          },
          {
            "x": "97",
            "y": "349.560070388738"
          },
          {
            "x": "98",
            "y": "346.847423331186"
          },
          {
            "x": "99",
            "y": "343.567515683977"
          },
          {
            "x": "100",
            "y": "342.326200780848"
          },
          {
            "x": "101",
            "y": "347.734200365779"
          },
          {
            "x": "102",
            "y": "354.289692027654"
          },
          {
            "x": "103",
            "y": "355.388759420114"
          },
          {
            "x": "104",
            "y": "358.861501078746"
          },
          {
            "x": "105",
            "y": "367.190546809808"
          },
          {
            "x": "106",
            "y": "371.588978195921"
          },
          {
            "x": "107",
            "y": "388.350836839079"
          },
          {
            "x": "108",
            "y": "401.794739868648"
          },
          {
            "x": "109",
            "y": "403.567429211326"
          },
          {
            "x": "110",
            "y": "405.893975882778"
          },
          {
            "x": "111",
            "y": "408.834046012098"
          },
          {
            "x": "112",
            "y": "412.602091773424"
          },
          {
            "x": "113",
            "y": "421.291296095327"
          },
          {
            "x": "114",
            "y": "426.385399957628"
          },
          {
            "x": "115",
            "y": "424.930497606869"
          },
          {
            "x": "116",
            "y": "419.023118463208"
          },
          {
            "x": "117",
            "y": "419.004959206527"
          },
          {
            "x": "118",
            "y": "422.734092274966"
          },
          {
            "x": "119",
            "y": "427.729184952029"
          },
          {
            "x": "120",
            "y": "430.23516237402"
          },
          {
            "x": "121",
            "y": "432.345095055062"
          },
          {
            "x": "122",
            "y": "432.031631695685"
          },
          {
            "x": "123",
            "y": "434.841128122203"
          },
          {
            "x": "124",
            "y": "442.407052709404"
          },
          {
            "x": "125",
            "y": "452.956283751357"
          },
          {
            "x": "126",
            "y": "459.684720714956"
          },
          {
            "x": "127",
            "y": "465.42693709547"
          },
          {
            "x": "128",
            "y": "468.041437694293"
          },
          {
            "x": "129",
            "y": "469.373116517573"
          },
          {
            "x": "130",
            "y": "468.256754594941"
          },
          {
            "x": "131",
            "y": "466.757318828987"
          },
          {
            "x": "132",
            "y": "465.915939936097"
          },
          {
            "x": "133",
            "y": "465.590802768854"
          },
          {
            "x": "134",
            "y": "465.390618582108"
          },
          {
            "x": "135",
            "y": "467.280478366705"
          },
          {
            "x": "136",
            "y": "469.628643200872"
          },
          {
            "x": "137",
            "y": "472.054201057561"
          },
          {
            "x": "138",
            "y": "473.667780722652"
          },
          {
            "x": "139",
            "y": "477.07999152568"
          },
          {
            "x": "140",
            "y": "480.009252573642"
          },
          {
            "x": "141",
            "y": "486.018669445321"
          },
          {
            "x": "142",
            "y": "492.227838140492"
          },
          {
            "x": "143",
            "y": "497.79797394579"
          },
          {
            "x": "144",
            "y": "499.820136886206"
          },
          {
            "x": "145",
            "y": "500.629520898278"
          },
          {
            "x": "146",
            "y": "502.342976475115"
          },
          {
            "x": "147",
            "y": "505.19830340659"
          },
          {
            "x": "148",
            "y": "506.066056457994"
          },
          {
            "x": "149",
            "y": "506.835230687414"
          },
          {
            "x": "150",
            "y": "509.649483109729"
          },
          {
            "x": "151",
            "y": "511.557934514262"
          },
          {
            "x": "152",
            "y": "514.264096122999"
          },
          {
            "x": "153",
            "y": "516.871678909753"
          },
          {
            "x": "154",
            "y": "520.416625231855"
          },
          {
            "x": "155",
            "y": "527.805713248043"
          },
          {
            "x": "156",
            "y": "528.035730499336"
          },
          {
            "x": "157",
            "y": "526.435554095129"
          },
          {
            "x": "158",
            "y": "526.263905883167"
          },
          {
            "x": "159",
            "y": "528.151603851492"
          },
          {
            "x": "160",
            "y": "533.798700316058"
          },
          {
            "x": "161",
            "y": "539.031592782993"
          },
          {
            "x": "162",
            "y": "550.064205943265"
          },
          {
            "x": "163",
            "y": "566.0114922153"
          },
          {
            "x": "164",
            "y": "588.512540696191"
          },
          {
            "x": "165",
            "y": "609.154427183543"
          },
          {
            "x": "166",
            "y": "633.018284642025"
          },
          {
            "x": "167",
            "y": "655.157877442312"
          },
          {
            "x": "168",
            "y": "662.716019490936"
          },
          {
            "x": "169",
            "y": "666.336629382542"
          },
          {
            "x": "170",
            "y": "666.357382818749"
          },
          {
            "x": "171",
            "y": "654.565107420651"
          },
          {
            "x": "172",
            "y": "634.05163281983"
          },
          {
            "x": "173",
            "y": "621.049605036167"
          },
          {
            "x": "174",
            "y": "617.553948125057"
          },
          {
            "x": "175",
            "y": "617.91324198939"
          },
          {
            "x": "176",
            "y": "616.322577576777"
          },
          {
            "x": "177",
            "y": "615.042782344014"
          },
          {
            "x": "178",
            "y": "615.526164462335"
          },
          {
            "x": "179",
            "y": "616.906700333352"
          }
        ],
        "plotFile": "econ22-fixed-results/realdata-country-r/plot.svg",
        "plotSHA256": "c547897413c86780bb12e404ebd98b400652d1dc4495a21abd34aac75bc77221",
        "scope": "Actually executed fixed example. Current browser controls are calculated separately by JavaScript. Base-R outputs use finite precision; Python outputs use exact fractions.",
        "summaryFile": "econ22-fixed-results/realdata-country-r/summary.csv",
        "summarySHA256": "d8a35be3edcbc7b8ecca91069b2ce0993561e3bc7f07e4c1b9cdfeac270be1ee",
        "plotPointsFile": "econ22-fixed-results/realdata-country-r/plot-points.csv",
        "plotPointsSHA256": "0bff949cf459e46ad7f6d67d90cea47540cf06410deff14232e499a8bfea648c"
      },
      "person": {
        "api": "realdata",
        "variant": "person",
        "language": "r",
        "codeFile": "econ22-code/realdata-person.R",
        "codeSHA256": "d5d519bac84ba4099d71d0f9b589ed1a54742aa8bc8b4edaa4828d1c9262e2e1",
        "codeText": "# Run from the extracted textbook bundle root.\nsource('econ22-fixed-support.R',encoding='UTF-8')\noptions(digits=17)\nargs<-commandArgs(trailingOnly=TRUE)\noutput<-if(length(args))args[1]else'econ22-fixed-results/realdata-person-r'\ntryCatch(run('realdata','person',output),error=function(error){cat('Rejected declared input: ',conditionMessage(error),'\\n',file=stderr());quit(status=2)})\n",
        "supportFiles": [
          {
            "file": "econ22-reproduce.R",
            "sha256": "2db22759696a6f288479189f44026f265536a54cdc2e72952c1e91af13661480",
            "codeText": "# ECON22 independent public base-R reproduction; binary64 approximations.\n# Run: Rscript --vanilla --encoding=UTF-8 econ22-reproduce.R [source-dir] [output-dir]\n# Source CSVs are never overwritten. No packages or network required.\nrebase <- function(values, base=1L, scale=100) {\n  if (length(base)!=1L || !is.finite(base) || base!=as.integer(base) || !length(values) || base<1 || base>length(values) || is.na(values[base]) || values[base]<=0 || !is.finite(scale) || scale<=0) stop('positive observed base/scale required')\n  scale*values/values[base]\n}\ngrowth <- function(start,end,periods=1L) {\n  if (start<=0 || end<0 || periods<1 || periods>12 || periods!=as.integer(periods)) stop('growth domain')\n  gross<-end/start;list(gross=gross,percentChange=(gross-1)*100,annualizedGross=gross^periods,annualizedPercent=(gross^periods-1)*100)\n}\ncomposition <- function(rows) {\n  if (!nrow(rows) || anyDuplicated(rows$id)) stop('nonempty unique units required')\n  if (!'weight'%in%names(rows)) rows$weight<-rep(1,nrow(rows))\n  if (any(!is.finite(rows$weight)) || any(rows$weight<0)) stop('nonnegative fixed weights required')\n  valid<-rows$weight>0;b<-valid&!is.na(rows$before);a<-valid&!is.na(rows$after);common<-b&a\n  avg<-function(mask,column)if(sum(rows$weight[mask])>0)sum(rows[[column]][mask]*rows$weight[mask])/sum(rows$weight[mask])else NA_real_\n  mb<-avg(b,'before');ma<-avg(a,'after');cb<-avg(common,'before');ca<-avg(common,'after');full<-all(is.finite(c(mb,ma,cb,ca)))\n  list(sourceUnits=nrow(rows),beforeAvailableUnits=sum(b),afterAvailableUnits=sum(a),commonUnits=sum(common),beforeAvailableMean=mb,afterAvailableMean=ma,beforeCommonMean=cb,afterCommonMean=ca,availableMeanChange=ma-mb,commonWithinChange=if(full)ca-cb else NA_real_,afterFrameShift=if(full)ma-ca else NA_real_,beforeFrameShift=if(full)cb-mb else NA_real_,exactDecompositionResidual=if(full)(ma-mb)-((ma-ca)+(ca-cb)+(cb-mb))else NA_real_)\n}\nproductivity <- function(output0,output1,hours0,hours1) {\n  if(any(c(output0,output1,hours0,hours1)<=0))stop('positive output and hours required')\n  go<-output1/output0;gh<-hours1/hours0;gp<-go/gh\n  list(outputGross=go,hoursGross=gh,productivityGross=gp,outputPercent=(go-1)*100,hoursPercent=(gh-1)*100,productivityPercent=(gp-1)*100,differenceOfPercentGrowths=(go-gh)*100,exactGrowthIdentityResidual=gp-go/gh)\n}\nmeasurement <- function(numerator,denominator,lower=NA_real_,upper=NA_real_) {\n  if(denominator<0)stop('nonnegative denominator required');interval<-NULL\n  if(!is.na(lower)||!is.na(upper)){if(any(!is.finite(c(lower,upper)))||lower<=0||upper<lower)stop('ordered positive scenario bounds');interval<-sort(c(numerator/lower,numerator/upper))}\n  list(ratio=if(denominator>0)numerator/denominator else NA_real_,denominatorScenarioInterval=interval)\n}\nload_sources <- function(folder) {\n  read<-function(file)read.csv(file.path(folder,file),stringsAsFactors=FALSE,check.names=FALSE,colClasses='character',na.strings=c('NA','','.'))\n  h<-read('actual180-KOR-housing-nominal-real-indexes.csv');b<-read('actual38-US-nonfarm-output-hours-productivity-indexes.csv');p<-read('actual10839-person-wage-panel-original-and-prior-derived-fields.csv');c<-read('actual3-Apple-revenue-and-approximate-periodend-FTE-facts.csv')\n  company<-list();for(i in seq_len(nrow(c))){value<-as.numeric(gsub(',','',c$originalToken[i],fixed=TRUE));if(c$fact[i]=='consolidated total net sales')company[[paste0('revenue',c$fiscalYear[i])]]<-value*1e6 else company$endpointFTE2024<-value}\n  list(housing=h,bls=b,person=p,company=company)\n}\nperson_comparison <- function(models,before=1976L,after=1980L) {\n  if(!before%in%c(1976,1978,1980)||!after%in%c(1976,1978,1980)||before>=after)stop('ordered observed waves required')\n  p<-models$person;if(anyDuplicated(paste(p$unit,p$time,sep=':')))stop('duplicate original unit-wave')\n  ids<-unique(p$unit);rows<-data.frame(id=ids,before=as.numeric(p$wageCentsOriginal[match(paste(ids,before),paste(p$unit,p$time))])/100,after=as.numeric(p$wageCentsOriginal[match(paste(ids,after),paste(p$unit,p$time))])/100,stringsAsFactors=FALSE)\n  composition(rows)\n}\nrealdata <- function(models,kind) {\n  if(kind=='country'){r<-models$housing;return(list(originalCount=nrow(r),growth=growth(as.numeric(r$nominal[1]),as.numeric(tail(r$nominal,1))),rebased=rebase(as.numeric(r$nominal))))}\n  if(kind=='person')return(person_comparison(models))\n  if(kind=='company'){c<-models$company;return(list(revenueGrowth=growth(c$revenue2023,c$revenue2024),ratio=measurement(c$revenue2024,c$endpointFTE2024)$ratio,proxyGrowth=NA_real_))}\n  stop('actual case required')\n}\nfull_source <- function(folder,out) {\n  dir.create(out,recursive=TRUE,showWarnings=FALSE);models<-load_sources(folder);metrics<-list();country<-list();frames<-list()\n  for(source in c('housing','bls')){data<-models[[source]];columns<-if(source=='housing')c('nominal','real')else c('outputIndexOriginalToken','hoursIndexOriginalToken','productivityIndexOriginalToken')\n    for(col in columns){values<-as.numeric(data[[col]]);rb<-rebase(values);g<-growth(values[1],tail(values,1));for(k in names(g))metrics[[paste(source,col,k,sep=':')]]<-g[[k]];quarterBase<-if(source=='housing')match('2010-Q1',data$quarter)else NA_integer_;qb<-if(!is.na(quarterBase))rebase(values,quarterBase)else rep(NA_real_,length(values));country[[length(country)+1]]<-data.frame(source=source,series=col,row=seq_len(nrow(data)),quarter=data$quarter,originalToken=data[[col]],rebasedFirst100Exact=rb,rebased2010Q1Exact=qb,stringsAsFactors=FALSE)}}\n  for(pair in list(c(1976,1978),c(1978,1980),c(1976,1980))){a<-pair[1];b<-pair[2];z<-person_comparison(models,a,b);frames[[length(frames)+1]]<-as.data.frame(c(list(before=a,after=b,elapsedYears=b-a),z),stringsAsFactors=FALSE);for(k in names(z))metrics[[paste('person',a,b,k,sep=':')]]<-z[[k]]}\n  company<-realdata(models,'company');metrics[['company:proxy']]<-company$ratio;metrics[['company:proxyGrowth']]<-NA_real_;for(k in names(company$revenueGrowth))metrics[[paste('company:sales',k,sep=':')]]<-company$revenueGrowth[[k]]\n  changes<-list();b<-models$bls\n  for(i in seq_len(nrow(b)-1L)){z<-productivity(as.numeric(b$outputIndexOriginalToken[i]),as.numeric(b$outputIndexOriginalToken[i+1]),as.numeric(b$hoursIndexOriginalToken[i]),as.numeric(b$hoursIndexOriginalToken[i+1]));g<-growth(as.numeric(b$productivityIndexOriginalToken[i]),as.numeric(b$productivityIndexOriginalToken[i+1]),4);changes[[i]]<-as.data.frame(c(list(start=b$quarter[i],end=b$quarter[i+1]),z,list(publishedProductivityPercent=g$percentChange,publishedAnnualizedPercent=g$annualizedPercent)),stringsAsFactors=FALSE)}\n  write<-function(name,rows)write.csv(rows,file.path(out,name),row.names=FALSE,na='',fileEncoding='UTF-8')\n  selected<-head(unique(models$person$unit),12);p<-models$person[models$person$unit%in%selected,];trajectories<-data.frame(unit=p$unit,year=p$time,nominalUSDPerHourExact=as.numeric(p$wageCentsOriginal)/100,stringsAsFactors=FALSE)\n  write('metrics.csv',data.frame(metric=names(metrics),value=as.numeric(unlist(metrics))));write('country-indexes.csv',do.call(rbind,country));write('wage-frames.csv',do.call(rbind,frames));write('bls-changes.csv',do.call(rbind,changes));write('first12-trajectories.csv',trajectories);invisible(metrics)\n}\nif(sys.nframe()==0L){args<-commandArgs(trailingOnly=TRUE);folder<-if(length(args)>=1)args[1]else'econ22-sources';out<-if(length(args)>=2)args[2]else'econ22-r-results';options(digits=17);metrics<-full_source(folder,out);cat('metrics:',length(metrics),'\\noutput directory:',out,'\\n')}\n"
          },
          {
            "file": "econ22-fixed-support.R",
            "sha256": "d4d63e1ad02017f20884b5932458dbde6013e0c2e560a4a9922a13d080a59fa1",
            "codeText": "# Run fixed drivers from the extracted bundle root. No packages or network required.\nsource('econ22-reproduce.R',encoding='UTF-8')\nexample <- function(api,variant) {\n  if(api=='rebase'){v<-if(variant=='invalid')c(0,1)else if(variant=='gap')c(80,NA,120)else c(80,100,120);z<-rebase(v);return(list(metrics=list(rows=length(z),defined=sum(!is.na(z)),last=tail(z,1)),x=seq_along(z)-1,y=z,xlabel='Position',ylabel='Rebased index'))}\n  if(api=='growth'){end<-if(variant=='quarterly')90 else 120;z<-growth(100,end,if(variant=='quarterly')4 else 1);return(list(metrics=z,x=c(0,1),y=c(100,end),xlabel='Date',ylabel='Supplied level'))}\n  if(api=='composition'){rows<-if(variant=='noCommon')data.frame(id=c('A','B'),before=c(10,NA),after=c(NA,20))else data.frame(id=c('A','B','C'),before=c(10,100,NA),after=c(11,NA,1));z<-composition(rows);metrics<-z[c('beforeAvailableMean','afterAvailableMean','availableMeanChange','commonWithinChange','commonUnits','exactDecompositionResidual')];return(list(metrics=metrics,x=c(0,1),y=c(z$beforeAvailableMean,z$afterAvailableMean),xlabel='Date',ylabel='Available mean / assumed units'))}\n  if(api=='productivity'){o<-if(variant=='contraction')90 else 103;h<-if(variant=='contraction')80 else 101;z<-productivity(100,o,100,h);return(list(metrics=z,x=c(0,1),y=c(1,z$productivityGross),xlabel='Date',ylabel='Output per hour / initial=1'))}\n  if(api=='measurement'){n<-if(variant=='zero')0 else 391035000000;d<-if(variant=='zero')0 else 164000;z<-measurement(n,d);return(list(metrics=list(ratio=z$ratio,denominatorZero=as.integer(d==0),sourceApproximate=as.integer(variant!='zero')),x=0,y=z$ratio,xlabel='Ratio position',ylabel='USD / approximate endpoint FTE'))}\n  models<-load_sources('econ22-sources');z<-realdata(models,variant)\n  if(variant=='country')return(list(metrics=list(sourceRows=z$originalCount,first=as.numeric(head(models$housing$nominal,1)),last=as.numeric(tail(models$housing$nominal,1)),percentChange=z$growth$percentChange),x=seq_along(z$rebased)-1,y=z$rebased,xlabel='Quarter position / original calendar',ylabel='Nominal housing / first=100'))\n  if(variant=='person')return(list(metrics=z[c('sourceUnits','beforeAvailableUnits','afterAvailableUnits','commonUnits','availableMeanChange','commonWithinChange','exactDecompositionResidual')],x=c(1976,1980),y=c(z$beforeAvailableMean,z$afterAvailableMean),xlabel='Observed wave',ylabel='Nominal USD/hour / available mean'))\n  if(variant=='company')return(list(metrics=list(sales2023=models$company$revenue2023,sales2024=models$company$revenue2024,proxy=z$ratio,proxyGrowth=NA_real_),x=c(2023,2024),y=c(models$company$revenue2023,models$company$revenue2024)/1e6,xlabel='Fiscal year',ylabel='Nominal USD millions'))\n  stop('fixed example name required')\n}\nrun <- function(api,variant,output) {\n  dir.create(output,recursive=TRUE,showWarnings=FALSE);z<-example(api,variant);metrics<-data.frame(metric=names(z$metrics),value=as.numeric(unlist(z$metrics)),stringsAsFactors=FALSE)\n  write.csv(metrics,file.path(output,'summary.csv'),row.names=FALSE,na='',fileEncoding='UTF-8');write.csv(data.frame(x=z$x,y=z$y),file.path(output,'plot-points.csv'),row.names=FALSE,na='',fileEncoding='UTF-8');print(metrics,row.names=FALSE)\n  good<-is.finite(z$x)&is.finite(z$y)\n  if(any(good)){svg(file.path(output,'plot.svg'),width=640/96,height=360/96,pointsize=10);par(mar=c(4.5,5.8,2,1));plot(z$x,z$y,type='o',pch=16,cex=.7,col='#355c72',xlab=z$xlabel,ylab=z$ylabel,cex.axis=.85,cex.lab=.9);grid(col='#d5dde1');dev.off();cat('plotProduced: TRUE\\n')}else cat('plotProduced: FALSE; undefined values retained\\n')\n}\n"
          }
        ],
        "inputFiles": [
          {
            "file": "econ22-sources/actual10839-person-wage-panel-original-and-prior-derived-fields.csv",
            "sha256": "971fae34928d73c1d7e8234d5fc6dd38767d993d85adb5d5060f26a7aa781d0f"
          },
          {
            "file": "econ22-sources/actual180-KOR-housing-nominal-real-indexes.csv",
            "sha256": "0db7456684f2da50d1fd15aee53b24217849744188d4f96e1e055cbdd2992777"
          },
          {
            "file": "econ22-sources/actual3-Apple-revenue-and-approximate-periodend-FTE-facts.csv",
            "sha256": "897e50d6ef2d05d1e934aa5a8048dda3296a53bc705bb3239610edd9db0e2922"
          },
          {
            "file": "econ22-sources/actual38-US-nonfarm-output-hours-productivity-indexes.csv",
            "sha256": "265369587eea705ef3ef8124988ad02ac3150efdd14142b469ba042c2495588b"
          }
        ],
        "returnCode": 0,
        "expectedFailure": false,
        "stdout": "                     metric                 value\n                sourceUnits 3613.0000000000000000\n       beforeAvailableUnits 3017.0000000000000000\n        afterAvailableUnits 2520.0000000000000000\n                commonUnits 2334.0000000000000000\n        availableMeanChange    2.9380521765550789\n         commonWithinChange    2.9920865467009437\n exactDecompositionResidual    0.0000000000000000\nplotProduced: TRUE\n",
        "stderr": "During startup - Warning messages:\n1: Setting LC_COLLATE=C.UTF-8 failed \n2: Setting LC_CTYPE=C.UTF-8 failed \n3: Setting LC_MONETARY=C.UTF-8 failed \n4: Setting LC_TIME=C.UTF-8 failed \n",
        "seconds": 0.32800000003771856,
        "summary": {
          "sourceUnits": "3613",
          "beforeAvailableUnits": "3017",
          "afterAvailableUnits": "2520",
          "commonUnits": "2334",
          "availableMeanChange": "2.93805217655508",
          "commonWithinChange": "2.99208654670094",
          "exactDecompositionResidual": "0"
        },
        "plotPoints": [
          {
            "x": "1976",
            "y": "5.7608882996354"
          },
          {
            "x": "1980",
            "y": "8.69894047619048"
          }
        ],
        "plotFile": "econ22-fixed-results/realdata-person-r/plot.svg",
        "plotSHA256": "1d60864491f8f1e5e9d063b47d6a098e289d769ea0e21b78caecb0ce8163747f",
        "scope": "Actually executed fixed example. Current browser controls are calculated separately by JavaScript. Base-R outputs use finite precision; Python outputs use exact fractions.",
        "summaryFile": "econ22-fixed-results/realdata-person-r/summary.csv",
        "summarySHA256": "8708d4d8db9028c2e6806215e33f05a89122b699ad5c4190ab3665ddbacaf3c7",
        "plotPointsFile": "econ22-fixed-results/realdata-person-r/plot-points.csv",
        "plotPointsSHA256": "fa8298d62f4409360ffbde6c064f2f4640a9ad39141df67ebcf1228ffb89c705"
      },
      "company": {
        "api": "realdata",
        "variant": "company",
        "language": "r",
        "codeFile": "econ22-code/realdata-company.R",
        "codeSHA256": "5d70273527bb071593bf56c89e3a6cfa6c695fc91612d0fa6fec1ba4ba2b18dc",
        "codeText": "# Run from the extracted textbook bundle root.\nsource('econ22-fixed-support.R',encoding='UTF-8')\noptions(digits=17)\nargs<-commandArgs(trailingOnly=TRUE)\noutput<-if(length(args))args[1]else'econ22-fixed-results/realdata-company-r'\ntryCatch(run('realdata','company',output),error=function(error){cat('Rejected declared input: ',conditionMessage(error),'\\n',file=stderr());quit(status=2)})\n",
        "supportFiles": [
          {
            "file": "econ22-reproduce.R",
            "sha256": "2db22759696a6f288479189f44026f265536a54cdc2e72952c1e91af13661480",
            "codeText": "# ECON22 independent public base-R reproduction; binary64 approximations.\n# Run: Rscript --vanilla --encoding=UTF-8 econ22-reproduce.R [source-dir] [output-dir]\n# Source CSVs are never overwritten. No packages or network required.\nrebase <- function(values, base=1L, scale=100) {\n  if (length(base)!=1L || !is.finite(base) || base!=as.integer(base) || !length(values) || base<1 || base>length(values) || is.na(values[base]) || values[base]<=0 || !is.finite(scale) || scale<=0) stop('positive observed base/scale required')\n  scale*values/values[base]\n}\ngrowth <- function(start,end,periods=1L) {\n  if (start<=0 || end<0 || periods<1 || periods>12 || periods!=as.integer(periods)) stop('growth domain')\n  gross<-end/start;list(gross=gross,percentChange=(gross-1)*100,annualizedGross=gross^periods,annualizedPercent=(gross^periods-1)*100)\n}\ncomposition <- function(rows) {\n  if (!nrow(rows) || anyDuplicated(rows$id)) stop('nonempty unique units required')\n  if (!'weight'%in%names(rows)) rows$weight<-rep(1,nrow(rows))\n  if (any(!is.finite(rows$weight)) || any(rows$weight<0)) stop('nonnegative fixed weights required')\n  valid<-rows$weight>0;b<-valid&!is.na(rows$before);a<-valid&!is.na(rows$after);common<-b&a\n  avg<-function(mask,column)if(sum(rows$weight[mask])>0)sum(rows[[column]][mask]*rows$weight[mask])/sum(rows$weight[mask])else NA_real_\n  mb<-avg(b,'before');ma<-avg(a,'after');cb<-avg(common,'before');ca<-avg(common,'after');full<-all(is.finite(c(mb,ma,cb,ca)))\n  list(sourceUnits=nrow(rows),beforeAvailableUnits=sum(b),afterAvailableUnits=sum(a),commonUnits=sum(common),beforeAvailableMean=mb,afterAvailableMean=ma,beforeCommonMean=cb,afterCommonMean=ca,availableMeanChange=ma-mb,commonWithinChange=if(full)ca-cb else NA_real_,afterFrameShift=if(full)ma-ca else NA_real_,beforeFrameShift=if(full)cb-mb else NA_real_,exactDecompositionResidual=if(full)(ma-mb)-((ma-ca)+(ca-cb)+(cb-mb))else NA_real_)\n}\nproductivity <- function(output0,output1,hours0,hours1) {\n  if(any(c(output0,output1,hours0,hours1)<=0))stop('positive output and hours required')\n  go<-output1/output0;gh<-hours1/hours0;gp<-go/gh\n  list(outputGross=go,hoursGross=gh,productivityGross=gp,outputPercent=(go-1)*100,hoursPercent=(gh-1)*100,productivityPercent=(gp-1)*100,differenceOfPercentGrowths=(go-gh)*100,exactGrowthIdentityResidual=gp-go/gh)\n}\nmeasurement <- function(numerator,denominator,lower=NA_real_,upper=NA_real_) {\n  if(denominator<0)stop('nonnegative denominator required');interval<-NULL\n  if(!is.na(lower)||!is.na(upper)){if(any(!is.finite(c(lower,upper)))||lower<=0||upper<lower)stop('ordered positive scenario bounds');interval<-sort(c(numerator/lower,numerator/upper))}\n  list(ratio=if(denominator>0)numerator/denominator else NA_real_,denominatorScenarioInterval=interval)\n}\nload_sources <- function(folder) {\n  read<-function(file)read.csv(file.path(folder,file),stringsAsFactors=FALSE,check.names=FALSE,colClasses='character',na.strings=c('NA','','.'))\n  h<-read('actual180-KOR-housing-nominal-real-indexes.csv');b<-read('actual38-US-nonfarm-output-hours-productivity-indexes.csv');p<-read('actual10839-person-wage-panel-original-and-prior-derived-fields.csv');c<-read('actual3-Apple-revenue-and-approximate-periodend-FTE-facts.csv')\n  company<-list();for(i in seq_len(nrow(c))){value<-as.numeric(gsub(',','',c$originalToken[i],fixed=TRUE));if(c$fact[i]=='consolidated total net sales')company[[paste0('revenue',c$fiscalYear[i])]]<-value*1e6 else company$endpointFTE2024<-value}\n  list(housing=h,bls=b,person=p,company=company)\n}\nperson_comparison <- function(models,before=1976L,after=1980L) {\n  if(!before%in%c(1976,1978,1980)||!after%in%c(1976,1978,1980)||before>=after)stop('ordered observed waves required')\n  p<-models$person;if(anyDuplicated(paste(p$unit,p$time,sep=':')))stop('duplicate original unit-wave')\n  ids<-unique(p$unit);rows<-data.frame(id=ids,before=as.numeric(p$wageCentsOriginal[match(paste(ids,before),paste(p$unit,p$time))])/100,after=as.numeric(p$wageCentsOriginal[match(paste(ids,after),paste(p$unit,p$time))])/100,stringsAsFactors=FALSE)\n  composition(rows)\n}\nrealdata <- function(models,kind) {\n  if(kind=='country'){r<-models$housing;return(list(originalCount=nrow(r),growth=growth(as.numeric(r$nominal[1]),as.numeric(tail(r$nominal,1))),rebased=rebase(as.numeric(r$nominal))))}\n  if(kind=='person')return(person_comparison(models))\n  if(kind=='company'){c<-models$company;return(list(revenueGrowth=growth(c$revenue2023,c$revenue2024),ratio=measurement(c$revenue2024,c$endpointFTE2024)$ratio,proxyGrowth=NA_real_))}\n  stop('actual case required')\n}\nfull_source <- function(folder,out) {\n  dir.create(out,recursive=TRUE,showWarnings=FALSE);models<-load_sources(folder);metrics<-list();country<-list();frames<-list()\n  for(source in c('housing','bls')){data<-models[[source]];columns<-if(source=='housing')c('nominal','real')else c('outputIndexOriginalToken','hoursIndexOriginalToken','productivityIndexOriginalToken')\n    for(col in columns){values<-as.numeric(data[[col]]);rb<-rebase(values);g<-growth(values[1],tail(values,1));for(k in names(g))metrics[[paste(source,col,k,sep=':')]]<-g[[k]];quarterBase<-if(source=='housing')match('2010-Q1',data$quarter)else NA_integer_;qb<-if(!is.na(quarterBase))rebase(values,quarterBase)else rep(NA_real_,length(values));country[[length(country)+1]]<-data.frame(source=source,series=col,row=seq_len(nrow(data)),quarter=data$quarter,originalToken=data[[col]],rebasedFirst100Exact=rb,rebased2010Q1Exact=qb,stringsAsFactors=FALSE)}}\n  for(pair in list(c(1976,1978),c(1978,1980),c(1976,1980))){a<-pair[1];b<-pair[2];z<-person_comparison(models,a,b);frames[[length(frames)+1]]<-as.data.frame(c(list(before=a,after=b,elapsedYears=b-a),z),stringsAsFactors=FALSE);for(k in names(z))metrics[[paste('person',a,b,k,sep=':')]]<-z[[k]]}\n  company<-realdata(models,'company');metrics[['company:proxy']]<-company$ratio;metrics[['company:proxyGrowth']]<-NA_real_;for(k in names(company$revenueGrowth))metrics[[paste('company:sales',k,sep=':')]]<-company$revenueGrowth[[k]]\n  changes<-list();b<-models$bls\n  for(i in seq_len(nrow(b)-1L)){z<-productivity(as.numeric(b$outputIndexOriginalToken[i]),as.numeric(b$outputIndexOriginalToken[i+1]),as.numeric(b$hoursIndexOriginalToken[i]),as.numeric(b$hoursIndexOriginalToken[i+1]));g<-growth(as.numeric(b$productivityIndexOriginalToken[i]),as.numeric(b$productivityIndexOriginalToken[i+1]),4);changes[[i]]<-as.data.frame(c(list(start=b$quarter[i],end=b$quarter[i+1]),z,list(publishedProductivityPercent=g$percentChange,publishedAnnualizedPercent=g$annualizedPercent)),stringsAsFactors=FALSE)}\n  write<-function(name,rows)write.csv(rows,file.path(out,name),row.names=FALSE,na='',fileEncoding='UTF-8')\n  selected<-head(unique(models$person$unit),12);p<-models$person[models$person$unit%in%selected,];trajectories<-data.frame(unit=p$unit,year=p$time,nominalUSDPerHourExact=as.numeric(p$wageCentsOriginal)/100,stringsAsFactors=FALSE)\n  write('metrics.csv',data.frame(metric=names(metrics),value=as.numeric(unlist(metrics))));write('country-indexes.csv',do.call(rbind,country));write('wage-frames.csv',do.call(rbind,frames));write('bls-changes.csv',do.call(rbind,changes));write('first12-trajectories.csv',trajectories);invisible(metrics)\n}\nif(sys.nframe()==0L){args<-commandArgs(trailingOnly=TRUE);folder<-if(length(args)>=1)args[1]else'econ22-sources';out<-if(length(args)>=2)args[2]else'econ22-r-results';options(digits=17);metrics<-full_source(folder,out);cat('metrics:',length(metrics),'\\noutput directory:',out,'\\n')}\n"
          },
          {
            "file": "econ22-fixed-support.R",
            "sha256": "d4d63e1ad02017f20884b5932458dbde6013e0c2e560a4a9922a13d080a59fa1",
            "codeText": "# Run fixed drivers from the extracted bundle root. No packages or network required.\nsource('econ22-reproduce.R',encoding='UTF-8')\nexample <- function(api,variant) {\n  if(api=='rebase'){v<-if(variant=='invalid')c(0,1)else if(variant=='gap')c(80,NA,120)else c(80,100,120);z<-rebase(v);return(list(metrics=list(rows=length(z),defined=sum(!is.na(z)),last=tail(z,1)),x=seq_along(z)-1,y=z,xlabel='Position',ylabel='Rebased index'))}\n  if(api=='growth'){end<-if(variant=='quarterly')90 else 120;z<-growth(100,end,if(variant=='quarterly')4 else 1);return(list(metrics=z,x=c(0,1),y=c(100,end),xlabel='Date',ylabel='Supplied level'))}\n  if(api=='composition'){rows<-if(variant=='noCommon')data.frame(id=c('A','B'),before=c(10,NA),after=c(NA,20))else data.frame(id=c('A','B','C'),before=c(10,100,NA),after=c(11,NA,1));z<-composition(rows);metrics<-z[c('beforeAvailableMean','afterAvailableMean','availableMeanChange','commonWithinChange','commonUnits','exactDecompositionResidual')];return(list(metrics=metrics,x=c(0,1),y=c(z$beforeAvailableMean,z$afterAvailableMean),xlabel='Date',ylabel='Available mean / assumed units'))}\n  if(api=='productivity'){o<-if(variant=='contraction')90 else 103;h<-if(variant=='contraction')80 else 101;z<-productivity(100,o,100,h);return(list(metrics=z,x=c(0,1),y=c(1,z$productivityGross),xlabel='Date',ylabel='Output per hour / initial=1'))}\n  if(api=='measurement'){n<-if(variant=='zero')0 else 391035000000;d<-if(variant=='zero')0 else 164000;z<-measurement(n,d);return(list(metrics=list(ratio=z$ratio,denominatorZero=as.integer(d==0),sourceApproximate=as.integer(variant!='zero')),x=0,y=z$ratio,xlabel='Ratio position',ylabel='USD / approximate endpoint FTE'))}\n  models<-load_sources('econ22-sources');z<-realdata(models,variant)\n  if(variant=='country')return(list(metrics=list(sourceRows=z$originalCount,first=as.numeric(head(models$housing$nominal,1)),last=as.numeric(tail(models$housing$nominal,1)),percentChange=z$growth$percentChange),x=seq_along(z$rebased)-1,y=z$rebased,xlabel='Quarter position / original calendar',ylabel='Nominal housing / first=100'))\n  if(variant=='person')return(list(metrics=z[c('sourceUnits','beforeAvailableUnits','afterAvailableUnits','commonUnits','availableMeanChange','commonWithinChange','exactDecompositionResidual')],x=c(1976,1980),y=c(z$beforeAvailableMean,z$afterAvailableMean),xlabel='Observed wave',ylabel='Nominal USD/hour / available mean'))\n  if(variant=='company')return(list(metrics=list(sales2023=models$company$revenue2023,sales2024=models$company$revenue2024,proxy=z$ratio,proxyGrowth=NA_real_),x=c(2023,2024),y=c(models$company$revenue2023,models$company$revenue2024)/1e6,xlabel='Fiscal year',ylabel='Nominal USD millions'))\n  stop('fixed example name required')\n}\nrun <- function(api,variant,output) {\n  dir.create(output,recursive=TRUE,showWarnings=FALSE);z<-example(api,variant);metrics<-data.frame(metric=names(z$metrics),value=as.numeric(unlist(z$metrics)),stringsAsFactors=FALSE)\n  write.csv(metrics,file.path(output,'summary.csv'),row.names=FALSE,na='',fileEncoding='UTF-8');write.csv(data.frame(x=z$x,y=z$y),file.path(output,'plot-points.csv'),row.names=FALSE,na='',fileEncoding='UTF-8');print(metrics,row.names=FALSE)\n  good<-is.finite(z$x)&is.finite(z$y)\n  if(any(good)){svg(file.path(output,'plot.svg'),width=640/96,height=360/96,pointsize=10);par(mar=c(4.5,5.8,2,1));plot(z$x,z$y,type='o',pch=16,cex=.7,col='#355c72',xlab=z$xlabel,ylab=z$ylabel,cex.axis=.85,cex.lab=.9);grid(col='#d5dde1');dev.off();cat('plotProduced: TRUE\\n')}else cat('plotProduced: FALSE; undefined values retained\\n')\n}\n"
          }
        ],
        "inputFiles": [
          {
            "file": "econ22-sources/actual10839-person-wage-panel-original-and-prior-derived-fields.csv",
            "sha256": "971fae34928d73c1d7e8234d5fc6dd38767d993d85adb5d5060f26a7aa781d0f"
          },
          {
            "file": "econ22-sources/actual180-KOR-housing-nominal-real-indexes.csv",
            "sha256": "0db7456684f2da50d1fd15aee53b24217849744188d4f96e1e055cbdd2992777"
          },
          {
            "file": "econ22-sources/actual3-Apple-revenue-and-approximate-periodend-FTE-facts.csv",
            "sha256": "897e50d6ef2d05d1e934aa5a8048dda3296a53bc705bb3239610edd9db0e2922"
          },
          {
            "file": "econ22-sources/actual38-US-nonfarm-output-hours-productivity-indexes.csv",
            "sha256": "265369587eea705ef3ef8124988ad02ac3150efdd14142b469ba042c2495588b"
          }
        ],
        "returnCode": 0,
        "expectedFailure": false,
        "stdout": "      metric                  value\n   sales2023 3.8328500000000000e+11\n   sales2024 3.9103500000000000e+11\n       proxy 2.3843597560975607e+06\n proxyGrowth                     NA\nplotProduced: TRUE\n",
        "stderr": "During startup - Warning messages:\n1: Setting LC_COLLATE=C.UTF-8 failed \n2: Setting LC_CTYPE=C.UTF-8 failed \n3: Setting LC_MONETARY=C.UTF-8 failed \n4: Setting LC_TIME=C.UTF-8 failed \n",
        "seconds": 0.2970000000204891,
        "summary": {
          "sales2023": "3.83285e+11",
          "sales2024": "3.91035e+11",
          "proxy": "2384359.75609756",
          "proxyGrowth": null
        },
        "plotPoints": [
          {
            "x": "2023",
            "y": "383285"
          },
          {
            "x": "2024",
            "y": "391035"
          }
        ],
        "plotFile": "econ22-fixed-results/realdata-company-r/plot.svg",
        "plotSHA256": "7bfee305e324082c7fc227f3a5b8ff3ecf63d3bf3c9cab636c4b6ad0a5dd3f8e",
        "scope": "Actually executed fixed example. Current browser controls are calculated separately by JavaScript. Base-R outputs use finite precision; Python outputs use exact fractions.",
        "summaryFile": "econ22-fixed-results/realdata-company-r/summary.csv",
        "summarySHA256": "d643736a96dcda0b0d45e79befd6cee8babe71dc6ebde19b9d5342d1bf63f974",
        "plotPointsFile": "econ22-fixed-results/realdata-company-r/plot-points.csv",
        "plotPointsSHA256": "2af7841be404e56f55a7a7c27d5357a8efcad53990d9c0900b0b59d52baf5bf6"
      }
    }
  }
}
